<commit_before>/*
Copyright (C) 2015 Jakob Sinclair

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "game.h"
#include "RM/cache.h"
#include "Graphics/spritesheet.h"
#include "Components/sprite.h"
#include "Components/controller.h"
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

//The constructor and destructor is nothing special in this case
Game::Game() {
	;
}

Game::~Game() {
	;
}

//The init function initializes the game, true if an error did not show up
bool Game::init() {
	bool success = true;

    	if(m_Screen.createNewWindow(1280, 720, "GameEngine") != true) {
		success = false;
	} else if(Cache::texCache.createTexture("resources/block.png",
		m_Screen.getRenderer()) == nullptr) {
		success = false;
	} else if(Cache::sheetCache.createSheet("resources/block.png")) {
		success = true;
	}
	Cache::fontCache.createFont("resources/desonanz.ttf", 20);
	Controller *temp3 = new Controller;
	temp3->initialize("controller", &m_Player);
	temp3->setInputReference(m_Input);
	m_Player.addComponent(temp3);
	temp3 = nullptr;
	SDL_Rect temp2;
	temp2.x = 0; temp2.y = 0; temp2.w = 64; temp2.h = 64;
	Sprite* temp = new Sprite;
	temp->initialize("sprite", &m_Player);
	temp->loadSpriteFromSheet(
		Cache::sheetCache.getSheet("resources/block.png"), temp2, 3);
	Cache::loadTexturesFromBlock("resources/game.txt", 1,
		m_Screen.getRenderer());
	m_Player.addComponent(temp);
	temp = nullptr;
	return success;
}

//The update function handles the game updates
void Game::update() {
	m_Input.update();
	m_Player.update();
}

//The draw function handles the rendering part of the game
void Game::drawGame() {
	SDL_Color color = {0, 255, 0, 255};
	SDL_RenderClear(m_Screen.getRenderer());
	draw.begin();
	m_Player.draw(draw);
	draw.drawText("Hello World", "resources/desonanz.ttf",
		glm::vec2(64.0f, 64.0f), color, m_Screen.getRenderer());
	draw.end();
	draw.render(m_Screen.getRenderer());
	SDL_RenderPresent(m_Screen.getRenderer());
}
<commit_msg>Tested Windows Build<commit_after>/*
Copyright (C) 2015 Jakob Sinclair

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "game.h"
#include "RM/cache.h"
#include "Graphics/spritesheet.h"
#include "Components/sprite.h"
#include "Components/controller.h"
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

//The constructor and destructor is nothing special in this case
Game::Game() {
	;
}

Game::~Game() {
	;
}

//The init function initializes the game, true if an error did not show up
bool Game::init() {
	bool success = true;

    	if(m_Screen.createNewWindow(1280, 720, "GameEngine") != true) {
		success = false;
	} else if(Cache::texCache.createTexture("resources/block.png",
		m_Screen.getRenderer()) == nullptr) {
		success = false;
	} else if(Cache::sheetCache.createSheet("resources/block.png") == nullptr) {
		success = false;
	}
	//Cache::fontCache.createFont("resources/desonanz.ttf", 20);
	Controller *temp3 = new Controller;
	temp3->initialize("controller", &m_Player);
	temp3->setInputReference(m_Input);
	m_Player.addComponent(temp3);
	temp3 = nullptr;
	SDL_Rect temp2;
	temp2.x = 0; temp2.y = 0; temp2.w = 64; temp2.h = 64;
	Sprite* temp = new Sprite;
	temp->initialize("sprite", &m_Player);
	temp->loadSpriteFromSheet(
		Cache::sheetCache.getSheet("resources/block.png"), temp2, 3);
	Cache::loadTexturesFromBlock("resources/game.txt", 1,
		m_Screen.getRenderer());
	m_Player.addComponent(temp);
	temp = nullptr;
	return success;
}

//The update function handles the game updates
void Game::update() {
	m_Input.update();
	m_Player.update();
}

//The draw function handles the rendering part of the game
void Game::drawGame() {
	SDL_Color color = {0, 255, 0, 255};
	SDL_RenderClear(m_Screen.getRenderer());
	draw.begin();
	m_Player.draw(draw);
	//draw.drawText("Hello World", "resources/desonanz.ttf",
		//glm::vec2(64.0f, 64.0f), color, m_Screen.getRenderer());
	draw.end();
	draw.render(m_Screen.getRenderer());
	SDL_RenderPresent(m_Screen.getRenderer());
}
<|endoftext|>


<commit_before>#include "audio/audio.hpp"
#include "main/main.hpp"
#include "world/world.hpp"
#include "graphics/graphics.hpp"

namespace Polarity {

AudioFile *audioTest;
AudioChannelPlayer *audioPlayer;

bool loaded = false;

void loadAssets() {
    test_image = loadImage("assets/helloworld.png");
    audioPlayer = new AudioChannelPlayer(16);
    if (audioPlayer->addChannel("white", "assets/audio/frozen_star.mp3", 0) != AudioFileError::OK) {
        std::cerr << "Couldn't load white track" << std::endl;
    }
    if (audioPlayer->addChannel("black", "assets/audio/lightless_dawn.mp3", 1) != AudioFileError::OK) {
        std::cerr << "Couldn't load black track" << std::endl;
    }
}

bool loopIter(SDL_Surface *screen) {
    SDL_Event event;
    std::vector<int> keyUps;
    while (SDL_PollEvent(&event)) {
      if (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP) {
        if (event.type == SDL_KEYDOWN) {
	  world->keyEvent(event.key.keysym.sym, true);
	} else {
	  keyUps.push_back(event.key.keysym.sym);
	}
        if (event.key.keysym.sym == SDLK_SPACE) {
            audioPlayer->playChannel("white");
            audioPlayer->playChannel("black");
        } else if (event.key.keysym.sym == SDLK_ESCAPE) {
            audioPlayer->stopChannel("white");
            audioPlayer->stopChannel("black");
        } else if (event.key.keysym.sym == SDLK_w) {
            audioPlayer->setChannelVolume("white", 1.0);
            audioPlayer->setChannelVolume("black", 0.0);
        } else if (event.key.keysym.sym == SDLK_b) {
            audioPlayer->setChannelVolume("white", 0.0);
            audioPlayer->setChannelVolume("black", 1.0);
        }
      }
    }
    world->tick();
    // all key up have to happen after key downs so we get a full tick of downs
    for (auto &key : keyUps) {
      world->keyEvent(key, false);
    }
    return true;
}
}
<commit_msg>Formatting and comments<commit_after>#include "audio/audio.hpp"
#include "main/main.hpp"
#include "world/world.hpp"
#include "graphics/graphics.hpp"

namespace Polarity {

AudioFile *audioTest;
AudioChannelPlayer *audioPlayer;

bool loaded = false;

void loadAssets() {
    test_image = loadImage("assets/helloworld.png");
    audioPlayer = new AudioChannelPlayer(16);
    if (audioPlayer->addChannel("white", "assets/audio/frozen_star.mp3", 0) != AudioFileError::OK) {
        std::cerr << "Couldn't load white track" << std::endl;
    }
    if (audioPlayer->addChannel("black", "assets/audio/lightless_dawn.mp3", 1) != AudioFileError::OK) {
        std::cerr << "Couldn't load black track" << std::endl;
    }
}

bool loopIter(SDL_Surface *screen) {
    SDL_Event event;
    std::vector<int> keyUps;
    while (SDL_PollEvent(&event)) {
        if (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP) {
            if (event.type == SDL_KEYDOWN) {
                world->keyEvent(event.key.keysym.sym, true);
            } else {
                keyUps.push_back(event.key.keysym.sym);
            }
            if (event.key.keysym.sym == SDLK_SPACE) {
                audioPlayer->playChannel("white");
                audioPlayer->playChannel("black");
            } else if (event.key.keysym.sym == SDLK_ESCAPE) {
                audioPlayer->stopChannel("white");
                audioPlayer->stopChannel("black");
            } else if (event.key.keysym.sym == SDLK_w) {
                // switch to white track
                audioPlayer->setChannelVolume("white", 1.0);
                audioPlayer->setChannelVolume("black", 0.0);
            } else if (event.key.keysym.sym == SDLK_b) {
                // switch to black track
                audioPlayer->setChannelVolume("white", 0.0);
                audioPlayer->setChannelVolume("black", 1.0);
            }
        }
    }
    world->tick();
    // all key up have to happen after key downs so we get a full tick of downs
    for (auto &key : keyUps) {
      world->keyEvent(key, false);
    }
    return true;
}
}
<|endoftext|>


<commit_before>#include "spellingproduceswarningstest.h"
#include <QUrl>
#include <QFileInfo>
#include <QThread>
#include <QStringList>
#include "integrationtestbase.h"
#include "signalwaiter.h"
#include "../../xpiks-qt/Commands/commandmanager.h"
#include "../../xpiks-qt/Models/artitemsmodel.h"
#include "../../xpiks-qt/MetadataIO/metadataiocoordinator.h"
#include "../../xpiks-qt/Models/artworkmetadata.h"
#include "../../xpiks-qt/Models/settingsmodel.h"
#include "../../xpiks-qt/Models/filteredartitemsproxymodel.h"
#include "../../xpiks-qt/SpellCheck/spellchecksuggestionmodel.h"
#include "../../xpiks-qt/SpellCheck/spellsuggestionsitem.h"
#include "../../xpiks-qt/Models/combinedartworksmodel.h"
#include "../../xpiks-qt/Common/basickeywordsmodel.h"
#include "../../xpiks-qt/Common/flags.h"
#include "../../xpiks-qt/Warnings/warningsservice.h"
#include "../../xpiks-qt/SpellCheck/spellcheckerservice.h"

QString SpellingProducesWarningsTest::testName() {
    return QLatin1String("SpellingProducesWarningsTest");
}

void SpellingProducesWarningsTest::setup() {
    Models::SettingsModel *settingsModel = m_CommandManager->getSettingsModel();
    settingsModel->setUseSpellCheck(true);
}

int SpellingProducesWarningsTest::doTest() {
    Models::ArtItemsModel *artItemsModel = m_CommandManager->getArtItemsModel();
    QList<QUrl> files;
    files << getImagePathForTest("images-for-tests/vector/026.jpg");

    int addedCount = artItemsModel->addLocalArtworks(files);

    VERIFY(addedCount == files.length(), "Failed to add file");

    MetadataIO::MetadataIOCoordinator *ioCoordinator = m_CommandManager->getMetadataIOCoordinator();
    SignalWaiter waiter;
    QObject::connect(ioCoordinator, SIGNAL(metadataReadingFinished()), &waiter, SIGNAL(finished()));

    ioCoordinator->continueReading(true);

    if (!waiter.wait(20)) {
        VERIFY(false, "Timeout exceeded for reading metadata.");
    }

    VERIFY(!ioCoordinator->getHasErrors(), "Errors in IO Coordinator while reading");

    QThread::sleep(3);

    Models::ArtworkMetadata *metadata = artItemsModel->getArtwork(0);

    VERIFY(!Common::HasFlag(metadata->getWarningsFlags(), Common::WarningTypeSpellErrorsInTitle), "Error for reading title");
    VERIFY(!Common::HasFlag(metadata->getWarningsFlags(), Common::WarningTypeSpellErrorsInDescription), "Error for reading description");
    VERIFY(!Common::HasFlag(metadata->getWarningsFlags(), Common::WarningTypeSpellErrorsInKeywords), "Error for reading keywords");

    QString wrongWord = "abbreviatioe";
    metadata->setDescription(metadata->getDescription() + ' ' + wrongWord);
    metadata->setTitle(metadata->getTitle() + ' ' + wrongWord);
    metadata->appendKeyword("correct part " + wrongWord);
    metadata->setIsSelected(true);

    Models::FilteredArtItemsProxyModel *filteredModel = m_CommandManager->getFilteredArtItemsModel();
    SpellCheck::SpellCheckerService *spellCheckService = m_CommandManager->getSpellCheckerService();

    SignalWaiter spellingWaiter;
    QObject::connect(spellCheckService, SIGNAL(spellCheckQueueIsEmpty()), &spellingWaiter, SIGNAL(finished()));

    // wait for checking warnings
    Warnings::WarningsService *warningsService = m_CommandManager->getWarningsService();
    SignalWaiter warningsQueueWaiter;
    QObject::connect(warningsService, SIGNAL(queueIsEmpty()), &warningsQueueWaiter, SIGNAL(finished()));

    filteredModel->spellCheckSelected();

    if (!spellingWaiter.wait(5)) {
        VERIFY(false, "Timeout for waiting for first spellcheck results");
    }

    LOG_INFO << "Spellchecking finished. Waiting for warnings...";

    if (!warningsQueueWaiter.wait(5)) {
        if (metadata->getWarningsFlags() == 0) {
            VERIFY(false, "Timeout for waiting for warnings checker");
        }
    }

    Common::BasicKeywordsModel *keywordsModel = metadata->getKeywordsModel();

    VERIFY(keywordsModel->hasDescriptionSpellError(), "Description spell error not detected");
    VERIFY(keywordsModel->hasTitleSpellError(), "Title spell error not detected");
    VERIFY(keywordsModel->hasKeywordsSpellError(), "Keywords spell error not detected");

    VERIFY(Common::HasFlag(metadata->getWarningsFlags(), Common::WarningTypeSpellErrorsInTitle),
           "Warning was not produced for title spelling error");
    VERIFY(Common::HasFlag(metadata->getWarningsFlags(), Common::WarningTypeSpellErrorsInDescription),
           "Warning was not produced for description spelling error");
    VERIFY(Common::HasFlag(metadata->getWarningsFlags(), Common::WarningTypeSpellErrorsInKeywords),
           "Warning was not produced for keywords spelling error");

    return 0;
}
<commit_msg>Fixed integration tests<commit_after>#include "spellingproduceswarningstest.h"
#include <QUrl>
#include <QFileInfo>
#include <QThread>
#include <QStringList>
#include "integrationtestbase.h"
#include "signalwaiter.h"
#include "../../xpiks-qt/Commands/commandmanager.h"
#include "../../xpiks-qt/Models/artitemsmodel.h"
#include "../../xpiks-qt/MetadataIO/metadataiocoordinator.h"
#include "../../xpiks-qt/Models/artworkmetadata.h"
#include "../../xpiks-qt/Models/settingsmodel.h"
#include "../../xpiks-qt/Models/filteredartitemsproxymodel.h"
#include "../../xpiks-qt/SpellCheck/spellchecksuggestionmodel.h"
#include "../../xpiks-qt/SpellCheck/spellsuggestionsitem.h"
#include "../../xpiks-qt/Models/combinedartworksmodel.h"
#include "../../xpiks-qt/Common/basickeywordsmodel.h"
#include "../../xpiks-qt/Common/flags.h"
#include "../../xpiks-qt/Warnings/warningsservice.h"
#include "../../xpiks-qt/SpellCheck/spellcheckerservice.h"

QString SpellingProducesWarningsTest::testName() {
    return QLatin1String("SpellingProducesWarningsTest");
}

void SpellingProducesWarningsTest::setup() {
    Models::SettingsModel *settingsModel = m_CommandManager->getSettingsModel();
    settingsModel->setUseSpellCheck(true);
}

int SpellingProducesWarningsTest::doTest() {
    Models::ArtItemsModel *artItemsModel = m_CommandManager->getArtItemsModel();
    QList<QUrl> files;
    files << getImagePathForTest("images-for-tests/vector/026.jpg");

    int addedCount = artItemsModel->addLocalArtworks(files);

    VERIFY(addedCount == files.length(), "Failed to add file");

    MetadataIO::MetadataIOCoordinator *ioCoordinator = m_CommandManager->getMetadataIOCoordinator();
    SignalWaiter waiter;
    QObject::connect(ioCoordinator, SIGNAL(metadataReadingFinished()), &waiter, SIGNAL(finished()));

    ioCoordinator->continueReading(true);

    if (!waiter.wait(20)) {
        VERIFY(false, "Timeout exceeded for reading metadata.");
    }

    VERIFY(!ioCoordinator->getHasErrors(), "Errors in IO Coordinator while reading");

    QThread::sleep(3);

    Models::ArtworkMetadata *metadata = artItemsModel->getArtwork(0);

    VERIFY(!Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInTitle), "Error for reading title");
    VERIFY(!Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInDescription), "Error for reading description");
    VERIFY(!Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInKeywords), "Error for reading keywords");

    QString wrongWord = "abbreviatioe";
    metadata->setDescription(metadata->getDescription() + ' ' + wrongWord);
    metadata->setTitle(metadata->getTitle() + ' ' + wrongWord);
    metadata->appendKeyword("correct part " + wrongWord);
    metadata->setIsSelected(true);

    Models::FilteredArtItemsProxyModel *filteredModel = m_CommandManager->getFilteredArtItemsModel();
    SpellCheck::SpellCheckerService *spellCheckService = m_CommandManager->getSpellCheckerService();

    SignalWaiter spellingWaiter;
    QObject::connect(spellCheckService, SIGNAL(spellCheckQueueIsEmpty()), &spellingWaiter, SIGNAL(finished()));

    // wait for checking warnings
    Warnings::WarningsService *warningsService = m_CommandManager->getWarningsService();
    SignalWaiter warningsQueueWaiter;
    QObject::connect(warningsService, SIGNAL(queueIsEmpty()), &warningsQueueWaiter, SIGNAL(finished()));

    filteredModel->spellCheckSelected();

    if (!spellingWaiter.wait(5)) {
        VERIFY(false, "Timeout for waiting for first spellcheck results");
    }

    LOG_INFO << "Spellchecking finished. Waiting for warnings...";

    if (!warningsQueueWaiter.wait(5)) {
        if (metadata->getWarningsFlags() == Common::WarningFlags::None) {
            VERIFY(false, "Timeout for waiting for warnings checker");
        }
    }

    Common::BasicKeywordsModel *keywordsModel = metadata->getKeywordsModel();

    VERIFY(keywordsModel->hasDescriptionSpellError(), "Description spell error not detected");
    VERIFY(keywordsModel->hasTitleSpellError(), "Title spell error not detected");
    VERIFY(keywordsModel->hasKeywordsSpellError(), "Keywords spell error not detected");

    VERIFY(Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInTitle),
           "Warning was not produced for title spelling error");
    VERIFY(Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInDescription),
           "Warning was not produced for description spelling error");
    VERIFY(Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInKeywords),
           "Warning was not produced for keywords spelling error");

    return 0;
}
<|endoftext|>


<commit_before>//
// RowVector/instance_method_mula.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

#ifndef EIGENJS_ROWVECTOR_INSTANCE_METHOD_MULA_HPP
#define EIGENJS_ROWVECTOR_INSTANCE_METHOD_MULA_HPP

namespace EigenJS {

EIGENJS_INSTANCE_METHOD(RowVector, mula,
{
  NanScope();

  if (args.Length() == 1) {
    RowVector* obj = node::ObjectWrap::Unwrap<RowVector>(args.This());
    typename RowVector::value_type& value = **obj;

    if (Matrix::is_matrix(args[0])) {
      const Matrix* const& rhs_obj =
        node::ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());
      const typename Matrix::value_type& rhs_matrix = **rhs_obj;

      if (T::is_invalid_matrix_product(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      if (value.cols() != rhs_matrix.rows() ||
          value.cols() != rhs_matrix.cols()) {
        NanThrowError("The matrix size must be mxm");
        NanReturnUndefined();
      }

      value *= rhs_matrix;

      NanReturnValue(args.This());
    } else if (Vector::is_vector(args[0])) {
      const Vector* const& rhs_obj =
        node::ObjectWrap::Unwrap<Vector>(args[0]->ToObject());
      const typename Vector::value_type& rhs_vector = **rhs_obj;

      if (T::is_invalid_matrix_product(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      if (value.rows() != 1 ||
          value.cols() != 1 ||
          rhs_vector.rows() != 1 ||
          rhs_vector.cols() != 1
      ) {
        NanThrowError("The operation result is out of range");
        NanReturnUndefined();
      }

      value *= rhs_vector;

      NanReturnValue(args.This());
    } else if (RowVector::is_rowvector(args[0])) {
      const RowVector* const& rhs_obj =
        node::ObjectWrap::Unwrap<RowVector>(args[0]->ToObject());
      const typename RowVector::value_type& rhs_rowvector = **rhs_obj;

      if (T::is_invalid_matrix_product(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      value *= rhs_rowvector;

      NanReturnValue(args.This());
    } else if (MatrixBlock::is_matrixblock(args[0])) {
      const MatrixBlock* const& rhs_obj =
        node::ObjectWrap::Unwrap<MatrixBlock>(args[0]->ToObject());
      const typename MatrixBlock::value_type& rhs_matrixblock = **rhs_obj;

      if (T::is_invalid_matrix_product(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      if (value.rows() != 1 ||
          value.cols() != 1 ||
          rhs_matrixblock.rows() != 1 ||
          rhs_matrixblock.cols() != 1
      ) {
        NanThrowError("The operation result is out of range");
        NanReturnUndefined();
      }

      value *= rhs_matrixblock;

      NanReturnValue(args.This());
    } else if (T::is_scalar(args[0])) {
      value *= args[0]->NumberValue();

      NanReturnValue(args.This());
    }
  }

  EIGENJS_THROW_ERROR_INVALID_ARGUMENT()
  NanReturnUndefined();
})

}  // namespace EigenJS

#endif  // EIGENJS_ROWVECTOR_INSTANCE_METHOD_MULA_HPP
<commit_msg>src: fixed and abstracted code, and supported VectorBlock and RowVectorBlock<commit_after>//
// RowVector/instance_method_mula.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

#ifndef EIGENJS_ROWVECTOR_INSTANCE_METHOD_MULA_HPP
#define EIGENJS_ROWVECTOR_INSTANCE_METHOD_MULA_HPP

namespace EigenJS {

EIGENJS_INSTANCE_METHOD(RowVector, mula,
{
  NanScope();

  if (args.Length() == 1) {
    T* obj = node::ObjectWrap::Unwrap<T>(args.This());
    typename T::value_type& value = **obj;

    if (Matrix::is_matrix(args[0])) {
      const Matrix* const& rhs_obj =
        node::ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());
      const typename Matrix::value_type& rhs_matrix = **rhs_obj;

      if (T::is_invalid_matrix_product(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      if (value.cols() != rhs_matrix.rows() ||
          value.cols() != rhs_matrix.cols()) {
        NanThrowError("The matrix size must be mxm");
        NanReturnUndefined();
      }

      value *= rhs_matrix;

      NanReturnValue(args.This());
    } else if (Vector::is_vector(args[0])) {
      const Vector* const& rhs_obj =
        node::ObjectWrap::Unwrap<Vector>(args[0]->ToObject());
      const typename Vector::value_type& rhs_vector = **rhs_obj;

      if (T::is_invalid_matrix_product(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      if (value.rows() != 1 ||
          value.cols() != 1 ||
          rhs_vector.rows() != 1 ||
          rhs_vector.cols() != 1
      ) {
        NanThrowError("The operation result is out of range");
        NanReturnUndefined();
      }

      value *= rhs_vector;

      NanReturnValue(args.This());
    } else if (RowVector::is_rowvector(args[0])) {
      const RowVector* const& rhs_obj =
        node::ObjectWrap::Unwrap<RowVector>(args[0]->ToObject());
      const typename RowVector::value_type& rhs_rowvector = **rhs_obj;

      if (T::is_invalid_matrix_product(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      if (value.rows() != 1 ||
          value.cols() != 1 ||
          rhs_rowvector.rows() != 1 ||
          rhs_rowvector.cols() != 1
      ) {
        NanThrowError("The operation result is out of range");
        NanReturnUndefined();
      }

      value *= rhs_rowvector;

      NanReturnValue(args.This());
    } else if (MatrixBlock::is_matrixblock(args[0])) {
      const MatrixBlock* const& rhs_obj =
        node::ObjectWrap::Unwrap<MatrixBlock>(args[0]->ToObject());
      const typename MatrixBlock::value_type& rhs_matrixblock = **rhs_obj;

      if (T::is_invalid_matrix_product(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      if (value.cols() != rhs_matrixblock.rows() ||
          value.cols() != rhs_matrixblock.cols()) {
        NanThrowError("The matrix block size must be mxm");
        NanReturnUndefined();
      }

      value *= rhs_matrixblock;

      NanReturnValue(args.This());
    } else if (VectorBlock::is_vectorblock(args[0])) {
      const VectorBlock* const& rhs_obj =
        node::ObjectWrap::Unwrap<VectorBlock>(args[0]->ToObject());
      const typename VectorBlock::value_type& rhs_vectorblock = **rhs_obj;

      if (T::is_invalid_matrix_product(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      if (value.rows() != 1 ||
          value.cols() != 1 ||
          rhs_vectorblock.rows() != 1 ||
          rhs_vectorblock.cols() != 1
      ) {
        NanThrowError("The operation result is out of range");
        NanReturnUndefined();
      }

      value *= rhs_vectorblock;

      NanReturnValue(args.This());
    } else if (RowVectorBlock::is_rowvectorblock(args[0])) {
      const RowVectorBlock* const& rhs_obj =
        node::ObjectWrap::Unwrap<RowVectorBlock>(args[0]->ToObject());
      const typename RowVectorBlock::value_type& rhs_rowvectorblock =
          **rhs_obj;

      if (T::is_invalid_matrix_product(obj, rhs_obj)) {
        NanReturnUndefined();
      }

      if (value.rows() != 1 ||
          value.cols() != 1 ||
          rhs_rowvectorblock.rows() != 1 ||
          rhs_rowvectorblock.cols() != 1
      ) {
        NanThrowError("The operation result is out of range");
        NanReturnUndefined();
      }

      value *= rhs_rowvectorblock;

      NanReturnValue(args.This());
    } else if (T::is_scalar(args[0])) {
      value *= args[0]->NumberValue();

      NanReturnValue(args.This());
    }
  }

  EIGENJS_THROW_ERROR_INVALID_ARGUMENT()
  NanReturnUndefined();
})

}  // namespace EigenJS

#endif  // EIGENJS_ROWVECTOR_INSTANCE_METHOD_MULA_HPP
<|endoftext|>


<commit_before>/*
 * Copyright 2022 Axel Waggershauser
*/
// SPDX-License-Identifier: Apache-2.0

