[Avida-SVN] r2892 - in development: . Avida.xcodeproj source/analyze source/cpu source/main source/script

brysonda at myxo.css.msu.edu brysonda at myxo.css.msu.edu
Mon Oct 27 21:01:39 PDT 2008


Author: brysonda
Date: 2008-10-28 00:01:39 -0400 (Tue, 28 Oct 2008)
New Revision: 2892

Added:
   development/source/main/cResourceHistory.cc
   development/source/main/cResourceHistory.h
Modified:
   development/Avida.xcodeproj/project.pbxproj
   development/CMakeLists.txt
   development/source/analyze/cAnalyze.cc
   development/source/analyze/cAnalyze.h
   development/source/cpu/cCPUTestInfo.h
   development/source/cpu/cTestCPU.cc
   development/source/cpu/cTestCPU.h
   development/source/main/cResourceLib.cc
   development/source/main/cResourceLib.h
   development/source/script/ASAnalyzeLib.cc
Log:
Add new cResourceHistory class to centralize and replace the STL based structure that was used to pass resource value history around in analyze mode and the test cpu.

Modified: development/Avida.xcodeproj/project.pbxproj
===================================================================
--- development/Avida.xcodeproj/project.pbxproj	2008-10-28 03:20:39 UTC (rev 2891)
+++ development/Avida.xcodeproj/project.pbxproj	2008-10-28 04:01:39 UTC (rev 2892)
@@ -192,6 +192,8 @@
 		7073972E0D725B9F003855D3 /* cSemanticASTVisitor.cc in Sources */ = {isa = PBXBuildFile; fileRef = 7073972C0D725B9D003855D3 /* cSemanticASTVisitor.cc */; };
 		7076FEB00D347FD000556CAF /* cAnalyzeTreeStats_CumulativeStemminess.cc in Sources */ = {isa = PBXBuildFile; fileRef = 7076FEAE0D347FD000556CAF /* cAnalyzeTreeStats_CumulativeStemminess.cc */; };
 		7076FEB10D347FD000556CAF /* cAnalyzeTreeStats_Gamma.cc in Sources */ = {isa = PBXBuildFile; fileRef = 7076FEAF0D347FD000556CAF /* cAnalyzeTreeStats_Gamma.cc */; };
+		709A1EEB0EB6C42D006090AF /* cOrgMovementPredicate.h in Headers */ = {isa = PBXBuildFile; fileRef = 709A1EE90EB6C42D006090AF /* cOrgMovementPredicate.h */; };
+		709A1EEC0EB6C42D006090AF /* cResourceHistory.cc in Sources */ = {isa = PBXBuildFile; fileRef = 709A1EEA0EB6C42D006090AF /* cResourceHistory.cc */; };
 		70A33CF60D8DCBB4008EF976 /* ASCoreLib.cc in Sources */ = {isa = PBXBuildFile; fileRef = 70A33CF50D8DCBB4008EF976 /* ASCoreLib.cc */; };
 		70A778390D69D5CA00735F1E /* cDemeProbSchedule.cc in Sources */ = {isa = PBXBuildFile; fileRef = 70A778370D69D5C200735F1E /* cDemeProbSchedule.cc */; };
 		70AA941A09D486CA006A24C8 /* system-alloc.cc in Sources */ = {isa = PBXBuildFile; fileRef = 70DCF50209CFB0B400924128 /* system-alloc.cc */; };
@@ -588,6 +590,9 @@
 		7099EF4E0B2FBC85001269F6 /* cTextViewerDriver_Base.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = cTextViewerDriver_Base.cc; sourceTree = "<group>"; };
 		7099EF4F0B2FBC85001269F6 /* cTextViewerDriver_Base.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = cTextViewerDriver_Base.h; sourceTree = "<group>"; };
 		7099EF500B2FBC85001269F6 /* cView_Base.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = cView_Base.h; sourceTree = "<group>"; };
+		709A1E540EB69DA6006090AF /* cResourceHistory.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = cResourceHistory.h; sourceTree = "<group>"; };
+		709A1EE90EB6C42D006090AF /* cOrgMovementPredicate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = cOrgMovementPredicate.h; sourceTree = "<group>"; };
+		709A1EEA0EB6C42D006090AF /* cResourceHistory.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = cResourceHistory.cc; sourceTree = "<group>"; };
 		709D92490A5D94FD00D6A163 /* cMutationalNeighborhood.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = cMutationalNeighborhood.h; sourceTree = "<group>"; };
 		709D924A0A5D94FD00D6A163 /* cMutationalNeighborhoodResults.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = cMutationalNeighborhoodResults.h; sourceTree = "<group>"; };
 		709D924B0A5D950D00D6A163 /* cMutationalNeighborhood.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = cMutationalNeighborhood.cc; sourceTree = "<group>"; };
@@ -1423,6 +1428,8 @@
 		DCC310040762539D008F7A48 /* main */ = {
 			isa = PBXGroup;
 			children = (
+				709A1EE90EB6C42D006090AF /* cOrgMovementPredicate.h */,
+				709A1EEA0EB6C42D006090AF /* cResourceHistory.cc */,
 				B4FA259E0C5EB7600086D4B5 /* cPhenPlastGenotype.cc */,
 				B4FA25800C5EB6510086D4B5 /* cPhenPlastGenotype.h */,
 				B4FA25810C5EB6510086D4B5 /* cPlasticPhenotype.cc */,
@@ -1509,6 +1516,7 @@
 				700AE91B09DB65F200A073FD /* cTaskContext.h */,
 				7099EEBF0B2F9D2A001269F6 /* cEnvReqs.h */,
 				70166B8D0B519CFE009533A5 /* cTaskState.h */,
+				709A1E540EB69DA6006090AF /* cResourceHistory.h */,
 			);
 			path = main;
 			sourceTree = "<group>";
@@ -1688,6 +1696,7 @@
 			buildActionMask = 2147483647;
 			files = (
 				2A57A4000D6B954D00FC54C7 /* cProbDemeProbSchedule.h in Headers */,
+				709A1EEB0EB6C42D006090AF /* cOrgMovementPredicate.h in Headers */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};
@@ -2040,6 +2049,7 @@
 				2A57A3FF0D6B954D00FC54C7 /* cProbDemeProbSchedule.cc in Sources */,
 				70EFD6600D975B6E00FAD32A /* cConstBurstSchedule.cc in Sources */,
 				70BB2AE20EA5303F008269D2 /* cDriverStatusConduit.cc in Sources */,
+				709A1EEC0EB6C42D006090AF /* cResourceHistory.cc in Sources */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};

