1 /*
2  *  cOrganism.h
3  *  Avida
4  *
5  *  Called "organism.hh" prior to 12/5/05.
6  *  Copyright 1999-2011 Michigan State University. All rights reserved.
7  *  Copyright 1993-2003 California Institute of Technology.
8  *
9  *
10  *  This file is part of Avida.
11  *
12  *  Avida is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License
13  *  as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
14  *
15  *  Avida is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
17  *
18  *  You should have received a copy of the GNU Lesser General Public License along with Avida.
19  *  If not, see <http://www.gnu.org/licenses/>.
20  *
21  */
22 
23 #ifndef cOrganism_h
24 #define cOrganism_h
25 
26 #include "avida/core/Genome.h"
27 
28 #include "cBioUnit.h"
29 #include "cCPUMemory.h"
30 #include "cGenomeTestMetrics.h"
31 #include "cMutationRates.h"
32 #include "cPhenotype.h"
33 #include "cOrgInterface.h"
34 #include "cOrgSeqMessage.h"
35 #include "cOrgSourceMessage.h"
36 #include "cOrgMessage.h"
37 #include "tArray.h"
38 #include "tBuffer.h"
39 #include "tList.h"
40 #include "tSmartArray.h"
41 
42 #include <deque>
43 #include <iostream>
44 #include <set>
45 #include <string>
46 #include <vector>
47 #include <utility>
48 #include <map>
49 
50 class cAvidaContext;
51 class cBioGroup;
52 class cContextPhenotype;
53 class cEnvironment;
54 class cHardwareBase;
55 class cInstSet;
56 class cLineage;
57 class cOrgSinkMessage;
58 class cSaleItem;
59 class cStateGrid;
60 
61 struct sOrgDisplay;
62 
63 using namespace Avida;
64 
65 
66 class cOrganism : public cBioUnit
67 {
68 private:
69   cWorld* m_world;
70   cHardwareBase* m_hardware;              // The actual machinery running this organism.
71   cPhenotype m_phenotype;                 // Descriptive attributes of organism.
72   eBioUnitSource m_src;
73   cString m_src_args;
74   const Genome m_initial_genome;         // Initial genome; can never be changed!
75   tArray<cBioUnit*> m_parasites;   // List of all parasites associated with this organism.
76   cMutationRates m_mut_rates;             // Rate of all possible mutations.
77   cOrgInterface* m_interface;             // Interface back to the population.
78   int m_id;                               // unique id for each org, is just the number it was born
79   int m_lineage_label;                    // a lineages tag; inherited unchanged in offspring
80   cLineage* m_lineage;                    // A lineage descriptor... (different from label)
81   int cclade_id;				                  // @MRR Coalescence clade information (set in cPopulation)
82 
83   int m_org_list_index;
84 
85   sOrgDisplay* m_org_display;
86   sOrgDisplay* m_queued_display_data;
87   bool m_display;
88 
89   // Other stats
90   Genome m_offspring_genome;              // Child genome, while under construction.
91 
92   // Input and Output with the environment
93   int m_input_pointer;
94   tBuffer<int> m_input_buf;
95   tBuffer<int> m_output_buf;
96   tBuffer<int> m_received_messages;
97   tList<tListNode<cSaleItem> > m_sold_items;
98 
99   int m_cur_sg;
100 
101   // Communication
102   int m_sent_value;         // What number is this org sending?
103   bool m_sent_active;       // Has this org sent a number?
104   int m_test_receive_pos;   // In a test CPU, what message to receive next?
105 
106   double m_gradient_movement;  // TEMP.  Remove once movement tasks are implemented.
107   bool m_pher_drop;	   // Is the organism dropping pheromone?
108   double frac_energy_donating;  // What fraction of the organism's energy is it donating
109 
110   int m_max_executed;      // Max number of instruction executed before death.
111   bool m_is_running;       // Does this organism have the CPU?
112   bool m_is_sleeping;      // Is this organism sleeping?
113   bool m_is_dead;          // Is this organism dead?
114 
115   bool killed_event;
116 
117   class cNetSupport
118   {
119   public:
120     tList<cOrgSinkMessage> pending;
121     tSmartArray<cOrgSinkMessage*> received;
122     tSmartArray<cOrgSourceMessage> sent;
123     tSmartArray<cOrgSeqMessage> seq;
124     int last_seq;
125     bool valid;
126     int completed;
127 
cNetSupport()128     cNetSupport() : last_seq(0), valid(false), completed(0) { ; }
129     ~cNetSupport();
130   };
131   cNetSupport* m_net;
132 
133   cOrganism(); // @not_implemented
134   cOrganism(const cOrganism&); // @not_implemented
135   cOrganism& operator=(const cOrganism&); // @not_implemented
136 
137 public:
138   cOrganism(cWorld* world, cAvidaContext& ctx, const Genome& genome, int parent_generation,
139     eBioUnitSource src, const cString& src_args = "");
140   ~cOrganism();
141 
142   // --------  cBioUnit Methods  --------
GetUnitSource()143   eBioUnitSource GetUnitSource() const { return m_src; }
GetUnitSourceArgs()144   const cString& GetUnitSourceArgs() const { return m_src_args; }
GetGenome()145   const Genome& GetGenome() const { return m_initial_genome; }
146 
147 
148   // --------  Support Methods  --------
149   inline double GetTestFitness(cAvidaContext& ctx) const;
150   inline double GetTestMerit(cAvidaContext& ctx) const;
151   inline double GetTestColonyFitness(cAvidaContext& ctx) const;
152   double CalcMeritRatio();
153 
154   void HardwareReset(cAvidaContext& ctx);
155   void NotifyDeath(cAvidaContext& ctx);
156 
157   void PrintStatus(std::ostream& fp, const cString& next_name);
158   void PrintMiniTraceStatus(cAvidaContext& ctx, std::ostream& fp, const cString& next_name);
159   void PrintMiniTraceSuccess(std::ostream& fp, const int exec_success);
160   void PrintFinalStatus(std::ostream& fp, int time_used, int time_allocated) const;
161   void Fault(int fault_loc, int fault_type, cString fault_desc="");
162 
163   void NewTrial();
164 
165   // --------  Accessor Methods  --------
GetPhenotype()166   const cPhenotype& GetPhenotype() const { return m_phenotype; }
GetPhenotype()167   cPhenotype& GetPhenotype() { return m_phenotype; }
SetPhenotype(cPhenotype & _in_phenotype)168   void SetPhenotype(cPhenotype& _in_phenotype) { m_phenotype = _in_phenotype; }
169 
MutationRates()170   const cMutationRates& MutationRates() const { return m_mut_rates; }
MutationRates()171   cMutationRates& MutationRates() { return m_mut_rates; }
172 
GetOrgInterface()173   const cOrgInterface& GetOrgInterface() const { assert(m_interface); return *m_interface; }
GetOrgInterface()174   cOrgInterface& GetOrgInterface() { assert(m_interface); return *m_interface; }
175   void SetOrgInterface(cAvidaContext& ctx, cOrgInterface* org_interface);
176 
SetLineageLabel(int in_label)177   void SetLineageLabel(int in_label) { m_lineage_label = in_label; }
GetLineageLabel()178   int GetLineageLabel() const { return m_lineage_label; }
SetLineage(cLineage * in_lineage)179   void SetLineage(cLineage* in_lineage) { m_lineage = in_lineage; }
GetLineage()180   cLineage* GetLineage() const { return m_lineage; }
181 
SetCCladeLabel(int in_label)182   void SetCCladeLabel( int in_label ) { cclade_id = in_label; };  //@MRR
GetCCladeLabel()183   int  GetCCladeLabel() const { return cclade_id; }
184 
GetRBins()185   const tArray<double>& GetRBins() const { return m_phenotype.GetCurRBinsAvail(); }
GetRBin(int index)186   double GetRBin(int index) { return m_phenotype.GetCurRBinAvail(index); }
187   double GetRBinsTotal();
188   void SetRBins(const tArray<double>& rbins_in);
189   void SetRBin(const int index, const double value);
190   void AddToRBin(const int index, const double value);
191   void IncCollectSpecCount(const int spec_id);
192 
GetMaxExecuted()193   int GetMaxExecuted() const { return m_max_executed; }
194 
OffspringGenome()195   Genome& OffspringGenome() { return m_offspring_genome; }
196 
SetRunning(bool in_running)197   void SetRunning(bool in_running) { m_is_running = in_running; }
IsRunning()198   bool IsRunning() { return m_is_running; }
199 
200   inline void SetSleeping(bool in_sleeping);
IsSleeping()201   bool IsSleeping() { return m_is_sleeping; }
202 
IsDead()203   bool IsDead() { return m_is_dead; }
204 
205   bool IsInterrupted();
206 
GetPheromoneStatus()207   bool GetPheromoneStatus() { return m_pher_drop; }
TogglePheromone()208   void TogglePheromone() { m_pher_drop = (m_pher_drop == true) ? false : true; }
SetPheromone(bool newval)209   void SetPheromone(bool newval) { m_pher_drop = newval; }
210 
GetFracEnergyDonating()211   double GetFracEnergyDonating() { return frac_energy_donating; }
SetFracEnergyDonating(double newval)212   void SetFracEnergyDonating(double newval) { assert(newval >= 0); assert(newval <= 1); frac_energy_donating = newval; }
213 
214   const cStateGrid& GetStateGrid() const;
215 
216   double GetVitality() const;
217 
SetOrgIndex(int index)218   inline void SetOrgIndex(int index) { m_org_list_index = index; }
GetOrgIndex()219   inline int GetOrgIndex() { return m_org_list_index; }
220 
221   // Org displaying
ActivateDisplay()222   inline void ActivateDisplay() { m_display = true; }
KillDisplay()223   inline void KillDisplay() { m_display = false; }
IsDisplaying()224   inline bool IsDisplaying() { return m_display; }
SetOrgDisplay(sOrgDisplay * org_display)225   inline void SetOrgDisplay(sOrgDisplay* org_display) { m_org_display = org_display; }
SetPotentialDisplay(sOrgDisplay * new_data)226   inline void SetPotentialDisplay(sOrgDisplay* new_data) { m_queued_display_data = new_data; }
227   bool UpdateOrgDisplay();
GetOrgDisplayData()228   inline sOrgDisplay* GetOrgDisplayData() { return m_org_display; }
GetPotentialDisplayData()229   inline sOrgDisplay* GetPotentialDisplayData() { return m_queued_display_data; }
230   void SetSimpDisplay(int display_part, int value);
231 
232   // --------  cOrgInterface Methods  --------
GetHardware()233   cHardwareBase& GetHardware() { return *m_hardware; }
GetID()234   int GetID() { return m_id; }
235 
GetCellID()236   int GetCellID() { return m_interface->GetCellID(); }
GetDemeID()237   int GetDemeID() { return m_interface->GetDemeID(); }
GetDeme()238   cDeme* GetDeme() { return m_interface->GetDeme(); }
239 
GetCellData()240   int GetCellData() { return m_interface->GetCellData(); }
GetCellDataOrgID()241   int GetCellDataOrgID() { return m_interface->GetCellDataOrgID(); }
GetCellDataUpdate()242   int GetCellDataUpdate() { return m_interface->GetCellDataUpdate(); }
GetCellDataTerritory()243   int GetCellDataTerritory() { return m_interface->GetCellDataTerritory(); }
GetCellDataForagerType()244   int GetCellDataForagerType() { return m_interface->GetCellDataForagerType(); }
SetCellData(const int data)245   void SetCellData(const int data) { m_interface->SetCellData(data); }
GetFacedCellData()246   int GetFacedCellData() { return m_interface->GetFacedCellData(); }
GetFacedCellDataOrgID()247   int GetFacedCellDataOrgID() { return m_interface->GetFacedCellDataOrgID(); }
GetFacedCellDataUpdate()248   int GetFacedCellDataUpdate() { return m_interface->GetFacedCellDataUpdate(); }
GetFacedCellDataTerritory()249   int GetFacedCellDataTerritory() { return m_interface->GetFacedCellDataTerritory(); }
250 
GetNeighbor()251   cOrganism* GetNeighbor() { return m_interface->GetNeighbor(); }
IsNeighborCellOccupied()252   bool IsNeighborCellOccupied() { return m_interface->IsNeighborCellOccupied(); }
GetNeighborhoodSize()253   int GetNeighborhoodSize() { return m_interface->GetNumNeighbors(); }
GetFacing()254   int GetFacing() { assert(m_interface); return m_interface->GetFacing(); }  // Returns the facing of this organism.
GetFacedCellID()255   int GetFacedCellID() { assert(m_interface); return m_interface->GetFacedCellID(); }  // Returns the faced cell of this organism.
GetFacedDir()256   int GetFacedDir() { assert(m_interface); return m_interface->GetFacedDir(); }  // Returns the human interpretable facing of this org.
GetNeighborCellContents()257   int GetNeighborCellContents() const { return m_interface->GetNeighborCellContents(); }
Rotate(int direction)258   void Rotate(int direction) { m_interface->Rotate(direction); }
259 
DoBreakpoint()260   void DoBreakpoint() { m_interface->Breakpoint(); }
261 
GetInputAt(int i)262   int GetInputAt(int i) { return m_interface->GetInputAt(i); }
GetNextInput()263   int GetNextInput() { return m_interface->GetInputAt(m_input_pointer); }
GetNextInput(int & in_input_pointer)264   int GetNextInput(int& in_input_pointer) { return m_interface->GetInputAt(in_input_pointer); }
GetInputBuf()265   tBuffer<int>& GetInputBuf() { return m_input_buf; }
GetOutputBuf()266   tBuffer<int>& GetOutputBuf() { return m_output_buf; }
Die(cAvidaContext & ctx)267   void Die(cAvidaContext& ctx) { m_interface->Die(ctx); m_is_dead = true; }
KillCellID(int target,cAvidaContext & ctx)268   void KillCellID(int target, cAvidaContext& ctx) { m_interface->KillCellID(target, ctx); }
Kaboom(int dist,cAvidaContext & ctx)269   void Kaboom(int dist, cAvidaContext& ctx) { m_interface->Kaboom(dist,ctx);}
SpawnDeme(cAvidaContext & ctx)270   void SpawnDeme(cAvidaContext& ctx) { m_interface->SpawnDeme(ctx); }
GetSentActive()271   bool GetSentActive() { return m_sent_active; }
SendValue(int value)272   void SendValue(int value) { m_sent_active = true; m_sent_value = value; }
RetrieveSentValue()273   int RetrieveSentValue() { m_sent_active = false; return m_sent_value; }
274   int ReceiveValue();
275   void SellValue(const int data, const int label, const int sell_price);
276   int BuyValue(const int label, const int buy_price);
AddSoldItem(tListNode<cSaleItem> * node)277   tListNode<tListNode<cSaleItem> >* AddSoldItem(tListNode<cSaleItem>* node) { return m_sold_items.PushRear(node); }
GetSoldItems()278   tList<tListNode<cSaleItem> >* GetSoldItems() { return &m_sold_items; }
UpdateMerit(double new_merit)279   void UpdateMerit(double new_merit) { m_interface->UpdateMerit(new_merit); }
280 
GetPrevSeenCellID()281   int GetPrevSeenCellID() const { return m_interface->GetPrevSeenCellID(); }
GetPrevTaskCellID()282   int GetPrevTaskCellID() const { return m_interface->GetPrevTaskCellID(); }
SetPrevSeenCellID(int id)283   void SetPrevSeenCellID(int id) const { m_interface->SetPrevSeenCellID(id); }
SetPrevTaskCellID(int id)284   void SetPrevTaskCellID(int id) const { m_interface->SetPrevTaskCellID(id); }
GetNumTaskCellsReached()285   int GetNumTaskCellsReached() const { return m_interface->GetNumTaskCellsReached(); }
AddReachedTaskCell()286   void AddReachedTaskCell() { m_interface->AddReachedTaskCell(); }
287 
AddLiveOrg()288   void AddLiveOrg() { m_interface->AddLiveOrg(); }
RemoveLiveOrg()289   void RemoveLiveOrg() { m_interface->RemoveLiveOrg(); }
290 
JoinGroup(int group_id)291   void JoinGroup(int group_id) { m_interface->JoinGroup(group_id); }
LeaveGroup(int group_id)292   void LeaveGroup(int group_id) { m_interface->LeaveGroup(group_id); }
293 
294   // --------  Input and Output Methods  --------
295   void DoInput(const int value);
296   void DoInput(tBuffer<int>& input_buffer, tBuffer<int>& output_buffer, const int value);
297 
298   /* These different flavors of DoOutput are "frontends" to the main DoOutput
299   that follows - One DoOutput to rule them all, etc., etc. */
300   //! Check tasks based on the current state of this organism's IO & message buffers.
301   // void DoOutput(cAvidaContext& ctx, const bool on_divide=false);
302   void DoOutput(cAvidaContext& ctx, const bool on_divide=false, cContextPhenotype* context_phenotype = 0);
303   //! Add the passed-in value to this organism's output buffer, and check tasks (on_divide=false).
304   void DoOutput(cAvidaContext& ctx, const int value);
305   //! Check if we're calling this from a parasite.
306   void DoOutput(cAvidaContext& ctx, const int value, bool is_parasite, cContextPhenotype* context_phenotype);
307   //! Check tasks based on the passed-in IO buffers and value (on_divide=false).
308   void DoOutput(cAvidaContext& ctx, tBuffer<int>& input_buffer, tBuffer<int>& output_buffer, const int value);
309 
ClearInput()310   void ClearInput() { m_input_buf.Clear(); }
ResetInput()311   void ResetInput() {m_input_pointer = 0; m_input_buf.Clear(); };
AddOutput(int val)312   void AddOutput(int val) { m_output_buf.Add(val); }
313 
314   // --------  Divide Methods  --------
315   bool Divide_CheckViable(cAvidaContext& ctx);
316   bool ActivateDivide(cAvidaContext& ctx, cContextPhenotype* context_phenotype = 0);
317 
318   // --------  Networking Support  --------
319   void NetGet(cAvidaContext& ctx, int& value, int& seq);
320   void NetSend(cAvidaContext& ctx, int value);
NetPop()321   cOrgSinkMessage* NetPop() { return m_net->pending.PopRear(); }
322   bool NetReceive(int& value);
323   void NetValidate(cAvidaContext& ctx, int value);
324   bool NetRemoteValidate(cAvidaContext& ctx, int value);
NetLast()325   int NetLast() { return m_net->last_seq; }
NetIsValid()326   bool NetIsValid() { if (m_net) return m_net->valid; else return false; }
NetCompleted()327   int NetCompleted() { if (m_net) return m_net->completed; else return 0; }
328 
329   // --------  Parasite Interactions  --------
330   bool InjectParasite(cBioUnit* parent, const cString& label, const Sequence& genome);
331   bool ParasiteInfectHost(cBioUnit* parasite);
GetNumParasites()332   int GetNumParasites() const { return m_parasites.GetSize(); }
GetParasites()333   const tArray<cBioUnit*>& GetParasites() const { return m_parasites; }
334   void ClearParasites();
335 
336   // --------  Mutation Rate Convenience Methods  --------
TestCopyMut(cAvidaContext & ctx)337   bool TestCopyMut(cAvidaContext& ctx) const { return m_mut_rates.TestCopyMut(ctx); }
TestCopyIns(cAvidaContext & ctx)338   bool TestCopyIns(cAvidaContext& ctx) const { return m_mut_rates.TestCopyIns(ctx); }
TestCopyDel(cAvidaContext & ctx)339   bool TestCopyDel(cAvidaContext& ctx) const { return m_mut_rates.TestCopyDel(ctx); }
TestCopyUniform(cAvidaContext & ctx)340   bool TestCopyUniform(cAvidaContext& ctx) const { return m_mut_rates.TestCopyUniform(ctx); }
TestCopySlip(cAvidaContext & ctx)341   bool TestCopySlip(cAvidaContext& ctx) const { return m_mut_rates.TestCopySlip(ctx); }
342 
TestDivideMut(cAvidaContext & ctx)343   bool TestDivideMut(cAvidaContext& ctx) const { return m_mut_rates.TestDivideMut(ctx); }
TestDivideIns(cAvidaContext & ctx)344   bool TestDivideIns(cAvidaContext& ctx) const { return m_mut_rates.TestDivideIns(ctx); }
TestDivideDel(cAvidaContext & ctx)345   bool TestDivideDel(cAvidaContext& ctx) const { return m_mut_rates.TestDivideDel(ctx); }
TestDivideUniform(cAvidaContext & ctx)346   bool TestDivideUniform(cAvidaContext& ctx) const { return m_mut_rates.TestDivideUniform(ctx); }
TestDivideSlip(cAvidaContext & ctx)347   bool TestDivideSlip(cAvidaContext& ctx) const { return m_mut_rates.TestDivideSlip(ctx); }
TestDivideTrans(cAvidaContext & ctx)348   bool TestDivideTrans(cAvidaContext& ctx) const { return m_mut_rates.TestDivideTrans(ctx); }
TestDivideLGT(cAvidaContext & ctx)349   bool TestDivideLGT(cAvidaContext& ctx) const { return m_mut_rates.TestDivideLGT(ctx); }
350 
NumDividePoissonMut(cAvidaContext & ctx)351   unsigned int NumDividePoissonMut(cAvidaContext& ctx) const { return m_mut_rates.NumDividePoissonMut(ctx); }
NumDividePoissonIns(cAvidaContext & ctx)352   unsigned int NumDividePoissonIns(cAvidaContext& ctx) const { return m_mut_rates.NumDividePoissonIns(ctx); }
NumDividePoissonDel(cAvidaContext & ctx)353   unsigned int NumDividePoissonDel(cAvidaContext& ctx) const { return m_mut_rates.NumDividePoissonDel(ctx); }
NumDividePoissonSlip(cAvidaContext & ctx)354   unsigned int NumDividePoissonSlip(cAvidaContext& ctx) const { return m_mut_rates.NumDividePoissonSlip(ctx); }
NumDividePoissonTrans(cAvidaContext & ctx)355   unsigned int NumDividePoissonTrans(cAvidaContext& ctx) const { return m_mut_rates.NumDividePoissonTrans(ctx); }
NumDividePoissonLGT(cAvidaContext & ctx)356   unsigned int NumDividePoissonLGT(cAvidaContext& ctx) const { return m_mut_rates.NumDividePoissonLGT(ctx); }
357 
TestDeath(cAvidaContext & ctx)358   bool TestDeath(cAvidaContext& ctx) const { return m_mut_rates.TestDeath(ctx); }
359 
GetCopyMutProb()360   double GetCopyMutProb() const { return m_mut_rates.GetCopyMutProb(); }
GetCopyInsProb()361   double GetCopyInsProb() const { return m_mut_rates.GetCopyInsProb(); }
GetCopyDelProb()362   double GetCopyDelProb() const { return m_mut_rates.GetCopyDelProb(); }
GetCopyUniformProb()363   double GetCopyUniformProb() const { return m_mut_rates.GetCopyUniformProb(); }
GetCopySlipProb()364   double GetCopySlipProb() const { return m_mut_rates.GetCopySlipProb(); }
365 
SetCopyMutProb(double _p)366   void SetCopyMutProb(double _p) { return m_mut_rates.SetCopyMutProb(_p); }
SetDivMutProb(double _p)367   void SetDivMutProb(double _p) { return m_mut_rates.SetDivMutProb(_p); }
368 
GetDivInsProb()369   double GetDivInsProb() const { return m_mut_rates.GetDivInsProb(); }
GetDivDelProb()370   double GetDivDelProb() const { return m_mut_rates.GetDivDelProb(); }
GetDivMutProb()371   double GetDivMutProb() const { return m_mut_rates.GetDivMutProb(); }
GetDivUniformProb()372   double GetDivUniformProb() const { return m_mut_rates.GetDivUniformProb(); }
GetDivSlipProb()373   double GetDivSlipProb() const { return m_mut_rates.GetDivSlipProb(); }
GetDivTransProb()374   double GetDivTransProb() const { return m_mut_rates.GetDivTransProb(); }
GetDivLGTProb()375   double GetDivLGTProb() const { return m_mut_rates.GetDivLGTProb(); }
376 
GetPointInsProb()377   double GetPointInsProb() const { return m_mut_rates.GetPointInsProb(); }
GetPointDelProb()378   double GetPointDelProb() const { return m_mut_rates.GetPointDelProb(); }
GetPointMutProb()379   double GetPointMutProb() const { return m_mut_rates.GetPointMutProb(); }
380 
GetParentMutProb()381   double GetParentMutProb() const { return m_mut_rates.GetParentMutProb();}
GetParentInsProb()382   double GetParentInsProb() const { return m_mut_rates.GetParentInsProb();}
GetParentDelProb()383   double GetParentDelProb() const { return m_mut_rates.GetParentDelProb();}
384 
GetDeathProb()385   double GetDeathProb() const { return m_mut_rates.GetDeathProb();}
386 
GetInjectInsProb()387   double GetInjectInsProb() const { return m_mut_rates.GetInjectInsProb(); }
GetInjectDelProb()388   double GetInjectDelProb() const { return m_mut_rates.GetInjectDelProb(); }
GetInjectMutProb()389   double GetInjectMutProb() const { return m_mut_rates.GetInjectMutProb(); }
390 
391   // --------  Configuration Convenience Methods  --------
392   bool GetTestOnDivide() const;
393   int GetSterilizeUnstable() const;
394 
395   bool GetRevertFatal() const;
396   bool GetRevertNeg() const;
397   bool GetRevertNeut() const;
398   bool GetRevertPos() const;
399   bool GetRevertTaskLoss() const;
400   bool GetRevertEquals() const;
401 
402   bool GetSterilizeFatal() const;
403   bool GetSterilizeNeg() const;
404   bool GetSterilizeNeut() const;
405   bool GetSterilizePos() const;
406   bool GetSterilizeTaskLoss() const;
407   double GetNeutralMin() const;
408   double GetNeutralMax() const;
409 
410 
411   // -------- Messaging support --------
412 public:
413   typedef std::deque<cOrgMessage> message_list_type; //!< Container-type for cOrgMessages.
414 
415   //! Called when this organism attempts to send a message.
416   bool SendMessage(cAvidaContext& ctx, cOrgMessage& msg);
417   //! Called when this organism attempts to broadcast a message.
418   bool BroadcastMessage(cAvidaContext& ctx, cOrgMessage& msg, int depth);
419   //! Called when this organism has been sent a message.
420   void ReceiveMessage(cOrgMessage& msg);
421   //! Called when this organism attempts to move a received message into its CPU.
422   std::pair<bool, cOrgMessage> RetrieveMessage();
423   //! Returns the list of all messsages received by this organism.
GetReceivedMessages()424   const message_list_type& GetReceivedMessages() { InitMessaging(); return m_msg->received; }
425   //! Returns the list of all messages sent by this organism.
GetSentMessages()426   const message_list_type& GetSentMessages() { InitMessaging(); return m_msg->sent; }
427   //! Use at your own rish; clear all the message buffers.
FlushMessageBuffers()428   void FlushMessageBuffers() { InitMessaging(); m_msg->sent.clear(); m_msg->received.clear(); }
PeekAtNextMessageType()429   int PeekAtNextMessageType() { InitMessaging(); return m_msg->received.front().GetMessageType(); }
430 
431 private:
432   /*! Contains all the different data structures needed to support messaging within
433   cOrganism.  Inspired by cNetSupport (above), the idea is to minimize impact on
434   organisms that DON'T use messaging. */
435   struct cMessagingSupport
436   {
cMessagingSupportcMessagingSupport437     cMessagingSupport() : retrieve_index(0) { }
438 
439     message_list_type sent; //!< List of all messages sent by this organism.
440     message_list_type received; //!< List of all messages received by this organism.
441     message_list_type::size_type retrieve_index; //!< Index of next message that can be retrieved.
442   };
443 
444   /*! This member variable is lazily initialized whenever any of the messaging
445   methods are used.  (My kingdom for boost::shared_ptr.) */
446   cMessagingSupport* m_msg;
447 
448   //! Called to check for (and initialize) messaging support within this organism.
InitMessaging()449   inline void InitMessaging() { if(!m_msg) m_msg = new cMessagingSupport(); }
450   //! Called as the bottom-half of a successfully sent message.
451   void MessageSent(cAvidaContext& ctx, cOrgMessage& msg);
452   // -------- End of messaging support --------
453 
454   // -------- Movement TEMP --------
455 public:
GetGradientMovement()456   double GetGradientMovement() const {
457     return m_gradient_movement;
458   }
459 
SetGradientMovement(const double value)460   void SetGradientMovement(const double value) {
461     m_gradient_movement = value;
462   }
463 
464 
465   // -------- BDC Movement ---------
466 public:
467   bool Move(cAvidaContext& ctx);
468 
469 
470   /***** context switch********/
471   bool BcastAlarmMSG(cAvidaContext& ctx, int jump_label, int bcast_range);
472   void moveIPtoAlarmLabel(int jump_label);
473 
DivideOrgTestamentAmongDeme(double value)474   void DivideOrgTestamentAmongDeme(double value) { m_interface->DivideOrgTestamentAmongDeme(value); }
475 
SetEventKilled()476   void SetEventKilled() { killed_event = true; }
GetEventKilled()477   bool GetEventKilled() { return killed_event; }
478 
479 
480   // -------- Opinion support --------
481   /*  Organisms express an opinion at a given point in time.  We can assume that they
482   hold this opinion until they express a new one.  The semantics of opinions are
483   left to the particular tasks or fitness functions in use; opinions are merely a generic
484   approach that we as developers can use to evaluate when an organism has made a decision.
485 
486   If we ever have a need for organisms to express different kinds of opinions, this code
487   can easily be adapted for that purpose (e.g., change the OpinionList typedef to a
488   std::map<int, DatedOpinion>, where the key represents the kind of opinion being expressed).
489 
490   As with other such types of "extended" functionality, opinion support is encapsulated in
491   a lazily-initialized struct.
492   */
493 public:
494   typedef int Opinion; //!< Typedef for an opinion.
495   typedef std::pair<Opinion, int> DatedOpinion; //!< Typedef for an opinion held at a given update.
496   typedef std::deque<DatedOpinion> DatedOpinionList; //!< Typedef for a list of dated opinions.
497   //! Called to set this organism's opinion.
498   void SetOpinion(const Opinion& opinion);
499   //! Retrieve this organism's current opinion.
GetOpinion()500   const DatedOpinion& GetOpinion() { InitOpinions(); return m_opinion->opinion_list.back(); }
501   //! Retrieve all opinions expressed during this organism's lifetime.
GetOpinions()502   const DatedOpinionList& GetOpinions() { InitOpinions(); return m_opinion->opinion_list; }
503   //! Return whether this organism has an opinion.
504   bool HasOpinion();
505   //! remove all opinions
ClearOpinion()506   void ClearOpinion() { InitOpinions(); m_opinion->opinion_list.clear(); }
507 
508 private:
509   //! Initialize opinion support.
InitOpinions()510   inline void InitOpinions() { if(!m_opinion) { m_opinion = new cOpinionSupport(); } }
511   //! Container for the data used to support opinions.
512   struct cOpinionSupport
513   {
514     DatedOpinionList opinion_list; //!< All opinions expressed by this organism during its lifetime.
515   };
516   cOpinionSupport* m_opinion; //!< Lazily-initialized pointer to the opinion data.
517   // -------- End of opinion support --------
518 
519 
520   // -------- Synchronization support --------
521 public:
522   //! Called when a neighboring organism issues a "flash" instruction.
523   void ReceiveFlash();
524   //! Sends a "flash" to all neighboring organisms.
525   void SendFlash(cAvidaContext& ctx);
526   // -------- End of synchronization support --------
527 
528 
529   // -------- Neighborhood support --------
530 public:
531   typedef std::set<int> Neighborhood; //!< Typedef for a neighborhood snapshot.
532   //! Get the current neighborhood.
533   Neighborhood GetNeighborhood();
534   //! Loads this organism's current neighborhood into memory.
535   void LoadNeighborhood();
536   //! Has the current neighborhood changed from what is in memory?
537   bool HasNeighborhoodChanged();
538 
539 protected:
540   //! Initialize neighborhood support.
InitNeighborhood()541   inline void InitNeighborhood() { if(!m_neighborhood) { m_neighborhood = new cNeighborhoodSupport(); } }
542   //! Container for neighborhood support.
543   struct cNeighborhoodSupport {
cNeighborhoodSupportcNeighborhoodSupport544     cNeighborhoodSupport() : loaded(false) { }
545     bool loaded;
546     Neighborhood neighbors;
547   };
548   cNeighborhoodSupport* m_neighborhood; //!< Lazily-initialized pointer to the neighborhood data.
549 
550 
551   // -------- Reputation support --------
552 public:
553   // Deduct amount number of self raw materials
554   bool SubtractSelfRawMaterials(int amount);
555   // Deduct amount number of other raw materials
556   bool SubtractOtherRawMaterials(int amount);
557   // receive raw materials from others
558   bool AddOtherRawMaterials(int amount, int donor_id);
559   // receive raw materials
560   bool AddRawMaterials(int amount, int donor_id);
561   // receive raw materials
AddSelfRawMaterials(int amount)562   void AddSelfRawMaterials(int amount) { if (m_self_raw_materials < 10) m_self_raw_materials += amount;}
563   // retrieve the organism's own amount of raw materials
GetSelfRawMaterials()564   int GetSelfRawMaterials() { return m_self_raw_materials; }
565   // retrieve the amount of raw materials collected from others
GetOtherRawMaterials()566   int GetOtherRawMaterials() { return m_other_raw_materials; }
567   // get the organism's reputation
568   int GetReputation();
569   // set the organism's reputation
570   void SetReputation(int rep);
571   // update the reputation to be an average on the basis of this new info
572   void SetAverageReputation(int rep);
573   // update the reputation by addint this new information
AddReputation(int rep)574   void AddReputation(int rep) { SetReputation(GetReputation() + rep); }
575   // increment reputation
IncReputation()576   void IncReputation() { SetReputation(GetReputation() + 1); }
577   // get number of donors
GetNumberOfDonors()578   int GetNumberOfDonors() { return donor_list.size(); }
579   // organism donated
Donated()580   void Donated(){m_num_donate++;}
581   // get number of donations
GetNumberOfDonations()582   int GetNumberOfDonations() { return m_num_donate; }
583   // get number of donations received
GetNumberOfDonationsReceived()584   int GetNumberOfDonationsReceived() { return m_num_donate_received; }
585   // get amout of donations received
GetAmountOfDonationsReceived()586   int GetAmountOfDonationsReceived() { return m_amount_donate_received; }
587   // organism reciprocated
Reciprocated()588   void Reciprocated() {m_num_reciprocate++;}
589   // get number of reciprocations
GetNumberOfReciprocations()590   int GetNumberOfReciprocations() { return m_num_reciprocate; }
591   // was the organism a donor
592   bool IsDonor(int neighbor_id);
593 
594   // Check if buffer contains this string; return # bits correct
595   int MatchOutputBuffer(cString string_to_match);
596 
597   // Add a donor
AddDonor(int org_id)598   void AddDonor(int org_id) { donor_list.insert(org_id); }
599   // Set tag
SetTag(int new_tag,int bits)600   void SetTag(int new_tag, int bits) { m_tag = make_pair(new_tag, bits); }
601   // Set tag
SetTag(pair<int,int> new_tag)602   void SetTag(pair < int, int > new_tag)  { m_tag = new_tag; }
603   // Update tag
604   void UpdateTag(int new_tag, int bits);
605   // Get tag
GetTagLabel()606   int GetTagLabel() { return m_tag.first; }
GetTag()607   pair < int, int > GetTag() { return m_tag; }
608   // Get number of failed reputation increases
GetFailedReputationIncreases()609   int GetFailedReputationIncreases() { return m_failed_reputation_increases; }
610 
611   // Clear the output buffer
612   void SetOutputNegative1();
AddDonatedLineage(int lin)613   void AddDonatedLineage(int lin) { donating_lineages.insert(lin); }
GetNumberOfDonatedLineages()614   int GetNumberOfDonatedLineages() { return donating_lineages.size(); }
615   void InitStringMap();
616   bool ProduceString(int i);
GetNumberStringsProduced(int i)617   int GetNumberStringsProduced(int i) { return  m_string_map[i].prod_string; }
GetNumberStringsOnHand(int i)618   int GetNumberStringsOnHand(int i) { return m_string_map[i].on_hand; }
619   bool DonateString(int string_tag, int amount);
620   bool ReceiveString(int string_tag, int amount, int donor_id);
621   bool CanReceiveString(int string_tag, int amount);
622 
623   // get the organism's relative position (from birth place)
GetNortherly()624   int GetNortherly() { return m_northerly; }
GetEasterly()625   int GetEasterly() { return m_easterly; }
ClearEasterly()626   void ClearEasterly() { m_easterly = 0; }
ClearNortherly()627   void ClearNortherly() { m_northerly = 0; }
628 
GetForageTarget()629   int GetForageTarget() const { return m_forage_target; }
630   void SetForageTarget(int forage_target);
HasSetFT()631   bool HasSetFT() const { return m_has_set_ft; }
RecordFTSet()632   void RecordFTSet() { m_has_set_ft = true; }
IsTeacher()633   bool IsTeacher() const { return m_teach; }
Teach(bool teach)634   void Teach(bool teach) { m_teach = teach; }
HadParentTeacher()635   bool HadParentTeacher() const { return m_parent_teacher; }
SetParentTeacher(bool had_teacher)636   void SetParentTeacher(bool had_teacher) { m_parent_teacher = had_teacher; }
SetParentFT(int parent_ft)637   void SetParentFT(int parent_ft) { m_parent_ft = parent_ft; }
GetParentFT()638   int GetParentFT() const { return m_parent_ft; }
639   void CopyParentFT();
SetParentGroup(int parent_group)640   void SetParentGroup(int parent_group) { m_parent_group = parent_group; }
GetParentGroup()641   int GetParentGroup() const { return m_parent_group; }
SetParentMerit(double parent_merit)642   void SetParentMerit(double parent_merit) { m_p_merit = parent_merit; }
GetParentMerit()643   double GetParentMerit() { return m_p_merit; }
SetParentMultiThreaded(bool parent_is_mt)644   void SetParentMultiThreaded(bool parent_is_mt) { m_p_mthread = parent_is_mt; }
IsParentMThreaded()645   bool IsParentMThreaded() { return m_p_mthread; }
646 
ChangeBeg()647   void ChangeBeg() { m_beggar = !m_beggar; }
IsBeggar()648   bool IsBeggar() { return m_beggar; }
649 
SetGuard()650   void SetGuard() { m_guard = !m_guard; }
IsGuard()651   bool IsGuard() { return m_guard; }
IncGuard()652   void IncGuard() { m_num_guard++; }
GetNumGuard()653   int GetNumGuard() { return m_num_guard; }
IncNumDeposits()654   void IncNumDeposits() { m_num_deposits++; }
IncAmountDeposited(double amount)655   void IncAmountDeposited(double amount) { m_amount_deposited = m_amount_deposited + amount; }
GetNumDeposits()656   int GetNumDeposits() { return m_num_deposits; }
GetAmountDeposited()657   double GetAmountDeposited() { return m_amount_deposited; }
658 
659 protected:
660   // The organism's own raw materials
661   int m_self_raw_materials;
662   // The raw materials an oranism has collected from others
663   int m_other_raw_materials;
664   // Organisms that have donated to this organism
665   set<int> donor_list;
666   // Strings this organism has received.
667   set<int> donating_lineages;
668   // number of donations
669   int m_num_donate;
670   // number of donations received
671   int m_num_donate_received;
672   // amount of donations received
673   int m_amount_donate_received;
674   // number of reciprocations
675   int m_num_reciprocate;
676   // reputation minimum for donation/rotation
677   // based on Nowak89
678   int m_k;
679   // int number of reputation increase failures
680   int m_failed_reputation_increases;
681   std::pair < int, int > m_tag;
682   //total number of steps taken to north (minus S steps) since birth
683   int m_northerly;
684   //total number of steps taken to east (minus W steps) since birth
685   int m_easterly;
686 
687   int m_forage_target;
688   bool m_has_set_ft;
689   bool m_teach;
690   bool m_parent_teacher;
691   int m_parent_ft;
692   int m_parent_group;
693   double m_p_merit;
694   bool m_p_mthread;
695 
696   bool m_beggar;
697 
698   bool m_guard;
699     int m_num_guard;
700     int m_num_deposits;
701     double m_amount_deposited;
702 
703   /*! Contains all the different data structures needed to
704   track strings, production of strings, and donation/trade
705   of strings. It is inspired by the cMessagingSupport*/
706   struct cStringSupport
707   {
cStringSupportcStringSupport708     cStringSupport()
709     { prod_string = 0; received_string = 0; on_hand = 0; }
710     cString m_string; //!< The string being tracked
711     int prod_string; //!< The number of times this string has been produced.
712     int received_string; //!< The number of times this string has been received.
713     int on_hand; //!< The number of copies of the string this organism has on hand
714   };
715 
716   /* This member variable is a map of tags to strings. It can
717   be used to track production, consumption, and donation of
718   strings. */
719   std::map < int, cStringSupport > m_string_map;
720 
721 
722   // -------- HGT conjugation support --------
723 public:
724   //! Called when this individual is the donor organism during conjugation.
725   void DoHGTDonation();
726 
727 
728   // -------- Division of Labor support --------
729 public:
730   void DonateResConsumedToDeme(); //! donate consumed resources to the deme.
GetNumOfPointMutationsApplied()731   int GetNumOfPointMutationsApplied() {return m_num_point_mut; } //! number of point mutations applied to org.
IncPointMutations(int n)732   void IncPointMutations(int n) {m_num_point_mut+=n;}
JoinGermline()733   void JoinGermline() {m_phenotype.is_germ_cell = true;}
ExitGermline()734   void ExitGermline() {m_phenotype.is_germ_cell = false;}
RepairPointMutOn()735   void RepairPointMutOn() {m_repair = true;}
RepairPointMutOff()736   void RepairPointMutOff() {m_repair = false;}
IsGermline()737   bool IsGermline() { return m_phenotype.is_germ_cell; }
738 private:
739   int m_num_point_mut;
740 //  bool m_germline;
741   bool m_repair;
742 
743 	// -------- Avatar support --------
744 public:
745   bool MoveAV(cAvidaContext& ctx);
SetAVInIndex(int index)746   inline void SetAVInIndex(int index) { m_av_in_index = index; }
GetAVInIndex()747   inline int GetAVInIndex() { return m_av_in_index; }
SetAVOutIndex(int index)748   inline void SetAVOutIndex(int index) { m_av_out_index = index; }
GetAVOutIndex()749   inline int GetAVOutIndex() { return m_av_out_index; }
750 
751 	// -------- Internal Support Methods --------
752 private:
753   int m_av_in_index;
754   int m_av_out_index;
755 
756   void initialize(cAvidaContext& ctx);
757 
758   /*! The main DoOutput function.  The DoOutputs above all forward to this function. */
759   void doOutput(cAvidaContext& ctx, tBuffer<int>& input_buffer, tBuffer<int>& output_buffer, const bool on_divide, bool is_parasite=false, cContextPhenotype* context_phenotype = 0);
760   // Need seperate doOutput function for avatars to avoid triggering reactions by true orgs
761   void doAVOutput(cAvidaContext& ctx, tBuffer<int>& input_buffer, tBuffer<int>& output_buffer, const bool on_divide, bool is_parasite=false, cContextPhenotype* context_phenotype = 0);
762 };
763 
764 
GetTestFitness(cAvidaContext & ctx)765 inline double cOrganism::GetTestFitness(cAvidaContext& ctx) const {
766   return cGenomeTestMetrics::GetMetrics(ctx, GetBioGroup("genotype"))->GetFitness();
767 }
768 
GetTestMerit(cAvidaContext & ctx)769 inline double cOrganism::GetTestMerit(cAvidaContext& ctx) const {
770   return cGenomeTestMetrics::GetMetrics(ctx, GetBioGroup("genotype"))->GetMerit();
771 }
772 
GetTestColonyFitness(cAvidaContext & ctx)773 inline double cOrganism::GetTestColonyFitness(cAvidaContext& ctx) const {
774   return cGenomeTestMetrics::GetMetrics(ctx, GetBioGroup("genotype"))->GetColonyFitness();
775 }
776 
777 
SetSleeping(bool sleeping)778 inline void cOrganism::SetSleeping(bool sleeping)
779 {
780   m_is_sleeping = sleeping;
781 
782   if (sleeping) m_interface->BeginSleep();
783   else m_interface->EndSleep();
784 }
785 
786 
787 #endif
788 
789