[Avida-SVN] r1643 - in branches/collect: Avida.xcodeproj source/actions source/classification source/cpu source/drivers source/main source/script source/targets/avida-s source/targets/avida-viewer source/tools tests/demes_germline

blwalker at myxo.css.msu.edu blwalker at myxo.css.msu.edu
Tue Jun 5 18:44:04 PDT 2007


Author: blwalker
Date: 2007-06-05 21:44:03 -0400 (Tue, 05 Jun 2007)
New Revision: 1643

Removed:
   branches/collect/tests/demes_germline/expected/
Modified:
   branches/collect/Avida.xcodeproj/project.pbxproj
   branches/collect/source/actions/EnvironmentActions.cc
   branches/collect/source/actions/PrintActions.cc
   branches/collect/source/classification/cGenotype.h
   branches/collect/source/classification/cInjectGenotype.cc
   branches/collect/source/cpu/cHardwareCPU.cc
   branches/collect/source/cpu/cHardwareCPU.h
   branches/collect/source/cpu/cHardwareGX.cc
   branches/collect/source/cpu/cHardwareManager.cc
   branches/collect/source/cpu/cInstSet.cc
   branches/collect/source/cpu/cInstSet.h
   branches/collect/source/drivers/cDefaultRunDriver.cc
   branches/collect/source/main/cAvidaConfig.h
   branches/collect/source/main/cBirthChamber.cc
   branches/collect/source/main/cEnvironment.cc
   branches/collect/source/main/cOrganism.cc
   branches/collect/source/main/cOrganism.h
   branches/collect/source/main/cPhenotype.cc
   branches/collect/source/main/cPhenotype.h
   branches/collect/source/main/cPopulation.cc
   branches/collect/source/main/cPopulation.h
   branches/collect/source/main/cReactionResult.cc
   branches/collect/source/main/cReactionResult.h
   branches/collect/source/main/cStats.cc
   branches/collect/source/main/nReaction.h
   branches/collect/source/script/cASLibrary.h
   branches/collect/source/script/cASSymbol.h
   branches/collect/source/script/cParser.cc
   branches/collect/source/script/cParser.h
   branches/collect/source/script/cScriptObject.h
   branches/collect/source/script/cSymbolTable.h
   branches/collect/source/targets/avida-s/main.cc
   branches/collect/source/targets/avida-viewer/cZoomScreen.cc
   branches/collect/source/tools/cDataFile.cc
   branches/collect/source/tools/cDataFile.h
   branches/collect/source/tools/cDoubleSum.h
   branches/collect/source/tools/cFile.h
   branches/collect/source/tools/cWeightedIndex.cc
Log:

Porting r1624:1642 from development into collect branch.


Modified: branches/collect/Avida.xcodeproj/project.pbxproj
===================================================================
--- branches/collect/Avida.xcodeproj/project.pbxproj	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/Avida.xcodeproj/project.pbxproj	2007-06-06 01:44:03 UTC (rev 1643)
@@ -198,61 +198,78 @@
 		};
 /* End PBXBuildRule section */
 
