Exemple #1
0
void simulationOERRW::detailledSimulation(double delta,int64 step,int64 end)
{
    out << "\n\n\n***** EXTENDED SIMULATION *****\n\n";
    std::string f = "extended_OERRW-d" + doubletostring_nice(delta);
    extendedOERRW ew(delta);
    if (ew.load(f)) {
        out << "Simulation found. Continuing it...\n\n";
    }
    else {
        ew.reset(delta);
        out << "Starting a new simulation.\n\n";
    }
    int64 inc = step/50;
    while(ew.nb_visited() < end)
    {
        int64 todo = step;
        out << ew.info()<< "\nSimulating";
        while(todo >= inc) {
            ew.makeWalk(inc);
            out << ".";
            todo -= inc;
        }
        if (todo != 0) {
            ew.makeWalk(todo);
            out << ".";
        }
        out << "\nSaving...";
        ew.save(f);
        out << "ok!\n\n\n";
    }
    out << "\n***** EXTENDED SIMULATION COMPLETED *****\n\n\n";
    return;
    return;
}
Exemple #2
0
int main(int argc, char **argv)
{
  
  DataCube dc(2); // datacube of dimension 2

  Vector<int> size(2); 
  size[1] = 5; // range of datacube in x-direction
  size[2] = 5; // range of datacube in y-direction

  Vector<double> spaceing(2);
  spaceing[1]=1.0;
  spaceing[2]=1.0;

  dc.SetCubeSizeAndSpaceing(size,spaceing); 
  dc.MallocCube();

  // define the dataarray
  for ( int i = 0; i < size[1]; i++ ){
    for ( int j = 0; j < size[2]; j++ ){

      if (  ( i == 2 ) || ( ( i > 1 ) && ( j == 2 ) ) )
	dc(i,j) = 1.0;

    } 
  }

  // test the calculation of moments

  //define volume
  Volume vol(0, 0, 0, 5, 5, spaceing[1], spaceing[2]);

  Moments mom(&dc);

  Vector<double> fp(2);
  int code = mom.focal_point( fp, vol );
  if ( code ) cout << errorCode(code);

  cout << "focal point: ( " << fp[1] << " " << fp[2] << " )" << endl;

  // caluclulate inertian tensor
  Vector<double> i_t(4);
  code = mom.inertian_tensor(i_t, vol );
  if ( code ) cout << errorCode(code);

  cout << "inertian tensor: ( " << i_t[1] << " " << i_t[2] << " )" << endl;
  cout << "                 ( " << i_t[3] << " " << i_t[4] << " )" << endl;

   // calculate inertian values

  Vector<double> ew(2);
  Vector<double> ev(4);
  code = mom.inertian_values(ew,ev,vol);
  if ( code ) cout << errorCode(code);

  cout << "eigenvektor: ( " << ev[1] << " " << ev[2] << " )" << endl;
  cout << "dazu eigenwert: " << ew[1] << endl;
  cout << "eigenvektor: ( " << ev[3] << " " << ev[4] << " )" << endl;
  cout << "dazu eigenwert: " << ew[2] << endl;
 
}
Exemple #3
0
int main(int argc, char **argv) {

    QApplication::setStyle("windows");
   QApplication a(argc,argv);
   EGS_Wizard ew(0);
   //a.connect(&ew,SIGNAL(quit()),SLOT(quit()));
   ew.show();
   return a.exec();

}
// ######################################################################
void GistEstimatorFFT::
onSimEventRetinaImage(SimEventQueue& q, rutz::shared_ptr<SimEventRetinaImage>& e)
{
  Image<float> img = normalize(e->frame().grayFloat());
  computeGistFeatureVector(img);
  LINFO("Gist features are computed");

  // post an event so that anyone interested in gist can grab it:
  rutz::shared_ptr<SimEventGistOutput>
    ew(new SimEventGistOutput(this, itsGistVector));
  q.post(ew);
}
// ######################################################################
void GistEstimatorGen::
onSimEventVisualCortexOutput(SimEventQueue& q, rutz::shared_ptr<SimEventVisualCortexOutput>& e)
{
  //Grab the channel maps from the visual cortex
  rutz::shared_ptr<SimReqVCXmaps> vcxm(new SimReqVCXmaps(this));
  q.request(vcxm); // VisualCortex is now filling-in the maps...
  rutz::shared_ptr<ChannelMaps> chm = vcxm->channelmaps();

  //Compute the full size gist feature vector
  getFeatureVector(chm);

  // post an event so that anyone interested in gist can grab it:
  rutz::shared_ptr<SimEventGistOutput>
    ew(new SimEventGistOutput(this, itsGistVector));
  q.post(ew);
}
Exemple #6
0
/*!
 * discretizes 3d nonlinear anisotropic diffusion 
 * by finite volume method using a 27-point stencil
 */