Modified: development/CMakeLists.txt
===================================================================
--- development/CMakeLists.txt	2008-10-28 03:20:39 UTC (rev 2891)
+++ development/CMakeLists.txt	2008-10-28 04:01:39 UTC (rev 2892)
@@ -244,6 +244,7 @@
   ${MAIN_DIR}/cReactionResult.cc
   ${MAIN_DIR}/cResource.cc
   ${MAIN_DIR}/cResourceCount.cc
+  ${MAIN_DIR}/cResourceHistory.cc
   ${MAIN_DIR}/cResourceLib.cc
   ${MAIN_DIR}/cSpatialCountElem.cc
   ${MAIN_DIR}/cSpatialResCount.cc

Modified: development/source/analyze/cAnalyze.cc
===================================================================
--- development/source/analyze/cAnalyze.cc	2008-10-28 03:20:39 UTC (rev 2891)
+++ development/source/analyze/cAnalyze.cc	2008-10-28 04:01:39 UTC (rev 2892)
@@ -61,6 +61,7 @@
 #include "cProbSchedule.h"
 #include "cReaction.h"
 #include "cReactionProcess.h"
+#include "cResourceHistory.h"
 #include "cSchedule.h"
 #include "cSpecies.h"
 #include "cStringIterator.h"
@@ -100,6 +101,7 @@
 , inst_set(world->GetHardwareManager().GetInstSet())
 , m_ctx(world->GetDefaultContext())
 , m_jobqueue(world)
+, m_resources(NULL)
 , interactive_depth(0)
 {
   random.ResetSeed(m_world->GetConfig().RANDOM_SEED.Get());
@@ -109,7 +111,6 @@
     batch[i].Name().Set("Batch%d", i);
   }
   
-  resources.clear();
 }
 
 
@@ -417,69 +418,21 @@
 // from a file specified by the user, or resource.dat by default.
 void cAnalyze::LoadResources(cString cur_string)
 {
-  resources.clear();
+  delete m_resources;
+  m_resources = new cResourceHistory;
   
   int words = cur_string.CountNumWords();
   
   cString filename = "resource.dat";
-  if(words >= 1) {
-    filename = cur_string.PopWord();
-  }
-  if(words >= 2) {
-    m_resource_time_spent_offset = cur_string.PopWord().AsInt();
-  }
+  if (words >= 1) filename = cur_string.PopWord();
+  if (words >= 2) m_resource_time_spent_offset = cur_string.PopWord().AsInt();
   
   cout << "Loading Resources from: " << filename << endl;
   
-  // Process the resource.dat, currently assuming this is the only possible
-  // input file
-  ifstream resourceFile(filename, ios::in);
-  if ( !resourceFile.good() ) {
-    m_world->GetDriver().RaiseException("Failed to load resource file.");
-    return;
-  }
-      
-  // Read in each line of the resource file and process in
-  char line[4096];
-  while(!resourceFile.eof()) {
-    resourceFile.getline(line, 4095);
-    
-    // Get rid of the whitespace at the beginning of the stream, then 
-    // see if the line begins with a #, if so move on to the next line.
-    stringstream ss;
-    ss << line; ss >> ws; 
-    if( (ss.peek() == '#') || (!ss.good()) ) { continue; }
-    
-    // Read the update number from the stream
-    int update;
-    ss >> update; assert(ss.good());
-    
-    // Read in the concentration values for the current update and put them
-    // into a temporary vector.
-    double x;
-    vector<double> tempValues;
-    // Loop until the stream is no longer valid, which means either all the
-    // data has been processed or a non-numeric was encountered.  Currently
-    // assuming a non-numeric is a comment denoting the rest of the line as
-    // not informational.
-    while(true) {
-      ss >> ws; ss >> x;
-      tempValues.push_back(x);
-      if(!ss.good()) { ss.clear(); break; }
-    }
-    // Can't have no resources, so assert
-    if(tempValues.empty()) { assert(0); }
-    // add the update to the list of updates.  Also assuming the values
-    // in the file are already sorted.  If this turns out not to be the
-    // case you will need to sort on resources[i].first
-    resources.push_back(make_pair(update, tempValues));
-  }
-  resourceFile.close();
-
-  return;
+  if (!m_resources->LoadFile(filename)) m_world->GetDriver().RaiseException("failed to load resource file");
 }
 