#include "Content.h"

#include "CharacterSetECI.h"
#include "TextDecoder.h"
#include "TextUtfEncoding.h"
#include "ZXContainerAlgorithms.h"

namespace ZXing {

std::string ToString(ContentType type)
{
	const char* t2s[] = {"Text", "Binary", "Mixed"};
	return t2s[static_cast<int>(type)];
}

template <typename FUNC>
void Content::ForEachECIBlock(FUNC func) const
{
	for (int i = 0; i < Size(encodings); ++i) {
		auto [eci, start] = encodings[i];
		int end = i + 1 == Size(encodings) ? Size(binary) : encodings[i + 1].pos;

		if (start != end)
			func(eci, start, end);
	}
}

void Content::switchEncoding(ECI eci, bool isECI)
{
	// replace all non-ECI entries on first ECI entry with default ECI
	if (isECI && !hasECI)
		encodings = {{ECI::ISO8859_1, 0}};
	if (isECI || !hasECI) {
		if (encodings.back().pos == Size(binary))
			encodings.back().eci = eci; // no point in recording 0 length segments
		else
			encodings.push_back({eci, Size(binary)});
	}
	hasECI |= isECI;
}

void Content::switchEncoding(CharacterSet cs)
{
	 switchEncoding(ToECI(cs), false);
}

std::wstring Content::text() const
{
	auto fallbackCS = CharacterSetECI::CharsetFromName(hintedCharset.c_str());
	if (!hasECI && fallbackCS == CharacterSet::Unknown)
		fallbackCS = guessEncoding();

	std::wstring wstr;
	ForEachECIBlock([&](ECI eci, int begin, int end) {
		CharacterSet cs = eci == ECI::Unknown ? fallbackCS : ToCharacterSet(eci);

		TextDecoder::Append(wstr, binary.data() + begin, end - begin, cs);
	});
	return wstr;
}

std::string Content::utf8Protocol() const
{
	std::wstring res = TextDecoder::FromLatin1(symbology.toString(true));
	ECI lastECI = ECI::Unknown;
	auto fallbackCS = guessEncoding();

	ForEachECIBlock([&](ECI eci, int begin, int end) {
		// first determine how to decode the content (choose character set)
		//  * eci == ECI::Unknown implies !hasECI and we guess
		//  * if !IsText(eci) the ToCharcterSet(eci) will return Unknown and we decode as binary
		CharacterSet cs = eci == ECI::Unknown ? fallbackCS : ToCharacterSet(eci);

		// then find the eci to report back in the ECI designator
		if (IsText(ToECI(cs))) // everything decoded as text is reported as utf8
			eci = ECI::UTF8;
		else if (eci == ECI::Unknown) // implies !hasECI and fallbackCS is Unknown or Binary
			eci = ECI::Binary;

		if (lastECI != eci)
			TextDecoder::AppendLatin1(res, ToString(eci));
		lastECI = eci;

		std::wstring tmp;
		TextDecoder::Append(tmp, binary.data() + begin, end - begin, cs);
		for (auto c : tmp) {
			res += c;
			if (c == L'\\') // in the ECI protocol a '\' has to be doubled
				res += c;
		}
	});

	return TextUtfEncoding::ToUtf8(res);
}

ByteArray Content::binaryECI() const
{
	std::string res = symbology.toString(true);

	ForEachECIBlock([&](ECI eci, int begin, int end) {
		if (hasECI)
			res += ToString(eci);

		for (int i = begin; i != end; ++i) {
			char c = static_cast<char>(binary[i]);
			res += c;
			if (c == '\\') // in the ECI protocol a '\' has to be doubled
				res += c;
		}
	});

	return ByteArray(res);
}

CharacterSet Content::guessEncoding() const
{
	// assemble all blocks with unknown encoding
	ByteArray input;
	ForEachECIBlock([&](ECI eci, int begin, int end) {
		if (eci == ECI::Unknown)
			input.insert(input.end(), binary.begin() + begin, binary.begin() + end);
	});

	if (input.empty())
		return CharacterSet::Unknown;

	return TextDecoder::GuessEncoding(input.data(), input.size(), CharacterSet::BINARY);
}

ContentType Content::type() const
{
	auto isBinary = [](Encoding e) { return !IsText(e.eci); };

	if (std::none_of(encodings.begin(), encodings.end(), isBinary))
		return ContentType::Text;
	if (std::all_of(encodings.begin(), encodings.end(), isBinary))
		return ContentType::Binary;

	if (!hasECI) {
		auto cs = guessEncoding();
		if (IsText(ToECI(cs)))
			return ContentType::Text;
		if (cs == CharacterSet::BINARY)
			return ContentType::Binary;
	}

	return ContentType::Mixed;
}

} // namespace ZXing
<commit_msg>style: trivial whitespace fix<commit_after>/*
 * Copyright 2022 Axel Waggershauser
*/
// SPDX-License-Identifier: Apache-2.0

