[Avida-SVN] r1637 - in development: documentation source/actions source/cpu source/drivers source/main source/targets/avida-viewer source/tools

beckma24 at myxo.css.msu.edu beckma24 at myxo.css.msu.edu
Mon Jun 4 09:32:45 PDT 2007


Author: beckma24
Date: 2007-06-04 12:32:44 -0400 (Mon, 04 Jun 2007)
New Revision: 1637

Modified:
   development/documentation/inst_set.html
   development/source/actions/EnvironmentActions.cc
   development/source/cpu/cHardwareCPU.cc
   development/source/cpu/cHardwareCPU.h
   development/source/cpu/cHardwareManager.cc
   development/source/cpu/cInstSet.cc
   development/source/cpu/cInstSet.h
   development/source/drivers/cDefaultRunDriver.cc
   development/source/main/cAvidaConfig.h
   development/source/main/cBirthChamber.cc
   development/source/main/cEnvironment.cc
   development/source/main/cOrganism.cc
   development/source/main/cOrganism.h
   development/source/main/cPhenotype.cc
   development/source/main/cPhenotype.h
   development/source/main/cPopulation.cc
   development/source/main/cPopulation.h
   development/source/main/cReactionResult.cc
   development/source/main/cReactionResult.h
   development/source/main/nReaction.h
   development/source/targets/avida-viewer/cZoomScreen.cc
   development/source/tools/cWeightedIndex.cc
Log:
Addition of energy model for use with asexual organisms and cHardwareCPU hardware.  This commit merges branches/energy into the development branch.  (revisions 1338:now)

Modified: development/documentation/inst_set.html
===================================================================
--- development/documentation/inst_set.html	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/documentation/inst_set.html	2007-06-04 16:32:44 UTC (rev 1637)
@@ -5,9 +5,7 @@
 </head>
 <body>
 
-<div class="revision">
-Revised 2006-09-05 DMB
-</div>
+<div class="revision">Revised 2007-03-20 BEB</div>
 
 <p><a href="index.html">Return to the Index</a></p>
 <hr />
@@ -22,7 +20,7 @@
 define how that instruction should be used.  The exact format is as follows:
 </p>
 <p>
-<code>inst-name redundancy cost ft_cost prob_fail</code>
+<code>inst-name redundancy cost ft_cost energy_cost prob_fail</code>
 </p>
 
 
@@ -50,13 +48,17 @@
   executed.  This is used to lower the diversity of instructions 
   inside an organism.  The default value here is 0.
 </dd>
-<dt><strong>prob_fail</strong></dt>
+<dt><strong>energy_cost</strong></dt>
 <dd>
+  The number of Energy units required to execute this instruction. Zero is the default if this value is not specified.
+</dd>
+<dt><strong>prob_fail</strong>	
+<dd>
   The probability of this instruction not working properly.  If an
   instruction fails it will simply do nothing, but still cost the
   CPU cycles to execute.  The defailt probability of failure is zero.
 </dd>
-</dl>
+		</dl>
 
 <p>
 Normally only the first column of numbers is used in the file.

Modified: development/source/actions/EnvironmentActions.cc
===================================================================
--- development/source/actions/EnvironmentActions.cc	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/actions/EnvironmentActions.cc	2007-06-04 16:32:44 UTC (rev 1637)
@@ -22,6 +22,7 @@
  *
  */
 
+#include "math.h"
 #include "EnvironmentActions.h"
 
 #include "cAction.h"
@@ -265,7 +266,6 @@
   }
 };
 
-
 class cActionSetTaskArgInt : public cAction
 {
 private:
@@ -295,7 +295,107 @@
   }
 };
 
+/**
+Sets resource availiblity to periodic
+ */
+class cActionSetPeriodicResource : public cAction
+{
+private:
+  cString m_res_name;
+  double m_res_count;
+  double amplitude;
+  double frequency;
+  double phaseShift;
+  double initY;
 
+public:
+  cActionSetPeriodicResource(cWorld* world, const cString& args): cAction(world, args), m_res_name(""), amplitude(1.0),
+                                                                  frequency(1.0), phaseShift(0.0), initY(0.0)
+  {
+    cString largs(args);
+    if (largs.GetSize()) m_res_name = largs.PopWord();
+    if (largs.GetSize()) amplitude = largs.PopWord().AsDouble();
+    if (largs.GetSize()) frequency = largs.PopWord().AsDouble();
+    if (largs.GetSize()) phaseShift = largs.PopWord().AsDouble();
+    if (largs.GetSize()) initY = largs.PopWord().AsDouble();
+  }
+  
+  static const cString GetDescription() { return "Arguments: <string reaction_name> <string amplitude> <string pi/frequence> <phaseShift*pi> <string initial_Y>"; }
+  
+  void Process(cAvidaContext& ctx)
+  {
+    int time = m_world->GetStats().GetUpdate();
+    m_res_count = (amplitude * sin(M_PI/frequency * time - phaseShift * M_PI) + initY) / 2;
+    cResource* res = m_world->GetEnvironment().GetResourceLib().GetResource(m_res_name);
+    if (res != NULL) m_world->GetPopulation().SetResource(res->GetID(), m_res_count);
+
+  }
+};
+
+
+/**
+Sets energy model config value NumInstBefore0Energy 
+ */
+
+class cActionSetNumInstBefore0Energy : public cAction
+{
+private:
+  int newValue;
+
+public:
+  cActionSetNumInstBefore0Energy(cWorld* world, const cString& args) : cAction(world, args), newValue(0)
+  {
+    cString largs(args);
+    if (largs.GetSize()) newValue = largs.PopWord().AsInt();
+  }
+  
+  static const cString GetDescription() { return "Arguments: <int new_value>"; }
+  
+  void Process(cAvidaContext& ctx)
+  {
+    m_world->GetConfig().NUM_INST_EXC_BEFORE_0_ENERGY.Set(newValue);
+  }
+};
+
+/*
+class cActionSetDoublePeriodicResource : public cAction
+{
+private:
+  cString m_res_name;
+  double m_res_count;
+  double amplitude;
+  double frequency;
+  double phaseShift;
+  double initY;
+
+public:
+  cActionSetDoublePeriodicResource(cWorld* world, const cString& args): cAction(world, args), m_res_name(""), amplitude(1.0),
+                                                                  frequency(1.0), phaseShift(0.0), initY(0.0)
+  {
+    cString largs(args);
+    if (largs.GetSize()) m_res_name = largs.PopWord();
+    if (largs.GetSize()) amplitude = largs.PopWord().AsDouble();
+    if (largs.GetSize()) frequency = largs.PopWord().AsDouble();
+    if (largs.GetSize()) phaseShift = largs.PopWord().AsDouble();
+    if (largs.GetSize()) initY = largs.PopWord().AsDouble();
+  }
+  
+  static const cString GetDescription() { return "Arguments: <string reaction_name> <string amplitude> <string pi/frequence> <phaseShift*pi> <string initial_Y>"; }
+  
+  void Process(cAvidaContext& ctx)
+  {
+    int time = m_world->GetStats().GetUpdate();
+    m_res_count = ampliture*(sin(pi/frequency1*x-pi*phaseShift1)+1+cos(pi/frequency2*x-pi*phaseShift1)+1)/4;
+    
+    std::cout << "Update " << time << " Y = " << m_res_count << std::endl;
+//    std::cout << m_res_count <<" = " << amplitude <<" * sin("<<frequency <<" * " << time <<" - "<< phaseShift<<") + "<<initY<<std::endl;
+    cResource* res = m_world->GetEnvironment().GetResourceLib().GetResource(m_res_name);
+    if (res != NULL) m_world->GetPopulation().SetResource(res->GetID(), m_res_count);
+
+  }
+};
+*/
+
 class cActionSetTaskArgDouble : public cAction
 {
 private:
@@ -355,22 +455,21 @@
   }
 };
 