+/* Begin PBXBuildStyle section */
+		B56E89620C144AFE00B99261 /* Development */ = {
+			isa = PBXBuildStyle;
+			buildSettings = {
+				COPY_PHASE_STRIP = NO;
+			};
+			name = Development;
+		};
+		B56E89630C144AFE00B99261 /* Deployment */ = {
+			isa = PBXBuildStyle;
+			buildSettings = {
+				COPY_PHASE_STRIP = YES;
+			};
+			name = Deployment;
+		};
+/* End PBXBuildStyle section */
+
 /* Begin PBXContainerItemProxy section */
 		7023ECA60C0A436000362B9C /* PBXContainerItemProxy */ = {
 			isa = PBXContainerItemProxy;
 			containerPortal = DCC30C4D0762532C008F7A48 /* Project object */;
 			proxyType = 1;
-			remoteGlobalIDString = 7023EC320C0A426900362B9C /* avida-core */;
+			remoteGlobalIDString = 7023EC320C0A426900362B9C;
 			remoteInfo = "avida-core";
 		};
 		7023ECCF0C0A445800362B9C /* PBXContainerItemProxy */ = {
 			isa = PBXContainerItemProxy;
 			containerPortal = DCC30C4D0762532C008F7A48 /* Project object */;
 			proxyType = 1;
-			remoteGlobalIDString = 7023EC320C0A426900362B9C /* avida-core */;
+			remoteGlobalIDString = 7023EC320C0A426900362B9C;
 			remoteInfo = "avida-core";
 		};
 		7023ECD10C0A445B00362B9C /* PBXContainerItemProxy */ = {
 			isa = PBXContainerItemProxy;
 			containerPortal = DCC30C4D0762532C008F7A48 /* Project object */;
 			proxyType = 1;
-			remoteGlobalIDString = 70AA941809D486AE006A24C8 /* tcmalloc */;
+			remoteGlobalIDString = 70AA941809D486AE006A24C8;
 			remoteInfo = tcmalloc;
 		};
 		7023ECE00C0A44DE00362B9C /* PBXContainerItemProxy */ = {
 			isa = PBXContainerItemProxy;
 			containerPortal = DCC30C4D0762532C008F7A48 /* Project object */;
 			proxyType = 1;
-			remoteGlobalIDString = 70AA941809D486AE006A24C8 /* tcmalloc */;
+			remoteGlobalIDString = 70AA941809D486AE006A24C8;
 			remoteInfo = tcmalloc;
 		};
 		7023ECE20C0A44E000362B9C /* PBXContainerItemProxy */ = {
 			isa = PBXContainerItemProxy;
 			containerPortal = DCC30C4D0762532C008F7A48 /* Project object */;
 			proxyType = 1;
-			remoteGlobalIDString = 7023EC320C0A426900362B9C /* avida-core */;
+			remoteGlobalIDString = 7023EC320C0A426900362B9C;
 			remoteInfo = "avida-core";
 		};
 		7023ED530C0A590B00362B9C /* PBXContainerItemProxy */ = {
 			isa = PBXContainerItemProxy;
 			containerPortal = DCC30C4D0762532C008F7A48 /* Project object */;
 			proxyType = 1;
-			remoteGlobalIDString = DCC3164C07626CF3008F7A48 /* avida */;
+			remoteGlobalIDString = DCC3164C07626CF3008F7A48;
 			remoteInfo = avida;
 		};
 		7023ED550C0A590F00362B9C /* PBXContainerItemProxy */ = {
 			isa = PBXContainerItemProxy;
 			containerPortal = DCC30C4D0762532C008F7A48 /* Project object */;
 			proxyType = 1;
-			remoteGlobalIDString = 700E2AF3085DE50C00CF158A /* avida-viewer */;
+			remoteGlobalIDString = 700E2AF3085DE50C00CF158A;
 			remoteInfo = "avida-viewer";
 		};
 		7023ED570C0A591100362B9C /* PBXContainerItemProxy */ = {
 			isa = PBXContainerItemProxy;
 			containerPortal = DCC30C4D0762532C008F7A48 /* Project object */;
 			proxyType = 1;
-			remoteGlobalIDString = 70B6514B0BEA6FAD002472ED /* unit-tests */;
+			remoteGlobalIDString = 70B6514B0BEA6FAD002472ED;
 			remoteInfo = "unit-tests";
 		};
 		70DCF67509D4E10500924128 /* PBXContainerItemProxy */ = {
@@ -1673,6 +1690,12 @@
 		DCC30C4D0762532C008F7A48 /* Project object */ = {
 			isa = PBXProject;
 			buildConfigurationList = 702442D70859E0B00059BD9B /* Build configuration list for PBXProject "Avida" */;
+			buildSettings = {
+			};
+			buildStyles = (
+				B56E89620C144AFE00B99261 /* Development */,
+				B56E89630C144AFE00B99261 /* Deployment */,
+			);
 			hasScannedForEncodings = 0;
 			mainGroup = DCC30C490762532C008F7A48;
 			productRefGroup = DCC3164E07626CF3008F7A48 /* Products */;
@@ -2107,7 +2130,7 @@
 				GCC_STRICT_ALIASING = YES;
 				GCC_UNROLL_LOOPS = YES;
 				PER_ARCH_CFLAGS_i386 = "-DCOMPILE_ARCH=\\\"Intel\\\"";
-				PER_ARCH_CFLAGS_ppc = "-DCOMPILE_ARCH=\\\"G4-G5\\\" -mpowerpc-gpopt -falign-loops-max-skip=15 -falign-jumps-max-skip=15 -falign-loops=16 -falign-jumps=16 -falign-functions=16 -ftree-loop-linear -fsched-interblock -fgcse-sm";
+				PER_ARCH_CFLAGS_ppc = "-DCOMPILE_ARCH=\\\"G4-G5\\\" -falign-loops-max-skip=15 -falign-jumps-max-skip=15 -falign-loops=16 -falign-jumps=16 -falign-functions=16 -ftree-loop-linear -fsched-interblock -fgcse-sm";
 				SEPARATE_STRIP = YES;
 				WARNING_CFLAGS = (
 					"-Wextra",

Modified: branches/collect/source/actions/EnvironmentActions.cc
===================================================================
--- branches/collect/source/actions/EnvironmentActions.cc	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/actions/EnvironmentActions.cc	2007-06-06 01:44:03 UTC (rev 1643)
@@ -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: branches/collect/source/actions/PrintActions.cc
===================================================================
--- branches/collect/source/actions/PrintActions.cc	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/actions/PrintActions.cc	2007-06-06 01:44:03 UTC (rev 1643)
@@ -774,7 +774,7 @@
 
 
 /*
- @MRR May 2007 [UNTESTED]
+ @MRR May 2007 [BETA]
  This function prints out fitness data. The main point is that it
  calculates the average fitness from info from the testCPU + the actual
  merit of the organisms, and assigns zero fitness to those organisms
@@ -929,7 +929,7 @@
 			gens.Push(genotype);
 		}
 		
-		tArray<int> histogram = MakeHistogram(orgs, gens, m_hist_fmin, m_hist_fstep, m_hist_fstep, m_mode, m_world, ctx);
+		tArray<int> histogram = MakeHistogram(orgs, gens, m_hist_fmin, m_hist_fstep, m_hist_fmax, m_mode, m_world, ctx);
 		
 		
 		//Output histogram
@@ -946,7 +946,7 @@
 
 
 /*
- @MRR May 2007  [INCOMPLETE]
+ @MRR May 2007  [BETA]
  
  This function requires Avida be in run mode.
  
@@ -984,7 +984,7 @@
 	cActionPrintRelativeFitnessHistogram(cWorld* world, const cString& args) : cAction(world, args) 
 	{ 
 		cString largs(args);
-		m_filename   = (largs.GetSize()) ? largs.PopWord()           : "rel_fitness.dat";
+		m_filename   = (largs.GetSize()) ? largs.PopWord()           : "rel_fitness_hist.dat";
 		m_mode       = (largs.GetSize()) ? largs.PopWord().ToUpper() : "CURRENT";
 		m_hist_fmin  = (largs.GetSize()) ? largs.PopWord().AsDouble(): 0;
 		m_hist_fstep = (largs.GetSize()) ? largs.PopWord().AsDouble(): 0.1;
@@ -1035,7 +1035,7 @@
 			for (git = gens.begin(), oit = orgs.begin(); git != gens.end(); git++, oit++){
 				cCPUTestInfo test_info;
 				double fitness = 0.0;
-				double parent_fitness = (*git)->GetParentGenotype()->GetFitness();
+				double parent_fitness = ( (*git)->GetParentID() > 0) ? (*git)->GetParentGenotype()->GetFitness() : 1.0;
 				if (mode == "TEST_CPU" || mode == "ACTUAL"){
 					testcpu->TestGenome(ctx, test_info, (*git)->GetGenome());
 				}
@@ -1055,7 +1055,7 @@
 				
 				//Update the histogram
 				if (parent_fitness <= 0.0)
-					world->GetDriver().RaiseFatalException(1, "PrintRelativeFitness::MakeHistogram: Parent fitness is zero.");
+					world->GetDriver().RaiseFatalException(1, cString("PrintRelativeFitness::MakeHistogram: Parent fitness is zero.") + cStringUtil::Convert((*git)->GetParentID()) + cString(":") + cStringUtil::Convert( (*git)->GetParentGenotype()->GetMerit() ));
 				
 				double rfitness = fitness/parent_fitness;
 				int update_bin = (rfitness == 0) ? 0 :       
@@ -1081,13 +1081,41 @@
 		//Handle possible errors
 		if (ctx.GetAnalyzeMode())
 			m_world->GetDriver().RaiseFatalException(1, "PrintRelativeFitnessHistogram requires avida to be in run mode.");
+	
+		//Gather data objects
+		cPopulation& pop        = m_world->GetPopulation();
+		const int    update     = m_world->GetStats().GetUpdate();
+		const double generation = m_world->GetStats().SumGeneration().Average();
+		tArray<cOrganism*> orgs;
+		tArray<cGenotype*> gens;
+		
+		for (int i = 0; i < pop.GetSize(); i++)
+		{
+			if (pop.GetCell(i).IsOccupied() == false) continue;  //Skip unoccupied cells
+			cOrganism* organism = pop.GetCell(i).GetOrganism();
+			cGenotype* genotype = organism->GetGenotype();
+			orgs.Push(organism);
+			gens.Push(genotype);
+		}
+		
+		tArray<int> histogram = MakeHistogram(orgs, gens, m_hist_fmin, m_hist_fstep, m_hist_fmax, m_mode, m_world, ctx);
+		
+		
+		//Output histogram
+		cDataFile& hdf = m_world->GetDataFile(m_filename);
+		hdf.Write(update, "Update");
+		hdf.Write(generation, "Generation");
+		
+		for (int k = 0; k < histogram.GetSize(); k++)
+			hdf.Write(histogram[k], GetHistogramBinLabel(k, m_hist_fmin, m_hist_fstep, m_hist_fmax));
+		hdf.Endl();
 	}
 };
 
 
 
 /*
- @MRR May 2007 [UNTESTED]
+ @MRR May 2007 [BETA]
  This function requires CCLADE_TRACKING to be enabled and avida
  operating non-analyze mode.
  
@@ -1124,7 +1152,7 @@
 		cActionPrintCCladeFitnessHistogram(cWorld* world, const cString& args) : cAction(world, args)
 		{
 			cString largs(args);
-		  m_filename   = (largs.GetSize()) ? largs.PopWord()           : "cclade_fitness.dat";
+		  m_filename   = (largs.GetSize()) ? largs.PopWord()           : "cclade_fitness_hist.dat";
 			m_mode       = (largs.GetSize()) ? largs.PopWord().ToUpper() : "CURRENT";
 			m_hist_fmin  = (largs.GetSize()) ? largs.PopWord().AsDouble(): -3.0;
 			m_hist_fstep = (largs.GetSize()) ? largs.PopWord().AsDouble(): 0.5;
@@ -1181,9 +1209,8 @@
 			map< int, tArray<cOrganism*> >::iterator oit = org_map.begin();
 			map< int, tArray<cGenotype*> >::iterator git = gen_map.begin();
 			for(; oit != org_map.end(); oit++, git++){
-				tArray<int> hist = cActionPrintLogFitnessHistogram::MakeHistogram( (oit->second), (git->second),
-																																				m_hist_fmin, m_hist_fstep, m_hist_fmax,
-																																				m_mode, m_world, ctx );
+				tArray<int> hist = 
+					cActionPrintLogFitnessHistogram::MakeHistogram( (oit->second), (git->second),m_hist_fmin, m_hist_fstep, m_hist_fmax, m_mode, m_world, ctx );
 				if (first_run){  //Print header information if first time through
 					first_run = false;
 					fp << "# PrintCCladeFitnessHistogram" << endl << "# Bins: ";
@@ -1204,7 +1231,7 @@
 
  
 /*
- @MRR May 2007  [INCOMPLETE]
+ @MRR May 2007  [BETA]
  This function requires CCLADE_TRACKING to be enabled and Avida
  operating non-analyze mode.
  
@@ -1241,7 +1268,7 @@
 	cActionPrintCCladeRelativeFitnessHistogram(cWorld* world, const cString& args) : cAction(world, args) 
 	{
 		cString largs(args);
-		m_filename   = (largs.GetSize()) ? largs.PopWord()           : "cclade_rel_fitness.dat";
+		m_filename   = (largs.GetSize()) ? largs.PopWord()           : "cclade_rel_fitness_hist.dat";
 		m_mode       = (largs.GetSize()) ? largs.PopWord().ToUpper() : "CURRENT";
 		m_hist_fmin  = (largs.GetSize()) ? largs.PopWord().AsDouble(): 0;
 		m_hist_fstep = (largs.GetSize()) ? largs.PopWord().AsDouble(): 0.2;
@@ -1346,7 +1373,7 @@
 			m_filename = (largs.GetSize()) ? largs.PopWord() : "GenomicSiteEntropy.dat";
 		}
 
-		static const cString GetDescription() { return "Arguments: [filename = \"GenomicSiteEntropyData\"] [use_gap = false]";}
+		static const cString GetDescription() { return "Arguments: [filename = \"GenomicSiteEntropyData.datcd \"] [use_gap = false]";}
 		
 		void Process(cAvidaContext& ctx){
 			const int        update     = m_world->GetStats().GetUpdate();

Modified: branches/collect/source/classification/cGenotype.h
===================================================================
--- branches/collect/source/classification/cGenotype.h	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/classification/cGenotype.h	2007-06-06 01:44:03 UTC (rev 1643)
@@ -27,7 +27,6 @@
 #define cGenotype_h
 
 #include <fstream>
-
 #ifndef cDoubleSum_h
 #include "cDoubleSum.h"
 #endif

Modified: branches/collect/source/classification/cInjectGenotype.cc
===================================================================
--- branches/collect/source/classification/cInjectGenotype.cc	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/classification/cInjectGenotype.cc	2007-06-06 01:44:03 UTC (rev 1643)
@@ -38,6 +38,7 @@
   , is_active(true)
       , can_reproduce(false)
   , defer_adjust(0)
+  , id_num(in_id)
   , symbol(0)
   , birth_data(in_update_born)
   , num_injected(0)

Modified: branches/collect/source/cpu/cHardwareCPU.cc
===================================================================
--- branches/collect/source/cpu/cHardwareCPU.cc	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/cpu/cHardwareCPU.cc	2007-06-06 01:44:03 UTC (rev 1643)
@@ -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"
@@ -333,6 +335,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),
@@ -393,8 +404,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
 {
 }
@@ -420,8 +433,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));
@@ -429,6 +444,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 
   
@@ -571,6 +589,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
@@ -587,6 +634,7 @@
     }
   }
   
+  inst_energy_cost[cur_inst.GetOp()] = m_inst_set->GetEnergyCost(cur_inst); //reset instruction energy cost
 #endif
   return true;
 }
@@ -602,7 +650,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);
   
@@ -4117,6 +4165,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
@@ -4316,6 +4391,7 @@
   return true;
 }
 
+
 //// Placebo insts ////
 bool cHardwareCPU::Inst_Skip(cAvidaContext& ctx)
 {

Modified: branches/collect/source/cpu/cHardwareCPU.h
===================================================================
--- branches/collect/source/cpu/cHardwareCPU.h	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/cpu/cHardwareCPU.h	2007-06-06 01:44:03 UTC (rev 1643)
@@ -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
   
   
@@ -523,6 +525,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: branches/collect/source/cpu/cHardwareGX.cc
===================================================================
--- branches/collect/source/cpu/cHardwareGX.cc	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/cpu/cHardwareGX.cc	2007-06-06 01:44:03 UTC (rev 1643)
@@ -457,11 +457,16 @@
 
   // Kill creatures who have reached their max num of instructions executed.
   const int max_executed = organism->GetMaxExecuted();
-  if ((max_executed > 0 && phenotype.GetTimeUsed() >= max_executed)
+  if((max_executed > 0 && phenotype.GetTimeUsed() >= max_executed)
       || phenotype.GetToDie() == true) {
     organism->Die();
-  }  
+  }
   
+  // Kill organisms that have no active programids.
+  if(m_programids.size() == 0) {
+    organism->Die();
+  }
+  
   organism->SetRunning(false);
 }
 
@@ -3498,6 +3503,7 @@
   cHeadProgramid& write = GetHead(nHardware::HEAD_WRITE);
   cHeadProgramid& read = GetHead(nHardware::HEAD_READ);
   read.Adjust(); // Strange things can happen (like we're reading from a programid that was being written).
+  write.Adjust(); // Always adjust if the memory spaces themselves are accessed.
   
   // Don't copy if this programid's write or read head is on itself
   if(read.GetMemSpace() == m_current->GetID()) return false;

Modified: branches/collect/source/cpu/cHardwareManager.cc
===================================================================
--- branches/collect/source/cpu/cHardwareManager.cc	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/cpu/cHardwareManager.cc	2007-06-06 01:44:03 UTC (rev 1643)
@@ -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: branches/collect/source/cpu/cInstSet.cc
===================================================================
--- branches/collect/source/cpu/cInstSet.cc	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/cpu/cInstSet.cc	2007-06-06 01:44:03 UTC (rev 1643)
@@ -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: branches/collect/source/cpu/cInstSet.h
===================================================================
--- branches/collect/source/cpu/cInstSet.h	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/cpu/cInstSet.h	2007-06-06 01:44:03 UTC (rev 1643)
@@ -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: branches/collect/source/drivers/cDefaultRunDriver.cc
===================================================================
--- branches/collect/source/drivers/cDefaultRunDriver.cc	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/drivers/cDefaultRunDriver.cc	2007-06-06 01:44:03 UTC (rev 1643)
@@ -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: branches/collect/source/main/cAvidaConfig.h
===================================================================
--- branches/collect/source/main/cAvidaConfig.h	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/main/cAvidaConfig.h	2007-06-06 01:44:03 UTC (rev 1643)
@@ -248,7 +248,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)");
@@ -354,11 +354,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: branches/collect/source/main/cBirthChamber.cc
===================================================================
--- branches/collect/source/main/cBirthChamber.cc	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/main/cBirthChamber.cc	2007-06-06 01:44:03 UTC (rev 1643)
@@ -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: branches/collect/source/main/cEnvironment.cc
===================================================================
--- branches/collect/source/main/cEnvironment.cc	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/main/cEnvironment.cc	2007-06-06 01:44:03 UTC (rev 1643)
@@ -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;
@@ -978,6 +979,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: branches/collect/source/main/cOrganism.cc
===================================================================
--- branches/collect/source/main/cOrganism.cc	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/main/cOrganism.cc	2007-06-06 01:44:03 UTC (rev 1643)
@@ -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"
@@ -251,7 +252,15 @@
   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, m_rbins, res_change, insts_triggered);
+  bool task_completed = m_phenotype.TestOutput(ctx, taskctx, resource_count, m_rbins, 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);
   

Modified: branches/collect/source/main/cOrganism.h
===================================================================
--- branches/collect/source/main/cOrganism.h	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/main/cOrganism.h	2007-06-06 01:44:03 UTC (rev 1643)
@@ -117,6 +117,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
   {
@@ -180,6 +181,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: branches/collect/source/main/cPhenotype.cc
===================================================================
--- branches/collect/source/main/cPhenotype.cc	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/main/cPhenotype.cc	2007-06-06 01:44:03 UTC (rev 1643)
@@ -119,6 +119,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;
@@ -263,6 +265,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;
@@ -301,6 +305,7 @@
   last_rbins_avail.SetAll(0);
   last_reaction_count.SetAll(0);
   last_reaction_add_reward.SetAll(0);
+  last_inst_count.SetAll(0);
   last_sense_count.SetAll(0);
 
   // Setup other miscellaneous values...
@@ -398,6 +403,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
@@ -408,6 +416,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;
@@ -424,6 +433,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);
@@ -843,7 +853,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);
@@ -1258,6 +1271,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++)
@@ -1285,4 +1321,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: branches/collect/source/main/cPhenotype.h
===================================================================
--- branches/collect/source/main/cPhenotype.h	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/main/cPhenotype.h	2007-06-06 01:44:03 UTC (rev 1643)
@@ -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
@@ -124,12 +130,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;
@@ -281,6 +289,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; }
@@ -383,6 +394,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; }
@@ -457,6 +470,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: branches/collect/source/main/cPopulation.cc
===================================================================
--- branches/collect/source/main/cPopulation.cc	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/main/cPopulation.cc	2007-06-06 01:44:03 UTC (rev 1643)
@@ -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());
@@ -300,6 +309,7 @@
     }
   }
   
+  double old_fitness = parent_genotype->GetFitness();
   // Do any statistics on the parent that just gave birth...
   parent_genotype->AddGestationTime( parent_phenotype.GetGestationTime() );
   parent_genotype->AddFitness(       parent_phenotype.GetFitness()       );
@@ -307,6 +317,7 @@
   parent_genotype->AddCopiedSize(    parent_phenotype.GetCopiedSize()    );
   parent_genotype->AddExecutedSize(  parent_phenotype.GetExecutedSize()  );
   
+  
   // Place all of the offspring...
   for (int i = 0; i < child_array.GetSize(); i++) {
     ActivateOrganism(ctx, child_array[i], GetCell(target_cells[i]));
@@ -457,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)
   {
@@ -2211,7 +2238,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());
   
@@ -2408,9 +2435,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) );
@@ -2601,7 +2637,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;
@@ -2613,3 +2649,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: branches/collect/source/main/cPopulation.h
===================================================================
--- branches/collect/source/main/cPopulation.h	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/main/cPopulation.h	2007-06-06 01:44:03 UTC (rev 1643)
@@ -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: branches/collect/source/main/cReactionResult.cc
===================================================================
--- branches/collect/source/main/cReactionResult.cc	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/main/cReactionResult.cc	2007-06-06 01:44:03 UTC (rev 1643)
@@ -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)
@@ -108,6 +109,11 @@
   reactions_triggered[id] = true;
 }
 
+void cReactionResult::AddEnergy(double value)
+{
+  ActivateReaction();
+  energy_add += value;
+}
 
 void cReactionResult::AddBonus(double value, int id)
 {

Modified: branches/collect/source/main/cReactionResult.h
===================================================================
--- branches/collect/source/main/cReactionResult.h	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/main/cReactionResult.h	2007-06-06 01:44:03 UTC (rev 1643)
@@ -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;
@@ -66,6 +67,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);
   
@@ -79,6 +81,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: branches/collect/source/main/cStats.cc
===================================================================
--- branches/collect/source/main/cStats.cc	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/main/cStats.cc	2007-06-06 01:44:03 UTC (rev 1643)
@@ -150,10 +150,10 @@
   
 
 #if INSTRUCTION_COUNT
-  sum_exe_inst_array.Resize( m_world->GetNumInstructions() );
+  sum_exe_inst_array.Resize(m_world->GetNumInstructions());
   ZeroInst();
 #endif
-  inst_names.Resize( m_world->GetNumInstructions() );
+  inst_names.Resize(m_world->GetNumInstructions());
 
   reaction_count.Resize( m_world->GetNumReactions() );
   reaction_count.SetAll(0);
@@ -343,7 +343,7 @@
 #if INSTRUCTION_COUNT
 void cStats::ZeroInst()
 {
-  for( int i=0; i < sum_exe_inst_array.GetSize(); i++ ){
+  for (int i = 0; i < sum_exe_inst_array.GetSize(); i++) {
     sum_exe_inst_array[i].Clear();
   }
 }
@@ -948,10 +948,11 @@
   df.WriteComment("Avida instruction execution data");
   df.WriteTimeStamp();
 
+  df.Write(m_update, "Update");
+
 #if INSTRUCTION_COUNT
-  df.Write(m_update, "Update");
-  for( int i=0; i < sum_exe_inst_array.GetSize(); i++ ){
-    df.Write((int) sum_exe_inst_array[i].Sum(), inst_names[i]);
+  for (int i = 0; i < sum_exe_inst_array.GetSize(); i++) {
+    df.Write(sum_exe_inst_array[i].Sum(), inst_names[i]);
   }
 #else // INSTRUCTION_COUNT undefined
   m_world->GetDriver().RaiseException("Warning: Instruction Counts not compiled in");

Modified: branches/collect/source/main/nReaction.h
===================================================================
--- branches/collect/source/main/nReaction.h	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/main/nReaction.h	2007-06-06 01:44:03 UTC (rev 1643)
@@ -30,7 +30,8 @@
     PROCTYPE_ADD = 0,
     PROCTYPE_MULT,
     PROCTYPE_POW,
-    PROCTYPE_LIN
+    PROCTYPE_LIN,
+    PROCTYPE_ENERGY
   };
 }
 

Modified: branches/collect/source/script/cASLibrary.h
===================================================================
--- branches/collect/source/script/cASLibrary.h	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/script/cASLibrary.h	2007-06-06 01:44:03 UTC (rev 1643)
@@ -42,16 +42,4 @@
   cASLibrary() { ; }
 };
 
-
-#ifdef ENABLE_UNIT_TESTS
-namespace nASLibrary {
-  /**
-   * Run unit tests
-   *
-   * @param full Run full test suite; if false, just the fast tests.
-   **/
-  void UnitTests(bool full = false);
-}
 #endif
-
-#endif

Modified: branches/collect/source/script/cASSymbol.h
===================================================================
--- branches/collect/source/script/cASSymbol.h	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/script/cASSymbol.h	2007-06-06 01:44:03 UTC (rev 1643)
@@ -41,15 +41,4 @@
 };
 
 
-#ifdef ENABLE_UNIT_TESTS
-namespace nASSymbol {
-  /**
-   * Run unit tests
-   *
-   * @param full Run full test suite; if false, just the fast tests.
-   **/
-  void UnitTests(bool full = false);
-}
-#endif  
-
 #endif

Modified: branches/collect/source/script/cParser.cc
===================================================================
--- branches/collect/source/script/cParser.cc	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/script/cParser.cc	2007-06-06 01:44:03 UTC (rev 1643)
@@ -25,8 +25,13 @@
 #include "cParser.h"
 
 #include "AvidaScript.h"
+#include "cFile.h"
 
 /*
+ The following represents the grammar for AvidaScript in BNF, adjusted so that it is compatible with recursive descent
+ parsing (to be) implemented by cParser.
+ 
+ 
  script: statement_list
  
  statement_list: statement statement_list
@@ -138,11 +143,17 @@
  declare_function: REF CMD_FUNCTION type_any ID PREC_OPEN var_declare_list PREC_CLOSE ENDL
  define_function: CMD_FUNCTION type_any ID PREC_OPEN var_declare_list PREC_CLOSE ENDL statement_list CMD_ENDFUNCTION
  
+ 
+ @TODO - return
+ @TODO - array definitions
+ @TODO - suppress
+ @TODO - ARR_OPEN ARR_CLOSE as block open/close.  
+ @TODO - function variant with block rather than endfunction.
  */
 
-cScriptObject* cParser::Parse(std::istream* input)
+bool cParser::Parse(cFile& input)
 {
-  m_lexer = new cLexer(input);
+  m_lexer = new cLexer(input.GetFileStream());
   
   int tok = m_lexer->yylex();
   while (tok) {
@@ -152,5 +163,11 @@
   
   delete m_lexer;
   
-  return NULL;
+  return m_success;
 }
+
+
+void cParser::Accept(cASTVisitor& visitor)
+{
+  
+}

Modified: branches/collect/source/script/cParser.h
===================================================================
--- branches/collect/source/script/cParser.h	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/script/cParser.h	2007-06-06 01:44:03 UTC (rev 1643)
@@ -27,6 +27,9 @@
 
 #include <iostream>
 
+#ifndef ASTree_h
+#include "ASTree.h"
+#endif
 #ifndef cASLibrary_h
 #include "cASLibrary.h"
 #endif
@@ -40,32 +43,26 @@
 #include "cSymbolTable.h"
 #endif
 
+class cFile;
 
+
 class cParser
 {
 private:
   cASLibrary* m_library;
   cLexer* m_lexer;
-  cSymbolTable* m_symtbl;
+  cASTNode* m_tree;
   
+  bool m_success;
+  
   cParser();
   
 public:
-  cParser(cASLibrary* library) : m_library(library), m_symtbl(NULL) { ; }
+  cParser(cASLibrary* library) : m_library(library), m_success(true) { ; }
   
-  cScriptObject* Parse(std::istream* input);
+  bool Parse(cFile& input);
+  
+  void Accept(cASTVisitor& visitor);
 };
 
-
-#ifdef ENABLE_UNIT_TESTS
-namespace nParser {
-  /**
-   * Run unit tests
-   *
-   * @param full Run full test suite; if false, just the fast tests.
-   **/
-  void UnitTests(bool full = false);
-}
-#endif  
-
 #endif

Modified: branches/collect/source/script/cScriptObject.h
===================================================================
--- branches/collect/source/script/cScriptObject.h	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/script/cScriptObject.h	2007-06-06 01:44:03 UTC (rev 1643)
@@ -34,15 +34,4 @@
 };
 
 
-#ifdef ENABLE_UNIT_TESTS
-namespace nScriptObject {
-  /**
-   * Run unit tests
-   *
-   * @param full Run full test suite; if false, just the fast tests.
-   **/
-  void UnitTests(bool full = false);
-}
-#endif  
-
 #endif

Modified: branches/collect/source/script/cSymbolTable.h
===================================================================
--- branches/collect/source/script/cSymbolTable.h	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/script/cSymbolTable.h	2007-06-06 01:44:03 UTC (rev 1643)
@@ -43,15 +43,4 @@
 };
 
 