#include "Content.h"

#include "CharacterSetECI.h"
#include "TextDecoder.h"
#include "TextUtfEncoding.h"
#include "ZXContainerAlgorithms.h"

namespace ZXing {

std::string ToString(ContentType type)
{
	const char* t2s[] = {"Text", "Binary", "Mixed"};
	return t2s[static_cast<int>(type)];
}

template <typename FUNC>
void Content::ForEachECIBlock(FUNC func) const
{
	for (int i = 0; i < Size(encodings); ++i) {
		auto [eci, start] = encodings[i];
		int end = i + 1 == Size(encodings) ? Size(binary) : encodings[i + 1].pos;

		if (start != end)
			func(eci, start, end);
	}
}

void Content::switchEncoding(ECI eci, bool isECI)
{
	// replace all non-ECI entries on first ECI entry with default ECI
	if (isECI && !hasECI)
		encodings = {{ECI::ISO8859_1, 0}};
	if (isECI || !hasECI) {
		if (encodings.back().pos == Size(binary))
			encodings.back().eci = eci; // no point in recording 0 length segments
		else
			encodings.push_back({eci, Size(binary)});
	}
	hasECI |= isECI;
}

void Content::switchEncoding(CharacterSet cs)
{
	switchEncoding(ToECI(cs), false);
}

std::wstring Content::text() const
{
	auto fallbackCS = CharacterSetECI::CharsetFromName(hintedCharset.c_str());
	if (!hasECI && fallbackCS == CharacterSet::Unknown)
		fallbackCS = guessEncoding();

	std::wstring wstr;
	ForEachECIBlock([&](ECI eci, int begin, int end) {
		CharacterSet cs = eci == ECI::Unknown ? fallbackCS : ToCharacterSet(eci);

		TextDecoder::Append(wstr, binary.data() + begin, end - begin, cs);
	});
	return wstr;
}

std::string Content::utf8Protocol() const
{
	std::wstring res = TextDecoder::FromLatin1(symbology.toString(true));
	ECI lastECI = ECI::Unknown;
	auto fallbackCS = guessEncoding();

	ForEachECIBlock([&](ECI eci, int begin, int end) {
		// first determine how to decode the content (choose character set)
		//  * eci == ECI::Unknown implies !hasECI and we guess
		//  * if !IsText(eci) the ToCharcterSet(eci) will return Unknown and we decode as binary
		CharacterSet cs = eci == ECI::Unknown ? fallbackCS : ToCharacterSet(eci);

		// then find the eci to report back in the ECI designator
		if (IsText(ToECI(cs))) // everything decoded as text is reported as utf8
			eci = ECI::UTF8;
		else if (eci == ECI::Unknown) // implies !hasECI and fallbackCS is Unknown or Binary
			eci = ECI::Binary;

		if (lastECI != eci)
			TextDecoder::AppendLatin1(res, ToString(eci));
		lastECI = eci;

		std::wstring tmp;
		TextDecoder::Append(tmp, binary.data() + begin, end - begin, cs);
		for (auto c : tmp) {
			res += c;
			if (c == L'\\') // in the ECI protocol a '\' has to be doubled
				res += c;
		}
	});

	return TextUtfEncoding::ToUtf8(res);
}

ByteArray Content::binaryECI() const
{
	std::string res = symbology.toString(true);

	ForEachECIBlock([&](ECI eci, int begin, int end) {
		if (hasECI)
			res += ToString(eci);

		for (int i = begin; i != end; ++i) {
			char c = static_cast<char>(binary[i]);
			res += c;
			if (c == '\\') // in the ECI protocol a '\' has to be doubled
				res += c;
		}
	});

	return ByteArray(res);
}

CharacterSet Content::guessEncoding() const
{
	// assemble all blocks with unknown encoding
	ByteArray input;
	ForEachECIBlock([&](ECI eci, int begin, int end) {
		if (eci == ECI::Unknown)
			input.insert(input.end(), binary.begin() + begin, binary.begin() + end);
	});

	if (input.empty())
		return CharacterSet::Unknown;

	return TextDecoder::GuessEncoding(input.data(), input.size(), CharacterSet::BINARY);
}

ContentType Content::type() const
{
	auto isBinary = [](Encoding e) { return !IsText(e.eci); };

	if (std::none_of(encodings.begin(), encodings.end(), isBinary))
		return ContentType::Text;
	if (std::all_of(encodings.begin(), encodings.end(), isBinary))
		return ContentType::Binary;

	if (!hasECI) {
		auto cs = guessEncoding();
		if (IsText(ToECI(cs)))
			return ContentType::Text;
		if (cs == CharacterSet::BINARY)
			return ContentType::Binary;
	}

	return ContentType::Mixed;
}

} // namespace ZXing
<|endoftext|>


<commit_before>/**
 * @file sparse_coding_test.cpp
 *
 * Test for Sparse Coding
 */

// Note: We don't use BOOST_REQUIRE_CLOSE in the code below because we need
// to use FPC_WEAK, and it's not at all intuitive how to do that.