int 
FV_3d27::
discretize(DataCube &dc)
{ 
 
  int code; // errorcode
  int e,i,j,k,ewc,evc; // loop variables
  NeuraDataType insert_diff; // help variable
  NeuraDataType diff_x, diff_y, diff_z; // help variables

  int n = a->Length(1);//=dc.GetSize()[1];
  int m = a->Length(2);//=dc.GetSize()[2];
  int l = a->Length(3);//=dc.GetSize()[3];
 
  int number_of_elements = (n-1)*(m-1)*(l-1);
  int number_of_nodes = n*m*l;

  // eigenvalues and eigenvectors of inertian tensor 
  // within current integration point
  Vector<NeuraDataType> ew(3);
  Vector<NeuraDataType> ev(9); 

  Vector<NeuraDataType> tmp(3); // help vector
  Vector<NeuraDataType> t(3); // coefficients of anisotropy

  NeuraDataType cl, cp, ci; // characteristic structure coefficients
  NeuraDataType sum_ew; // sum over eigenvalues of inertian tensor
  NeuraDataType swap; // help variable 

  a->SetZero();

  // prepare moment calculation

  // for to use fastest method
  if ( gt == CUBE ){
    int warn = 0;
    if ( integration_size_x % 2 == 1 ){ integration_size_x ++; warn = 1;}
    if ( integration_size_y % 2 == 1 ){ integration_size_y ++; warn = 1;}
    if ( integration_size_z % 2 == 1 ){ integration_size_z ++; warn = 1;}
    if ( warn ) cout << "Warning: You should use even integration sizes in all directions at CUBE integration! Given values were adapted." << endl;
  }

  Volume vol(gt, 3, integration_size_x, integration_size_y, integration_size_z );

  Moments mom(&dc);
  Vector<NeuraDataType> *vals; 
  Vector<NeuraDataType> *vects;
  
  time_t time1, time2, timediff;
  // calculate moments
  cout << "calculate moments..." << endl;
  time1 = time(NULL);

  if ( 
      ( integration_size_x > n ) || 
      ( integration_size_y > m ) || 
      ( integration_size_z > l ) 
      ) 
    {
      return INTEGRATION_DOMAIN_TOO_BIG;
    } 
  
  switch ( gt )
    {
    case CUBE: // fast moments calculation and elementwise kindOfMoments
      kind_of_moments = ELEMENTWISE;
      vals = new ( Vector<NeuraDataType>[number_of_elements])(3);
      vects = new (Vector<NeuraDataType>[number_of_elements])(9);
      code = mom.elemwise_fast2_all_inertian_values(vals,vects,vol);
      if ( code ) return code;
      break;
    case BALL: // fourier moments calculation and nodewise kindOfMoments
      kind_of_moments = NODEWISE;
      vals = new ( Vector<NeuraDataType>[number_of_nodes])(3);
      vects = new (Vector<NeuraDataType>[number_of_nodes])(9);
      code = mom.fourier_all_inertian_values(vals,vects,vol,n,m,l);
      code = mom.all_inertian_values(vals,vects,vol);
      if ( code ) return code;
      break;
    default:
      return UNKNOWN_GEOMETRY_TYPE;
    }
  
  if ( code ) return code;
  time2 = time(NULL);
  cout << "...moments calculated" << endl;
  timediff = time2-time1;
  cout << "calculation of moments took " << timediff << " seconds" << endl;
 
  // discretise
  for ( e = 0; e < number_of_elements; e++ ) // elements 
    {  
      elements_nodes(e,n,m,en);
      
      for ( i = 0; i < 8; i++ ) // nodes
	{   
	  // determine moments
	  switch ( kind_of_moments )
	    {
	    case ELEMENTWISE:
	      // eigenvalues
	      for ( ewc = 1; ewc <= 3; ewc++ )
		ew[ewc] = vals[e][ewc];
	      // eigenvectors
	      for ( evc = 1; evc <= 9; evc++ )
		ev[evc] = vects[e][evc];
	      break;
	    case NODEWISE:
	      // eigenvalues
	      for ( ewc = 1; ewc <= 3; ewc++ )
		ew[ewc] = vals[en[i]-1][ewc];
	      // eigenvectors
	      for ( evc = 1; evc <= 9; evc++ )
		ev[evc] = vects[en[i]-1][evc];
	      break;
	    default: 
	      cout << "FV_3d27::RunTimeError: Unknown kindOfMoments! \n Abort " << endl;
	      exit(1);
	    }
	  
	  k = 0;
	  while ( ( ip[i][k][0] != -1 ) && ( k < 2 ) ) // ips
	    {   
	      for ( j = 0; j < 8; j++ ) // ansatzfunctions
		{  
		  diff_x = grad_phi_x(j,ip[i][k][0],ip[i][k][1],ip[i][k][2]);
		  diff_y = grad_phi_y(j,ip[i][k][0],ip[i][k][1],ip[i][k][2]);
		  diff_z = grad_phi_z(j,ip[i][k][0],ip[i][k][1],ip[i][k][2]);
		  
		  // sort eigenvalues
		  if ( ew[1] < ew[2] ){ 
		    swap = ew[1]; ew[1] = ew[2]; ew[2] = swap;
		    swap = ev[1]; ev[1] = ev[4]; ev[4] = swap;
		    swap = ev[2]; ev[2] = ev[5]; ev[5] = swap;
		    swap = ev[3]; ev[3] = ev[6]; ev[6] = swap;
		    
		  }
		  if ( ew[1] < ew[3] ){ 
		    swap = ew[1]; ew[1] = ew[3]; ew[3] = swap;
		    swap = ev[1]; ev[1] = ev[7]; ev[7] = swap;
		    swap = ev[2]; ev[2] = ev[8]; ev[8] = swap;
		    swap = ev[3]; ev[3] = ev[9]; ev[9] = swap;
		  }
		  if ( ew[2] < ew[3] ){ 
		    swap = ew[2]; ew[2] = ew[3]; ew[3] = swap;
		    swap = ev[4]; ev[4] = ev[7]; ev[7] = swap;
		    swap = ev[5]; ev[5] = ev[8]; ev[8] = swap;
		    swap = ev[6]; ev[6] = ev[9]; ev[9] = swap;
		  }
		  
		  
		  // determine coefficients of anisotropy
		 	  
		  if ( fixed_coeffs )
		    {
		      t[1] = anicoeff1;
		      t[2] = anicoeff2;
		      t[3] = anicoeff3;
		    }
		  else
		    {
		      sum_ew = ew[1]+ew[2]+ew[3];
		      if ( fabs(sum_ew) <= 0.000001 )
			{ cl = 0; cp = 0; ci = 1; }
		      else {
			cl = (ew[1]-ew[2])/sum_ew;
			cp = 2*(ew[2]-ew[3])/sum_ew;
			ci = 3*ew[3]/sum_ew;
		      }
		      
		      t[1] = 1.0;
		      switch (dependence_type)
			{
			case PERONA_MALIK:
			  t[2] = g_pm(cl);
			  t[3] = g_pm(1-ci);
			  break;
			case WEIKERT:
			  t[2] = g_w(cl);
			  t[3] = g_w(1-ci);
			  break;
			case BLACK_SAPIRO: 
			  t[2] = g_bs(cl);
			  t[3] = g_bs(1-ci);
			  break;
			default:
			  cout << "Unknown nonlinear function specified!\n Abort" << endl;
			  exit(1);	
			}
		    }

		  // multiplication with the anisotropy tensor

		  tmp[1] = ev[1]*diff_x + ev[2]*diff_y + ev[3]*diff_z;
		  tmp[2] = ev[4]*diff_x + ev[5]*diff_y + ev[6]*diff_z;
		  tmp[3] = ev[7]*diff_x + ev[8]*diff_y + ev[9]*diff_z;

		  tmp[1] *= t[1]; tmp[2] *= t[2]; tmp[3] *= t[3];

		  diff_x = ev[1]*tmp[1] + ev[4]*tmp[2] + ev[7]*tmp[3];
		  diff_y = ev[2]*tmp[1] + ev[5]*tmp[2] + ev[8]*tmp[3];
		  diff_z = ev[3]*tmp[1] + ev[6]*tmp[2] + ev[9]*tmp[3];


		  // multiplication with normal
		  insert_diff = diff_x * nip[i][k][0] +
		    diff_y * nip[i][k][1] +
		    diff_z * nip[i][k][2];
 
		
		  insert_diff *= 0.25; // surface of subcontrolvolume
		 
		      a->Add(en[i], en[j], insert_diff);
		    
		      a->Add( en[intact[i][k]], en[j], -insert_diff); 
		     	  
		}//for j
	    
	      k++;
       
	    }// while
	 
	}// for i
     	  	      
    }// for e

  delete [] vals;
  delete [] vects;


  // treatment of boundary

  int position; 
  
  // lower and upper boundary
  for ( i = 0; i < n; i++ )
    {
      for ( j = 0; j < m; j++ )
	{
	  k = 0;
	  position = 1 + i + j*n + k*n*m;
	  a->MultiplyRow(position,2);
	  k = l-1;
	  position = 1 + i + j*n + k*n*m;
	  a->MultiplyRow(position,2);
	} 
    }
  //left and right boundary
  for ( j = 0; j < m; j++ )
    {
      for ( k = 0; k < l; k++ )
	{ 
	  i = 0;
	  position = 1 + i + j*n + k*n*m;
	  a->MultiplyRow(position,2);
	  i = n-1;
	  position = 1 + i + j*n + k*n*m;
	  a->MultiplyRow(position,2);
	} 
    }
  
  // front and back boundary
  for ( i = 0; i < n; i++ )
    {
      for ( k = 0; k < l; k++ )
	{
	  j = 0;
	  position = 1 + i + j*n + k*n*m;
	  a->MultiplyRow(position,2);
	  j = m-1;
	  position = 1 + i + j*n + k*n*m;
	  a->MultiplyRow(position,2);
	}
    }


return OK;
}
static void customCatalogTests(Node& node, TestRunner& tr)
{
   resetTestEnvironment(node);

   Messenger* messenger = node.getMessenger();

   // generate the ware URLs that will be used throughout the test.
   Url waresUrl;
   waresUrl.format(
      "%s/api/3.0/catalog/wares?nodeuser=%" PRIu64,
      messenger->getSelfUrl(true).c_str(), TEST_USER_ID);
   Url waresNonDefaultListUrl;
   waresNonDefaultListUrl.format(
      "%s/api/3.0/catalog/wares?nodeuser=%" PRIu64 "&id=%s&default=false",
      messenger->getSelfUrl(true).c_str(), TEST_USER_ID, TEST_WARE_ID_2);
   Url wareUrl;
   wareUrl.format(
      "%s/api/3.0/catalog/wares/%s?nodeuser=%" PRIu64,
      messenger->getSelfUrl(true).c_str(), TEST_WARE_ID_2, TEST_USER_ID);

   // generate the files URL that will be used to prime the medialibrary
   Url filesUrl;
   filesUrl.format("%s/api/3.2/medialibrary/files?nodeuser=%" PRIu64,
      messenger->getSelfUrl(true).c_str(), TEST_USER_ID);
   Url removeUrl;
   removeUrl.format(
      "%s/api/3.2/medialibrary/files/%s?nodeuser=%" PRIu64,
      messenger->getSelfUrl(true).c_str(), TEST_FILE_ID_2, TEST_USER_ID);

   // Create basic and detailed test ware with id=2
   Ware basicWare2;
   Ware detailedWare2;
   {
      basicWare2["id"] = TEST_WARE_ID_2;
      basicWare2["description"] =
         "This ware was added by test-services-customcatalog";

      detailedWare2 = basicWare2.clone();
      detailedWare2["mediaId"] = 2;
      detailedWare2["fileInfos"]->setType(Array);
      FileInfo fi = detailedWare2["fileInfos"]->append();
      fi["id"] = TEST_FILE_ID_2;
      fi["mediaId"] = 2;
      File file((sTestDataDir + TEST_FILENAME_2).c_str());
      fi["extension"] = file->getExtension() + 1;
      fi["contentType"] = "audio/mpeg";
      fi["contentSize"] = TEST_CONTENT_SIZE_2;
      fi["size"] = (uint64_t)file->getLength();
      fi["path"] = file->getAbsolutePath();

      detailedWare2["payees"]->setType(Array);
      Payee p1 = detailedWare2["payees"]->append();
      Payee p2 = detailedWare2["payees"]->append();

      p1["id"] = 900;
      p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE;
      p1["amount"] = "0.10";
      p1["description"] = "This payee is for media ID 2";

      p2["id"] = 900;
      p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL;
      p2["percentage"] = "0.10";
      p2["description"] = "This payee is for media ID 2";
   }

   // remove any previous files from the media library
   messenger->deleteResource(&removeUrl, NULL, node.getDefaultUserId());
   // pass even if there is an exception - this is meant to just clear any
   // previous entries in the medialibrary database if they existed.
   Exception::clear();

   tr.group("customcatalog");

   tr.test("add file to medialibrary (valid)");
   {
      DynamicObject in;
      DynamicObject out;

      // create a FileInfo object
      string normalizedPath;
      File::normalizePath(
         (sTestDataDir + TEST_FILENAME_2).c_str(), normalizedPath);
      out["path"] = normalizedPath.c_str();
      out["mediaId"] = 2;

      // prepare event waiter
      EventWaiter ew(node.getEventController());
      ew.start("bitmunk.medialibrary.File.updated");
      ew.start("bitmunk.medialibrary.File.exception");

      // add the file to the media library
      assertNoException(
         messenger->post(&filesUrl, &out, &in, node.getDefaultUserId()));

      // wait for file ID set event
      assert(ew.waitForEvent(5*1000));

      // ensure it has an exception
      Event e = ew.popEvent();
      //dumpDynamicObject(e);
      if(e["details"]->hasMember("exception"))
      {
         ExceptionRef ex = Exception::convertToException(
            e["details"]["exception"]);
         Exception::set(ex);
      }
      else if(strcmp(
         e["type"]->getString(), "bitmunk.medialibrary.File.updated") == 0)
      {
         // add new mediaLibraryId to the basic and detailed wares
         basicWare2["mediaLibraryId"] = e["details"]["mediaLibraryId"];
         detailedWare2["mediaLibraryId"] = e["details"]["mediaLibraryId"];
      }
   }
   tr.passIfNoException();

   tr.test("add ware without payee-scheme (valid)");
   {
      DynamicObject in;
      DynamicObject out;

      // create the outgoing ware object
      FileInfo fi;
      fi["id"] = TEST_FILE_ID_2;

      out["id"] = TEST_WARE_ID_2;
      out["mediaId"] = 2;
      out["description"] = "This ware was added by test-services-customcatalog";
      out["fileInfo"] = fi;
      out["payees"]->setType(Array);
      Payee p1 = out["payees"]->append();
      Payee p2 = out["payees"]->append();

      p1["id"] = 900;
      p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE;
      p1["amount"] = "0.10";
      p1["description"] = "This payee is for media ID 2";

      p2["id"] = 900;
      p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL;
      p2["percentage"] = "0.10";
      p2["description"] = "This payee is for media ID 2";

      // add the ware to the custom catalog
      messenger->post(&waresUrl, &out, &in, node.getDefaultUserId());

      // set ware payeeSchemeIds
      basicWare2["payeeSchemeId"] = in["payeeSchemeId"];
      detailedWare2["payeeSchemeId"] = in["payeeSchemeId"];
   }
   tr.passIfNoException();

   tr.test("get ware (valid)");
   {
      // get a specific ware from the custom catalog
      Ware receivedWare;
      assertNoException(
         messenger->get(&wareUrl, receivedWare, node.getDefaultUserId()));

      // remove format details for comparison
      if(receivedWare->hasMember("fileInfos") &&
         receivedWare["fileInfos"]->getType() == Array &&
         receivedWare["fileInfos"]->length() == 1)
      {
         receivedWare["fileInfos"][0]->removeMember("formatDetails");
      }

      // check to make sure that the wares match
      assertNamedDynoCmp(
         "Expected ware ResourceSet", detailedWare2,
         "Received ware ResourceSet", receivedWare);
   }
   tr.passIfNoException();

   tr.test("get wares");
   {
      // get a specific ware from the custom catalog
      Ware receivedWareSet;
      Url url;
      url.format(
         "%s/api/3.0/catalog/wares?nodeuser=%" PRIu64 "&id=%s",
         messenger->getSelfUrl(true).c_str(), TEST_USER_ID, TEST_WARE_ID_2);
      assertNoException(
         messenger->get(&url, receivedWareSet, node.getDefaultUserId()));

      // check ware set
      Ware expectedWareSet;
      expectedWareSet["resources"][0] = basicWare2.clone();
      expectedWareSet["total"] = 1;
      expectedWareSet["num"] = 1;
      expectedWareSet["start"] = 0;

      assertNamedDynoCmp(
         "Expected ware ResourceSet", expectedWareSet,
         "Received ware ResourceSet", receivedWareSet);
   }
   tr.passIfNoException();

   tr.test("get wares by fileId");
   {
      // get a specific ware from the custom catalog
      Ware receivedWareSet;
      Url url;
      url.format(
         "%s/api/3.0/catalog/wares?nodeuser=%" PRIu64 "&fileId=%s",
         messenger->getSelfUrl(true).c_str(), TEST_USER_ID, TEST_FILE_ID_2);
      assertNoException(
         messenger->get(&url, receivedWareSet, node.getDefaultUserId()));

      // check ware set
      Ware expectedWareSet;
      expectedWareSet["resources"][0] = basicWare2.clone();
      expectedWareSet["total"] = 1;
      expectedWareSet["num"] = 1;
      expectedWareSet["start"] = 0;

      assertNamedDynoCmp(
         "Expected ware ResourceSet", expectedWareSet,
         "Received ware ResourceSet", receivedWareSet);
   }
   tr.passIfNoException();

   tr.test("get specific unknown wares");
   {
      // get a specific ware from the custom catalog
      Ware receivedWareSet;
      Url url;
      url.format(
         "%s/api/3.0/catalog/wares?nodeuser=%" PRIu64 "&id=%s&id=INVALID",
         messenger->getSelfUrl(true).c_str(), TEST_USER_ID, TEST_WARE_ID_2);
      messenger->get(&url, receivedWareSet, node.getDefaultUserId());

      // check ware set
      Ware expectedWareSet;
      expectedWareSet["resources"][0] = basicWare2.clone();
      expectedWareSet["total"] = 1;
      expectedWareSet["num"] = 2;
      expectedWareSet["start"] = 0;

      assertNamedDynoCmp(
         "Expected ware ResourceSet", expectedWareSet,
         "Received ware ResourceSet", receivedWareSet);
   }
   tr.passIfNoException();

   tr.test("get wares by dup ware+file ids");
   {
      // This test gets the same ware by both ware id and file id and returns
      // duplicate results.

      // get a specific ware from the custom catalog
      Ware receivedWareSet;
      Url url;
      url.format(
         "%s/api/3.0/catalog/wares?nodeuser=%" PRIu64 "&id=%s&fileId=%s",
         messenger->getSelfUrl(true).c_str(), TEST_USER_ID,
         TEST_WARE_ID_2, TEST_FILE_ID_2);
      messenger->get(&url, receivedWareSet, node.getDefaultUserId());

      // check ware set
      Ware expectedWareSet;
      expectedWareSet["resources"][0] = basicWare2.clone();
      expectedWareSet["total"] = 1;
      expectedWareSet["num"] = 2;
      expectedWareSet["start"] = 0;

      assertNamedDynoCmp(
         "Expected ware ResourceSet", expectedWareSet,
         "Received ware ResourceSet", receivedWareSet);
   }
   tr.passIfNoException();

   tr.test("remove ware (valid)");
   {
      // remove the ware
      messenger->deleteResource(&wareUrl, NULL, node.getDefaultUserId());
   }
   tr.passIfNoException();

   /*************************** Payee Scheme tests **************************/
   // generate the payee schemes URL
   Url payeeSchemesUrl;
   payeeSchemesUrl.format("%s/api/3.0/catalog/payees/schemes?nodeuser=%" PRIu64,
      messenger->getSelfUrl(true).c_str(), TEST_USER_ID);
   PayeeSchemeId psId = 0;

   tr.test("add payee scheme (valid)");
   {
      DynamicObject in;
      DynamicObject out;

      // create the outgoing list of payees to organize into a payee scheme
      out["description"] = "Payee scheme description 1";
      out["payees"]->setType(Array);
      PayeeList payees = out["payees"];
      Payee p1 = payees->append();
      Payee p2 = payees->append();

      p1["id"] = 900;
      p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE;
      p1["amount"] = "0.10";
      p1["description"] = "test-services-customcatalog test payee 1";

      p2["id"] = 900;
      p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL;
      p2["percentage"] = "0.10";
      p2["description"] = "test-services-customcatalog test payee 2";

      // add the ware to the custom catalog
      messenger->post(&payeeSchemesUrl, &out, &in, node.getDefaultUserId());

      if(in->hasMember("payeeSchemeId"))
      {
         psId = in["payeeSchemeId"]->getUInt32();
      }
   }
   tr.passIfNoException();

   // generate the payee scheme URL
   Url payeeSchemeIdUrl;
   payeeSchemeIdUrl.format("%s/api/3.0/catalog/payees/schemes/%u?nodeuser=%"
      PRIu64,
      messenger->getSelfUrl(true).c_str(), psId, TEST_USER_ID);
   tr.test("get payee scheme (valid)");
   {
      // Create the expected payee scheme
      PayeeScheme expectedPayeeScheme;
      expectedPayeeScheme["id"] = psId;
      expectedPayeeScheme["userId"] = node.getDefaultUserId();
      expectedPayeeScheme["description"] = "Payee scheme description 1";
      expectedPayeeScheme["payees"]->setType(Array);
      Payee p1 = expectedPayeeScheme["payees"]->append();
      Payee p2 = expectedPayeeScheme["payees"]->append();

      p1["id"] = 900;
      p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE;
      p1["amount"] = "0.10";
      p1["description"] = "test-services-customcatalog test payee 1";

      p2["id"] = 900;
      p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL;
      p2["percentage"] = "0.10";
      p2["description"] = "test-services-customcatalog test payee 2";

      // get a specific payee scheme from the custom catalog
      PayeeScheme receivedPayeeScheme;
      messenger->get(
         &payeeSchemeIdUrl, receivedPayeeScheme, node.getDefaultUserId());

      // check payee schemes
      assertNamedDynoCmp(
         "Expected payee scheme", expectedPayeeScheme,
         "Received payee scheme", receivedPayeeScheme);
   }
   tr.passIfNoException();

   tr.test("get all payee schemes (valid)");
   {
      // Create the result set
      ResourceSet expectedResults;
      expectedResults["total"] = 2;
      expectedResults["start"] = 0;
      expectedResults["num"] = 2;

      PayeeScheme ps = expectedResults["resources"]->append();
      ps["id"] = 1;
      ps["userId"] = node.getDefaultUserId();
      ps["description"] = "This ware was added by test-services-customcatalog";
      ps["payees"]->setType(Array);
      Payee p1 = ps["payees"]->append();
      Payee p2 = ps["payees"]->append();

      p1["id"] = 900;
      p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE;
      p1["amount"] = "0.10";
      p1["description"] = "This payee is for media ID 2";

      p2["id"] = 900;
      p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL;
      p2["percentage"] = "0.10";
      p2["description"] = "This payee is for media ID 2";

      ps = expectedResults["resources"]->append();
      ps["id"] = 2;
      ps["userId"] = node.getDefaultUserId();
      ps["description"] = "Payee scheme description 1";
      ps["payees"]->setType(Array);
      Payee p3 = ps["payees"]->append();
      Payee p4 = ps["payees"]->append();

      p3["id"] = 900;
      p3["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE;
      p3["amount"] = "0.10";
      p3["description"] = "test-services-customcatalog test payee 1";

      p4["id"] = 900;
      p4["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL;
      p4["percentage"] = "0.10";
      p4["description"] = "test-services-customcatalog test payee 2";

      // get all payee schemes from the custom catalog
      ResourceSet receivedResults;
      messenger->get(
         &payeeSchemesUrl, receivedResults, node.getDefaultUserId());

      // check payee schemes
      assertNamedDynoCmp(
         "Expected payee scheme ResourceSet", expectedResults,
         "Received payee scheme ResourceSet", receivedResults);
   }
   tr.passIfNoException();

   tr.test("update payee scheme (valid)");
   {
      DynamicObject in;
      DynamicObject out;

      // create the outgoing list of payees to organize into a payee scheme
      out["description"] = "Payee scheme description 2";
      Payee p1 = out["payees"]->append();
      Payee p2 = out["payees"]->append();

      p1["id"] = 900;
      p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE;
      p1["amount"] = "0.15";
      p1["description"] = "test-services-customcatalog test payee 1 (updated)";

      p2["id"] = 900;
      p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL;
      p2["percentage"] = "0.14";
      p2["description"] = "test-services-customcatalog test payee 2 (updated)";

      // update a pre-existing payee scheme
      assertNoException(
         messenger->post(
            &payeeSchemeIdUrl, &out, &in, node.getDefaultUserId()));

      // ensure that the payee scheme was updated
      assert(in["payeeSchemeId"]->getUInt32() == 2);

      if(in->hasMember("payeeSchemeId"))
      {
         psId = in["payeeSchemeId"]->getUInt32();
      }
   }
   tr.passIfNoException();

   tr.test("add ware with payee scheme (valid)");
   {
      DynamicObject in;
      DynamicObject out;

      // create the outgoing ware object
      FileInfo fi;
      fi["id"] = TEST_FILE_ID_2;
      out["id"] = TEST_WARE_ID_2;
      out["mediaId"] = 2;
      out["description"] = "This ware was added by test-services-customcatalog";
      out["fileInfo"] = fi;
      out["payeeSchemeId"] = psId;

      // add the ware to the custom catalog
      messenger->post(&waresUrl, &out, &in, node.getDefaultUserId());
   }
   tr.passIfNoException();

   tr.test("remove associated payee scheme (invalid)");
   {
      messenger->deleteResource(
         &payeeSchemeIdUrl, NULL, node.getDefaultUserId());
   }
   tr.passIfException();

   tr.test("remove ware associated w/ payee scheme (valid)");
   {
      messenger->deleteResource(
         &wareUrl, NULL, node.getDefaultUserId());
   }
   tr.passIfNoException();

   tr.test("remove payee scheme (valid)");
   {
      messenger->deleteResource(
         &payeeSchemeIdUrl, NULL, node.getDefaultUserId());
   }
   tr.passIfNoException();

   tr.test("create ware w/ invalid payee scheme (invalid)");
   {
      DynamicObject in;
      DynamicObject out;

      // create the outgoing ware object
      FileInfo fi;
      fi["id"] = TEST_FILE_ID_2;
      PayeeScheme ps;
      ps["id"] = psId;

      out["id"] = TEST_WARE_ID_2;
      out["mediaId"] = 2;
      out["description"] = "This ware was added by test-services-customcatalog";
      out["fileInfo"] = fi;
      out["payeeScheme"] = ps;

      // add the ware to the custom catalog
      messenger->post(&waresUrl, &out, &in, node.getDefaultUserId());
   }
   tr.passIfException();

   tr.test("remove ware (invalid)");
   {
      // remove a ware that doesn't exist
      messenger->deleteResource(&wareUrl, NULL, node.getDefaultUserId());
   }
   tr.passIfException();

   tr.ungroup();
}
static void interactiveCustomCatalogTests(Node& node, TestRunner& tr)
{
   Messenger* messenger = node.getMessenger();

   tr.group("customcatalog+listing updater");

   // generate the ware URLs that will be used throughout the test.
   Url waresUrl;
   waresUrl.format("%s/api/3.0/catalog/wares?nodeuser=%" PRIu64,
      messenger->getSelfUrl(true).c_str(), TEST_USER_ID);
   Url wareUrl;
   wareUrl.format("%s/api/3.0/catalog/wares/%s?nodeuser=%" PRIu64,
      messenger->getSelfUrl(true).c_str(), TEST_WARE_ID_2, TEST_USER_ID);

   // generate the files URL that will be used to prime the medialibrary
   Url filesUrl;
   filesUrl.format("%s/api/3.2/medialibrary/files?nodeuser=%" PRIu64,
      messenger->getSelfUrl(true).c_str(), TEST_USER_ID);
   Url removeUrl;
   removeUrl.format(
      "%s/api/3.2/medialibrary/files/%s?nodeuser=%" PRIu64,
      messenger->getSelfUrl(true).c_str(), TEST_FILE_ID_2, TEST_USER_ID);

   // remove any previous files from the media library
   messenger->deleteResource(&removeUrl, NULL, node.getDefaultUserId());
   // pass even if there is an exception - this is meant to just clear any
   // previous entries in the medialibrary database if they existed.
   Exception::clear();

   tr.test("add file to medialibrary (valid)");
   {
      DynamicObject in;
      DynamicObject out;

      // create a FileInfo object
      string normalizedPath;
      File::normalizePath(
         (sTestDataDir + TEST_FILENAME_2).c_str(), normalizedPath);
      out["path"] = normalizedPath.c_str();
      out["mediaId"] = 2;

      // prepare event waiter
      EventWaiter ew(node.getEventController());
      ew.start("bitmunk.medialibrary.File.updated");
      ew.start("bitmunk.medialibrary.File.exception");

      // add the file to the media library
      assertNoException(
         messenger->post(&filesUrl, &out, &in, node.getDefaultUserId()));

      // wait for file ID set event
      assert(ew.waitForEvent(5*1000));

      // ensure it has an exception
      Event e = ew.popEvent();
      //dumpDynamicObject(e);
      if(e["details"]->hasMember("exception"))
      {
         ExceptionRef ex = Exception::convertToException(
            e["details"]["exception"]);
         Exception::set(ex);
      }
   }
   tr.passIfNoException();

   tr.test("add ware without payee-scheme (valid)");
   {
      DynamicObject in;
      DynamicObject out;

      // create the outgoing ware object
      FileInfo fi;
      fi["id"] = TEST_FILE_ID_2;

      out["id"] = TEST_WARE_ID_2;
      out["mediaId"] = 2;
      out["description"] = "This ware was added by test-services-customcatalog";
      out["fileInfo"] = fi;
      out["payees"]->setType(Array);
      Payee p1 = out["payees"]->append();
      Payee p2 = out["payees"]->append();

      p1["id"] = 900;
      p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE;
      p1["amount"] = "0.10";
      p1["description"] = "This payee is for media ID 2";

      p2["id"] = 900;
      p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL;
      p2["percentage"] = "0.10";
      p2["description"] = "This payee is for media ID 2";

      // add the ware to the custom catalog
      messenger->post(&waresUrl, &out, &in, node.getDefaultUserId());
   }
   tr.passIfNoException();

   printf("\nWaiting for server info to update...\n");
   Thread::sleep(2*1000);

   while(true)
   {
      tr.test("get server info");
      {
         Url serverUrl;
         serverUrl.format("%s/api/3.0/catalog/server?nodeuser=%" PRIu64,
            messenger->getSelfUrl(true).c_str(), TEST_USER_ID);
         DynamicObject in;
         messenger->get(&serverUrl, in, node.getDefaultUserId());
         dumpDynamicObject(in);
      }
      tr.passIfNoException();

      printf(
         "\nSleeping to allow listing updater to run. Hit CTRL+C to quit.\n");
      Thread::sleep(30*1000);
   }

   tr.ungroup();
}
bool DuffingFloquet()
{
  int np = MPIComm::world().getNProc();
  TEUCHOS_TEST_FOR_EXCEPT(np != 1);

  const double pi = 4.0*atan(1.0);

  /* We will do our linear algebra using Epetra */
  VectorType<double> vecType = new EpetraVectorType();

  /* Create a periodic mesh */
  int nx = 128;

  MeshType meshType = new PeriodicMeshType1D();
  MeshSource mesher = new PeriodicLineMesher(0.0, 2.0*pi, nx, meshType);
  Mesh mesh = mesher.getMesh();

  /* Create a cell filter that will identify the maximal cells
   * in the interior of the domain */
  CellFilter interior = new MaximalCellFilter();
  CellFilter pts = new DimensionalCellFilter(0);
      
  CellFilter left = pts.subset(new CoordinateValueCellPredicate(0,0.0));
  CellFilter right = pts.subset(new CoordinateValueCellPredicate(0,2.0*pi));
      
  /* Create unknown and test functions, discretized using first-order
   * Lagrange interpolants */
  Expr u1 = new UnknownFunction(new Lagrange(1), "u1");
  Expr u2 = new UnknownFunction(new Lagrange(1), "u2");
  Expr v1 = new TestFunction(new Lagrange(1), "v1");
  Expr v2 = new TestFunction(new Lagrange(1), "v2");

  /* Create differential operator and coordinate function */
  Expr dx = new Derivative(0);
  Expr x = new CoordExpr(0);

  /* We need a quadrature rule for doing the integrations */
  QuadratureFamily quad = new GaussianQuadrature(4);

  double F0 = 0.5;
  double gamma = 2.0/3.0;
  double a0 = 1.0;
  double w0 = 1.0;
  double eps = 0.5;

  Expr u1Guess = -0.75*cos(x) + 0.237*sin(x);
  Expr u2Guess = 0.237*cos(x) + 0.75*sin(x);

  DiscreteSpace discSpace(mesh, 
    List(new Lagrange(1), new Lagrange(1)),
    vecType);
  L2Projector proj(discSpace, List(u1Guess, u2Guess));
  Expr u0 = proj.project();


  Expr rhs1 = u2;
  Expr rhs2 = -w0*w0*u1 - gamma*u2 - eps*w0*w0*pow(u1,3.0)/a0/a0 
    + F0*w0*w0*sin(x);

  /* Define the weak form */
  Expr eqn = Integral(interior, 
    v1*(dx*u1 - rhs1) + v2*(dx*u2 - rhs2),
    quad);
  Expr dummyBC ; 

  NonlinearProblem prob(mesh, eqn, dummyBC, List(v1,v2), List(u1,u2), 
    u0, vecType);


  ParameterXMLFileReader reader("nox.xml");
  ParameterList solverParams = reader.getParameters();

  Out::root() << "finding periodic solution" << endl;
  NOXSolver solver(solverParams);
  prob.solve(solver);

  /* unfold the solution onto a non-periodic mesh */
      
  Expr uP = unfoldPeriodicDiscreteFunction(u0, "u_p");
  Out::root() << "uP=" << uP << endl;
      
  Mesh unfoldedMesh = DiscreteFunction::discFunc(uP)->mesh();
  DiscreteSpace unfDiscSpace = DiscreteFunction::discFunc(uP)->discreteSpace();

  FieldWriter writer = new MatlabWriter("Floquet.dat");
  writer.addMesh(unfoldedMesh);
  writer.addField("u_p[0]", new ExprFieldWrapper(uP[0]));
  writer.addField("u_p[1]", new ExprFieldWrapper(uP[1]));

  Array<Expr> a(2);
  a[0] = new Sundance::Parameter(0.0, "a1");
  a[1] = new Sundance::Parameter(0.0, "a2");


  Expr bc = EssentialBC(left, v1*(u1-uP[0]-a[0]) + v2*(u2-uP[1]-a[1]), quad);

  NonlinearProblem unfProb(unfoldedMesh, eqn, bc, 
    List(v1,v2), List(u1,u2), uP, vecType);

  unfProb.setEvalPoint(uP);

  LinearOperator<double> J = unfProb.allocateJacobian();
  Vector<double> b = J.domain().createMember();

  LinearSolver<double> linSolver
    = LinearSolverBuilder::createSolver("amesos.xml");
        
  SerialDenseMatrix<int, double> F(a.size(), a.size());

  for (int i=0; i<a.size(); i++)
  {
    Out::root() << "doing perturbed orbit #" << i << endl;
    for (int j=0; j<a.size(); j++) 
    {
      if (i==j) a[j].setParameterValue(1.0);
      else a[j].setParameterValue(0.0);
    }
        
    unfProb.computeJacobianAndFunction(J, b);
    Vector<double> w = b.copy();
    linSolver.solve(J, b, w);
    Expr w_i = new DiscreteFunction(unfDiscSpace, w);

    for (int j=0; j<a.size(); j++)
    {
      Out::root() << "postprocessing" << i << endl;

      writer.addField("w[" + Teuchos::toString(i)
        + ", " + Teuchos::toString(j) + "]", new ExprFieldWrapper(w_i[j]));
      Expr g = Integral(right, w_i[j], quad);
      F(j,i) = evaluateIntegral(unfoldedMesh, g);
    }
  }

  writer.write();

  Out::root() << "Floquet matrix = " << endl
              << F << endl;
        

  Out::root() << "doing eigenvalue analysis" << endl;
  Array<double> ew_r(a.size());
  Array<double> ew_i(a.size());
  int lWork = 6*a.size();
  Array<double> work(lWork);
  int info = 0;
  LAPACK<int, double> lapack;
  lapack.GEEV('N','N', a.size(), F.values(),
    a.size(), &(ew_r[0]), &(ew_i[0]), 0, 1, 0, 1, &(work[0]), lWork,
    &info);

  TEUCHOS_TEST_FOR_EXCEPTION(info != 0,
    std::runtime_error,
    "LAPACK GEEV returned error code =" << info);
      
  Array<double> ew(a.size());
  for (int i=0; i<a.size(); i++)
  {
    ew[i] = sqrt(ew_r[i]*ew_r[i]+ew_i[i]*ew_i[i]);
    Out::root() << setw(5) << i 
                << setw(16) << ew_r[i] 
                << setw(16) << ew_i[i] 
                << setw(16) << ew[i]
                << endl;
  }

  double err = ::fabs(ew[0] - 0.123);
  return SundanceGlobal::checkTest(err, 0.001);
}
void PageRegister::dump() const
{
  std::cout << std::hex << "AL(" << al() << "), E/W(" << ew() << "), PPA(" << ppa() << ")" << std::endl;
}