-#ifdef ENABLE_UNIT_TESTS
-namespace nSymbolTable {
-  /**
-   * Run unit tests
-   *
-   * @param full Run full test suite; if false, just the fast tests.
-   **/
-  void UnitTests(bool full = false);
-}
-#endif  
-
 #endif

Modified: branches/collect/source/targets/avida-s/main.cc
===================================================================
--- branches/collect/source/targets/avida-s/main.cc	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/targets/avida-s/main.cc	2007-06-06 01:44:03 UTC (rev 1643)
@@ -1,6 +1,6 @@
 /*
  *  main.cc
- *  avida_test_language
+ *  Avida
  *
  *  Created by David on 1/13/06.
  *  Copyright 1999-2007 Michigan State University. All rights reserved.
@@ -23,6 +23,7 @@
  */
 
 #include "cASLibrary.h"
+#include "cFile.h"
 #include "cParser.h"
 
 #include <iostream>
@@ -32,7 +33,9 @@
 {
   cASLibrary* lib = new cASLibrary;
   cParser* parser = new cParser(lib);
-  parser->Parse(&std::cin);
   
+  cFile file;
+  if (file.Open("main.asl")) parser->Parse(file);
+  
   return 0;
 }

Modified: branches/collect/source/targets/avida-viewer/cZoomScreen.cc
===================================================================
--- branches/collect/source/targets/avida-viewer/cZoomScreen.cc	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/targets/avida-viewer/cZoomScreen.cc	2007-06-06 01:44:03 UTC (rev 1643)
@@ -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: branches/collect/source/tools/cDataFile.cc
===================================================================
--- branches/collect/source/tools/cDataFile.cc	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/tools/cDataFile.cc	2007-06-06 01:44:03 UTC (rev 1643)
@@ -61,6 +61,16 @@
 }
 
 