#include <mlpack/core.hpp>
#include <mlpack/methods/sparse_coding/sparse_coding.hpp>

#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"

using namespace arma;
using namespace mlpack;
using namespace mlpack::regression;
using namespace mlpack::sparse_coding;

BOOST_AUTO_TEST_SUITE(SparseCodingTest);

void SCVerifyCorrectness(vec beta, vec errCorr, double lambda)
{
  const double tol = 1e-12;
  size_t nDims = beta.n_elem;
  for(size_t j = 0; j < nDims; j++)
  {
    if (beta(j) == 0)
    {
      // Make sure that errCorr(j) <= lambda.
      BOOST_REQUIRE_SMALL(std::max(fabs(errCorr(j)) - lambda, 0.0), tol);
    }
    else if (beta(j) < 0)
    {
      // Make sure that errCorr(j) == lambda.
      BOOST_REQUIRE_SMALL(errCorr(j) - lambda, tol);
    }
    else // beta(j) > 0.
    {
      // Make sure that errCorr(j) == -lambda.
      BOOST_REQUIRE_SMALL(errCorr(j) + lambda, tol);
    }
  }
}

BOOST_AUTO_TEST_CASE(SparseCodingTestCodingStepLasso)
{
  double lambda1 = 0.1;
  uword nAtoms = 25;

  mat X;
  X.load("mnist_first250_training_4s_and_9s.arm");
  uword nPoints = X.n_cols;

  // Normalize each point since these are images.
  for (uword i = 0; i < nPoints; ++i)
    X.col(i) /= norm(X.col(i), 2);

  SparseCoding<> sc(X, nAtoms, lambda1);
  sc.OptimizeCode();

  mat D = sc.Dictionary();
  mat Z = sc.Codes();

  for (uword i = 0; i < nPoints; ++i)
  {
    vec errCorr = trans(D) * (D * Z.unsafe_col(i) - X.unsafe_col(i));
    SCVerifyCorrectness(Z.unsafe_col(i), errCorr, lambda1);
  }
}

BOOST_AUTO_TEST_CASE(SparseCodingTestCodingStepElasticNet)
{
  double lambda1 = 0.1;
  double lambda2 = 0.2;
  uword nAtoms = 25;

  mat X;
  X.load("mnist_first250_training_4s_and_9s.arm");
  uword nPoints = X.n_cols;

  // Normalize each point since these are images.
  for (uword i = 0; i < nPoints; ++i)
    X.col(i) /= norm(X.col(i), 2);

  SparseCoding<> sc(X, nAtoms, lambda1, lambda2);
  sc.OptimizeCode();

  mat D = sc.Dictionary();
  mat Z = sc.Codes();

  for(uword i = 0; i < nPoints; ++i)
  {
    vec errCorr = (trans(D) * D + lambda2 *
       eye(nAtoms, nAtoms)) * Z.unsafe_col(i) - trans(D) * X.unsafe_col(i);

    SCVerifyCorrectness(Z.unsafe_col(i), errCorr, lambda1);
  }
}

BOOST_AUTO_TEST_CASE(SparseCodingTestDictionaryStep)
{
  const double tol = 1e-12;

  double lambda1 = 0.1;
  uword nAtoms = 25;

  mat X;
  X.load("mnist_first250_training_4s_and_9s.arm");
  uword nPoints = X.n_cols;

  // Normalize each point since these are images.
  for(uword i = 0; i < nPoints; ++i)
    X.col(i) /= norm(X.col(i), 2);

  SparseCoding<> sc(X, nAtoms, lambda1);
  sc.OptimizeCode();

  mat D = sc.Dictionary();
  mat Z = sc.Codes();

  X = D * Z;

  SparseCoding<> sc2(X, nAtoms, lambda1);
//  sc.Data() = X;

  uvec adjacencies = find(Z);
  sc.OptimizeDictionary(adjacencies);

  mat D_hat = sc.Dictionary();

  BOOST_REQUIRE_SMALL(norm(D - D_hat, "fro"), tol);
}

/*
BOOST_AUTO_TEST_CASE(SparseCodingTestWhole)
{

}
*/

BOOST_AUTO_TEST_SUITE_END();
<commit_msg>Formatting fix, and handle things a little more carefully.<commit_after>/**
 * @file sparse_coding_test.cpp
 *
 * Test for Sparse Coding
 */

// Note: We don't use BOOST_REQUIRE_CLOSE in the code below because we need
// to use FPC_WEAK, and it's not at all intuitive how to do that.

#include <mlpack/core.hpp>
#include <mlpack/methods/sparse_coding/sparse_coding.hpp>

#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"

using namespace arma;
using namespace mlpack;
using namespace mlpack::regression;
using namespace mlpack::sparse_coding;

BOOST_AUTO_TEST_SUITE(SparseCodingTest);

void SCVerifyCorrectness(vec beta, vec errCorr, double lambda)
{
  const double tol = 1e-12;
  size_t nDims = beta.n_elem;
  for(size_t j = 0; j < nDims; j++)
  {
    if (beta(j) == 0)
    {
      // Make sure that errCorr(j) <= lambda.
      BOOST_REQUIRE_SMALL(std::max(fabs(errCorr(j)) - lambda, 0.0), tol);
    }
    else if (beta(j) < 0)
    {
      // Make sure that errCorr(j) == lambda.
      BOOST_REQUIRE_SMALL(errCorr(j) - lambda, tol);
    }
    else // beta(j) > 0.
    {
      // Make sure that errCorr(j) == -lambda.
      BOOST_REQUIRE_SMALL(errCorr(j) + lambda, tol);
    }
  }
}

BOOST_AUTO_TEST_CASE(SparseCodingTestCodingStepLasso)
{
  double lambda1 = 0.1;
  uword nAtoms = 25;

  mat X;
  X.load("mnist_first250_training_4s_and_9s.arm");
  uword nPoints = X.n_cols;

  // Normalize each point since these are images.
  for (uword i = 0; i < nPoints; ++i)
    X.col(i) /= norm(X.col(i), 2);

  SparseCoding<> sc(X, nAtoms, lambda1);
  sc.OptimizeCode();

  mat D = sc.Dictionary();
  mat Z = sc.Codes();

  for (uword i = 0; i < nPoints; ++i)
  {
    vec errCorr = trans(D) * (D * Z.unsafe_col(i) - X.unsafe_col(i));
    SCVerifyCorrectness(Z.unsafe_col(i), errCorr, lambda1);
  }
}

BOOST_AUTO_TEST_CASE(SparseCodingTestCodingStepElasticNet)
{
  double lambda1 = 0.1;
  double lambda2 = 0.2;
  uword nAtoms = 25;

  mat X;
  X.load("mnist_first250_training_4s_and_9s.arm");
  uword nPoints = X.n_cols;

  // Normalize each point since these are images.
  for (uword i = 0; i < nPoints; ++i)
    X.col(i) /= norm(X.col(i), 2);

  SparseCoding<> sc(X, nAtoms, lambda1, lambda2);
  sc.OptimizeCode();

  mat D = sc.Dictionary();
  mat Z = sc.Codes();

  for(uword i = 0; i < nPoints; ++i)
  {
    vec errCorr = (trans(D) * D + lambda2 *
       eye(nAtoms, nAtoms)) * Z.unsafe_col(i) - trans(D) * X.unsafe_col(i);

    SCVerifyCorrectness(Z.unsafe_col(i), errCorr, lambda1);
  }
}

BOOST_AUTO_TEST_CASE(SparseCodingTestDictionaryStep)
{
  const double tol = 1e-12;

  double lambda1 = 0.1;
  uword nAtoms = 25;

  mat X;
  X.load("mnist_first250_training_4s_and_9s.arm");
  uword nPoints = X.n_cols;

  // Normalize each point since these are images.
  for (uword i = 0; i < nPoints; ++i)
    X.col(i) /= norm(X.col(i), 2);

  SparseCoding<> sc(X, nAtoms, lambda1);
  sc.OptimizeCode();

  mat D = sc.Dictionary();
  mat Z = sc.Codes();

  X = D * Z;

  // This will update sc.data (that is a reference to X).
  DataDependentRandomInitializer::Initialize(X, nAtoms, sc.Dictionary());

  uvec adjacencies = find(Z);
  sc.OptimizeDictionary(adjacencies);

  mat D_hat = sc.Dictionary();

  BOOST_REQUIRE_SMALL(norm(D - D_hat, "fro"), tol);
}

/*
BOOST_AUTO_TEST_CASE(SparseCodingTestWhole)
{

}
*/

BOOST_AUTO_TEST_SUITE_END();
<|endoftext|>


<commit_before><commit_msg>Remove dependency on base from drfuzz_main.cc.<commit_after><|endoftext|>


<commit_before>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/MIRIAM/CRDFWriter.cpp,v $
//   $Revision: 1.8 $
//   $Name:  $
//   $Author: shoops $
//   $Date: 2008/07/11 16:05:18 $
// End CVS Header

// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include <sstream>

#include "copasi.h"

#include "CRDFWriter.h"
#include "CRDFGraph.h"
#include "CRDFSubject.h"
#include "CRDFObject.h"
#include "CRDFLiteral.h"

#include "utilities/CCopasiMessage.h"

//static
std::string CRDFWriter::xmlFromGraph(const CRDFGraph * pGraph)
{
  CRDFWriter Writer;

  char * XML = Writer.CRDFWriter::write(pGraph);

  if (XML != NULL)
    return XML;

  return "";
}

CRDFWriter::CRDFWriter():
    CRaptorInit(),
    mpWriter(NULL),
    mpGraph(NULL)
{
  mpWriter = raptor_new_serializer("rdfxml-abbrev");

  // We do not want <?xml version="1.0" encoding="utf-8"?>
  raptor_serializer_set_feature(mpWriter, RAPTOR_FEATURE_WRITER_XML_DECLARATION, 0);

  // Remove any empty elements
  raptor_serializer_set_feature(mpWriter, RAPTOR_FEATURE_WRITER_AUTO_EMPTY, 1);
}

CRDFWriter::~CRDFWriter()
{
  if (mpWriter != NULL)
    raptor_free_serializer(mpWriter);
}

void CRDFWriter::initNamespaces(const CRDFGraph * pGraph)
{
  std::map< std::string, std::string >::const_iterator it =
    pGraph->getNameSpaceMap().begin();
  std::map< std::string, std::string >::const_iterator end =
    pGraph->getNameSpaceMap().end();

  raptor_uri* pURI = NULL;

  for (; it != end; ++it)
    {
      pURI = raptor_new_uri((const unsigned char *) it->second.c_str());
      raptor_serialize_set_namespace(mpWriter, pURI, (const unsigned char *) it->first.c_str());
      pRaptorFreeUri(pURI);
    }
}