-
-
-
-
 void RegisterEnvironmentActions(cActionLibrary* action_lib)
 {
   action_lib->Register<cActionInjectResource>("InjectResource");
   action_lib->Register<cActionInjectScaledResource>("InjectScaledResource");
   action_lib->Register<cActionOutflowScaledResource>("OutflowScaledResource");
   action_lib->Register<cActionSetResource>("SetResource");
-  action_lib->Register<cActionSetCellResource>("SetCellResource");
+  action_lib->Register<cActionSetCellResource>("SetCellResource");  
 
   action_lib->Register<cActionSetReactionValue>("SetReactionValue");
   action_lib->Register<cActionSetReactionValueMult>("SetReactionValueMult");
   action_lib->Register<cActionSetReactionInst>("SetReactionInst");
 
+  action_lib->Register<cActionSetPeriodicResource>("SetPeriodicResource");
+  action_lib->Register<cActionSetNumInstBefore0Energy>("SetNumInstBefore0Energy");
+
   action_lib->Register<cActionSetTaskArgInt>("SetTaskArgInt");
   action_lib->Register<cActionSetTaskArgDouble>("SetTaskArgDouble");
   action_lib->Register<cActionSetTaskArgString>("SetTaskArgString");

Modified: development/source/cpu/cHardwareCPU.cc
===================================================================
--- development/source/cpu/cHardwareCPU.cc	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/cpu/cHardwareCPU.cc	2007-06-04 16:32:44 UTC (rev 1637)
@@ -39,6 +39,8 @@
 #include "nMutation.h"
 #include "cOrganism.h"
 #include "cPhenotype.h"
+#include "cPopulation.h"
+#include "cPopulationCell.h"
 #include "cStringUtil.h"
 #include "cTestCPU.h"
 #include "cWorldDriver.h"
@@ -330,6 +332,15 @@
     tInstLibEntry<tMethod>("kazi5", &cHardwareCPU::Inst_Kazi5),
     tInstLibEntry<tMethod>("die", &cHardwareCPU::Inst_Die),
 
+    // Sleep and time
+    tInstLibEntry<tMethod>("sleep", &cHardwareCPU::Inst_Sleep),
+    tInstLibEntry<tMethod>("sleep1", &cHardwareCPU::Inst_Sleep),
+    tInstLibEntry<tMethod>("sleep2", &cHardwareCPU::Inst_Sleep),
+    tInstLibEntry<tMethod>("sleep3", &cHardwareCPU::Inst_Sleep),
+    tInstLibEntry<tMethod>("sleep4", &cHardwareCPU::Inst_Sleep),
+    tInstLibEntry<tMethod>("time", &cHardwareCPU::Inst_GetUpdate),
+    
+
     // Promoter Model
     tInstLibEntry<tMethod>("up-reg-*", &cHardwareCPU::Inst_UpRegulatePromoter),
     tInstLibEntry<tMethod>("down-reg-*", &cHardwareCPU::Inst_DownRegulatePromoter),
@@ -390,8 +401,10 @@
 #if INSTRUCTION_COSTS
 , inst_cost(hardware_cpu.inst_cost)
 , inst_ft_cost(hardware_cpu.inst_ft_cost)
+, inst_energy_cost(hardware_cpu.inst_energy_cost)
 , m_has_costs(hardware_cpu.m_has_costs)
 , m_has_ft_costs(hardware_cpu.m_has_ft_costs)
+  // TODO - m_has_energy_costs
 #endif
 {
 }
@@ -417,8 +430,10 @@
   const int num_inst_cost = m_inst_set->GetSize();
   inst_cost.Resize(num_inst_cost);
   inst_ft_cost.Resize(num_inst_cost);
+  inst_energy_cost.Resize(num_inst_cost);
   m_has_costs = false;
   m_has_ft_costs = false;
+  // TODO - m_has_energy_costs
   
   for (int i = 0; i < num_inst_cost; i++) {
     inst_cost[i] = m_inst_set->GetCost(cInstruction(i));
@@ -426,6 +441,9 @@
     
     inst_ft_cost[i] = m_inst_set->GetFTCost(cInstruction(i));
     if (!m_has_ft_costs && inst_ft_cost[i]) m_has_ft_costs = true;
+
+    inst_energy_cost[i] = m_inst_set->GetEnergyCost(cInstruction(i));    
+    // TODO - m_has_energy_costs  if()
   }
 #endif 
   
@@ -568,6 +586,35 @@
 #if INSTRUCTION_COSTS
   assert(cur_inst.GetOp() < inst_cost.GetSize());
   
+  // check avaliable energy first
+  double energy_req = inst_energy_cost[cur_inst.GetOp()] * (organism->GetPhenotype().GetMerit().GetDouble() / 100.0); //compensate by factor of 100
+
+  if(m_world->GetConfig().ENERGY_ENABLED.Get() == 1 && energy_req > 0.0) {
+    if(organism->GetPhenotype().GetStoredEnergy() >= energy_req) {
+      inst_energy_cost[cur_inst.GetOp()] = 0;
+      //subtract energy used from current org energy.
+      organism->GetPhenotype().ReduceEnergy(energy_req);  
+    
+    
+    // tracking sleeping organisms
+  cString instName = m_world->GetHardwareManager().GetInstSet().GetName(cur_inst);
+  int cellID = organism->GetCellID();
+  if( instName == cString("sleep") || instName == cString("sleep1") || instName == cString("sleep2") ||
+      instName == cString("sleep3") || instName == cString("sleep4")) {
+    cPopulation& pop = m_world->GetPopulation();
+    if(m_world->GetConfig().LOG_SLEEP_TIMES.Get() == 1) {
+      pop.AddBeginSleep(cellID,m_world->GetStats().GetUpdate());
+    }
+    pop.GetCell(cellID).GetOrganism()->SetSleeping(true);
+    pop.incNumAsleep();    //TODO - Fix me:  this functions get called repeatedly
+  }
+    
+    } else {
+      // not enough energy
+      return false;
+    }
+  }
+    
   // If first time cost hasn't been paid off...
   if (m_has_ft_costs && inst_ft_cost[cur_inst.GetOp()] > 0) {
     inst_ft_cost[cur_inst.GetOp()]--;       // dec cost
@@ -584,6 +631,7 @@
     }
   }
   
+  inst_energy_cost[cur_inst.GetOp()] = m_inst_set->GetEnergyCost(cur_inst); //reset instruction energy cost
 #endif
   return true;
 }
@@ -599,7 +647,7 @@
   // If there is an execution error, execute a random instruction.
   if (organism->TestExeErr()) actual_inst = m_inst_set->GetRandomInst(ctx);
 #endif /* EXECUTION_ERRORS */
-  
+    
   // Get a pointer to the corresponding method...
   int inst_idx = m_inst_set->GetLibFunctionIndex(actual_inst);
   
@@ -3991,6 +4039,33 @@
   return true; 
 }
 