-double cAnalyze::AnalyzeEntropy(cAnalyzeGenotype * genotype, double mu) 
+double cAnalyze::AnalyzeEntropy(cAnalyzeGenotype* genotype, double mu) 
 {
   double entropy = 0.0;
   
@@ -1892,7 +1845,7 @@
       test_info.UseManualInputs(manual_inputs);
     else
       test_info.UseRandomInputs(use_random_inputs); 
-    test_info.SetResourceOptions(use_resources, &resources, update, m_resource_time_spent_offset);
+    test_info.SetResourceOptions(use_resources, m_resources, update, m_resource_time_spent_offset);
 
     if (m_world->GetVerbosity() >= VERBOSE_ON){
       msg = cString("Tracing ") + filename;
@@ -2872,7 +2825,7 @@
   // Create Test Info 
   // No choice of use_resources for this analyze command...
   cCPUTestInfo test_info;
-  test_info.SetResourceOptions(RES_CONSTANT, &resources, update, m_resource_time_spent_offset);
+  test_info.SetResourceOptions(RES_CONSTANT, m_resources, update, m_resource_time_spent_offset);
   
   
   ///////////////////////////////////////////////////////////////////////
@@ -3451,7 +3404,7 @@
   // Backup test CPU data
   cCPUTestInfo test_info;
   // No choice of use_resources for this analyze command...
-  test_info.SetResourceOptions(RES_CONSTANT, &resources, update, m_resource_time_spent_offset);
+  test_info.SetResourceOptions(RES_CONSTANT, m_resources, update, m_resource_time_spent_offset);
   
   vector<cAnalyzeGenotype *> community;
   cAnalyzeGenotype * genotype = NULL;
@@ -3802,53 +3755,46 @@
   for (int i=0; i<fitnesses.GetSize(); i++)
 	  fitnesses[i].Resize(fsize[1]+1,1);
   
-   // figure out what index into resources that we loaded goes with update we want
-  int index=-1;
-  for (unsigned int i = 0; i < resources.size(); i++)
-  {
-	  if (resources.at(i).first == update)
-	  {
-		  index=i;
-		  i=resources.size();
-	  }
+  // Get the resources for the specified update
+  tArray<double> resources;
+  if (!m_resources || !m_resources->GetResourceLevelsForUpdate(update, resources, true)) {
+    cout << "error: did not find the desired update in resource history" << endl;
+    return;
   }
-  if (index<0) cout << "error, never found desired update in resource array!\n";
-
-  else cout << "creating map using resources at update: " << update << endl;
+  
+  cout << "creating map using resources at update: " << update << endl;
    
-  for (int i=0; i<m_world->GetEnvironment().GetResourceLib().GetSize(); i++)
-  {
-  	  // first have to find reaction that matches this resource, so compare names
+  for (int i = 0; i < m_world->GetEnvironment().GetResourceLib().GetSize(); i++) {
+    
+    // first have to find reaction that matches this resource, so compare names
 	  cString name = m_world->GetEnvironment().GetResourceLib().GetResource(i)->GetName();
 	  cReaction* react = NULL;
-	  for (int j=0; j<m_world->GetEnvironment().GetReactionLib().GetSize(); j++)
-	  {
-		  if (m_world->GetEnvironment().GetReactionLib().GetReaction(j)->GetProcesses().GetPos(0)->GetResource()->GetName() == name)
-		  {
+	  for (int j = 0; j < m_world->GetEnvironment().GetReactionLib().GetSize(); j++) {
+		  if (m_world->GetEnvironment().GetReactionLib().GetReaction(j)->GetProcesses().GetPos(0)->GetResource()->GetName() == name) {
 			  react = m_world->GetEnvironment().GetReactionLib().GetReaction(j);
 			  j = m_world->GetEnvironment().GetReactionLib().GetSize();
 		  }
 	  }
-	  if (react==NULL)
-	    continue;
+	  if (react == NULL) continue;
+    
 	  // now have proper reaction, pull all the data need from the reaction
 	  double frac = react->GetProcesses().GetPos(0)->GetMaxFraction(); 
 	  double max = react->GetProcesses().GetPos(0)->GetMaxNumber();
 	  double min = react->GetProcesses().GetPos(0)->GetMinNumber();
 	  double value = react->GetValue();
 	  int fun = react->GetTask()->GetArguments().GetInt(0);
-	  if (fun==f1)
-		  fun=0;
-	  else if (fun==f2)
-		  fun=1;
+	  
+    if (fun == f1) fun = 0;
+	  else if (fun == f2) fun = 1;
 	  else cout << "function is neither f1 or f2! doh!\n";
+    
 	  double thresh = react->GetTask()->GetArguments().GetDouble(3);
 	  double threshMax = react->GetTask()->GetArguments().GetDouble(4);
 	  //double maxFx = react->GetTask()->GetArguments().GetDouble(1);
 	  //double minFx = react->GetTask()->GetArguments().GetDouble(2);
 
 	  // and pull the concentration of this resource from resource object loaded from resource.dat
-	  double concentration = resources.at(index).second.at(i);
+	  double concentration = resources[i];
 
 	  // calculate the merit based on this resource concentration, fraction, and value
 	  double mer = concentration * frac * value;
@@ -4766,7 +4712,7 @@
     cCPUTestInfo test_info;
     if (use_manual_inputs)
       test_info.UseManualInputs(manual_inputs);
-    test_info.SetResourceOptions(use_resources, &resources);
+    test_info.SetResourceOptions(use_resources, m_resources);
     genotype->Recalculate(m_ctx, &test_info);
     
     // Headers...
@@ -7107,7 +7053,7 @@
     int updateBorn = -1;
     updateBorn = genotype->GetUpdateBorn();
     cCPUTestInfo test_info;
-    test_info.SetResourceOptions(useResources, &resources, updateBorn, m_resource_time_spent_offset);
+    test_info.SetResourceOptions(useResources, m_resources, updateBorn, m_resource_time_spent_offset);
     
     // Calculate the stats for the genotype we're working with ...
     genotype->Recalculate(m_ctx, &test_info);
@@ -7287,7 +7233,7 @@
     int updateBorn = -1;
     updateBorn = genotype->GetUpdateBorn();
     cCPUTestInfo test_info;
-    test_info.SetResourceOptions(useResources, &resources, updateBorn, m_resource_time_spent_offset);
+    test_info.SetResourceOptions(useResources, m_resources, updateBorn, m_resource_time_spent_offset);
     
     // Calculate the stats for the genotype we're working with ...
     genotype->Recalculate(m_ctx, &test_info);
@@ -7480,7 +7426,7 @@
     int updateBorn = -1;
     updateBorn = genotype->GetUpdateBorn();
     cCPUTestInfo test_info;
-    test_info.SetResourceOptions(useResources, &resources, updateBorn, m_resource_time_spent_offset);
+    test_info.SetResourceOptions(useResources, m_resources, updateBorn, m_resource_time_spent_offset);
     
     // Calculate the stats for the genotype we're working with ...
     genotype->Recalculate(m_ctx, &test_info);
@@ -8293,7 +8239,7 @@
     test_info.UseManualInputs(manual_inputs);
   else
     test_info.UseRandomInputs(use_random_inputs); 
-  test_info.SetResourceOptions(use_resources, &resources, update, m_resource_time_spent_offset);
+  test_info.SetResourceOptions(use_resources, m_resources, update, m_resource_time_spent_offset);
 
   if (m_world->GetVerbosity() >= VERBOSE_ON) {
     msg.Set("Running batch %d through test CPUs...", cur_batch);
@@ -8380,7 +8326,7 @@
     test_info.UseManualInputs(manual_inputs);
   else
     test_info.UseRandomInputs(use_random_inputs); 
-  test_info.SetResourceOptions(use_resources, &resources, update, m_resource_time_spent_offset);
+  test_info.SetResourceOptions(use_resources, m_resources, update, m_resource_time_spent_offset);
   
   // Notifications
   if (m_world->GetVerbosity() >= VERBOSE_ON) {

Modified: development/source/analyze/cAnalyze.h
===================================================================
--- development/source/analyze/cAnalyze.h	2008-10-28 03:20:39 UTC (rev 2891)
+++ development/source/analyze/cAnalyze.h	2008-10-28 04:01:39 UTC (rev 2892)
@@ -27,7 +27,6 @@
 #define cAnalyze_h
 
 #include <iostream>
-#include <vector>
 
 #ifndef cAnalyzeJobQueue_h
 #include "cAnalyzeJobQueue.h"
@@ -67,18 +66,20 @@
 const int MAX_BATCHES = 2000;
 
 class cAnalyzeCommand;
+class cAnalyzeCommandDefBase;
 class cAnalyzeFunction;
-class cAnalyzeCommandDefBase;
+class cAnalyzeGenotype;
 class cAnalyzeScreen;
-template <class T> class tDataEntry;
+class cEnvironment;
+class cInitFile;
 class cInstSet;
-class cAnalyzeGenotype;
-class cInitFile;
-template <class T> class tDataEntryCommand;
-class cEnvironment;
+class cResourceHistory;
 class cTestCPU;
 class cWorld;
+template <class T> class tDataEntry;
+template <class T> class tDataEntryCommand;
 
+
 class cAnalyze {
   friend class cAnalyzeScreen;
 #if USE_tMemTrack
@@ -115,9 +116,8 @@
   cAvidaContext& m_ctx;
   cAnalyzeJobQueue m_jobqueue;
 
-  // This is the storage for the resource information from resource.dat.  It 
-  // is a pair of the update and a vector of the resource concentrations
-  std::vector<std::pair<int, std::vector<double> > > resources;
+  // This is the storage for the resource information from resource.dat.
+  cResourceHistory* m_resources;
   int m_resource_time_spent_offset; // The amount to offset the time spent when 
                                     // beginning, using resources that change
 

Modified: development/source/cpu/cCPUTestInfo.h
===================================================================
--- development/source/cpu/cCPUTestInfo.h	2008-10-28 03:20:39 UTC (rev 2891)
+++ development/source/cpu/cCPUTestInfo.h	2008-10-28 04:01:39 UTC (rev 2892)
@@ -26,8 +26,6 @@
 #ifndef cCPUTestInfo_h
 #define cCPUTestInfo_h
 
-#include <vector>
-
 #ifndef nHardware_h
 #include "nHardware.h"
 #endif
@@ -42,8 +40,10 @@
 class cInstSet;
 class cOrganism;
 class cPhenotype;
+class cResourceHistory;
 class cString;
 
+
 enum eTestCPUResourceMethod { RES_INITIAL = 0, RES_CONSTANT, RES_UPDATED_DEPLETABLE, RES_DYNAMIC, RES_LAST };  
 // Modes for how the test CPU handles resources:
 // OFF - all resources are at zero. (OLD: use_resources = 0)
@@ -52,6 +52,7 @@
 //    is an average time slice). The organism also depletes these resources when using them.
 // DYNAMIC - UPDATED_DEPLETABLE + resources inflow/outflow (NOT IMPLEMENTED YET!)
 
+
 class cCPUTestInfo
 {
   friend class cTestCPU;
@@ -77,7 +78,7 @@
   
   // Information about how to handle resources
   eTestCPUResourceMethod m_res_method;
-  std::vector<std::pair<int, std::vector<double> > > * m_res;
+  cResourceHistory* m_res;
   int m_res_update;
   int m_res_cpu_cycle_offset;
 
@@ -97,7 +98,7 @@
   void ResetInputMode() {use_manual_inputs = false; use_random_inputs = false;}
   void SetTraceExecution(cHardwareTracer* tracer = NULL) { m_tracer = tracer; }
   void SetInstSet(cInstSet* inst_set = NULL) { m_inst_set = inst_set; }
-  void SetResourceOptions(int res_method = RES_INITIAL, std::vector<std::pair<int, std::vector<double> > > * res = NULL, int update = 0, int cpu_cycle_offset = 0)
+  void SetResourceOptions(int res_method = RES_INITIAL, cResourceHistory* res = NULL, int update = 0, int cpu_cycle_offset = 0)
     { m_res_method = (eTestCPUResourceMethod)res_method; m_res = res; m_res_update = update; m_res_cpu_cycle_offset = cpu_cycle_offset; }
 
 

Modified: development/source/cpu/cTestCPU.cc
===================================================================
--- development/source/cpu/cTestCPU.cc	2008-10-28 03:20:39 UTC (rev 2891)
+++ development/source/cpu/cTestCPU.cc	2008-10-28 04:01:39 UTC (rev 2892)
@@ -25,10 +25,11 @@
 
 #include "cTestCPU.h"
 
+#include "functions.h"
+
 #include "cAvidaContext.h"
 #include "cCPUTestInfo.h"
 #include "cEnvironment.h"
-#include "functions.h"
 #include "cGenomeUtil.h"
 #include "cGenotype.h"
 #include "cHardwareBase.h"
@@ -38,11 +39,12 @@
 #include "cInstSet.h"
 #include "cOrganism.h"
 #include "cPhenotype.h"
-#include "cTestCPUInterface.h"
+#include "cResource.h"
 #include "cResourceCount.h"
+#include "cResourceHistory.h"
 #include "cResourceLib.h"
-#include "cResource.h"
 #include "cStringUtil.h"
+#include "cTestCPUInterface.h"
 #include "cWorld.h"
 #include "tMatrix.h"
 
@@ -50,7 +52,6 @@
 
 using namespace std;
 
-std::vector<std::pair<int, std::vector<double> > > * cTestCPU::s_resources = NULL;
 
 cTestCPU::cTestCPU(cWorld* world)
 {
@@ -60,16 +61,14 @@
 }  
 
  
-void cTestCPU::InitResources(int res_method, std::vector<std::pair<int, std::vector<double> > > * res, int update, int cpu_cycle_offset)
+void cTestCPU::InitResources(int res_method, cResourceHistory* res, int update, int cpu_cycle_offset)
 {  
   //FOR DEMES
   m_deme_resource_count.SetSize(0);
 
   m_res_method = (eTestCPUResourceMethod)res_method;
   // Make sure it's valid
-  if(res_method < 0 ||  res_method >= RES_LAST) {
-    m_res_method = RES_INITIAL;
-  }
+  if (res_method < 0 || res_method >= RES_LAST) m_res_method = RES_INITIAL;
   
   // Setup the resources...
   m_res = res;
@@ -92,24 +91,7 @@
     // be changed if LOAD_RESOURCES analyze command is called.  If there are
     // no resources in the environment or there is no environment, the list
     // is empty then the all resources will default to 0.0
-    if (!s_resources)
-    {
-      s_resources = new std::vector<std::pair<int, std::vector<double> > >;
-      const cResourceLib &resource_lib = m_world->GetEnvironment().GetResourceLib();
-      if(resource_lib.GetSize() > 0) 
-      {
-        vector<double> r;
-        for(int i=0; i<resource_lib.GetSize(); i++) 
-        {
-          cResource *resource = resource_lib.GetResource(i);
-          assert(resource);
-          r.push_back(resource->GetInitial());
-        }
-        s_resources->push_back(make_pair(0, r));
-      }
-    }
-    m_res = s_resources;
-    assert(m_res != NULL);
+    m_res = &m_world->GetEnvironment().GetResourceLib().GetInitialResourceLevels();
   }
   
   const cResourceLib& resource_lib = m_world->GetEnvironment().GetResourceLib();
@@ -117,86 +99,27 @@
   
   // Set the resource count to zero by default
   m_resource_count.SetSize(resource_lib.GetSize());
-  for(int i=0; i<resource_lib.GetSize(); i++) 
-  {     
-     m_resource_count.Set(i, 0.0);
-  }
+  for (int i = 0; i < resource_lib.GetSize(); i++) m_resource_count.Set(i, 0.0);
     
-  SetResourceUpdate(m_res_update, true);
+  SetResourceUpdate(m_res_update, false);
   // Round down to the closest update to choose how to initialize resources
 }
 
 void cTestCPU::UpdateResources(int cpu_cycles_used)
 {
-    int ave_time_slice = m_world->GetConfig().AVE_TIME_SLICE.Get();
-    if ((m_res_method >= RES_UPDATED_DEPLETABLE) && (cpu_cycles_used % ave_time_slice == 0))
-    {
-      SetResourceUpdate(m_res_update+1);
-    }
+  int ave_time_slice = m_world->GetConfig().AVE_TIME_SLICE.Get();
+  if ((m_res_method >= RES_UPDATED_DEPLETABLE) && (cpu_cycles_used % ave_time_slice == 0))
+    SetResourceUpdate(m_res_update + 1, true);
 }
 
-void cTestCPU::SetResourceUpdate(int update, bool round_to_closest)
+inline void cTestCPU::SetResourceUpdate(int update, bool round_to_closest)
 {
   // No resources defined? -- you can't do this!
   if (!m_res) return;
 
   m_res_update = update;
-
-  int which = -1;
-  if (round_to_closest)
-  {
-    // Assuming resource vector is sorted by update, front to back
-    
-    /*
-    if(update <= (*m_res)[0].first) {
-      which = 0;
-    } else if(update >= (*m_res).back().first) {
-      which = m_res->size() - 1;
-    } else {
-      // Find the update that is closest to the born update
-      for(unsigned int i=0; i<(*m_res).size()-1; i++) {
-        if(update >= (*m_res)[i+1].first) { continue; }
-        if(update - (*m_res)[i].first <=
-           (*m_res)[i+1].first - update) {
-          which = i;
-        } else {
-          which = i + 1;
-        }
-        break;
-      */
-      // Find the update that is closest to the born update, round down instead @JEB
-      which = 0;
-      while ( which < (int)m_res->size() )
-      {
-        if ( (*m_res)[which].first > update ) break;
-        which++;
-      }
-      if (which > 0) which--;
- // }
-    assert(which >= 0);
-  }
-  else // Only find exact update matches
-  {
-    for(unsigned int i=0; i<m_res->size(); i++)
-    {
-      if (update == (*m_res)[i].first)
-      {
-        which = i;
-        break;
-      }
-    }
-    if (which < 0) return; // Not found (do nothing)
-  }
   
-  const cResourceLib& resource_lib = m_world->GetEnvironment().GetResourceLib();
-  for(int i=0; i<resource_lib.GetSize(); i++) 
-  {
-    if( (which >= (int)m_res->size()) || (i >= (int)(*m_res)[which].second.size()) ) {
-      m_resource_count.Set(i, 0.0);
-    } else {
-      m_resource_count.Set(i, (*m_res)[which].second[i]);
-    }
-  }
+  m_res->GetResourceCountForUpdate(update, m_resource_count, !round_to_closest);
 }
 
 void cTestCPU::ModifyResources(const tArray<double>& res_change)

Modified: development/source/cpu/cTestCPU.h
===================================================================
--- development/source/cpu/cTestCPU.h	2008-10-28 03:20:39 UTC (rev 2891)
+++ development/source/cpu/cTestCPU.h	2008-10-28 04:01:39 UTC (rev 2892)
@@ -27,7 +27,6 @@
 #define cTestCPU_h
 
 #include <fstream>
-#include <vector>
 
 #ifndef tArray_h
 #include "tArray.h"
@@ -48,6 +47,7 @@
 class cInjectGenotype;
 class cInstSet;
 class cResourceCount;
+class cResourceHistory;
 class cWorld;
 
 
@@ -66,7 +66,7 @@
   
   // Resource settings. Reinitialized from cCPUTestInfo on each test.
   eTestCPUResourceMethod m_res_method;
-  std::vector<std::pair<int, std::vector<double> > > * m_res;
+  const cResourceHistory* m_res;
   int m_res_update;
   int m_res_cpu_cycle_offset;
 
@@ -77,17 +77,15 @@
   bool ProcessGestation(cAvidaContext& ctx, cCPUTestInfo& test_info, int cur_depth);
   bool TestGenome_Body(cAvidaContext& ctx, cCPUTestInfo& test_info, const cGenome& genome, int cur_depth);
 
-  // one copy of resources initialized from environment file
-  static std::vector<std::pair<int, std::vector<double> > > * s_resources;
-
+  
   cTestCPU(); // @not_implemented
   cTestCPU(const cTestCPU&); // @not_implemented
   cTestCPU& operator=(const cTestCPU&); // @not_implemented
   
   // Internal methods for setting up and updating resources
-  void InitResources(int res_method = RES_INITIAL, std::vector<std::pair<int, std::vector<double> > > * res = NULL, int update = 0, int cpu_cycle_offset = 0);
+  void InitResources(int res_method = RES_INITIAL, cResourceHistory* res = NULL, int update = 0, int cpu_cycle_offset = 0);
   void UpdateResources(int cpu_cycles_used);
-  void SetResourceUpdate(int update, bool round_to_closest = false);
+  inline void SetResourceUpdate(int update, bool exact = true);
   inline void SetResource(int id, double new_level);
 public:
   cTestCPU(cWorld* world);

Added: development/source/main/cResourceHistory.cc
===================================================================
--- development/source/main/cResourceHistory.cc	                        (rev 0)
+++ development/source/main/cResourceHistory.cc	2008-10-28 04:01:39 UTC (rev 2892)
@@ -0,0 +1,117 @@
+/*
+ *  cResourceHistory.cpp
+ *  Avida
+ *
+ *  Created by David Bryson on 10/27/08.
+ *  Copyright 2008 Michigan State University. All rights reserved.
+ *
+ *
+ *  This program is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU General Public License
+ *  as published by the Free Software Foundation; version 2
+ *  of the License.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ */
+
+#include "cResourceHistory.h"
+
+#include "cInitFile.h"
+#include "cResourceCount.h"
+#include "cStringList.h"
+
+
+int cResourceHistory::getEntryForUpdate(int update, bool exact) const
+{
+  int entry = -1;
+  
+  if (exact) {
+    for (int i = 0; i < m_entries.GetSize(); i++) {
+      if (update == m_entries[i].update) {
+        entry = i;
+        break;
+      }
+    }
+  } else {
+    // Find the update that is closest to the born update, round down
+    entry = 0;
+    for (; entry < m_entries.GetSize(); entry++) if (m_entries[entry].update > update) break;
+    if (entry > 0) entry--;
+  }
+
+  return entry;
+}
+
+bool cResourceHistory::GetResourceCountForUpdate(int update, cResourceCount& rc, bool exact) const
+{
+  int entry = getEntryForUpdate(update, exact);
+  if (entry == -1) return false;
+      
+  for (int i = 0; i < rc.GetSize(); i++) {
+    if (entry >= m_entries.GetSize() || i >= m_entries[entry].values.GetSize()) rc.Set(i, 0.0);
+    else rc.Set(i, m_entries[entry].values[i]);
+  }
+  
+  return true;
+}
+
+bool cResourceHistory::GetResourceLevelsForUpdate(int update, tArray<double>& levels, bool exact) const
+{
+  int entry = getEntryForUpdate(update, exact);
+  if (entry == -1) return false;
+  
+  levels.Resize(m_entries[entry].values.GetSize());
+  for (int i = 0; i < levels.GetSize(); i++) {
+    if (entry >= m_entries.GetSize()) levels[i] = 0.0;
+    else levels[i] = m_entries[entry].values[i];
+  }
+  
+  return true;
+}
+
+void cResourceHistory::AddEntry(int update, const tArray<double>& values)
+{
+  // Note that this method does not currently validate that 'update' does not already exist as an entry
+  // If this happens, incorrect resource levels may be returned upon retreival
+
+  int new_entry = m_entries.GetSize();
+  m_entries.Resize(new_entry + 1);
+  m_entries[new_entry].update = update;
+  m_entries[new_entry].values = values;
+}
+
+bool cResourceHistory::LoadFile(const cString& filename)
+{
+  cInitFile file(filename);
+  
+  if (!file.WasOpened()) {
+//    tConstListIterator<cString> err_it(file.GetErrors());
+//    const cString* errstr = NULL;
+//    while ((errstr = err_it.Next())) m_world->GetDriver().RaiseException(*errstr);
+//    m_world->GetDriver().RaiseFatalException(1, cString("Could not open instruction set '") + filename + "'.");
+    return false;
+  }
+  
+  m_entries.Resize(file.GetNumLines());
+  for (int line = 0; line < file.GetNumLines(); line++) {
+    cStringList cur_line(file.GetLine(line));
+    assert(cur_line.GetSize());
+    
+    m_entries[line].update = cur_line.Pop().AsInt();
+    
+    int num_values = cur_line.GetSize();
+    m_entries[line].values.Resize(num_values);
+    for (int i = 0; i < num_values; i++) m_entries[line].values[i] = cur_line.Pop().AsDouble();
+  }
+  
+  return true;
+}
+

Added: development/source/main/cResourceHistory.h
===================================================================
--- development/source/main/cResourceHistory.h	                        (rev 0)
+++ development/source/main/cResourceHistory.h	2008-10-28 04:01:39 UTC (rev 2892)
@@ -0,0 +1,64 @@
+/*
+ *  cResourceHistory.h
+ *  Avida
+ *
+ *  Created by David Bryson on 10/27/08.
+ *  Copyright 2008 Michigan State University. All rights reserved.
+ *
+ *
+ *  This program is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU General Public License
+ *  as published by the Free Software Foundation; version 2
+ *  of the License.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ */
+
+#ifndef cResourceHistory_h
+#define cResourceHistory_h
+
+#ifndef tArray_h
+#include "tArray.h"
+#endif
+
+class cResourceCount;
+class cString;
+template<class T> class tArray;
+
+
+class cResourceHistory
+{
+private:
+  struct sResourceHistoryEntry {
+    int update;
+    tArray<double> values;
+  };
+  
+  tArray<sResourceHistoryEntry> m_entries;
+  
+  
+  int getEntryForUpdate(int update, bool exact) const;
+  
+  
+  cResourceHistory(const cResourceHistory&); // @not_implemented
+  cResourceHistory& operator=(const cResourceHistory&); // @not_implemented
+  
+public:
+  cResourceHistory() { ; }
+  
+  bool GetResourceCountForUpdate(int update, cResourceCount& rc, bool exact = false) const;
+  bool GetResourceLevelsForUpdate(int update, tArray<double>& levels, bool exact = false) const;
+  void AddEntry(int update, const tArray<double>& values);
+  
+  bool LoadFile(const cString& filename);
+};
+
+#endif

Modified: development/source/main/cResourceLib.cc
===================================================================
--- development/source/main/cResourceLib.cc	2008-10-28 03:20:39 UTC (rev 2891)
+++ development/source/main/cResourceLib.cc	2008-10-28 04:01:39 UTC (rev 2892)
@@ -26,48 +26,55 @@
 #include "cResourceLib.h"
 
 #include "cResource.h"
+#include "cResourceHistory.h"
 
 using namespace std;
 
 
 cResourceLib::~cResourceLib()
 {
-  for (int i = 0; i < resource_array.GetSize(); i++) {
-    delete resource_array[i];
-  }
+  for (int i = 0; i < m_resource_array.GetSize(); i++) delete m_resource_array[i];
+  delete m_initial_levels;
 }
 
-cResource * cResourceLib::AddResource(const cString & res_name)
+cResource* cResourceLib::AddResource(const cString& res_name)
 {
-  const int new_id = resource_array.GetSize();
-  cResource * new_resource = new cResource(res_name, new_id);
-  resource_array.Resize(new_id + 1);
-  resource_array[new_id] = new_resource;
+  if (m_initial_levels) return NULL; // Initial levels calculated, cannot add more resources
+  
+  const int new_id = m_resource_array.GetSize();
+  cResource* new_resource = new cResource(res_name, new_id);
+  m_resource_array.Resize(new_id + 1);
+  m_resource_array[new_id] = new_resource;
+  
   return new_resource;
 }
 
-cResource * cResourceLib::GetResource(const cString & res_name) const
+cResource* cResourceLib::GetResource(const cString& res_name) const
 {
-  for (int i = 0; i < resource_array.GetSize(); i++) {
-    if (resource_array[i]->GetName() == res_name) return resource_array[i];
+  for (int i = 0; i < m_resource_array.GetSize(); i++) {
+    if (m_resource_array[i]->GetName() == res_name) return m_resource_array[i];
   }
   cerr << "Error: Unknown resource '" << res_name << "'." << endl;
   return NULL;
 }
 
-cResource * cResourceLib::GetResource(int id) const
+
+const cResourceHistory& cResourceLib::GetInitialResourceLevels() const
 {
-  return resource_array[id];
+  if (!m_initial_levels) {
+    tArray<double> levels(m_resource_array.GetSize());
+    for (int i = 0; i < m_resource_array.GetSize(); i++) levels[i] = m_resource_array[i]->GetInitial();
+    m_initial_levels = new cResourceHistory;
+    m_initial_levels->AddEntry(0, levels);
+  }
+ 
+  return *m_initial_levels;
 }
 
-bool cResourceLib::DoesResourceExist(const cString & res_name) 
 
-/* Return boolean for if the named resource exists in the resource library */
-
+bool cResourceLib::DoesResourceExist(const cString& res_name) 
 {
-  for (int i = 0; i < resource_array.GetSize(); i++) {
-    if (resource_array[i]->GetName() == res_name) return true;
-  }
+  for (int i = 0; i < m_resource_array.GetSize(); i++) if (m_resource_array[i]->GetName() == res_name) return true;
   return false;
 }
 

Modified: development/source/main/cResourceLib.h
===================================================================
--- development/source/main/cResourceLib.h	2008-10-28 03:20:39 UTC (rev 2891)
+++ development/source/main/cResourceLib.h	2008-10-28 04:01:39 UTC (rev 2892)
@@ -31,26 +31,29 @@
 #endif
 
 class cResource;
+class cResourceHistory;
 class cString;
 
 class cResourceLib
 {
 private:
-  tArray<cResource*> resource_array;
+  tArray<cResource*> m_resource_array;
+  mutable cResourceHistory* m_initial_levels;
   
   cResourceLib(const cResourceLib&); // @not_implemented
   cResourceLib& operator=(const cResourceLib&); // @not_implemented
   
 public:
-  cResourceLib() { ; }
+  cResourceLib() : m_initial_levels(NULL) { ; }
   ~cResourceLib();
 
-  int GetSize() const { return resource_array.GetSize(); }
+  int GetSize() const { return m_resource_array.GetSize(); }
 
   cResource* AddResource(const cString& res_name);
   cResource* GetResource(const cString& res_name) const;
-  cResource* GetResource(int id) const;
-  bool DoesResourceExist(const cString & res_name);
+  inline cResource* GetResource(int id) const { return m_resource_array[id]; }
+  const cResourceHistory& GetInitialResourceLevels() const;
+  bool DoesResourceExist(const cString& res_name);
 };
 
 

Modified: development/source/script/ASAnalyzeLib.cc
===================================================================
--- development/source/script/ASAnalyzeLib.cc	2008-10-28 03:20:39 UTC (rev 2891)
+++ development/source/script/ASAnalyzeLib.cc	2008-10-28 04:01:39 UTC (rev 2892)
@@ -162,12 +162,14 @@
 #define BIND_FUNCTION(CLASS, NAME, METHOD, SIGNATURE) \
   tASNativeObject<CLASS>::RegisterMethod(new tASNativeObjectBoundFunction<CLASS, SIGNATURE>(&ASAnalyzeLib::METHOD), NAME);
 #define REGISTER_FUNCTION(NAME, SIGNATURE) lib->RegisterFunction(new tASFunction<SIGNATURE>(&ASAnalyzeLib::NAME, #NAME));
-  
 
+
   BIND_FUNCTION(cWorld, "LoadOrganism", LoadOrganism, cAnalyzeGenotype* (const cString&));
   BIND_FUNCTION(cWorld, "LoadOrganismWithInstSet", LoadOrganismWithInstSet, cAnalyzeGenotype* (const cString&, cInstSet*));
   BIND_FUNCTION(cWorld, "LoadSequence", LoadSequence, cAnalyzeGenotype* (const cString&));
   BIND_FUNCTION(cWorld, "LoadSequenceWithInstSet", LoadSequenceWithInstSet, cAnalyzeGenotype* (const cString&, cInstSet*));
+  BIND_FUNCTION(cWorld, "LoadBatch", LoadBatch, cAnalyzeGenotype* (const cString&));
+  BIND_FUNCTION(cWorld, "LoadBatchWithInstSet", LoadBatchWithInstSet, cAnalyzeGenotype* (const cString&, cInstSet*));
 
 
 #undef BIND_FUNCTION




More information about the Avida-cvs mailing list