char * CRDFWriter::write(const CRDFGraph * pGraph)
{
  bool success = true;

  void * XML;     /* destination for string */
  size_t Length;  /* length of constructed string */

  initNamespaces(pGraph);

  raptor_uri * pURI = raptor_new_uri((const unsigned char *) "");

  if (raptor_serialize_start_to_string(mpWriter, pURI, & XML, & Length))
    fatalError();

  // We need to add all triplets
  std::set< CRDFTriplet >::const_iterator it = pGraph->getTriplets().begin();
  std::set< CRDFTriplet >::const_iterator end = pGraph->getTriplets().end();

  raptor_uri * pSubjectURI = NULL;
  raptor_uri * pPredicateURI = NULL;
  raptor_uri * pObjectURI = NULL;
  raptor_uri * pLiteralDataTypeURI = NULL;

  raptor_statement Triplet;

  for (; it != end; ++it)
    {
      // Set the subject of the triplet
      const CRDFSubject & Subject = it->pSubject->getSubject();
      switch (Subject.getType())
        {
        case CRDFSubject::RESOURCE:
          Triplet.subject_type = RAPTOR_IDENTIFIER_TYPE_RESOURCE;
          pSubjectURI = raptor_new_uri((const unsigned char *) Subject.getResource().c_str());
          Triplet.subject = pSubjectURI;
          break;

        case CRDFSubject::BLANK_NODE:
          Triplet.subject_type = RAPTOR_IDENTIFIER_TYPE_ANONYMOUS;
          Triplet.subject = Subject.getBlankNodeID().c_str();
          break;
        }

      // Set the predicate of the triplet
      Triplet.predicate_type = RAPTOR_IDENTIFIER_TYPE_RESOURCE;
      pPredicateURI = raptor_new_uri((const unsigned char *) it->Predicate.getURI().c_str());
      Triplet.predicate = pPredicateURI;

      // Set the object of the triplet
      const CRDFObject & Object = it->pObject->getObject();
      switch (Object.getType())
        {
        case CRDFObject::RESOURCE:
          Triplet.object_type = RAPTOR_IDENTIFIER_TYPE_RESOURCE;
          pObjectURI = raptor_new_uri((const unsigned char *) Object.getResource().c_str());
          Triplet.object = pObjectURI;
          break;

        case CRDFObject::BLANK_NODE:
          Triplet.object_type = RAPTOR_IDENTIFIER_TYPE_ANONYMOUS;
          Triplet.object = Object.getBlankNodeID().c_str();
          break;

        case CRDFObject::LITERAL:
          Triplet.object_type = RAPTOR_IDENTIFIER_TYPE_LITERAL;
          const CRDFLiteral & Literal = Object.getLiteral();

          switch (Literal.getType())
            {
            case CRDFLiteral::TYPED:
              pLiteralDataTypeURI = raptor_new_uri((const unsigned char *) Literal.getDataType().c_str());
              Triplet.object_literal_datatype = pLiteralDataTypeURI;
              Triplet.object_literal_language = NULL;
              break;

            case CRDFLiteral::PLAIN:
              Triplet.object_literal_datatype = NULL;
              if (Literal.getLanguage() != "")
                Triplet.object_literal_language = (const unsigned char *) Literal.getLanguage().c_str();
              else
                Triplet.object_literal_language = NULL;
              break;
            }

          Triplet.object = Literal.getLexicalData().c_str();
          break;
        }

      if (raptor_serialize_statement(mpWriter, &Triplet))
        success = false;

      pRaptorFreeUri(pPredicateURI);
      pRaptorFreeUri(pObjectURI);
      pRaptorFreeUri(pLiteralDataTypeURI);
      pRaptorFreeUri(pSubjectURI);
    }

  if (raptor_serialize_end(mpWriter))
    fatalError();

  return static_cast< char * >(XML);
}
<commit_msg>Fixed Bug 1501. The memory leak in CRDFWriter::xmlFromGraph() is fixed.<commit_after>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/MIRIAM/CRDFWriter.cpp,v $
//   $Revision: 1.9 $
//   $Name:  $
//   $Author: shoops $
//   $Date: 2011/11/10 17:14:10 $
// End CVS Header

// Copyright (C) 2011 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include <stdlib.h>

#include <sstream>

#include "copasi.h"

#include "CRDFWriter.h"
#include "CRDFGraph.h"
#include "CRDFSubject.h"
#include "CRDFObject.h"
#include "CRDFLiteral.h"

#include "utilities/CCopasiMessage.h"

//static
std::string CRDFWriter::xmlFromGraph(const CRDFGraph * pGraph)
{
  CRDFWriter Writer;

  char * pXML = Writer.CRDFWriter::write(pGraph);

  if (pXML != NULL)
    {
      std::string XML = pXML;
      free(pXML);

      return XML;
    }

  return "";
}

CRDFWriter::CRDFWriter():
    CRaptorInit(),
    mpWriter(NULL),
    mpGraph(NULL)
{
  mpWriter = raptor_new_serializer("rdfxml-abbrev");

  // We do not want <?xml version="1.0" encoding="utf-8"?>
  raptor_serializer_set_feature(mpWriter, RAPTOR_FEATURE_WRITER_XML_DECLARATION, 0);

  // Remove any empty elements
  raptor_serializer_set_feature(mpWriter, RAPTOR_FEATURE_WRITER_AUTO_EMPTY, 1);
}

CRDFWriter::~CRDFWriter()
{
  if (mpWriter != NULL)
    raptor_free_serializer(mpWriter);
}

void CRDFWriter::initNamespaces(const CRDFGraph * pGraph)
{
  std::map< std::string, std::string >::const_iterator it =
    pGraph->getNameSpaceMap().begin();
  std::map< std::string, std::string >::const_iterator end =
    pGraph->getNameSpaceMap().end();

  raptor_uri* pURI = NULL;

  for (; it != end; ++it)
    {
      pURI = raptor_new_uri((const unsigned char *) it->second.c_str());
      raptor_serialize_set_namespace(mpWriter, pURI, (const unsigned char *) it->first.c_str());
      pRaptorFreeUri(pURI);
    }
}

char * CRDFWriter::write(const CRDFGraph * pGraph)
{
  bool success = true;

  void * XML;     /* destination for string */
  size_t Length;  /* length of constructed string */

  initNamespaces(pGraph);

  raptor_uri * pURI = raptor_new_uri((const unsigned char *) "");

  if (raptor_serialize_start_to_string(mpWriter, pURI, & XML, & Length))
    fatalError();

  // We need to add all triplets
  std::set< CRDFTriplet >::const_iterator it = pGraph->getTriplets().begin();
  std::set< CRDFTriplet >::const_iterator end = pGraph->getTriplets().end();

  raptor_uri * pSubjectURI = NULL;
  raptor_uri * pPredicateURI = NULL;
  raptor_uri * pObjectURI = NULL;
  raptor_uri * pLiteralDataTypeURI = NULL;

  raptor_statement Triplet;

  for (; it != end; ++it)
    {
      // Set the subject of the triplet
      const CRDFSubject & Subject = it->pSubject->getSubject();

      switch (Subject.getType())
        {
          case CRDFSubject::RESOURCE:
            Triplet.subject_type = RAPTOR_IDENTIFIER_TYPE_RESOURCE;
            pSubjectURI = raptor_new_uri((const unsigned char *) Subject.getResource().c_str());
            Triplet.subject = pSubjectURI;
            break;

          case CRDFSubject::BLANK_NODE:
            Triplet.subject_type = RAPTOR_IDENTIFIER_TYPE_ANONYMOUS;
            Triplet.subject = Subject.getBlankNodeID().c_str();
            break;
        }

      // Set the predicate of the triplet
      Triplet.predicate_type = RAPTOR_IDENTIFIER_TYPE_RESOURCE;
      pPredicateURI = raptor_new_uri((const unsigned char *) it->Predicate.getURI().c_str());
      Triplet.predicate = pPredicateURI;

      // Set the object of the triplet
      const CRDFObject & Object = it->pObject->getObject();

      switch (Object.getType())
        {
          case CRDFObject::RESOURCE:
            Triplet.object_type = RAPTOR_IDENTIFIER_TYPE_RESOURCE;
            pObjectURI = raptor_new_uri((const unsigned char *) Object.getResource().c_str());
            Triplet.object = pObjectURI;
            break;

          case CRDFObject::BLANK_NODE:
            Triplet.object_type = RAPTOR_IDENTIFIER_TYPE_ANONYMOUS;
            Triplet.object = Object.getBlankNodeID().c_str();
            break;

          case CRDFObject::LITERAL:
            Triplet.object_type = RAPTOR_IDENTIFIER_TYPE_LITERAL;
            const CRDFLiteral & Literal = Object.getLiteral();

            switch (Literal.getType())
              {
                case CRDFLiteral::TYPED:
                  pLiteralDataTypeURI = raptor_new_uri((const unsigned char *) Literal.getDataType().c_str());
                  Triplet.object_literal_datatype = pLiteralDataTypeURI;
                  Triplet.object_literal_language = NULL;
                  break;

                case CRDFLiteral::PLAIN:
                  Triplet.object_literal_datatype = NULL;

                  if (Literal.getLanguage() != "")
                    Triplet.object_literal_language = (const unsigned char *) Literal.getLanguage().c_str();
                  else
                    Triplet.object_literal_language = NULL;

                  break;
              }

            Triplet.object = Literal.getLexicalData().c_str();
            break;
        }

      if (raptor_serialize_statement(mpWriter, &Triplet))
        success = false;

      pRaptorFreeUri(pPredicateURI);
      pRaptorFreeUri(pObjectURI);
      pRaptorFreeUri(pLiteralDataTypeURI);
      pRaptorFreeUri(pSubjectURI);
    }

  if (raptor_serialize_end(mpWriter))
    fatalError();

  return static_cast< char * >(XML);
}
<|endoftext|>


<commit_before>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/model/CModelValue.cpp,v $
   $Revision: 1.11 $
   $Name:  $
   $Author: shoops $
   $Date: 2006/03/02 02:22:53 $
   End CVS Header */

#include <iostream>
#include <string>
#include <vector>
#include <limits>

#include "copasi.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "utilities/utility.h"
#include "report/CCopasiObjectReference.h"
#include "report/CKeyFactory.h"
#include "CModel.h"
#include "CModelValue.h"

//static
const std::string CModelEntity::StatusName[] =
  {"fixed", "independent variable modified by reactions", "determined by moieties", "unused", "ode", "assignment", ""};

//static
const char * CModelEntity::XMLStatus[] =
  {"fixed", "variable", "variable", "variable", "ode", "assignment", NULL};
// the "variable" keyword is used for compatibility reasons. It actually means "this metab is part
// of the reaction network, copasi needs to figure out if it is independent, dependent (moieties) or unused."

CModelEntity::CModelEntity(const std::string & name,
                           const CCopasiContainer * pParent,
                           const std::string & type,
                           const unsigned C_INT32 & flag):
    CCopasiContainer(name, pParent, type, flag),
    mKey(""),
    mpValueAccess(NULL),
    mpValueData(NULL),
    mpIValue(NULL),
    mRate(0.0),
    mStatus(FIXED),
    mpModel(NULL)
{
  initObjects();

  *mpIValue = 1.0;
  *mpValueData = std::numeric_limits<C_FLOAT64>::quiet_NaN();

  CONSTRUCTOR_TRACE;
}

CModelEntity::CModelEntity(const CModelEntity & src,
                           const CCopasiContainer * pParent):
    CCopasiContainer(src, pParent),
    mKey(""),
    mpValueAccess(NULL),
    mpValueData(NULL),
    mpIValue(NULL),
    mRate(src.mRate),
    mStatus(),
    mpModel(NULL)
{
  initObjects();

  setStatus(src.mStatus);

  *mpValueData = *src.mpValueData;
  *mpIValue = *src.mpIValue;

  CONSTRUCTOR_TRACE;
}

CModelEntity::~CModelEntity()
{
  if (!mpModel)
    {
      pdelete(mpValueData);
      pdelete(mpIValue);
    }

  DESTRUCTOR_TRACE;
}

const std::string & CModelEntity::getKey() const {return mKey;}

const C_FLOAT64 & CModelEntity::getValue() const {return *mpValueAccess;}

const C_FLOAT64 & CModelEntity::getInitialValue() const {return *mpIValue;}

const CModelEntity::Status & CModelEntity::getStatus() const {return mStatus;}

/**
 * Return rate of production of this entity
 */
const C_FLOAT64 & CModelEntity::getRate() const
  {
    return mRate;
  }

//***********

void CModelEntity::setValue(const C_FLOAT64 & value)
{
  if (mStatus == FIXED) return;

  *mpValueData = value;

#ifdef COPASI_DEBUG
  //if (mStatus == FIXED)
  //std::cout << "warning: set the transient concentration on a fixed entity" << std::endl;
#endif
}

void CModelEntity::setInitialValue(const C_FLOAT64 & initialValue)
{
  *mpIValue = initialValue;

  if (mStatus != FIXED) return;
}

void CModelEntity::setRate(const C_FLOAT64 & rate)
{
  mRate = rate;
}

//  ******************

void CModelEntity::setStatus(const CModelEntity::Status & status)
{
  if (mStatus != status)
    {
      mStatus = status;
      this->setValuePtr(mpValueData);
    }
}

void * CModelEntity::getReference() const
  {return const_cast<C_FLOAT64 *>(mpValueAccess);}

