Example #1
0
	int mapdump( int argc, char* argv[] )
	{
	  u16 wxl = 5485, wxh = 5500, wyl = 0, wyh = 30;

	  if ( argc >= 4 )
	  {
		wxl = wxh = static_cast<u16>( atoi( argv[2] ) );
		wyl = wyh = static_cast<u16>( atoi( argv[3] ) );
	  }
	  if ( argc >= 6 )
	  {
		wxh = static_cast<u16>( atoi( argv[4] ) );
		wyh = static_cast<u16>( atoi( argv[5] ) );
	  }

      Core::open_uo_data_files( );
      Core::read_uo_data( );

	  std::ofstream ofs( "mapdump.html" );

	  ofs << "<table border=1 cellpadding=5 cellspacing=0>" << std::endl;
	  ofs << "<tr><td>&nbsp;</td>";
	  for ( u16 x = wxl; x <= wxh; ++x )
	  {
		ofs << "<td align=center>" << x << "</td>";
	  }
      ofs << "</tr>" << std::endl;
	  for ( u16 y = wyl; y <= wyh; ++y )
	  {
          ofs << "<tr><td valign=center>" << y << "</td>" << std::endl;
		for ( u16 x = wxl; x <= wxh; ++x )
		{
		  ofs << "<td align=left valign=top>";
		  short z;
		  Core::USTRUCT_MAPINFO mi;
		  safe_getmapinfo( x, y, &z, &mi );
		  Core::USTRUCT_LAND_TILE landtile;
		  readlandtile( mi.landtile, &landtile );
		  ofs << "z=" << z << "<br>";
		  ofs << "landtile=" << Clib::hexint( mi.landtile ) << " " << landtile.name << "<br>";
		  ofs << "&nbsp;flags=" << Clib::hexint( landtile.flags ) << "<br>";
		  ofs << "mapz=" << (int)mi.z << "<br>";

          Core::StaticList statics;
		  readallstatics( statics, x, y );
		  if ( !statics.empty() )
		  {
              ofs << "<table border=1 cellpadding=5 cellspacing=0>" << std::endl;
              ofs << "<tr><td>graphic</td><td>z</td><td>flags</td><td>ht</td>" << std::endl;
			for ( const auto &rec : statics )
			{
			  ofs << "<tr>";
			  ofs << "<td>" << Clib::hexint( rec.graphic ) << "</td>";
			  ofs << "<td>" << int( rec.z ) << "</td>";
			  ofs << "<td>" << Clib::hexint( rec.flags ) << "</td>";
			  ofs << "<td>" << int( rec.height ) << "</td>";
			  ofs << "</tr>" << std::endl;
			}
			ofs << "</table>" << std::endl;
		  }
		  ofs << "</td>" << std::endl;
		}
		ofs << "</tr>" << std::endl;
	  }
	  ofs << "</table>" << std::endl;
      Core::clear_tiledata( );
	  return 0;
	}