+bool cHardwareCPU::Inst_Sleep(cAvidaContext& ctx) {
+  cPopulation& pop = m_world->GetPopulation();
+  if(m_world->GetConfig().LOG_SLEEP_TIMES.Get() == 1) {
+    pop.AddEndSleep(organism->GetCellID(), m_world->GetStats().GetUpdate());
+  }
+  int cellID = organism->GetCellID();
+  pop.GetCell(cellID).GetOrganism()->SetSleeping(false);  //this instruction get executed at the end of a sleep cycle
+  pop.decNumAsleep();
+  if(m_world->GetConfig().APPLY_ENERGY_METHOD.Get() == 2) {
+    organism->GetPhenotype().RefreshEnergy();
+    double newMerit = organism->GetPhenotype().ApplyToEnergyStore();
+    if(newMerit != -1) {
+      std::cerr.precision(20);
+      std::cerr<<"[cHardwareCPU::Inst_Sleep] newMerit = "<< newMerit <<std::endl;
+      organism->GetOrgInterface().UpdateMerit(newMerit);
+    }
+  }
+  return true;
+}
+
+bool cHardwareCPU::Inst_GetUpdate(cAvidaContext& ctx) {
+  const int reg_used = FindModifiedRegister(REG_BX);
+  GetRegister(reg_used) = m_world->GetStats().GetUpdate();
+  return true;
+}
+
+
 //// Promoter Model ////
 
 // Starting at the current position reads a promoter pattern
@@ -4190,6 +4265,7 @@
   return true;
 }
 
+
 //// Placebo insts ////
 bool cHardwareCPU::Inst_Skip(cAvidaContext& ctx)
 {

Modified: development/source/cpu/cHardwareCPU.h
===================================================================
--- development/source/cpu/cHardwareCPU.h	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/cpu/cHardwareCPU.h	2007-06-04 16:32:44 UTC (rev 1637)
@@ -142,8 +142,10 @@
 #if INSTRUCTION_COSTS
   tArray<int> inst_cost;
   tArray<int> inst_ft_cost;
+  tArray<int> inst_energy_cost;
   bool m_has_costs;
   bool m_has_ft_costs;
+  bool m_has_energy_costs;
 #endif
   
   
@@ -520,6 +522,9 @@
   bool Inst_HeadDivide0_01(cAvidaContext& ctx);
   bool Inst_HeadDivide0_001(cAvidaContext& ctx);
 
+  bool Inst_Sleep(cAvidaContext& ctx);
+  bool Inst_GetUpdate(cAvidaContext& ctx);
+
   //// Promoter Model ////
   void GetPromoterPattern(tArray<int>& promoter);
   void RegulatePromoter(cAvidaContext& ctx, bool up);

Modified: development/source/cpu/cHardwareManager.cc
===================================================================
--- development/source/cpu/cHardwareManager.cc	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/cpu/cHardwareManager.cc	2007-06-04 16:32:44 UTC (rev 1637)
@@ -89,6 +89,7 @@
     int redundancy = cur_line.PopWord().AsInt();
     int cost = cur_line.PopWord().AsInt();
     int ft_cost = cur_line.PopWord().AsInt();
+    int energy_cost = cur_line.PopWord().AsInt();
     double prob_fail = cur_line.PopWord().AsDouble();
     int addl_time_cost = cur_line.PopWord().AsInt();
 
@@ -113,9 +114,9 @@
     }
     
     if (inst_lib[inst_idx].IsNop()) {
-      m_inst_set->AddNop(inst_idx, redundancy, ft_cost, cost, prob_fail, addl_time_cost);
+      m_inst_set->AddNop(inst_idx, redundancy, ft_cost, cost, energy_cost, prob_fail, addl_time_cost);
     } else {
-      m_inst_set->AddInst(inst_idx, redundancy, ft_cost, cost, prob_fail, addl_time_cost);
+      m_inst_set->AddInst(inst_idx, redundancy, ft_cost, cost, energy_cost, prob_fail, addl_time_cost);
     }
   }
 }

Modified: development/source/cpu/cInstSet.cc
===================================================================
--- development/source/cpu/cInstSet.cc	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/cpu/cInstSet.cc	2007-06-04 16:32:44 UTC (rev 1637)
@@ -58,7 +58,7 @@
   return cInstruction(inst_op);
 }
 
-int cInstSet::AddInst(int lib_fun_id, int redundancy, int ft_cost, int cost, double prob_fail, int addl_time_cost)
+int cInstSet::AddInst(int lib_fun_id, int redundancy, int ft_cost, int cost, int energy_cost, double prob_fail, int addl_time_cost)
 {
   const int inst_id = m_lib_name_map.GetSize();
 
@@ -72,6 +72,7 @@
   m_lib_name_map[inst_id].redundancy = redundancy;
   m_lib_name_map[inst_id].cost = cost;
   m_lib_name_map[inst_id].ft_cost = ft_cost;
+  m_lib_name_map[inst_id].energy_cost = energy_cost;
   m_lib_name_map[inst_id].prob_fail = prob_fail;
   m_lib_name_map[inst_id].addl_time_cost = addl_time_cost;
 
@@ -80,16 +81,17 @@
   for (int i = 0; i < redundancy; i++) {
     m_mutation_chart[total_redundancy + i] = inst_id;
   }
+  total_energy_cost += energy_cost;
 
   return inst_id;
 }
 
-int cInstSet::AddNop(int lib_nopmod_id, int redundancy, int ft_cost, int cost, double prob_fail, int addl_time_cost)
+int cInstSet::AddNop(int lib_nopmod_id, int redundancy, int ft_cost, int cost, int energy_cost, double prob_fail, int addl_time_cost)
 {
   // Assert nops are at the _beginning_ of an inst_set.
   assert(m_lib_name_map.GetSize() == m_lib_nopmod_map.GetSize());
 
-  const int inst_id = AddInst(lib_nopmod_id, redundancy, ft_cost, cost, prob_fail, addl_time_cost);
+  const int inst_id = AddInst(lib_nopmod_id, redundancy, ft_cost, cost, energy_cost, prob_fail, addl_time_cost);
 
   m_lib_nopmod_map.Resize(inst_id + 1);
   m_lib_nopmod_map[inst_id] = lib_nopmod_id;

Modified: development/source/cpu/cInstSet.h
===================================================================
--- development/source/cpu/cInstSet.h	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/cpu/cInstSet.h	2007-06-04 16:32:44 UTC (rev 1637)
@@ -65,6 +65,7 @@
     int redundancy;           // Weight in instruction set (not impl.)
     int cost;                 // additional time spent to exectute inst.
     int ft_cost;              // time spent first time exec (in add to cost)
+    int energy_cost;          // energy required to execute.
     double prob_fail;         // probability of failing to execute inst
     int addl_time_cost;       // additional time added to age for executing instruction
   };
@@ -75,12 +76,14 @@
   // Static components...
   cInstruction m_inst_error;
   cInstruction m_inst_default;
+
+  double total_energy_cost; // summation of energy costs of each instruction
   
   cInstSet(); // @not_implemented
 
 public:
   inline cInstSet(cWorld* world, cInstLib* inst_lib) : m_world(world), m_inst_lib(inst_lib),
-    m_inst_error(inst_lib->GetInstError()), m_inst_default(inst_lib->GetInstDefault()) { ; }
+    m_inst_error(inst_lib->GetInstError()), m_inst_default(inst_lib->GetInstDefault()), total_energy_cost(0) { ; }
   inline cInstSet(const cInstSet& is);
   inline ~cInstSet() { ; }
 