void CModelEntity::initObjects()
{
  mpModel = static_cast<CModel *>(getObjectAncestor("Model"));

  if (mpModel)
    mpModel->getStateTemplate().add(this);
  else
    {
      mpValueData = new C_FLOAT64;
      mpIValue = new C_FLOAT64;
    }

  mpValueAccess = mpIValue;

  mpValueReference =
    static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference("Value",
        *mpValueAccess,
        CCopasiObject::ValueDbl));
  mpIValueReference =
    static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference("InitialValue",
        *mpIValue,
        CCopasiObject::ValueDbl));

  addObjectReference("Rate", mRate, CCopasiObject::ValueDbl);
}

void CModelEntity::setInitialValuePtr(C_FLOAT64 * pInitialValue)
{
  mpIValue = pInitialValue;
  if (!mpIValue) mpIValue = new C_FLOAT64;
  mpIValueReference->setReference(*mpIValue);
}

void CModelEntity::setValuePtr(C_FLOAT64 * pValue)
{
  mpValueData = pValue;
  if (!mpValueData) mpValueData = new C_FLOAT64;

  if (mStatus == FIXED)
    mpValueAccess = mpIValue;
  else
    mpValueAccess = mpValueData;

  mpValueReference->setReference(*mpValueAccess);
}

bool CModelEntity::setObjectParent(const CCopasiContainer * pParent)
{
  CCopasiContainer::setObjectParent(pParent);
  CModel * pNewModel = static_cast<CModel *>(getObjectAncestor("Model"));

  if (mpModel == pNewModel) return true;

  C_FLOAT64 InitialValue = *mpIValue;
  C_FLOAT64 Value = *mpValueData;

  if (mpModel)
    mpModel->getStateTemplate().remove(this);
  else
    {
      pdelete(mpIValue);
      pdelete(mpValueData);
    }

  if (pNewModel)
    pNewModel->getStateTemplate().add(this);
  else
    {
      mpValueData = new C_FLOAT64;
      mpIValue = new C_FLOAT64;
    }

  mpModel = pNewModel;
  *mpIValue = InitialValue;
  *mpValueData = Value;

  return true;
}

void CModelEntity::setSBMLId(const std::string& id)
{
  this->mSBMLId = id;
}

const std::string& CModelEntity::getSBMLId() const
  {
    return this->mSBMLId;
  }
//********************************************************************+

CModelValue::CModelValue(const std::string & name,
                         const CCopasiContainer * pParent):
    CModelEntity(name, pParent, "ModelValue")
{
  mKey = GlobalKeys.add("ModelValue", this);
  initObjects();

  CONSTRUCTOR_TRACE;
}

CModelValue::CModelValue(const CModelValue & src,
                         const CCopasiContainer * pParent):
    CModelEntity(src, pParent)
{
  mKey = GlobalKeys.add("ModelValue", this);
  initObjects();
  CONSTRUCTOR_TRACE;
}

CModelValue::~CModelValue()
{
  GlobalKeys.remove(mKey);
  DESTRUCTOR_TRACE;
}

void CModelValue::initObjects()
{}

std::ostream & operator<<(std::ostream &os, const CModelValue & d)
{
  os << "    ++++CModelValue: " << d.getObjectName() << std::endl;
  os << "        mValue " << *d.mpValueAccess << " mIValue " << *d.mpIValue << std::endl;
  os << "        mRate " << d.mRate << " mStatus " << d.getStatus() << std::endl;
  os << "    ----CModelValue " << std::endl;

  return os;
}
<commit_msg>Fixed Bug 423. The order in which the objects are created in CModelEntity::initObjects is fixed to avoid access violations.<commit_after>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/model/CModelValue.cpp,v $
   $Revision: 1.12 $
   $Name:  $
   $Author: shoops $
   $Date: 2006/03/08 13:06:32 $
   End CVS Header */

#include <iostream>
#include <string>
#include <vector>
#include <limits>

#include "copasi.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "utilities/utility.h"
#include "report/CCopasiObjectReference.h"
#include "report/CKeyFactory.h"
#include "CModel.h"
#include "CModelValue.h"

//static
const std::string CModelEntity::StatusName[] =
  {"fixed", "independent variable modified by reactions", "determined by moieties", "unused", "ode", "assignment", ""};

//static
const char * CModelEntity::XMLStatus[] =
  {"fixed", "variable", "variable", "variable", "ode", "assignment", NULL};
// the "variable" keyword is used for compatibility reasons. It actually means "this metab is part
// of the reaction network, copasi needs to figure out if it is independent, dependent (moieties) or unused."

CModelEntity::CModelEntity(const std::string & name,
                           const CCopasiContainer * pParent,
                           const std::string & type,
                           const unsigned C_INT32 & flag):
    CCopasiContainer(name, pParent, type, flag),
    mKey(""),
    mpValueAccess(NULL),
    mpValueData(NULL),
    mpIValue(NULL),
    mRate(0.0),
    mStatus(FIXED),
    mpModel(NULL)
{
  initObjects();

  *mpIValue = 1.0;
  *mpValueData = std::numeric_limits<C_FLOAT64>::quiet_NaN();

  CONSTRUCTOR_TRACE;
}

CModelEntity::CModelEntity(const CModelEntity & src,
                           const CCopasiContainer * pParent):
    CCopasiContainer(src, pParent),
    mKey(""),
    mpValueAccess(NULL),
    mpValueData(NULL),
    mpIValue(NULL),
    mRate(src.mRate),
    mStatus(),
    mpModel(NULL)
{
  initObjects();

  setStatus(src.mStatus);

  *mpValueData = *src.mpValueData;
  *mpIValue = *src.mpIValue;

  CONSTRUCTOR_TRACE;
}

CModelEntity::~CModelEntity()
{
  if (!mpModel)
    {
      pdelete(mpValueData);
      pdelete(mpIValue);
    }

  DESTRUCTOR_TRACE;
}

const std::string & CModelEntity::getKey() const {return mKey;}

const C_FLOAT64 & CModelEntity::getValue() const {return *mpValueAccess;}

const C_FLOAT64 & CModelEntity::getInitialValue() const {return *mpIValue;}

const CModelEntity::Status & CModelEntity::getStatus() const {return mStatus;}

/**
 * Return rate of production of this entity
 */
const C_FLOAT64 & CModelEntity::getRate() const
  {
    return mRate;
  }

//***********

void CModelEntity::setValue(const C_FLOAT64 & value)
{
  if (mStatus == FIXED) return;

  *mpValueData = value;

#ifdef COPASI_DEBUG
  //if (mStatus == FIXED)
  //std::cout << "warning: set the transient concentration on a fixed entity" << std::endl;
#endif
}

void CModelEntity::setInitialValue(const C_FLOAT64 & initialValue)
{
  *mpIValue = initialValue;

  if (mStatus != FIXED) return;
}

void CModelEntity::setRate(const C_FLOAT64 & rate)
{
  mRate = rate;
}

//  ******************

void CModelEntity::setStatus(const CModelEntity::Status & status)
{
  if (mStatus != status)
    {
      mStatus = status;
      this->setValuePtr(mpValueData);
    }
}

void * CModelEntity::getReference() const
  {return const_cast<C_FLOAT64 *>(mpValueAccess);}

void CModelEntity::initObjects()
{
  C_FLOAT64 Dummy;

  mpValueReference =
    static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference("Value",
        Dummy,
        CCopasiObject::ValueDbl));
  mpIValueReference =
    static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference("InitialValue",
        Dummy,
        CCopasiObject::ValueDbl));

  mpModel = static_cast<CModel *>(getObjectAncestor("Model"));

  if (mpModel)
    mpModel->getStateTemplate().add(this);
  else
    {
      // This creates the needed values.
      setInitialValuePtr(NULL);
      setValuePtr(NULL);
    }

  addObjectReference("Rate", mRate, CCopasiObject::ValueDbl);
}

void CModelEntity::setInitialValuePtr(C_FLOAT64 * pInitialValue)
{
  mpIValue = pInitialValue;
  if (!mpIValue) mpIValue = new C_FLOAT64;
  mpIValueReference->setReference(*mpIValue);
}

void CModelEntity::setValuePtr(C_FLOAT64 * pValue)
{
  mpValueData = pValue;
  if (!mpValueData) mpValueData = new C_FLOAT64;

  if (mStatus == FIXED)
    mpValueAccess = mpIValue;
  else
    mpValueAccess = mpValueData;

  mpValueReference->setReference(*mpValueAccess);
}

bool CModelEntity::setObjectParent(const CCopasiContainer * pParent)
{
  CCopasiContainer::setObjectParent(pParent);
  CModel * pNewModel = static_cast<CModel *>(getObjectAncestor("Model"));

  if (mpModel == pNewModel) return true;

  C_FLOAT64 InitialValue = *mpIValue;
  C_FLOAT64 Value = *mpValueData;

  if (mpModel)
    mpModel->getStateTemplate().remove(this);
  else
    {
      pdelete(mpIValue);
      pdelete(mpValueData);
    }

  if (pNewModel)
    pNewModel->getStateTemplate().add(this);
  else
    {
      mpValueData = new C_FLOAT64;
      mpIValue = new C_FLOAT64;
    }

  mpModel = pNewModel;
  *mpIValue = InitialValue;
  *mpValueData = Value;

  return true;
}

void CModelEntity::setSBMLId(const std::string& id)
{
  this->mSBMLId = id;
}

const std::string& CModelEntity::getSBMLId() const
  {
    return this->mSBMLId;
  }
//********************************************************************+

CModelValue::CModelValue(const std::string & name,
                         const CCopasiContainer * pParent):
    CModelEntity(name, pParent, "ModelValue")
{
  mKey = GlobalKeys.add("ModelValue", this);
  initObjects();

  CONSTRUCTOR_TRACE;
}

CModelValue::CModelValue(const CModelValue & src,
                         const CCopasiContainer * pParent):
    CModelEntity(src, pParent)
{
  mKey = GlobalKeys.add("ModelValue", this);
  initObjects();
  CONSTRUCTOR_TRACE;
}

CModelValue::~CModelValue()
{
  GlobalKeys.remove(mKey);
  DESTRUCTOR_TRACE;
}

void CModelValue::initObjects()
{}

std::ostream & operator<<(std::ostream &os, const CModelValue & d)
{
  os << "    ++++CModelValue: " << d.getObjectName() << std::endl;
  os << "        mValue " << *d.mpValueAccess << " mIValue " << *d.mpIValue << std::endl;
  os << "        mRate " << d.mRate << " mStatus " << d.getStatus() << std::endl;
  os << "    ----CModelValue " << std::endl;

  return os;
}
<|endoftext|>


<commit_before><commit_msg>[ubuntu] Begun volume filtering<commit_after><|endoftext|>


<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright (c) 2010, Rice University
*  All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   * Neither the name of the Rice University nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
*  POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/

/* Author: Ioan Sucan */

#include "ompl/base/ProblemDefinition.h"
#include "ompl/base/goals/GoalState.h"
#include "ompl/base/goals/GoalStates.h"
#include "ompl/base/OptimizationObjective.h"
#include "ompl/control/SpaceInformation.h"
#include "ompl/control/PathControl.h"
#include "ompl/tools/config/MagicConstants.h"
#include <sstream>
#include <algorithm>

#include <boost/thread/mutex.hpp>

/// @cond IGNORE
namespace ompl
{
    namespace base
    {

        class ProblemDefinition::PlannerSolutionSet
        {
        public:

            PlannerSolutionSet()
            {
            }

            void add(const PlannerSolution &s)
            {
                boost::mutex::scoped_lock slock(lock_);
                int index = solutions_.size();
                solutions_.push_back(s);
                solutions_.back().index_ = index;
                std::sort(solutions_.begin(), solutions_.end());
            }

            void clear()
            {
                boost::mutex::scoped_lock slock(lock_);
                solutions_.clear();
            }

            std::vector<PlannerSolution> getSolutions()
            {
                boost::mutex::scoped_lock slock(lock_);
                std::vector<PlannerSolution> copy = solutions_;
                return copy;
            }