Example #2
0
void DrawCosmicResult(){
  
  TFile* tf = new TFile("Cosmic3Out.root");
  TTree* trin = (TTree*)tf->Get("trOut");


  const int nCSI = 2716;
  Int_t    RunNumber;
  Int_t    EventNumber;
  Double_t ScintiSignal = 0;
  Double_t ScintiHHTime = -500.;
  Double_t ScintiTime   =-500.;
  Int_t    nCSIDigi     = 0;
  Double_t CSIDigiE[nCSI];//nCSIDigi
  Double_t CSIDigiTime[nCSI];//nCSIDigi
  Double_t CSIDigiHHTime[nCSI];//nCSIDigi
  Int_t    CSIDigiID[nCSI];//nCSIDigi
  Double_t CSIDigiSignal[nCSI];//nCSIDigi
  Double_t FitP0[2];
  Double_t FitP1[2];
  Double_t FitChisq[2];
  Double_t CSIDigiDeltaT0[nCSI];//nCSIDigi
  Double_t CSIDigiDeltaT1[nCSI];//nCSIDigi
  Int_t    CosmicTrigUp;
  Int_t    CosmicTrigDn;
  Double_t Roh;
  Double_t Theta;

  trin->SetBranchAddress( "RunNumber"     , &RunNumber      );
  trin->SetBranchAddress( "EventNumber"   , &EventNumber    );
  trin->SetBranchAddress( "ScintiSignal"  , &ScintiSignal   );
  trin->SetBranchAddress( "ScintiHHTimne" , &ScintiHHTime   );
  trin->SetBranchAddress( "ScintiTime"    , &ScintiTime     );
  trin->SetBranchAddress( "nCSIDigi"      , &nCSIDigi       );
  trin->SetBranchAddress( "CSIDigiE"      , CSIDigiE        );
  trin->SetBranchAddress( "CSIDigiTime"   , CSIDigiTime     );
  trin->SetBranchAddress( "CSIDigiHHTime" , CSIDigiHHTime   );
  trin->SetBranchAddress( "CSIDigiID"     , CSIDigiID       );
  trin->SetBranchAddress( "CSIDigiSignal" , CSIDigiSignal   );
  trin->SetBranchAddress( "CSIDigiDeltaT0" , CSIDigiDeltaT0 );
  trin->SetBranchAddress( "CSIDigiDeltaT1" , CSIDigiDeltaT1 );
  trin->SetBranchAddress( "FitP0"         , FitP0           );
  trin->SetBranchAddress( "FitP1"         , FitP1           );
  trin->SetBranchAddress( "FitChisq"      , FitChisq        );
  trin->SetBranchAddress( "CosmicTrigUp"  , &CosmicTrigUp   );
  trin->SetBranchAddress( "CosmicTrigDn"  , &CosmicTrigDn   );
  trin->SetBranchAddress( "Roh"           , &Roh            );
  trin->SetBranchAddress( "Theta"         , &Theta          );

  TFile* tfout = new TFile("CosmicOut_hist3.root", "recreate");
  TH2D* hisDeltaChannel = new TH2D("hisDeltaChannel","hisDeltaChannel",2716,0,2716,100,-10,10);
  TH1D* hisDelta[2716];
  TGraphErrors* grDelta = new TGraphErrors();
  TGraphErrors* grRES   = new TGraphErrors(); 
  TCanvas *can = new TCanvas("can","",800,800);


  for( int i = 0; i< 2716; i++){
    hisDelta[i] = new TH1D(Form("hisDelta%d",i ),Form("hisDelta%d",i),100,-10,10);
  }

  for( int ievent = 0; ievent < trin->GetEntries(); ievent++){

    trin->GetEntry(ievent);
    
    for( int idigi = 0; idigi < nCSIDigi ; idigi++){
      hisDelta[ CSIDigiID[ idigi ] ]->Fill( CSIDigiDeltaT1[ idigi ] );
      hisDeltaChannel->Fill( CSIDigiID[ idigi  ] , CSIDigiDeltaT1[ idigi ] );
      //std::cout  << CSIDigiID[ idigi ] << std::endl;
    }
  }
  for( int i = 0; i< 2716; i++){
    //std::cout << hisDelta[i]->GetEntries() << std::endl;
    if( hisDelta[i]->GetEntries() > 10){
      int rst = hisDelta[i]->Fit("gaus","Q","",hisDelta[i]->GetBinCenter( hisDelta[i]->GetMaximumBin() ) - 3, hisDelta[i]->GetBinCenter( hisDelta[i]->GetMaximumBin() )+3);
      TF1* func = NULL;
      func = hisDelta[i]->GetFunction("gaus");
      if( func != NULL ){
	grDelta->SetPoint( grDelta->GetN(), i, func->GetParameter(1));
	grDelta->SetPointError( grDelta->GetN()-1, 0, func->GetParError(2));
	grRES->SetPoint( grRES->GetN() , i , func->GetParameter(2));
      }
    }
    /*
    hisDelta[i]->Draw();
    can->Modified();
    can->Update();
    getchar();
    */
    hisDelta[ i ]  ->Write(); 
  }

  std::ofstream ofs("TimeResolutionCosmic3.dat");
  int    ID[2716];
  double Delta[2716];
  double Resolution[2716];
  for( int i = 0; i< 2716; i++){
    Resolution[i] = 0xFFFF;
    Delta[i]      = 0xFFFF;
  }
  for( int i = 0; i< grRES->GetN(); i++){
    Delta[(int)(grDelta->GetX()[i])] = grDelta->GetY()[i];
    Resolution[(int)(grRES->GetX()[i])] = grRES->GetY()[i] ;
  }
  for( int i = 0; i< 2716; i++){
    ofs << i             << "\t" 
	<< Delta[i]      << "\t"
	<< Resolution[i] << "\n";
  }
  
  grDelta->SetNameTitle("grDelta","grDelta");
  grRES->SetNameTitle("grRES","grRES");
  grDelta->Write();
  grRES->Write();
  hisDeltaChannel->Write();
  tfout->Close();
  ofs.close();
}
Example #3
0
MStatus AbcBullet::doIt(const MArgList & args)
{
try
{
	MStatus status;

	MTime oldCurTime = MAnimControl::currentTime();

	MArgParser argData(syntax(), args, &status);

	if (argData.isFlagSet("help"))
	{
		MGlobal::displayInfo(util::getHelpText());
		return MS::kSuccess;
	}

	bool verbose = argData.isFlagSet("verbose");

	// If skipFrame is true, when going through the playback range of the
	// scene, as much frames are skipped when possible.  This could cause
	// a problem for, time dependent solutions like
	// particle system / hair simulation
	bool skipFrame = true;
	if (argData.isFlagSet("dontSkipUnwrittenFrames"))
		skipFrame = false;

	double startEvaluationTime = DBL_MAX;
	if (argData.isFlagSet("preRollStartFrame"))
	{
		double startAt = 0.0;
		argData.getFlagArgument("preRollStartFrame", 0, startAt);
		startEvaluationTime = startAt;
	}

	unsigned int jobSize = argData.numberOfFlagUses("jobArg");

	if (jobSize == 0)
		return status;

	// the frame range we will be iterating over for all jobs,
	// includes frames which are not skipped and the startAt offset
	std::set<double> allFrameRange;

	// this will eventually hold only the animated jobs.
	// its a list because we will be removing jobs from it
	std::list < AbcWriteJobPtr > jobList;

	for (unsigned int jobIndex = 0; jobIndex < jobSize; jobIndex++)
	{
		JobArgs jobArgs;
		MArgList jobArgList;
		argData.getFlagArgumentList("jobArg", jobIndex, jobArgList);
		MString jobArgsStr = jobArgList.asString(0);
		MStringArray jobArgsArray;

		jobArgs.verbose = verbose;
		{
			// parse the job arguments
			// e.g. -perFrameCallbackMel "print \"something\"" will be splitted to
			//	[0] -perFrameCallbackMel
			//	[1] print "something"
			enum State {
				kArgument,			   // parsing an argument (not quoted)
				kDoubleQuotedString,	 // parsing a double quoted string
				kSingleQuotedString,	 // parsing a single quoted string
			};

			State state = kArgument;
			MString stringBuffer;
			for (unsigned int charIdx = 0; charIdx < jobArgsStr.numChars();
				charIdx++)
			{
				MString ch = jobArgsStr.substringW(charIdx, charIdx);
				switch (state)
				{
				case kArgument:
					if (ch == " ")
					{
						// space terminates the current argument
						if (stringBuffer.length() > 0) {
							jobArgsArray.append(stringBuffer);
							stringBuffer.clear();
						}
						// goto another argument
						state = kArgument;
					}
					else if (ch == "\"")
					{
						if (stringBuffer.length() > 0)
						{
							// double quote is part of the argument
							stringBuffer += ch;
						}
						else
						{
							// goto double quoted string
							state = kDoubleQuotedString;
						}
					}
					else if (ch == "'")
					{
						if (stringBuffer.length() > 0)
						{
							// single quote is part of the argument
							stringBuffer += ch;
						}
						else
						{
							// goto single quoted string
							state = kSingleQuotedString;
						}
					}
					else
					{
						stringBuffer += ch;
					}
				break;

				case kDoubleQuotedString:
					// double quote terminates the current string
					if (ch == "\"")
					{
						jobArgsArray.append(stringBuffer);
						stringBuffer.clear();
						state = kArgument;
					}
					else if (ch == "\\")
					{
						// escaped character
						MString nextCh = (++charIdx < jobArgsStr.numChars())
							? jobArgsStr.substringW(charIdx, charIdx) : "\\";
						if (nextCh == "n")	   stringBuffer += "\n";
						else if (nextCh == "t")  stringBuffer += "\t";
						else if (nextCh == "r")  stringBuffer += "\r";
						else if (nextCh == "\\") stringBuffer += "\\";
						else if (nextCh == "'")  stringBuffer += "'";
						else if (nextCh == "\"") stringBuffer += "\"";
						else					 stringBuffer += nextCh;
					}
					else
					{
						stringBuffer += ch;
					}
				break;

				case kSingleQuotedString:
					// single quote terminates the current string
					if (ch == "'")
					{
						jobArgsArray.append(stringBuffer);
						stringBuffer.clear();
						state = kArgument;
					}
					else if (ch == "\\")
					{
						// escaped character
						MString nextCh = (++charIdx < jobArgsStr.numChars())
							? jobArgsStr.substringW(charIdx, charIdx) : "\\";
						if (nextCh == "n")	   stringBuffer += "\n";
						else if (nextCh == "t")  stringBuffer += "\t";
						else if (nextCh == "r")  stringBuffer += "\r";
						else if (nextCh == "\\") stringBuffer += "\\";
						else if (nextCh == "'")  stringBuffer += "'";
						else if (nextCh == "\"") stringBuffer += "\"";
						else					 stringBuffer += nextCh;
					}
					else
					{
						stringBuffer += ch;
					}
				break;
				}
			}

			// the rest of the argument
			if (stringBuffer.length() > 0)
			{
				jobArgsArray.append(stringBuffer);
			}
		}

		double startTime = oldCurTime.value();
		double endTime = oldCurTime.value();
		double strideTime = 1.0;
		bool hasRange = false;
		bool hasRoot = false;
		std::set <double> shutterSamples;
		std::string fileName;

		unsigned int numJobArgs = jobArgsArray.length();
		for (unsigned int i = 0; i < numJobArgs; ++i)
		{
			MString arg = jobArgsArray[i];
			arg.toLowerCase();

			if (arg == "-f" || arg == "-file")
			{
				if (i+1 >= numJobArgs)
				{
					MString err = MStringResource::getString( kInvalidArgFile, status );
					MGlobal::displayError(err);
					return MS::kFailure;
				}
				fileName = jobArgsArray[++i].asChar();
			} 

			else if (arg == "-fr" || arg == "-framerange")
			{
				if (i+2 >= numJobArgs || !jobArgsArray[i+1].isDouble() ||
					!jobArgsArray[i+2].isDouble())
				{
					MString err = MStringResource::getString( kInvalidArgFrameRange, status );
					MGlobal::displayError(err);
					return MS::kFailure;
				}

				hasRange = true;
				startTime = jobArgsArray[++i].asDouble();
				endTime = jobArgsArray[++i].asDouble();

				// make sure start frame is smaller or equal to endTime
				if (startTime > endTime)
				{
					double temp = startTime;
					startTime = endTime;
					endTime = temp;
				}
			}

			else if (arg == "-frs" || arg == "-framerelativesample")
			{
				if (i+1 >= numJobArgs || !jobArgsArray[i+1].isDouble())
				{
					MString err = MStringResource::getString( kInvalidArgFrameRelativeSample, status );
					MGlobal::displayError(err);
					return MS::kFailure;
				}
				shutterSamples.insert(jobArgsArray[++i].asDouble());
			}

			else if (arg == "-nn" || arg == "-nonormals")
			{
				jobArgs.noNormals = true;
			}

			else if (arg == "-ro" || arg == "-renderableonly")
			{
				jobArgs.excludeInvisible = true;
			}

			else if (arg == "-s" || arg == "-step")
			{
				if (i+1 >= numJobArgs || !jobArgsArray[i+1].isDouble())
				{
					MString err = MStringResource::getString( kInvalidArgStep, status );
					MGlobal::displayError(err);
					return MS::kFailure;
				}
				strideTime = jobArgsArray[++i].asDouble();
			}

			else if (arg == "-sl" || arg == "-selection")
			{
				jobArgs.useSelectionList = true;
			}

			else if (arg == "-sn" || arg == "-stripnamespaces")
			{
				if (i+1 >= numJobArgs || !jobArgsArray[i+1].isUnsigned())
				{
					// the strip all namespaces case
					// so we pick a very LARGE number
					jobArgs.stripNamespace = 0xffffffff;
				}
				else
				{
					jobArgs.stripNamespace = jobArgsArray[++i].asUnsigned();
				}
			}

			else if (arg == "-uv" || arg == "-uvwrite")
			{
				jobArgs.writeUVs = true;
			}

			else if (arg == "-wcs" || arg == "-writecolorsets")
			{
				jobArgs.writeColorSets = true;
			}

			else if (arg == "-wfs" || arg == "-writefacesets")
			{
				jobArgs.writeFaceSets = true;
			}

			else if (arg == "-ws" || arg == "-worldspace")
			{
				jobArgs.worldSpace = true;
			}

			else if (arg == "-wv" || arg == "-writevisibility")
			{
				jobArgs.writeVisibility = true;
			}

			else if (arg == "-mfc" || arg == "-melperframecallback")
			{
				if (i+1 >= numJobArgs)
				{
					MGlobal::displayError(
						"melPerFrameCallback incorrectly specified.");
					return MS::kFailure;
				}
				jobArgs.melPerFrameCallback = jobArgsArray[++i].asChar();
			}

			else if (arg == "-pfc" || arg == "-pythonperframecallback")
			{
				if (i+1 >= numJobArgs)
				{
					MString err = MStringResource::getString( kInvalidArgPythonPerframeCallback, status );
					MGlobal::displayError(err);
					return MS::kFailure;
				}
				jobArgs.pythonPerFrameCallback = jobArgsArray[++i].asChar();
			}

			else if (arg == "-mpc" || arg == "-melpostjobcallback")
			{
				if (i+1 >= numJobArgs)
				{
					MString err = MStringResource::getString( kInvalidArgMelPostJobCallback, status );
					MGlobal::displayError(err);
					return MS::kFailure;
				}
				jobArgs.melPostCallback = jobArgsArray[++i].asChar();
			}

			else if (arg == "-ppc" || arg == "-pythonpostjobcallback")
			{
				if (i+1 >= numJobArgs)
				{
					MString err = MStringResource::getString( kInvalidArgPythonPostJobCallback, status );
					MGlobal::displayError(err);
					return MS::kFailure;
				}
				jobArgs.pythonPostCallback = jobArgsArray[++i].asChar();
			}

			// geomArbParams - attribute filtering stuff
			else if (arg == "-atp" || arg == "-attrprefix")
			{
				if (i+1 >= numJobArgs)
				{
					MString err = MStringResource::getString( kInvalidArgAttrPrefix, status );
					MGlobal::displayError(err);
					return MS::kFailure;
				}
				jobArgs.prefixFilters.push_back(jobArgsArray[++i].asChar());
			}

			else if (arg == "-a" || arg == "-attr")
			{
				if (i+1 >= numJobArgs)
				{
					MString err = MStringResource::getString( kInvalidArgAttr, status );
					MGlobal::displayError(err);
					return MS::kFailure;
				}
				jobArgs.attribs.insert(jobArgsArray[++i].asChar());
			}

			// userProperties - attribute filtering stuff
			else if (arg == "-uatp" || arg == "-userattrprefix")
			{
				if (i+1 >= numJobArgs)
				{
					MString err = MStringResource::getString( kInvalidArgUserAttrPrefix, status );
					MGlobal::displayError(err);
					return MS::kFailure;
				}
				jobArgs.userPrefixFilters.push_back(jobArgsArray[++i].asChar());
			}

			else if (arg == "-u" || arg == "-userattr")
			{
				if (i+1 >= numJobArgs)
				{
					MGlobal::displayError("userAttr incorrectly specified.");
					return MS::kFailure;
				}
				jobArgs.userAttribs.insert(jobArgsArray[++i].asChar());
			}

			else if (arg == "-rt" || arg == "-root")
			{
				if (i+1 >= numJobArgs)
				{
					MGlobal::displayError("root incorrectly specified.");
					return MS::kFailure;
				}
				hasRoot = true;
				MString root = jobArgsArray[++i];

				MSelectionList sel;
				if (sel.add(root) != MS::kSuccess)
				{
					MString warn = root;
					warn += " could not be select, skipping.";
					MGlobal::displayWarning(warn);
					continue;
				}

				unsigned int numRoots = sel.length();
				for (unsigned int j = 0; j < numRoots; ++j)
				{
					MDagPath path;
					if (sel.getDagPath(j, path) != MS::kSuccess)
					{
						MString warn = path.fullPathName();
						warn += " (part of ";
						warn += root;
						warn += " ) not a DAG Node, skipping.";
						MGlobal::displayWarning(warn);
						continue;
					}
					jobArgs.dagPaths.insert(path);
				}
			}
			else if (arg == "-ef" || arg == "-eulerfilter")
			{
				jobArgs.filterEulerRotations = true;
			}
			else
			{
				MString warn = "Ignoring unsupported flag: ";
				warn += jobArgsArray[i];
				MGlobal::displayWarning(warn);
			}
		} //  for i

		if (fileName == "")
		{
			MString error = "-file not specified.";
			MGlobal::displayError(error);
			return MS::kFailure;
		}

		{
			MString fileRule, expandName;
			MString alembicFileRule = "alembicCache";
			MString alembicFilePath = "cache/alembic";

			MString queryFileRuleCmd;
			queryFileRuleCmd.format("workspace -q -fre \"^1s\"",
				alembicFileRule);

			MString queryFolderCmd;
			queryFolderCmd.format("workspace -en `workspace -q -fre \"^1s\"`",
				alembicFileRule);

			// query the file rule for alembic cache
			MGlobal::executeCommand(queryFileRuleCmd, fileRule);
			if (fileRule.length() > 0)
			{
				// we have alembic file rule, query the folder
				MGlobal::executeCommand(queryFolderCmd, expandName);
			}
			else
			{
				// alembic file rule does not exist, create it
				MString addFileRuleCmd;
				addFileRuleCmd.format("workspace -fr \"^1s\" \"^2s\"",
					alembicFileRule, alembicFilePath);
				MGlobal::executeCommand(addFileRuleCmd);

				// save the workspace. maya may discard file rules on exit
				MGlobal::executeCommand("workspace -s");

				// query the folder
				MGlobal::executeCommand(queryFolderCmd, expandName);
			}

			// resolve the expanded file rule
			if (expandName.length() == 0)
			{
				expandName = alembicFilePath;
			}

			// get the path to the alembic file rule
			MFileObject directory;
			directory.setRawFullName(expandName);
			MString directoryName = directory.resolvedFullName();

			// make sure the cache folder exists
			if (!directory.exists())
			{
				// create the cache folder
				MString createFolderCmd;
				createFolderCmd.format("sysFile -md \"^1s\"", directoryName);
				MGlobal::executeCommand(createFolderCmd);
			}

			// resolve the relative path
			MFileObject absoluteFile;
			absoluteFile.setRawFullName(fileName.c_str());
#if MAYA_API_VERSION < 201300
			if (absoluteFile.resolvedFullName() !=
				absoluteFile.expandedFullName())
			{
#else
			if (!MFileObject::isAbsolutePath(fileName.c_str())) {
#endif
				// this is a relative path
				MString absoluteFileName = directoryName + "/" +
					fileName.c_str();
				absoluteFile.setRawFullName(absoluteFileName);
				fileName = absoluteFile.resolvedFullName().asChar();
			}
			else
			{
				fileName = absoluteFile.resolvedFullName().asChar();
			}

			// check the path must exist before writing
			MFileObject absoluteFilePath;
			absoluteFilePath.setRawFullName(absoluteFile.path());
			if (!absoluteFilePath.exists()) {
				MString error;
				error.format("Path ^1s does not exist!", absoluteFilePath.resolvedFullName());
				MGlobal::displayError(error);
				return MS::kFailure;
			}

			// check the file is used by any AlembicNode in the scene
			MItDependencyNodes dgIter(MFn::kPluginDependNode);
			for (; !dgIter.isDone(); dgIter.next()) {
				MFnDependencyNode alembicNode(dgIter.thisNode());
				if (alembicNode.typeName() != "AlembicNode") {
					continue;
				}

				MPlug abcFilePlug = alembicNode.findPlug("abc_File");
				if (abcFilePlug.isNull()) {
					continue;
				}

				MFileObject alembicFile;
				alembicFile.setRawFullName(abcFilePlug.asString());
				if (!alembicFile.exists()) {
					continue;
				}

				if (alembicFile.resolvedFullName() == absoluteFile.resolvedFullName()) {
					MString error = "Can't export to an Alembic file which is in use.";
					MGlobal::displayError(error);
					return MS::kFailure;
				}
			}

			std::ofstream ofs(fileName.c_str());
			if (!ofs.is_open()) {
				MString error = MString("Can't write to file: ") + fileName.c_str();
				MGlobal::displayError(error);
				return MS::kFailure;
			}
			ofs.close();
		}

		if (shutterSamples.empty())
		{
			shutterSamples.insert(0.0);
		}

		if (jobArgs.prefixFilters.empty())
		{
			jobArgs.prefixFilters.push_back("ABC_");
		}

		// the list of frames written into the abc file
		std::set<double> transSamples;
		std::set <double>::const_iterator shutter;
		std::set <double>::const_iterator shutterStart = shutterSamples.begin();
		std::set <double>::const_iterator shutterEnd = shutterSamples.end();
		for (double frame = startTime; frame <= endTime; frame += strideTime)
		{
			for (shutter = shutterStart; shutter != shutterEnd; ++shutter)
			{
				double curFrame = *shutter + frame;
				transSamples.insert(curFrame);
			}
		}

		if (transSamples.empty())
		{
			transSamples.insert(startTime);
		}

		if (jobArgs.dagPaths.size() > 1)
		{
			// check for validity of the DagPath relationships complexity : n^2

			util::ShapeSet::const_iterator m, n;
			util::ShapeSet::const_iterator end = jobArgs.dagPaths.end();
			for (m = jobArgs.dagPaths.begin(); m != end; )
			{
				MDagPath path1 = *m;
				m++;
				for (n = m; n != end; n++)
				{
					MDagPath path2 = *n;
					if (util::isAncestorDescendentRelationship(path1,path2))
					{
						MString errorMsg = path1.fullPathName();
						errorMsg += " and ";
						errorMsg += path2.fullPathName();
						errorMsg += " have an ancestor relationship.";
						MGlobal::displayError(errorMsg);
						return MS::kFailure;
					}
				}  // for n
			}  // for m
		}
		// no root is specified, and we aren't using a selection
		// so we'll try to translate the whole Maya scene by using all
		// children of the world as roots.
		else if (!hasRoot && !jobArgs.useSelectionList)
		{
			MSelectionList sel;
#if MAYA_API_VERSION >= 201100
			sel.add("|*", true);
#else
			// older versions of Maya will not be able to find top level nodes
			// within namespaces
			sel.add("|*");
#endif
			unsigned int numRoots = sel.length();
			for (unsigned int i = 0; i < numRoots; ++i)
			{
				MDagPath path;
				sel.getDagPath(i, path);
				jobArgs.dagPaths.insert(path);
			}
		}
		else if (hasRoot && jobArgs.dagPaths.empty())
		{
			MString errorMsg = "No valid root nodes were specified.";
			MGlobal::displayError(errorMsg);
			return MS::kFailure;
		}
		else if (jobArgs.useSelectionList)
		{
			MSelectionList activeList;
			MGlobal::getActiveSelectionList(activeList);
			if (activeList.length() == 0)
			{
				MString errorMsg =
					"-selection specified but nothing is actively selected.";
				MGlobal::displayError(errorMsg);
				return MS::kFailure;
			}
		}

		AbcA::TimeSamplingPtr transTime;

		std::vector<double> samples;
		for (shutter = shutterStart; shutter != shutterEnd; ++shutter)
		{
			samples.push_back((startTime + *shutter) * util::spf());
		}

		if (hasRange)
		{
			transTime.reset(new AbcA::TimeSampling(AbcA::TimeSamplingType(
				static_cast<Alembic::Util::uint32_t>(samples.size()),
				strideTime * util::spf()), samples));
		}
		else
		{
			transTime.reset(new AbcA::TimeSampling());
		}

		AbcWriteJobPtr job(new AbcWriteJob(fileName.c_str(),
			transSamples, transTime, jobArgs));

	   jobList.push_front(job);

		// make sure we add additional whole frames, if we arent skipping
		// the inbetween ones
		if (!skipFrame && !allFrameRange.empty())
		{
			double localMin = *(transSamples.begin());
			std::set<double>::iterator last = transSamples.end();
			last--;
			double localMax = *last;

			double globalMin = *(allFrameRange.begin());
			last = allFrameRange.end();
			last--;
			double globalMax = *last;

			// if the min of our current frame range is beyond
			// what we know about, pad a few more frames
			if (localMin > globalMax)
			{
				for (double f = globalMax; f < localMin; f++)
				{
					allFrameRange.insert(f);
				}
			}

			// if the max of our current frame range is beyond
			// what we know about, pad a few more frames
			if (localMax < globalMin)
			{
				for (double f = localMax; f < globalMin; f++)
				{
					allFrameRange.insert(f);
				}
			}
		}

		// right now we just copy over the translation samples since
		// they are guaranteed to contain all the geometry samples
		allFrameRange.insert(transSamples.begin(), transSamples.end());
	}

	// add extra evaluation run up, if necessary
	if (startEvaluationTime != DBL_MAX && !allFrameRange.empty())
	{
		double firstFrame = *allFrameRange.begin();
		for (double f = startEvaluationTime; f < firstFrame; ++f)
		{
			allFrameRange.insert(f);
		}
	}

	std::set<double>::iterator it = allFrameRange.begin();
	std::set<double>::iterator itEnd = allFrameRange.end();

	MComputation computation;
	computation.beginComputation();

	// loop through every frame in the list, if a job has that frame in it's
	// list of transform or shape frames, then it will write out data and
	// call the perFrameCallback, if that frame is also the last one it has
	// to work on then it will also call the postCallback.
	// If it doesn't have this frame, then it does nothing

	MTimer timer;

	for (; it != itEnd; it++)
	{
		timer.beginTimer();

		MGlobal::viewFrame(*it);
		std::list< AbcWriteJobPtr >::iterator j = jobList.begin();
		std::list< AbcWriteJobPtr >::iterator jend = jobList.end();
		while (j != jend)
		{
			if (computation.isInterruptRequested())
				return MS::kFailure;

			bool lastFrame = (*j)->eval(*it);

			if (lastFrame)
			{
				j = jobList.erase(j);
			}
			else
				j++;
		}

		timer.endTimer();

		if (verbose)
		{
			double frame = *it;
			MString info,arg1,arg2;
			arg1.set(frame);
			arg2.set(timer.elapsedTime());
			info.format( "processed frame: ^1s in ^2s seconds", arg1, arg2 );
			MGlobal::displayInfo(info);
		}


	}
	computation.endComputation();

	// set the time back
	MGlobal::viewFrame(oldCurTime);

	return MS::kSuccess;
}
catch (Alembic::Util::Exception & e)
{
	MString theError("Alembic Exception encountered: ");
	theError += e.what();
	MGlobal::displayError(theError);
	return MS::kFailure;
}
catch (std::exception & e)
{
	MString theError("std::exception encountered: ");
	theError += e.what();
	MGlobal::displayError(theError);
	return MS::kFailure;
}

}
Example #4
0
    void toPython()
    {
        RefElem RefConv;

        std::ostringstream ostr;

        ostr << getName() << "_" << getPointsInfo() << ".py";

        std::ofstream ofs( ostr.str().c_str() );

        ofs << "from pyx import *\n";

        ofs << "p=path.path(";

        for ( uint16_type i = 0; i < Convex::numEdges; ++i )
        {
            for ( uint16_type  j = 0; j < 2; ++j )
            {
                node_type x( 2 );

                if ( Convex::nRealDim == 1 )
                {
                    x( 0 ) = RefConv.edgeVertex( i,j )( 0 );
                    x( 1 ) = value_type( 0 );
                }

                if ( Convex::nRealDim == 2 )
                {
                    x = RefConv.edgeVertex( i, j );
                }

                if ( Convex::nRealDim == 3 )
                {
                    x( 0 ) = RefConv.edgeVertex( i, j )( 0 )+RefConv.edgeVertex( i, j )( 1 )*std::cos( M_PI/4 );
                    x( 1 ) = RefConv.edgeVertex( i, j )( 2 )+RefConv.edgeVertex( i, j )( 1 )*std::sin( M_PI/4 );
                }

                if ( j == 0 )
                    ofs << "path.moveto(" << double( x( 0 ) )<< "," << double( x( 1 ) ) << "),\n";

                else if ( j == 1 )
                    ofs << "path.lineto(" << double( x( 0 ) )<< "," << double( x( 1 ) ) << "),\n";
            }
        }

        ofs << "path.closepath() )\n";

        ofs << "text.set(mode=\"latex\")\n"
            << "c = canvas.canvas()\n"
            << "c.stroke(p, [style.linewidth.Thin])\n";

        for ( uint16_type i = 0; i < nPoints(); ++i )
        {
            node_type x( 2 );

            if ( Convex::nRealDim == 1 )
            {
                x( 0 ) = this->point( i )( 0 );
                x( 1 ) = value_type( 0 );
            }

            if ( Convex::nRealDim == 2 )
            {
                x = this->point( i );
            }

            if ( Convex::nRealDim == 3 )
            {
                x( 0 ) = this->point( i )( 0 ) + this->point( i )( 1 )*std::cos( M_PI/4 );
                x( 1 ) = this->point( i )( 2 ) + this->point( i )( 1 )*std::sin( M_PI/4 );
            }


            ofs << "c.fill ( path.circle(" << double( x( 0 ) ) << "," << double( x( 1 ) )<< ", 0.02 ),[deco.filled([color.rgb.red])])\n";
            ofs << "c.text( " << double( x( 0 )+0.025 ) << "," << double( x( 1 )+0.025 )<< ", r\"{\\scriptsize " << i << "}\")\n";
        }

        ofs << "c.writeEPSfile(\"" << getName() << "_" << getPointsInfo()
            << "\", document.paperformat.A4)\n";
    }
std::pair<bool /*success*/, std::string /* message */>
    ivy_engine::startup(
            const std::string& output_folder_root,
            const std::string& test_name,
            const std::string& ivyscript_filename,
            const std::string& hosts_string,
            const std::string& select_available_test_LUNs)
{
    std::string api_log_entry;
    {
        std::ostringstream o;
        o << "ivy engine API startup("
            << "output_folder_root = "   << output_folder_root
            << ", test_name = "          << test_name
            << ", ivyscript_filename = " << ivyscript_filename
            << ", test_hosts = "         << hosts_string
            << ", select = "             << select_available_test_LUNs
            << ")" << std::endl;
        std::cout << o.str();
        api_log_entry = o.str();
    }

    outputFolderRoot = output_folder_root;
    testName = test_name;

    struct stat struct_stat;

    if( stat(outputFolderRoot.c_str(),&struct_stat))
    {
        std::ostringstream o;
        o << "<Error> directory \"" << outputFolderRoot << "\" does not exist." << std::endl;
        std::cout << o.str();
        return std::make_pair(false,o.str());
    }

    if(!S_ISDIR(struct_stat.st_mode))
    {
        std::ostringstream o;
        o << "<Error> \"" << outputFolderRoot << "\" is not a directory." << std::endl;
        std::cout << o.str();
        return std::make_pair(false,o.str());
    }

    testFolder=outputFolderRoot + std::string("/") + testName;

    if(0==stat(testFolder.c_str(),&struct_stat))  // output folder already exists
    {
        if(!S_ISDIR(struct_stat.st_mode))
        {
            std::ostringstream o;
            o << "<Error> Output folder for this test run \"" << testFolder << "\" already exists but is not a directory." << std::endl;
            std::cout << o.str();
            return std::make_pair(false,o.str());
        }
        // output folder already exists and is a directory, so we delete it to make a fresh one.
        if (0 == system((std::string("rm -rf ")+testFolder).c_str()))   // ugly but easy.
        {
            std::ostringstream o;
            o << "      Deleted pre-existing folder \"" << testFolder << "\"." << std::endl;
            std::cout << o.str();

        }
        else
        {
            std::ostringstream o;
            o << "<Error> Failed trying to delete previously existing version of test run output folder \"" << testFolder << "\"." << std::endl;
            std::cout << o.str();
            return std::make_pair(false,o.str());
        }

    }

    if (mkdir(testFolder.c_str(),S_IRWXU | S_IRWXG | S_IRWXO))
    {
        std::ostringstream o;
        o << "<Error> Failed trying to create output folder \"" << testFolder << "\" << errno = " << errno << " " << strerror(errno) << std::endl;
        std::cout << o.str();
        return std::make_pair(false,o.str());
    }

    std::cout << "      Created test run output folder \"" << testFolder << "\"." << std::endl;

    if (mkdir((testFolder+std::string("/logs")).c_str(),S_IRWXU | S_IRWXG | S_IRWXO))
    {
        std::ostringstream o;
        o << "<Error> - Failed trying to create logs subfolder in output folder \"" << testFolder << "\" << errno = " << errno << " " << strerror(errno) << std::endl;
        std::cout << o.str();
        return std::make_pair(false,o.str());
    }

    masterlogfile = testFolder + std::string("/logs/log.ivymaster.txt");
    ivy_engine_logfile = testFolder + std::string("/logs/ivy_engine_API_calls.txt");


    log(masterlogfile,      api_log_entry);
    log(ivy_engine_logfile, api_log_entry);

    {
        std::ostringstream o;
        o << "ivy version " << ivy_version << " build date " << IVYBUILDDATE << " starting." << std::endl << std::endl;
        log(masterlogfile,o.str());
    }

    if (!routine_logging)
    {
        std::ostringstream o;
        o << "For logging of routine (non-error) events, and to record the conversation with each ivydriver/ivy_cmddev, use the ivy -log command line option, like \"ivy -log a.ivyscript\".\n\n";
        log(masterlogfile,o.str());
    }

    if (ivyscript_filename.size() > 0)
    {
        std::string copyivyscriptcmd = std::string("cp -p ") + ivyscript_filename + std::string(" ") +
                                       testFolder + std::string("/") + testName + std::string(".ivyscript");
        if (0!=system(copyivyscriptcmd.c_str()))   // now getting lazy, but purist maintainers could write C++ code to do this.
        {
            std::ostringstream o;
            o << "<Error> Failed trying to copy input ivyscript to output folder: \"" << copyivyscriptcmd << "\"." << std::endl;
            log(masterlogfile,o.str());
            std::cout << o.str();
            return std::make_pair(false,o.str());
        }
    }

    std::pair<bool,std::string> retval = rollups.initialize();
    if (!retval.first)
    {
        std::ostringstream o;
        o << "<Error> Internal programming error - failed initializing rollups in ivymaster.cpp saying: " << retval.second << std::endl;
        log(masterlogfile,o.str());
        std::cout << o.str();
        return std::make_pair(false,o.str());
    }

    test_start_time.setToNow();

    initialize_io_time_clip_levels();

    availableControllers[toLower(std::string("measure"))] = &the_dfc;

    auto rv = random_steady_template.setParameter("iosequencer=random_steady");
    if ( ! rv.first)
    {
        std::ostringstream o;
        o << "<Error> dreaded internal programming error - ivymaster startup - failed trying to set the default random steady I/O generator template - " << rv.second << std::endl;
        std::cout << o.str();
        return std::make_pair(false,o.str());
    }

    rv = random_independent_template.setParameter("iosequencer=random_independent");
    if ( !rv.first )
    {
        std::ostringstream o;
        o << "<Error> dreaded internal programming error - ivymaster startup - failed trying to set the default random independent I/O generator template - " << rv.second << std::endl;
        std::cout << o.str();
        return std::make_pair(false,o.str());
    }

    rv = sequential_template.setParameter("iosequencer=sequential");
    if ( !rv.first )
    {
        std::ostringstream o;
        o << "<Error> dreaded internal programming error - ivymaster startup - failed trying to set the default sequential I/O generator template - " << rv.second << std::endl;
        std::cout << o.str();
        return std::make_pair(false,o.str());
    }

    hosts_list test_hosts;
    if (!test_hosts.compile(hosts_string))
    {
        std::ostringstream o;

        o << "<Error> failed parsing list of test hosts \"" << hosts_string << "\" - " << test_hosts.message;
        return std::make_pair(false,o.str());
    }

    for (auto& s: test_hosts.hosts) { hosts.push_back(s);}

    write_clear_script();  // This writes a shell script to run the clear_hung_ivy_threads executable on all involved hosts - handy if you are a developer and you mess things up

    if (hosts.size() == 0)
    {
        std::ostringstream o;

        o << "<Error> ivy engine startup failed - No hosts specified." << std::endl;
        return std::make_pair(false,o.str());
    }

    JSON_select select;

    if (!select.compile_JSON_select(select_available_test_LUNs))
    {
        std::ostringstream o;
        o << "<Error> ivy engine startup failure - invalid select expression for available test LUNs \"" << select_available_test_LUNs << "\" - error message follows: " << select.error_message << std::endl;
        log(masterlogfile,o.str());
        std::cout << o.str();
        kill_subthreads_and_exit();
    }

    { std::ostringstream o; o << "select " << select << std::endl; std::cout << o.str(); log(masterlogfile,o.str()); }

    if
    (
        (!select.contains_attribute("serial_number"))
        &&
        (!select.contains_attribute("vendor"))
    )
    {
        std::ostringstream o;

        o << "<Error> ivy engine startup failure -  select for available test LUNs \"" << select_available_test_LUNs << "\" - must specify either \"serial_number\" or \"vendor\"." << std::endl;
        return std::make_pair(false,o.str());
    }

    for ( auto& host : hosts )
    {
        if (routine_logging) { std::cout << "Starting thread for " << host << std::endl; }
        log( masterlogfile, std::string("Starting thread for ") + host + std::string("\n") );

        pipe_driver_subthread* p_pipe_driver_subthread = new pipe_driver_subthread
            (
                host,
                outputFolderRoot,
                testName,
                testFolder+std::string("/logs")
            );
        host_subthread_pointers[host] = p_pipe_driver_subthread;
        threads.push_back(std::thread(invokeThread,p_pipe_driver_subthread));
    }
    ofstream ahl(testFolder+std::string("/all_discovered_LUNs.txt"));
    ofstream ahl_csv(testFolder+std::string("/all_discovered_LUNs.csv"));

    {
        std::ostringstream o;
        o << std::endl << "Note:" << std::endl
            << "Sometimes the ssh command to start up ivydriver on a test host can take a long time when waiting for DNS timeouts.  "
            << "This can be speeded up by editing /etc/nsswitch.conf / resolv.conf to use /etc/hosts first, or options for the sshd daemon can be edited; search for \"ssh login timeout\"." << std::endl << std::endl;
        std::cout << o.str();
        log(masterlogfile,o.str());
    }

    bool first_host {true};

    for (auto&  pear : host_subthread_pointers)
    {
        {
            std::unique_lock<std::mutex> u_lk(pear.second->master_slave_lk);

            std::chrono::system_clock::time_point leftnow {std::chrono::system_clock::now()};
            if
            (
                pear.second->master_slave_cv.wait_until
                (
                    u_lk,
                    leftnow + std::chrono::seconds(ivy_ssh_timeout),
                    [&pear]() { return pear.second->startupComplete || pear.second->dead; }
                )
            )
            {
                if (pear.second->startupSuccessful)
                {
                    std::ostringstream o;
                    o << "pipe_driver_subthread successful fireup for host " << pear.first << std::endl;
                    std::cout << o.str();
                    log(masterlogfile,o.str());
                }
                else
                {
                    std::ostringstream o;
                    o << "Aborting - unsuccessful startup for ivydriver on host " << pear.first << ".  Reason: \"" << pear.second->commandErrorMessage << "\"." << std::endl;
                    o << std::endl << "Usually if try to run ivy again, it will work the next time.  Don\'t know why this happens." << std::endl;
                    o << std::endl << "Run the \"clear_hung_ivy_threads.sh\" script to clear any hung ivy / ivydriver / ivy_cmddev threads on the ivy master host and all test hosts." << std::endl;
                    std::cout << o.str();
                    log(masterlogfile,o.str());
                    u_lk.unlock();
                    kill_subthreads_and_exit(); // doesn't return
                }

            }
            else
            {
                std::ostringstream o;
                o << "Aborting - timeout waiting " << timeout_seconds << " seconds for pipe_driver_subthread fireup for host " << pear.first << std::endl;
                std::cout << o.str();
                log(masterlogfile,o.str());
                u_lk.unlock();
                kill_subthreads_and_exit(); // doesn't return
            }
        }


        {ostringstream o; o << "Subthread for \"" << pear.first << "\" posted startupComplete." << std::endl; std::cout  << o.str(); log(masterlogfile,o.str());}

        for (auto& pLUN : pear.second->thisHostLUNs.LUNpointers)
        {
            allDiscoveredLUNs.LUNpointers.push_back(pLUN);
            ahl << pLUN->toString() << std::endl;
        }
//*debug*/{ostringstream o; o << "Loop for \"" << pear.first << "\" about to copy on sample LUN." << std::endl; std::cout  << o.str(); log(masterlogfile,o.str());}

//*debug*/{ostringstream o; o << "Loop for \"" << pear.first << "\" HostSampleLUN=" << pear.second->HostSampleLUN.toString() << std::endl; std::cout  << o.str(); log(masterlogfile,o.str());}

        TheSampleLUN.copyOntoMe(&pear.second->HostSampleLUN);

        if (first_host) {ahl_csv << pear.second->lun_csv_header;}
        ahl_csv << pear.second->lun_csv_body.str();

        first_host = false;
    }
    ahl.close();
    ahl_csv.close();
    allThreadsSentTheLUNsTheySee=true;
    /*debug*/
    if (routine_logging){
        ostringstream o;
        o <<"allDiscoveredLUNs contains:"<<std::endl<< allDiscoveredLUNs.toString() <<std::endl;
        //std::cout<<o.str();
        log(masterlogfile,o.str());
    }
    else
    {
        ostringstream o;
        o <<"Discovered " << allDiscoveredLUNs.LUNpointers.size() << " LUNs on the test hosts." << std::endl;
        //std::cout<<o.str();
        log(masterlogfile,o.str());
    }

    if (0 == allDiscoveredLUNs.LUNpointers.size())
    {
        std::ostringstream o;
        o << ivyscript_line_number << ": \"" << ivyscript_line << "\"" << std::endl;
        o << "No LUNs were found on any of the hosts." << std::endl;
        std::cout << o.str();
        log (masterlogfile,o.str());
        ivyscriptIfstream.close();
        kill_subthreads_and_exit();
    }


    allDiscoveredLUNs.split_out_command_devices_into(commandDeviceLUNs);

    /*debug*/
    {
        ostringstream o;
        o <<"commandDeviceLUNs contains:"<<std::endl<< commandDeviceLUNs.toString() <<std::endl;
        //std::cout<<o.str();
        log(masterlogfile,o.str());
    }

    for (LUN* pLUN : allDiscoveredLUNs.LUNpointers)
    {
        if (select.matches(pLUN))
        {
            if (     pLUN->attribute_value_matches("ldev",      "FF:FF"         )
                &&   pLUN->attribute_value_matches("ldev_type", ""              )
                && ( pLUN->attribute_value_matches("product",   "DISK-SUBSYSTEM") || pLUN->attribute_value_matches("product","OPEN-V") ) )
            {
                ; // Ignore "phantom LUNs" that have been deleted on the subsystem but for which a /dev/sdxxx entry still exists.
            }
            else if ( pLUN->attribute_value_matches("ldev",      "FF:FF")
                &&    pLUN->attribute_value_matches("ldev_type", "phantom LUN")  )
            {
                ; // Ignore "phantom LUNs" that have been deleted on the subsystem but for which a /dev/sdxxx entry still exists.
            }
            else
            {
                availableTestLUNs.LUNpointers.push_back(pLUN);
            }
        }
    }


    if ( 0 == availableTestLUNs.LUNpointers.size() )
    {
        std::ostringstream o;
        o << "No LUNs matched [hosts] statement [select] clause." << std::endl;
        //p_Select->display("",o);

        std::cout << o.str();
        log(masterlogfile,o.str());
        kill_subthreads_and_exit();
    }

    for (auto& pLUN : availableTestLUNs.LUNpointers) pLUN -> createNicknames();

    // Now we create the Subsystem objects

    for (auto& pLUN : availableTestLUNs.LUNpointers)
    {
        std::string serial_number = pLUN->attribute_value(std::string("serial_number"));
        trim(serial_number);

        Subsystem* pSubsystem;

        auto subsystemIt = subsystems.find(serial_number);
        if (subsystems.end() == subsystemIt)
        {
            std::string product = pLUN->attribute_value("product");
            trim(product);
            if (0 == product.compare(std::string("OPEN-V")))
            {
                pSubsystem = new Hitachi_RAID_subsystem(serial_number, pLUN);
            }
            else
            {
                pSubsystem = new Subsystem(serial_number);
            }
            subsystems[serial_number] = pSubsystem;
        }
        else
        {
            pSubsystem = (*subsystemIt).second;
        }
        pSubsystem->add(pLUN);
    }

    // For each subsystem that the available test LUNs map to,
    // for the first available real-time interface,
    // start up the appropriate subthread to drive that interface.

    // Which means - for each Hitachi RAID subsystem, use the first command device
    // in commandDeviceLUNs that leads to that subsystem and start an
    // pipe_driver_subthread, which fires up the ivy_cmddev executable remotely via ssh
    // communicating via stdin/stdout pipes the same way we communicate with remote ivydriver instances.

    for (auto& pear : subsystems)
    {
        Subsystem* pSubsystem = pear.second;

        if (0 == std::string("Hitachi RAID").compare(pSubsystem->type()))
        {
            Hitachi_RAID_subsystem* pRAIDsubsystem {(Hitachi_RAID_subsystem*) pSubsystem};
            bool have_cmd_dev_this_subsystem = false;

            if (m_s.use_command_device) for (auto& pL : commandDeviceLUNs.LUNpointers)
                // for each command device LUN as candidate to match as first command device for this subsystem.
            {
                if (0 == pSubsystem->serial_number.compare(pL->attribute_value("serial_number")))
                    // we have found the first command device for this subsystem
                {
                    // fire up command device thread

                    std::string cmd_dev_description;

                    {
                        std::ostringstream o;
                        o << "command device for " << pL->attribute_value("Hitachi_product") << " " << pL->attribute_value("HDS_product")
                            <<  " serial number " << pSubsystem->serial_number
                            << " on host = " << pL->attribute_value("ivyscript_hostname")
                            << ", subsystem port = " << pL->attribute_value("port")
                            << ", LDEV = " << pL->attribute_value("LDEV")
                            << std::endl;
                        cmd_dev_description = o.str();
                    }

                    std::string cmddevLDEV = pL->attribute_value("LDEV");
                    if (cmddevLDEV.length() >= 5 && ':' == cmddevLDEV[2]) cmddevLDEV.erase(2,1);

                    std::ostringstream o;
                    o << "Connecting to " << cmd_dev_description << std::endl;
                    std::cout << o.str();
                    log(masterlogfile,o.str());

                    pipe_driver_subthread* p_pipe_driver_subthread = new pipe_driver_subthread(

                        pL->attribute_value("ivyscript_hostname")
                        , outputFolderRoot
                        , testName,
                        testFolder+std::string("/logs")
                    );

                    p_pipe_driver_subthread->pCmdDevLUN = pL;  // Seeing this set tells the subthread it's running a command device.

                    p_pipe_driver_subthread->p_Hitachi_RAID_subsystem = pRAIDsubsystem;

                    pRAIDsubsystem->command_device_description = cmd_dev_description;

                    pRAIDsubsystem->pRMLIBthread=p_pipe_driver_subthread;

                    command_device_subthread_pointers[pSubsystem->serial_number] = p_pipe_driver_subthread;

                    ivymaster_RMLIB_threads.push_back(std::thread(invokeThread,p_pipe_driver_subthread));
                    // Note: I wasn't sure, since std::thread is not copyable but is moveable, how to handle
                    //       the case when the command device doesn't start up correctly.  So in the interest of
                    //       time, I left any unsuccessful-startup command device threads in moribund state
                    //       in ivymaster_RMLIB_threads to be joined when ivy shuts down.

                    // wait with timeout for thread status to show "startupComplete", i.e. waiting for command;

                    {
                        std::unique_lock<std::mutex> u_lk(p_pipe_driver_subthread->master_slave_lk);
                        std::chrono::system_clock::time_point leftnow {std::chrono::system_clock::now()};

                        if
                        (
                            p_pipe_driver_subthread->master_slave_cv.wait_until
                            (
                                u_lk,
                                leftnow + std::chrono::seconds(ivy_ssh_timeout),
                                [&p_pipe_driver_subthread](){return p_pipe_driver_subthread->startupComplete || p_pipe_driver_subthread->dead;}
                        )
                    )
                        {
                            if (p_pipe_driver_subthread->startupSuccessful)
                            {
                                std::ostringstream o;
                                o << "ivy_cmddev pipe_driver_subthread successful fireup for subsystem " << pSubsystem->serial_number << std::endl;
                                std::cout << o.str();
                                log(masterlogfile,o.str());
                                haveCmdDev = true;
                                have_cmd_dev_this_subsystem = true;
                            }
                            else
                            {
                                std::ostringstream o;
                                o   << "Unsuccessful startup for command device = " << cmd_dev_description << std::endl
                                    << "Reason - " <<  p_pipe_driver_subthread->commandErrorMessage << std::endl;
                                std::cout << o.str();
                                log(masterlogfile,o.str());
                                pRAIDsubsystem->command_device_description.clear();
                                pRAIDsubsystem->pRMLIBthread=nullptr;
                            }
                        }
                        else
                        {
                            std::ostringstream o;
                            o   << "Timeout waiting " << timeout_seconds << " seconds for for startup of command device = " << cmd_dev_description << std::endl;
                            std::cout << o.str();
                            log(masterlogfile,o.str());
                            pRAIDsubsystem->command_device_description.clear();
                            pRAIDsubsystem->pRMLIBthread=nullptr;
                        }
                    }

                    if (!have_cmd_dev_this_subsystem) continue;  // This command device did not start up OK - try the next one if we have another to the same subsystem.
                                                  // Maybe there is a command device perhaps on a different host that does have RMLIB installed,
                                                  // does have a valid license key installed, and does have the ivy_cmddev executable.


                    // Command device reports startup complete

                    // gather config

                    ivytime config_gather_start;
                    config_gather_start.setToNow();
                    std::chrono::system_clock::time_point
                    start_getconfig_time_point { std::chrono::system_clock::now() };

                    {
                        std::unique_lock<std::mutex> u_lk(p_pipe_driver_subthread->master_slave_lk);
                        p_pipe_driver_subthread->commandString = std::string("get config");
                        p_pipe_driver_subthread->command=true;
                        p_pipe_driver_subthread->commandComplete=false;
                        p_pipe_driver_subthread->commandSuccess=false;
                        p_pipe_driver_subthread->commandErrorMessage.clear();

                        {
                            std::ostringstream o;
                            o << "Posted \"get config\" to thread for subsystem serial " << pRAIDsubsystem->serial_number << " managed on host " << p_pipe_driver_subthread->ivyscript_hostname << '.' << std::endl;
                            log(masterlogfile,o.str());
                        }
                    }
                    p_pipe_driver_subthread->master_slave_cv.notify_all();

                    {
                        std::unique_lock<std::mutex> u_lk(p_pipe_driver_subthread->master_slave_lk);

                        if
                        (
                            p_pipe_driver_subthread->master_slave_cv.wait_until
                            (
                                u_lk,
                                start_getconfig_time_point + std::chrono::seconds(get_config_timeout_seconds /* see ivydefines.h */),
                                [&p_pipe_driver_subthread](){ return p_pipe_driver_subthread->commandComplete || p_pipe_driver_subthread->dead; }
                            )
                        )
                        {
                            if (!p_pipe_driver_subthread->commandSuccess)
                            {
                                std::ostringstream o;
                                o << "\"get config\" to thread for subsystem serial " << pRAIDsubsystem->serial_number
                                  << " managed on host " << p_pipe_driver_subthread->ivyscript_hostname << " failed.  Aborting." << std::endl;
                                log(masterlogfile,o.str());
                                kill_subthreads_and_exit();
                            }

                            ivytime config_gather_complete;
                            config_gather_complete.setToNow();

                            pRAIDsubsystem->config_gather_time  = config_gather_complete - config_gather_start;

                            {
                                std::ostringstream o;
                                o << "\"get config\" reported complete with duration " << pRAIDsubsystem->config_gather_time.format_as_duration_HMMSSns()
                                  << " by thread for subsystem serial " << pRAIDsubsystem->serial_number << " managed on host " << p_pipe_driver_subthread->ivyscript_hostname << '.' << std::endl;
                                log(masterlogfile,o.str());
                            }
                        }
                        else // timeout
                        {
                            std::ostringstream o;
                            o << "Aborting - timeout waiting " << get_config_timeout_seconds
                              << " seconds for pipe_driver_subthread for subsystem " << pRAIDsubsystem->serial_number
                              << " managed on host " << p_pipe_driver_subthread->ivyscript_hostname
                              << " to complete a \"get config\"." <<  std::endl;
                            std::cout << o.str();
                            log(masterlogfile,o.str());
                            u_lk.unlock();
                            kill_subthreads_and_exit();
                        }
                    }

                    // post process after gather to augment available test LUN attributes with LDEV attributes from the config gather

                    for (auto pLUN : availableTestLUNs.LUNpointers)
                    {
                        if ( 0 == std::string("Hitachi RAID").compare(pSubsystem->type())  &&  0 == pSubsystem->serial_number.compare(pLUN->attribute_value("serial_number")))
                        {

                            // for each test LUN, if we are processing a Hitachi RAID subsystem with a given serial number and the test LUN serial_number matches the subsystem
                            // 1) if CLPR is non-empty add the <CLPR,serial_number> pair to cooldown_WP_watch_set
                            // 2) copy the LDEV's RMLIB attributes to the test LUN.
                            // put a suffix "_RMLIB" if the test LUN already has the attribute name (from the SCSI Inquiry LUN lister tool" showluns.sh").

                            if (0 < pLUN->attribute_value("CLPR").length())
                            {
                                cooldown_WP_watch_set.insert(std::make_pair(pLUN->attribute_value("CLPR"),pSubsystem));
                            }


                            // Copy the LDEV attributes obtained from a command device to the corresponding available test LUN,
                            // appending "_RMLIB" upon attribute name collisions.

                            // NOTE - in the LUN object all map keys are first translated to lower case upon insertion.
                            //        It is advised to use the LUN's own functions to do lookups, attribute value matching, etc.
                            //        as then you won't need to worry about case sensitivity of attribute names.

                            // NOTE2 - The data returned by ivy_cmddev for a "get config" command has attribute names like LDEV
                            //         in upper case and the LDEV attribute values like 00:FF are provided in upper case.


                            if (!pLUN->contains_attribute_name(std::string("ldev")))
                            {
                                std::ostringstream o;
                                o << "Aborting - available test LUN matched on Hitachi RAID subsystem serial number " << pSubsystem->serial_number
                                  << ", but the LUN did have the \"ldev\" attribute." <<  std::endl
                                  << "  LUN =" << pLUN->toString() <<  std::endl;
                                std::cout << o.str();
                                log(masterlogfile,o.str());
                                kill_subthreads_and_exit();
                            }

                            std::string LUN_ldev = pLUN->attribute_value(std::string("ldev"));

                            if (0==LUN_ldev.size())
                            {
                                std::ostringstream o;
                                o << "Aborting - available test LUN matched on Hitachi RAID subsystem serial number " << pSubsystem->serial_number
                                  << ", but the LUN's \"ldev\" attribute value was the null string." <<  std::endl
                                  << "  LUN =" << pLUN->toString() <<  std::endl;
                                std::cout << o.str();
                                log(masterlogfile,o.str());
                                kill_subthreads_and_exit();
                            }

                            auto subsystemLDEVit = pRAIDsubsystem->configGatherData.data.find(std::string("LDEV"));
                            if (pRAIDsubsystem->configGatherData.data.end() == subsystemLDEVit)
                            {
                                std::ostringstream o;
                                o << "Aborting - available test LUN matched on Hitachi RAID subsystem serial number " << pSubsystem->serial_number
                                  << ", but the subsystem configuration data from a command device didn\'t have \"LDEV\" element type." <<  std::endl
                                  << "  LUN =" << pLUN->toString() <<  std::endl;
                                std::cout << o.str();
                                log(masterlogfile,o.str());
                                kill_subthreads_and_exit();
                            }

                            std::string cmddev_LDEV = toUpper(LUN_ldev);

                            auto subsystemLDEVinstanceIt = (*subsystemLDEVit).second.find(cmddev_LDEV);
                            if ((*subsystemLDEVit).second.end() == subsystemLDEVinstanceIt)
                            {
                                std::ostringstream o;
                                o << "Aborting - available test LUN matched on Hitachi RAID subsystem serial number " << pSubsystem->serial_number
                                  << ", but the subsystem didn\'t have the \"LDEV\" instance \"" << cmddev_LDEV << "\"." <<  std::endl
                                  << "  LUN =" << pLUN->toString() <<  std::endl;
                                std::cout << o.str();
                                log(masterlogfile,o.str());
                                kill_subthreads_and_exit();
                            }

                            for (auto& pear : (*subsystemLDEVinstanceIt).second)
                            {

                                // To reduce clutter, upon an attribute name collision, meaning that both the SCSI Inquiry-based LUN Lister tool like showluns.sh
                                // and the RMLIB API-based command device data returned an attribute name that when translated to lower case was the same,
                                // then if the attribute values from either side are the same when translated to lower case and with leading/trailing
                                // blanks removed, we don't alter the existing attribute value, and the RMLIB API value is discarded.

                                // If RMLIB returned a substantially different value for the same metric, then we create a new attribute name
                                // by appending "_rmlib" and store the RMLIB value there.

                                // pear is std::map<std::string,metric_value>

                                std::string attribute_name = toLower(pear.first);
                                std::string attribute_value = pear.second.string_value();

                                std::string trimmed_attribute_value = toLower(attribute_value);
                                trim(trimmed_attribute_value);

                                if (pLUN->contains_attribute_name(attribute_name))
                                {
                                    std::string trimmed_LUN_value = toLower(pLUN->attribute_value(attribute_name));
                                    trim(trimmed_LUN_value);
                                    if (0 != trimmed_attribute_value.compare(trimmed_LUN_value))
                                    {
                                        attribute_name += std::string("_rmlib");
                                        pLUN->set_attribute(attribute_name, attribute_value);
                                    }
                                }
                                else
                                {
                                    pLUN->set_attribute(attribute_name, attribute_value);
                                }

                            }
                        }
                    }

                    // end of augmenting available test LUN attributes with config info from the command device

                    break;  // out of loop over command device LUNs as candidates to be first command device for this subsystem


                } // if we found the first command device for this subsystem


            } // for each command device LUN as candidate to match as first command device for this subsystem.

            // back to Hitachi RAID subsystem type

            if (!have_cmd_dev_this_subsystem)
            {
                std::ostringstream o;
                o << "No command device found for subsystem " << pSubsystem->serial_number << std::endl;
                std::cout << o.str();
                log(masterlogfile,o.str());
            }
            else
            {
                pRAIDsubsystem->configGatherData.print_csv_file_set
                (
                    testFolder,
                    pRAIDsubsystem->serial_number+std::string(".config")
                );
            }

        } // end for Hitachi RAID subsystem

    } // end for each subsystem

    for (auto& pLUN : availableTestLUNs.LUNpointers)
    {
        TheSampleLUN.copyOntoMe(pLUN);  // add nicknames, and command device LDEV attributes to TheSampleLUN.
    }


    for (auto& pLUN : availableTestLUNs.LUNpointers) // populate test config thumbnail data structures
    {
        available_LUNs_thumbnail.add(pLUN);
    }

    {
        std::ostringstream o;
        o << available_LUNs_thumbnail;

        bool saw_command_device {false};

        for (auto& pear : subsystems)
        {
            if (0 == std::string("Hitachi RAID").compare(pear.second->type()))
            {
                Hitachi_RAID_subsystem* pRAID = (Hitachi_RAID_subsystem*) pear.second;
                if (pRAID->command_device_description.size() > 0)
                {
                    saw_command_device = true;
                    o << pRAID->command_device_description;
                }
            }
        }

        if (saw_command_device) o << std::endl;

        log(masterlogfile,o.str());
        std::cout << o.str();

        ofstream ofs(testFolder+std::string("/available_test_config.txt"));
        ofs << o.str();
        ofs.close();

    }

    if (routine_logging)
    {
        ostringstream o;
        o << "After adding subsystem config attributes, availableTestLUNs contains:" << std::endl << availableTestLUNs.toString() << std::endl;
        // std::cout << o.str();
        log(masterlogfile,o.str());
    }
    else
    {
        ostringstream o;
        o <<"availableTestLUNs contains " << availableTestLUNs.LUNpointers.size() << " LUNs." << std::endl;
        //std::cout<<o.str();
        log(masterlogfile,o.str());
    }


    ofstream atlcsv(testFolder+std::string("/available_test_LUNs.csv"));
    availableTestLUNs.print_csv_file(atlcsv);
    atlcsv.close();

    if (cooldown_WP_watch_set.size() == 0)

    {
        std::ostringstream o;
        o << "No command devices for RAID_subsystem LDEVs, so cooldown_by_wp settings will not have any effect." << std::endl;
        log(masterlogfile,o.str());
        std::cout << o.str();
    }
    else
    {
        std::ostringstream o;
        o << "Cooldown_WP_watch_set contains:";
        for (auto& pear : cooldown_WP_watch_set) o << " < " << pear.first << ", " << pear.second->serial_number << " >";
        o << std::endl << std::endl;
        log(masterlogfile,o.str());
        std::cout << o.str();
    }

    haveHosts = true;



    return std::make_pair(true,std::string("hello, whirled!"));
}
Example #6
0
void testsl() {
  gSystem->Load("libStarLight");
  gSystem->Load("libAliStarLight");

  TStarLight* sl = new TStarLight("starlight generator", "title", "");

  sl->SetParameter("baseFileName = slight	#suite of output files will be saved with this base name");
  sl->SetParameter("BEAM_1_Z = 82    #Z of projectile");
  sl->SetParameter("BEAM_1_A = 208   #A of projectile");
  sl->SetParameter("BEAM_2_Z = 82   #Z of target");
  sl->SetParameter("BEAM_2_A = 208   #A of target");
  sl->SetParameter("BEAM_1_GAMMA = 1470.0 #Gamma of the colliding ion 1");
  sl->SetParameter("BEAM_2_GAMMA = 1470.0 #Gamma of the colliding ion 2");
  sl->SetParameter("W_MAX = -1   #Max value of w");
  sl->SetParameter("W_MIN = -1    #Min value of w");
  sl->SetParameter("W_N_BINS = 50    #Bins i w");
  sl->SetParameter("RAP_MAX = 9.    #max y");
  sl->SetParameter("RAP_N_BINS = 200    #Bins i y");
  sl->SetParameter("CUT_PT = 0 #Cut in pT? 0 = (no, 1 = yes)");
  sl->SetParameter("PT_MIN = 1.0 #Minimum pT in GeV");
  sl->SetParameter("PT_MAX = 3.0 #Maximum pT in GeV");
  sl->SetParameter("CUT_ETA = 0 #Cut in pseudorapidity? (0 = no, 1 = yes)");
  sl->SetParameter("ETA_MIN = -10 #Minimum pseudorapidity");
  sl->SetParameter("ETA_MAX = 10 #Maximum pseudorapidity");
  sl->SetParameter("PROD_MODE = 2     #gg or gP switch (1 = 2-photon, 2 = coherent vector meson (narrow), 3 = coherent vector meson (wide), 4 = incoherent vector meson)");
  sl->SetParameter("N_EVENTS = 1000   #Number of events");
  sl->SetParameter("PROD_PID = 443013   #Channel of interest; this is j/psi --> mu+ mu-");
  sl->SetParameter("RND_SEED = 5574533 #Random number seed");
  sl->SetParameter("BREAKUP_MODE = 5     #Controls the nuclear breakup; a 5 here makes no requirement on the breakup of the ions");
  sl->SetParameter("INTERFERENCE = 0     #Interference (0 = off, 1 = on)");
  sl->SetParameter("IF_STRENGTH = 1.    #percent of intefernce (0.0 - 0.1)");
  sl->SetParameter("INT_PT_MAX = 0.24  #Maximum pt considered, when interference is turned on");
  sl->SetParameter("INT_PT_N_BINS =120   #Number of pt bins when interference is turned on");
  sl->SetParameter("XSEC_METHOD = 1 # Set to 0 to use old method for calculating gamma-gamma luminosity");
  sl->SetParameter("PYTHIA_FULL_EVENTRECORD = 0 # Write full pythia information to output (vertex, parents, daughter etc).");

  sl->InitStarLight();
  sl->PrintInputs(std::cout);
  TClonesArray tca("TParticle", 100);

  TLorentzVector v[2], vSum;
  TH1* hM  = new TH1D("hM",  "STARLIGHT;M#(){#pi^{+}#pi^{-}}",    200, 3.0, 3.2);
  TH1* hPt = new TH1D("hPt", "STARLIGHT;P_{T}#(){#pi^{+}#pi^{-}}", 80, 0., 2.);
  TH1* hY  = new TH1D("hY",  "STARLIGHT;Y#(){#pi^{+}#pi^{-}}",    100,-10., 10.);

  std::ofstream ofs("sl.txt");
  TParticle *p;
  for (Int_t counter(0); counter<20000; ) {
    sl->GenerateEvent();
    sl->BoostEvent();
    sl->ImportParticles(&tca, "ALL");
    Bool_t genOK = kTRUE;
    TLorentzVector vSum;
    for (Int_t i=0; i<tca.GetEntries() && genOK; ++i) {
      p = (TParticle*)tca.At(i);
      p->Momentum(v[i]);
      vSum += v[i];
//       genOK = TMath::Abs(v[i].Rapidity()) <= 1.5;
    }
    tca.Clear();
    if (!genOK) continue;
    Printf("%5d %d", counter, genOK);
    ++counter;
    vSum = v[0] + v[1];
    ofs << std::fixed << std::setprecision(4)
	<< vSum.M() << " " << vSum.Perp() << " " << vSum.Rapidity() << " "
	<< v[0].Eta() << " " << v[0].Px() << " " << v[0].Py() << " " << v[0].Pz() << " "
	<< v[1].Eta() << " " << v[1].Px() << " " << v[1].Py() << " " << v[1].Pz()
	<< std::endl;
    hM->Fill(vSum.M());
    hPt->Fill(vSum.Perp());
    hY->Fill(vSum.Rapidity());
  }
  TFile::Open("sl.root", "RECREATE");
  sl->Write();
  gFile->Write();

  hM->Draw();
  c1->SaveAs("SL.pdf(");
  hPt->Draw();
  c1->SaveAs("SL.pdf");
  hY->Draw();
  c1->SaveAs("SL.pdf)");
}
Example #7
0
int main(int argc, char** argv)
{
  if ( argc == 2 )
  {
      if( (std::string(argv[1]) == "--help" ||
           std::string(argv[1]) == "-h" ) )
      {
          printHelp();
          return 0;
      }
  }
  if (argc != 5)
  {
      printHelp();
      return -1;
  }

  std::string urdf_file_name         = argv[1];
  std::string base_link_name         = argv[2];
  std::string end_effector_link_name = argv[3];
  std::string ikin_ini_file_name     = argv[4];

  KDL::Tree kdl_tree;
  KDL::Chain kdl_chain;
  iCub::iKin::iKinLimb ikin_limb;
  std::vector<std::string> joint_names;
  KDL::JntArray min,max;

  //
  // URDF --> KDL::Tree
  //
  bool root_inertia_workaround = true;
  if( !treeFromUrdfFile(urdf_file_name,kdl_tree,root_inertia_workaround) )
  {
      cerr << "urdf2dh: Could not parse urdf robot model" << endl;
      std::cerr << "urdf2dh: Please open an issue at https://github.com/robotology-playground/idyntree/issues " << std::endl;

      return EXIT_FAILURE;
  }

  //
  // URDF --> position ranges
  //
  if( !jointPosLimitsFromUrdfFile(urdf_file_name,joint_names,min,max) )
  {
      cerr << "Could not parse urdf robot model limits" << endl;
      return EXIT_FAILURE;
  }

  if( joint_names.size() != min.rows() ||
      joint_names.size() != max.rows() ||
      joint_names.size() == 0)
  {
      cerr << "Inconsistent joint limits got from urdf (nr of joints extracted: " << joint_names.size() << " ) " << endl;
      return EXIT_FAILURE;
  }

  //
  // KDL::Tree --> KDL::CoDyCo::UndirectedTree
  // (for extracting arbitrary chains,
  //    using KDL::Tree you can just get chains where the base of the chain
  //    is proximal to the tree base with respect to the end effector.
  //
  KDL::CoDyCo::UndirectedTree undirected_tree(kdl_tree);

  KDL::Tree kdl_rotated_tree = undirected_tree.getTree(base_link_name);

  bool result = kdl_rotated_tree.getChain(base_link_name,end_effector_link_name,kdl_chain);
  if( !result )
  {
      cerr << "urdf2dh: Impossible to find " << base_link_name << " or "
           << end_effector_link_name << " in the URDF."  << endl;
      return EXIT_FAILURE;
  }

  //
  // Copy the limits extracted from the URDF to the chain
  //
  int nj = kdl_chain.getNrOfJoints();
  KDL::JntArray chain_min(nj), chain_max(nj);

  size_t seg_i, jnt_i;
  for(seg_i=0,jnt_i=0; seg_i < kdl_chain.getNrOfSegments(); seg_i++)
  {
      const Segment & seg = kdl_chain.getSegment(seg_i);
      if( seg.getJoint().getType() != KDL::Joint::None )
      {
          std::string jnt_name = seg.getJoint().getName();
         // std::cerr << "searching for joint " << jnt_name << std::endl;
          int tree_jnt = 0;
          for(tree_jnt = 0; tree_jnt < joint_names.size(); tree_jnt++ )
          {
              //std::cerr << "joint_names[ " << tree_jnt << "] is " << joint_names[tree_jnt] << std::endl;
              if( joint_names[tree_jnt] == jnt_name )
              {
                  chain_min(jnt_i) = min(tree_jnt);
                  chain_max(jnt_i) = max(tree_jnt);
                  jnt_i++;
                  break;
              }
          }
          if( tree_jnt == joint_names.size() )
          {
              std::cerr << "urdf2dh failure in converting limits from tree to chain, unable to find joint " << jnt_name << std::endl;
              return EXIT_FAILURE;
          }
      }
  }

  if( jnt_i != nj )
  {
      std::cerr << "urdf2dh failure in converting limits from tree to chain" << std::endl;
      return EXIT_FAILURE;
  }

  //
  // Convert the chain and the limits to an iKin chain (i.e. DH parameters)
  //
  result = iKinLimbFromKDLChain(kdl_chain,ikin_limb,chain_min,chain_max);
  if( !result )
  {
      cerr << "urdf2dh: Could not export KDL::Tree to iKinChain" << endl;
      return EXIT_FAILURE;
  }

  bool result_corrupted = false;
  if( !checkChainsAreEqual(kdl_chain,ikin_limb) )
  {
      cerr << "urdf2dh error: KDL::Chain and iKinChain results does not match" << endl;
      std::cerr << "urdf2dh: Please open an issue at https://github.com/robotology-playground/idyntree/issues " << std::endl;
      return false;
  }

  yarp::os::Property prop;
  result = ikin_limb.toLinksProperties(prop);
  if( !result )
  {
      cerr << "urdf2dh: Could not export Link Properties from ikin_limb" << endl;
      return EXIT_FAILURE;
  } else {
      std::cout << "urdf2dh: Conversion to iKin DH chain completed correctly" << std::endl;
  }

  std::string ikin_prop = prop.toString();
  yarp::os::Bottle prop_bot;
  prop_bot.fromString(prop.toString());

  //Write the properties to file
   std::ofstream ofs (ikin_ini_file_name.c_str(), std::ofstream::out);

   ofs << prop_bot.findGroup("type").toString() << std::endl;
   ofs << prop_bot.findGroup("numLinks").toString() << std::endl;
   ofs << prop_bot.findGroup("H0").toString() << std::endl;
   for( int link = 0; link < ikin_limb.getN(); link++ )
   {
        std::string link_name = "link_" + int2string(link);
        ofs << prop_bot.findGroup(link_name).toString() << std::endl;

   }
   ofs << prop_bot.findGroup("HN").toString() << std::endl;


   ofs.close();

   if( result_corrupted )
   {
       return EXIT_FAILURE;
   }
   else
   {
     return EXIT_SUCCESS;
   }
}
Example #8
0
	void SaveRenderMaterial(RenderMaterialPtr const & mtl, std::string const & mtlml_name)
	{
		KlayGE::XMLDocument doc;

		XMLNodePtr root = doc.AllocNode(XNT_Element, "material");
		doc.RootNode(root);

		{
			XMLNodePtr albedo_node = doc.AllocNode(XNT_Element, "albedo");

			std::string color_str = boost::lexical_cast<std::string>(mtl->albedo.x())
				+ ' ' + boost::lexical_cast<std::string>(mtl->albedo.y())
				+ ' ' + boost::lexical_cast<std::string>(mtl->albedo.z())
				+ ' ' + boost::lexical_cast<std::string>(mtl->albedo.w());
			albedo_node->AppendAttrib(doc.AllocAttribString("color", color_str));

			if (!mtl->tex_names[RenderMaterial::TS_Albedo].empty())
			{
				albedo_node->AppendAttrib(doc.AllocAttribString("texture", mtl->tex_names[RenderMaterial::TS_Albedo]));
			}

			root->AppendNode(albedo_node);
		}

		if ((mtl->metalness > 0) || !mtl->tex_names[RenderMaterial::TS_Metalness].empty())
		{
			XMLNodePtr metalness_node = doc.AllocNode(XNT_Element, "metalness");

			if (mtl->metalness > 0)
			{
				metalness_node->AppendAttrib(doc.AllocAttribFloat("value", mtl->metalness));
			}
			if (!mtl->tex_names[RenderMaterial::TS_Metalness].empty())
			{
				metalness_node->AppendAttrib(doc.AllocAttribString("texture", mtl->tex_names[RenderMaterial::TS_Metalness]));
			}

			root->AppendNode(metalness_node);
		}

		if ((mtl->glossiness > 0) || !mtl->tex_names[RenderMaterial::TS_Glossiness].empty())
		{
			XMLNodePtr glossiness_node = doc.AllocNode(XNT_Element, "glossiness");

			if (mtl->glossiness > 0)
			{
				glossiness_node->AppendAttrib(doc.AllocAttribFloat("value", mtl->glossiness));
			}
			if (!mtl->tex_names[RenderMaterial::TS_Glossiness].empty())
			{
				glossiness_node->AppendAttrib(doc.AllocAttribString("texture", mtl->tex_names[RenderMaterial::TS_Glossiness]));
			}

			root->AppendNode(glossiness_node);
		}

		if ((mtl->emissive.x() > 0) || (mtl->emissive.y() > 0) || (mtl->emissive.z() > 0)
			|| (!mtl->tex_names[RenderMaterial::TS_Emissive].empty()))
		{
			XMLNodePtr emissive_node = doc.AllocNode(XNT_Element, "emissive");

			if ((mtl->emissive.x() > 0) || (mtl->emissive.y() > 0) || (mtl->emissive.z() > 0))
			{
				std::string color_str = boost::lexical_cast<std::string>(mtl->emissive.x())
					+ ' ' + boost::lexical_cast<std::string>(mtl->emissive.y())
					+ ' ' + boost::lexical_cast<std::string>(mtl->emissive.z());
				emissive_node->AppendAttrib(doc.AllocAttribString("color", color_str));
			}
			if (!mtl->tex_names[RenderMaterial::TS_Emissive].empty())
			{
				emissive_node->AppendAttrib(doc.AllocAttribString("texture", mtl->tex_names[RenderMaterial::TS_Emissive]));
			}

			root->AppendNode(emissive_node);
		}

		if (!mtl->tex_names[RenderMaterial::TS_Normal].empty())
		{
			XMLNodePtr normal_node = doc.AllocNode(XNT_Element, "normal");

			normal_node->AppendAttrib(doc.AllocAttribString("texture", mtl->tex_names[RenderMaterial::TS_Normal]));

			root->AppendNode(normal_node);
		}

		if (!mtl->tex_names[RenderMaterial::TS_Height].empty())
		{
			XMLNodePtr height_node = doc.AllocNode(XNT_Element, "height");

			height_node->AppendAttrib(doc.AllocAttribString("texture", mtl->tex_names[RenderMaterial::TS_Height]));
			height_node->AppendAttrib(doc.AllocAttribFloat("offset", mtl->height_offset_scale.x()));
			height_node->AppendAttrib(doc.AllocAttribFloat("scale", mtl->height_offset_scale.y()));

			root->AppendNode(height_node);
		}

		if (mtl->detail_mode != RenderMaterial::SDM_Parallax)
		{
			XMLNodePtr detail_node = doc.AllocNode(XNT_Element, "detail");

			std::string detail_mode_str;
			switch (mtl->detail_mode)
			{
			case RenderMaterial::SDM_FlatTessellation:
				detail_mode_str = "Flat Tessellation";
				break;

			case RenderMaterial::SDM_SmoothTessellation:
				detail_mode_str = "Smooth Tessellation";
				break;

			default:
				KFL_UNREACHABLE("Invalid surface detail mode");
			}
			detail_node->AppendAttrib(doc.AllocAttribString("mode", detail_mode_str));

			{
				XMLNodePtr tess_node = doc.AllocNode(XNT_Element, "tess");
				tess_node->AppendAttrib(doc.AllocAttribFloat("edge_hint", mtl->tess_factors.x()));
				tess_node->AppendAttrib(doc.AllocAttribFloat("inside_hint", mtl->tess_factors.y()));
				tess_node->AppendAttrib(doc.AllocAttribFloat("min", mtl->tess_factors.z()));
				tess_node->AppendAttrib(doc.AllocAttribFloat("max", mtl->tess_factors.w()));
				detail_node->AppendNode(tess_node);
			}

			root->AppendNode(detail_node);
		}

		if (mtl->transparent)
		{
			XMLNodePtr transparent_node = doc.AllocNode(XNT_Element, "transparent");

			transparent_node->AppendAttrib(doc.AllocAttribString("value", "1"));

			root->AppendNode(transparent_node);
		}

		if (mtl->alpha_test > 0)
		{
			XMLNodePtr alpha_test_node = doc.AllocNode(XNT_Element, "alpha_test");

			alpha_test_node->AppendAttrib(doc.AllocAttribFloat("value", mtl->alpha_test));

			root->AppendNode(alpha_test_node);
		}

		if (mtl->sss)
		{
			XMLNodePtr sss_node = doc.AllocNode(XNT_Element, "sss");

			sss_node->AppendAttrib(doc.AllocAttribString("value", "1"));

			root->AppendNode(sss_node);
		}

		if (mtl->two_sided)
		{
			XMLNodePtr two_sided_node = doc.AllocNode(XNT_Element, "two_sided");

			two_sided_node->AppendAttrib(doc.AllocAttribString("value", "1"));

			root->AppendNode(two_sided_node);
		}

		std::ofstream ofs(mtlml_name.c_str());
		if (!ofs)
		{
			ofs.open((ResLoader::Instance().LocalFolder() + mtlml_name).c_str());
		}
		doc.Print(ofs);
	}
Example #9
0
void FeatureStats::savetxt(const string &file)
{
  ofstream ofs(file.c_str(), ios::out);
  ostream* os = &ofs;
  savetxt(os);
}
	void WorldInternal::Culling(const Matrix44& cameraProjMat, bool isOpenGL)
	{
		objs.clear();
	
#ifdef _WIN32
		if (_finite(cameraProjMat.Values[2][2]) != 0 &&
			cameraProjMat.Values[0][0] != 0.0f &&
			cameraProjMat.Values[1][1] != 0.0f)
		{
#else
		
		if (isfinite(cameraProjMat.Values[2][2]) != 0 &&
			cameraProjMat.Values[0][0] != 0.0f &&
			cameraProjMat.Values[1][1] != 0.0f)
		{
#endif
			Matrix44 cameraProjMatInv = cameraProjMat;
			cameraProjMatInv.SetInverted();

			float maxx = 1.0f;
			float minx = -1.0f;

			float maxy = 1.0f;
			float miny = -1.0f;

			float maxz = 1.0f;
			float minz = 0.0f;
			if (isOpenGL) minz = -1.0f;

			Vector3DF eyebox[8];

			eyebox[0 + 0] = Vector3DF(minx, miny, maxz);
			eyebox[1 + 0] = Vector3DF(maxx, miny, maxz);
			eyebox[2 + 0] = Vector3DF(minx, maxy, maxz);
			eyebox[3 + 0] = Vector3DF(maxx, maxy, maxz);

			eyebox[0 + 4] = Vector3DF(minx, miny, minz);
			eyebox[1 + 4] = Vector3DF(maxx, miny, minz);
			eyebox[2 + 4] = Vector3DF(minx, maxy, minz);
			eyebox[3 + 4] = Vector3DF(maxx, maxy, minz);

			for (int32_t i = 0; i < 8; i++)
			{
				eyebox[i] = cameraProjMatInv.Transform3D(eyebox[i]);
			}

			// 0-right 1-left 2-top 3-bottom 4-front 5-back
			Vector3DF facePositions[6];
			facePositions[0] = eyebox[5];
			facePositions[1] = eyebox[4];
			facePositions[2] = eyebox[6];
			facePositions[3] = eyebox[4];
			facePositions[4] = eyebox[4];
			facePositions[5] = eyebox[0];

			Vector3DF faceDir[6];
			faceDir[0] = Vector3DF::Cross(eyebox[1] - eyebox[5], eyebox[7] - eyebox[5]);
			faceDir[1] = Vector3DF::Cross(eyebox[6] - eyebox[4], eyebox[0] - eyebox[4]);

			faceDir[2] = Vector3DF::Cross(eyebox[7] - eyebox[6], eyebox[2] - eyebox[6]);
			faceDir[3] = Vector3DF::Cross(eyebox[0] - eyebox[4], eyebox[5] - eyebox[4]);

			faceDir[4] = Vector3DF::Cross(eyebox[5] - eyebox[4], eyebox[6] - eyebox[4]);
			faceDir[5] = Vector3DF::Cross(eyebox[2] - eyebox[0], eyebox[1] - eyebox[5]);

			for (int32_t i = 0; i < 6; i++)
			{
				faceDir[i].Normalize();
			}

			for (int32_t z = 0; z < viewCullingZDiv; z++)
			{
				for (int32_t y = 0; y < viewCullingYDiv; y++)
				{
					for (int32_t x = 0; x < viewCullingXDiv; x++)
					{
						Vector3DF eyebox_[8];

						float xsize = 1.0f / (float) viewCullingXDiv;
						float ysize = 1.0f / (float) viewCullingYDiv;
						float zsize = 1.0f / (float) viewCullingZDiv;

						for (int32_t e = 0; e < 8; e++)
						{
							float x_, y_, z_;
							if (e == 0){ x_ = xsize * x; y_ = ysize * y; z_ = zsize * z; }
							if (e == 1){ x_ = xsize * (x + 1); y_ = ysize * y; z_ = zsize * z; }
							if (e == 2){ x_ = xsize * x; y_ = ysize * (y + 1); z_ = zsize * z; }
							if (e == 3){ x_ = xsize * (x + 1); y_ = ysize * (y + 1); z_ = zsize * z; }
							if (e == 4){ x_ = xsize * x; y_ = ysize * y; z_ = zsize * (z + 1); }
							if (e == 5){ x_ = xsize * (x + 1); y_ = ysize * y; z_ = zsize * (z + 1); }
							if (e == 6){ x_ = xsize * x; y_ = ysize * (y + 1); z_ = zsize * (z + 1); }
							if (e == 7){ x_ = xsize * (x + 1); y_ = ysize * (y + 1); z_ = zsize * (z + 1); }

							Vector3DF yzMid[4];
							yzMid[0] = eyebox[0] * x_ + eyebox[1] * (1.0f - x_);
							yzMid[1] = eyebox[2] * x_ + eyebox[3] * (1.0f - x_);
							yzMid[2] = eyebox[4] * x_ + eyebox[5] * (1.0f - x_);
							yzMid[3] = eyebox[6] * x_ + eyebox[7] * (1.0f - x_);

							Vector3DF zMid[2];
							zMid[0] = yzMid[0] * y_ + yzMid[1] * (1.0f - y_);
							zMid[1] = yzMid[2] * y_ + yzMid[3] * (1.0f - y_);

							eyebox_[e] = zMid[0] * z_ + zMid[1] * (1.0f - z_);
						}



						Vector3DF max_(-FLT_MAX, -FLT_MAX, -FLT_MAX);
						Vector3DF min_(FLT_MAX, FLT_MAX, FLT_MAX);

						for (int32_t i = 0; i < 8; i++)
						{
							if (eyebox_[i].X > max_.X) max_.X = eyebox_[i].X;
							if (eyebox_[i].Y > max_.Y) max_.Y = eyebox_[i].Y;
							if (eyebox_[i].Z > max_.Z) max_.Z = eyebox_[i].Z;

							if (eyebox_[i].X < min_.X) min_.X = eyebox_[i].X;
							if (eyebox_[i].Y < min_.Y) min_.Y = eyebox_[i].Y;
							if (eyebox_[i].Z < min_.Z) min_.Z = eyebox_[i].Z;
						}

						/* 範囲内に含まれるグリッドを取得 */
						for (size_t i = 0; i < layers.size(); i++)
						{
							layers[i]->AddGrids(max_, min_, grids);
						}
					}
				}
			}

			/* 外領域追加 */
			grids.push_back(&outofLayers);
			grids.push_back(&allLayers);

			/* グリッドからオブジェクト取得 */
			for (size_t i = 0; i < grids.size(); i++)
			{
				for (size_t j = 0; j < grids[i]->GetObjects().size(); j++)
				{
					Object* o = grids[i]->GetObjects()[j];
					ObjectInternal* o_ = (ObjectInternal*) o;

					if (
						o_->GetNextStatus().Type == OBJECT_SHAPE_TYPE_ALL ||
						IsInView(o_->GetPosition(), o_->GetNextStatus().CalcRadius(), facePositions, faceDir))
					{
						objs.push_back(o);
					}
				}
			}

			/* 取得したグリッドを破棄 */
			for (size_t i = 0; i < grids.size(); i++)
			{
				grids[i]->IsScanned = false;
			}

			grids.clear();
		}
		else
		{
			grids.push_back(&allLayers);

			/* グリッドからオブジェクト取得 */
			for (size_t i = 0; i < grids.size(); i++)
			{
				for (size_t j = 0; j < grids[i]->GetObjects().size(); j++)
				{
					Object* o = grids[i]->GetObjects()[j];
					ObjectInternal* o_ = (ObjectInternal*) o;

					if (o_->GetNextStatus().Type == OBJECT_SHAPE_TYPE_ALL)
					{
						objs.push_back(o);
					}
				}
			}

			/* 取得したグリッドを破棄 */
			for (size_t i = 0; i < grids.size(); i++)
			{
				grids[i]->IsScanned = false;
			}

			grids.clear();
		}
		
	}

	bool WorldInternal::Reassign()
	{
		/* 数が少ない */
		if (outofLayers.GetObjects().size() < 10) return false;

		objs.clear();

		for (size_t i = 0; i < layers.size(); i++)
		{
			delete layers[i];
		}

		layers.clear();
		outofLayers.GetObjects().clear();
		allLayers.GetObjects().clear();

		outofLayers.IsScanned = false;
		allLayers.IsScanned = false;

		for (auto& it : containedObjects)
		{
			auto o = (ObjectInternal*) (it);
			o->ObjectIndex = -1;
		}

		float xmin = FLT_MAX;
		float xmax = -FLT_MAX;
		float ymin = FLT_MAX;
		float ymax = -FLT_MAX;
		float zmin = FLT_MAX;
		float zmax = -FLT_MAX;

		for (auto& it : containedObjects)
		{
			ObjectInternal* o_ = (ObjectInternal*) it;
			if (o_->GetNextStatus().Type == OBJECT_SHAPE_TYPE_ALL) continue;

			if (xmin > o_->GetNextStatus().Position.X) xmin = o_->GetNextStatus().Position.X;
			if (xmax < o_->GetNextStatus().Position.X) xmax = o_->GetNextStatus().Position.X;
			if (ymin > o_->GetNextStatus().Position.Y) ymin = o_->GetNextStatus().Position.Y;
			if (ymax < o_->GetNextStatus().Position.Y) ymax = o_->GetNextStatus().Position.Y;
			if (zmin > o_->GetNextStatus().Position.Z) zmin = o_->GetNextStatus().Position.Z;
			if (zmax < o_->GetNextStatus().Position.Z) zmax = o_->GetNextStatus().Position.Z;

		}

		auto xlen = Max(abs(xmax), abs(xmin)) * 2.0f;
		auto ylen = Max(abs(ymax), abs(ymin)) * 2.0f;
		auto zlen = Max(abs(zmax), abs(zmin)) * 2.0f;

		WorldInternal(xlen, ylen, zlen, this->layerCount);

		for (auto& it: containedObjects)
		{
			ObjectInternal* o_ = (ObjectInternal*) (it);
			AddObjectInternal(o_);
		}
		return true;
	}

	void WorldInternal::Dump(const char* path, const Matrix44& cameraProjMat, bool isOpenGL)
	{
		std::ofstream ofs(path);

		/* カメラ情報出力 */
		Matrix44 cameraProjMatInv = cameraProjMat;
		cameraProjMatInv.SetInverted();

		float maxx = 1.0f;
		float minx = -1.0f;

		float maxy = 1.0f;
		float miny = -1.0f;

		float maxz = 1.0f;
		float minz = 0.0f;
		if (isOpenGL) minz = -1.0f;

		Vector3DF eyebox[8];

		eyebox[0 + 0] = Vector3DF(minx, miny, maxz);
		eyebox[1 + 0] = Vector3DF(maxx, miny, maxz);
		eyebox[2 + 0] = Vector3DF(minx, maxy, maxz);
		eyebox[3 + 0] = Vector3DF(maxx, maxy, maxz);

		eyebox[0 + 4] = Vector3DF(minx, miny, minz);
		eyebox[1 + 4] = Vector3DF(maxx, miny, minz);
		eyebox[2 + 4] = Vector3DF(minx, maxy, minz);
		eyebox[3 + 4] = Vector3DF(maxx, maxy, minz);

		for (int32_t i = 0; i < 8; i++)
		{
			eyebox[i] = cameraProjMatInv.Transform3D(eyebox[i]);
		}

		ofs << viewCullingXDiv << "," << viewCullingYDiv << "," << viewCullingZDiv << std::endl;
		for (int32_t i = 0; i < 8; i++)
		{
			ofs << eyebox[i].X << "," << eyebox[i].Y << "," << eyebox[i].Z << std::endl;
		}
		ofs << std::endl;

		for (int32_t z = 0; z < viewCullingZDiv; z++)
		{
			for (int32_t y = 0; y < viewCullingYDiv; y++)
			{
				for (int32_t x = 0; x < viewCullingXDiv; x++)
				{
					Vector3DF eyebox_[8];

					float xsize = 1.0f / (float) viewCullingXDiv;
					float ysize = 1.0f / (float) viewCullingYDiv;
					float zsize = 1.0f / (float) viewCullingZDiv;

					for (int32_t e = 0; e < 8; e++)
					{
						float x_, y_, z_;
						if (e == 0){ x_ = xsize * x; y_ = ysize * y; z_ = zsize * z; }
						if (e == 1){ x_ = xsize * (x + 1); y_ = ysize * y; z_ = zsize * z; }
						if (e == 2){ x_ = xsize * x; y_ = ysize * (y + 1); z_ = zsize * z; }
						if (e == 3){ x_ = xsize * (x + 1); y_ = ysize * (y + 1); z_ = zsize * z; }
						if (e == 4){ x_ = xsize * x; y_ = ysize * y; z_ = zsize * (z + 1); }
						if (e == 5){ x_ = xsize * (x + 1); y_ = ysize * y; z_ = zsize * (z + 1); }
						if (e == 6){ x_ = xsize * x; y_ = ysize * (y + 1); z_ = zsize * (z + 1); }
						if (e == 7){ x_ = xsize * (x + 1); y_ = ysize * (y + 1); z_ = zsize * (z + 1); }

						Vector3DF yzMid[4];
						yzMid[0] = eyebox[0] * x_ + eyebox[1] * (1.0f - x_);
						yzMid[1] = eyebox[2] * x_ + eyebox[3] * (1.0f - x_);
						yzMid[2] = eyebox[4] * x_ + eyebox[5] * (1.0f - x_);
						yzMid[3] = eyebox[6] * x_ + eyebox[7] * (1.0f - x_);

						Vector3DF zMid[2];
						zMid[0] = yzMid[0] * y_ + yzMid[1] * (1.0f - y_);
						zMid[1] = yzMid[2] * y_ + yzMid[3] * (1.0f - y_);

						eyebox_[e] = zMid[0] * z_ + zMid[1] * (1.0f - z_);
					}

					Vector3DF max_(-FLT_MAX, -FLT_MAX, -FLT_MAX);
					Vector3DF min_(FLT_MAX, FLT_MAX, FLT_MAX);

					for (int32_t i = 0; i < 8; i++)
					{
						if (eyebox_[i].X > max_.X) max_.X = eyebox_[i].X;
						if (eyebox_[i].Y > max_.Y) max_.Y = eyebox_[i].Y;
						if (eyebox_[i].Z > max_.Z) max_.Z = eyebox_[i].Z;

						if (eyebox_[i].X < min_.X) min_.X = eyebox_[i].X;
						if (eyebox_[i].Y < min_.Y) min_.Y = eyebox_[i].Y;
						if (eyebox_[i].Z < min_.Z) min_.Z = eyebox_[i].Z;
					}

					ofs << x << "," << y << "," << z << std::endl;
					for (int32_t i = 0; i < 8; i++)
					{
						ofs << eyebox_[i].X << "," << eyebox_[i].Y << "," << eyebox_[i].Z << std::endl;
					}
					ofs << max_.X << "," << max_.Y << "," << max_.Z << std::endl;
					ofs << min_.X << "," << min_.Y << "," << min_.Z << std::endl;
					ofs << std::endl;
				}
			}
		}

		ofs << std::endl;
	
		/* レイヤー情報 */
		ofs << layers.size() << std::endl;

		for (size_t i = 0; i < layers.size(); i++)
		{
			auto& layer = layers[i];
			ofs << layer->GetGridXCount() << "," << layer->GetGridYCount() << "," << layer->GetGridZCount() 
				<< "," << layer->GetOffsetX() << "," << layer->GetOffsetY() << "," << layer->GetOffsetZ() << "," << layer->GetGridSize() << std::endl;
		
			for (size_t j = 0; j < layer->GetGrids().size(); j++)
			{
				auto& grid = layer->GetGrids()[j];

				if (grid.GetObjects().size() > 0)
				{
					ofs << j << "," << grid.GetObjects().size() << std::endl;
				}
			}
		}

		Culling(cameraProjMat, isOpenGL);


	}
 void solve_problem(const char *fname)
 {
   int i,j,k; // monies of players 1,2,3 
   int a=0,s=0; // s counts number of solutions found, a counts number of trials
   int n=0; // n manages display of progress
   int l; // l is the minimum length, in rounds, of the game starting at (i,j,k)
   bool found=false; // A flag to note when a solution is found for display purposes
  
   std::set<std::pair<GameState,int> > results;
   
   // Outer loop over the money of player one
   for (i=3;i<256;i++)
   {
      // Print a dot whilst searching, but print a star if the last search was successful            
      std::cout << (found ? '*' : '.') << std::flush;
      found = false;
      
      // Scroll the screen nicely to demonstrate activity
      n++;
      if (((n % 60)==0) && (n!=0))
      {      
         double progress = double(a)/double(255.0*254.0*253.0/6.0);
         std::cout << " " << i << "/255 (" << float(int(progress*1000.0))/10.0;
         std::cout << "%)" << std::endl;
      }
                  
      // Inner loops over the money of players two and three
      for (j=2;j<i;j++)
      {
         for (k=1;k<j;k++)
         {
            // Create a gamestate for the current value of (i,j,k)
            GameState g(i,j,k);
            // Measure the number of moves required to complete game (i,j,k)
            l = explore_game(g);
            // If the game ends on turn 11 or later (counted from zero)
            // then the game will take at least 60 minutes
            if (l>=11)
            {
               // Store the result for printing later
               results.insert(std::pair<GameState,int>(g,l));
               // s counts the total number of solutions found
               s++;
               // flag that we found a solution
               found = true;
            }
            // 'a' counts the total number of iterations
            a++;            
         }
      }

      // Signal that we've searched all combinations
      if (i==255)
      {
         std::cout << " 255/255 (100%)" << std::endl;
      } 
   }  
   
   // Report the results
   i = 1; // Recycle variable 'i' now to count solutions
   std::cout << std::endl << "Found " << s << " solution" << ( (s==1) ? ' ' : 's' );
   std::cout << std::endl << std::endl;
   
   // Write the result to disk also
   std::ofstream ofs(fname,std::ios::out);
   
   std::set<std::pair<GameState,int> >::iterator it;
   for (it=results.begin();it!=results.end();it++)
   {
      std::stringstream ss;

      ss << "Solution " << i++ << ": Game starting in state ";
      ss << it->first << " takes " << (it->second + 1) * 5;
      ss << " minutes to complete";
      
      ofs << ss.str() << std::endl;
      std::cout << ss.str() << std::endl;
   }
   
   std::cout << std::endl;
}
Example #12
0
float
surface_ripMark(
    s_env&              st_env
) {
    //
    // ARGS
    // st_env   in   environment data
    //
    // DESCRIPTION
    // Adds a TRUE to the ripflag of each vertex that is part of the
    // Dijskstra path. Also saves the route itself and cost information
    // to a text file.
    //
    // PRECONDITIONS
    // o Rips on the "active" surface are marked.
    // o The cumulative cost of traveling along the marked path is returned.
    //
    // HISTORY
    // 18 November 2004
    //  o Initial design and coding.
    //
    // 10 March 2005
    // o Added "active" surface.
    //
    // 30 October 2009
    // o Added cumulative cost value to result channel and stdout.
    //

//    s_iterInfo  st_iterInfo;
    string      str_costFile            = st_env.str_workingDir +
                                          st_env.str_costFileName;
    int         i;
    int         ii, jj;
    float       f_cost                  = 0.;
    float       f_costSum               = 0.;
//    bool        b_relNextReference    = false;

    ofstream    ofs(str_costFile.c_str(), ios::out);
    ofs.flags(ios::fixed );

    for (i = st_env.endVertex; i != st_env.startVertex;
        i = st_env.pMS_active->vertices[i].old_undefval) {
        ii = st_env.pMS_active->vertices[i].old_undefval;
        jj = i;
//        f_cost = st_env.costFunc_do(st_env, &st_iterInfo, ii, jj,
//                                    b_relNextReference);
	f_cost = s_env_edgeCostFind(st_env, ii, jj);
        st_env.pMS_active->vertices[i].ripflag = TRUE;
        f_costSum += f_cost;
        if(st_env.b_costPathSave) {
            ofs << ii << "\t" << jj;
            ofs << "\t"  << f_cost;
            ofs << "\t"  << st_env.pst_iterInfo->iter;
            ofs << "\t"  << st_env.pst_iterInfo->f_distance;
            ofs << "\t"  << st_env.pst_iterInfo->f_curvature;
            ofs << "\t"  << st_env.pst_iterInfo->f_sulcalHeight;
            ofs << "\t"  << st_env.pst_iterInfo->f_dir;
            ofs << endl;
        }
    }
    st_env.pMS_active->vertices[i].ripflag = TRUE;
    if(st_env.b_costPathSave) ofs.close();
    return f_costSum;
}
Example #13
0
 void write_configuration(std::string const& fname) const
 {
     std::ofstream ofs(fname);
     for (size_type i=0; i<N_; ++i)
         ofs << data_[i][0] << "  " << data_[i][1] << std::endl;
 }
int main()
{
	cv::FileStorage fs("config.yml", cv::FileStorage::READ);

	std::string folder_name = static_cast<std::string>(fs["folder_name"]);
	double c = static_cast<double>(fs["f_edge_scale"]);
	std::cout << c << " a" << folder_name << std::endl;
	std::stringstream    stream_result;
	stream_result << folder_name << "/result.csv";
	std::string fileName_result = stream_result.str();
	std::ofstream ofs( fileName_result );
	ofs  << "thita" << "," << "fay" << "," << "f_edge" << "," << "f_grad" << "," << "f_var" << "," << "f_mean" << "," << "f_hist" << "," << "f_dir" << "," 	<< "f_Q" << std::endl;
	
	std::vector< std::vector <double> > f_e_all, f_g_all, f_v_all, f_m_all, f_h_all, f_q_all;
	double min[6] = {1000000,1000000,1000000,1000000,1000000,1000000};
	double max[6]= {-1000000,-1000000,-1000000,-1000000,-1000000,-1000000};
	std::cout << "|----------|" << std::endl;
	std::cout << " ";
	for(int i = 0; i <= 9; ++i )
	{
		std::vector<double> f_e_tmp, f_g_tmp, f_v_tmp, f_m_tmp, f_h_tmp, f_q_tmp;
		std::cout << "+";
		for(int j = 0; j < 36; ++j)
		{
			if(j!=0 && i==0) break;
			std::stringstream    stream;
			stream << folder_name << "/"  << "sita" << i*10 << "fay" << j*10 << ".png";
			std::string fileName = stream.str();
			std::stringstream    stream_pim;
			stream_pim << folder_name << "/PIM.bmp";
			std::string fileName_pim = stream_pim.str();
			cv::Mat raw_img = cv::imread(fileName,0);
			cv::Mat PIM = cv::imread(fileName_pim,0);

			double f_e = f_edge(raw_img, PIM);
			double f_g = f_grad(raw_img, PIM);
			double f_v = f_var(raw_img, PIM);
			double f_m = f_mean(raw_img, PIM);
			double f_h = f_hist(raw_img, PIM);
			double f_d = f_dir(raw_img, PIM);
			double f_q =  f_Q( f_g, f_e, f_v, f_m, f_h,f_d);

			f_e_tmp.push_back(f_e);
			f_g_tmp.push_back(f_g);
			f_v_tmp.push_back(f_v);
			f_m_tmp.push_back(f_m);
			f_h_tmp.push_back(f_h); 
			f_q_tmp.push_back(f_q);

			if(min[0] > f_e) min[0] = f_e;
			if(min[1] > f_g) min[1] = f_g;
			if(min[2] > f_v) min[2] = f_v;
			if(min[3] > f_m) min[3] = f_m;
			if(min[4] > f_h) min[4] = f_h;
			if(min[5] > f_q) min[5] = f_q;

			if(max[0] < f_e) max[0] = f_e;
			if(max[1] < f_g) max[1] = f_g;
			if(max[2] < f_v) max[2] = f_v;
			if(max[3] < f_m) max[3] = f_m;
			if(max[4] < f_h) max[4] = f_h;
			if(max[5] < f_q) max[5] = f_q;

			

			ofs  << i*10 << ","	<< j*10 << "," << f_e << ","<< f_g << "," << f_v << ","<< 
				f_m << ","	<< f_h << "," << f_d << ","<< f_q << std::endl;
		}
		f_e_all.push_back(f_e_tmp);
		f_g_all.push_back(f_g_tmp);
		f_v_all.push_back(f_v_tmp);
		f_m_all.push_back(f_m_tmp);
		f_h_all.push_back(f_h_tmp); 
		f_q_all.push_back(f_q_tmp);
	}
	std::cout << std::endl;

	std::vector<cv::Mat> results;
	for(int k = 0; k < 6; ++k)
	{
		results.push_back(cv::Mat::zeros(600, 600, CV_8UC3));
		int angle = 270;
		cv::ellipse(results[k], cv::Point(300, 300), cv::Size(250, 250), angle, angle, angle+360, cv::Scalar(255,255,255), 3, CV_AA);
		for( int i = 9; i >= 0; --i )
		{
			for( int j = 35; j >= 0; --j )
			{
				double color = 0.0;
				/*if      (k == 0) color = f_e_all[i][j] == 0 ? 0 : 255 - (255 * (max[k] - f_e_all[i][j]) / (max[k] - min[k]));
				else if (k == 1) color = f_g_all[i][j] == 0 ? 0 : 255 - (255 * (max[k] - f_g_all[i][j]) / (max[k] - min[k]));
				else if (k == 2) color = f_v_all[i][j] == 0 ? 0 : 255 - (255 * (max[k] - f_v_all[i][j]) / (max[k] - min[k]));
				else if (k == 3) color = f_m_all[i][j] == 0 ? 0 : 255 - (255 * (max[k] - f_m_all[i][j]) / (max[k] - min[k]));
				else if (k == 4) color = f_h_all[i][j] == 0 ? 0 : 255 - (255 * (max[k] - f_h_all[i][j]) / (max[k] - min[k]));
				else if (k == 5) color = f_q_all[i][j] == 0 ? 0 : 255 - (255 * (max[k] - f_q_all[i][j]) / (max[k] - min[k]));
*/
				if      (k == 0) color = f_e_all[i][j] == 0 ? 0 : 255 - (255 * (f_e_all[i][j] - min[k]) / (max[k] - min[k]));
				else if (k == 1) color = f_g_all[i][j] == 0 ? 0 : 255 - (255 * (f_g_all[i][j] - min[k]) / (max[k] - min[k]));
				else if (k == 2) color = f_v_all[i][j] == 0 ? 0 : 255 - (255 * (f_v_all[i][j] - min[k]) / (max[k] - min[k]));
				else if (k == 3) color = f_m_all[i][j] == 0 ? 0 : 255 - (255 * (f_m_all[i][j] - min[k]) / (max[k] - min[k]));
				else if (k == 4) color = f_m_all[i][j] == 0 ? 0 : 255 - (255 * (f_h_all[i][j] - min[k]) / (max[k] - min[k]));
				else if (k == 5) color = f_q_all[i][j] == 0 ? 0 : 255 - (255 * (f_q_all[i][j] - min[k]) / (max[k] - min[k]));

				/*if      (k == 0) color = f_e_all[i][j] == 0 ? 0 : (255 * (1 - f_e_all[i][j]) / (1 - 0));
				else if (k == 1) color = f_g_all[i][j] == 0 ? 0 : (255 * (1 - f_g_all[i][j]) / (1 - 0));
				else if (k == 2) color = f_v_all[i][j] == 0 ? 0 : (255 * (1 - f_v_all[i][j]) / (1 - 0));
				else if (k == 3) color = f_m_all[i][j] == 0 ? 0 : (255 * (1 - f_m_all[i][j]) / (1 - 0));
				else if (k == 4) color = f_m_all[i][j] == 0 ? 0 : (255 * (1 - f_h_all[i][j]) / (1 - 0));
				else if (k == 5) color = f_q_all[i][j] == 0 ? 0 : (255 * (max[k] - f_q_all[i][j]) / (max[k] - min[k]));

*/

				if(i==0 && j == 0){
					cv::ellipse(results[k], cv::Point(300, 300), cv::Size(25, 25), angle, angle-90, angle-90+360, cv::Scalar(color,color,color), -1, CV_AA);
				}
				else if(i==0 && j != 0) ;
				else		cv::ellipse(results[k], cv::Point(300, 300), cv::Size(250*(i+1)/10.0, 250*(i+1)/10.0), angle, angle-90-10*(j), angle-90-10*(j+1), cv::Scalar(color,color,color), -1, CV_AA);
			}
		}

		if(k==0) cv::imwrite("f_edge.jpg",results[k]);
		else if(k==1) cv::imwrite("f_grad.jpg",results[k]);
		else if(k==2) cv::imwrite("f_var.jpg",results[k]);
		else if(k==3) cv::imwrite("f_mean.jpg",results[k]);
		else if(k==4) cv::imwrite("f_hist.jpg",results[k]);
		else if(k==5) cv::imwrite("f_Q.jpg",results[k]);
		cv::waitKey( 0 );
	}

	return 0;
}
Example #15
0
static
bool
run_output_check(const output_check oc, const atf::fs::path& path,
                 const std::string& stdxxx)
{
    bool result;

    if (oc.type == oc_empty) {
        const bool is_empty = file_empty(path);
        if (!oc.negated && !is_empty) {
            std::cerr << "Fail: " << stdxxx << " not empty\n";
            print_diff(atf::fs::path("/dev/null"), path);
            result = false;
        } else if (oc.negated && is_empty) {
            std::cerr << "Fail: " << stdxxx << " is empty\n";
            result = false;
        } else
            result = true;
    } else if (oc.type == oc_file) {
        const bool equals = compare_files(path, atf::fs::path(oc.value));
        if (!oc.negated && !equals) {
            std::cerr << "Fail: " << stdxxx << " does not match golden "
                "output\n";
            print_diff(atf::fs::path(oc.value), path);
            result = false;
        } else if (oc.negated && equals) {
            std::cerr << "Fail: " << stdxxx << " matches golden output\n";
            cat_file(atf::fs::path(oc.value));
            result = false;
        } else
            result = true;
    } else if (oc.type == oc_ignore) {
        result = true;
    } else if (oc.type == oc_inline) {
        atf::fs::path path2 = atf::fs::path(atf::config::get("atf_workdir"))
                              / "inline.XXXXXX";
        temp_file temp(path2);
        temp.write(decode(oc.value));
        temp.close();

        const bool equals = compare_files(path, temp.get_path());
        if (!oc.negated && !equals) {
            std::cerr << "Fail: " << stdxxx << " does not match expected "
                "value\n";
            print_diff(temp.get_path(), path);
            result = false;
        } else if (oc.negated && equals) {
            std::cerr << "Fail: " << stdxxx << " matches expected value\n";
            cat_file(temp.get_path());
            result = false;
        } else
            result = true;
    } else if (oc.type == oc_match) {
        const bool matches = grep_file(path, oc.value);
        if (!oc.negated && !matches) {
            std::cerr << "Fail: regexp " + oc.value + " not in " << stdxxx
                      << "\n";
            cat_file(path);
            result = false;
        } else if (oc.negated && matches) {
            std::cerr << "Fail: regexp " + oc.value + " is in " << stdxxx
                      << "\n";
            cat_file(path);
            result = false;
        } else
            result = true;
    } else if (oc.type == oc_save) {
        INV(!oc.negated);
        std::ifstream ifs(path.c_str(), std::fstream::binary);
        ifs >> std::noskipws;
        std::istream_iterator< char > begin(ifs), end;

        std::ofstream ofs(oc.value.c_str(), std::fstream::binary
                                     | std::fstream::trunc);
        std::ostream_iterator <char> obegin(ofs);

        std::copy(begin, end, obegin);
        result = true;
    } else {
void CrashHandlerImpl::processCrash() {
	
	if(m_pCrashInfo) {
		m_pCrashInfo->processorProcessId = platform::getProcessId();
	}
	
	// Launch crash reporter GUI
	platform::process_handle reporter = 0;
	{
		fs::path executable = platform::getHelperExecutable("arxcrashreporter");
		char argument[256];
		strcpy(argument, "--crashinfo=");
		strcat(argument, m_SharedMemoryName.c_str());
		const char * args[] = { executable.string().c_str(), argument, NULL };
		reporter = platform::runAsync(args);
	}
	
	if(m_pCrashInfo) {
		
		std::time_t timestamp = std::time(NULL);
		{
			fs::path crashReportDir = util::loadString(m_pCrashInfo->crashReportFolder);
			std::tm * time = std::gmtime(&timestamp);
			for(int count = 0; ; count++) {
				std::ostringstream oss;
				oss << (time->tm_year + 1900) << '-'
				    << std::setfill('0') << std::setw(2) << (time->tm_mon + 1) << '-'
				    << std::setfill('0') << std::setw(2) << time->tm_mday << '-'
				    << std::setfill('0') << std::setw(2) << time->tm_hour << '-'
				    << std::setfill('0') << std::setw(2) << time->tm_min << '-'
				    << std::setfill('0') << std::setw(2) << time->tm_sec << '-'
				    << std::setfill('0') << std::setw(2) << count;
				m_crashReportDir = crashReportDir / oss.str();
				if(!fs::exists(m_crashReportDir)) {
					break;
				}
			}
			fs::create_directories(m_crashReportDir);
			util::storeStringTerminated(m_pCrashInfo->crashReportFolder, m_crashReportDir.string());
		}
		
		processCrashInfo();
		processCrashSignal();
		processCrashRegisters();
		processCrashTrace();
		processCrashDump();
		
		{
			size_t nfiles = std::min(size_t(m_pCrashInfo->nbFilesAttached),
			                         size_t(CrashInfo::MaxNbFiles));
			for(size_t i = 0; i < nfiles; i++) {
				fs::path file = util::loadString(m_pCrashInfo->attachedFiles[i]);
				if(file.empty() || !fs::is_regular_file(file)) {
					continue;
				}
				fs::path copy = m_crashReportDir / file.filename();
				if(copy == file || !fs::copy_file(file, copy)) {
					continue;
				}
				util::storeStringTerminated(m_pCrashInfo->attachedFiles[i], copy.string());
			}
		}
		
		// Terminate the crashed process - we collected all the information we could
		if(m_pCrashInfo->processId != m_pCrashInfo->processorProcessId) {
			m_pCrashInfo->exitLock.post();
			platform::killProcess(m_pCrashInfo->processId);
		}
		
		// Write the crash description to a file
		fs::path crashinfo = m_crashReportDir / "crash.txt";
		fs::ofstream ofs(crashinfo, fs::fstream::out | fs::fstream::trunc);
		if(ofs.is_open()) {
			
			ofs.write(m_pCrashInfo->description, m_textLength);
			
			ofs << '\n';
			
			ofs << "\nProcess information:\n";
			ofs << "- path: " << util::loadString(m_pCrashInfo->executablePath) << '\n';
			ofs << "- version: " << util::loadString(m_pCrashInfo->executableVersion) << '\n';
			if(m_pCrashInfo->memoryUsage != 0) {
				ofs << "- memory usage: " << m_pCrashInfo->memoryUsage << " bytes" << '\n';
			}
			const char * arch = platform::getArchitectureName(m_pCrashInfo->architecture);
			ofs << "- architecture: " << arch << '\n';
			if(m_pCrashInfo->runningTime > 0.0) {
				ofs << "- runnig time: " << m_pCrashInfo->runningTime << " seconds" << '\n';
			}
			std::tm * time = std::gmtime(&timestamp);
			ofs << "- crash time: " << (time->tm_year + 1900) << '-'
			    << std::setfill('0') << std::setw(2) << (time->tm_mon + 1) << '-'
			    << std::setfill('0') << std::setw(2) << time->tm_mday << ' '
			    << std::setfill('0') << std::setw(2) << time->tm_hour << ':'
			    << std::setfill('0') << std::setw(2) << time->tm_min << ':'
			    << std::setfill('0') << std::setw(2) << time->tm_sec << '\n';
			
			ofs << "\nSystem information:\n";
			std::string os = platform::getOSName();
			if(!os.empty()) {
				ofs << "- operating system: " << os << '\n';
			}
			std::string osarch = platform::getOSArchitecture();
			if(!osarch.empty()) {
				ofs << "- architecture: " << osarch << '\n';
			}
			std::string distro = platform::getOSDistribution();
			if(!distro.empty()) {
				ofs << "- distribution: " << distro << '\n';
			}
			
			ofs << "\nVariables:\n";
			size_t nbVariables = std::min(size_t(m_pCrashInfo->nbVariables),
			                              size_t(CrashInfo::MaxNbVariables));
			for(size_t i = 0; i < nbVariables; ++i) {
				ofs << "- " << util::loadString(m_pCrashInfo->variables[i].name) << ": "
				    << util::loadString(m_pCrashInfo->variables[i].value) << '\n';
			}
			
			ofs << "\nAdditional files:\n";
			size_t nfiles = std::min(size_t(m_pCrashInfo->nbFilesAttached),
			                         size_t(CrashInfo::MaxNbFiles));
			for(size_t i = 0; i < nfiles; i++) {
				fs::path file = util::loadString(m_pCrashInfo->attachedFiles[i]);
				if(fs::exists(file) && fs::file_size(file) != 0) {
					ofs << "- " << file.filename() << '\n';
				}
			}
			
			addAttachedFile(crashinfo);
		}
		
	}
	
	// Wait for the crash reporter to start
	while(reporter) {
		if(platform::getProcessExitCode(reporter, false) != platform::StillRunning) {
			reporter = 0;
			break;
		}
		boost::posix_time::ptime timeout
		 = boost::posix_time::microsec_clock::universal_time()
		 + boost::posix_time::milliseconds(100);
		if(m_pCrashInfo->reporterStarted.timed_wait(timeout)) {
			break;
		}
	}
	
	// Tell the crash reporter we are done
	if(m_pCrashInfo) {
		m_pCrashInfo->processorDone.post();
	}
	
	// If the crash reporter started successfully, we are done here
	if(reporter) {
		return;
	}
	
	// The crash reporter is not available or failed to start - provide our own dialog
	{
		std::ostringstream oss;
		oss <<"Arx Libertatis crashed!\n\n";
		oss << "Please install arxcrashreporter or manually report the crash to "
		    << url::bug_report << "\n\n";
		oss << "Include the files contained in the following directory in your report:\n";
		oss << " " << m_crashReportDir;
		std::cout << "\n\n" << oss.str() << '\n';
		oss << "\n\nClick OK to open that directory now.";
		platform::showErrorDialog(oss.str(), "Fatal Error - " + arx_version);
		platform::launchDefaultProgram(m_crashReportDir.string());
	}
	
}
void CXBindingsGenerator::SaveFile( const std::string& file , const std::string& content )
{
	boost::filesystem::path p(file.c_str());
	 boost::filesystem::ofstream ofs(p); 
	ofs << content;
}
Example #18
0
bool ZipFile::extractCurrentFile(const std::string& path, bool whiny)
{    
    int ret;
    unz_file_info info;
    char fname[1024];

    try {
        internal::api("unzGetCurrentFileInfo", unzGetCurrentFileInfo(this->fp, &info, fname, 1024, nullptr, 0, nullptr, 0));
        
        std::string outPath(path);
        fs::addnode(outPath, fname);

        TraceL << "Extracting asset: " << outPath << endl;

        // Create directory
#if !WIN32
        const int FILE_ATTRIBUTE_DIRECTORY = 0x10;
#endif
        if (info.external_fa & FILE_ATTRIBUTE_DIRECTORY || 
            fname[strlen(fname) - 1] == fs::delimiter) {
            TraceL << "Create directory: " << outPath << endl;
            fs::mkdirr(outPath);
        }

        // Create file
        else {            
            TraceL << "Create file: " << outPath << endl;

            // Note: If this fails the file we are trying 
            // to write may be in use on the filesystem.
            openCurrentFile();

            std::ofstream ofs(outPath, std::ios::binary | std::ios::out);

            // FIX: FILE_ATTRIBUTE_DIRECTORY can be inconsistent, so we 
            // need to be ready to create directories if the output file 
            // fails to open.
            if (!ofs.is_open()) {
                fs::mkdirr(fs::dirname(outPath));
                ofs.open(outPath);
            }

            if (!ofs.is_open())
                throw std::runtime_error("Cannot open zip output file: " + outPath);
            
            char buffer[16384];
            while ((ret = unzReadCurrentFile(this->fp, buffer, 16384)) > 0)
                ofs.write(buffer, ret);
            
            ofs.close();
            
            internal::api("unzReadCurrentFile", ret); // throw file read errors
            closeCurrentFile();
        }
    } 
    catch (std::exception& exc) {
        ErrorL << "Cannot unzip file: " << exc.what() << endl;
        if (whiny)
            throw exc;
        return false;
    }
    return true;
}
Example #19
0
int main(int argc, const char **argv)
{
  // Instantiate a ModelManager:
  ModelManager *manager = new ModelManager("Test wiimote");

  nub::soft_ref<OutputFrameSeries> ofs(new OutputFrameSeries(*manager));
  manager->addSubComponent(ofs);

  //Create the GUI
  nub::soft_ref<GeneralGUI> pwiiGUI(new GeneralGUI(*manager, "PWiiGUI", "PWiiGUI", Dims(700,512)));
  manager->addSubComponent(pwiiGUI);

  //Create the PWiiBot Controller
  nub::soft_ref<PWiiController> controller(new PWiiController(*manager));
  manager->addSubComponent(controller);

  // Parse command-line:
  if (manager->parseCommandLine(argc, argv, "", 0, 0) == false) return(1);



  manager->exportOptions(MC_RECURSE);
  manager->start();
  sleep(1);
  setupGUI(pwiiGUI, ofs, controller);



  while(1) {

  }

//  sleep(1);


#ifdef HAVE_LIBWIIMOTE
/*        wiimote_t wiimote = WIIMOTE_INIT;
        //wiimote_report_t report = WIIMOTE_REPORT_INIT;

  LINFO("Press buttons 1 and 2 on the wiimote now to connect.");
  int nmotes = wiimote_discover(&wiimote, 1);
  if (nmotes == 0)
    LFATAL("no wiimotes were found");

  LINFO("found: %s\n", wiimote.link.r_addr);

  if (wiimote_connect(&wiimote, wiimote.link.r_addr) < 0) {
    LFATAL("Unable to connect to wiimote");
    Raster::waitForKey();
    }
    */

  /* Activate the first led on the wiimote. It will take effect on the
     next call to wiimote_update. */
/*
  wiimote.led.one  = 1;

  // let's get all our ModelComponent instances started:
  LINFO("Open ");

  LINFO("Status %i", wiimote_is_open(&wiimote));

  int speed = 100;
  int motor1_dir = 0;
  int motor1_vel = 0;

  int motor2_dir = 0;
  int motor2_vel = 0;

  Point2D<int> loc(128,128);

*/

//  while(wiimote_is_open(&wiimote))
//  {
    /* The wiimote_update function is used to synchronize the wiimote
       object with the real wiimote. It should be called as often as
       possible in order to minimize latency. */

  /*  if (wiimote_update(&wiimote) < 0) {
      wiimote_disconnect(&wiimote);
      break;
    }*/

                /* The wiimote object has member 'keys' which keep track of the
                   current key state. */
        /*
                if (wiimote.keys.home) { //press home to exit
                            wiimote_write_byte(&wiimote, 0x04a40001, motor1_dir);
                            wiimote_write_byte(&wiimote, 0x04a40002, 0);
                           wiimote_write_byte(&wiimote, 0x04a40003, motor2_dir);
                            wiimote_write_byte(&wiimote, 0x04a40004, 0);

                        LINFO("Shutting Down Motors and Gracefully Disconnecting...");

                        wiimote_disconnect(&wiimote);

                        LINFO("Disconnected, Goodbye!");
                }
                */

                /* Activate the accelerometer when the 'A' key is pressed. */
                //if (wiimote.keys.a) {
                //        wiimote.mode.acc = 1;
                //}
                //else {
                //        wiimote.mode.acc = 0;
                //}


   // Image<PixRGB<byte> > img(255,255,ZEROS);

//    drawLine(img, Point2D<int>(128, 128), Point2D<int>(128+(int)(wiimote.force.x*400), 128), PixRGB<byte>(255,0,0),3);
//    drawLine(img, Point2D<int>(128, 128), Point2D<int>(128, 128+(int)(wiimote.force.y*400)), PixRGB<byte>(0,255,0),3);
//    drawLine(img, Point2D<int>(128, 128), Point2D<int>(128+(int)(wiimote.force.z*400), 128), PixRGB<byte>(0,0,255),3);

   // ofs->writeRGB(img, "Output", FrameInfo("output", SRC_POS));

 /*
    int key = getKey(ofs);
    if (key != -1)
    {
      switch(key)
      {
        case 10:  //l
          speed += 10;
          break;
        case 24:
          speed -= 10;
          break;
        case KEY_UP:
          motor1_dir = 2;
          motor2_dir = 2;
          break;
        case KEY_DOWN:
          motor1_dir = 1;
          motor2_dir = 1;
          break;
        case KEY_LEFT:
          motor1_dir = 2;
          motor2_dir = 1;
          break;
        case KEY_RIGHT:
          motor1_dir = 1;
          motor2_dir = 2;
          break;
        case 65: //space
          motor1_dir = 4; motor1_vel = 0;
          motor2_dir = 4; motor2_vel = 0;
          break;

      }
        LINFO("Key: %d  -- Sending Motor Command...", key);
    //send the data to the wiimote
    wiimote_write_byte(&wiimote, 0x04a40001, motor1_dir);
    wiimote_write_byte(&wiimote, 0x04a40002, speed);
    wiimote_write_byte(&wiimote, 0x04a40003, motor2_dir);
    wiimote_write_byte(&wiimote, 0x04a40004, speed);
    }*/



          /*
                LINFO("KEYS %04x one=%d two=%d a=%d b=%d <=%d >=%d ^=%d v=%d h=%d +=%d -=%d\n",
                        wiimote.keys.bits,
                        wiimote.keys.one,
                        wiimote.keys.two,
                        wiimote.keys.a,
                        wiimote.keys.b,
                        wiimote.keys.left,
                        wiimote.keys.right,
                        wiimote.keys.up,
                        wiimote.keys.down,
                        wiimote.keys.home,
                        wiimote.keys.plus,
                        wiimote.keys.minus);

                LINFO("TILT x=%.3f y=%.3f z=%.3f\n",
                        wiimote.tilt.x,
                        wiimote.tilt.y,
                        wiimote.tilt.z);

                LINFO("FORCE x=%.3f y=%.3f z=%.3f (sum=%.3f)\n",
                        wiimote.force.x,
                        wiimote.force.y,
                        wiimote.force.z,
      sqrt(wiimote.force.x*wiimote.force.x+wiimote.force.y*wiimote.force.y+wiimote.force.z*wiimote.force.z));*/

//  }

  // stop all our ModelComponents
  manager->stop();
#else
  LFATAL("Need the libwiimote");
#endif

  // all done!
  return 0;
}
int main(int argc, const char ** argv) {

 // print_copyright();
  write_copyright();
  //* GraphChi initialization will read the command line arguments and the configuration file. */
  graphchi_init(argc, argv);

  /* Metrics object for keeping track of performance counters
     and other information. Currently required. */
  metrics m("sgd-inmemory-factors");

  /* Basic arguments for application. NOTE: File will be automatically 'sharded'. */
  sgd_lambda    = get_option_float("sgd_lambda", 1e-3);
  sgd_gamma     = get_option_float("sgd_gamma", 1e-3);
  sgd_step_dec  = get_option_float("sgd_step_dec", 0.9);

  int file_format   = get_option_int("ff", 3);


  parse_command_line_args();
  parse_implicit_command_line();

  /* Preprocess data if needed, or discover preprocess files */
  int nshards = convert_matrixmarket<EdgeDataType>(training, 0, 0, file_format, TRAINING, false);
  init_feature_vectors<std::vector<vertex_data> >(M+N, latent_factors_inmem, !load_factors_from_file);
  if (validation != ""){
    int vshards = convert_matrixmarket<EdgeDataType>(validation, 0, 0, 3, VALIDATION, false);
    init_validation_rmse_engine<VertexDataType, EdgeDataType>(pvalidation_engine, vshards, &sgd_predict);
  }

  /* load initial state from disk (optional) */
  if (load_factors_from_file){
    load_matrix_market_matrix(training + "_U.mm", 0, D);
    load_matrix_market_matrix(training + "_V.mm", M, D);
  }

  print_config();

  /* Run */
  SGDVerticesInMemProgram program;
  graphchi_engine<VertexDataType, EdgeDataType> engine(training, nshards, false, m); 
  set_engine_flags(engine);
  pengine = &engine;

  timer train_timer;
  engine.run(program, niters);
 // std::cout << "Trn Time for file test: " << std::setw(10) << train_timer.current_time() / niters << std::endl;

  std::ofstream ofs(result.c_str(), std::ofstream::out | std::ofstream::app);
  ofs << D << " " << train_timer.current_time() << " ";


  /* Run TopN program */
  n_top = get_option_int("n_int", 10);
  /*timer test_timer1;

  ofs << test_timer1.current_time() << " ";*/
  //run_general_topn_program(pengine, &latent_factors_inmem, &sgd_predict);
  timer index_timer;
  kd_Node* mroot = init_kdtree(&latent_factors_inmem);
  ofs << index_timer.current_time() << " ";
  timer test_timer;
  /* construct kd tree index */ 
//  ofs << "constructing index: " << test_timer.current_time() << " ";
  run_kd_topn_program(pengine, &latent_factors_inmem, mroot);

 // std::coua << "Tst Time: " << std::setw(10) << test_timer.current_time() << std::endl;
  ofs << test_timer.current_time() << std::endl;
  ofs.close();
  /* Output latent factor matrices in matrix-market format */
  output_sgd_result(training);
  test_predictions(&sgd_predict);    
  /* Report execution metrics */
  if (!quiet)
    metrics_report(m);
  
  return 0;
}
Example #21
0
 void write(std::string out_file, Char delimiter) const
 {
     std::ofstream ofs(out_file, std::ios::binary);
     ofs << frequency_map.str() << delimiter << bit_string.compress(delimiter);
 }
Example #22
0
bool ServiceOptions::bindServiceObject(CORBA::ORB_ptr orb, 
                                       CORBA::Object_ptr object,
                                       PortableServer::Servant p_servant,
                                       const char* objName,
                                       bool rebind)
{
 if(is_set("with-naming")) {
     CosNaming::Name name;
     name.length(1);
     name[0].id=CORBA::string_dup(objName);
     name[0].kind=CORBA::string_dup("");
     CORBA::Object_var obj ;
     try {
        obj = orb->resolve_initial_references("NameService");
     }catch(const CORBA::ORB::InvalidName& ex){
        std::cerr << argv()[0] << ": can't resolve `NameService'" << std::endl;
        return false;
     }
     CosNaming::NamingContext_var nc;
     try {
        nc = CosNaming::NamingContext::_narrow(obj.in());
     }catch(const CORBA::SystemException& ex){
        std::cerr << argv()[0] << ": can't narrow naming service" << std::endl;
        return false;
     }
     try {
        if(rebind){
          nc->rebind(name,object);
        }else{
          try{
            nc->bind(name,object);
          }catch(const CosNaming::NamingContext::AlreadyBound&){
            std::cerr<<argv()[0]<<":can't bind "<<objName<<" (AlreadyBound)"<< std::endl;
            return false;
          }
        }
     }catch(const CosNaming::NamingContext::CannotProceed&){
        std::cerr<<argv()[0]<<": can't bind "<<objName<<" (CannotProceed)"<< std::endl;
        return false;
     }catch(const CosNaming::NamingContext::InvalidName&){
        std::cerr<<argv()[0]<<":can't bind "<<objName<<" (InvalidName)"<< std::endl;
        return false;
     }
     std::cout<<argv()[0]<<": binding completed successfully"<<std::endl;
 }
 CORBA::String_var ior ;
 try {
   ior = orb->object_to_string(object);
 }catch(const CORBA::SystemException& ex){
#ifdef CORBA_SYSTEM_EXCEPTION_IS_STREAMBLE
   std::cerr << ex << std::endl;
#else
   std::cerr << "CORBA::SystemException" << std::endl; 
#endif
   return false;
 }
 const char* fname = get_ior_fname(objName);
 if (fname!=NULL && strcmp(fname,"")!=0) {
    std::ofstream ofs (fname);
    if (ofs.bad()) {
       std::cerr << argv()[0] << ": can't open file " << fname <<  std::endl;
       perror(argv()[0]);
       return false;
    }
    ofs << ior.in();
    ofs.close();
 }
 if (is_set("ior-stdout")) {
    std::cout << ior << std::flush;
 }
#ifdef ORBACUS
 CORBA::Object_var bmgrObj = orb->resolve_initial_references("BootManager");
 OB::BootManager_var bootManager = OB::BootManager::_narrow(bmgrObj);
 PortableServer::ObjectId_var oid = PortableServer::string_to_ObjectId(objName);
 bootManager -> add_binding(oid.in(),object);
#elif defined(OMNIORB)
 PortableServer::POA_var objPOA = p_servant->_default_POA();
 CORBA::String_var objPOAName = objPOA->the_name();
 if (strcmp(objPOAName.in(),"omniINSPOA")!=0) {
   CORBA::Object_var insPOAObj = orb->resolve_initial_references("omniINSPOA");
   PortableServer::POA_var insPOA = PortableServer::POA::_narrow(insPOAObj);
   PortableServer::POAManager_var insPOAManager=insPOA->the_POAManager();
   insPOAManager->activate();
   PortableServer::ObjectId_var oid = 
                          PortableServer::string_to_ObjectId(objName);
   insPOA->activate_object_with_id(oid.in(),p_servant);
 }
#elif defined(RSSH_TAO)
#ifdef TAO_HAVE_IORTABLE_ADAPTER
 CORBA::Object_var table = orb->resolve_initial_references ("IORTable");
 IORTable::Table_var adapter = IORTable::Table::_narrow (table.in());
 if (CORBA::is_nil(adapter.in())) {
   cerr<<argv()[0]<<": nil IORTable reference"<<endl;
 } else {
   adapter->bind (objName, ior.in ());
 }
#else
 ACE_CString ins(objName);
 if (orb->_tao_add_to_IOR_table(ins,object)!=0) {
   return false;
 }
#endif
#elif defined(MICO)
  // create persistent POA with name as service name if we have no one.
 PortableServer::POA_var objPOA = p_servant->_default_POA();
 CORBA::String_var objPOAName = objPOA->the_name();
 std::cerr << "existent OBJPOAName=" << objPOAName.in() << std::endl;
 std::cerr << "objName=" << objName << std::endl;
 if (strcmp(objPOAName.in(),objName)!=0) {
   CORBA::Object_var rootPOAObj = orb->resolve_initial_references ("RootPOA");
   PortableServer::POA_var rootPOA = PortableServer::POA::_narrow(rootPOAObj);
   CORBA::PolicyList pl;
   pl.length (2);                              
   pl[0] = rootPOA->create_lifespan_policy (PortableServer::PERSISTENT);
   pl[1] = rootPOA->create_id_assignment_policy (PortableServer::USER_ID);
   PortableServer::POA_var objPOA = rootPOA->create_POA(objName,
			                  PortableServer::POAManager::_nil (),
			                  pl);
   PortableServer::POAManager_var objPOAManager = objPOA->the_POAManager ();   
   PortableServer::ObjectId_var objId =
                           PortableServer::string_to_ObjectId (objName);
   objPOA->activate_object_with_id (objId.in(), p_servant);
   objPOAManager->activate();
 }else{
   //PortbaobjPOA
 }  
#endif
 return true;
}
    void TestArchivingSetOfSetOfPointers() throw (Exception)
    {
        /*
         * This test is an abstraction of archiving a set of sets of pointers and a list of objects.
         * Note that the list.push_back method uses the copy constructor. This is why we iterate
         * through the list to generate the pointers to populate the set.
         */

        std::vector<double> doubles;
        std::vector<bool> bools;

        OutputFileHandler handler("archive",false);
        std::string archive_filename;
        archive_filename = handler.GetOutputDirectoryFullPath() + "pointer_set.arch";

        // Save
        {
            // Create aClassOfSimpleVariablesn output archive
            std::ofstream ofs(archive_filename.c_str());
            boost::archive::text_oarchive output_arch(ofs);

            ClassOfSimpleVariables one(42, "hello", doubles,bools);
            ClassOfSimpleVariables two(256, "goodbye", doubles,bools);
            ClassOfSimpleVariables three(1, "not used in set", doubles,bools);

            std::list<ClassOfSimpleVariables> a_list;
            std::set<ClassOfSimpleVariables*> a_set;
            a_list.push_back(one);
            a_set.insert( &(a_list.back()) );
            a_list.push_back(two);
            a_set.insert( &(a_list.back()) );
            a_list.push_back(three);

            std::set<std::set<ClassOfSimpleVariables*> > wrapper_set;
            wrapper_set.insert(a_set);

            output_arch << static_cast<const std::list<ClassOfSimpleVariables>&>(a_list);
            output_arch << static_cast<const std::set<std::set<ClassOfSimpleVariables*> >&>(wrapper_set);
        }

        // Load
        {
            std::set<std::set<ClassOfSimpleVariables*> > wrapper_set;
            std::list<ClassOfSimpleVariables> a_list;

            // Create an input archive
            std::ifstream ifs(archive_filename.c_str(), std::ios::binary);
            boost::archive::text_iarchive input_arch(ifs);

            TS_ASSERT_EQUALS(wrapper_set.size(), 0u);
            input_arch >> a_list;
            input_arch >> wrapper_set;
            TS_ASSERT_EQUALS(wrapper_set.size(), 1u);
            const std::set<ClassOfSimpleVariables*>& a_set = *(wrapper_set.begin());
            TS_ASSERT_EQUALS(a_set.size(), 2u);

            ClassOfSimpleVariables* p_one_in_set = NULL;
            ClassOfSimpleVariables* p_two_in_set = NULL;
            for (std::set<ClassOfSimpleVariables*>::iterator it = a_set.begin();
                 it != a_set.end();
                 ++it)
            {
                   ClassOfSimpleVariables* p_class = *(it);
                   if (p_class->GetNumber() == 42)
                   {
                        TS_ASSERT_EQUALS(p_class->GetNumber(), 42);
                        TS_ASSERT_EQUALS(p_class->GetString(), "hello");
                        p_one_in_set = p_class;
                   }
                   else
                   {
                        TS_ASSERT_EQUALS(p_class->GetNumber(), 256);
                        TS_ASSERT_EQUALS(p_class->GetString(), "goodbye");
                        p_two_in_set = p_class;
                   }
            }

            ClassOfSimpleVariables* p_one_in_list = NULL;
            ClassOfSimpleVariables* p_two_in_list = NULL;
            for (std::list<ClassOfSimpleVariables>::iterator it = a_list.begin();
                 it != a_list.end();
                 ++it)
            {
                   ClassOfSimpleVariables* p_class = &(*it);
                   if (p_class->GetNumber() == 42)
                   {
                        TS_ASSERT_EQUALS(p_class->GetNumber(), 42);
                        TS_ASSERT_EQUALS(p_class->GetString(), "hello");
                        p_one_in_list = p_class;
                   }
                   else if (p_class->GetNumber() == 256)
                   {
                        TS_ASSERT_EQUALS(p_class->GetNumber(), 256);
                        TS_ASSERT_EQUALS(p_class->GetString(), "goodbye");
                        p_two_in_list = p_class;
                   }
                   else
                   {
                        TS_ASSERT_EQUALS(p_class->GetNumber(), 1);
                        TS_ASSERT_EQUALS(p_class->GetString(), "not used in set");
                   }
            }
            TS_ASSERT_DIFFERS(p_one_in_list, (void*)NULL);
            TS_ASSERT_DIFFERS(p_two_in_list, (void*)NULL);
            TS_ASSERT_EQUALS(p_one_in_list, p_one_in_set);
            TS_ASSERT_EQUALS(p_two_in_list, p_two_in_set);
        }
    }
int execute() {
	//input and output file specification
	ifstream ifs("/Users/zehadyzbdullahkhan/Documents/workspace/Research/Thesis/Bitcoin/BitcoinTransactionNetworkDataset/MyData/user_edges_2011-07-13.txt");
	ofstream ofs("/Users/zehadyzbdullahkhan/Documents/workspace/Research/Thesis/Bitcoin/BitcoinTransactionNetworkDataset/MyData/user_edges_for_PA.txt");

	string s;
	si timeAndLineNum; //pair storing time and line number
	vsi timesAndLineNums; //vector of such pairs
	vs savedLines;//storing the entire file in string vectors
	vs prefinalLines; // string vector to store with increasing time
	vs finalLines;    // storing only unique from->to transactions
//	vi markLine;              *****what's wrong with vector<int>

	int c = 0;
	int lineNumber = 0;

	string tmpString;
	while(ifs >> s){
		c++;
		if(c < 4)			// not the timestamp
			tmpString += s + "\t";  //adding from node, to node and bitcoin value to the data row

		if(c == 4){        //when it's timestamp
			int year,month,day,hour,min,sec;
			sscanf(s.c_str(),"%d-%d-%d-%d-%d-%d",&year,&month,&day,&hour,&min,&sec);
			//cout << year <<" " << month <<" " << day <<" " << hour <<" " << min <<" " << sec << endl;

			//converting to unix time
			struct tm* time_info;
			//time_info -> tm_year = year;
			time_info -> tm_mon = month;
			time_info -> tm_mday = day;
			time_info -> tm_hour = hour;
			time_info -> tm_min = min;
			time_info -> tm_sec = sec;

			time_t unix_time = mktime(time_info); //converting to Unix time

			int time = unix_time;
			string t = convertInt(time);

			tmpString += t;//adding the unix time to the temporary string to complete creating each data row
			//cout << tmpString << endl;
			savedLines.push_back(tmpString); //saving the data row
			tmpString.clear();

			timeAndLineNum.first = s;
			timeAndLineNum.second = lineNumber++;
			timesAndLineNums.push_back(timeAndLineNum);

			c = 0;
		}
	}

	sort(timesAndLineNums.begin(),timesAndLineNums.end()); //sorting the pair vector according to the increasing time

	//printing out the data according to the increasing time
	tr(timesAndLineNums,i){
		int N = i -> second;
		ofs << savedLines[N] << endl;
	//	prefinalLines.push_back(savedLines[N]);
	}
Example #25
0
int main() {
   constants_wrapper cfg;
   cfg.show();
   InitRNG RNG;
   RNG.seed(cfg.SEED);
   int a(0);
   if (!a) std::cout << "TRUEEEEE!!!" << std::endl;
   std::cout << std::endl << std::endl;
   std::cout << "X_MIN = " << cfg.X_MIN << std::endl;
   std::cout << "X_MAX = " << cfg.X_MAX << std::endl;
   std::cout << "Y_MIN = " << cfg.Y_MIN << std::endl;
   std::cout << "Y_MAX = " << cfg.Y_MAX << std::endl;

   std::cout << "READ_FOOD_FROM_FILE = " << cfg.READ_FOOD_FROM_FILE << std::endl;
   std::cout << "FOOD_POINT_DISTRIBUTION = " << cfg.FOOD_POINT_DISTRIBUTION << std::endl;


   chromo beauty_d(beauty_default);
   chromo dim_d(dim_default);
   chromo athlet_d(athlet_default);
   chromo karma_d(karma_default);
   chromo attracted_d(attracted_default);
   chromo charm_d(charm_default);

   DNA dna1(charm_d, beauty_d, dim_d, athlet_d, karma_d, attracted_d);
   DNA dna2(attracted_d, beauty_d, dim_d, athlet_d, karma_d, attracted_d);
   //dna2.set_chromo(c1,5);
   if (dna1 == dna2)  {
      std::cout << "TRUE1" << std::endl;
   } else { std::cout << "qualche problema" << std::endl;
     };
   
   being conf_being(dna1, 0, cfg.starting_energy, true, 1.0, 2.0, 0, 0);
   conf_being.configure(cfg);
   being b1(dna1, 0, cfg.starting_energy, true, 1.0, 2.0, 0, 0);
   //b1.show();
   being b2(dna2, 0, 100, true, 2.0, 2.0, 0, 0);

   food_point fp2(4.1, 4.2, cfg.default_nutrival);
   food_point fp3(1.1, 2.2, cfg.default_nutrival);

   point_2d p1(1,1);
   point_2d p2(2,2);

   // create and open a character archive for output
   std::ofstream ofs("./points.txt");
   // save data to archive
    {
        boost::archive::text_oarchive oa(ofs);
        // write class instance to archive
        oa << p1;
        oa << p2;
        oa << beauty_d;
        oa << dna1;
        oa << b1;
    	// archive and stream closed when destructors are called
    }


    // ... some time later restore the class instance to its orginal state
    point_2d p1new;
    point_2d p2new;
    chromo new_beauty;
    DNA dna1new;
    being b1new;

    {
        // create and open an archive for input
        std::ifstream ifs("./points.txt");
        boost::archive::text_iarchive ia(ifs);
        // read class state from archive
        ia >> p1new;
        ia >> p2new;
        ia >> new_beauty;
        ia >> dna1new;
        ia >> b1new;
        // archive and stream closed when destructors are called
    }

   std::cout << "P1new = ";
   p1new.show_point();
   std::cout << std::endl;

   std::cout << "P2new = ";
   p2new.show_point();
   std::cout << std::endl;

   std::cout << "new beauty = " << new_beauty << std::endl;
   std::cout << "newdna1 = " << dna1new << std::endl;

   if (dna1 == dna1new) std::cout << "TRUE!" << std::endl;

   std::cout << "B1NEW = " << std::endl << b1new << std::endl;

   world myworld(cfg.N_BEINGS,cfg.N_FOOD_POINT_AT_START);
   myworld.name("MyWorld");
   std::cout << "World name = " << myworld.name() << std::endl;
   
   //myworld.add(b1);
   //myworld.add(b2);
   //myworld.add(fp2);
   //myworld.add(fp3);
   //myworld.stats();
   //myworld.advance_one_generation();
   //myworld.stats();

//   myworld.load("DATA/200.txt");
//   myworld.stats();
//   myworld.evolve(1);
//   myworld.stats();

   std::vector<int> iv;
   iv.reserve(10);
   for (int i=0; i<10; ++i) iv.push_back(i);

   std::vector<int>::iterator iv_end = iv.end();
   for (std::vector<int>::iterator it = iv.begin(); it!=iv_end; ++it) {
      std::cout << *it << std::endl;
      iv.push_back(11);
   }

   if (cfg.BEINGS_START_DISTRIBUTION == "UNIFORM") {
      std::uniform_real_distribution<float> beings_distribution_x(cfg.X_MIN , cfg.X_MAX);
      std::uniform_real_distribution<float> beings_distribution_y(cfg.Y_MIN , cfg.Y_MAX);
      for (int i = 0; i < cfg.N_BEINGS; ++i) {
         b1.set_x(beings_distribution_x(RNG.generator));
         b1.set_y(beings_distribution_y(RNG.generator));
         myworld.add(b1) ;
      };
   };

   std::cout << "READ_FOOD_FROM_FILE = " << cfg.READ_FOOD_FROM_FILE << std::endl;
   if (!cfg.READ_FOOD_FROM_FILE) 
   {
      std::cout << "Creating food point from scratch" << std::endl;
      if (cfg.FOOD_POINT_DISTRIBUTION == "UNIFORM") {
         std::uniform_real_distribution<float> food_distribution_x(cfg.X_MIN , cfg.X_MAX);
         std::uniform_real_distribution<float> food_distribution_y(cfg.Y_MIN , cfg.Y_MAX);
         for (int i = 0; i < cfg.N_FOOD_POINT_AT_START; ++i) {
            food_point fpx( food_distribution_x(RNG.generator) , food_distribution_y(RNG.generator) , cfg.default_nutrival );
            myworld.add(fpx) ;
         }
      }
   }
   else 
   {
      std::cout << "Reading food points from file = " << cfg.food_file << std::endl;
      // create and open an archive for input
      std::ifstream ifs2(cfg.food_file);
      boost::archive::text_iarchive ia(ifs2);
      food_point newfp;
      // read class state from archive
      for (int i=0; i<cfg.N_FOOD_POINT_AT_START; ++i) {
         ia >> newfp;
         myworld.add(newfp);
      }
   };
  

   myworld.stats();

   //return 0;
   std::chrono::time_point<std::chrono::high_resolution_clock> start, end;
   start = std::chrono::high_resolution_clock::now();
   myworld.evolve(cfg.ITER_NUMBER);
   end = std::chrono::high_resolution_clock::now();
   cfg.save("myworld.cfg");
   std::cout << "World evolved in = " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms." << std::endl;
/*
   // create and open a character archive for output
   std::ofstream ofs2("./world.txt");
   // save data to archive
    {
        boost::archive::text_oarchive oa(ofs2);
        // write class instance to archive
        oa << myworld;
        // archive and stream closed when destructors are called
    }



    world newworld(1000,1000);


    {
        // create and open an archive for input
        std::ifstream ifs2("./world.txt");
        boost::archive::text_iarchive ia(ifs2);
        // read class state from archive
        ia >> newworld;
        // archive and stream closed when destructors are called
    }


   newworld.stats();
*/
   return 0;
};
int main(int argc, const char *argv[])
{
    signal(SIGINT, terminate);
    try {
        po::options_description desc("Allowed options");
        desc.add_options()
            ("help,h", "print this help message")
            ("config,c", po::value<std::string>()->required(), "path to config file")
        ;

        po::variables_map vm;
        po::store(po::parse_command_line(argc, argv, desc), vm);

        if (vm.count("help")) {
            std::cout << desc << std::endl;
            return 0;
        }

        po::notify(vm);

        std::shared_ptr<TextDetector::ConfigurationManager> config(
        	new TextDetector::ConfigurationManager(
        		vm["config"].as<std::string>()));
        TextDetector::ConfigurationManager::set_instance(config);


        float threshold = config->get_threshold();
        if (config->has_cache()) {
            CacheManager::set_instance(
                std::shared_ptr<CacheManager>((new CacheManager(config->get_cache_directory()))));
        }

        srand(config->get_random_seed());

        // creates the models
        TextDetector::ModelManager model_manager(config);

        if (config->verbose())
            std::cout << "Read inputs" << std::endl;

        if (!fs::is_directory(config->get_input_directory()) ||
            !fs::is_directory(config->get_responses_directory())) {
            std::cerr << "Error: response or input directory does not exist" << std::endl;
            return 1;
        }

        std::vector<fs::path> directories;
        std::copy(fs::directory_iterator(
            config->get_input_directory()),
            fs::directory_iterator(), 
            std::back_inserter(directories));
        std::sort(directories.begin(), directories.end());

        TextDetector::MserDetector detector(config);
        for (auto it = directories.begin(); it != directories.end(); ++it) {
            fs::path p(*it);
            //p = "../train_icdar_2005/332.jpg";
            //p = "../test_icdar_2005/214.jpg";

            if (p.extension() != ".jpg" && p.extension() != ".png") {
                std::cout << "Skipping: " << p << std::endl;
                continue;
            }

            fs::path number = p.stem();

            std::string response_name = number.generic_string() + "_response.png";
            fs::path response = config->get_responses_directory();
            response += "/";
            response += response_name;

            if (!fs::exists(response) && 
                !config->ignore_responses()) {
                std::cout << "Error, " << response
                		  << " does not exist -> skipping!" << std::endl;
                continue;
            }

            std::cout << "Processing: " << p.filename() << " " 
                      << number << " " << response << std::endl;

            if (CacheManager::instance()) {
                CacheManager::instance()->load_image(number.generic_string());
            }
            
            cv::Mat response_image;
            if (fs::exists(response)) {
                response_image = cv::imread(response.generic_string());
                if (response_image.channels() > 1) {
                    cv::cvtColor(response_image, response_image, cv::COLOR_RGB2GRAY);
                }
            }
            cv::Mat train_image = cv::imread(p.generic_string());
            cv::Mat mask;

            if (!response_image.empty()) 
                mask = response_image > (threshold * 255);

            if (config->ignore_responses()) {
                mask = cv::Mat(train_image.rows, train_image.cols, CV_8UC1, cv::Scalar(255));
            }

            cv::Mat gt_mask;
            if (config->include_binary_masks()) {
                std::string mask_path = config->get_input_directory() + number.generic_string() + "_mask.png";
                if (!fs::exists(mask_path)) {
                    std::cout << "Skipping: " << mask_path << " due to missing mask!" << std::endl;
                    continue;
                }
                gt_mask = cv::imread(mask_path);
            }
            cv::Mat result_image;
            std::vector<cv::Rect> words = detector(train_image, result_image, mask, gt_mask);

            fs::path out_name(config->get_responses_directory());
            std::string box_name = number.generic_string() + "_boxes.txt";
            out_name += "/"; out_name += box_name;
            std::ofstream ofs(out_name.generic_string());
//            cv::Mat result_img = show_groups_color(
//                groups,
//                cv::Size(train_image.cols, train_image.rows),
//                all_probs, false);
            for (size_t i = 0; i < words.size(); i++) {
                cv::Rect r = words[i];
                cv::rectangle(result_image, r.tl(), r.br(), cv::Scalar(0, 0, 255), 4);
                ofs << r.x << "," << r.y << "," << r.width << "," << r.height << std::endl;
            }
            ofs.close();

            std::string box_img_name = number.generic_string() + "_boxes.png";
            fs::path out_img_name(config->get_responses_directory());
            out_img_name += "/"; out_img_name += box_img_name;
            cv::imwrite(out_img_name.generic_string(), result_image);

            if (CacheManager::instance())
                CacheManager::instance()->save_image(number.generic_string());
        }
        
    } catch (const std::exception &e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }

    return 0;
}
Example #27
0
int main() {


  DrawTools::setStyle();

  std::vector<std::string> runs;
  runs.push_back( "BTF_229_20140501-155939_beam" ); // 0
  runs.push_back( "BTF_231_20140501-163742_beam" ); // 1
  runs.push_back( "BTF_233_20140501-171741_beam" ); // 2
  runs.push_back( "BTF_237_20140501-183950_beam" ); // 3
  runs.push_back( "BTF_235_20140501-175948_beam" ); // 4
  runs.push_back( "BTF_239_20140501-191908_beam" ); // 5
  runs.push_back( "BTF_241_20140501-200053_beam" ); // 6
  runs.push_back( "BTF_243_20140501-203838_beam" ); // 7


  std::string outputdir = "BGOCalibration/";
  std::string mkdir_command = "mkdir -p " + outputdir;
  system(mkdir_command.c_str());


  std::vector<TH1D*> rawHistos;
  std::vector<TH1D*> calibHistos;
  std::vector<float> calibConstants;
  float yMax = 0.;

  for( unsigned i=0; i<runs.size(); ++i ) {
    TH1D* h1_raw = fitSingleChannelBGO( outputdir, "raw", runs[i], i, 1. );
    rawHistos.push_back(h1_raw);
    TF1* thisFunc = (TF1*)(h1_raw->GetListOfFunctions()->FindObject(Form("gaussian_%s", runs[i].c_str())));
    calibConstants.push_back(thisFunc->GetParameter(1));
    float thisMax = h1_raw->GetMaximum()/h1_raw->Integral();
    if( thisMax>yMax )
      yMax = thisMax;
  }


  float calibAve = sumVector(calibConstants)/calibConstants.size();


  std::string constantsFileName = outputdir + "/constants.txt";
  ofstream ofs(constantsFileName.c_str());

  for( unsigned i=0; i<runs.size(); ++i ) {
    float thisCalib = calibAve/calibConstants[i];
    calibHistos.push_back(fitSingleChannelBGO( outputdir, "calib", runs[i], i, thisCalib ));
    ofs << i << "\t" << thisCalib << std::endl;
  }

  ofs.close();

  drawHistos( outputdir, rawHistos,   "rawSpectra"  , yMax );
  drawHistos( outputdir, calibHistos, "calibSpectra", yMax );


  std::cout << std::endl;
  std::cout << "-> Calibration constants saved in: " << constantsFileName << std::endl;

  std::cout << "Calibration average for BGO: " << calibAve << std::endl;


  std::string run_cef3 = "BTF_227_20140501-151233_beam";
  TH1D* h1_cef3 = fitCeF3( outputdir, "cef3_raw", run_cef3 );
  TF1* f1_cef3 = (TF1*)(h1_cef3->GetListOfFunctions()->FindObject(Form("gaussian_%s", run_cef3.c_str())));

  std::cout << "BGO/CeF3 relative calibration: " << calibAve/f1_cef3->GetParameter(1) << std::endl;
  
  return 0;

}
Example #28
0
// Handle the remote SSL connection.
void RemoteProxyClient::remote_threadproc()
{
   try
   {
      DOUT(this->dinfo());
      if ( this->m_local_ep.size() == 0 )
      {
         throw std::runtime_error("No local endpoints found");
      }
      this->m_remote_connected = true; // Should perhaps be after the SSL handshake.
      this->dolog(this->dinfo() + "Performing SSL hansdshake connection");
      this->m_remote_socket.handshake( boost::asio::ssl::stream_base::server );
      this->dolog(this->dinfo() + "SSL connection ok");

      bool hit = false;
      // See if we can find the relevant
      std::string issuer, subject, common_name = "NOT VALID";
      if ( get_certificate_issuer_subject( this->m_remote_socket, issuer, subject ) && issuer.length() > 0 )
      {
         std::vector< std::string > result;
         boost::algorithm::split_regex( result, issuer, boost::regex( "/CN=" ) );
         if ( result.size() > 1 )
         {
            common_name = result[1];
         }
         DOUT(this->dinfo() << "Received certificate CN= " << common_name );
         for ( auto iter1 = this->m_host.m_remote_ep.begin(); iter1 != this->m_host.m_remote_ep.end(); iter1++ )
         {
            if ( common_name == (*iter1).m_name )
            {
               hit = true;
               this->m_endpoint = (*iter1);
               break;
            }
         }
      }
      if ( !hit )
      {
         throw std::runtime_error("Certificate valid but no active connections specified: " + common_name );
      }
      this->m_local_connected = false;
      std::vector<int> indexes(this->m_local_ep.size());
      for (int index = 0; index < indexes.size(); index++)
      {
         indexes[index] = index;
      }
      std::shuffle(std::begin(indexes), std::end(indexes), std::default_random_engine(static_cast<unsigned int>(std::chrono::system_clock::now().time_since_epoch().count())));
      for (int i = 0; i < indexes.size(); i++)
      {
         DOUT(this->dinfo() << "Random i: " << i << " index " << indexes[i] << " size: " << indexes.size());
      }
      std::string ep;
      for (int index = 0; index < this->m_local_ep.size(); index++)
      {
         int proxy_index = indexes[index];
         ep = this->m_local_ep[proxy_index].m_hostname + ":" + mylib::to_string(this->m_local_ep[proxy_index].m_port);
         try
         {
            this->dolog(this->dinfo() + "Performing local connection to: " + ep );
            boost::asio::sockect_connect( this->m_local_socket, this->m_io_service, this->m_local_ep[proxy_index].m_hostname, this->m_local_ep[proxy_index].m_port );
            this->m_local_connected = true;
            break;
         }
         catch( std::exception &exc )
         {
            DOUT(this->dinfo() << " Failed connection to: " << ep << " " << exc.what() );
         }
      }
      if ( !this->m_local_connected )
      {
         throw std::runtime_error("Failed connection to local host");
      }
      this->dolog(this->dinfo() + "Performing logon procedure to " + ep);
      if ( ! this->m_host.m_plugin.connect_handler( this->m_local_socket, this->m_endpoint ) )
      {     
         throw std::runtime_error("Failed plugin connect_handler for type: " + this->m_host.m_plugin.m_type );
      }
      this->dolog(this->dinfo() + "Completed logon procedure to " + ep);
      this->m_local_thread.start( [&]{this->local_threadproc(); } );
      boost::asio::socket_set_keepalive_to( this->m_remote_socket.lowest_layer(), std::chrono::seconds(20) );
      for ( ; this->m_remote_thread.check_run(); )
      {
         boost::system::error_code ec;
         int length = this->m_remote_socket.read_some(boost::asio::buffer(this->m_remote_read_buffer, this->m_host.m_plugin.max_buffer_size()), ec);
         if (ec.value() != 0 || length == 0)
         {
            DOUT(this->dinfo() << "Remote read socket Failed reading data " << ec.category().name() << " val: " << (int)ec.value() << " msg: " << ec.category().message(ec.value()) << " length: " << length);
            DOUT(this->dinfo() << "Last received msg: " << this->m_last_incoming_stamp << ":" << this->m_last_incoming_msg);
            break;
         }
         if (length > 0)
         {
            this->m_remote_read_buffer[length] = 0;
            this->m_last_incoming_msg = (const char*)this->m_remote_read_buffer;
            this->m_last_incoming_stamp = boost::get_system_time();
            if (global.m_in_data_log_file.is_open())
            {
               std::ofstream ofs(global.m_log_path + "in_" + common_name + ".log", std::ios::ate | std::ios::app | std::ios::binary);
               ofs << "[" << mylib::to_string(boost::get_system_time()) << "]" << this->m_remote_read_buffer;
            }
            Buffer buffer( this->m_remote_read_buffer, length );
            if ( this->m_host.m_plugin.message_filter_remote2local( buffer ) )
            {
               length = this->m_local_socket.write_some( boost::asio::buffer( buffer.m_buffer, buffer.m_size ) );
               this->m_count_in.add(length);
            }
            else
            {
               // This should not happen too often.
               this->dolog(this->dinfo() + "Data overflow");
            }
         }
      }
   }
   catch( boost::system::system_error &boost_error )
   {
      std::ostringstream oss; oss << "SSL: " << boost_error.code() << " what: " << boost_error.what();
      this->dolog(this->dinfo() + oss.str());
   }
   catch( std::exception &exc )
   {
      this->dolog(this->dinfo() + exc.what());
   }
   DOUT(this->dinfo() << "Thread stopping");
   this->interrupt();
   boost::system::error_code ec;
   this->m_remote_socket.shutdown(ec);
   this->m_remote_socket.lowest_layer().close(ec);
   DOUT(this->dinfo() << "Thread stopped");
}
Example #29
0
void SequenceViewer::ExportAlignment(eExportType type)
{
    // get filename
    wxString extension, wildcard;
    if (type == asFASTA) { extension = ".fsa"; wildcard = "FASTA Files (*.fsa)|*.fsa"; }
    else if (type == asFASTAa2m) { extension = ".a2m"; wildcard = "A2M FASTA (*.a2m)|*.a2m"; }
    else if (type == asText) { extension = ".txt"; wildcard = "Text Files (*.txt)|*.txt"; }
    else if (type == asHTML) { extension = ".html"; wildcard = "HTML Files (*.html)|*.html"; }
    else if (type == asPSSM) { extension = ".pssm"; wildcard = "PSSM Files (*.pssm)|*.pssm"; }

    wxString outputFolder = wxString(GetUserDir().c_str(), GetUserDir().size() - 1); // remove trailing /
    wxString baseName, outputFile;
    wxFileName::SplitPath(GetWorkingFilename().c_str(), NULL, &baseName, NULL);
    wxFileDialog dialog(sequenceWindow, "Choose a file for alignment export:", outputFolder,
#ifdef __WXGTK__
        baseName + extension,
#else
        baseName,
#endif
        wildcard, wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
    dialog.SetFilterIndex(0);
    if (dialog.ShowModal() == wxID_OK)
        outputFile = dialog.GetPath();

    if (outputFile.size() > 0) {

        // create output stream
        auto_ptr<CNcbiOfstream> ofs(new CNcbiOfstream(WX_TO_STD(outputFile).c_str(), IOS_BASE::out));
        if (!(*ofs)) {
            ERRORMSG("Unable to open output file " << outputFile.c_str());
            return;
        }

        // map display row order to rows in BlockMultipleAlignment
        vector < int > rowOrder;
        const SequenceDisplay *display = GetCurrentDisplay();
        for (unsigned int i=0; i<display->rows.size(); ++i) {
            DisplayRowFromAlignment *alnRow = dynamic_cast<DisplayRowFromAlignment*>(display->rows[i]);
            if (alnRow) rowOrder.push_back(alnRow->row);
        }

        // actually write the alignment
        if (type == asFASTA || type == asFASTAa2m) {
            INFOMSG("exporting" << (type == asFASTAa2m ? " A2M " : " ") << "FASTA to " << outputFile.c_str());
            DumpFASTA((type == asFASTAa2m), alignmentManager->GetCurrentMultipleAlignment(),
                rowOrder, sequenceWindow->GetCurrentJustification(), *ofs);
        } else if (type == asText || type == asHTML) {
            INFOMSG("exporting " << (type == asText ? "text" : "HTML") << " to " << outputFile.c_str());
            DumpText((type == asHTML), alignmentManager->GetCurrentMultipleAlignment(),
                rowOrder, sequenceWindow->GetCurrentJustification(), *ofs);
        } else if (type == asPSSM) {
            static string prevTitle;
            if (prevTitle.size() == 0)
                prevTitle = GetWorkingTitle();
            string title = WX_TO_STD(wxGetTextFromUser(
                "Enter a name for this PSSM (to be used by other applications like PSI-BLAST or RPS-BLAST):",
                "PSSM Title?", prevTitle.c_str(), *viewerWindow).Strip(wxString::both));
            if (title.size() > 0) {
                INFOMSG("exporting PSSM (" << title << ") to " << outputFile.c_str());
                alignmentManager->GetCurrentMultipleAlignment()->GetPSSM().OutputPSSM(*ofs, title);
                prevTitle = title;
            }
        }
    }
}
void FlameDecider::userInput(const map<int, Target>& targets)
{
    ofstream ofs(SAMPLE_FILE, ios::app);
    for (map<int, Target>::const_iterator it = targets.begin(); it != targets.end(); it++) {
        if (it->second.lostTimes > 0) {
            continue;
        }
        
        const Feature& feature = it->second.feature;
        const Rectangle& rect = it->second.region.rect;
        
        Mat temp;
        mFrame.copyTo(temp);
        bool flag = true;
        
        while (true) {
            int key = waitKey(200);
            switch (key) {
                case -1:    // no key pressed
                    rectangle(temp, rect, flag ? Scalar(0, 0, 255) : Scalar(0, 255, 0));
                    namedWindow("temp");
                    moveWindow("temp", 350, 400);
                    imshow("temp", temp);
                    flag = !flag;
                    break;
                case 'y':   // press 'y' to add a positive record to sample
                    ofs << feature << true << endl;
#ifdef DEBUG_OUTPUT
                    cout << "freq: " << feature.frequency << endl;
                    feature.printAreaVec();
#endif
                    mFeatureVec.push_back(feature);
                    mResultVec.push_back(true);
                    mFlameCount++;
                    goto next;
                case 'n':   // press 'n' to add a negative record to sample
                    ofs << feature << false << endl;
                    mFeatureVec.push_back(feature);
                    mResultVec.push_back(false);
                    mNonFlameCount++;
                    goto next;
                case ' ':   // press SPACE to skip current target
                    goto next;
                case 's':   // press 's' to skip current frame
                    goto end;
                case 27:    // press ESC to stop training and exit program
                    trainComplete = true;
                    goto end;
                case 'o':   // press 'o' to stop input and start studying
                    mSampleEnough = true;
                    goto end;
                default:
                    break;
            }
        }

    next:
        if (mFlameCount >= MIN_SAMPLE_COUNT && mNonFlameCount >= MIN_SAMPLE_COUNT) {
            mSampleEnough = true;
            goto end;
        }
    }
    
end:
    ofs.close();
    cout << "Flame count: " << mFlameCount << ", non-flame count: " << mNonFlameCount << "." << endl;
}