@@ -93,10 +96,12 @@
   const cString& GetName(const cInstruction& inst) const { return GetName(inst.GetOp()); }
   int GetCost(const cInstruction& inst) const { return m_lib_name_map[inst.GetOp()].cost; }
   int GetFTCost(const cInstruction& inst) const { return m_lib_name_map[inst.GetOp()].ft_cost; }
+  int GetEnergyCost(const cInstruction& inst) const { return m_lib_name_map[inst.GetOp()].energy_cost; }
   int GetAddlTimeCost(const cInstruction& inst) const { return m_lib_name_map[inst.GetOp()].addl_time_cost; }
   double GetProbFail(const cInstruction& inst) const { return m_lib_name_map[inst.GetOp()].prob_fail; }
   int GetRedundancy(const cInstruction& inst) const { return m_lib_name_map[inst.GetOp()].redundancy; }
   int GetLibFunctionIndex(const cInstruction& inst) const { return m_lib_name_map[inst.GetOp()].lib_fun_id; }
+//  double GetAvgEnergyCostPerInst() const { return total_energy_cost/m_lib_name_map.GetSize(); }
 
   int GetNopMod(const cInstruction& inst) const
   {
@@ -115,8 +120,8 @@
   int IsLabel(const cInstruction& inst) const { return m_inst_lib->Get(GetLibFunctionIndex(inst)).IsLabel(); }
 
   // Insertion of new instructions...
-  int AddInst(int lib_fun_id, int redundancy = 1, int ft_cost = 0, int cost = 0, double prob_fail = 0.0, int addl_time_cost = 0);
-  int AddNop(int lib_nopmod_id, int redundancy = 1, int ft_cost = 0, int cost = 0, double prob_fail = 0.0, int addl_time_cost = 0);
+  int AddInst(int lib_fun_id, int redundancy = 1, int ft_cost = 0, int cost = 0, int energy_cost = 0, double prob_fail = 0.0, int addl_time_cost = 0);
+  int AddNop(int lib_nopmod_id, int redundancy = 1, int ft_cost = 0, int cost = 0, int energy_cost = 0, double prob_fail = 0.0, int addl_time_cost = 0);
 
   // accessors for instruction library
   cInstLib* GetInstLib() { return m_inst_lib; }

Modified: development/source/drivers/cDefaultRunDriver.cc
===================================================================
--- development/source/drivers/cDefaultRunDriver.cc	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/drivers/cDefaultRunDriver.cc	2007-06-04 16:32:44 UTC (rev 1637)
@@ -120,6 +120,8 @@
       cout << "UD: " << setw(6) << stats.GetUpdate() << "  "
         << "Gen: " << setw(9) << setprecision(7) << stats.SumGeneration().Average() << "  "
         << "Fit: " << setw(9) << setprecision(7) << stats.GetAveFitness() << "  "
+      //  << "Energy: " << setw(9) << setprecision(7) << stats.GetAveEnergy() << "  "
+//        << "Merit: " << setw(9) << setprecision(7) << stats.GetAveMerit() << "  "
         << "Orgs: " << setw(6) << population.GetNumOrganisms() << "  "
         << "Thrd: " << setw(6) << stats.GetNumThreads() << "  "
         << "Para: " << stats.GetNumParasites()

Modified: development/source/main/cAvidaConfig.h
===================================================================
--- development/source/main/cAvidaConfig.h	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/main/cAvidaConfig.h	2007-06-04 16:32:44 UTC (rev 1637)
@@ -247,7 +247,7 @@
   CONFIG_ADD_VAR(REQUIRED_TASK, int, -1, "Task ID required for successful divide.");
   CONFIG_ADD_VAR(IMMUNITY_TASK, int, -1, "Task providing immunity from the required task.");
   CONFIG_ADD_VAR(REQUIRED_REACTION, int, -1, "Reaction ID required for successful divide.");
-  CONFIG_ADD_VAR(REQUIRED_BONUS, int, 0, "The bonus that an organism must accumulate to divide."); 
+  CONFIG_ADD_VAR(REQUIRED_BONUS, int, 0, "The bonus that an organism must accumulate to divide.");  
  
   CONFIG_ADD_GROUP(MUTATION_GROUP, "Mutations");
   CONFIG_ADD_VAR(POINT_MUT_PROB, double, 0.0, "Mutation rate (per-location per update)");
@@ -347,11 +347,23 @@
   CONFIG_ADD_VAR(MT_CONCURRENCY, int, 1, "Number of concurrent analyze threads");
   CONFIG_ADD_VAR(ANALYZE_OPTION_1, cString, "", "String variable accessible from analysis scripts");
   CONFIG_ADD_VAR(ANALYZE_OPTION_2, cString, "", "String variable accessible from analysis scripts");
+  
+  CONFIG_ADD_GROUP(ENERGY_GROUP, "Energy Settings");
+  CONFIG_ADD_VAR(ENERGY_ENABLED, bool, 0, "Enable Energy Model. 0/1 (off/on)");
+  CONFIG_ADD_VAR(ENERGY_GIVEN_ON_INJECT, int, 0, "Energy given to organism upon injection.");
+  CONFIG_ADD_VAR(ENERGY_GIVEN_AT_BIRTH, int, 0, "Energy given to offspring upon birth.");
+  CONFIG_ADD_VAR(FRAC_PARENT_ENERGY_GIVEN_AT_BIRTH, double, 0.5, "Fraction of perent's energy given to offspring.");
+  CONFIG_ADD_VAR(FRAC_ENERGY_DECAY_AT_BIRTH, double, 0.0, "Fraction of energy lost due to decay during reproduction.");
+  CONFIG_ADD_VAR(NUM_INST_EXC_BEFORE_0_ENERGY, int, 0, "Number of instructions executed before energy is exhausted.");
+  CONFIG_ADD_VAR(ENERGY_CAP, int, -1, "Maximun amount of energy that can be stored in an organism.  -1 means the cap is set to Max Int");  // TODO - is this done?
+  CONFIG_ADD_VAR(APPLY_ENERGY_METHOD, int, 0, "When should rewarded energy be applied to current energy?\n0 = on divide\n1 = on completion of task\n2 = on sleep");  
+  CONFIG_ADD_VAR(ENERGY_VERBOSE, bool, 0, "Print energy and merit values. 0/1 (off/on)");
+  CONFIG_ADD_VAR(LOG_SLEEP_TIMES, bool, 0, "Log sleep start and end times. 0/1 (off/on)\nWARNING: may use lots of memory.");
+//  CONFIG_ADD_VAR(FIX_METABOLIC_RATE, bool, 0, "When activated the metabolic rate of all orgiansims are equal. 0/1 (off/on)"); // TODO - check for correctness
 
-		CONFIG_ADD_GROUP(SECOND_PASS_GROUP, "Tracking metrics known after the running experiment previously");
-	CONFIG_ADD_VAR(TRACK_CCLADES, int, 0, "Enable tracking of coalescence clades");
-	CONFIG_ADD_VAR(TRACK_CCLADES_IDS, cString, "coalescence.ids", "File storing coalescence IDs");
-	
+  CONFIG_ADD_GROUP(SECOND_PASS_GROUP, "Tracking metrics known after the running experiment previously");
+  CONFIG_ADD_VAR(TRACK_CCLADES, int, 0, "Enable tracking of coalescence clades");
+  CONFIG_ADD_VAR(TRACK_CCLADES_IDS, cString, "coalescence.ids", "File storing coalescence IDs");
 #endif
   
   void Load(const cString& filename, const bool& crash_if_not_found);

Modified: development/source/main/cBirthChamber.cc
===================================================================
--- development/source/main/cBirthChamber.cc	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/main/cBirthChamber.cc	2007-06-04 16:32:44 UTC (rev 1637)
@@ -150,8 +150,47 @@
   child_array.Resize(1);
   child_array[0] = new cOrganism(m_world, ctx, child_genome);
   merit_array.Resize(1);
-  merit_array[0] = parent.GetPhenotype().GetMerit();
+  
+  if(m_world->GetConfig().ENERGY_ENABLED.Get() == 1) {
+    // energy model config variables
+    double energy_given_at_birth = m_world->GetConfig().ENERGY_GIVEN_AT_BIRTH.Get();
+    double frac_parent_energy_given_at_birth = m_world->GetConfig().FRAC_PARENT_ENERGY_GIVEN_AT_BIRTH.Get();
+    double frac_energy_decay_at_birth = m_world->GetConfig().FRAC_ENERGY_DECAY_AT_BIRTH.Get();
+    int inst_2_exc = m_world->GetConfig().NUM_INST_EXC_BEFORE_0_ENERGY.Get();
+    double energy_cap = (double) m_world->GetConfig().ENERGY_CAP.Get();
+  
+    // apply energy if APPLY_ENERGY_METHOD is set to "on divide" (0)
+    if(m_world->GetConfig().APPLY_ENERGY_METHOD.Get() == 0) {
+      parent.GetPhenotype().RefreshEnergy();
+      parent.GetPhenotype().ApplyToEnergyStore();
+    }
+    
+    // decay of energy in parent
+    parent.GetPhenotype().ReduceEnergy(parent.GetPhenotype().GetStoredEnergy() * frac_energy_decay_at_birth);
 
+    // calculate energy to be given to child
+    double child_energy = min(parent.GetPhenotype().GetStoredEnergy() * frac_parent_energy_given_at_birth + energy_given_at_birth, energy_cap);
+        
+    // adjust energy in parent
+    parent.GetPhenotype().ReduceEnergy(child_energy - energy_given_at_birth);
+
+    // set child energy & merit
+    child_array[0]->GetPhenotype().SetEnergy(child_energy);
+    merit_array[0] = 100 * child_energy / (inst_2_exc);
+    
+
+    cMerit parentMerit = cMerit(min(100 * (parent.GetPhenotype().GetStoredEnergy() + energy_given_at_birth)/(inst_2_exc), energy_cap));
+    parent.GetPhenotype().SetMerit(parentMerit);
+
+    if(m_world->GetConfig().ENERGY_VERBOSE.Get()) {
+      cerr<<"child merit: "<<merit_array[0]<<endl<<"child energy: "<< child_energy <<endl
+          <<"parent merit: "<<parent.GetPhenotype().GetMerit()<<endl<<"parent energy: "<< parent.GetPhenotype().GetStoredEnergy() <<endl;
+    }
+  } else {
+    merit_array[0] = parent.GetPhenotype().GetMerit();
+  }
+  
+
   // Setup the genotype for the child
   cGenotype * child_genotype = parent.GetGenotype();
   

Modified: development/source/main/cEnvironment.cc
===================================================================
--- development/source/main/cEnvironment.cc	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/main/cEnvironment.cc	2007-06-04 16:32:44 UTC (rev 1637)
@@ -155,6 +155,7 @@
       else if (var_value=="mult") new_process->SetType(nReaction::PROCTYPE_MULT);
       else if (var_value=="pow") new_process->SetType(nReaction::PROCTYPE_POW);
       else if (var_value=="lin") new_process->SetType(nReaction::PROCTYPE_LIN);
+      else if (var_value=="energy") new_process->SetType(nReaction::PROCTYPE_ENERGY);
       else {
         cerr << "Unknown reaction process type '" << var_value
         << "' found in '" << reaction->GetName() << "'." << endl;
@@ -961,6 +962,10 @@
       case nReaction::PROCTYPE_LIN:
         result.AddBonus( bonus * task_count, reaction_id);
         break;
+      case nReaction::PROCTYPE_ENERGY:
+        result.AddEnergy(bonus);
+        break;
+        
       default:
         assert(false);  // Should not get here!
         break;

Modified: development/source/main/cOrganism.cc
===================================================================
--- development/source/main/cOrganism.cc	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/main/cOrganism.cc	2007-06-04 16:32:44 UTC (rev 1637)
@@ -37,6 +37,7 @@
 #include "cInjectGenotype.h"
 #include "cInstSet.h"
 #include "cOrgSinkMessage.h"
+#include "cPopulation.h"
 #include "cStringUtil.h"
 #include "cTaskContext.h"
 #include "cTools.h"
@@ -224,7 +225,16 @@
   
   cTaskContext taskctx(m_interface, input_buffer, output_buffer, other_input_list, 
                        other_output_list, net_valid, 0, on_divide, received_messages_point);
-  m_phenotype.TestOutput(ctx, taskctx, resource_count, res_change, insts_triggered);
+  bool task_completed = m_phenotype.TestOutput(ctx, taskctx, resource_count, res_change, insts_triggered);
+  
+  if(m_world->GetConfig().ENERGY_ENABLED.Get() && m_world->GetConfig().APPLY_ENERGY_METHOD.Get() == 1 && task_completed) {
+    m_phenotype.RefreshEnergy();
+    double newMerit = m_phenotype.ApplyToEnergyStore();
+    if(newMerit != -1) {
+      m_interface->UpdateMerit(newMerit);
+    }
+  }
+
   m_interface->UpdateResources(res_change);
   
   for (int i = 0; i < insts_triggered.GetSize(); i++) {

Modified: development/source/main/cOrganism.h
===================================================================
--- development/source/main/cOrganism.h	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/main/cOrganism.h	2007-06-04 16:32:44 UTC (rev 1637)
@@ -115,6 +115,7 @@
 
   int m_max_executed;      // Max number of instruction executed before death.  
   bool m_is_running;       // Does this organism have the CPU?
+  bool m_is_sleeping;      // Is this organisms sleeping?
   
   class cNetSupport
   {
@@ -172,6 +173,9 @@
 
   void SetRunning(bool in_running) { m_is_running = in_running; }
   bool IsRunning() { return m_is_running; }
+
+  void SetSleeping(bool in_sleeping) { m_is_sleeping = in_sleeping; }
+  bool IsSleeping() { return m_is_sleeping; }
   
   
   // --------  cOrgInterface Methods  --------

Modified: development/source/main/cPhenotype.cc
===================================================================
--- development/source/main/cPhenotype.cc	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/main/cPhenotype.cc	2007-06-04 16:32:44 UTC (rev 1637)
@@ -111,6 +111,8 @@
 {
   // Copy divide values from parent, which should already be setup.
   merit           = parent_phenotype.merit;
+  energy_store    = min(energy_store, (double) m_world->GetConfig().ENERGY_CAP.Get());
+  energy_tobe_applied = 0.0;
   genome_length   = _genome.GetSize();
   copied_size     = parent_phenotype.child_copied_size;
   executed_size   = parent_phenotype.executed_size;
@@ -247,6 +249,8 @@
   merit           = genome_length;
   copied_size     = genome_length;
   executed_size   = genome_length;
+  energy_store    = min(m_world->GetConfig().ENERGY_GIVEN_ON_INJECT.Get(), m_world->GetConfig().ENERGY_CAP.Get());
+  energy_tobe_applied = 0.0;
   gestation_time  = 0;
   gestation_start = 0;
   fitness         = 0;
@@ -375,6 +379,9 @@
     merit = cur_merit_base * cur_bonus;
   }
   
+  // update energy store
+  energy_store += cur_energy_bonus;
+  
   genome_length   = _genome.GetSize();
   (void) copied_size;          // Unchanged
   (void) executed_size;        // Unchanged
@@ -385,6 +392,7 @@
   // Lock in cur values as last values.
   last_merit_base           = cur_merit_base;
   last_bonus                = cur_bonus;
+//TODO?  last_energy         = cur_energy_bonus;
   last_num_errors           = cur_num_errors;
   last_num_donates          = cur_num_donates;
   last_task_count           = cur_task_count;
@@ -397,6 +405,7 @@
 
   // Reset cur values.
   cur_bonus       = m_world->GetConfig().DEFAULT_BONUS.Get();
+  cur_energy_bonus = 0.0;
   cur_num_errors  = 0;
   cur_num_donates  = 0;
   cur_task_count.SetAll(0);
@@ -797,7 +806,10 @@
   // Update the merit bonus
   cur_bonus *= result.GetMultBonus();
   cur_bonus += result.GetAddBonus();
-
+  
+  // Update the energy bonus
+  cur_energy_bonus += result.GetAddEnergy();
+  
   // Denote consumed resources...
   for (int i = 0; i < res_in.GetSize(); i++) {
     res_change[i] = result.GetProduced(i) - result.GetConsumed(i);
@@ -1148,6 +1160,29 @@
   }
 }
 
+/**
+Credit organism with energy reward, but only update energy store if APPLY_ENERGY_METHOD = "no task completion" (1)
+ */
+void cPhenotype::RefreshEnergy() {
+  if(cur_energy_bonus > 0) {
+    if(m_world->GetConfig().APPLY_ENERGY_METHOD.Get() == 0 || m_world->GetConfig().APPLY_ENERGY_METHOD.Get() == 2) {
+      energy_tobe_applied += cur_energy_bonus;
+    } else if(m_world->GetConfig().APPLY_ENERGY_METHOD.Get() == 1) {
+      energy_store += cur_energy_bonus;
+    } else {
+      cerr<< "Unknown APPLY_ENERGY_METHOD value " << m_world->GetConfig().APPLY_ENERGY_METHOD.Get();
+      exit(-1);
+    }
+    cur_energy_bonus = 0;
+  }
+}
+
+double cPhenotype::ApplyToEnergyStore() {
+  energy_store += energy_tobe_applied;
+  energy_tobe_applied = 0.0;
+  return min(100 * energy_store / (m_world->GetConfig().NUM_INST_EXC_BEFORE_0_ENERGY.Get()), (double) m_world->GetConfig().ENERGY_CAP.Get());
+}
+
 void cPhenotype::DecayAllPromoterRegulation()
 {
   for ( int i=0; i<cur_promoter_weights.GetSize(); i++)
@@ -1175,4 +1210,3 @@
   
   cur_promoter_weights[i] = base_promoter_weights[i] * exp((1+promoter_activation[i])*log(2.0)) / exp((1+promoter_repression[i])*log(2.0));
 }
-

Modified: development/source/main/cPhenotype.h
===================================================================
--- development/source/main/cPhenotype.h	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/main/cPhenotype.h	2007-06-04 16:32:44 UTC (rev 1637)
@@ -46,6 +46,9 @@
 #ifndef tHashTable_h
 #include "tHashTable.h"
 #endif
+#ifndef cWorld_h
+#include "cWorld.h"
+#endif
 
 
 /*************************************************************************
@@ -80,7 +83,7 @@
 template <class T> class tList;
 class cTaskContext;
 class cTaskState;
-class cWorld;
+//class cWorld;
 
 class cPhenotype
 {
@@ -90,6 +93,8 @@
 
   // 1. These are values calculated at the last divide (of self or offspring)
   cMerit merit;             // Relative speed of CPU
+  double energy_store;      // Amount of energy.  Determines relative speed of CPU when turned on.
+  double energy_tobe_applied; //Energy that has not yet been added to energy store.
   int genome_length;        // Number of instructions in genome.
   int bonus_instruction_count; // Number of times MERIT_BONUS_INT is in genome.
   int copied_size;          // Instructions copied into genome.
@@ -102,6 +107,7 @@
 
   // 2. These are "in progress" variables, updated as the organism operates
   double cur_bonus;                           // Current Bonus
+  double cur_energy_bonus;                    // Current energy bonus
   int cur_num_errors;                         // Total instructions executed illeagally.
   int cur_num_donates;                        // Number of donations so far
   tArray<int> cur_task_count;                 // Total times each task was performed
@@ -120,12 +126,14 @@
   tArray<double> promoter_repression;         // Amount of negative regulation in play at each site; @JEB 
   bool promoter_last_inst_terminated;         // Did terminatin occur when executing the last instruction
   
+
   tHashTable<void*, cTaskState*> m_task_states;
 
   
   // 3. These mark the status of "in progess" variables at the last divide.
   double last_merit_base;         // Either constant or based on genome length.
   double last_bonus;
+  double last_energy_bonus;
   int last_num_errors;
   int last_num_donates;
   tArray<int> last_task_count;
@@ -273,6 +281,9 @@
   int    GetCurBonusInstCount() const { assert(bonus_instruction_count >= 0); return bonus_instruction_count; }
 
   double GetCurMeritBase() const { assert(initialized == true); return CalcSizeMerit(); }
+  double GetStoredEnergy() const { assert(initialized == true); return energy_store; }
+  double GetEnergyBonus() const { assert(initialized == true); return cur_energy_bonus; }
+  
   bool GetToDie() const { assert(initialized == true); return to_die; }
   bool GetToDelete() const { assert(initialized == true); return to_delete; }
   int GetCurNumErrors() const { assert(initialized == true); return cur_num_errors; }
@@ -367,6 +378,8 @@
 
   ////////////////////  Accessors -- Modifying  ///////////////////
   void SetMerit(const cMerit& in_merit) { merit = in_merit; }
+  void ReduceEnergy(const double cost) { energy_store -= min(cost, (double) m_world->GetConfig().ENERGY_CAP.Get()); }
+  void SetEnergy(const double value) { energy_store = value; } //min(value, (double) m_world->GetConfig().ENERGY_CAP.Get()); }
   void SetGestationTime(int in_time) { gestation_time = in_time; }
   void SetTimeUsed(int in_time) { time_used = in_time; }
   void SetFault(const cString& in_fault) { fault_desc = in_fault; }
@@ -434,6 +447,9 @@
   int& CrossNum()     { assert(initialized == true); return cross_num; }
   bool& ChildFertile() { assert(initialized == true); return child_fertile; }
   bool& IsMultiThread() { assert(initialized == true); return is_multi_thread; }
+  
+  void RefreshEnergy();
+  double ApplyToEnergyStore();
 };
 
 

Modified: development/source/main/cPopulation.cc
===================================================================
--- development/source/main/cPopulation.cc	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/main/cPopulation.cc	2007-06-04 16:32:44 UTC (rev 1637)
@@ -59,7 +59,6 @@
 #include <vector>
 #include <algorithm>
 #include <set>
-
 #include <cfloat>
 #include <cmath>
 #include <climits>
@@ -75,6 +74,7 @@
 , environment(world->GetEnvironment())
 , num_organisms(0)
 , sync_events(false)
+, numAsleep(0)
 {
   // Avida specific information.
   world_x = world->GetConfig().WORLD_X.Get();
@@ -84,6 +84,12 @@
   const int geometry = world->GetConfig().WORLD_GEOMETRY.Get();
 	const int birth_method = m_world->GetConfig().BIRTH_METHOD.Get();
   
+  if(m_world->GetConfig().ENERGY_CAP.Get() == -1)
+    m_world->GetConfig().ENERGY_CAP.Set(INT_MAX);
+  
+  if(m_world->GetConfig().LOG_SLEEP_TIMES.Get() == 1)  {
+    sleep_log = new tVector<pair<int,int> >[world_x*world_y];
+  }
   // Print out world details
   if (world->GetVerbosity() > VERBOSE_NORMAL) {
     cout << "Building world " << world_x << "x" << world_y << " = " << num_cells << " organisms." << endl;
@@ -234,6 +240,11 @@
   tArray<cOrganism*> child_array;
   tArray<cMerit> merit_array;
   
+  //for energy model
+/*  double init_energy_given = m_world->GetConfig().ENERGY_GIVEN_AT_BIRTH.Get();
+  int inst_2_exc = m_world->GetConfig().NUM_INST_EXC_BEFORE_0_ENERGY.Get();
+*/
+  
   // Update the parent's phenotype.
   // This needs to be done before the parent goes into the birth chamber
   // or the merit doesn't get passed onto the child correctly
@@ -274,7 +285,6 @@
     // Update the phenotypes of each child....
     const cGenome & child_genome = child_array[i]->GetGenome();
     child_array[i]->GetPhenotype().SetupOffspring(parent_phenotype,child_genome);
-    
     child_array[i]->GetPhenotype().SetMerit(merit_array[i]);
     
     // Do lineage tracking for the new organisms.
@@ -284,8 +294,7 @@
 		//By default, store the parent cclade, this may get modified in ActivateOrgansim (@MRR)
 		child_array[i]->SetCCladeLabel(parent_organism.GetCCladeLabel());
   }
-  
-  
+    
   // If we're not about to kill the parent, do some extra work on it.
   if (parent_alive == true) {
     schedule->Adjust(parent_cell.GetID(), parent_phenotype.GetMerit());
@@ -459,6 +468,22 @@
   cGenotype* genotype = organism->GetGenotype();
   m_world->GetStats().RecordDeath();
   
+  int cellID = in_cell.GetID();
+
+  if(GetCell(cellID).GetOrganism()->IsSleeping()) {
+    GetCell(cellID).GetOrganism()->SetSleeping(false);
+    decNumAsleep();
+  }
+  if(m_world->GetConfig().LOG_SLEEP_TIMES.Get() == 1) {
+    if(sleep_log[cellID].Size() > 0) {
+      pair<int,int> p = sleep_log[cellID][sleep_log[cellID].Size()-1];
+      if(p.second == -1) {
+        AddEndSleep(cellID,m_world->GetStats().GetUpdate());
+      }
+    }
+  }
+  
+  
   tList<tListNode<cSaleItem> >* sold_items = organism->GetSoldItems();
   if (sold_items)
   {
@@ -2200,7 +2225,7 @@
   InjectGenome(cell_id, genome, lineage_label);
   cPhenotype& phenotype = GetCell(cell_id).GetOrganism()->GetPhenotype();
   phenotype.SetNeutralMetric(neutral);
-  
+    
   if (merit > 0) phenotype.SetMerit(cMerit(merit));
   schedule->Adjust(cell_id, phenotype.GetMerit());
   
@@ -2397,9 +2422,18 @@
   
   // Setup the phenotype...
   cPhenotype & phenotype = new_organism->GetPhenotype();
-  phenotype.SetupInject(new_genotype->GetGenome());
+  phenotype.SetupInject(new_genotype->GetGenome());  //TODO  sets merit to lenght of genotype
+  
+  if(m_world->GetConfig().ENERGY_ENABLED.Get()) {
+    double initial_energy = min(m_world->GetConfig().ENERGY_GIVEN_ON_INJECT.Get(), m_world->GetConfig().ENERGY_CAP.Get());
+    phenotype.SetEnergy(initial_energy);
+  }
+  // BB - Don't need to fix metabolic rate here, only on birth
+
   phenotype.SetMerit( cMerit(new_genotype->GetTestMerit(ctx)) );
   
+  cerr<<"initial energy: " << phenotype.GetStoredEnergy() <<endl<<"initial Merit: "<<phenotype.GetMerit().GetDouble()<<endl;
+  
   // @CAO are these really needed?
   phenotype.SetLinesCopied( new_genotype->GetTestCopiedSize(ctx) );
   phenotype.SetLinesExecuted( new_genotype->GetTestExecutedSize(ctx) );
@@ -2590,7 +2624,7 @@
   if (new_merit <= old_merit) {
 	  phenotype.SetIsDonorCur(); }  
   else  { phenotype.SetIsReceiver(); } 
-  
+  std::cerr<<"[cPopulation::UpdateMerit] phenotype.GetMerit() = "<<phenotype.GetMerit()<< " new_merit = " << new_merit << std::endl; 
   schedule->Adjust(cell_id, phenotype.GetMerit());
   
   return true;
@@ -2602,3 +2636,13 @@
 cChangeList *cPopulation::GetChangeList(){
   return schedule->GetChangeList();
 }
+
+void cPopulation::AddBeginSleep(int cellID, int start_time) {
+  sleep_log[cellID].Add(make_pair(start_time,-1));
+}
+  
+void cPopulation::AddEndSleep(int cellID, int end_time) {
+  pair<int,int> p = sleep_log[cellID][sleep_log[cellID].Size()-1];
+  sleep_log[cellID].RemoveAt(sleep_log[cellID].Size()-1);
+  sleep_log[cellID].Add(make_pair(p.first, end_time));
+}

Modified: development/source/main/cPopulation.h
===================================================================
--- development/source/main/cPopulation.h	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/main/cPopulation.h	2007-06-04 16:32:44 UTC (rev 1637)
@@ -55,6 +55,9 @@
 #ifndef tList_h
 #include "tList.h"
 #endif
+#ifndef tVector_h
+#include "tVector.h"
+#endif
 
 #if USE_tMemTrack
 # ifndef tMemTrack_h
@@ -62,6 +65,7 @@
 # endif
 #endif
 
+#include "cInstSet.h"
 
 class cAvidaContext;
 class cCodeLabel;
@@ -90,6 +94,9 @@
   cBirthChamber birth_chamber;         // Global birth chamber.
   tArray<tList<cSaleItem> > market;   // list of lists of items for sale, each list goes with 1 label
 
+  tVector<pair<int,int> > *sleep_log;
+  int numAsleep;
+  
   // Data Tracking...
   tList<cPopulationCell> reaper_queue; // Death order in some mass-action runs
 
@@ -221,6 +228,15 @@
 
   void SetChangeList(cChangeList* change_list);
   cChangeList* GetChangeList();
+  
+  void AddBeginSleep(int cellID, int start_time);
+  void AddEndSleep(int cellID, int end_time);
+ 
+  tVector<pair<int,int> > getCellSleepLog(int i) { return sleep_log[i]; }
+  
+  int getNumAsleep() { return numAsleep; }
+  void incNumAsleep() { numAsleep++; }
+  void decNumAsleep() { numAsleep--; }
 };
 
 

Modified: development/source/main/cReactionResult.cc
===================================================================
--- development/source/main/cReactionResult.cc	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/main/cReactionResult.cc	2007-06-04 16:32:44 UTC (rev 1637)
@@ -37,6 +37,7 @@
   , tasks_value(num_tasks)
   , reactions_triggered(num_reactions)
   , reaction_add_bonus(num_reactions)
+  , energy_add(0.0)
   , bonus_add(0.0)
   , bonus_mult(1.0)
   , insts_triggered(0)
@@ -106,6 +107,11 @@
   reactions_triggered[id] = true;
 }
 
+void cReactionResult::AddEnergy(double value)
+{
+  ActivateReaction();
+  energy_add += value;
+}
 
 void cReactionResult::AddBonus(double value, int id)
 {

Modified: development/source/main/cReactionResult.h
===================================================================
--- development/source/main/cReactionResult.h	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/main/cReactionResult.h	2007-06-04 16:32:44 UTC (rev 1637)
@@ -40,6 +40,7 @@
   tArray<double> tasks_value;
   tArray<bool> reactions_triggered;
   tArray<double> reaction_add_bonus; 
+  double energy_add;
   double bonus_add;
   double bonus_mult;
   tArray<int> insts_triggered;
@@ -65,6 +66,7 @@
   void MarkTask(int id, const double quality=1, const double value=0);
 
   void MarkReaction(int id);
+  void AddEnergy(double value);
   void AddBonus(double value, int id);
   void MultBonus(double value);
   
@@ -78,6 +80,7 @@
   bool TaskDone(int id);
   double TaskQuality(int id);
   double TaskValue(int id);
+  double GetAddEnergy() { return energy_add; }
   double GetAddBonus() { return bonus_add; }
   double GetReactionAddBonus(const int i) { return reaction_add_bonus[i]; }
   double GetMultBonus() { return bonus_mult; }

Modified: development/source/main/nReaction.h
===================================================================
--- development/source/main/nReaction.h	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/main/nReaction.h	2007-06-04 16:32:44 UTC (rev 1637)
@@ -30,7 +30,8 @@
     PROCTYPE_ADD = 0,
     PROCTYPE_MULT,
     PROCTYPE_POW,
-    PROCTYPE_LIN
+    PROCTYPE_LIN,
+    PROCTYPE_ENERGY
   };
 }
 

Modified: development/source/targets/avida-viewer/cZoomScreen.cc
===================================================================
--- development/source/targets/avida-viewer/cZoomScreen.cc	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/targets/avida-viewer/cZoomScreen.cc	2007-06-04 16:32:44 UTC (rev 1637)
@@ -99,11 +99,13 @@
   
   Print(5, 0, "Fitness...:");
   Print(6, 0, "Gestation.:");
-  Print(7, 0, "CPU Speed.:");
-  Print(8, 0, "Cur Merit.:");
-  Print(9, 0, "GenomeSize:");
-  Print(10, 0, "Mem Size..:");
-  Print(11, 0, "Faults....:");
+  Print(7, 0, "Cur Energy:");
+  Print(8, 0, "Str Energy:");
+  Print(9, 0, "CPU Speed.:");
+  Print(10, 0, "Cur Merit.:");
+  Print(11, 0, "GenomeSize:");
+  Print(12, 0, "Mem Size..:");
+  Print(13, 0, "Faults....:");
   
   Print(1,  27, "Location..:");
   
@@ -237,7 +239,7 @@
   Print(13, 52, "Location.....:");
   Print(14, 52, "Genotype ID..:");
   Print(15, 52, "Genotype Name:");
-  
+  Print(16, 52, "Cur Energy...:");  
   Print(17, 52, "Faults.......:");
   Print(18, 52, "Offspring....:");
   Print(19, 52, "Thread.......:");
@@ -426,12 +428,14 @@
   
   PrintDouble(5, 14, phenotype.GetFitness());
   Print(6, 15, "%6d ", phenotype.GetGestationTime());
-  PrintDouble(7, 14, phenotype.GetMerit().GetDouble());
-  PrintDouble(8, 14, cur_merit.GetDouble());
-  Print(9, 15, "%6d ", genotype ? genotype->GetLength() : 0);
-  Print(10, 15, "%6d ", hardware.GetMemory().GetSize());
+  PrintDouble(7, 14, phenotype.GetStoredEnergy());
+  PrintDouble(8, 14, phenotype.GetEnergyBonus());
+  PrintDouble(9, 14, phenotype.GetMerit().GetDouble());
+  PrintDouble(10, 14, cur_merit.GetDouble());
+  Print(11, 15, "%6d ", genotype ? genotype->GetLength() : 0);
+  Print(12, 15, "%6d ", hardware.GetMemory().GetSize());
   
-  Print(11, 15, "%6d ", phenotype.GetCurNumErrors());
+  Print(13, 15, "%6d ", phenotype.GetCurNumErrors());
   
   Print(4, 39, "%9d ", phenotype.GetGeneration());
   Print(5, 39, "%9d ", phenotype.GetAge());
@@ -601,12 +605,15 @@
   
   Print(14, 69, "%10d", info.GetActiveGenotypeID());
   Print(15, 69, "%10s", static_cast<const char*>(info.GetActiveName()));
-  
+
   cPhenotype& phenotype = info.GetActiveCell()->GetOrganism()->GetPhenotype();
-  Print(17, 69, "%10d", phenotype.GetCurNumErrors());
-  Print(18, 69, "%10d", phenotype.GetNumDivides());
-  if (info.GetThreadLock() != -1) Print(19, 67, "LOCKED");
-  else Print(19, 67, "      ");
+  PrintDouble(16, 69, phenotype.GetStoredEnergy());
+  PrintDouble(17, 69, phenotype.GetEnergyBonus());
+
+  Print(18, 69, "%10d", phenotype.GetCurNumErrors());
+  Print(19, 69, "%10d", phenotype.GetNumDivides());
+  if (info.GetThreadLock() != -1) Print(20, 67, "LOCKED");
+  else Print(20, 67, "      ");
   
   if(info.GetConfig().HARDWARE_TYPE.Get() == HARDWARE_TYPE_CPU_ORIGINAL)
     UpdateCPU_Original(hardware);

Modified: development/source/tools/cWeightedIndex.cc
===================================================================
--- development/source/tools/cWeightedIndex.cc	2007-06-04 14:07:57 UTC (rev 1636)
+++ development/source/tools/cWeightedIndex.cc	2007-06-04 16:32:44 UTC (rev 1637)
@@ -46,6 +46,8 @@
 void cWeightedIndex::AdjustSubtree(int id, double weight_change)
 {
   subtree_weight[id] += weight_change;
+  if(subtree_weight[id] < 0.0001)  //bb: added to catch round off error
+    subtree_weight[id] = 0.0;
   if (id != 0) {
     AdjustSubtree(GetParent(id), weight_change);
   }




More information about the Avida-cvs mailing list