            bool isApproximate()
            {
                boost::mutex::scoped_lock slock(lock_);
                bool result = false;
                if (!solutions_.empty())
                    result = solutions_[0].approximate_;
                return result;
            }

            bool isOptimized()
            {
                boost::mutex::scoped_lock slock(lock_);
                bool result = false;
                if (!solutions_.empty())
                    result = solutions_[0].optimized_;
                return result;
            }

            double getDifference()
            {
                boost::mutex::scoped_lock slock(lock_);
                double diff = -1.0;
                if (!solutions_.empty())
                    diff = solutions_[0].difference_;
                return diff;
            }

            PathPtr getTopSolution()
            {
                boost::mutex::scoped_lock slock(lock_);
                PathPtr copy;
                if (!solutions_.empty())
                    copy = solutions_[0].path_;
                return copy;
            }

            const std::string& getTopSolutionPlannerName(void)
            {
                boost::mutex::scoped_lock slock(lock_);
                if (!solutions_.empty())
                    return solutions_[0].plannerName_;
                else
                    return std::string("");
            }

            std::size_t getSolutionCount()
            {
                boost::mutex::scoped_lock slock(lock_);
                std::size_t result = solutions_.size();
                return result;
            }

        private:

            std::vector<PlannerSolution> solutions_;
            boost::mutex                 lock_;
        };
    }
}
/// @endcond

ompl::base::ProblemDefinition::ProblemDefinition(const SpaceInformationPtr &si) : si_(si), solutions_(new PlannerSolutionSet())
{
}

void ompl::base::ProblemDefinition::setStartAndGoalStates(const State *start, const State *goal, const double threshold)
{
    clearStartStates();
    addStartState(start);
    setGoalState(goal, threshold);
}

void ompl::base::ProblemDefinition::setGoalState(const State *goal, const double threshold)
{
    clearGoal();
    GoalState *gs = new GoalState(si_);
    gs->setState(goal);
    gs->setThreshold(threshold);
    setGoal(GoalPtr(gs));
}

bool ompl::base::ProblemDefinition::hasStartState(const State *state, unsigned int *startIndex)
{
    for (unsigned int i = 0 ; i < startStates_.size() ; ++i)
        if (si_->equalStates(state, startStates_[i]))
        {
            if (startIndex)
                *startIndex = i;
            return true;
        }
    return false;
}

bool ompl::base::ProblemDefinition::fixInvalidInputState(State *state, double dist, bool start, unsigned int attempts)
{
    bool result = false;

    bool b = si_->satisfiesBounds(state);
    bool v = false;
    if (b)
    {
        v = si_->isValid(state);
        if (!v)
            OMPL_DEBUG("%s state is not valid", start ? "Start" : "Goal");
    }
    else
        OMPL_DEBUG("%s state is not within space bounds", start ? "Start" : "Goal");

    if (!b || !v)
    {
        std::stringstream ss;
        si_->printState(state, ss);
        ss << " within distance " << dist;
        OMPL_DEBUG("Attempting to fix %s state %s", start ? "start" : "goal", ss.str().c_str());

        State *temp = si_->allocState();
        if (si_->searchValidNearby(temp, state, dist, attempts))
        {
            si_->copyState(state, temp);
            result = true;
        }
        else
            OMPL_WARN("Unable to fix %s state", start ? "start" : "goal");
        si_->freeState(temp);
    }

    return result;
}

bool ompl::base::ProblemDefinition::fixInvalidInputStates(double distStart, double distGoal, unsigned int attempts)
{
    bool result = true;

    // fix start states
    for (unsigned int i = 0 ; i < startStates_.size() ; ++i)
        if (!fixInvalidInputState(startStates_[i], distStart, true, attempts))
            result = false;

    // fix goal state
    GoalState *goal = dynamic_cast<GoalState*>(goal_.get());
    if (goal)
    {
        if (!fixInvalidInputState(const_cast<State*>(goal->getState()), distGoal, false, attempts))
            result = false;
    }

    // fix goal state
    GoalStates *goals = dynamic_cast<GoalStates*>(goal_.get());
    if (goals)
    {
        for (unsigned int i = 0; i < goals->getStateCount(); ++i)
            if (!fixInvalidInputState(const_cast<State*>(goals->getState(i)), distGoal, false, attempts))
                result = false;
    }

    return result;
}

void ompl::base::ProblemDefinition::getInputStates(std::vector<const State*> &states) const
{
    states.clear();
    for (unsigned int i = 0 ; i < startStates_.size() ; ++i)
        states.push_back(startStates_[i]);

    GoalState *goal = dynamic_cast<GoalState*>(goal_.get());
    if (goal)
        states.push_back(goal->getState());

    GoalStates *goals = dynamic_cast<GoalStates*>(goal_.get());
    if (goals)
        for (unsigned int i = 0; i < goals->getStateCount(); ++i)
            states.push_back (goals->getState(i));
}

ompl::base::PathPtr ompl::base::ProblemDefinition::isStraightLinePathValid() const
{
    PathPtr path;
    if (control::SpaceInformationPtr sic = boost::dynamic_pointer_cast<control::SpaceInformation, SpaceInformation>(si_))
    {
        unsigned int startIndex;
        if (isTrivial(&startIndex, NULL))
        {
            control::PathControl *pc = new control::PathControl(sic);
            pc->append(startStates_[startIndex]);
            control::Control *null = sic->allocControl();
            sic->nullControl(null);
            pc->append(startStates_[startIndex], null, 0.0);
            sic->freeControl(null);
            path.reset(pc);
        }
        else
        {
            control::Control *nc = sic->allocControl();
            State *result1 = sic->allocState();
            State *result2 = sic->allocState();
            sic->nullControl(nc);

            for (unsigned int k = 0 ; k < startStates_.size() && !path ; ++k)
            {
                const State *start = startStates_[k];
                if (start && si_->isValid(start) && si_->satisfiesBounds(start))
                {
                    sic->copyState(result1, start);
                    for (unsigned int i = 0 ; i < sic->getMaxControlDuration() && !path ; ++i)
                        if (sic->propagateWhileValid(result1, nc, 1, result2))
                        {
                            if (goal_->isSatisfied(result2))
                            {
                                control::PathControl *pc = new control::PathControl(sic);
                                pc->append(start);
                                pc->append(result2, nc, (i + 1) * sic->getPropagationStepSize());
                                path.reset(pc);
                                break;
                            }
                            std::swap(result1, result2);
                        }
                }
            }
            sic->freeState(result1);
            sic->freeState(result2);
            sic->freeControl(nc);
        }
    }
    else
    {
        std::vector<const State*> states;
        GoalState *goal = dynamic_cast<GoalState*>(goal_.get());
        if (goal)
            if (si_->isValid(goal->getState()) && si_->satisfiesBounds(goal->getState()))
                states.push_back(goal->getState());
        GoalStates *goals = dynamic_cast<GoalStates*>(goal_.get());
        if (goals)
            for (unsigned int i = 0; i < goals->getStateCount(); ++i)
                if (si_->isValid(goals->getState(i)) && si_->satisfiesBounds(goals->getState(i)))
                    states.push_back(goals->getState(i));

        if (states.empty())
        {
            unsigned int startIndex;
            if (isTrivial(&startIndex))
            {
                geometric::PathGeometric *pg = new geometric::PathGeometric(si_, startStates_[startIndex], startStates_[startIndex]);
                path.reset(pg);
            }
        }
        else
        {
            for (unsigned int i = 0 ; i < startStates_.size() && !path ; ++i)
            {
                const State *start = startStates_[i];
                if (start && si_->isValid(start) && si_->satisfiesBounds(start))
                {
                    for (unsigned int j = 0 ; j < states.size() && !path ; ++j)
                        if (si_->checkMotion(start, states[j]))
                        {
                            geometric::PathGeometric *pg = new geometric::PathGeometric(si_, start, states[j]);
                            path.reset(pg);
                            break;
                        }
                }
            }
        }
    }

    return path;
}

bool ompl::base::ProblemDefinition::isTrivial(unsigned int *startIndex, double *distance) const
{
    if (!goal_)
    {
        OMPL_ERROR("Goal undefined");
        return false;
    }

    for (unsigned int i = 0 ; i < startStates_.size() ; ++i)
    {
        const State *start = startStates_[i];
        if (start && si_->isValid(start) && si_->satisfiesBounds(start))
        {
            double dist;
            if (goal_->isSatisfied(start, &dist))
            {
                if (startIndex)
                    *startIndex = i;
                if (distance)
                    *distance = dist;
                return true;
            }
        }
        else
        {
            OMPL_ERROR("Initial state is in collision!");
        }
    }

    return false;
}

bool ompl::base::ProblemDefinition::hasSolution() const
{
    return solutions_->getSolutionCount() > 0;
}

std::size_t ompl::base::ProblemDefinition::getSolutionCount() const
{
    return solutions_->getSolutionCount();
}

ompl::base::PathPtr ompl::base::ProblemDefinition::getSolutionPath() const
{
    return solutions_->getTopSolution();
}

const std::string& ompl::base::ProblemDefinition::getSolutionPlannerName(void) const
{
    return solutions_->getTopSolutionPlannerName();
}

void ompl::base::ProblemDefinition::addSolutionPath(const PathPtr &path, bool approximate, double difference, const std::string& plannerName) const
{
    if (approximate)
        OMPL_INFORM("Adding approximate solution");
    solutions_->add(PlannerSolution(path, approximate, difference, plannerName));
}

void ompl::base::ProblemDefinition::addSolutionPath(const PlannerSolution &sol) const
{
    if (sol.approximate_)
        OMPL_INFORM("Adding approximate solution");
    solutions_->add(sol);
}

bool ompl::base::ProblemDefinition::hasApproximateSolution() const
{
    return solutions_->isApproximate();
}

bool ompl::base::ProblemDefinition::hasOptimizedSolution() const
{
    return solutions_->isOptimized();
}

double ompl::base::ProblemDefinition::getSolutionDifference() const
{
    return solutions_->getDifference();
}

std::vector<ompl::base::PlannerSolution> ompl::base::ProblemDefinition::getSolutions() const
{
    return solutions_->getSolutions();
}

void ompl::base::ProblemDefinition::clearSolutionPaths() const
{
    solutions_->clear();
}

void ompl::base::ProblemDefinition::print(std::ostream &out) const
{
    out << "Start states:" << std::endl;
    for (unsigned int i = 0 ; i < startStates_.size() ; ++i)
        si_->printState(startStates_[i], out);
    if (goal_)
        goal_->print(out);
    else
        out << "Goal = NULL" << std::endl;
    if (optimizationObjective_)
        out << "Average state cost: " << optimizationObjective_->averageStateCost(magic::TEST_STATE_COUNT) << std::endl;
    out << "There are " << solutions_->getSolutionCount() << " solutions" << std::endl;
}

bool ompl::base::ProblemDefinition::hasSolutionNonExistenceProof() const
{
    return nonExistenceProof_.get();
}

void ompl::base::ProblemDefinition::clearSolutionNonExistenceProof()
{
    nonExistenceProof_.reset();
}

const ompl::base::SolutionNonExistenceProofPtr& ompl::base::ProblemDefinition::getSolutionNonExistenceProof() const
{
    return nonExistenceProof_;
}

void ompl::base::ProblemDefinition::setSolutionNonExistenceProof(const ompl::base::SolutionNonExistenceProofPtr& nonExistenceProof)
{
    nonExistenceProof_ = nonExistenceProof;
}
<commit_msg>Changed to non-reference return string<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright (c) 2010, Rice University
*  All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   * Neither the name of the Rice University nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
*  POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/

/* Author: Ioan Sucan */

#include "ompl/base/ProblemDefinition.h"
#include "ompl/base/goals/GoalState.h"
#include "ompl/base/goals/GoalStates.h"
#include "ompl/base/OptimizationObjective.h"
#include "ompl/control/SpaceInformation.h"
#include "ompl/control/PathControl.h"
#include "ompl/tools/config/MagicConstants.h"
#include <sstream>
#include <algorithm>

#include <boost/thread/mutex.hpp>

/// @cond IGNORE
namespace ompl
{
    namespace base
    {

        class ProblemDefinition::PlannerSolutionSet
        {
        public:

