Example #1
0
  // 2008/03/12 kazuhide nakata
void Newton::initialize_sparse_bMat(int m, IV *newToOldIV,
				    IVL *symbfacIVL)
{

  //  bMat_type = SPARSE;
  //  printf("SPARSE computation\n");

  int* newToOld;

  newToOld = IV_entries(newToOldIV);

  NewArray(ordering,int,m);
  NewArray(reverse_ordering,int,m);
  for (int i=0; i<m; i++){
    ordering[i] = newToOld[i];
  }
  for (int i=0; i<m; i++){
    reverse_ordering[ordering[i]] = i;
  }
  
  // separate front or back node
  int* counter;
  int nClique = IVL_nlist(symbfacIVL);
  int psize;
  int* pivec;
  bool* bnode;
  int* nFront;

  NewArray(counter,int ,m);
  NewArray(bnode  ,bool,m);
  NewArray(nFront ,int ,nClique);

  for (int k=0; k<m; k++){
    bnode[k] = false;
    counter[k] = -1;
  }

  // search number of front 
  for (int l=nClique-1; l >= 0; l--){
    IVL_listAndSize(symbfacIVL,l,&psize,&pivec);
    int i;
    for (i=0; i<psize; i++){
      int ii = reverse_ordering[pivec[i]];
      if (bnode[ii] == false){
        counter[ii] = psize - i;
        bnode[ii] = true;
      } else {
        nFront[l] = i;
        break;
      }
    }
    if (i == psize){
      nFront[l] = psize;
    }
  }

  // error check
  for (int k=0; k<m; k++){
    if (counter[k] == -1){ 
      rError("Newton::initialize_sparse_bMat: program bug");
    }
  }

  // make index of diagonal
  NewArray(diagonalIndex,int,m+1);
  diagonalIndex[0] = 0;
  for (int k=1; k<m+1; k++){
    diagonalIndex[k] = diagonalIndex[k-1] + counter[k-1];
  }
  
  // initialize sparse_bMat
  sparse_bMat.initialize(m,m,SparseMatrix::SPARSE,diagonalIndex[m]);
  
  // initialize index of sparse_bmat
  int nonzeros = 0;
  for (int l=0; l<nClique; l++){
    IVL_listAndSize(symbfacIVL,l,&psize,&pivec);
    for (int i=0; i<nFront[l]; i++){
      int ii = reverse_ordering[pivec[i]];
      for (int j=i; j<psize; j++){
        int jj = reverse_ordering[pivec[j]];
        int index = diagonalIndex[ii] + j - i;
        sparse_bMat.row_index[index] = ii;
        sparse_bMat.column_index[index] = jj;
        nonzeros++;
      }
    }
  }
  // error check
  if (nonzeros!= sparse_bMat.NonZeroNumber){
    rError("Newton::initialize_sparse_bMat  probram bug");
  }
  sparse_bMat.NonZeroCount = nonzeros;  
  //  sparse_bMat.display();

  DeleteArray(counter);
  DeleteArray(bnode);
  DeleteArray(nFront);
}
Example #2
0
void AutoMapSaver::checkSave()
{
	// Check if we have a proper map
	if (!GlobalMap().isValid() || !GlobalMainFrame().screenUpdatesEnabled())
	{
		return;
	}

	// greebo: Check if we have a valid main window to grab the pointer
	wxFrame* mainWindow = GlobalMainFrame().getWxTopLevelWindow();

	if (mainWindow == NULL || !mainWindow->IsActive())
	{
		rMessage() << "AutoSaver: Main window not present or not shown on screen, " <<
			 "will wait for another period." << std::endl;
		return;
	}

	// Check, if changes have been made since the last autosave
    if (_changes == GlobalSceneGraph().root()->getUndoChangeTracker().changes())
	{
		return;
	}

	// Check if the user is currently pressing a mouse button
	// Don't start the save if the user is holding a mouse button
	if (wxGetMouseState().ButtonIsDown(wxMOUSE_BTN_ANY)) 
	{
		return;
	}

    _changes = GlobalSceneGraph().root()->getUndoChangeTracker().changes();

	// Stop the timer before saving
	stopTimer();

	if (_enabled)
	{
		// only snapshot if not working on an unnamed map
		if (_snapshotsEnabled && !GlobalMap().isUnnamed())
		{
			try
			{
				saveSnapshot();
			}
			catch (boost::filesystem::filesystem_error& f) 
			{
				rError() << "AutoSaver::saveSnapshot: " << f.what() << std::endl;
			}
		}
		else
		{
			if (GlobalMap().isUnnamed())
			{
				// Get the maps path (within the mod path)
				std::string autoSaveFilename = GlobalRegistry().get(RKEY_MAP_PATH);

				// Try to create the map folder, in case there doesn't exist one
				os::makeDirectory(autoSaveFilename);

				// Append the "autosave.map" to the filename
				autoSaveFilename += "autosave.";
				autoSaveFilename += game::current::getValue<std::string>(GKEY_MAP_EXTENSION);

				rMessage() << "Autosaving unnamed map to " << autoSaveFilename << std::endl;

				// Invoke the save call
				GlobalMap().saveDirect(autoSaveFilename);
			}
			else
			{
				// Construct the new filename (e.g. "test_autosave.map")
				std::string filename = GlobalMap().getMapName();
				std::string extension = os::getExtension(filename);

				// Cut off the extension
				filename = filename.substr(0, filename.rfind('.'));
				filename += "_autosave";
				filename += "." + extension;

				rMessage() << "Autosaving map to " << filename << std::endl;

				// Invoke the save call
				GlobalMap().saveDirect(filename);
			}
		}
	}
	else
	{
		rMessage() << "Autosave skipped..." << std::endl;
	}

	// Re-start the timer after saving has finished
	startTimer();
}
Example #3
0
void user_error_fn(png_structp png_ptr, png_const_charp error_msg)
{
	rError() << "libpng error: " << error_msg << std::endl;
	longjmp(png_jmpbuf(png_ptr), 1);
}
Example #4
0
int main(int argc, char **argv)
{
	g_BufferedMemorySize = 100;

	string compressorName;
	string commandLineOptions;

	std::vector<string> fuseOptions;
	fuseOptions.push_back(argv[0]);

	po::options_description desc("Usage: " PACKAGE "_offline [options] path\n"
	                                "\nPath may be directory or file.\n"
	                                "\nNo options mean decompression mode.\n\n"
	                                "Allowed options");
	desc.add_options()
		("options,o", po::value<string>(&commandLineOptions),
				"fc_c:arg  - compression method (lzo/bzip2/zlib/lzma)\n"
				"            (default: gz)\n"
				"fc_b:arg  - size of blocks in kilobytes\n"
				"            (default: 100)\n"
				"fc_d      - run in debug mode\n"
				"fc_ma:arg - files with passed mime types to be\n"
				"            always not compressed\n"
				"fc_mr:arg - files with passed mime types to be\n"
				"            always compressed\n"
				"\nOther options are passed directly to fuse library. See fuse documentation for full list of supported options.\n")
		("dir_lower", po::value<string>(&g_dirLower), "path")
		("help,h", "print this help")
		("version,v", "print version")
		("quiet,q", "quiet mode")
	;

	po::positional_options_description pdesc;
	pdesc.add("dir_lower", 1);

	po::variables_map vm;
	try {
		po::store(po::command_line_parser(argc, argv).options(desc).positional(pdesc).run(), vm);
	} catch (...) {
		print_help(desc);
		exit(EXIT_FAILURE);
	}
	po::notify(vm);

	if (vm.count("help"))
	{
		print_help(desc);
		exit(EXIT_SUCCESS);
	}
	if (vm.count("version"))
	{
		print_license();
		exit(EXIT_SUCCESS);
	}
	if (vm.count("quiet"))
	{
		g_QuietMode = true;
	}

	g_RLog = new rlog::RLog("FuseCompress_offline", g_QuietMode ? LOG_NOTICE : LOG_INFO, true);

	if (vm.count("options"))
	{
		typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
		boost::char_separator<char> sep(",");
		tokenizer tokens(commandLineOptions, sep);

		for (tokenizer::iterator tok_it = tokens.begin(); tok_it != tokens.end(); ++tok_it)
		{
			if ((*tok_it).find_first_of("fc_", 0, 3) == 0)
			{
				typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
				boost::char_separator<char> sep(":");
				tokenizer tokens(*tok_it, sep);

				tokenizer::iterator key = tokens.begin();
				tokenizer::iterator value = key; ++value;

				if (*key == "fc_c")
				{
					if (value == tokens.end())
					{
						rError("Compression type not set!");
						exit(EXIT_FAILURE);
					}
					compressorName = *value;
				}
				if (*key == "fc_b")
				{
					if (value == tokens.end())
					{
						rError("Block size not set!");
						exit(EXIT_FAILURE);
					}
					g_BufferedMemorySize = boost::lexical_cast<unsigned int>(*value);
				}
				if (*key == "fc_d")
				{
					g_DebugMode = true;
					g_RLog->setLevel(LOG_DEBUG);
				}
				if (*key == "fc_ma")
				{
					if (value == tokens.end())
					{
						rError("Mime type(s) not set!");
						exit(EXIT_FAILURE);
					}
					g_CompressedMagic.Add(*value);
				}
				if (*key == "fc_mr")
				{
					if (value == tokens.end())
					{
						rError("Mime type(s) not set!");
						exit(EXIT_FAILURE);
					}
					g_CompressedMagic.Remove(*value);
				}
			}
			else
			{
				fuseOptions.push_back("-o");
				fuseOptions.push_back(*tok_it);
			}
		}
	}
	if (!vm.count("dir_lower"))
	{
		print_help(desc);
		exit(EXIT_FAILURE);
	}

	g_BufferedMemorySize *= 1024;

	if (compressorName != "")
	{
		g_RawOutput = false;

		if (g_CompressionType.parseType(compressorName) == false)
		{
			rError("Compressor %s not found!", compressorName.c_str());
			exit(EXIT_FAILURE);
		}
	}

	fs::path pathLower(g_dirLower
#if BOOST_VERSION <= 104600
            , fs::native
#endif
            );

	if (!pathLower.is_complete())
	{
		char cwd[PATH_MAX];

		// Transform relative path to absolute path.

		if (getcwd(cwd, sizeof(cwd)) == NULL)
		{
			rError("Cannot determine current working directory!");
			exit(EXIT_FAILURE);
		}

        pathLower = fs::path(cwd
#if BOOST_VERSION <= 104600
                , fs::native
#endif
                ) / pathLower;
	}

	// Set signal handler to catch SIGINT (CTRL+C).

	struct sigaction setup_kill;
	memset(&setup_kill, 0, sizeof(setup_kill));
	setup_kill.sa_handler = catch_kill;
	sigaction(SIGINT, &setup_kill, NULL);

	// Iterate over directory structure and execute compress
	// for every files there.

	if (nftw(const_cast<char *>(pathLower.string().c_str()), compress, 100, FTW_PHYS | FTW_CHDIR))
		exit(EXIT_FAILURE);

	exit(EXIT_SUCCESS);
}
void CommandEditor::createArgumentWidgets(int commandTypeID)
{
	try
	{
		const conversation::ConversationCommandInfo& cmdInfo =
			conversation::ConversationCommandLibrary::Instance().findCommandInfo(commandTypeID);

		// Remove all possible previous items from the list
		_argumentItems.clear();

		// Clear the panel and add a new table
		wxPanel* argPanel = findNamedObject<wxPanel>(this, "ConvCmdEditorArgPanel");
		argPanel->DestroyChildren();

		// Create the table
		wxFlexGridSizer* table = new wxFlexGridSizer(static_cast<int>(cmdInfo.arguments.size()), 3, 6, 12);
		table->AddGrowableCol(1);

		argPanel->SetSizer(table);

		if (cmdInfo.arguments.empty())
		{
			wxStaticText* noneText = new wxStaticText(argPanel, wxID_ANY, _("None"));
			noneText->SetFont(noneText->GetFont().Italic());
			argPanel->GetSizer()->Add(noneText, 0, wxLEFT, 6);
			return;
		}

		// Setup the table with default spacings
		typedef conversation::ConversationCommandInfo::ArgumentInfoList::const_iterator ArgumentIter;

		int index = 1;

		for (ArgumentIter i = cmdInfo.arguments.begin();
			 i != cmdInfo.arguments.end(); ++i, ++index)
		{
			const conversation::ArgumentInfo& argInfo = *i;

			CommandArgumentItemPtr item;

			switch (argInfo.type)
			{
			case conversation::ArgumentInfo::ARGTYPE_BOOL:
				// Create a new bool argument item
				item = CommandArgumentItemPtr(new BooleanArgument(argPanel, argInfo));
				break;
			case conversation::ArgumentInfo::ARGTYPE_INT:
			case conversation::ArgumentInfo::ARGTYPE_FLOAT:
			case conversation::ArgumentInfo::ARGTYPE_STRING:
				// Create a new string argument item
				item = CommandArgumentItemPtr(new StringArgument(argPanel, argInfo));
				break;
			case conversation::ArgumentInfo::ARGTYPE_VECTOR:
			case conversation::ArgumentInfo::ARGTYPE_SOUNDSHADER:
				// Create a new string argument item
				item = CommandArgumentItemPtr(new StringArgument(argPanel, argInfo));
				break;
			case conversation::ArgumentInfo::ARGTYPE_ACTOR:
				// Create a new actor argument item
				item = CommandArgumentItemPtr(new ActorArgument(argPanel, argInfo, _conversation.actors));
				break;
			case conversation::ArgumentInfo::ARGTYPE_ENTITY:
				// Create a new string argument item
				item = CommandArgumentItemPtr(new StringArgument(argPanel, argInfo));
				break;
			default:
				rError() << "Unknown command argument type: " << argInfo.type << std::endl;
				break;
			};

			if (item != NULL)
			{
				_argumentItems.push_back(item);

				// The label
				table->Add(item->getLabelWidget(), 0, wxALIGN_CENTER_VERTICAL | wxLEFT, 6);

				// The edit widgets
				table->Add(item->getEditWidget(), 1, wxEXPAND, wxALIGN_CENTER_VERTICAL);
				
				// The help widgets
				table->Add(item->getHelpWidget(), 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxRIGHT, 6);
			}
		}
	}
	catch (std::runtime_error&)
	{
		rError() << "Cannot find conversation command info for index " << commandTypeID << std::endl;
	}

	wxPanel* mainPanel = findNamedObject<wxPanel>(this, "ConvCmdEditorMainPanel");
	mainPanel->Fit();
	mainPanel->Layout();
	Fit();
}
Example #6
0
bool rSdpaLib::dumpInit(const char* filename)
{
  ofstream output;
  output.open(filename);
  if (output.fail()) {
    rError("Cannot Open " << filename);
  }
  output << "{ ";
  for (int k = 0; k<m ; ++k) {
    output << -initPt.yVec.ele[k] << " ";
  }
  output << "}";
  output << '\n';
  for (int l=0; l<nBlock; ++l) {
    int size;
	int i = 0;
    switch (initPt.zMat.ele[l].De_Di) {
    case rDenseMatrix::DENSE:
      size = initPt.zMat.ele[l].nRow;
      for (i=0; i<size; ++i) {
	for (int j=0; j<size; ++j) {
	  double value = initPt.zMat.ele[l].de_ele[i+size*j];
	  if (i<=j && value!=0.0) {
	    output << "1 " << l+1 << " "
		   << i+1 << " " << j+1 << " "
		   << value << '\n';
	  }
	}
      }
      break;
    case rDenseMatrix::DIAGONAL:
      for (int index = 0; index < initPt.zMat.ele[l].nRow; ++index) {
	double value = initPt.zMat.ele[l].di_ele[index];
	if (value!=0.0) {
	  output << "1 " << l+1 << " "
		 << index+1 << " " << index+1 << " "
		 << value << '\n';
	}
      }
	break;
    } // end of switch
  }// end of 'for (int l)'
  for (int l=0; l<nBlock; ++l) {
    int size;
	int i = 0;
    switch (initPt.xMat.ele[l].De_Di) {
    case rDenseMatrix::DENSE:
      size = initPt.xMat.ele[l].nRow;
      for (i=0; i<size; ++i) {
	for (int j=0; j<size; ++j) {
	  double value = initPt.xMat.ele[l].de_ele[i+size*j];
	  if (i<=j && value!=0.0) {
	    output << "2 " << l+1 << " "
		   << i+1 << " " << j+1 << " "
		   << value << '\n';
	  }
	}
      }
      break;
    case rDenseMatrix::DIAGONAL:
      for (int index = 0; index < initPt.xMat.ele[l].nRow; ++index) {
	double value = initPt.xMat.ele[l].di_ele[index];
	if (value!=0.0) {
	  output << "2 " << l+1 << " "
		 << index+1 << " " << index+1 << " "
		 << value << '\n';
	}
      }
	break;
    } // end of switch
  }// end of 'for (int l)'
  output.close();
  return true;
}
// Required entity visit function
void ConversationKeyExtractor::operator()(const std::string& key, const std::string& value) 
{
	// Quick discard of any non-conversation keys
	if (key.substr(0, 4) != "conv") return;

	// Extract the objective number
	static const std::regex reConvNum("conv_(\\d+)_(.*)");
	std::smatch results;
	int iNum;

	if (!std::regex_match(key, results, reConvNum)) {
		// No match, abort
		return;
	}

	// Get the conversation number
	iNum = string::convert<int>(results[1].str());

	// We now have the conversation number and the substring (everything after
	// "conv_<n>_" which applies to this conversation.
	std::string convSubString = results[2];

	// Switch on the substring
	if (convSubString == "name") {
		_convMap[iNum].name = value;
	}
	else if (convSubString == "talk_distance") {
		_convMap[iNum].talkDistance = string::convert<float>(value, 60);
	}
	else if (convSubString == "actors_must_be_within_talkdistance") {
		_convMap[iNum].actorsMustBeWithinTalkdistance = (value == "1");
	}
	else if (convSubString == "actors_always_face_each_other_while_talking") {
		_convMap[iNum].actorsAlwaysFaceEachOther = (value == "1");
	}
	else if (convSubString == "max_play_count") {
		_convMap[iNum].maxPlayCount = string::convert<int>(value, -1);
	}
	else if (convSubString.substr(0, 6) == "actor_") {
		// This is an actor definition, extract the number
		int actorNum = string::convert<int>(convSubString.substr(6), -1);

		if (actorNum == -1) {
			return;
		}

		// Store the actor in the map
		_convMap[iNum].actors.insert(Conversation::ActorMap::value_type(actorNum, value));
	}
	else if (convSubString.substr(0, 4) == "cmd_") {
		// This is a conversation command, form a new regex
		static const std::regex reCommand("cmd_(\\d+)_(.*)");
		std::smatch cmdResults;

		if (!std::regex_match(convSubString, cmdResults, reCommand)) {
			return; // not matching
		}

		int cmdIndex = string::convert<int>(cmdResults[1].str());
		std::string cmdSubStr = cmdResults[2];

		ConversationCommandPtr command;
		Conversation::CommandMap::iterator found = _convMap[iNum].commands.find(cmdIndex);

		if (found != _convMap[iNum].commands.end()) {
			// Command already exists
			command = found->second;
		}
		else {
			// Command with the given index does not exist yet, create it
			command = ConversationCommandPtr(new ConversationCommand);

			// Insert this into the map
			_convMap[iNum].commands[cmdIndex] = command;
		}

		if (cmdSubStr == "type") {
			try {
				command->type = ConversationCommandLibrary::Instance().findCommandInfo(value).id;
			}
			catch (std::runtime_error& e) {
				rError() << e.what() << std::endl;
				return;
			}
		}
		else if (cmdSubStr == "actor") {
			command->actor = string::convert<int>(value);
		}
		else if (cmdSubStr == "wait_until_finished") {
			command->waitUntilFinished = (value == "1");
		}
		else if (cmdSubStr.substr(0,4) == "arg_") {
			int cmdArgIndex = string::convert<int>(cmdSubStr.substr(4));

			command->arguments[cmdArgIndex] = value;
		}
	}
}
Example #8
0
void rSparseMatrix::
initialize(int nRow, int nCol,
	   rSparseMatrix::rSpMat_Sp_De_Di Sp_De_Di,
	   int NonZeroNumber)
{
  // rMessage("rSparseMatrix initialize");

  rSparseMatrix();
  if (nRow<=0 || nCol<=0) {
    rError("rSparseMatrix:: Dimensions are nonpositive");
  }
  this->nRow          = nRow;
  this->nCol          = nCol;
  this->Sp_De_Di      = Sp_De_Di;

  int length;
	row_index = NULL;
	column_index = NULL;
	sp_ele = NULL;
  switch(Sp_De_Di) {
  case SPARSE:
    this->NonZeroNumber  = NonZeroNumber;
    this->NonZeroCount   = 0;
    this->NonZeroEffect  = 0;
    if (NonZeroNumber > 0) {
      rNewCheck();
      row_index    = new int[NonZeroNumber];
      rNewCheck();
      column_index = new int[NonZeroNumber];
      rNewCheck();
      sp_ele       = new double[NonZeroNumber];
      if (row_index==NULL || column_index==NULL
	  || sp_ele==NULL) {
	rError("rSparseMatrix:: memory exhausted");
      }
    }
    break;
  case DENSE:
    this->NonZeroNumber = nRow*nCol;
    this->NonZeroCount  = nRow*nCol;
    this->NonZeroEffect = nRow*nCol;
    rNewCheck();
    de_ele = new double[NonZeroNumber];
    if (de_ele==NULL) {
      rError("rSparseMatrix:: memory exhausted");
    }
    length = nRow*nCol;
    catlas_dset(length,DZERO,de_ele,IONE);
    // all elements are 0.
    break;
  case DIAGONAL:
    if (nRow!=nCol) {
      rError("rSparseMatrix:: Diagonal must be Square matrix");
    }
    this->NonZeroNumber = nCol;
    this->NonZeroCount  = nCol;
    this->NonZeroEffect = nCol;
    if (di_ele==NULL) {
      rNewCheck();
      di_ele = new double[NonZeroNumber];
      if (di_ele==NULL) {
	rError("rSparseMatrix:: memory exhausted");
      }
    }
    catlas_dset(nCol,DZERO,di_ele,IONE);
    // all elements are 0.

    break;
  }
}
Example #9
0
bool rSparseMatrix::copyFrom(rSparseMatrix& other)
{
  if (Sp_De_Di != other.Sp_De_Di || nRow != other.nRow
      || nCol != other.nCol) {
    this->~rSparseMatrix();
    initialize(other.nRow,other.nCol,other.Sp_De_Di,
	       NonZeroNumber);
    NonZeroCount  = other.NonZeroCount;
    NonZeroEffect = other.NonZeroEffect;
    int length,index=0;
    switch(Sp_De_Di) {
    case SPARSE:
      for (index = 0; index<NonZeroCount;++index) {
	row_index[index]    = other.row_index[index];
	column_index[index] = other.column_index[index];
	sp_ele[index]       = other.sp_ele[index];
      }
      break;
    case DENSE:
      length = nRow*nCol;
      dcopy(&length,other.de_ele,&IONE,de_ele,&IONE);
      break;
    case DIAGONAL:
      dcopy(&nCol,other.di_ele,&IONE,di_ele,&IONE);
      break;
    }
  } else { // Sp_De_Di == other.Sp_De_Di
           // && nRow == other.nRow && nCol == other.nCol
    NonZeroCount  = other.NonZeroCount;
    NonZeroEffect = other.NonZeroEffect;
    int length,index=0;
    switch(Sp_De_Di) {
    case SPARSE:
      if (NonZeroNumber!=other.NonZeroNumber) {
	delete[] row_index;
	delete[] column_index;
	delete[] sp_ele;
	row_index = column_index = NULL;
	sp_ele = NULL;
	rNewCheck();
	row_index    = new int[NonZeroNumber];
	rNewCheck();
	column_index = new int[NonZeroNumber];
	rNewCheck();
	sp_ele       = new double[NonZeroNumber];
	if (row_index==NULL || column_index==NULL
	    || sp_ele==NULL) {
	  rError("rSparseMatrix:: memory exhausted");
	}
      }
      for (index = 0; index<NonZeroCount;++index) {
	row_index[index]    = other.row_index[index];
	column_index[index] = other.column_index[index];
	sp_ele[index]       = other.sp_ele[index];
      }
      break;
    case DENSE:
      length = nRow*nCol;
      dcopy(&length,other.de_ele,&IONE,de_ele,&IONE);
      break;
    case DIAGONAL:
      dcopy(&nCol,other.di_ele,&IONE,di_ele,&IONE);
      break;
    } // end of switch
  } // end of else
  return _SUCCESS;
}
// Set the model, this also resets the camera
void AnimationPreview::setModelNode(const scene::INodePtr& node)
{
	// Ensure that this is an MD5 model node
	model::ModelNodePtr model = Node_getModel(node);
	
	if (!model)
	{
		rError() << "AnimationPreview::setModelNode: node is not a model." << std::endl;
		_model.reset();
		return;
	}

	// Set up the scene
	if (!_entity)
	{
		setupSceneGraph();
	}

	try
	{
		dynamic_cast<const md5::IMD5Model&>(model->getIModel());
	}
	catch (std::bad_cast&)
	{
		rError() << "AnimationPreview::setModelNode: modelnode doesn't contain an MD5 model." << std::endl;
		_model.reset();
		return;
	}

	if (_model)
	{
		_entity->removeChildNode(_model);
	}

	_model = node;

	// Set the animation to play
	dynamic_cast<md5::IMD5Model&>(model->getIModel()).setAnim(_anim);

	// AddChildNode also tells the model which renderentity it is attached to
	_entity->addChildNode(_model);

	if (_model != NULL)
	{
		// Reset preview time
		stopPlayback();

		// Reset the rotation to the default one
		_rotation = Matrix4::getRotation(Vector3(0,-1,0), Vector3(0,-0.3f,1));
		_rotation.multiplyBy(Matrix4::getRotation(Vector3(0,1,0), Vector3(1,-1,0)));
		
		// Use AABB to adjust camera distance
		const AABB& bounds = _model->localAABB();

		if (bounds.isValid())
		{
			_camDist = -5.0f * static_cast<float>(bounds.getRadius());
		}
		else
		{
			// Bounds not valid, fall back to default
			_camDist = -40.0f;
		}

		// Start playback when switching particles
		startPlayback();
	}
	else
	{
		stopPlayback();
	}

	// Redraw
	queueDraw();
}
std::ostream& ApplicationContextImpl::getErrorStream() const {
	return rError();
}
Example #12
0
bool pinpal(char* dataFile, char* initFile, char* outFile,
	    char* paraFile, bool isInitFile, bool isInitSparse,
	    bool isDataSparse, bool isParameter,
	    rParameter::parameterType parameterType,
	    FILE* Display)
{

  rTimeStart(TOTAL_TIME_START1);
  rTimeStart(FILE_READ_START1);
  rComputeTime com;
  
  FILE* fpData      = NULL;
  FILE* fpOut       = NULL;

  if ((fpOut=fopen(outFile,"w"))==NULL) {
    rError("Cannot open out file " << outFile);
  }
  rParameter param;
  param.setDefaultParameter(parameterType);
  if (isParameter) {
    FILE* fpParameter = NULL;
    if ((fpParameter=fopen(paraFile,"r"))==NULL) {
      fprintf(Display,"Cannot open parameter file %s \n",
	      paraFile);
      exit(0);
    } else {
      param.readFile(fpParameter);
      fclose(fpParameter);
    }
  }
  // param.display(Display);

  if ((fpData=fopen(dataFile,"r"))==NULL) {
    rError("Cannot open data file " << dataFile);
  }
  char titleAndComment[LengthOfBuffer];
  int m;
  time_t ltime;
  time( &ltime );
  fprintf(fpOut,"SDPA start at %s",ctime(&ltime));
  rIO::read(fpData,fpOut,m,titleAndComment);
  fprintf(fpOut,"data      is %s\n",dataFile);
  if (paraFile) {
    fprintf(fpOut,"parameter is %s\n",paraFile);
  }
  if (initFile) {
    fprintf(fpOut,"initial   is %s\n",initFile);
  }
  fprintf(fpOut,"out       is %s\n",outFile);

  int nBlock;
  rIO::read(fpData,nBlock);
  int* blockStruct = NULL;
  blockStruct = new int[nBlock];
  if (blockStruct==NULL) {
    rError("Memory exhausted about blockStruct");
  }
  rIO::read(fpData,nBlock,blockStruct);
  int nDim = 0;
  for (int l=0; l<nBlock; ++l) {
    nDim += abs(blockStruct[l]);
  }
  
  // rMessage("b has not been read yet , m = " << m);
  rVector b(m);
  rIO::read(fpData,b);
  // rMessage("b has been read");
  
  rBlockSparseMatrix C;
  rBlockSparseMatrix* A = NULL;
  A = new rBlockSparseMatrix[m];
  if (A==NULL) {
    rError("Memory exhausted about blockStruct");
  }

  long position = ftell(fpData);
  // C,A must be accessed "twice".

  // count numbers of elements of C and A
  int* CNonZeroCount = NULL;
  CNonZeroCount = new int[nBlock];
  if (CNonZeroCount==NULL) {
    rError("Memory exhausted about blockStruct");
  }
  int* ANonZeroCount = NULL;
  ANonZeroCount = new int[nBlock*m];
  if (ANonZeroCount==NULL) {
    rError("Memory exhausted about blockStruct");
  }
  // initialize C and A
  rIO::read(fpData,m,nBlock,blockStruct,
	    CNonZeroCount,ANonZeroCount,isDataSparse);
  // rMessage(" C and A count over");
    
  C.initialize(nBlock,blockStruct);
  for (int l=0; l<nBlock; ++l) {
    int size = blockStruct[l];
    if (size > 0) {
      C.ele[l].initialize(size,size,rSparseMatrix::SPARSE,
			  CNonZeroCount[l]);
    } else {
      C.ele[l].initialize(-size,-size,rSparseMatrix::DIAGONAL,
			  -size);
    }
  }
  for (int k=0; k<m; ++k) {
    A[k].initialize(nBlock,blockStruct);
    for (int l=0; l<nBlock; ++l) {
      int size = blockStruct[l];
      if (size > 0) {
	A[k].ele[l].initialize(size,size,rSparseMatrix::SPARSE,
			       ANonZeroCount[k*nBlock+l]);
      } else {
	A[k].ele[l].initialize(-size,-size,rSparseMatrix::DIAGONAL,
			       -size);
      }
    }
  }
  delete[] CNonZeroCount;
  CNonZeroCount = NULL;
  delete[] ANonZeroCount;
  ANonZeroCount = NULL;
    
  // rMessage(" C and A initialize over");
  rIO::read(fpData, C, A, m, nBlock, blockStruct, position, isDataSparse);
  // rMessage(" C and A have been read");
  fclose(fpData);

#if 0
  fprintf(Display,"C = \n");
  C.display(Display);
  for (int k=0; k<m; ++k) {
    fprintf(Display,"A[%d] = \n",k);
    A[k].display(Display);
  }
#endif

#if 0
  // write  C and A in SDPA sparse data format to file
  ofstream output;
  output.open("dumped.rsdpa.dat-s");
  if (output.fail()) {
    rError("Cannot Open dumped.rsdpa.dat-s");
  }
  output << m << endl;
  output << nBlock << endl;
  for (l = 0; l<nBlock ; ++l) {
    output << blockStruct[l] << " " ;
  }
  output << endl;
  for (k=0; k<m; ++k) {
	output << b.ele[k] << " ";
  }
  output << endl;
  int index=0;
  for (l=0; l<nBlock; ++l) {
    switch (C.ele[l].Sp_De_Di) {
    case rSparseMatrix::SPARSE:
      for (index = 0; index < C.ele[l].NonZeroCount; ++index) {
	int i = C.ele[l].row_index[index];
	int j = C.ele[l].column_index[index];
	double value = C.ele[l].sp_ele[index];
	if (value!=0.0) {
	  output << "0 " << l+1 << " "
		 << i+1 << " " << j+1 << " "
		 << -value << endl;
	}
      }
      break;
    case rSparseMatrix::DENSE:
      break;
    case rSparseMatrix::DIAGONAL:
      for (int index = 0; index < C.ele[l].nRow; ++index) {
	double value = C.ele[l].di_ele[index];
	if (value!=0.0) {
	  output << "0 " << l+1 << " "
		 << index+1 << " " << index+1 << " "
		 << -value << endl;
	}
      }
	break;
    } // end of switch
  }// end of 'for (int l)'

  for (k=0; k<m; ++k) {
    for (int l=0; l<nBlock; ++l) {
      switch (A[k].ele[l].Sp_De_Di) {
      case rSparseMatrix::SPARSE:
	for (index = 0; index < A[k].ele[l].NonZeroCount; ++index) {
	  int i = A[k].ele[l].row_index[index];
	  int j = A[k].ele[l].column_index[index];
	  double value = A[k].ele[l].sp_ele[index];
	  if (value!=0.0) {
	    output << k+1 << " "  << l+1 << " "
		   << i+1 << " " << j+1 << " "
		   << value << endl;
	  }
	}
	break;
      case rSparseMatrix::DENSE:
	break;
      case rSparseMatrix::DIAGONAL:
	for (int index = 0; index < A[k].ele[l].nRow; ++index) {
	  double value = A[k].ele[l].di_ele[index];
	  if (value!=0.0) {
	    output << k+1 << " " << l+1 << " "
		   << index+1 << " " << index+1 << " "
		   << value << endl;
	  }
	}
	break;
      } // end of switch
    } // end of 'for (int l)'
  } // end of 'for (int k)'
  output.close();
#endif
  
#if 0
  rTimeStart(FILE_CHECK_START1);
  // check whether C,A are symmetric or not.
  int lin,iin,jin;
  if (C.sortSparseIndex(lin,iin,jin)==FAILURE) {
    fprintf(Display,"C is not symmetric, block %d,"
	    "(%d,%d) ", lin+1,iin+1,jin+1);
    exit(0);
  }
  for (int k=0; k<m; ++k) {
    if (A[k].sortSparseIndex(lin,iin,jin)==FAILURE) {
      fprintf(Display,"A[%d] is not symmetric, block %d,"
	      "(%d,%d) ", k+1,lin+1,iin+1,jin+1);
      exit(0);
    }
  }
  rTimeEnd(FILE_CHECK_END1);
  com.FileCheck += rTimeCal(FILE_CHECK_START1,
			    FILE_CHECK_END1);
#endif
  
#if 1
  rTimeStart(FILE_CHANGE_START1);
  // if possible , change C and A to Dense
  C.changeToDense();
  for (int k=0; k<m; ++k) {
    A[k].changeToDense();
  }
  rTimeEnd(FILE_CHANGE_END1);
  com.FileChange += rTimeCal(FILE_CHANGE_START1,
			     FILE_CHANGE_END1);
#endif

  // rMessage("C = ");
  // C.display(Display);
  // for (int k=0; k<m; ++k) {
  //   rMessage("A["<<k<<"] = ");
  //   A[k].display(Display);
  //   }
  
  // the end of initialization of C and A

  // set initial solutions.
  rSolutions initPt;
  rSolutions currentPt;

  if (isInitFile) {
    initPt.initializeZero(m,nBlock,blockStruct,com);
    FILE* fpInit = NULL;
    if ((fpInit=fopen(initFile,"r"))==NULL) {
      rError("Cannot open init file " << initFile);
    }
    rIO::read(fpInit,initPt.xMat,initPt.yVec,initPt.zMat, nBlock,
	      blockStruct, isInitSparse);
    fclose(fpInit);
    initPt.initializeResetup(m,nBlock,blockStruct,com);
    currentPt.copyFrom(initPt);
  } else {
    initPt.initialize(m,nBlock,blockStruct,param.lambdaStar,com);
    currentPt.initialize(m,nBlock,blockStruct,param.lambdaStar,com);
  }
  // rMessage("initial pt = ");
  // initPt.display(Display);
  // rMessage("current pt = ");
  // currentPt.display(Display);
  
  
  rTimeEnd(FILE_READ_END1);
  com.FileRead += rTimeCal(FILE_READ_START1,
			   FILE_READ_END1);

  // -------------------------------------------------------------
  // the end of file read
  // -------------------------------------------------------------
  
  rResiduals initRes(m, nBlock, blockStruct, b, C, A, currentPt);
  rResiduals currentRes;
  currentRes.copyFrom(initRes);
  // rMessage("initial currentRes = ");
  // currentRes.display(Display);

  rNewton newton(m, nBlock, blockStruct);
  newton.computeFormula(m,A,0.0,KAPPA);

  rStepLength alpha(1.0,1.0,nBlock, blockStruct);
  rDirectionParameter beta(param.betaStar);
  rSwitch reduction(rSwitch::ON);
  rAverageComplementarity mu(param.lambdaStar);
  rLanczos lanczos(nBlock,blockStruct);
  
  // rMessage("init mu");
  // mu.display();
  if (isInitFile) {
    mu.initialize(nDim, initPt);
  }
  rRatioInitResCurrentRes theta(param, initRes);
  rSolveInfo solveInfo(nDim, b, C, A, initPt, mu.initial,
		       param.omegaStar);
  rPhase phase(initRes, solveInfo, param, nDim);

  int pIteration = 0;
  rIO::printHeader(fpOut, Display);
  // -----------------------------------------------------
  // Here is MAINLOOP
  // -----------------------------------------------------

  rTimeStart(MAIN_LOOP_START1);

  // explicit maxIteration
  // param.maxIteration = 2;
  while (phase.updateCheck(currentRes, solveInfo, param)
	 && pIteration < param.maxIteration) {
    // rMessage(" turn hajimari " << pIteration );
    // Mehrotra's Predictor
    rTimeStart(MEHROTRA_PREDICTOR_START1);

    // set variable of Mehrotra
    reduction.MehrotraPredictor(phase);
    beta.MehrotraPredictor(phase, reduction, param);
    // rMessage("reduction = ");
    // reduction.display();
    // rMessage("phase = ");
    // phase.display();
    // rMessage("beta.predictor.value = " << beta.value);
    
    // rMessage("xMat = ");
    // currentPt.xMat.display();
    // rMessage("zMat = ");
    // currentPt.zMat.display();
    // rMessage(" mu = " << mu.current);

    bool isSuccessCholesky;
    isSuccessCholesky = newton.Mehrotra(rNewton::PREDICTOR,
					m, A, C, mu,
					beta, reduction,
					phase, currentPt,
					currentRes, com);
    if (isSuccessCholesky == false) {
      break;
    }
      
    // rMessage("newton predictor = ");
    // newton.display();
    // rMessage("newton Dy predictor = ");
    // newton.DyVec.display();
    // newton.bMat.display();
    rTimeEnd(MEHROTRA_PREDICTOR_END1);
    com.Predictor += rTimeCal(MEHROTRA_PREDICTOR_START1,
			      MEHROTRA_PREDICTOR_END1);
    
    rTimeStart(STEP_PRE_START1);
    alpha.MehrotraPredictor(b,C,A, currentPt, phase, newton,
			    lanczos, com);
    // rMessage("xMat = ");
    // currentPt.xMat.display();
    // rMessage("zMat = ");
    // currentPt.zMat.display();
    // rMessage("alpha predictor = ");
    // alpha.display();
    // phase.display();
    // rMessage("newton predictor = ");
    // newton.display();
    // rMessage("currentPt = ");
    // currentPt.display();
    rTimeStart(STEP_PRE_END1);
    com.StepPredictor += rTimeCal(STEP_PRE_START1,STEP_PRE_END1);

    // rMessage("alphaStar = " << param.alphaStar);
    // Mehrotra's Corrector
    // rMessage(" Corrector ");
    rTimeStart(CORRECTOR_START1);
    beta.MehrotraCorrector(nDim,phase,alpha,currentPt,
			   newton,mu,param);
    // rMessage("beta corrector = " << beta.value);
    newton.Mehrotra(rNewton::CORRECTOR,m,A,C,mu,beta,reduction,
		    phase, currentPt, currentRes, com);
    // rMessage("currentPt = ");
    // currentPt.display();
    // rMessage("newton corrector = ");
    // newton.display();
    // rMessage("newton Dy corrector = ");
    // newton.DyVec.display();

    rTimeEnd(CORRECTOR_END1);
    com.Corrector += rTimeCal(CORRECTOR_START1,
			      CORRECTOR_END1);
      
    rTimeStart(CORRECTOR_STEP_START1);
    alpha.MehrotraCorrector(nDim, b, C, A, currentPt, phase,
			    reduction, newton, mu, theta,
			    lanczos, param, com);
    // rMessage("alpha corrector = ");
    // alpha.display();
    rTimeEnd(CORRECTOR_STEP_END1);
    com.StepCorrector += rTimeCal(CORRECTOR_STEP_START1,
				  CORRECTOR_STEP_END1);
    // the end of Corrector
    
    rIO::printOneIteration(pIteration, mu, theta, solveInfo,
			   alpha, beta, currentRes, fpOut, Display);

    if (currentPt.update(alpha,newton,com)==false) {
      // if step length is too short,
      // we finish algorithm
      rMessage("cannot move");
      pIteration++;
      break;
    }

    // rMessage("currentPt = ");
    // currentPt.display();
    // rMessage("newton = ");
    // newton.display();

    // rMessage("updated");
    theta.update(reduction,alpha);
    mu.update(nDim,currentPt);
    currentRes.update(m,nBlock,blockStruct,b,C,A,
		      initRes, theta, currentPt, phase, mu,com);
    
    theta.update_exact(initRes,currentRes);
    solveInfo.update(nDim, b, C, initPt, currentPt,
		     currentRes, mu, theta, param);
    pIteration++;

  } // end of MAIN_LOOP

  rTimeEnd(MAIN_LOOP_END1);

  com.MainLoop = rTimeCal(MAIN_LOOP_START1,
			  MAIN_LOOP_END1);
  currentPt.update_last(com);
  currentRes.compute(m,nBlock,blockStruct,b,C,A,currentPt,mu);
  
  rTimeEnd(TOTAL_TIME_END1);
  
  com.TotalTime = rTimeCal(TOTAL_TIME_START1,
			   TOTAL_TIME_END1);

  #if REVERSE_PRIMAL_DUAL
  phase.reverse();
  #endif
#if 1
  rIO::printLastInfo(pIteration, mu, theta, solveInfo, alpha, beta,
		     currentRes, phase, currentPt, com.TotalTime,
		     nDim, b, C, A, com, param, fpOut, Display);
#endif
  // com.display(fpOut);

  if (blockStruct) {
    delete[] blockStruct;
    blockStruct = NULL;
  }

  C.~rBlockSparseMatrix();
  for (int k=0; k<m; ++k) {
    A[k].~rBlockSparseMatrix();
  }
  delete[] A;
  A = NULL;

  
  fprintf(Display,   "  main loop time = %.6f\n",com.MainLoop);
  fprintf(fpOut,   "    main loop time = %.6f\n",com.MainLoop);
  fprintf(Display,   "      total time = %.6f\n",com.TotalTime);
  fprintf(fpOut,   "        total time = %.6f\n",com.TotalTime);
  #if 0
  fprintf(Display,   "file  check time = %.6f\n",com.FileCheck);
  fprintf(fpOut,   "  file  check time = %.6f\n",com.FileCheck);
  fprintf(Display,   "file change time = %.6f\n",com.FileChange);
  fprintf(fpOut,   "  file change time = %.6f\n",com.FileChange);
  #endif
  fprintf(Display,   "file   read time = %.6f\n",com.FileRead);
  fprintf(fpOut,   "  file   read time = %.6f\n",com.FileRead);
  fclose(fpOut);
  
  return true;
}
Example #13
0
void brushMakePrefab(const cmd::ArgumentList& args)
{
	if (args.size() != 1) {
		return;
	}

	if (GlobalSelectionSystem().getSelectionInfo().brushCount != 1)
	{
		// Display a modal error dialog
		gtkutil::MessageBox::ShowError(_("Exactly one brush must be selected for this operation."), GlobalMainFrame().getTopLevelWindow());
		return;
	}

	// First argument contains the number of sides
	int input = args[0].getInt();

	if (input >= eBrushCuboid && input < eNumPrefabTypes) {
		// Boundary checks passed
		EBrushPrefab type = static_cast<EBrushPrefab>(input);

		int minSides = 3;
		int maxSides = Brush::PRISM_MAX_SIDES;

		switch (type)
		{
		case eBrushCuboid:
			// Cuboids don't need to query the number of sides
			Scene_BrushConstructPrefab(GlobalSceneGraph(), type, 0, GlobalTextureBrowser().getSelectedShader());
			return;

		case eBrushPrism:
			minSides = Brush::PRISM_MIN_SIDES;
			maxSides = Brush::PRISM_MAX_SIDES;
			break;

		case eBrushCone:
			minSides = Brush::CONE_MIN_SIDES;
			maxSides = Brush::CONE_MAX_SIDES;
			break;

		case eBrushSphere:
			minSides = Brush::SPHERE_MIN_SIDES;
			maxSides = Brush::SPHERE_MAX_SIDES;
			break;
		default:
			maxSides = 9999;
		};

		ui::QuerySidesDialog dialog(minSides, maxSides);

		int sides = dialog.queryNumberOfSides();

		if (sides != -1)
		{
			Scene_BrushConstructPrefab(GlobalSceneGraph(), type, sides, GlobalTextureBrowser().getSelectedShader());
		}
	}
	else {
		rError() << "BrushMakePrefab: invalid prefab type. Allowed types are: " << std::endl
			<< eBrushCuboid << " = cuboid " << std::endl
			<< eBrushPrism  << " = prism " << std::endl
			<< eBrushCone  << " = cone " << std::endl
			<< eBrushSphere << " = sphere " << std::endl;
	}
}
Example #14
0
void Newton::make_aggrigateIndex_LP(InputData& inputData)
{
  int t, ii, jj;
  
  LP_nBlock = inputData.LP_nBlock;
  NewArray(LP_number,int,LP_nBlock);

  // memory allocate for aggrigateIndex
  NewArray(LP_constraint1,int*,LP_nBlock);
  NewArray(LP_constraint2,int*,LP_nBlock);
  NewArray(LP_blockIndex1,int*,LP_nBlock);
  NewArray(LP_blockIndex2,int*,LP_nBlock);
  NewArray(LP_location_sparse_bMat,int*,LP_nBlock);

  for (int l=0; l<LP_nBlock; l++){
    int size = (inputData.LP_nConstraint[l] + 1) 
      * inputData.LP_nConstraint[l] / 2;
    LP_number[l] = size;
    NewArray(LP_constraint1[l],int,size);
    NewArray(LP_constraint2[l],int,size);
    NewArray(LP_blockIndex1[l],int,size);
    NewArray(LP_blockIndex2[l],int,size);
    NewArray(LP_location_sparse_bMat[l],int,size);
  }

  for (int l = 0; l<LP_nBlock; l++){
    int NonZeroCount = 0;

    for (int k1=0; k1<inputData.LP_nConstraint[l]; k1++){
      int i = inputData.LP_constraint[l][k1];
      int ib = inputData.LP_blockIndex[l][k1];

      for (int k2=0; k2<inputData.LP_nConstraint[l]; k2++){
	int j = inputData.LP_constraint[l][k2];
	int jb = inputData.LP_blockIndex[l][k2];

	if (i < j){
	  continue;
	}

	// set index which A_i and A_j are not zero matrix
	LP_constraint1[l][NonZeroCount] = i;
	LP_constraint2[l][NonZeroCount] = j;
	LP_blockIndex1[l][NonZeroCount] = ib;
	LP_blockIndex2[l][NonZeroCount] = jb;
	if (reverse_ordering[i] < reverse_ordering[j]){
	  ii = reverse_ordering[i];
	  jj = reverse_ordering[j];
	} else {
	  jj = reverse_ordering[i];
	  ii = reverse_ordering[j];
	}

	// binary search for index of sparse_bMat 
        t = -1;
        int begin = diagonalIndex[ii]; 
        int end = diagonalIndex[ii+1]-1;
        int target = (begin + end) / 2;
        while (end - begin > 1){
          if (sparse_bMat.column_index[target] < jj){
            begin = target;
            target = (begin + end) / 2;
          } else if (sparse_bMat.column_index[target] > jj){
            end = target;
            target = (begin + end) / 2;
          } else if (sparse_bMat.column_index[target] == jj){
            t = target;
            break;
          }
        }
        if (t == -1){
          if (sparse_bMat.column_index[begin] == jj){
            t = begin;
          } else if (sparse_bMat.column_index[end] == jj){
            t = end;
          } else {
            rError("Newton::make_aggrigateIndex_SDP  program bug");
          }
        } 

	LP_location_sparse_bMat[l][NonZeroCount] = t;
	NonZeroCount++;
      }
    } // for k1
  } //for k  kth block
}
Example #15
0
void rSdpaLib::inputElement(int k,int l, int i, int j, double value)
{
  k--;
  if (k<-1 || k>=m) {
    #if REVERSE_PRIMAL_DUAL
    rMessage("Over index of F:: " << k+1);
    rError("Length of F :: " << m);
    #else
    rMessage("Over index of A or C:: " << k+1);
    rError("Length of A :: " << m);
    #endif
  }
  l--;
  if (l<0 || l>=nBlock) {
    #if REVERSE_PRIMAL_DUAL
    rMessage("Over nBlock of F:: " << l+1);
    rError("nBlock of F :: " << nBlock);
    #else
    rMessage("Over nBlock of A or C:: " << l+1);
    rError("nBlock of A :: " << nBlock);
    #endif
  }
  i--;
  j--;
  int size = blockStruct[l];
  if (k==-1) {
    rSparseMatrix& target = C.ele[l];
    int count = target.NonZeroCount;
    if (target.Sp_De_Di == rSparseMatrix::SPARSE
	&& count >= target.NonZeroNumber) {
      #if REVERSE_PRIMAL_DUAL
      rError("C.ele[" << (l+1) << "]"
	     << " is too much element which is assigned");
      #else
      rError("F[0].ele[" << (l+1) << "]"
	     << " is too much element which is assigned");
      #endif
    }
    if (size>0) {
      target.row_index[count] = i;
      target.column_index[count] = j;
      #if REVERSE_PRIMAL_DUAL
      target.sp_ele[count] = -value;
      #else
      target.sp_ele[count] = value;
      #endif
      target.NonZeroCount++;
      if (i==j) {
	target.NonZeroEffect++;
      } else {
	target.NonZeroEffect += 2;
      }
    } else {
      #if REVERSE_PRIMAL_DUAL
      target.di_ele[j] = -value;
      #else
      target.di_ele[j] = value;
      #endif
    }
  } else { // k>=0
    rSparseMatrix& target = A[k].ele[l];
    int count = target.NonZeroCount;
    if (target.Sp_De_Di == rSparseMatrix::SPARSE
	&& count >= target.NonZeroNumber) {
      #if REVERSE_PRIMAL_DUAL
      rError("F["<<(k+1)<<"].ele[" << (l+1) << "]"
	     << " is too much element which is assigned");
      #else
      rError("A["<<(k+1)<<"].ele[" << (l+1) << "]"
	     << " is too much element which is assigned");
      #endif
    }
    if (size>0) {
      target.row_index[count] = i;
      target.column_index[count] = j;
      target.sp_ele[count] = value;
      target.NonZeroCount++;
      if (i==j) {
	target.NonZeroEffect++;
      } else {
	target.NonZeroEffect += 2;
      }
    } else {
      target.di_ele[j] = value;
    }
  }
}
Example #16
0
bool rDenseMatrix::copyFrom(rSparseMatrix& other)
{
  int length,index=0;
  switch(other.Sp_De_Di) {
  case rSparseMatrix::SPARSE:
    De_Di = DENSE;
    if (de_ele) {
      delete[] de_ele;
    }
    de_ele = NULL;
    nRow = other.nRow;
    nCol = other.nCol;
    rNewCheck();
    de_ele = new double[nRow*nCol];
    if (de_ele==NULL) {
      rError("rDenseMatrix:: memory exhausted");
    }
    length = nRow*nCol;
    catlas_dset(length,DZERO,de_ele,IONE);
    for (index = 0; index<other.NonZeroCount; ++index) {
      int i = other.row_index[index];
      int j = other.column_index[index];
      double value = other.sp_ele[index];
      de_ele[i+nCol*j] = de_ele[j+nCol*i] = value;
    }
    break;
  case rSparseMatrix::DENSE:
    De_Di = DENSE;
    if (de_ele && (other.nRow!=nRow || other.nCol!=nCol)) {
      delete[] de_ele;
      de_ele = NULL;
    }
    nRow = other.nRow;
    nCol = other.nCol;
    rNewCheck();
    de_ele = new double[nRow*nCol];
    if (de_ele==NULL) {
      rError("rDenseMatrix:: memory exhausted");
    }
    length = nRow*nCol;
    dcopy(&length,other.de_ele,&IONE,de_ele,&IONE);
    break;
  case rSparseMatrix::DIAGONAL:
    De_Di = DIAGONAL;
    if (di_ele && (other.nRow!=nRow || other.nCol!=nCol)) {
      delete[] di_ele;
      di_ele = NULL;
    }
    nRow = other.nRow;
    nCol = other.nCol;
    if (di_ele==NULL) {
      rNewCheck();
      di_ele = new double[nCol];
      if (di_ele==NULL) {
	rError("rDenseMatrix:: memory exhausted");
      }
    }
    dcopy(&nCol,other.di_ele,&IONE,di_ele,&IONE);
    break;
  }
  return _SUCCESS;
}
Example #17
0
bool rSdpaLib::dumpData(const char* filename)
{
  ofstream output;
  output.open(filename);
  if (output.fail()) {
    rError("Cannot Open " << filename);
  }
  output << m << endl;
  output << nBlock << endl;
  for (int l = 0; l<nBlock ; ++l) {
    output << blockStruct[l] << " " ;
  }
  output << '\n';
  output << "{ ";
  for (int k=0; k<m; ++k) {
    output << b.ele[k] << " ";
  }
  output << "}";
  output << '\n';
  for (int l=0; l<nBlock; ++l) {
	  int index = 0;
    switch (C.ele[l].Sp_De_Di) {
    case rSparseMatrix::SPARSE:
      for (index = 0; index < C.ele[l].NonZeroCount; ++index) {
	int i = C.ele[l].row_index[index];
	int j = C.ele[l].column_index[index];
	double value = C.ele[l].sp_ele[index];
	if (value!=0.0) {
	  output << "0 " << l+1 << " "
		 << i+1 << " " << j+1 << " "
		 << -value << '\n';
	}
      }
      break;
    case rSparseMatrix::DENSE:
      // a Matrix must not be DENSE,
      // since it was read as SPARSE or DIAGONAL
      break;
    case rSparseMatrix::DIAGONAL:
      for (index = 0; index < C.ele[l].nRow; ++index) {
	double value = C.ele[l].di_ele[index];
	if (value!=0.0) {
	  output << "0 " << l+1 << " "
		 << index+1 << " " << index+1 << " "
		 << -value << '\n';
	}
      }
	break;
    } // end of switch
  }// end of 'for (int l)'

  for (int k=0; k<m; ++k) {
    for (int l=0; l<nBlock; ++l) {
		int index = 0;
      switch (A[k].ele[l].Sp_De_Di) {
      case rSparseMatrix::SPARSE:
	for (index = 0; index < A[k].ele[l].NonZeroCount;
	     ++index) {
	  int i = A[k].ele[l].row_index[index];
	  int j = A[k].ele[l].column_index[index];
	  double value = A[k].ele[l].sp_ele[index];
	  if (value!=0.0) {
	    output << k+1 << " "  << l+1 << " "
		   << i+1 << " " << j+1 << " "
		   << value << '\n';
	  }
	}
	break;
      case rSparseMatrix::DENSE:
	// a Matrix must not be DENSE,
	// since it was read as SPARSE or DIAGONAL
	break;
      case rSparseMatrix::DIAGONAL:
	for (index = 0; index < A[k].ele[l].nRow; ++index) {
	  double value = A[k].ele[l].di_ele[index];
	  if (value!=0.0) {
	    output << k+1 << " " << l+1 << " "
		   << index+1 << " " << index+1 << " "
		   << value << '\n';
	  }
	}
	break;
      } // end of switch
    } // end of 'for (int l)'
  } // end of 'for (int k)'
  output.close();
  return true;
}
Example #18
0
off_t Compress::writeCompressed(LayerMap& lm, off_t offset, off_t coffset, const char *buf, size_t size, int fd, off_t rawFileSize)
{
	assert(coffset >= FileHeader::MaxSize);

	rDebug("offset: 0x%lx, coffset: 0x%lx, size: 0x%lx",
	       (long int) offset, (long int) coffset, (long int) size);

	Block *bl = NULL;

	try {
		// Append a new Block to the file.

		bl = new Block(g_CompressionType);

		bl->offset = offset;
		bl->coffset = coffset;
		bl->length = size;
		bl->olength = size;

		// Truncate the file to m_RawFileSize.
		//
		// This efectively removes layer map from the file, so if
		// anything wrong happens until store() is called we lost the
		// file!
		//
		// We have to do that until I find a way how to get length of
		// the compressed block that is written by io::write()...
		//
		// OK, I now know how to get length of the compressed block,
		// but I don't know anymore how to use it to avoid the truncation.

		assert(bl->coffset == rawFileSize);
		::ftruncate(fd, bl->coffset);

		// Compress and write block to the file.

		io::nonclosable_file_descriptor file(fd);
		file.seek(bl->coffset, ios_base::beg);
		io::bytescounter length;
		{
			io::filtering_ostream out;

			bl->type.push(out);
			out.push(boost::ref(length));
			out.push(file);

			io::write(out, buf, bl->length);

			// Destroying the object 'out' causes all filters to flush.
		}

		bl->clength = length.bytes();
		coffset = bl->coffset + bl->clength;
	}
	catch (...)
	{
		rError("Failed to add a new Block to the file.");

		delete bl;
		return -1;
	}
	
	assert(bl != NULL);
	lm.Put(bl);

	rDebug("length: 0x%lx", (long int) coffset);

	return coffset;
}
Example #19
0
void rSdpaLib::solve()
{
  if (CheckMatrix) {
    rTimeStart(FILE_CHECK_START1);
      int i=0,j=0,k=0,l=0;
    // this method needs long time
    checkData(k,l,i,j);
    if (i>0 || j>0) {
      rError("checkData stops");
      cout << "constraint " << k <<":"
	   << "block " << l <<":"
	   << "row " << i <<":"
	   << "column " << j << endl;
    }
    rTimeEnd(FILE_CHECK_END1);
    com.FileCheck += rTimeCal(FILE_CHECK_START1,
			      FILE_CHECK_END1);
  }
#if 1
  rTimeStart(FILE_CHANGE_START1);
  // if possible, change C and A to Dense type matrices.
  C.changeToDense();
  for (int k=0; k<m; ++k) {
    A[k].changeToDense();
  }
  rTimeEnd(FILE_CHANGE_END1);
  com.FileChange += rTimeCal(FILE_CHANGE_START1,
			     FILE_CHANGE_END1);
#endif

  if (InitialPoint) {
    initPt.initializeResetup(m,nBlock,blockStruct,com);
    currentPt.copyFrom(initPt);
    // rMessage("initialize? ");
  } else {
    currentPt.initialize(m,nBlock,blockStruct,pARAM.lambdaStar,com);
  }
  // rMessage("initPt = ");
  // initPt.display();
  // rMessage("currentPt = ");
  // currentPt.display();
  initRes.initialize(m, nBlock, blockStruct, b, C, A, currentPt);
  currentRes.copyFrom(initRes);
  // rMessage("initial currentRes = ");
  // currentRes.display();

  newton.initialize(m, nBlock, blockStruct);
  newton.computeFormula(m,A,0.0,KAPPA);

  alpha.initialize(1.0,1.0,nBlock, blockStruct);
  beta.initialize(pARAM.betaStar);
  reduction.initialize(rSwitch::ON);
  mu.initialize(pARAM.lambdaStar);
  lanczos.initialize(nBlock,blockStruct);

  if (InitialPoint) {
    mu.initialize(nDim,initPt);
  }

  theta.initialize(pARAM,initRes);
  solveInfo.initialize(nDim, b, C, A, initPt, mu.initial,
		       pARAM.omegaStar);
  phase.initialize(initRes, solveInfo, pARAM, nDim);

  rIO::printHeader(OutputFile,DisplayInformation);
  
  int pIteration = 0;

  // -----------------------------------------------------
  // Here is MAINLOOP
  // -----------------------------------------------------

  rTimeStart(MAIN_LOOP_START1);

  // explisit maxIteration
  // pARAM.maxIteration = 100;
  while (phase.updateCheck(currentRes, solveInfo, pARAM)
	 && pIteration < pARAM.maxIteration) {
    // rMessage(" turn hajimari " << pIteration );

    #if 0
    if (alpha.primal<1.0e-5 && alpha.dual<1.0e-5) {
      break;
    }
    #endif

    // Mehrotra's Predictor
    rTimeStart(MEHROTRA_PREDICTOR_START1);

    // calculate variables of Mehrotra
    reduction.MehrotraPredictor(phase);
    beta.MehrotraPredictor(phase, reduction, pARAM);
    // rMessage("reduction = ");
    // reduction.display();
    // rMessage("phase = ");
    // phase.display();
    // rMessage("beta.predictor.value = " << beta.value);
    
    // rMessage("xMat = ");
    // currentPt.xMat.display();
    // rMessage("zMat = ");
    // currentPt.zMat.display();
    // rMessage(" mu = " << mu.current);

    bool isSuccessCholesky;
    isSuccessCholesky = newton.Mehrotra(rNewton::PREDICTOR,
					m, A, C, mu,
					beta, reduction,
					phase, currentPt,
					currentRes, com);
    if (isSuccessCholesky == false) {
      break;
    }
      
    // rMessage("newton predictor = ");
    // newton.display();
    // rMessage("newton Dy predictor = ");
    // newton.DyVec.display();
    // newton.bMat.display();
    rTimeEnd(MEHROTRA_PREDICTOR_END1);
    com.Predictor += rTimeCal(MEHROTRA_PREDICTOR_START1,
			      MEHROTRA_PREDICTOR_END1);
    
    rTimeStart(STEP_PRE_START1);
    alpha.MehrotraPredictor(b,C,A, currentPt, phase,
			    newton, lanczos, com);
    // rMessage("xMat = ");
    // currentPt.xMat.display();
    // rMessage("zMat = ");
    // currentPt.zMat.display();
    // rMessage("alpha predictor = ");
    // alpha.display();
    // phase.display();
    // rMessage("newton predictor = ");
    // newton.display();
    // rMessage("currentPt = ");
    // currentPt.display();
    rTimeStart(STEP_PRE_END1);
    com.StepPredictor += rTimeCal(STEP_PRE_START1,STEP_PRE_END1);

    // rMessage("alphaStar = " << pARAM.alphaStar);
    // Mehrotra's Corrector
    // rMessage(" Corrector ");
    rTimeStart(CORRECTOR_START1);
    beta.MehrotraCorrector(nDim,phase,alpha,currentPt,
			   newton,mu,pARAM);
    // rMessage("beta corrector = " << beta.value);
    newton.Mehrotra(rNewton::CORRECTOR,m,A,C,mu,beta,reduction,
		    phase, currentPt, currentRes, com);
    // rMessage("currentPt = ");
    // currentPt.display();
    // rMessage("newton corrector = ");
    // newton.display();
    // rMessage("newton Dy corrector = ");
    // newton.DyVec.display();

    rTimeEnd(CORRECTOR_END1);
    com.Corrector += rTimeCal(CORRECTOR_START1,
			      CORRECTOR_END1);
      
    rTimeStart(CORRECTOR_STEP_START1);
    alpha.MehrotraCorrector(nDim, b, C, A, currentPt, phase,
			    reduction, newton, mu, theta,
			    lanczos, pARAM, com);
    // rMessage("alpha corrector = ");
    // alpha.display();
    rTimeEnd(CORRECTOR_STEP_END1);
    com.StepCorrector += rTimeCal(CORRECTOR_STEP_START1,
				  CORRECTOR_STEP_END1);
    // the end of Corrector
    
    rIO::printOneIteration(pIteration, mu, theta, solveInfo,
			   alpha, beta, currentRes, OutputFile,
			   DisplayInformation);

    if (currentPt.update(alpha,newton,com)==false) {
      // if step length is too short,
      // the algorithm ends.
      // rMessage("cannot move");
      pIteration++;
      break;
    }

    // rMessage("currentPt = ");
    // currentPt.display();
    // rMessage("newton = ");
    // newton.display();

    // rMessage("updated");
    theta.update(reduction,alpha);
    mu.update(nDim,currentPt);
    currentRes.update(m,nBlock,blockStruct,b,C,A,
		      initRes, theta, currentPt, phase, mu,com);
    
    theta.update_exact(initRes,currentRes);
    solveInfo.update(nDim, b, C, initPt, currentPt,
		     currentRes, mu, theta, pARAM);
    pIteration++;

  } // end of MAIN_LOOP

  rTimeEnd(MAIN_LOOP_END1);

  com.MainLoop = rTimeCal(MAIN_LOOP_START1,
			  MAIN_LOOP_END1);
  currentPt.update_last(com);
  currentRes.compute(m,nBlock,blockStruct,b,C,A,currentPt,mu);
  rIO::printLastInfo(pIteration, mu, theta, solveInfo, alpha, beta,
		     currentRes, phase, currentPt, com.TotalTime,
		     nDim,b,C,A,com,pARAM, OutputFile,
		     DisplayInformation,false);

  #if REVERSE_PRIMAL_DUAL
  // reverse the sign of y and phase
  rAl::let(currentPt.yVec,'=',currentPt.yVec,'*',&DMONE);
  phase.reverse();
  #endif
  
  iteration = pIteration;

  // for compability SDPA
  PrimalObj    = getPrimalObj();
  DualObj      = getDualObj();
  PrimalError  = getPrimalError();
  DualError    = getDualError();
  Iteration    = getIteration();
  switch (phase.value) {
  case rSolveInfo::noINFO    : Value = ::noINFO;      break;
  case rSolveInfo::pFEAS     : Value = ::pFEAS;       break;
  case rSolveInfo::dFEAS     : Value = ::dFEAS;       break;
  case rSolveInfo::pdFEAS    : Value = ::pdFEAS;      break;
  case rSolveInfo::pdINF     : Value = ::pdINF;       break;
  case rSolveInfo::pFEAS_dINF: Value = ::pFEAS_dINF;  break;
  case rSolveInfo::pINF_dFEAS: Value = ::pINF_dFEAS;  break;
  case rSolveInfo::pdOPT     : Value = ::pdOPT;       break;
  case rSolveInfo::pUNBD     : Value = ::pUNBD;       break;
  case rSolveInfo::dUNBD     : Value = ::dUNBD;       break;
  }
}
Example #20
0
/* m_fh.size, m_lm */
ssize_t Compress::readCompressed(char *buf, size_t size, off_t offset, int fd) const
{
	Block	 block;
	size_t	 osize;
	off_t	 len;

	if (offset + (off_t) size > m_fh.size)
	{
		if (m_fh.size > offset)
		{
			size = m_fh.size - offset;
		} else
			size = 0;
	}
	osize = size;

	while (size > 0)
	{
		if (!m_lm.Get(offset, block, len))
		{
			// Block not found. There also is no block on a upper
			// offset.
			//
			memset(buf, 0, size);
			size = 0;
			break;
		}

		if (len)
		{
			// Block covers the offset, we can read len bytes
			// from it's de-compressed stream...

			off_t r;

			try {
				r = readBlock(fd, block, size, len, offset, buf);
			}
			catch (...)
			{
				rError("%s: Block read failed: block.offset:%lx, block.coffset:%lx, block.length: %lx, block.clength: %lx",
					__PRETTY_FUNCTION__, (long int) block.offset, (long int) block.coffset,
				        (long int) block.length, (long int) block.clength);
				return -1;
			}

			buf += r;
			offset += r;
			size -= r;
		}
		else
		{
			off_t r;

			// Block doesn't exists on the offset, but there is
			// a Block on the bigger offset. Fill the gap with
			// zeroes...

			r = min(block.offset - offset, (off_t) (size));

			memset(buf, 0, r);

			buf += r;
			offset += r;
			size -= r;
		}
	}

	return osize - size;
}
Example #21
0
int compress(const char *i, const struct stat *i_st, int mode, struct FTW *n)
{
	if (!((mode == FTW_F) && (S_ISREG(i_st->st_mode))))
		return 0;

    fs::path input(i
#if BOOST_VERSION <= 104600
            , fs::native
#endif
            );
	fs::path input_directory(input.branch_path());
	fs::path output(input_directory / "XXXXXX");
	
	rInfo("Processing file (%s)", input.string().c_str());

	// Remember times of the input file.

	struct stat stbuf;
	lstat(input.string().c_str(), &stbuf);

	int o_fd = mkstemp(const_cast<char *>(output.string().c_str()));
	if (o_fd < 0)
	{
		rError("Failed to create an temporary file in (%s) directory", input_directory.string().c_str());
		return -1;
	}

	rInfo("Temporary file (%s)", output.string().c_str());

	struct stat o_st;
	if (fstat(o_fd, &o_st) == -1)
	{
		rError("Failed to read stat of temporary file (%s)", output.string().c_str());
		close(o_fd);
		return -1;
	}
	close(o_fd);

	if (!copy(i, output.string().c_str(), i_st, &o_st))
	{
		unlink(output.string().c_str());
		return -1;
	}

	if (rename(output.string().c_str(), i) == -1)
	{
		rError("Failed to rename temporary file (%s) to (%s) (%s)", output.string().c_str(), input.string().c_str(), strerror(errno));
		return -1;
	}

	if (chmod(i, i_st->st_mode) == -1)
	{
		rError("Failed to change mode (%s) (%s)", input.string().c_str(), strerror(errno));
		return -1;
	}

	// Write back original times.

	struct timespec times[2];
	times[0].tv_sec = stbuf.st_atime;
	times[0].tv_nsec = stbuf.st_atim.tv_nsec;
	times[1].tv_sec = stbuf.st_mtime;
	times[1].tv_nsec = stbuf.st_mtim.tv_nsec;
	utimensat(AT_FDCWD, i, times, AT_SYMLINK_NOFOLLOW);
	
	return 0;
}
Example #22
0
off_t Compress::cleverCopy(int readFd, off_t writeOffset, int writeFd, LayerMap& writeLm)
{
	off_t offset = 0;
	off_t size = m_fh.size;

	Block	 block;
	off_t	 len;

	while (size > 0)
	{
		if (!m_lm.Get(offset, block, len))
		{
			// Block not found. There also is no block on a upper
			// offset.
			//
			break;
		}

		if (len)
		{
			// Block covers the offset, we can read len bytes
			// from it's de-compressed stream...

			try {
				boost::scoped_array<char> buf(new char[block.length]);

				// Read old block (or part of it we need)...

				off_t r = readBlock(readFd, block, size, len, offset, buf.get());

				// Write new block...

				writeOffset = writeCompressed(writeLm, offset, writeOffset, buf.get(), r, writeFd, writeOffset);
				if (writeOffset == -1)
					return -1;

				assert (r == writeOffset);

				offset += r;
				size -= r;
			}
			catch (...)
			{
				rError("%s: Block read failed: block.offset:%lx, block.coffset:%lx, block.length: %lx, block.clength: %lx",
					__PRETTY_FUNCTION__, (long int) block.offset, (long int) block.coffset,
				        (long int) block.length, (long int) block.clength);
				return -1;
			}
		}
		else
		{
			off_t r;

			// Block doesn't exists on the offset, but there is
			// a Block on the bigger offset.

			r = min(block.offset - offset, (off_t) (size));

			offset += r;
			size -= r;
		}
	}

	return writeOffset;
}
Example #23
0
bool copy(const char *i, const char *o, const struct stat *i_st, const struct stat *o_st)
{
	Compress input(i_st, i);

	int i_fd = input.open(i, O_RDONLY);
	if (i_fd == -1)
	{
		rError("File (%s) cannot be opened! (%s)", i, strerror(errno));
		return false;
	}

	if (input.isCompressed() == false)
	{
		rInfo(" Not compressed");

		if (g_RawOutput)
		{
			rInfo(" Skipped");

			// Input file is not compressed an user wants
			// to decomrpess file. Return now.

			input.release(i);
			return false;
		}
	}
	else
	{
		rInfo(" Compressed");

		if (g_RawOutput)
		{
		}
		else
		{
			if (input.isCompressedOnlyWith(g_CompressionType))
			{
				rInfo(" All blocks compressed with the same compression method");

				// Input file is compressed only with
				// the same compression type as user wants.
				// Return now.

				input.release(i);
				return false;
			}
			rInfo(" Some block(s) compressed with different compression method than others");
		}
	}

	Compress output(o_st, o);

	if (g_RawOutput)
	{
		output.setCompressed(false);
	}

	boost::scoped_array<char> buffer(new char[g_BufferedMemorySize]);

	int o_fd = output.open(o, O_WRONLY);
	if (o_fd == -1)
	{
		rError("File (%s) cannot be opened! (%s)", o, strerror(errno));
		input.release(i);
		return false;
	}

	// Get the apparent input file size.

	struct stat st;
	int r = input.getattr(i, &st);
	if (r == -1)
	{
		rError("Cannot determine apparent size of input file (%s) (%s)", i, strerror(errno));
		input.release(i);
		return false;
	}

	rInfo(" Processing");

	for (off_t off = 0; off < st.st_size; off += g_BufferedMemorySize)
	{
		if (g_BreakFlag)
		{
			rWarning("Interrupted when processing file (%s)", i);
			rWarning("File is left untouched");
			input.release(i);
			output.release(o);
			return false;
		}
		off_t r = input.read(buffer.get(), g_BufferedMemorySize, off);
		if (r == -1)
		{
			rError("Read failed! (offset: %lld, size: %lld)", (unsigned long long) off ,(unsigned long long) g_BufferedMemorySize);
			input.release(i);
			output.release(o);
			return false;
		}
		off_t rr = output.write(buffer.get(), r, off);
		if (rr != r)
		{
			rError("Write failed! (offset: %lld, size: %lld)", (unsigned long long) off , (unsigned long long) r);
			input.release(i);
			output.release(o);
			return false;
		}
	}

	// Remember extended attributes.

	FileRememberXattrs xattrs;
	xattrs.read(i_fd);
	xattrs.write(o_fd);

	input.release(i);
	output.release(o);
	return true;
}
Example #24
0
void Compress::DefragmentFast()
{
	rDebug("%s", __PRETTY_FUNCTION__);

	struct stat st;
	struct timespec m_times[2];

	::fstat(m_fd, &st);
	m_times[0].tv_sec = st.st_atime;
	m_times[0].tv_nsec = st.st_atim.tv_nsec;
	m_times[1].tv_sec = st.st_mtime;
	m_times[1].tv_nsec = st.st_mtim.tv_nsec;

	// Prepare a temporary file.

	char tmp_name[] = "./.fc.XXXXXX";

	int tmp_fd = mkstemp(tmp_name);
	if (tmp_fd < 0)
	{
		// EINVAL would be a programmer error.
		//
		assert(errno != EINVAL);

		rError("%s: Temporary file creation failed with errno: %d", __PRETTY_FUNCTION__, errno);
		return;
	}

	// Reserve space for a FileHeader.

	off_t tmp_offset = FileHeader::MaxSize;

	// Temporary file prepared, now do the deframentation.

	LayerMap tmp_lm;

	tmp_offset = cleverCopy(m_fd, tmp_offset, tmp_fd, tmp_lm);
//	tmp_offset = copy(m_fd, tmp_offset, tmp_fd, tmp_lm);

	if (tmp_offset == -1)
	{
		::unlink(tmp_name);
		::close(tmp_fd);
		return;
	}

	::fchmod(tmp_fd, st.st_mode);
	::fchown(tmp_fd, st.st_uid, st.st_gid);
	::futimens(tmp_fd, m_times);

	::close(m_fd);
	m_fd = tmp_fd;

	// Store new file header and layer map to the new file.
	// m_fd contains file descriptor of the new file and
	// file header is the same except m_fh.index but
	// the index will be updated in the store() function.
	// Update m_RawFileSize to tell store() where save the
	// index and set m_lm to layer map of the new file.

	m_RawFileSize = tmp_offset;

	// Set index to zero (no index). Index will be set to
	// correct value in store according to m_RawFileSize and
	// existence of modified layer map.

	m_fh.index = 0;

	m_lm = tmp_lm;

	store();

	// The inode number of the lower file will be changed
	// by rename so we have to update the g_FileManager to reflect
	// that change. Without this update the g_FileManager
	// would create an another File object for the same file.

	::fstat(tmp_fd, &st);

	g_FileManager->Lock();
	g_FileManager->UpdateUnlocked(dynamic_cast<CFile*>(this), st.st_ino);

	if (::rename(tmp_name, m_name.c_str()) == -1)
	{
		g_FileManager->Unlock();

		rError("Cannot rename '%s' to '%s'", tmp_name, m_name.c_str());
		return;
	}

	g_FileManager->Unlock();
}
Example #25
0
void AutoMapSaver::saveSnapshot() 
{
	// Original GtkRadiant comments:
	// we need to do the following
	// 1. make sure the snapshot directory exists (create it if it doesn't)
	// 2. find out what the lastest save is based on number
	// 3. inc that and save the map

	unsigned int maxSnapshotFolderSize =
		registry::getValue<int>(RKEY_AUTOSAVE_MAX_SNAPSHOT_FOLDER_SIZE);

	// Sanity check in case there is something weird going on in the registry
	if (maxSnapshotFolderSize == 0)
	{
		maxSnapshotFolderSize = 100;
	}

	// Construct the boost::path class out of the full map path (throws on fail)
	Path fullPath = GlobalMap().getMapName();

	// Append the the snapshot folder to the path
	Path snapshotPath = fullPath;
	snapshotPath.remove_filename();
	snapshotPath /= GlobalRegistry().get(RKEY_AUTOSAVE_SNAPSHOTS_FOLDER);

	// Retrieve the mapname
	std::string mapName = os::filename_from_path(fullPath.filename());

	// Check if the folder exists and create it if necessary
	if (boost::filesystem::exists(snapshotPath) || os::makeDirectory(snapshotPath.string()))
	{
		// Reset the size counter of the snapshots folder
		std::size_t folderSize = 0;

		// This holds the target path of the snapshot
		std::string filename;

		for (int nCount = 0; nCount < INT_MAX; nCount++) 
		{
			// Construct the base name without numbered extension
			filename = (snapshotPath / mapName).string();

			// Now append the number and the map extension to the map name
			filename += ".";
			filename += string::to_string(nCount);
			filename += ".";
			filename += game::current::getValue<std::string>(GKEY_MAP_EXTENSION);

			if (os::fileOrDirExists(filename)) 
			{
				// Add to the folder size
				folderSize += file_size(filename.c_str());
			}
			else 
			{
				// We've found an unused filename, break the loop
				break;
			}
		}

		rMessage() << "Autosaving snapshot to " << filename << std::endl;

		// Dump to map to the next available filename
		GlobalMap().saveDirect(filename);

		// Display a warning, if the folder size exceeds the limit
		if (folderSize > maxSnapshotFolderSize*1024*1024)
		{
			rMessage() << "AutoSaver: The snapshot files in " << snapshotPath;
			rMessage() << " total more than " << maxSnapshotFolderSize;
			rMessage() << " MB. You might consider cleaning up." << std::endl;
		}
	}
	else 
	{
		rError() << "Snapshot save failed.. unable to create directory";
		rError() << snapshotPath << std::endl;
	}
}
Example #26
0
bool pinpal(char* dataFile, char* initFile, char* outFile,
	    char* paraFile, bool isInitFile, bool isInitSparse,
	    bool isDataSparse, bool isParameter,
	    Parameter::parameterType parameterType,
	    FILE* Display)
{
  TimeStart(TOTAL_TIME_START1);
  TimeStart(FILE_READ_START1);
  ComputeTime com;

  FILE* fpData      = NULL;
  FILE* fpOut       = NULL;

  if ((fpOut=fopen(outFile,"w"))==NULL) {
    rError("Cannot open out file " << outFile);
  }
  Parameter param;
  param.setDefaultParameter(parameterType);
  if (isParameter) {
    FILE* fpParameter = NULL;
    if ((fpParameter=fopen(paraFile,"r"))==NULL) {
      fprintf(Display,"Cannot open parameter file %s \n",
	      paraFile);
      exit(0);
    } else {
      param.readFile(fpParameter);
      fclose(fpParameter);
    }
  }
  
  // param.display(Display,param.infPrint);

  if ((fpData=fopen(dataFile,"r"))==NULL) {
    rError("Cannot open data file " << dataFile);
  }
  char titleAndComment[LengthOfBuffer];
  int m;
  time_t ltime;
  time( &ltime );
  fprintf(fpOut,"SDPA start at %s",ctime(&ltime));
  IO::read(fpData,fpOut,m,titleAndComment);
  fprintf(fpOut,"data      is %s\n",dataFile);
  if (paraFile) {
    fprintf(fpOut,"parameter is %s\n",paraFile);
  }
  if (initFile) {
    fprintf(fpOut,"initial   is %s\n",initFile);
  }
  fprintf(fpOut,"out       is %s\n",outFile);


#if 1 // 2007/11/28 nakata    for multi LP block

  int SDP_nBlock, SOCP_nBlock,LP_nBlock, nBlock;
  IO::read(fpData,nBlock);

  int* blockStruct          = NULL;
  IO::BlockType* blockType  = NULL;
  int* blockNumber          = NULL;
  int* SDP_blockStruct      = NULL;
  int* SOCP_blockStruct     = NULL;
  NewArray(blockStruct,int,nBlock);
  NewArray(blockType,  IO::BlockType, nBlock);
  NewArray(blockNumber,int,nBlock);
  IO::read(fpData,nBlock,blockStruct);

  SDP_nBlock  = 0;
  SOCP_nBlock = 0;
  LP_nBlock   = 0;
  for (int l=0; l<nBlock; l++){
	if (blockStruct[l] >= 2) {
	  blockType[l] = IO::btSDP;
	  blockNumber[l] = SDP_nBlock;
	  SDP_nBlock++;
	} else if (blockStruct[l] < 0) {
	  blockType[l] = IO::btLP;
	  blockStruct[l] = - blockStruct[l];
	  blockNumber[l] = LP_nBlock;
	  LP_nBlock += blockStruct[l];
	} else if (blockStruct[l] == 1) {
	  blockType[l] = IO::btLP;
	  blockNumber[l] = LP_nBlock;
	  LP_nBlock += blockStruct[l];
	} else {
	  rError("block struct");
	}
  }

  NewArray(SDP_blockStruct, int,SDP_nBlock);
  NewArray(SOCP_blockStruct,int,SOCP_nBlock);
  
  SDP_nBlock = 0;
  for (int l=0; l<nBlock; l++){
	if (blockType[l] == IO::btSDP) {
	  SDP_blockStruct[SDP_nBlock] = blockStruct[l];
	  SDP_nBlock++;
	} 
  }

  InputData inputData;
  //  rMessage("read input data: start");
  IO::read(fpData, m, SDP_nBlock, SDP_blockStruct,
	   SOCP_nBlock, SOCP_blockStruct, LP_nBlock,
	   nBlock, blockStruct, blockType, blockNumber,
	   inputData,isDataSparse);
  //  rMessage("read input data: end");
  inputData.initialize_index(SDP_nBlock,SOCP_nBlock,LP_nBlock,com);
#else 

  int SDP_nBlock, SOCP_nBlock,LP_nBlock;
  IO::read(fpData,SDP_nBlock,SOCP_nBlock,LP_nBlock);
  int* SDP_blockStruct;
  int* SOCP_blockStruct;
  NewArray(SDP_blockStruct ,int,SDP_nBlock);
  NewArray(SOCP_blockStruct,int,SOCP_nBlock);
  IO::read(fpData,SDP_nBlock,SDP_blockStruct,
	   SOCP_nBlock,SOCP_blockStruct, LP_nBlock);

  for (int l=0; l<SDP_nBlock-1; l++){
    if (SDP_blockStruct[l] < 0){
      rError("LP block must be in the last block");
    }
  }
  // muriyari nyuuryoku saseru
  if (SDP_blockStruct[SDP_nBlock-1] < 0){
    LP_nBlock = - SDP_blockStruct[SDP_nBlock-1];
    SDP_nBlock--;
  }

  InputData inputData;
  IO::read(fpData, m, SDP_nBlock, SDP_blockStruct,
	   SOCP_nBlock, SOCP_blockStruct, LP_nBlock,
	   inputData,isDataSparse);
  inputData.initialize_index(SDP_nBlock,SOCP_nBlock,LP_nBlock,com);

#endif
  fclose(fpData);
  
  // inputData.display();


#if 1
  TimeStart(FILE_CHANGE_START1);
  // if possible , change C and A to Dense
  inputData.C.changeToDense();
  for (int k=0; k<m; ++k) {
    inputData.A[k].changeToDense();
  }
  TimeEnd(FILE_CHANGE_END1);
  com.FileChange += TimeCal(FILE_CHANGE_START1,
			     FILE_CHANGE_END1);
#endif

  // rMessage("C = ");
  // inputData.C.display(Display);
  // for (int k=0; k<m; ++k) {
  //   rMessage("A["<<k<<"] = ");
  //   inputData.A[k].display(Display);
  //   }
  
  // the end of initialization of C and A

  Newton newton(m, SDP_nBlock, SDP_blockStruct,
		SOCP_nBlock, SOCP_blockStruct,	LP_nBlock);
  int nBlock2 = SDP_nBlock+SOCP_nBlock+LP_nBlock;
  // 2008/03/12 kazuhide nakata
  Chordal chordal;
  // rMessage("ordering bMat: start");
  chordal.ordering_bMat(m, nBlock2, inputData, fpOut);
  // rMessage("ordering bMat: end");
  newton.initialize_bMat(m, chordal,inputData, fpOut);
  chordal.terminate();

  //  rMessage("newton.computeFormula_SDP: start");
  newton.computeFormula_SDP(inputData,0.0,KAPPA);
  //  rMessage("newton.computeFormula_SDP: end");

  // set initial solutions.
  Solutions currentPt;
  WorkVariables work;
  DenseLinearSpace initPt_xMat;
  DenseLinearSpace initPt_zMat;

  currentPt.initialize(m, SDP_nBlock, SDP_blockStruct,
		       SOCP_nBlock, SOCP_blockStruct, LP_nBlock,
		       param.lambdaStar,com);
  work.initialize(m, SDP_nBlock, SDP_blockStruct,
		  SOCP_nBlock, SOCP_blockStruct, LP_nBlock);

  if (isInitFile) {
    FILE* fpInit = NULL;
    if ((fpInit=fopen(initFile,"r"))==NULL) {
      rError("Cannot open init file " << initFile);
    }
    IO::read(fpInit,currentPt.xMat,currentPt.yVec,currentPt.zMat,
	     SDP_nBlock,SDP_blockStruct,
	     SOCP_nBlock,SOCP_blockStruct,
	     LP_nBlock, nBlock, blockStruct,
	     blockType, blockNumber,
	     isInitSparse);
    #if 0
    rMessage("intial X = ");
    currentPt.xMat.display();
    rMessage("intial Z = ");
    currentPt.zMat.display();
    #endif
    fclose(fpInit);
    currentPt.computeInverse(work,com);

    initPt_xMat.initialize(SDP_nBlock, SDP_blockStruct,
			   SOCP_nBlock, SOCP_blockStruct, 
			   LP_nBlock);
    
    initPt_zMat.initialize(SDP_nBlock, SDP_blockStruct,
			   SOCP_nBlock, SOCP_blockStruct, 
			   LP_nBlock);
    initPt_xMat.copyFrom(currentPt.xMat);
    initPt_zMat.copyFrom(currentPt.zMat);

  }
  //  rMessage("initial xMat = "); initPt_xMat.display(Display);
  //  rMessage("initial yVec = "); currentPt.yVec.display(Display);
  //  rMessage("initial zMat = "); initPt_zMat.display(Display);
  //  rMessage("current pt = "); currentPt.display(Display);
  
  TimeEnd(FILE_READ_END1);
  com.FileRead += TimeCal(FILE_READ_START1,
			   FILE_READ_END1);
  // -------------------------------------------------------------
  // the end of file read
  // -------------------------------------------------------------
  
  Residuals initRes(m, SDP_nBlock, SDP_blockStruct,
		    SOCP_nBlock, SOCP_blockStruct,
		    LP_nBlock, inputData, currentPt);
  Residuals currentRes;
  currentRes.copyFrom(initRes);
  // rMessage("initial currentRes = ");
  // currentRes.display(Display);


  StepLength alpha;
  DirectionParameter beta(param.betaStar);
  Switch reduction(Switch::ON);
  AverageComplementarity mu(param.lambdaStar);

  // rMessage("init mu"); mu.display();

  if (isInitFile) {
    mu.initialize(currentPt);
  }

  RatioInitResCurrentRes theta(param, initRes);
  SolveInfo solveInfo(inputData, currentPt, 
			mu.initial, param.omegaStar);
  Phase phase(initRes, solveInfo, param, currentPt.nDim);

  int pIteration = 0;
  IO::printHeader(fpOut, Display);
  // -----------------------------------------------------
  // Here is MAINLOOP
  // -----------------------------------------------------

  TimeStart(MAIN_LOOP_START1);
  // explicit maxIteration for debug
  // param.maxIteration = 2;
  while (phase.updateCheck(currentRes, solveInfo, param)
	 && pIteration < param.maxIteration) {
    // rMessage(" turn hajimari " << pIteration );
    // Mehrotra's Predictor
    TimeStart(MEHROTRA_PREDICTOR_START1);
    // set variable of Mehrotra
    reduction.MehrotraPredictor(phase);
    beta.MehrotraPredictor(phase, reduction, param);

    // rMessage("reduction = "); reduction.display();
    // rMessage("phase = "); phase.display();
    // rMessage("beta.predictor.value = " << beta.value);
    // rMessage(" mu = " << mu.current);
    // rMessage("currentPt = "); currentPt.display();

    bool isSuccessCholesky;
    isSuccessCholesky = newton.Mehrotra(Newton::PREDICTOR,
					inputData, currentPt,
					currentRes,
					mu, beta, reduction,
					phase,work,com);
    if (isSuccessCholesky == false) {
      break;
    }
    // rMessage("newton predictor = "); newton.display();

    TimeEnd(MEHROTRA_PREDICTOR_END1);
    com.Predictor += TimeCal(MEHROTRA_PREDICTOR_START1,
			      MEHROTRA_PREDICTOR_END1);

    TimeStart(STEP_PRE_START1);
    alpha.MehrotraPredictor(inputData, currentPt, phase, newton,
			      work, com);
    // rMessage("alpha predictor = "); alpha.display();

    TimeStart(STEP_PRE_END1);
    com.StepPredictor += TimeCal(STEP_PRE_START1,STEP_PRE_END1);

    // rMessage("alphaStar = " << param.alphaStar);
    // Mehrotra's Corrector
    // rMessage(" Corrector ");

    TimeStart(CORRECTOR_START1);
    beta.MehrotraCorrector(phase,alpha,currentPt, newton,mu,param);

    // rMessage("beta corrector = " << beta.value);

#if 1 // 2007/08/29 kazuhide nakata
    // add stopping criteria: objValPrimal < ObjValDual
    //	if ((pIteration > 10) &&
    if (phase.value == SolveInfo::pdFEAS
	&& ( beta.value> 5.0
	     || solveInfo.objValPrimal < solveInfo.objValDual)){
      break;
    }
#endif

    newton.Mehrotra(Newton::CORRECTOR,
		    inputData, currentPt, currentRes,
		    mu, beta, reduction, phase,work,com);

    // rMessage("currentPt = "); currentPt.display();
    // rMessage("newton corrector = "); newton.display();

    TimeEnd(CORRECTOR_END1);
    com.Corrector += TimeCal(CORRECTOR_START1,
			      CORRECTOR_END1);
    TimeStart(CORRECTOR_STEP_START1);
    alpha.MehrotraCorrector(inputData, currentPt, phase,
			    reduction, newton, mu, theta,
			    work, param, com);
    // rMessage("alpha corrector = "); alpha.display();
    TimeEnd(CORRECTOR_STEP_END1);
    com.StepCorrector += TimeCal(CORRECTOR_STEP_START1,
				  CORRECTOR_STEP_END1);
    // the end of Corrector
    
    IO::printOneIteration(pIteration, mu, theta, solveInfo,
			   alpha, beta, fpOut, Display);

    if (currentPt.update(alpha,newton,work,com)==false) {
      // if step length is too short,
      // we finish algorithm
      rMessage("cannot move: step length is too short");
      //   memo by kazuhide nakata
      //   StepLength::MehrotraCorrector
      //   thetaMax*mu.initial -> thetamax*thetaMax*mu.initial
      break;
    }

    // rMessage("currentPt = "); currentPt.display();
    // rMessage("updated");

    theta.update(reduction,alpha);
    mu.update(currentPt);
    currentRes.update(m,inputData, currentPt, com);
    theta.update_exact(initRes,currentRes);

    if (isInitFile) {
      solveInfo.update(inputData, initPt_xMat, initPt_zMat, currentPt,
		       currentRes, mu, theta, param);
    } else {
      solveInfo.update(param.lambdaStar,inputData, currentPt,
		       currentRes, mu, theta, param);
    }
    // 2007/09/18 kazuhide nakata
    // print information of ObjVal, residual, gap, complementarity
    // solveInfo.check(inputData, currentPt,
    //                 currentRes, mu, theta, param);
    pIteration++;
  } // end of MAIN_LOOP

  TimeEnd(MAIN_LOOP_END1);

  com.MainLoop = TimeCal(MAIN_LOOP_START1,
			  MAIN_LOOP_END1);
  currentRes.compute(m,inputData,currentPt);
  TimeEnd(TOTAL_TIME_END1);
  
  com.TotalTime = TimeCal(TOTAL_TIME_START1,
			   TOTAL_TIME_END1);
  #if REVERSE_PRIMAL_DUAL
  phase.reverse();
  #endif
#if 1
  IO::printLastInfo(pIteration, mu, theta, solveInfo, alpha, beta,
		    currentRes, phase, currentPt, com.TotalTime,
			nBlock, blockStruct, blockType, blockNumber,
		    inputData, work, com, param, fpOut, Display);
#else
  IO::printLastInfo(pIteration, mu, theta, solveInfo, alpha, beta,
		    currentRes, phase, currentPt, com.TotalTime,
		    inputData, work, com, param, fpOut, Display);
#endif
  // com.display(fpOut);

  DeleteArray(SDP_blockStruct);
  DeleteArray(blockStruct);
  DeleteArray(blockType);
  DeleteArray(blockNumber);
  
  fprintf(Display,   "  main loop time = %.6f\n",com.MainLoop);
  fprintf(fpOut,   "    main loop time = %.6f\n",com.MainLoop);
  fprintf(Display,   "      total time = %.6f\n",com.TotalTime);
  fprintf(fpOut,   "        total time = %.6f\n",com.TotalTime);
  #if 0
  fprintf(Display,   "file  check time = %.6f\n",com.FileCheck);
  fprintf(fpOut,   "  file  check time = %.6f\n",com.FileCheck);
  fprintf(Display,   "file change time = %.6f\n",com.FileChange);
  fprintf(fpOut,   "  file change time = %.6f\n",com.FileChange);
  #endif
  fprintf(Display,   "file   read time = %.6f\n",com.FileRead);
  fprintf(fpOut,   "  file   read time = %.6f\n",com.FileRead);
  fclose(fpOut);


#if 0
  rMessage("memory release");
  currentRes.terminate();
  initRes.terminate();
  currentPt.terminate();
  initPt_xMat.terminate();
  initPt_zMat.terminate();
  newton.terminate();
  work.terminate();
  inputData.terminate();
  com.~ComputeTime();
  param.~Parameter();
  alpha.~StepLength();
  beta.~DirectionParameter();
  reduction.~Switch();
  mu.~AverageComplementarity();
  theta.~RatioInitResCurrentRes();
  solveInfo.~SolveInfo();
  phase.~Phase();
#endif

  return true;
}
Example #27
0
void user_warning_fn(png_structp png_ptr, png_const_charp warning_msg)
{
	rError() << "libpng warning: " << warning_msg << std::endl;
}
Example #28
0
void rSdpaLib::initializeFromFile()
{
  rTimeStart(FILE_READ_START1);
  bool isDataSparse = false;
  int len = strlen(InputFileName);
  if (InputFileName[len-1] == 's'
      && InputFileName[len-2] == '-') {
    isDataSparse = true;
  }

  // initialize b,C,A
  char titleAndComment[1024];
  rIO::read(InputFile,OutputFile,m,titleAndComment);
  if (OutputFile) {
    fprintf(OutputFile,"data      is %s\n",InputFileName);
    fprintf(OutputFile,"parameter is %s\n",ParameterFileName);
    fprintf(OutputFile,"initial   is %s\n",InitialFileName);
    fprintf(OutputFile,"out       is %s\n",OutputFileName);
  }
  mDIM = m;
  rIO::read(InputFile,nBlock);
  blockStruct = NULL;
  blockStruct = new int[nBlock];
  if (blockStruct==NULL) {
    rError("Memory exhausted about blockStruct");
  }
  nBLOCK = nBlock;
  bLOCKsTRUCT = blockStruct;
  rIO::read(InputFile,nBlock,blockStruct);
  nDim = 0;
  for (int l=0; l<nBlock; ++l) {
    nDim += abs(blockStruct[l]);
  }
  
  b.initialize(m);
  rIO::read(InputFile,b);
  A = new rBlockSparseMatrix[m];
  if (A==NULL) {
    rError("Memory exhausted about blockStruct");
  }

  long position = ftell(InputFile);
  // C,A must be accessed "twice".

  // count numbers of elements of C and A
  int* CNonZeroCount = NULL;
  CNonZeroCount = new int[nBlock];
  if (CNonZeroCount==NULL) {
    rError("Memory exhausted about blockStruct");
  }
  int* ANonZeroCount = NULL;
  ANonZeroCount = new int[nBlock*m];
  if (ANonZeroCount==NULL) {
    rError("Memory exhausted about blockStruct");
  }
  // initialize C and A
  rIO::read(InputFile,m,nBlock,blockStruct,
	    CNonZeroCount,ANonZeroCount,isDataSparse);
  // rMessage(" C and A count over");
  C.initialize(nBlock,blockStruct);
  for (int l=0; l<nBlock; ++l) {
    int size = blockStruct[l];
    if (size > 0) {
      C.ele[l].initialize(size,size,rSparseMatrix::SPARSE,
			  CNonZeroCount[l]);
    } else {
      C.ele[l].initialize(-size,-size,rSparseMatrix::DIAGONAL,
			  -size);
    }
  }
  for (int k=0; k<m; ++k) {
    A[k].initialize(nBlock,blockStruct);
    for (int l=0; l<nBlock; ++l) {
      int size = blockStruct[l];
      if (size > 0) {
	A[k].ele[l].initialize(size,size,rSparseMatrix::SPARSE,
			       ANonZeroCount[k*nBlock+l]);
      } else {
	A[k].ele[l].initialize(-size,-size,rSparseMatrix::DIAGONAL,
			       -size);
      }
    }
  }
  delete[] CNonZeroCount;
  CNonZeroCount = NULL;
  delete[] ANonZeroCount;
  ANonZeroCount = NULL;

  rIO::read(InputFile, C, A, m, nBlock, blockStruct,
	    position, isDataSparse);

  if (InitialFile != NULL && InitialPoint == true) {
    // isInitPoint = true;
    bool isInitSparse = false;
    int len = strlen(InitialFileName);
    if (InitialFileName[len-1] == 's'
	&& InitialFileName[len-2] == '-') {
      isInitSparse = true;
    }
    initPt.initializeZero(m,nBlock,blockStruct,com);
    rIO::read(InitialFile,initPt.xMat,initPt.yVec,initPt.zMat, nBlock,
	      blockStruct, isInitSparse);
    initPt.initializeResetup(m,nBlock,blockStruct,com);
  } else {
    initPt.initialize(m,nBlock,blockStruct,pARAM.lambdaStar,com);
  }
 
  rTimeEnd(FILE_READ_END1);
  com.FileRead += rTimeCal(FILE_READ_START1,
			   FILE_READ_END1);

}
Example #29
0
static RGBAImagePtr LoadPNGBuff (unsigned char* fbuffer)
{
	png_byte** row_pointers;
	png_bytep p_fbuffer;

	p_fbuffer = fbuffer;

	// the reading glue
	// http://www.libpng.org/pub/png/libpng-manual.html

	png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 
						  (png_voidp)NULL, user_error_fn, user_warning_fn);

	if (!png_ptr)
	{
		rError() << "libpng error: png_create_read_struct\n";
		return RGBAImagePtr();
	}

	png_infop info_ptr = png_create_info_struct(png_ptr);

	if (!info_ptr)
	{
		png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
		rError() << "libpng error: png_create_info_struct (info_ptr)" << std::endl;
		return RGBAImagePtr();
	}

	png_infop end_info = png_create_info_struct(png_ptr);

	if (!end_info)
	{
		png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);

		rError() << "libpng error: png_create_info_struct (end_info)" << std::endl;
		return RGBAImagePtr();
	}

	// configure the read function
	png_set_read_fn(png_ptr, (png_voidp)&p_fbuffer, (png_rw_ptr)&user_read_data);

	if (setjmp(png_jmpbuf(png_ptr)))
	{
		png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
		return RGBAImagePtr();
	}

	png_read_info(png_ptr, info_ptr);

	int bit_depth = png_get_bit_depth(png_ptr, info_ptr);
	int color_type = png_get_color_type(png_ptr, info_ptr);

	// we want to treat all images the same way
	//   The following code transforms grayscale images of less than 8 to 8 bits,
	//   changes paletted images to RGB, and adds a full alpha channel if there is
	//   transparency information in a tRNS chunk.
	if (color_type == PNG_COLOR_TYPE_PALETTE)
	{
		png_set_palette_to_rgb(png_ptr);
	}

	if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
	{
#if PNG_LIBPNG_VER < 10400
		png_set_gray_1_2_4_to_8(png_ptr);
#else
		png_set_expand_gray_1_2_4_to_8(png_ptr);
#endif 
	}

	if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
	{
		png_set_tRNS_to_alpha(png_ptr);
	}

	if (!(color_type & PNG_COLOR_MASK_ALPHA))
	{
		// Set the background color to draw transparent and alpha images over.
		png_color_16 my_background, *image_background;

		if (png_get_bKGD(png_ptr, info_ptr, &image_background))
		{
			png_set_background(png_ptr, image_background, PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
		}
		else
		{
			png_set_background(png_ptr, &my_background, PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
		}

		// Add alpha byte after each RGB triplet
		png_set_filler(png_ptr, 0xff, PNG_FILLER_AFTER);
	}

	// read the sucker in one chunk
	png_read_update_info(png_ptr, info_ptr);

	color_type = png_get_color_type(png_ptr, info_ptr);
	bit_depth = png_get_bit_depth(png_ptr, info_ptr);

	int width = png_get_image_width(png_ptr, info_ptr);
	int height = png_get_image_height(png_ptr, info_ptr);

	// allocate the pixel buffer, and the row pointers
	RGBAImagePtr image(new RGBAImage(width, height));

	row_pointers = (png_byte**) malloc((height) * sizeof(png_byte*));

	for (int i = 0; i < height; i++)
	{
		row_pointers[i] = (png_byte*)(image->getMipMapPixels(0)) + i * 4 * (width);
	}

	// actual read
	png_read_image(png_ptr, row_pointers);

	/* read rest of file, and get additional chunks in info_ptr - REQUIRED */
	png_read_end(png_ptr, info_ptr);

	/* free up the memory structure */
	png_destroy_read_struct(&png_ptr, &info_ptr, png_infopp_NULL);

	free(row_pointers);

	return image;
}
Example #30
0
void SoundPlayer::play(ArchiveFile& file) {
	// If we're not initialised yet, do it now
	if (!_initialised) {
		initialise();
    }

	// Stop any previous playback operations, that might be still active
	clearBuffer();

	// Retrieve the extension
	std::string ext = os::getExtension(file.getName());

	if (boost::algorithm::to_lower_copy(ext) == "ogg") {
		// Convert the file into a buffer, self-destructs at end of scope
		ScopedArchiveBuffer buffer(file);

		// This is an OGG Vorbis file, decode it
		vorbis_info* vorbisInfo;
  		OggVorbis_File oggFile;

  		// Initialise the wrapper class
  		OggFileStream stream(buffer);

  		// Setup the callbacks and point them to the helper class
  		ov_callbacks callbacks;
  		callbacks.read_func = OggFileStream::oggReadFunc;
  		callbacks.seek_func = OggFileStream::oggSeekFunc;
  		callbacks.close_func = OggFileStream::oggCloseFunc;
  		callbacks.tell_func = OggFileStream::oggTellFunc;

  		// Open the OGG data stream using the custom callbacks
  		int res = ov_open_callbacks(static_cast<void*>(&stream), &oggFile,
									NULL, 0, callbacks);

  		if (res == 0) {
  			// Open successful

  			// Get some information about the OGG file
			vorbisInfo = ov_info(&oggFile, -1);

			// Check the number of channels
			ALenum format = (vorbisInfo->channels == 1) ? AL_FORMAT_MONO16
														: AL_FORMAT_STEREO16;

			// Get the sample Rate
			ALsizei freq = (vorbisInfo->rate);
			//std::cout << "Sample rate is " << freq << "\n";

			long bytes;
			char smallBuffer[4096];
			DecodeBufferPtr largeBuffer(new DecodeBuffer());
			do {
				int bitStream;
				// Read a chunk of decoded data from the vorbis file
				bytes = ov_read(&oggFile, smallBuffer, sizeof(smallBuffer),
								0, 2, 1, &bitStream);

				if (bytes == OV_HOLE) {
					rError() << "SoundPlayer: Error decoding OGG: OV_HOLE.\n";
				}
				else if (bytes == OV_EBADLINK) {
					rError() << "SoundPlayer: Error decoding OGG: OV_EBADLINK.\n";
				}
				else {
					// Stuff this into the variable-sized buffer
					largeBuffer->insert(largeBuffer->end(), smallBuffer, smallBuffer + bytes);
				}
			} while (bytes > 0);

			// Allocate a new buffer
			alGenBuffers(1, &_buffer);

			DecodeBuffer& bufferRef = *largeBuffer;

			// Upload sound data to buffer
			alBufferData(_buffer,
						 format,
						 &bufferRef[0],
						 static_cast<ALsizei>(bufferRef.size()),
						 freq);

			// Clean up the OGG routines
  			ov_clear(&oggFile);
  		}
  		else {
  			rError() << "SoundPlayer: Error opening OGG file.\n";
  		}
	}
	else {
		// Must be a wave file
		try {
			// Create an AL sound buffer directly from the buffer in memory
			_buffer = WavFileLoader::LoadFromStream(file.getInputStream());
		}
		catch (std::runtime_error& e) {
			rError() << "SoundPlayer: Error opening WAV file: " << e.what() << std::endl;
			_buffer = 0;
		}
	}

	if (_buffer != 0) {
		alGenSources(1, &_source);
		// Assign the buffer to the source and play it
		alSourcei(_source, AL_BUFFER, _buffer);

		// greebo: Wait 10 msec. to fix a problem with buffers not being played
		// maybe the AL needs time to push the data?
		usleep(10000);

		alSourcePlay(_source);

		// Enable the periodic buffer check, this destructs the buffer
		// as soon as the playback has finished
		_timer.enable();
	}
}