+void cDataFile::Write(long i, const char* descr)
+{
+  if (!m_descr_written) {
+    m_data += cStringUtil::Stringf("%i ", i);
+    WriteColumnDesc(descr);
+  } else
+    m_fp << i << " ";
+}
+
+
 void cDataFile::Write(const char* data_str, const char* descr)
 {
   if (!m_descr_written) {

Modified: branches/collect/source/tools/cDataFile.h
===================================================================
--- branches/collect/source/tools/cDataFile.h	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/tools/cDataFile.h	2007-06-06 01:44:03 UTC (rev 1643)
@@ -107,9 +107,11 @@
 
   void Write(double x, const char* descr);
   void Write(int i, const char* descr);
+  void Write(long i, const char* descr);
   void Write(const char* data_str, const char* descr);
   inline void WriteAnonymous(double x) { m_fp << x << " "; }
   inline void WriteAnonymous(int i) { m_fp << i << " "; }
+  inline void WriteAnonymous(long i) { m_fp << i << " "; }
   inline void WriteAnonymous(const char* data_str) { m_fp << data_str << " "; }
   void WriteBlockElement(double x, int element, int x_size);
   void WriteBlockElement(int i, int element, int x_size);

Modified: branches/collect/source/tools/cDoubleSum.h
===================================================================
--- branches/collect/source/tools/cDoubleSum.h	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/tools/cDoubleSum.h	2007-06-06 01:44:03 UTC (rev 1643)
@@ -54,7 +54,7 @@
   double S3()           const { return s3; }
   double S4()           const { return s4; }
 
-  double Average() const { return ( n >1 ) ? (s1/n) : 0; }
+  double Average() const { return ( n > 0 ) ? (s1/n) : 0; }
 
   double Variance() const { return ( n > 1 ) ?
       (s2 - s1*s1/n) / (n-1) : INF_ERR; }

Modified: branches/collect/source/tools/cFile.h
===================================================================
--- branches/collect/source/tools/cFile.h	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/tools/cFile.h	2007-06-06 01:44:03 UTC (rev 1643)
@@ -90,6 +90,10 @@
    **/
   bool Open(cString _filename, std::ios::openmode mode=(std::ios::in));
   
+  // Access to the underlying implmentation
+  std::fstream* GetFileStream() { return &fp; }
+  
+  
   /**
    * Close the currently open file.
    **/

Modified: branches/collect/source/tools/cWeightedIndex.cc
===================================================================
--- branches/collect/source/tools/cWeightedIndex.cc	2007-06-06 00:47:55 UTC (rev 1642)
+++ branches/collect/source/tools/cWeightedIndex.cc	2007-06-06 01:44:03 UTC (rev 1643)
@@ -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