            PlannerSolutionSet()
            {
            }

            void add(const PlannerSolution &s)
            {
                boost::mutex::scoped_lock slock(lock_);
                int index = solutions_.size();
                solutions_.push_back(s);
                solutions_.back().index_ = index;
                std::sort(solutions_.begin(), solutions_.end());
            }

            void clear()
            {
                boost::mutex::scoped_lock slock(lock_);
                solutions_.clear();
            }

            std::vector<PlannerSolution> getSolutions()
            {
                boost::mutex::scoped_lock slock(lock_);
                std::vector<PlannerSolution> copy = solutions_;
                return copy;
            }

            bool isApproximate()
            {
                boost::mutex::scoped_lock slock(lock_);
                bool result = false;
                if (!solutions_.empty())
                    result = solutions_[0].approximate_;
                return result;
            }

            bool isOptimized()
            {
                boost::mutex::scoped_lock slock(lock_);
                bool result = false;
                if (!solutions_.empty())
                    result = solutions_[0].optimized_;
                return result;
            }

            double getDifference()
            {
                boost::mutex::scoped_lock slock(lock_);
                double diff = -1.0;
                if (!solutions_.empty())
                    diff = solutions_[0].difference_;
                return diff;
            }

            PathPtr getTopSolution()
            {
                boost::mutex::scoped_lock slock(lock_);
                PathPtr copy;
                if (!solutions_.empty())
                    copy = solutions_[0].path_;
                return copy;
            }

            const std::string getTopSolutionPlannerName(void)
            {
                boost::mutex::scoped_lock slock(lock_);
                if (!solutions_.empty())
                    return solutions_[0].plannerName_;
                else
                    return std::string("");
            }

            std::size_t getSolutionCount()
            {
                boost::mutex::scoped_lock slock(lock_);
                std::size_t result = solutions_.size();
                return result;
            }

        private:

            std::vector<PlannerSolution> solutions_;
            boost::mutex                 lock_;
        };
    }
}
/// @endcond

ompl::base::ProblemDefinition::ProblemDefinition(const SpaceInformationPtr &si) : si_(si), solutions_(new PlannerSolutionSet())
{
}

void ompl::base::ProblemDefinition::setStartAndGoalStates(const State *start, const State *goal, const double threshold)
{
    clearStartStates();
    addStartState(start);
    setGoalState(goal, threshold);
}

void ompl::base::ProblemDefinition::setGoalState(const State *goal, const double threshold)
{
    clearGoal();
    GoalState *gs = new GoalState(si_);
    gs->setState(goal);
    gs->setThreshold(threshold);
    setGoal(GoalPtr(gs));
}

bool ompl::base::ProblemDefinition::hasStartState(const State *state, unsigned int *startIndex)
{
    for (unsigned int i = 0 ; i < startStates_.size() ; ++i)
        if (si_->equalStates(state, startStates_[i]))
        {
            if (startIndex)
                *startIndex = i;
            return true;
        }
    return false;
}

bool ompl::base::ProblemDefinition::fixInvalidInputState(State *state, double dist, bool start, unsigned int attempts)
{
    bool result = false;

    bool b = si_->satisfiesBounds(state);
    bool v = false;
    if (b)
    {
        v = si_->isValid(state);
        if (!v)
            OMPL_DEBUG("%s state is not valid", start ? "Start" : "Goal");
    }
    else
        OMPL_DEBUG("%s state is not within space bounds", start ? "Start" : "Goal");

    if (!b || !v)
    {
        std::stringstream ss;
        si_->printState(state, ss);
        ss << " within distance " << dist;
        OMPL_DEBUG("Attempting to fix %s state %s", start ? "start" : "goal", ss.str().c_str());

        State *temp = si_->allocState();
        if (si_->searchValidNearby(temp, state, dist, attempts))
        {
            si_->copyState(state, temp);
            result = true;
        }
        else
            OMPL_WARN("Unable to fix %s state", start ? "start" : "goal");
        si_->freeState(temp);
    }

    return result;
}

bool ompl::base::ProblemDefinition::fixInvalidInputStates(double distStart, double distGoal, unsigned int attempts)
{
    bool result = true;

    // fix start states
    for (unsigned int i = 0 ; i < startStates_.size() ; ++i)
        if (!fixInvalidInputState(startStates_[i], distStart, true, attempts))
            result = false;

    // fix goal state
    GoalState *goal = dynamic_cast<GoalState*>(goal_.get());
    if (goal)
    {
        if (!fixInvalidInputState(const_cast<State*>(goal->getState()), distGoal, false, attempts))
            result = false;
    }

    // fix goal state
    GoalStates *goals = dynamic_cast<GoalStates*>(goal_.get());
    if (goals)
    {
        for (unsigned int i = 0; i < goals->getStateCount(); ++i)
            if (!fixInvalidInputState(const_cast<State*>(goals->getState(i)), distGoal, false, attempts))
                result = false;
    }

    return result;
}

void ompl::base::ProblemDefinition::getInputStates(std::vector<const State*> &states) const
{
    states.clear();
    for (unsigned int i = 0 ; i < startStates_.size() ; ++i)
        states.push_back(startStates_[i]);

    GoalState *goal = dynamic_cast<GoalState*>(goal_.get());
    if (goal)
        states.push_back(goal->getState());

    GoalStates *goals = dynamic_cast<GoalStates*>(goal_.get());
    if (goals)
        for (unsigned int i = 0; i < goals->getStateCount(); ++i)
            states.push_back (goals->getState(i));
}

ompl::base::PathPtr ompl::base::ProblemDefinition::isStraightLinePathValid() const
{
    PathPtr path;
    if (control::SpaceInformationPtr sic = boost::dynamic_pointer_cast<control::SpaceInformation, SpaceInformation>(si_))
    {
        unsigned int startIndex;
        if (isTrivial(&startIndex, NULL))
        {
            control::PathControl *pc = new control::PathControl(sic);
            pc->append(startStates_[startIndex]);
            control::Control *null = sic->allocControl();
            sic->nullControl(null);
            pc->append(startStates_[startIndex], null, 0.0);
            sic->freeControl(null);
            path.reset(pc);
        }
        else
        {
            control::Control *nc = sic->allocControl();
            State *result1 = sic->allocState();
            State *result2 = sic->allocState();
            sic->nullControl(nc);

            for (unsigned int k = 0 ; k < startStates_.size() && !path ; ++k)
            {
                const State *start = startStates_[k];
                if (start && si_->isValid(start) && si_->satisfiesBounds(start))
                {
                    sic->copyState(result1, start);
                    for (unsigned int i = 0 ; i < sic->getMaxControlDuration() && !path ; ++i)
                        if (sic->propagateWhileValid(result1, nc, 1, result2))
                        {
                            if (goal_->isSatisfied(result2))
                            {
                                control::PathControl *pc = new control::PathControl(sic);
                                pc->append(start);
                                pc->append(result2, nc, (i + 1) * sic->getPropagationStepSize());
                                path.reset(pc);
                                break;
                            }
                            std::swap(result1, result2);
                        }
                }
            }
            sic->freeState(result1);
            sic->freeState(result2);
            sic->freeControl(nc);
        }
    }
    else
    {
        std::vector<const State*> states;
        GoalState *goal = dynamic_cast<GoalState*>(goal_.get());
        if (goal)
            if (si_->isValid(goal->getState()) && si_->satisfiesBounds(goal->getState()))
                states.push_back(goal->getState());
        GoalStates *goals = dynamic_cast<GoalStates*>(goal_.get());
        if (goals)
            for (unsigned int i = 0; i < goals->getStateCount(); ++i)
                if (si_->isValid(goals->getState(i)) && si_->satisfiesBounds(goals->getState(i)))
                    states.push_back(goals->getState(i));

        if (states.empty())
        {
            unsigned int startIndex;
            if (isTrivial(&startIndex))
            {
                geometric::PathGeometric *pg = new geometric::PathGeometric(si_, startStates_[startIndex], startStates_[startIndex]);
                path.reset(pg);
            }
        }
        else
        {
            for (unsigned int i = 0 ; i < startStates_.size() && !path ; ++i)
            {
                const State *start = startStates_[i];
                if (start && si_->isValid(start) && si_->satisfiesBounds(start))
                {
                    for (unsigned int j = 0 ; j < states.size() && !path ; ++j)
                        if (si_->checkMotion(start, states[j]))
                        {
                            geometric::PathGeometric *pg = new geometric::PathGeometric(si_, start, states[j]);
                            path.reset(pg);
                            break;
                        }
                }
            }
        }
    }

    return path;
}

bool ompl::base::ProblemDefinition::isTrivial(unsigned int *startIndex, double *distance) const
{
    if (!goal_)
    {
        OMPL_ERROR("Goal undefined");
        return false;
    }

    for (unsigned int i = 0 ; i < startStates_.size() ; ++i)
    {
        const State *start = startStates_[i];
        if (start && si_->isValid(start) && si_->satisfiesBounds(start))
        {
            double dist;
            if (goal_->isSatisfied(start, &dist))
            {
                if (startIndex)
                    *startIndex = i;
                if (distance)
                    *distance = dist;
                return true;
            }
        }
        else
        {
            OMPL_ERROR("Initial state is in collision!");
        }
    }

    return false;
}

bool ompl::base::ProblemDefinition::hasSolution() const
{
    return solutions_->getSolutionCount() > 0;
}

std::size_t ompl::base::ProblemDefinition::getSolutionCount() const
{
    return solutions_->getSolutionCount();
}

ompl::base::PathPtr ompl::base::ProblemDefinition::getSolutionPath() const
{
    return solutions_->getTopSolution();
}

const std::string& ompl::base::ProblemDefinition::getSolutionPlannerName(void) const
{
    return solutions_->getTopSolutionPlannerName();
}

void ompl::base::ProblemDefinition::addSolutionPath(const PathPtr &path, bool approximate, double difference, const std::string& plannerName) const
{
    if (approximate)
        OMPL_INFORM("Adding approximate solution");
    solutions_->add(PlannerSolution(path, approximate, difference, plannerName));
}

void ompl::base::ProblemDefinition::addSolutionPath(const PlannerSolution &sol) const
{
    if (sol.approximate_)
        OMPL_INFORM("Adding approximate solution");
    solutions_->add(sol);
}

bool ompl::base::ProblemDefinition::hasApproximateSolution() const
{
    return solutions_->isApproximate();
}

bool ompl::base::ProblemDefinition::hasOptimizedSolution() const
{
    return solutions_->isOptimized();
}

double ompl::base::ProblemDefinition::getSolutionDifference() const
{
    return solutions_->getDifference();
}

std::vector<ompl::base::PlannerSolution> ompl::base::ProblemDefinition::getSolutions() const
{
    return solutions_->getSolutions();
}

void ompl::base::ProblemDefinition::clearSolutionPaths() const
{
    solutions_->clear();
}

void ompl::base::ProblemDefinition::print(std::ostream &out) const
{
    out << "Start states:" << std::endl;
    for (unsigned int i = 0 ; i < startStates_.size() ; ++i)
        si_->printState(startStates_[i], out);
    if (goal_)
        goal_->print(out);
    else
        out << "Goal = NULL" << std::endl;
    if (optimizationObjective_)
        out << "Average state cost: " << optimizationObjective_->averageStateCost(magic::TEST_STATE_COUNT) << std::endl;
    out << "There are " << solutions_->getSolutionCount() << " solutions" << std::endl;
}

bool ompl::base::ProblemDefinition::hasSolutionNonExistenceProof() const
{
    return nonExistenceProof_.get();
}

void ompl::base::ProblemDefinition::clearSolutionNonExistenceProof()
{
    nonExistenceProof_.reset();
}

const ompl::base::SolutionNonExistenceProofPtr& ompl::base::ProblemDefinition::getSolutionNonExistenceProof() const
{
    return nonExistenceProof_;
}

void ompl::base::ProblemDefinition::setSolutionNonExistenceProof(const ompl::base::SolutionNonExistenceProofPtr& nonExistenceProof)
{
    nonExistenceProof_ = nonExistenceProof;
}
<|endoftext|>