<commit_before>#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include "StateSpace3.h"
#include "PriorityQueue.h"
#include "State3.h"
#include "environment.h"

template<typename T> std::string to_string(T x) {
	return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}

//function to calculate a temperature for the select action function as a function of time
double temperature(unsigned long t);

//function to select next action
float selectAction(PriorityQueue<float, double>& a_queue, unsigned long int iterations);

//function to update a q value
void updateQ(StateSpace & space, float  action, State & new_state, State & old_state, double alpha, double gamma);

int main()
{
	//learning factor
	const double alpha = 0.5;
	//discount factor
	const double gamma = 0.5;
	const double deltatime = 0.1;
	const double mass = 0.5;
	const double length = 0.08;

	const int angle_bins = 100;
	const int velocity_bins = 50;
	const int torque_bins = 9;
	const double maxangle = 4;
	const double maxvelocity = 4;
	const double maxtorque = 4;

	/*for (int i = 0; i < torque_bins; ++i) {
		const int t_i = -maxtorque + i;
	}*/

	environment* env = new environment(0, 0, 0, maxtorque, 0, deltatime, mass, length, gamma);

	//seed rng
	std::srand(static_cast<unsigned int>(std::time(NULL)));

	//create pointers to the possible actions as well as a pointer to hold the chosen action
	float chosen_action = 1.0f;	// THE F MUST NOT BE DELETED UNDER ANY CIRCUMSTANCES
	float actions[torque_bins];
	for (int i = 0; i < (maxtorque*2)+1 ; ++i) {
		actions[i] = static_cast<float>(-maxtorque+i);
	}

	//create a priority queue to copy to all the state space priority queues
	PriorityQueue<float, double> initiator_queue(MAX);
	for (int i = 0; i < torque_bins; ++i) {
		initiator_queue.enqueueWithPriority(actions[i], 0);
	}

	//create the state space
	StateSpace space(initiator_queue, angle_bins, velocity_bins, torque_bins, maxangle, maxvelocity, maxtorque);

	//state objects
	State current_state(0, 0, 0);
	State old_state(0, 0, 0);

	std::ofstream file("output.txt");
	file.precision(16);

	file << "Trialno" << "	" << "Time" << "		" << "Theta" << "	" << "Thetadot" << "		" << "Torque" << std::endl;

	double trialno = 1;
	unsigned long i=0UL;
	while (true)
	{
		current_state.theta = env->getTheta();
		current_state.theta_dot = env->getThetadot();
		current_state.torque = env->getTorque();
		std::cout << "State Read" << std::endl;

		updateQ(space, chosen_action, old_state, current_state, alpha, gamma);
		std::cout << "Q Updated" << std::endl;

		if (current_state.theta>2 * 3.1415 && current_state.theta_dot>2 * 3.1415 && env->getTime() >= 10) {
			env->resetPendulum();
			std::domain_error("unsuccessful trial");
			trialno++;
			i = 0;
		}

		old_state = current_state;

		chosen_action = selectAction(space[current_state],i);
		std::cout << "Action Selected" << std::endl;
		env->setTorque(chosen_action);

		env->propagate();
		std::cout << "Environment Propogated\n" << std::endl;

		file << trialno << "	  " << env->getTime() << "	  " << current_state.theta << "	  " << current_state.theta_dot << "	   " << current_state.torque << std::endl;
		++i;
	}

	file.close();
	delete env;
	return 1;
}

double temperature(unsigned long t) {
	return 100.0*std::exp((-8.0*t*t) / (2600.0*2600.0)) + 0.1;//0.1 is an offset
}

float selectAction(PriorityQueue<float, double>& a_queue, unsigned long iterations) {

	typedef std::vector<std::pair<float, double> > VecPair ;

	//turn priority queue into a vector of pairs
	VecPair vec = a_queue.saveOrderedQueueAsVector();

    //sum for partition function
	double sum = 0.0;

	// calculate partition function by iterating over action-values
	for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
		sum += std::exp((iter->second) / temperature(iterations));
	}

	// compute Boltzmann factors for action-values and enqueue to vec
	for (VecPair::iterator iter = vec.begin(); iter < vec.end(); ++iter) {
		iter->second = std::exp(iter->second / temperature(iterations)) / sum;
	}

	// calculate cumulative probability distribution
	for (VecPair::iterator iter = vec.begin()++, end = vec.end(); iter < end; ++iter) {
        //second member of pair becomes addition of its current value
        //and that of the index before it
		iter->second += (iter-1)->second;
	}

	//generate RN between 0 and 1
	double rand_num = static_cast<double>(rand()) / RAND_MAX;

	// choose action based on random number relation to priorities within action queue
	for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
		if (rand_num < iter->second)
			return iter->first;
	}

	return -1; //note that this line should never be reached
}

void updateQ(StateSpace & space, float action, State & new_state, State & old_state, double alpha, double gamma)
{
	//std::cout << action << std::endl;
	//std::cout << space[old_state].toString() << std::endl << "-----------";

	//oldQ value reference
	double oldQ = space[old_state].search(action).second;

	//reward given to current state
	double R = new_state.getReward();
	std::cout << "Reward: " << R << std::endl;
	//optimal Q value for new state i.e. first element
	double maxQ = space[new_state].peekFront().second;

	//new Q value determined by Q learning algorithm
	double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);
	//std::cout << "New Q-Value: " << newQ << std::endl;
	space[old_state].changePriority(action, newQ);
}

<commit_msg>Fixed iterator access in selectAction<commit_after>#define _USE_MATH_DEFINES
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include "StateSpace3.h"
#include "PriorityQueue.h"
#include "State3.h"
#include "environment.h"

template<typename T> std::string to_string(T x) {
	return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}

//function to calculate a temperature for the select action function as a function of time
double temperature(unsigned long t);

//function to select next action
float selectAction(PriorityQueue<float, double>& a_queue, unsigned long int iterations);

//function to update a q value
void updateQ(StateSpace & space, float  action, State & new_state, State & old_state, double alpha, double gamma);

int main() {
	//learning factor
	const double alpha = 0.5;
	//discount factor
	const double gamma = 0.5;
	const double deltatime = 0.1;
	const double mass = 0.5;
	const double length = 0.08;

	const int angle_bins = 100;
	const int velocity_bins = 50;
	const int torque_bins = 9;
	const double maxangle = 4;
	const double maxvelocity = 4;
	const double maxtorque = 4;

	/*for (int i = 0; i < torque_bins; ++i) {
	const int t_i = -maxtorque + i;
	}*/

	environment* env = new environment(0, 0, 0, maxtorque, 0, deltatime, mass, length, gamma);

	//seed rng
	std::srand(static_cast<unsigned int>(std::time(NULL)));

	//create pointers to the possible actions as well as a pointer to hold the chosen action
	float chosen_action = 1.0f;	// THE F MUST NOT BE DELETED UNDER ANY CIRCUMSTANCES
	float actions[torque_bins];
	for (int i = 0; i < (maxtorque * 2) + 1; ++i) {
		actions[i] = static_cast<float>(-maxtorque + i);
	}

	//create a priority queue to copy to all the state space priority queues
	PriorityQueue<float, double> initiator_queue(MAX);
	for (int i = 0; i < torque_bins; ++i) {
		initiator_queue.enqueueWithPriority(actions[i], 0);
	}

	//create the state space
	StateSpace space(initiator_queue, angle_bins, velocity_bins, torque_bins, maxangle, maxvelocity, maxtorque);

	//state objects
	State current_state(0, 0, 0);
	State old_state(0, 0, 0);

	std::ofstream file("output.txt");
	file.precision(16);

	file << "Trialno" << "	" << "Time" << "		" << "Theta" << "	" << "Thetadot" << "		" << "Torque" << std::endl;

	double trialno = 1;
	unsigned long i = 0UL;
	while (true) {
		current_state.theta = env->getTheta();
		current_state.theta_dot = env->getThetadot();
		current_state.torque = env->getTorque();
		std::cout << "State Read" << std::endl;

		updateQ(space, chosen_action, old_state, current_state, alpha, gamma);
		std::cout << "Q Updated" << std::endl;

		if (current_state.theta > 2*M_PI && current_state.theta_dot> 2*M_PI && env->getTime() >= 10) {
			env->resetPendulum();
			std::domain_error("unsuccessful trial");
			trialno++;
			i = 0;
		}

		old_state = current_state;

		chosen_action = selectAction(space[current_state], i);
		std::cout << "Action Selected" << std::endl;
		env->setTorque(chosen_action);

		env->propagate();
		std::cout << "Environment Propogated\n" << std::endl;

		file << trialno << "	  " << env->getTime() << "	  " << current_state.theta << "	  " << current_state.theta_dot << "	   " << current_state.torque << std::endl;
		++i;
	}

	file.close();
	delete env;
	return 1;
}

double temperature(unsigned long t) {
	return 100.0*std::exp((-8.0*t*t) / (2600.0*2600.0)) + 0.1;//0.1 is an offset
}

float selectAction(PriorityQueue<float, double>& a_queue, unsigned long iterations) {

	typedef std::vector<std::pair<float, double> > VecPair;

	//turn priority queue into a vector of pairs
	VecPair vec = a_queue.saveOrderedQueueAsVector();
	std::cout << "\tqueue saved as vector" << std::endl;
	//sum for partition function
	double sum = 0.0;

	// calculate partition function by iterating over action-values
	for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
		sum += std::exp((iter->second) / temperature(iterations));
	}
	std::cout << "\tpartition function computed" << std::endl;
	// compute Boltzmann factors for action-values and enqueue to vec
	for (VecPair::iterator iter = vec.begin(); iter < vec.end(); ++iter) {
		iter->second = std::exp(iter->second / temperature(iterations)) / sum;
	}
	std::cout << "\tBoltzmann factors calculated" << std::endl;
	// calculate cumulative probability distribution
	for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
		//second member of pair becomes addition of its current value
		//and that of the index before it
		if (iter == vec.begin()) {}
		else {
			iter->second += (iter - 1)->second;
		}
	}
	std::cout << "\tCumulative PD computed" << std::endl;
	//generate RN between 0 and 1
	double rand_num = static_cast<double>(rand()) / RAND_MAX;

	// choose action based on random number relation to priorities within action queue
	for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
		if (rand_num < iter->second)
			return iter->first;
	}
	std::cout << "\tAction chosen" << std::endl;
	return -1; //note that this line should never be reached
}

void updateQ(StateSpace & space, float action, State & new_state, State & old_state, double alpha, double gamma) {
	//std::cout << action << std::endl;
	//std::cout << space[old_state].toString() << std::endl << "-----------";

	//oldQ value reference
	double oldQ = space[old_state].search(action).second;

	//reward given to current state
	double R = new_state.getReward();
	std::cout << "Reward: " << R << std::endl;
	//optimal Q value for new state i.e. first element
	double maxQ = space[new_state].peekFront().second;

	//new Q value determined by Q learning algorithm
	double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);
	//std::cout << "New Q-Value: " << newQ << std::endl;
	space[old_state].changePriority(action, newQ);
}<|endoftext|>


<commit_before>// This file is part of Playslave-C++.
// Playslave-C++ is licenced under the MIT license: see LICENSE.txt.

/**
 * @file player/player.cpp
 * Main implementation file for the Player class.
 * @see player/player.hpp
 * @see player/player_position.cpp
 * @see player/player_state.cpp
 */

#include <stdexcept>
#include <sstream>
#include <string>
#include <cassert>

#include "player.hpp"
#include "../audio/audio.hpp"
#include "../audio/audio_system.hpp"
#include "../errors.hpp"
#include "../io/io_responder.hpp"
#include "../messages.h"

/// List of states in which some audio is loaded.
const Player::StateList Player::AUDIO_LOADED_STATES = {State::PLAYING,
                                                       State::STOPPED};

Player::Player(const AudioSystem &audio_system, const Player::TP &time_parser)
    : audio_system(audio_system), time_parser(time_parser)
{
	this->current_state = State::EJECTED;
	this->audio = nullptr;
}

void Player::Update()
{
	if (this->current_state == State::PLAYING) {
		if (this->audio->IsStopped()) {
			Eject();
		} else {
			UpdatePosition();
		}
	}
	if (CurrentStateIn(AUDIO_LOADED_STATES)) {
		this->audio->Update();
	}
}

void Player::OpenFile(const std::string &path)
{
	this->audio = decltype(this->audio)(this->audio_system.Load(path));
}

void Player::WelcomeClient(Responder &client)
{
        client.Respond(Response::OHAI, MSG_OHAI);

        std::ostringstream os;
        os << "None " << StateString(this->current_state);
        client.Respond(Response::STAT, os.str());

        this->position.Emit(client);
}

//
// Commands
//

bool Player::Eject()
{
	return IfCurrentStateIn(AUDIO_LOADED_STATES, [this] {
		this->audio = nullptr;
		SetState(State::EJECTED);
		return true;
	});
}

bool Player::Load(const std::string &path)
{
	bool valid = !path.empty();
	if (valid) {
		try
		{
			OpenFile(path);
			ResetPosition();
			Debug("Loaded ", path);
			SetState(State::STOPPED);
		}
		catch (Error &error)
		{
			// Ensure a load failure doesn't leave a corrupted track
			// loaded.
			Eject();
			throw error;
		}
	}
	return valid;
}

bool Player::Play()
{
	return IfCurrentStateIn({State::STOPPED}, [this] {
		assert(this->audio != nullptr);
		this->audio->Start();
		SetState(State::PLAYING);
		return true;
	});
}

bool Player::Quit()
{
	Eject();
	SetState(State::QUITTING);

	return true; // Always a valid command.
}

bool Player::Seek(const std::string &time_str)
{
	return IfCurrentStateIn(AUDIO_LOADED_STATES, [this, &time_str] {
		bool success = true;
		std::chrono::microseconds position(0);

		try
		{
			position = this->time_parser.Parse(time_str);
		}
		catch (std::out_of_range)
		{
			success = false;
		}

		if (success) {
			this->audio->SeekToPosition(position);
			this->ResetPosition();
			this->UpdatePosition();
		}

		return success;
	});
}

bool Player::Stop()
{
	return IfCurrentStateIn({State::PLAYING}, [this] {
		this->audio->Stop();
		SetState(State::STOPPED);
		return true;
	});
}
<commit_msg>Don't bail on file errors.<commit_after>// This file is part of Playslave-C++.
// Playslave-C++ is licenced under the MIT license: see LICENSE.txt.

/**
 * @file player/player.cpp
 * Main implementation file for the Player class.
 * @see player/player.hpp
 * @see player/player_position.cpp
 * @see player/player_state.cpp
 */

#include <stdexcept>
#include <sstream>
#include <string>
#include <cassert>

#include "player.hpp"
#include "../audio/audio.hpp"
#include "../audio/audio_system.hpp"
#include "../errors.hpp"
#include "../io/io_responder.hpp"
#include "../messages.h"

/// List of states in which some audio is loaded.
const Player::StateList Player::AUDIO_LOADED_STATES = {State::PLAYING,
                                                       State::STOPPED};

Player::Player(const AudioSystem &audio_system, const Player::TP &time_parser)
    : audio_system(audio_system), time_parser(time_parser)
{
	this->current_state = State::EJECTED;
	this->audio = nullptr;
}

void Player::Update()
{
	if (this->current_state == State::PLAYING) {
		if (this->audio->IsStopped()) {
			Eject();
		} else {
			UpdatePosition();
		}
	}
	if (CurrentStateIn(AUDIO_LOADED_STATES)) {
		this->audio->Update();
	}
}

void Player::OpenFile(const std::string &path)
{
	this->audio = decltype(this->audio)(this->audio_system.Load(path));
}

void Player::WelcomeClient(Responder &client)
{
        client.Respond(Response::OHAI, MSG_OHAI);

        std::ostringstream os;
        os << "None " << StateString(this->current_state);
        client.Respond(Response::STAT, os.str());

        this->position.Emit(client);
}

//
// Commands
//

bool Player::Eject()
{
	return IfCurrentStateIn(AUDIO_LOADED_STATES, [this] {
		this->audio = nullptr;
		SetState(State::EJECTED);
		return true;
	});
}

bool Player::Load(const std::string &path)
{
	bool valid = !path.empty();
	if (valid) {
		try
		{
			OpenFile(path);
			ResetPosition();
			Debug("Loaded ", path);
			SetState(State::STOPPED);
		}
		catch (FileError &)
		{
			// File errors aren't fatal, so catch them here.
			Eject();
			valid = false;
		}
		catch (Error &error)
		{
			// Ensure a load failure doesn't leave a corrupted track
			// loaded.
			Eject();
			throw error;
		}
	}
	return valid;
}

bool Player::Play()
{
	return IfCurrentStateIn({State::STOPPED}, [this] {
		assert(this->audio != nullptr);
		this->audio->Start();
		SetState(State::PLAYING);
		return true;
	});
}

bool Player::Quit()
{
	Eject();
	SetState(State::QUITTING);

	return true; // Always a valid command.
}

bool Player::Seek(const std::string &time_str)
{
	return IfCurrentStateIn(AUDIO_LOADED_STATES, [this, &time_str] {
		bool success = true;
		std::chrono::microseconds position(0);

		try
		{
			position = this->time_parser.Parse(time_str);
		}
		catch (std::out_of_range)
		{
			success = false;
		}

		if (success) {
			this->audio->SeekToPosition(position);
			this->ResetPosition();
			this->UpdatePosition();
		}

		return success;
	});
}

bool Player::Stop()
{
	return IfCurrentStateIn({State::PLAYING}, [this] {
		this->audio->Stop();
		SetState(State::STOPPED);
		return true;
	});
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qversitproperty.h"
#include "qversitproperty_p.h"
#include "qmobilityglobal.h"

#include <QStringList>
#include <QTextCodec>

QTM_BEGIN_NAMESPACE

/*!
  \class QVersitProperty
  \brief The QVersitProperty class stores the name, value, groups and parameters of a Versit property.
  \ingroup versit
  \inmodule QtVersit

  A vCard is represented in abstract form as a QVersitDocument that consists of a number of
  properties such as a name (N), a telephone number (TEL) and an email address (EMAIL), for
  instance.  Each of these properties is stored as an instance of a QVersitProperty in a
  QVersitDocument.

  A QVersitProperty consists of a list of groups, a name, a list of parameters (key/value pairs),
  and a value.

  The value of a QVersitProperty is stored as a QVariant and should always be one of four types:
  QString for textual values, QByteArray for binary data (eg. images), QStringList for structured
  textual data, or QVersitDocument for nested documents.  The \l QVersitReader will parse Versit
  properties and assign the correct type of object to the property value.  The \l QVersitWriter will
  serialize objects of these types correctly into the (text-based) Versit format.

  For example, a property might appear in a vCard as:
  \code
  ADR;TYPE=home,postal:;;123 Main Street;Any Town;CA;91921-1234
  \endcode
  This would be stored as a QVersitProperty with the name \tt{ADR} and two parameters (both named
  \tt{TYPE} and with values \tt{home} and \tt{postal} respectively.  The value of the
  QVersitProperty is a QStringList with six strings, and the valueType is CompoundType.

  QVersitProperty supports implicit sharing.  The property name and parameter names of a
  QVersitProperty are converted to upper-case when they are stored to a QVersitProperty.

  \sa QVersitDocument
 */

/*!
  \enum QVersitProperty::ValueType
  Describes the type of data held in the property's value.

  The vCard and iCalendar specifications allows a property value to hold a string, binary data, or a
  nested document.  String values can either be unstructured or structured.  Structured strings can
  be either of compound type or list type.  A compound value is one that is delimited by semicolons,
  allows empty components, and has a property-specific cardinality and ordering.  A list value is
  one that is delimited by commas, does not have empty components, and has no restrictions on
  cardinality or ordering.

  \value PlainType The property value holds an unstructured string and can be retrieved with
  QVersitProperty::value()
  \value CompoundType The property value holds a compound string and can be retrieved with
  QVersitProperty::value<QStringList>()
  \value ListType The property value holds a list of strings and can be retrieved with
  QVersitProperty::value<QStringList>()
  \value BinaryType The property value holds a binary value and can be retrieved with
  QVersitProperty::value<QByteArray>()
  \value VersitDocumentType The property value holds a nested Versit document and can be retrieved
  \value PreformattedType The property value holds a string that represents exactly the text for
  the property in the vCard file, bar line-wrapping.  That is, if the property were to be written
  to file it should be written as-is, with no backslash escaping.
 */

/*! Constructs a new empty property */
QVersitProperty::QVersitProperty() : d(new QVersitPropertyPrivate())
{
}

/*! Constructs a property that is a copy of \a other */
QVersitProperty::QVersitProperty(const QVersitProperty& other) : d(other.d)
{
}

/*! Frees the memory used by the property */
QVersitProperty::~QVersitProperty()
{
}

/*! Assigns this property to \a other */
QVersitProperty& QVersitProperty::operator=(const QVersitProperty& other)
{
    if (this != &other)
        d = other.d;
    return *this;
}

/*! Returns true if this is equal to \a other; false otherwise. */
bool QVersitProperty::operator==(const QVersitProperty& other) const
{
    bool equal = d->mGroups == other.d->mGroups &&
            d->mName == other.d->mName &&
            d->mParameters == other.d->mParameters &&
            d->mValueType == other.d->mValueType;
    if (!equal)
        return false;

    // QVariant doesn't support == on QVersitDocuments - do it manually
    if (d->mValue.userType() == qMetaTypeId<QVersitDocument>())
        return  other.d->mValue.userType() == qMetaTypeId<QVersitDocument>()
            && d->mValue.value<QVersitDocument>() == other.d->mValue.value<QVersitDocument>();
    else
        return d->mValue == other.d->mValue;
}

/*! Returns true if this is not equal to \a other; false otherwise. */
bool QVersitProperty::operator!=(const QVersitProperty& other) const
{
    return !(*this == other);
}

/*! Returns the hash value for \a key. */
uint qHash(const QVersitProperty &key)
{
    uint hash = QT_PREPEND_NAMESPACE(qHash)(key.name()) + QT_PREPEND_NAMESPACE(qHash)(key.value());
    foreach (const QString& group, key.groups()) {
        hash += QT_PREPEND_NAMESPACE(qHash)(group);
    }
    QHash<QString,QString>::const_iterator it = key.parameters().constBegin();
    QHash<QString,QString>::const_iterator end = key.parameters().constEnd();
    while (it != end) {
        hash += QT_PREPEND_NAMESPACE(qHash)(it.key()) + QT_PREPEND_NAMESPACE(qHash)(it.value());
        ++it;
    }
    return hash;
}

#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug dbg, const QVersitProperty& property)
{
    QStringList groups = property.groups();
    QString name = property.name();
    QMultiHash<QString,QString> parameters = property.parameters();
    dbg.nospace() << "QVersitProperty(";
    foreach (const QString& group, groups) {
        dbg.nospace() << group << '.';
    }
    dbg.nospace() << name;
    QHash<QString,QString>::const_iterator it;
    for (it = parameters.constBegin(); it != parameters.constEnd(); ++it) {
        dbg.nospace() << ';' << it.key() << '=' << it.value();
    }
    if (property.valueType() == QVersitProperty::VersitDocumentType)
        dbg.nospace() << ':' << property.value<QVersitDocument>();
    else
        dbg.nospace() << ':' << property.variantValue();
    dbg.nospace() << ')';
    return dbg.maybeSpace();
}
#endif

/*!
 * Sets the groups in the property to the given list of \a groups.
 */
void QVersitProperty::setGroups(const QStringList& groups)
{
    d->mGroups.clear();
    foreach (const QString& group, groups) {
        d->mGroups.append(group);
    }
}

/*!
 * Gets the groups of the property.
 */
QStringList QVersitProperty::groups() const
{
    return d->mGroups;
}

/*!
 * Sets the \a name of the property.
 * The \a name is converted to upper-case.
 */
void QVersitProperty::setName(const QString& name)
{
    d->mName = name.toUpper();
}

/*!
 * Gets the name of the property in upper-case.
 */
QString QVersitProperty::name() const
{
    return d->mName;
}

/*!
 * Replaces all the parameters with \a parameters.
 * The parameters are converted to upper-case.
 */
void QVersitProperty::setParameters(const QMultiHash<QString,QString>& parameters)
{
    d->mParameters.clear();
    // Traverse parameters in the reverse order, because they are added to
    // d->mParameters using insert in QVersitProperty::addParameter
    QList<QString> keys = parameters.uniqueKeys();
    for (int i=keys.count()-1; i >= 0; i--) {
        QString key = keys.at(i);
        QList<QString> values = parameters.values(key);
        for (int j=values.count()-1; j >= 0; j--) {
            // Convert all the parameter names and values to upper case
            insertParameter(key,values.at(j));
        }
    }
}

/*!
 * Adds a new parameter with \a name and \a value.
 * Both the name and the value are converted to upper-case.
 */
void QVersitProperty::insertParameter(const QString& name, const QString& value)
{
    d->mParameters.insert(name.toUpper(), value);
}

/*!
 * Removes a parameter with \a name and \a value.
 *
 * \sa removeParameters()
 */
void QVersitProperty::removeParameter(const QString& name, const QString& value)
{
    d->mParameters.remove(name.toUpper(), value);
}

/*!
 * Removes all parameters with the given \a name.
 *
 * \sa removeParameter()
 */
void QVersitProperty::removeParameters(const QString& name)
{
    d->mParameters.remove(name.toUpper());
}

/*!
 * Return a copy of the contained list of parameters.
 * Note that actual the parameters cannot be modified using the copy.
 */
QMultiHash<QString,QString> QVersitProperty::parameters() const
{
    return d->mParameters;
}

/*!
 * Sets the property value to \a value.
 */
void QVersitProperty::setValue(const QVariant& value)
{
    d->mValue = value;
}

/*!
 * Returns the value of the property.
 */
QVariant QVersitProperty::variantValue() const
{
    return d->mValue;
}

/*!
 * \fn T QVersitProperty::value() const
 * \overload
 * Returns the value of the property as a \tt T.
 */

/*!
 * Returns the value of the property as a string if possible, otherwise return an empty string.
 * If the property is stored as a QByteArray, it is decoded using the charset specified in the
 * property's parameters.
 * \sa QVariant::toString()
 */
QString QVersitProperty::value() const
{
    if (d->mValue.type() == QVariant::ByteArray) {
        if (d->mParameters.contains(QLatin1String("CHARSET"))) {
            QTextCodec* codec = QTextCodec::codecForName(
                    d->mParameters.value(QLatin1String("CHARSET")).toAscii());
            if (codec != NULL) {
                return codec->toUnicode(d->mValue.toByteArray());
            }
        }
        return QString();
    } else {
        return d->mValue.toString();
    }
}

/*!
 * Sets the type of value held in the property to \a type.
 */
void QVersitProperty::setValueType(QVersitProperty::ValueType type)
{
    d->mValueType = type;
}

/*!
 * Returns the type of value held in the property.
 */
QVersitProperty::ValueType QVersitProperty::valueType() const
{
    return d->mValueType;
}

/*!
 * Returns true if the property is empty.
 */
bool QVersitProperty::isEmpty() const
{
    return d->mGroups.isEmpty()
            && d->mName.isEmpty()
            && d->mParameters.isEmpty()
            && !d->mValue.isValid();
}

/*!
 * Clears the contents of this property.
 */
void QVersitProperty::clear()
{
    d->mGroups.clear();
    d->mName.clear();
    d->mValue.clear();
    d->mParameters.clear();
    d->mValueType = QVersitProperty::PlainType;
}

QTM_END_NAMESPACE
<commit_msg>Remove documentation about uppercasing Versit parameter values.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qversitproperty.h"
#include "qversitproperty_p.h"
#include "qmobilityglobal.h"

#include <QStringList>
#include <QTextCodec>

QTM_BEGIN_NAMESPACE

/*!
  \class QVersitProperty
  \brief The QVersitProperty class stores the name, value, groups and parameters of a Versit property.
  \ingroup versit
  \inmodule QtVersit

  A vCard is represented in abstract form as a QVersitDocument that consists of a number of
  properties such as a name (N), a telephone number (TEL) and an email address (EMAIL), for
  instance.  Each of these properties is stored as an instance of a QVersitProperty in a
  QVersitDocument.

  A QVersitProperty consists of a list of groups, a name, a list of parameters (key/value pairs),
  and a value.

  The value of a QVersitProperty is stored as a QVariant and should always be one of four types:
  QString for textual values, QByteArray for binary data (eg. images), QStringList for structured
  textual data, or QVersitDocument for nested documents.  The \l QVersitReader will parse Versit
  properties and assign the correct type of object to the property value.  The \l QVersitWriter will
  serialize objects of these types correctly into the (text-based) Versit format.

  For example, a property might appear in a vCard as:
  \code
  ADR;TYPE=home,postal:;;123 Main Street;Any Town;CA;91921-1234
  \endcode
  This would be stored as a QVersitProperty with the name \tt{ADR} and two parameters (both named
  \tt{TYPE} and with values \tt{home} and \tt{postal} respectively.  The value of the
  QVersitProperty is a QStringList with six strings, and the valueType is CompoundType.

  QVersitProperty supports implicit sharing.  The property name and parameter names of a
  QVersitProperty are converted to upper-case when they are stored to a QVersitProperty.

  \sa QVersitDocument
 */

/*!
  \enum QVersitProperty::ValueType
  Describes the type of data held in the property's value.

  The vCard and iCalendar specifications allows a property value to hold a string, binary data, or a
  nested document.  String values can either be unstructured or structured.  Structured strings can
  be either of compound type or list type.  A compound value is one that is delimited by semicolons,
  allows empty components, and has a property-specific cardinality and ordering.  A list value is
  one that is delimited by commas, does not have empty components, and has no restrictions on
  cardinality or ordering.

  \value PlainType The property value holds an unstructured string and can be retrieved with
  QVersitProperty::value()
  \value CompoundType The property value holds a compound string and can be retrieved with
  QVersitProperty::value<QStringList>()
  \value ListType The property value holds a list of strings and can be retrieved with
  QVersitProperty::value<QStringList>()
  \value BinaryType The property value holds a binary value and can be retrieved with
  QVersitProperty::value<QByteArray>()
  \value VersitDocumentType The property value holds a nested Versit document and can be retrieved
  \value PreformattedType The property value holds a string that represents exactly the text for
  the property in the vCard file, bar line-wrapping.  That is, if the property were to be written
  to file it should be written as-is, with no backslash escaping.
 */

/*! Constructs a new empty property */
QVersitProperty::QVersitProperty() : d(new QVersitPropertyPrivate())
{
}

/*! Constructs a property that is a copy of \a other */
QVersitProperty::QVersitProperty(const QVersitProperty& other) : d(other.d)
{
}

/*! Frees the memory used by the property */
QVersitProperty::~QVersitProperty()
{
}

/*! Assigns this property to \a other */
QVersitProperty& QVersitProperty::operator=(const QVersitProperty& other)
{
    if (this != &other)
        d = other.d;
    return *this;
}

/*! Returns true if this is equal to \a other; false otherwise. */
bool QVersitProperty::operator==(const QVersitProperty& other) const
{
    bool equal = d->mGroups == other.d->mGroups &&
            d->mName == other.d->mName &&
            d->mParameters == other.d->mParameters &&
            d->mValueType == other.d->mValueType;
    if (!equal)
        return false;

    // QVariant doesn't support == on QVersitDocuments - do it manually
    if (d->mValue.userType() == qMetaTypeId<QVersitDocument>())
        return  other.d->mValue.userType() == qMetaTypeId<QVersitDocument>()
            && d->mValue.value<QVersitDocument>() == other.d->mValue.value<QVersitDocument>();
    else
        return d->mValue == other.d->mValue;
}

/*! Returns true if this is not equal to \a other; false otherwise. */
bool QVersitProperty::operator!=(const QVersitProperty& other) const
{
    return !(*this == other);
}

/*! Returns the hash value for \a key. */
uint qHash(const QVersitProperty &key)
{
    uint hash = QT_PREPEND_NAMESPACE(qHash)(key.name()) + QT_PREPEND_NAMESPACE(qHash)(key.value());
    foreach (const QString& group, key.groups()) {
        hash += QT_PREPEND_NAMESPACE(qHash)(group);
    }
    QHash<QString,QString>::const_iterator it = key.parameters().constBegin();
    QHash<QString,QString>::const_iterator end = key.parameters().constEnd();
    while (it != end) {
        hash += QT_PREPEND_NAMESPACE(qHash)(it.key()) + QT_PREPEND_NAMESPACE(qHash)(it.value());
        ++it;
    }
    return hash;
}

#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug dbg, const QVersitProperty& property)
{
    QStringList groups = property.groups();
    QString name = property.name();
    QMultiHash<QString,QString> parameters = property.parameters();
    dbg.nospace() << "QVersitProperty(";
    foreach (const QString& group, groups) {
        dbg.nospace() << group << '.';
    }
    dbg.nospace() << name;
    QHash<QString,QString>::const_iterator it;
    for (it = parameters.constBegin(); it != parameters.constEnd(); ++it) {
        dbg.nospace() << ';' << it.key() << '=' << it.value();
    }
    if (property.valueType() == QVersitProperty::VersitDocumentType)
        dbg.nospace() << ':' << property.value<QVersitDocument>();
    else
        dbg.nospace() << ':' << property.variantValue();
    dbg.nospace() << ')';
    return dbg.maybeSpace();
}
#endif

/*!
 * Sets the groups in the property to the given list of \a groups.
 */
void QVersitProperty::setGroups(const QStringList& groups)
{
    d->mGroups.clear();
    foreach (const QString& group, groups) {
        d->mGroups.append(group);
    }
}

/*!
 * Gets the groups of the property.
 */
QStringList QVersitProperty::groups() const
{
    return d->mGroups;
}

/*!
 * Sets the \a name of the property.
 * The \a name is converted to upper-case.
 */
void QVersitProperty::setName(const QString& name)
{
    d->mName = name.toUpper();
}

/*!
 * Gets the name of the property in upper-case.
 */
QString QVersitProperty::name() const
{
    return d->mName;
}

/*!
 * Replaces all the parameters with \a parameters.
 * The names of the parameters are converted to upper-case.
 */
void QVersitProperty::setParameters(const QMultiHash<QString,QString>& parameters)
{
    d->mParameters.clear();
    // Traverse parameters in the reverse order, because they are added to
    // d->mParameters using insert in QVersitProperty::addParameter
    QList<QString> keys = parameters.uniqueKeys();
    for (int i=keys.count()-1; i >= 0; i--) {
        QString key = keys.at(i);
        QList<QString> values = parameters.values(key);
        for (int j=values.count()-1; j >= 0; j--) {
            // Convert all the parameter names and values to upper case
            insertParameter(key,values.at(j));
        }
    }
}

/*!
 * Adds a new parameter with \a name and \a value.
 * The parameter name is converted to upper-case.
 */
void QVersitProperty::insertParameter(const QString& name, const QString& value)
{
    d->mParameters.insert(name.toUpper(), value);
}

/*!
 * Removes a parameter with \a name and \a value.
 *
 * \sa removeParameters()
 */
void QVersitProperty::removeParameter(const QString& name, const QString& value)
{
    d->mParameters.remove(name.toUpper(), value);
}

/*!
 * Removes all parameters with the given \a name.
 *
 * \sa removeParameter()
 */
void QVersitProperty::removeParameters(const QString& name)
{
    d->mParameters.remove(name.toUpper());
}

/*!
 * Return a copy of the contained list of parameters.
 * Note that actual the parameters cannot be modified using the copy.
 */
QMultiHash<QString,QString> QVersitProperty::parameters() const
{
    return d->mParameters;
}

/*!
 * Sets the property value to \a value.
 */
void QVersitProperty::setValue(const QVariant& value)
{
    d->mValue = value;
}

/*!
 * Returns the value of the property.
 */
QVariant QVersitProperty::variantValue() const
{
    return d->mValue;
}

/*!
 * \fn T QVersitProperty::value() const
 * \overload
 * Returns the value of the property as a \tt T.
 */

/*!
 * Returns the value of the property as a string if possible, otherwise return an empty string.
 * If the property is stored as a QByteArray, it is decoded using the charset specified in the
 * property's parameters.
 * \sa QVariant::toString()
 */
QString QVersitProperty::value() const
{
    if (d->mValue.type() == QVariant::ByteArray) {
        if (d->mParameters.contains(QLatin1String("CHARSET"))) {
            QTextCodec* codec = QTextCodec::codecForName(
                    d->mParameters.value(QLatin1String("CHARSET")).toAscii());
            if (codec != NULL) {
                return codec->toUnicode(d->mValue.toByteArray());
            }
        }
        return QString();
    } else {
        return d->mValue.toString();
    }
}

/*!
 * Sets the type of value held in the property to \a type.
 */
void QVersitProperty::setValueType(QVersitProperty::ValueType type)
{
    d->mValueType = type;
}

/*!
 * Returns the type of value held in the property.
 */
QVersitProperty::ValueType QVersitProperty::valueType() const
{
    return d->mValueType;
}

/*!
 * Returns true if the property is empty.
 */
bool QVersitProperty::isEmpty() const
{
    return d->mGroups.isEmpty()
            && d->mName.isEmpty()
            && d->mParameters.isEmpty()
            && !d->mValue.isValid();
}

/*!
 * Clears the contents of this property.
 */
void QVersitProperty::clear()
{
    d->mGroups.clear();
    d->mName.clear();
    d->mValue.clear();
    d->mParameters.clear();
    d->mValueType = QVersitProperty::PlainType;
}

QTM_END_NAMESPACE
<|endoftext|>


<commit_before>/*
* Copyright 2010-2011 Research In Motion Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include <QTime>
#include "PortScanner.h"

PortScanner::PortScanner()
{
    // random number generator init
    qsrand(QTime::currentTime().msec());
}

PortScanner::~PortScanner()
{

}

// simple function to find open port on system
unsigned short PortScanner::findUsablePort(unsigned short port)
{
    bool portFound = false;

    QTcpServer server = new QTcpServer();

    while (!portFound)
    {
        if (!server->listen(QHostAddress::LocalHost, port))
        {
            qDebug() << "Cannot start server, port" << port << "in use.";
            // try a random port
            port = qrand() % 65535;
        }
        else
            portFound = true;
    }

    if (server) delete server;

    return port;
}
<commit_msg>Fixed a typo<commit_after>/*
* Copyright 2010-2011 Research In Motion Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include <QTime>
#include "PortScanner.h"

PortScanner::PortScanner()
{
    // random number generator init
    qsrand(QTime::currentTime().msec());
}

PortScanner::~PortScanner()
{

}

// simple function to find open port on system
unsigned short PortScanner::findUsablePort(unsigned short port)
{
    bool portFound = false;

    QTcpServer *server = new QTcpServer();

    while (!portFound)
    {
        if (!server->listen(QHostAddress::LocalHost, port))
        {
            qDebug() << "Cannot start server, port" << port << "in use.";
            // try a random port
            port = qrand() % 65535;
        }
        else
            portFound = true;
    }

    if (server) delete server;

    return port;
}
<|endoftext|>


<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "SurgSim/Graphics/OsgManager.h"

#include <vector>

#include "SurgSim/Framework/Log.h"
#include "SurgSim/Framework/Scene.h"
#include "SurgSim/Framework/Runtime.h"

#include "SurgSim/Graphics/OsgRepresentation.h"
#include "SurgSim/Graphics/OsgCamera.h"
#include "SurgSim/Graphics/OsgGroup.h"
#include "SurgSim/Graphics/OsgView.h"
#include "SurgSim/Graphics/OsgScreenSpacePass.h"

#include <osgViewer/Scene>
#include <osgDB/WriteFile>

using SurgSim::Graphics::OsgRepresentation;
using SurgSim::Graphics::OsgCamera;
using SurgSim::Graphics::OsgGroup;
using SurgSim::Graphics::OsgManager;

namespace SurgSim
{
namespace Graphics
{
OsgManager::OsgManager() : SurgSim::Graphics::Manager(),
	m_viewer(new osgViewer::CompositeViewer())
{
}

OsgManager::~OsgManager()
{
}

void OsgManager::setMultiThreading(bool val)
{
	if (val == true)
	{
		m_viewer->setThreadingModel(osgViewer::ViewerBase::ThreadPerContext);
	}
	else
	{
		m_viewer->setThreadingModel(osgViewer::ViewerBase::SingleThreaded);
	}
}

bool OsgManager::isMultiThreading() const
{
	return m_viewer->getThreadingModel() != osgViewer::ViewerBase::SingleThreaded;
}

std::shared_ptr<Group> OsgManager::getOrCreateGroup(const std::string& name)
{
	std::shared_ptr<Group> result;
	auto groups = getGroups();

	auto group = groups.find(name);

	if (group == std::end(groups))
	{
		auto newGroup = std::make_shared<OsgGroup>(name);
		addGroup(newGroup);
		result = newGroup;
	}
	else
	{
		result = group->second;
	}

	return result;
}

bool OsgManager::addRepresentation(std::shared_ptr<SurgSim::Graphics::Representation> representation)
{
	std::shared_ptr<OsgRepresentation> osgRepresentation = std::dynamic_pointer_cast<OsgRepresentation>(representation);
	bool result;
	if (osgRepresentation)
	{
		result = Manager::addRepresentation(osgRepresentation);
	}
	else
	{
		SURGSIM_LOG_INFO(getLogger())
				<< __FUNCTION__ << " Representation is not a subclass of OsgRepresentation "
				<< representation->getName();
		result = false;
	}
	return result;
}

bool OsgManager::addView(std::shared_ptr<SurgSim::Graphics::View> view)
{
	std::shared_ptr<OsgView> osgView = std::dynamic_pointer_cast<OsgView>(view);

	bool result = true;
	if (osgView == nullptr)
	{
		SURGSIM_LOG_WARNING(getLogger()) << __FUNCTION__ << " View is not a subclass of OsgView " << view->getName();
		result = false;
	}
	else
	{
		SURGSIM_ASSERT(view->getCamera() != nullptr) << "View should have a camera when added to the manager.";
		if (Manager::addView(view))
		{
			m_viewer->addView(osgView->getOsgView());
		}
	}

	return result;
}

bool OsgManager::removeView(std::shared_ptr<SurgSim::Graphics::View> view)
{
	std::shared_ptr<OsgView> osgView = std::dynamic_pointer_cast<OsgView>(view);
	if (osgView)
	{
		m_viewer->removeView(osgView->getOsgView());
	}

	return Manager::removeView(view);
}

bool OsgManager::doInitialize()
{
	m_hudElement = std::make_shared<OsgScreenSpacePass>(Representation::DefaultHudGroupName);
	return true;
}

bool OsgManager::doStartUp()
{
	return true;
}

bool OsgManager::doUpdate(double dt)
{

	// There is a bug in the scene initialisation where addSceneElement() will not be correctly executed if
	// performed inside of doInitialize(), this needs to be fixed
	// HS-2014-dec-12
	// #workaround
	if (!m_hudElement->isInitialized())
	{
		getRuntime()->getScene()->addSceneElement(m_hudElement);
	}

	if (Manager::doUpdate(dt))
	{
		m_viewer->frame();

		// \note HS-2013-dec-12 This will work as long as we deal with one view, when we move to stereoscopic
		//	     we might have to revise things. Or just assume that most views have the same size
		if (m_viewer->getNumViews() > 0)
		{
			auto dimensions = getViews()[0]->getDimensions();
			m_hudElement->setViewPort(dimensions[0], dimensions[1]);
		}
		return true;
	}
	else
	{
		return false;
	}
}

void OsgManager::doBeforeStop()
{
#ifdef OSS_DEBUG
	dumpDebugInfo();
#endif
	// Delete the viewer so that the graphics context will be released in the manager's thread
	m_viewer = nullptr;
}

osg::ref_ptr<osgViewer::CompositeViewer> OsgManager::getOsgCompositeViewer() const
{
	return m_viewer;
}

void SurgSim::Graphics::OsgManager::dumpDebugInfo() const
{
	osgDB::writeNodeFile(*m_viewer->getView(0)->getCamera(), "viewer_zero_camera.osgt");
}

}
}

<commit_msg>Change default threading mode for viewer<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "SurgSim/Graphics/OsgManager.h"

#include <vector>

#include "SurgSim/Framework/Log.h"
#include "SurgSim/Framework/Scene.h"
#include "SurgSim/Framework/Runtime.h"

#include "SurgSim/Graphics/OsgRepresentation.h"
#include "SurgSim/Graphics/OsgCamera.h"
#include "SurgSim/Graphics/OsgGroup.h"
#include "SurgSim/Graphics/OsgView.h"
#include "SurgSim/Graphics/OsgScreenSpacePass.h"

#include <osgViewer/Scene>
#include <osgDB/WriteFile>

using SurgSim::Graphics::OsgRepresentation;
using SurgSim::Graphics::OsgCamera;
using SurgSim::Graphics::OsgGroup;
using SurgSim::Graphics::OsgManager;

namespace SurgSim
{
namespace Graphics
{
OsgManager::OsgManager() : SurgSim::Graphics::Manager(),
	m_viewer(new osgViewer::CompositeViewer())
{
	setMultiThreading(true);
}

OsgManager::~OsgManager()
{
}

void OsgManager::setMultiThreading(bool val)
{
	if (val == true)
	{
		m_viewer->setThreadingModel(osgViewer::ViewerBase::DrawThreadPerContext);
	}
	else
	{
		m_viewer->setThreadingModel(osgViewer::ViewerBase::SingleThreaded);
	}
}

bool OsgManager::isMultiThreading() const
{
	return m_viewer->getThreadingModel() != osgViewer::ViewerBase::SingleThreaded;
}

std::shared_ptr<Group> OsgManager::getOrCreateGroup(const std::string& name)
{
	std::shared_ptr<Group> result;
	auto groups = getGroups();

	auto group = groups.find(name);

	if (group == std::end(groups))
	{
		auto newGroup = std::make_shared<OsgGroup>(name);
		addGroup(newGroup);
		result = newGroup;
	}
	else
	{
		result = group->second;
	}

	return result;
}

bool OsgManager::addRepresentation(std::shared_ptr<SurgSim::Graphics::Representation> representation)
{
	std::shared_ptr<OsgRepresentation> osgRepresentation = std::dynamic_pointer_cast<OsgRepresentation>(representation);
	bool result;
	if (osgRepresentation)
	{
		result = Manager::addRepresentation(osgRepresentation);
	}
	else
	{
		SURGSIM_LOG_INFO(getLogger())
				<< __FUNCTION__ << " Representation is not a subclass of OsgRepresentation "
				<< representation->getName();
		result = false;
	}
	return result;
}

bool OsgManager::addView(std::shared_ptr<SurgSim::Graphics::View> view)
{
	std::shared_ptr<OsgView> osgView = std::dynamic_pointer_cast<OsgView>(view);

	bool result = true;
	if (osgView == nullptr)
	{
		SURGSIM_LOG_WARNING(getLogger()) << __FUNCTION__ << " View is not a subclass of OsgView " << view->getName();
		result = false;
	}
	else
	{
		SURGSIM_ASSERT(view->getCamera() != nullptr) << "View should have a camera when added to the manager.";
		if (Manager::addView(view))
		{
			m_viewer->addView(osgView->getOsgView());
		}
	}

	return result;
}

bool OsgManager::removeView(std::shared_ptr<SurgSim::Graphics::View> view)
{
	std::shared_ptr<OsgView> osgView = std::dynamic_pointer_cast<OsgView>(view);
	if (osgView)
	{
		m_viewer->removeView(osgView->getOsgView());
	}

	return Manager::removeView(view);
}

bool OsgManager::doInitialize()
{
	m_hudElement = std::make_shared<OsgScreenSpacePass>(Representation::DefaultHudGroupName);
	return true;
}

bool OsgManager::doStartUp()
{
	return true;
}

bool OsgManager::doUpdate(double dt)
{

	// There is a bug in the scene initialisation where addSceneElement() will not be correctly executed if
	// performed inside of doInitialize(), this needs to be fixed
	// HS-2014-dec-12
	// #workaround
	if (!m_hudElement->isInitialized())
	{
		getRuntime()->getScene()->addSceneElement(m_hudElement);
	}

	if (Manager::doUpdate(dt))
	{
		m_viewer->frame();

		// \note HS-2013-dec-12 This will work as long as we deal with one view, when we move to stereoscopic
		//	     we might have to revise things. Or just assume that most views have the same size
		if (m_viewer->getNumViews() > 0)
		{
			auto dimensions = getViews()[0]->getDimensions();
			m_hudElement->setViewPort(dimensions[0], dimensions[1]);
		}
		return true;
	}
	else
	{
		return false;
	}
}

void OsgManager::doBeforeStop()
{
#ifdef OSS_DEBUG
	dumpDebugInfo();
#endif
	// Delete the viewer so that the graphics context will be released in the manager's thread
	m_viewer = nullptr;
}

osg::ref_ptr<osgViewer::CompositeViewer> OsgManager::getOsgCompositeViewer() const
{
	return m_viewer;
}

void SurgSim::Graphics::OsgManager::dumpDebugInfo() const
{
	osgDB::writeNodeFile(*m_viewer->getView(0)->getCamera(), "viewer_zero_camera.osgt");
}

}
}

<|endoftext|>


<commit_before>#include "TextureLoader.h"
#include "App.h"
#include "ModuleRenderer3D.h"
#include "GameObject.h"
#include "ModuleGameObject.h"
#include "ComponentTexture.h"
#include "Functions.h"

#include "Devil\include\il.h"
#include "Devil\include\ilu.h"
#include "Devil\include\ilut.h"

#pragma comment (lib, "Devil/libx86/DevIL.lib")
#pragma comment (lib, "Devil/libx86/ILU.lib")
#pragma comment (lib, "Devil/libx86/ILUT.lib")

TextureLoader::TextureLoader(bool start_enabled)
{
}

TextureLoader::~TextureLoader()
{
}

bool TextureLoader::Awake()
{
	bool ret = true;

	ilInit();
	iluInit();
	ilutInit();
	ilutRenderer(ILUT_OPENGL);

	return ret;
}

bool TextureLoader::Start()
{
	bool ret = true;

	return ret;
}

bool TextureLoader::Update()
{
	bool ret = true;

	return ret;
}

bool TextureLoader::CleanUp()
{
	bool ret = true;

	return ret;
}

void TextureLoader::OnLoadFile(const char * file_path, const char * file_name, const char * file_extension)
{
	if (TextCmp("png", file_extension))
	{
		LoadTexture(file_path);
	}
}

bool TextureLoader::LoadTexture(const char * full_path)
{
	bool ret = true;

	ILuint id;
	GLuint textureID;

	if (ilLoad(IL_TYPE_UNKNOWN, full_path))
	{
		ILinfo ImageInfo;
		iluGetImageInfo(&ImageInfo);

		if (ImageInfo.Origin == IL_ORIGIN_UPPER_LEFT)
		{
			iluFlipImage();
		}

		ilConvertImage(IL_RGB, IL_UNSIGNED_BYTE);

		textureID = App->renderer3D->LoadTextureBuffer(ilGetData(), 1, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT),
			GL_REPEAT, GL_REPEAT, GL_NEAREST, GL_NEAREST);

		Texture* texture = new Texture(textureID, ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT));

		ilDeleteImages(1, &id);

		textures.push_back(texture);

		// CUSTOM GAME OBJECT TEXTURE LOADING FOR THIS ASSIGNMENT
		vector<GameObject*> go = App->gameobj->GetListGameObjects();

		for (vector<GameObject*>::iterator it = go.begin(); it != go.end(); it++)
		{
			(*it)->RemoveComponent(TEXTURE);
			(*it)->AddComponent(TEXTURE);
			ComponentTexture* comp = (ComponentTexture*)(*it)->FindComponentByType(TEXTURE);

			comp->SetTexture(texture);
		}
		// ------------------------------------------------------
	}
	else
	{
		LOG_OUTPUT("Cannot load image %s. Error: %s", full_path, iluErrorString(ilGetError()));
	}

	return ret;
}

void TextureLoader::UnloadTexture(Texture * text)
{
	for (vector<Texture*>::iterator it = textures.begin(); it != textures.end(); it++)
	{
		if ((*it) == text)
		{
			if(text->GetId() != 0)
				App->renderer3D->UnloadTextureBuffer(text->GetId(), 1);

			text->CleanUp();
			textures.erase(it);
			break;
		}
	}
}

Texture::Texture(uint _id, uint _width, uint _height)
{
	id = _id;
	width = _width;
	height = _height;
}

bool Texture::operator==(Texture * text)
{
	bool ret = false;

	if (id == text->id && width == text->width && height == text->height)
		ret = true;

	return ret;
}

void Texture::CleanUp()
{
}

uint Texture::GetId()
{
	return id;
}

void Texture::AddUser()
{
	used_by++;
}

void Texture::DeleteUser()
{
	used_by--;
}

int Texture::UsedBy()
{
	return used_by;
}

bool Texture::IsUsed()
{
	return used_by != 0 ? true : false;
}
<commit_msg>Bug unloading textures<commit_after>#include "TextureLoader.h"
#include "App.h"
#include "ModuleRenderer3D.h"
#include "GameObject.h"
#include "ModuleGameObject.h"
#include "ComponentTexture.h"
#include "Functions.h"

#include "Devil\include\il.h"
#include "Devil\include\ilu.h"
#include "Devil\include\ilut.h"

#pragma comment (lib, "Devil/libx86/DevIL.lib")
#pragma comment (lib, "Devil/libx86/ILU.lib")
#pragma comment (lib, "Devil/libx86/ILUT.lib")

TextureLoader::TextureLoader(bool start_enabled)
{
}

TextureLoader::~TextureLoader()
{
}

bool TextureLoader::Awake()
{
	bool ret = true;

	ilInit();
	iluInit();
	ilutInit();
	ilutRenderer(ILUT_OPENGL);

	return ret;
}

bool TextureLoader::Start()
{
	bool ret = true;

	return ret;
}

bool TextureLoader::Update()
{
	bool ret = true;

	return ret;
}

bool TextureLoader::CleanUp()
{
	bool ret = true;

	for (vector<Texture*>::iterator it = textures.begin(); it != textures.end();)
	{
		if ((*it)->GetId() != 0)
			App->renderer3D->UnloadTextureBuffer((*it)->GetId(), 1);

		(*it)->CleanUp();
		delete (*it);

		it = textures.erase(it);
	}

	return ret;
}

void TextureLoader::OnLoadFile(const char * file_path, const char * file_name, const char * file_extension)
{
	if (TextCmp("png", file_extension))
	{
		LoadTexture(file_path);
	}
}

bool TextureLoader::LoadTexture(const char * full_path)
{
	bool ret = true;

	ILuint id;
	GLuint textureID;

	if (ilLoad(IL_TYPE_UNKNOWN, full_path))
	{
		ILinfo ImageInfo;
		iluGetImageInfo(&ImageInfo);

		if (ImageInfo.Origin == IL_ORIGIN_UPPER_LEFT)
		{
			iluFlipImage();
		}

		ilConvertImage(IL_RGB, IL_UNSIGNED_BYTE);

		textureID = App->renderer3D->LoadTextureBuffer(ilGetData(), 1, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT),
			GL_REPEAT, GL_REPEAT, GL_NEAREST, GL_NEAREST);

		Texture* texture = new Texture(textureID, ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT));

		ilDeleteImages(1, &id);

		textures.push_back(texture);

		// CUSTOM GAME OBJECT TEXTURE LOADING FOR THIS ASSIGNMENT
		vector<GameObject*> go = App->gameobj->GetListGameObjects();

		for (vector<GameObject*>::iterator it = go.begin(); it != go.end(); it++)
		{
			(*it)->RemoveComponent(TEXTURE);
			(*it)->AddComponent(TEXTURE);
			ComponentTexture* comp = (ComponentTexture*)(*it)->FindComponentByType(TEXTURE);

			comp->SetTexture(texture);
		}
		// ------------------------------------------------------
	}
	else
	{
		LOG_OUTPUT("Cannot load image %s. Error: %s", full_path, iluErrorString(ilGetError()));
	}

	return ret;
}

void TextureLoader::UnloadTexture(Texture * text)
{
	for (vector<Texture*>::iterator it = textures.begin(); it != textures.end(); it++)
	{
		if ((*it) == text)
		{
			if((*it)->GetId() != 0)
				App->renderer3D->UnloadTextureBuffer((*it)->GetId(), 1);

			(*it)->CleanUp();

			delete(*it);
			textures.erase(it);
			break;
		}
	}
}

Texture::Texture(uint _id, uint _width, uint _height)
{
	id = _id;
	width = _width;
	height = _height;
}

bool Texture::operator==(Texture * text)
{
	bool ret = false;

	if (id == text->id && width == text->width && height == text->height)
		ret = true;

	return ret;
}

void Texture::CleanUp()
{
}

uint Texture::GetId()
{
	return id;
}

void Texture::AddUser()
{
	used_by++;
}

void Texture::DeleteUser()
{
	used_by--;
}

int Texture::UsedBy()
{
	return used_by;
}

bool Texture::IsUsed()
{
	return used_by != 0 ? true : false;
}
<|endoftext|>


<commit_before>// SetTests.cpp : Defines the entry point for the console application.
//

#include "gtest/gtest.h"
#include <set.h>

TEST(SuperSet, InitialSizeIsZero) {
	Set set;
	EXPECT_EQ(0, set.size());
}

int main(int argc, char** argv)
{
	// run all tests
	::testing::InitGoogleTest(&argc, argv);

	return RUN_ALL_TESTS();
}
<commit_msg>FInd our Set not std::set<commit_after>// SetTests.cpp : Defines the entry point for the console application.
//

#include "gtest/gtest.h"
#include <Set.h>

TEST(SuperSet, InitialSizeIsZero) {
	Set set;
	EXPECT_EQ(0, set.size());
}

int main(int argc, char** argv)
{
	// run all tests
	::testing::InitGoogleTest(&argc, argv);

	return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#pragma once

#include "prion/core.hpp"
#include <map>
#include <memory>
#include <stdexcept>
#include <string>

namespace Unicorn {

    using namespace Prion;
    namespace Literals { using namespace Prion::Literals; }

    // Exceptions

    class InitializationError:
    public std::runtime_error {
    public:
        explicit InitializationError(const u8string& message):
            std::runtime_error(message) {}
    };

    class EncodingError:
    public std::runtime_error {
    public:
        EncodingError():
            std::runtime_error(prefix({}, 0)), enc(), ofs(0) {}
        explicit EncodingError(const u8string& encoding, size_t offset = 0, char32_t c = 0):
            std::runtime_error(prefix(encoding, offset) + hexcode(&c, 1)), enc(make_shared<u8string>(encoding)), ofs(offset) {}
        template <typename C>
            EncodingError(const u8string& encoding, size_t offset, const C* ptr, size_t n = 1):
            std::runtime_error(prefix(encoding, offset) + hexcode(ptr, n)), enc(make_shared<u8string>(encoding)), ofs(offset) {}
        const char* encoding() const noexcept { static const char c = 0; return enc ? enc->data() : &c; }
        size_t offset() const noexcept { return ofs; }
    private:
        shared_ptr<u8string> enc;
        size_t ofs;
        static u8string prefix(const u8string& encoding, size_t offset);
        template <typename C> static u8string hexcode(const C* ptr, size_t n);
    };

    template <typename C>
    u8string EncodingError::hexcode(const C* ptr, size_t n) {
        using utype = std::make_unsigned_t<C>;
        if (! ptr || ! n)
            return {};
        u8string s = "; hex";
        auto uptr = reinterpret_cast<const utype*>(ptr);
        for (size_t i = 0; i < n; ++i) {
            s += ' ';
            s += hex(uptr[i]);
        }
        return s;
    }

    // Basic character types

    template <typename C> struct IsCharacterType { static constexpr bool value = false; };
    template <> struct IsCharacterType<char> { static constexpr bool value = true; };
    template <> struct IsCharacterType<char16_t> { static constexpr bool value = true; };
    template <> struct IsCharacterType<char32_t> { static constexpr bool value = true; };
    template <> struct IsCharacterType<wchar_t> { static constexpr bool value = true; };

    #if defined(PRI_TARGET_UNIX)
        using NativeCharacter = char;
    #else
        #define UNICORN_NATIVE_WCHAR 1
        using NativeCharacter = wchar_t;
    #endif

    #if WCHAR_MAX < 0x7fffffff
        #define UNICORN_WCHAR_UTF16 1
        using WcharEquivalent = char16_t;
    #else
        #define UNICORN_WCHAR_UTF32 1
        using WcharEquivalent = char32_t;
    #endif

    using NativeString = basic_string<NativeCharacter>;
    using WstringEquivalent = basic_string<WcharEquivalent>;

    // Version information

    namespace UnicornDetail {

        struct UnicodeVersionTable {
            std::map<Version, char32_t> table;
            UnicodeVersionTable();
        };

        const UnicodeVersionTable& unicode_version_table();

    }

    Version unicorn_version() noexcept;
    Version unicode_version() noexcept;

}
<commit_msg>Explicitly link with pcre etc<commit_after>#pragma once

#include "prion/core.hpp"
#include <map>
#include <memory>
#include <stdexcept>
#include <string>

PRI_LDLIB(unicorn)
PRI_LDLIB(pcre)
PRI_LDLIB(z)

namespace Unicorn {

    using namespace Prion;
    namespace Literals { using namespace Prion::Literals; }

    // Exceptions

    class InitializationError:
    public std::runtime_error {
    public:
        explicit InitializationError(const u8string& message):
            std::runtime_error(message) {}
    };

    class EncodingError:
    public std::runtime_error {
    public:
        EncodingError():
            std::runtime_error(prefix({}, 0)), enc(), ofs(0) {}
        explicit EncodingError(const u8string& encoding, size_t offset = 0, char32_t c = 0):
            std::runtime_error(prefix(encoding, offset) + hexcode(&c, 1)), enc(make_shared<u8string>(encoding)), ofs(offset) {}
        template <typename C>
            EncodingError(const u8string& encoding, size_t offset, const C* ptr, size_t n = 1):
            std::runtime_error(prefix(encoding, offset) + hexcode(ptr, n)), enc(make_shared<u8string>(encoding)), ofs(offset) {}
        const char* encoding() const noexcept { static const char c = 0; return enc ? enc->data() : &c; }
        size_t offset() const noexcept { return ofs; }
    private:
        shared_ptr<u8string> enc;
        size_t ofs;
        static u8string prefix(const u8string& encoding, size_t offset);
        template <typename C> static u8string hexcode(const C* ptr, size_t n);
    };

    template <typename C>
    u8string EncodingError::hexcode(const C* ptr, size_t n) {
        using utype = std::make_unsigned_t<C>;
        if (! ptr || ! n)
            return {};
        u8string s = "; hex";
        auto uptr = reinterpret_cast<const utype*>(ptr);
        for (size_t i = 0; i < n; ++i) {
            s += ' ';
            s += hex(uptr[i]);
        }
        return s;
    }

    // Basic character types

    template <typename C> struct IsCharacterType { static constexpr bool value = false; };
    template <> struct IsCharacterType<char> { static constexpr bool value = true; };
    template <> struct IsCharacterType<char16_t> { static constexpr bool value = true; };
    template <> struct IsCharacterType<char32_t> { static constexpr bool value = true; };
    template <> struct IsCharacterType<wchar_t> { static constexpr bool value = true; };

    #if defined(PRI_TARGET_UNIX)
        using NativeCharacter = char;
    #else
        #define UNICORN_NATIVE_WCHAR 1
        using NativeCharacter = wchar_t;
    #endif

    #if WCHAR_MAX < 0x7fffffff
        #define UNICORN_WCHAR_UTF16 1
        using WcharEquivalent = char16_t;
    #else
        #define UNICORN_WCHAR_UTF32 1
        using WcharEquivalent = char32_t;
    #endif

    using NativeString = basic_string<NativeCharacter>;
    using WstringEquivalent = basic_string<WcharEquivalent>;

    // Version information

    namespace UnicornDetail {

        struct UnicodeVersionTable {
            std::map<Version, char32_t> table;
            UnicodeVersionTable();
        };

        const UnicodeVersionTable& unicode_version_table();

    }

    Version unicorn_version() noexcept;
    Version unicode_version() noexcept;

}
<|endoftext|>


<commit_before>#include "CalibTest.h"

// declare external tests here, to save us some trivial header files
void TestTipCalibration();
void Test2D3DPoseEstimation();
void Test3DPointReconstruction();
void TestAbsoluteOrientation();
void TestBundleAdjustment();
void TestDecomposeProjection();
void TestFundamentalMatrix();
void TestHomography();
void TestProjectionDLT();
void TestHandEye();
void TestDualHandEye();

CalibrationTest::CalibrationTest()
	: boost::unit_test::test_suite( "Calibration test suite" )
{
	add( BOOST_TEST_CASE( &TestTipCalibration ) );
	// add( BOOST_TEST_CASE( &Test2D3DPoseEstimation ) );
	// add( BOOST_TEST_CASE( &Test3DPointReconstruction ) );
	// add( BOOST_TEST_CASE( &TestAbsoluteOrientation ) );
	// add( BOOST_TEST_CASE( &TestBundleAdjustment ) );
	// add( BOOST_TEST_CASE( &TestDecomposeProjection ) );
	// add( BOOST_TEST_CASE( &TestFundamentalMatrix ) );
	// add( BOOST_TEST_CASE( &TestHomography ) );
	// add( BOOST_TEST_CASE( &TestProjectionDLT ) );
	// add( BOOST_TEST_CASE( &TestHandEye ) );
	// add( BOOST_TEST_CASE( &TestDualHandEye ) );
}

<commit_msg>accidentally removed lots of test cases last time, uncommented again<commit_after>#include "CalibTest.h"

// declare external tests here, to save us some trivial header files
void TestTipCalibration();
void Test2D3DPoseEstimation();
void Test3DPointReconstruction();
void TestAbsoluteOrientation();
void TestBundleAdjustment();
void TestDecomposeProjection();
void TestFundamentalMatrix();
void TestHomography();
void TestProjectionDLT();
void TestHandEye();
void TestDualHandEye();

CalibrationTest::CalibrationTest()
	: boost::unit_test::test_suite( "Calibration test suite" )
{
	add( BOOST_TEST_CASE( &TestTipCalibration ) );
	add( BOOST_TEST_CASE( &Test2D3DPoseEstimation ) );
	add( BOOST_TEST_CASE( &Test3DPointReconstruction ) );
	add( BOOST_TEST_CASE( &TestAbsoluteOrientation ) );
	add( BOOST_TEST_CASE( &TestBundleAdjustment ) );
	add( BOOST_TEST_CASE( &TestDecomposeProjection ) );
	add( BOOST_TEST_CASE( &TestFundamentalMatrix ) );
	add( BOOST_TEST_CASE( &TestHomography ) );
	add( BOOST_TEST_CASE( &TestProjectionDLT ) );
	add( BOOST_TEST_CASE( &TestHandEye ) );
	add( BOOST_TEST_CASE( &TestDualHandEye ) );
}

<|endoftext|>


<commit_before>/*
    Copyright 2002-2014 CEA LIST

    This file is part of LIMA.

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

    LIMA 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with LIMA.  If not, see <http://www.gnu.org/licenses/>
*/
/************************************************************************
 *
 * @file       SemanticRoleLabelingLoader.cpp
 * @author     Clémence Filmont <clemence.filmont@cea.fr>
 * @date       2014--
 * copyright   Copyright (C) 2014 by CEA LIST
 * Project     mm_linguisticprocessing
 *
 *
 ***********************************************************************/

#include "SemanticRoleLabelingLoader.h"
#include "common/AbstractFactoryPattern/SimpleFactory.h"
#include "common/Data/strwstrtools.h"
#include "linguisticProcessing/core/Automaton/recognizerMatch.h"
#include "linguisticProcessing/core/Automaton/recognizerData.h"
#include "common/MediaticData/mediaticData.h"
#include "linguisticProcessing/common/annotationGraph/AnnotationData.h"
#include "linguisticProcessing/common/annotationGraph/AnnotationGraph.h"
#include "linguisticProcessing/core/LinguisticAnalysisStructure/LinguisticGraph.h"
#include "linguisticProcessing/LinguisticProcessingCommon.h"
#include "QStringList"
#include <QString>
#include "QTextCodec"
#include <boost/regex.hpp>
#include <queue>
#include <map>
#include <utility>
#include <iostream>
#include<fstream>

using namespace std;
using namespace Lima::LinguisticProcessing::LinguisticAnalysisStructure;
using namespace Lima::LinguisticProcessing::ApplyRecognizer;
using namespace Lima::Common::XMLConfigurationFiles;
using namespace Lima::Common::AnnotationGraphs;
using namespace Lima::LinguisticProcessing::SemanticAnalysis;
using namespace Lima::Common::AnnotationGraphs;

namespace Lima {
namespace LinguisticProcessing {
namespace SemanticAnalysis {

SimpleFactory<MediaProcessUnit,SemanticRoleLabelingLoader> SemanticRoleLabelingFactory(SEMANTICROLELABELINGLOADER_CLASSID);

//***********************************************************************
SemanticRoleLabelingLoader::SemanticRoleLabelingLoader():
m_language(0),
m_graph("PosGraph"),
m_suffix(".conll")
{}

SemanticRoleLabelingLoader::~SemanticRoleLabelingLoader()
{
}

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

void SemanticRoleLabelingLoader::init(Common::XMLConfigurationFiles::GroupConfigurationStructure& unitConfiguration,
            Manager* manager){

  SEMANTICANALYSISLOGINIT;
  m_language=manager->getInitializationParameters().media;
   AnalysisLoader::init(unitConfiguration,manager);
  try
  {
    m_graph=unitConfiguration.getParamsValueAtKey("graph");

  }
  catch (NoSuchParam& ) {} // keep default value
  try
  {
    m_suffix=unitConfiguration.getParamsValueAtKey("outputSuffix");
  }
   catch (NoSuchParam& ) {} // keep default value
    AnalysisLoader::init(unitConfiguration,manager);
}

LimaStatusCode SemanticRoleLabelingLoader::process(AnalysisContent& analysis) const{
  SEMANTICANALYSISLOGINIT;
  std::cerr << "je suis le fichier SRLLoader" << endl;
  AnalysisGraph* tokenList=static_cast<AnalysisGraph*>(analysis.getData(m_graph));
  if (tokenList==0) {
    LERROR << "graph " << m_graph << " has not been produced: check pipeline" << LENDL;
    return MISSING_DATA;
  }
  AnnotationData* annotationData = static_cast<AnnotationData*>(analysis.getData("AnnotationData"));
  int sentencesNb;
  LimaConllTokenIdMapping* limaConllMapping= static_cast<LimaConllTokenIdMapping*>(analysis.getData("LimaConllTokenIdMapping"));

  QFile file("/home/clemence/textes_test/jamaica_out.conll");
  int sentenceNb=1;
  std::map <int, QString> sentence;
  if (!file.open(QIODevice::ReadOnly))
    qDebug() << "cannot open file" << endl;
  while (!file.atEnd()) {
    QByteArray text=file.readLine();
    QString textString = QString::fromUtf8(text.constData());
//     LDEBUG << " ligne : " << textString << " " << LENDL;
    if (textString.size()<3){
      sentenceNb++;
    }else {
      QString becomingSentence=sentence[sentenceNb]+textString;
      sentence[sentenceNb]= becomingSentence;
    }
  }
  qDebug() << " There is " << sentenceNb << "sentences ";

//     SemanticRoleLabelingLoader::ConllHandler cHandler(m_language, analysis, tokenList);
//     if(cHandler.extractSemanticInformations(sentenceNb, limaConllMapping,sentence)){
// //
// // //         AnnotationGraphEdge semAnnotation=annotationData->createAnnotationEdge(it->first, );
// // //         annotationData->annotate(it->first, semRole, semRole);
// // //         annotationData->annotate(semAnnotation, "SemAnnot", roleName);
//     }

  return SUCCESS_ID;
}

SemanticRoleLabelingLoader::ConllHandler::ConllHandler(MediaId language, AnalysisContent& analysis, LinguisticAnalysisStructure::AnalysisGraph* graph):
m_language(language),
m_analysis(analysis),
m_graph(graph),
m_descriptorSeparator("\\t+"),
m_tokenSeparator("\\n+")
{
  SEMANTICANALYSISLOGINIT;
  LDEBUG << "SemanticRoleLabelingLoader::ConllHandler constructor";
}
SemanticRoleLabelingLoader::ConllHandler::~ConllHandler(){}

// repeated on each sentence
bool SemanticRoleLabelingLoader::ConllHandler::extractSemanticInformations(int sentenceNb, LimaConllTokenIdMapping* limaConllMapping, const QString & sent)
{
  SEMANTICANALYSISLOGINIT;
  SemanticRoleLabelingLoader::ConllHandler cHandler(m_language, m_analysis, m_graph);
  QStringList sentenceTokens=cHandler.splitSegment(sent, m_tokenSeparator);
  QStringList::const_iterator tokensIterator;
  QString firstSentenceToken=(*sent.constBegin());
  int classIndex=0;
  int classNumbers=cHandler.splitSegment(firstSentenceToken, m_descriptorSeparator).size()-11;

//   LDEBUG << "There is " << classNumbers << "verbal classes in the sentence " <<LENDL;

//   verbClasses=new std::pair<int, QString>[classNumbers];
  //repeated on each token of the sentence, that is on each line
//   for (tokensIterator = sentenceTokens.constBegin(); tokensIterator != sentenceTokens.constEnd();
//             ++tokensIterator){
//     int  roleNumbers=0;
//     QStringList descriptors=cHandler.splitSegment((*tokensIterator),"\\t+");
//     if (descriptors.size()>=10){
//       int conllTokenId=descriptors[0].toInt();
//       int conllToken=descriptors[1].toInt();
//       std::string semanticRoleLabel=descriptors[11].toStdString();
//       if(descriptors[10]!="-"){
//         QString vClass=descriptors[10];
//         LinguisticGraphVertex limaTokenId=cHandler.getLimaTokenId(conllTokenId, sentenceNb, limaConllMapping);
//           LDEBUG << limaTokenId <<endl;
//           verbClasses[classIndex]=make_pair(limaTokenId, vClass);
//           classIndex++;
//           break;
//       }else{
//         LDEBUG <<  "no relation found in mapping for the token " << conllToken << " in the sentence " << sentenceNb <<endl;
//       }
//       for (int i = descriptors.size()-classNumbers; i < descriptors.size(); ++i){
//         if (descriptors.at(i)!="-"){
//           LinguisticGraphVertex limaTokenId=cHandler.getLimaTokenId(conllTokenId, sentenceNb, limaConllMapping);
//           semanticRoles=new std::vector<std::pair<int,QString>>[classNumbers];
//           semanticRoles[classNumbers][roleNumbers]=make_pair(limaTokenId,descriptors.at(i));
//           roleNumbers++;
//           delete [] semanticRoles;
//         }
//       }
//       return true;
//     }else{
//       LERROR << "no token on line" <<endl;
//       return false;
//     }
//   }
//   delete [] verbClasses;
}

bool SemanticRoleLabelingLoader::ConllHandler::newSentence(const QString & line){
  SemanticRoleLabelingLoader::ConllHandler cHandler(m_language, m_analysis, m_graph);
  QStringList columns;
  columns=cHandler.splitSegment(line, m_descriptorSeparator);
  if (columns[0].toInt()==1){
    return true;
  }else{
    return false;
  }
}

QStringList SemanticRoleLabelingLoader::ConllHandler::splitSegment(const QString & segment, QRegExp separator)
{
QStringList segmentsSplited;
segmentsSplited =segment.split(QRegExp(separator));
return segmentsSplited;
}

LinguisticGraphVertex SemanticRoleLabelingLoader::ConllHandler::getLimaTokenId(LinguisticGraphVertex conllTokenId, int sentenceNb, LimaConllTokenIdMapping* limaConllMapping){
  std::map< int,std::map< int,LinguisticGraphVertex>>::iterator limaConllMappingIt = limaConllMapping->find(sentenceNb);
  if (limaConllMappingIt!= limaConllMapping->end() and limaConllMapping[sentenceNb].find(conllTokenId)!= limaConllMapping->end()){
  LinguisticGraphVertex limaTokenId=limaConllMappingIt->second.at(conllTokenId);
  return limaTokenId;

  }
}

}
}
} // end namespace

<commit_msg>Implement the nested ConllHandler class<commit_after>/*
    Copyright 2002-2014 CEA LIST

    This file is part of LIMA.

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

    LIMA 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with LIMA.  If not, see <http://www.gnu.org/licenses/>
*/
/************************************************************************
 *
 * @file       SemanticRoleLabelingLoader.cpp
 * @author     Clémence Filmont <clemence.filmont@cea.fr>
 * @date       2014--
 * copyright   Copyright (C) 2014 by CEA LIST
 * Project     mm_linguisticprocessing
 *
 *
 ***********************************************************************/

#include "SemanticRoleLabelingLoader.h"
#include "common/AbstractFactoryPattern/SimpleFactory.h"
#include "common/Data/strwstrtools.h"
#include "linguisticProcessing/core/Automaton/recognizerData.h"
#include "common/MediaticData/mediaticData.h"
#include "linguisticProcessing/common/annotationGraph/AnnotationData.h"
#include "linguisticProcessing/common/annotationGraph/AnnotationGraph.h"
#include "linguisticProcessing/core/LinguisticAnalysisStructure/LinguisticGraph.h"
#include "linguisticProcessing/LinguisticProcessingCommon.h"
#include <utility>
#include <iostream>
#include<fstream>

using namespace std;
using namespace Lima::LinguisticProcessing::LinguisticAnalysisStructure;
using namespace Lima::LinguisticProcessing::ApplyRecognizer;
using namespace Lima::Common::XMLConfigurationFiles;
using namespace Lima::Common::AnnotationGraphs;
using namespace Lima::LinguisticProcessing::SemanticAnalysis;
using namespace Lima::Common::AnnotationGraphs;

namespace Lima {
namespace LinguisticProcessing {
namespace SemanticAnalysis {

SimpleFactory<MediaProcessUnit,SemanticRoleLabelingLoader> SemanticRoleLabelingFactory(SEMANTICROLELABELINGLOADER_CLASSID);

//***********************************************************************
SemanticRoleLabelingLoader::SemanticRoleLabelingLoader():
m_language(0),
m_graph("PosGraph"),
m_suffix(".conll")
{}

SemanticRoleLabelingLoader::~SemanticRoleLabelingLoader()
{
}

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

void SemanticRoleLabelingLoader::init(Common::XMLConfigurationFiles::GroupConfigurationStructure& unitConfiguration, Manager* manager){

  SEMANTICANALYSISLOGINIT;
  m_language=manager->getInitializationParameters().media;
  AnalysisLoader::init(unitConfiguration,manager);
  try
  {
    m_graph=unitConfiguration.getParamsValueAtKey("graph");
  }
  catch (NoSuchParam& ) {} // keep default value
  try
  {
    m_suffix=unitConfiguration.getParamsValueAtKey("outputSuffix");
  }
   catch (NoSuchParam& ) {} // keep default value
    AnalysisLoader::init(unitConfiguration,manager);
  }

LimaStatusCode SemanticRoleLabelingLoader::process(AnalysisContent& analysis) const{
  SEMANTICANALYSISLOGINIT;
  AnalysisGraph* tokenList=static_cast<AnalysisGraph*>(analysis.getData(m_graph));
  if (tokenList==0) {
    LERROR << "graph " << m_graph << " has not been produced: check pipeline" << LENDL;
    return MISSING_DATA;
  }
  AnnotationData* annotationData = static_cast<AnnotationData*>(analysis.getData("AnnotationData"));
  LimaConllTokenIdMapping* limaConllMapping= static_cast<LimaConllTokenIdMapping*>(analysis.getData("LimaConllTokenIdMapping"));

  QFile file("/home/clemence/textes_test/jamaica_out.conll");
  if (!file.open(QIODevice::ReadOnly))
    qDebug() << "cannot open file" << endl;
  int sentenceNb=1;
  std::map <int, QString> sentences;
  while (!file.atEnd()) {
    QByteArray text=file.readLine();
    QString textString = QString::fromUtf8(text.constData());
    //One assume that the input file does not start with a blank line
    if (textString.size()<3){
      sentenceNb++;
    }else {
      QString becomingSentence=sentences[sentenceNb]+textString;
      sentences[sentenceNb]= becomingSentence;
    }
  }
  SemanticRoleLabelingLoader::ConllHandler cHandler(m_language, analysis, tokenList);
  for (std::map<int,QString>::iterator it=sentences.begin(); it!=sentences.end(); ++it){
    int sentenceIndex=it->first;
    QString sentence=it->second;
    if(cHandler.extractSemanticInformations(sentenceIndex, limaConllMapping,sentence)){
      LDEBUG << "there are " << cHandler.m_verbalClassNb << "classes for this sentence " << LENDL;
      for (int vClassIndex=0;vClassIndex<cHandler.m_verbalClassNb;vClassIndex++){
        LDEBUG  << cHandler.m_verbalClasses[vClassIndex].second << " triggered by the lima token whose id is " << cHandler.m_verbalClasses[vClassIndex].first<< ", and which evokes the following semantic roles in the sentence : " << LENDL;
        std::vector <pair<LinguisticGraphVertex,QString>>::iterator semRoleIt;
        for (semRoleIt=cHandler.m_semanticRoles[vClassIndex].begin(); semRoleIt!=cHandler.m_semanticRoles[vClassIndex].end();semRoleIt++){
          LDEBUG << (*semRoleIt).second << LENDL;
        }
      }
    }
  }
  return SUCCESS_ID;
}

SemanticRoleLabelingLoader::ConllHandler::ConllHandler(MediaId language, AnalysisContent& analysis, LinguisticAnalysisStructure::AnalysisGraph* graph):
m_language(language),
m_analysis(analysis),
m_graph(graph),
m_descriptorSeparator("\t+"),
m_tokenSeparator("\n+"),
m_verbalClasses(),
m_semanticRoles(),
m_verbalClassNb()
{
  SEMANTICANALYSISLOGINIT;
  LDEBUG << "SemanticRoleLabelingLoader::ConllHandler constructor";
}
SemanticRoleLabelingLoader::ConllHandler::~ConllHandler(){
  delete [] m_semanticRoles;
  delete [] m_verbalClasses;
}

// designed to be repeated on each sentence
bool SemanticRoleLabelingLoader::ConllHandler::extractSemanticInformations(int sentenceI, LimaConllTokenIdMapping* limaConllMapping, const QString & sent){
  SEMANTICANALYSISLOGINIT;
  SemanticRoleLabelingLoader::ConllHandler cHandler(m_language, m_analysis, m_graph);
  QStringList sentenceTokens=cHandler.splitSegment(sent, m_tokenSeparator);
  QStringList::const_iterator tokensIterator;
  QString firstSentenceToken=(*sentenceTokens.constBegin());
  int descriptorsNb=cHandler.splitSegment(firstSentenceToken, m_descriptorSeparator).size();
  m_verbalClassNb=descriptorsNb-11;
  if (m_verbalClassNb!=0){
    LDEBUG << sentenceI << " : \n" << sent << LENDL;
    int classIndex=0;
    m_verbalClasses=new std::pair<LinguisticGraphVertex, QString>[m_verbalClassNb];
    m_semanticRoles=new std::vector<std::pair<LinguisticGraphVertex,QString>>[m_verbalClassNb];
    //repeated on each token of the sentence, that is on each line
    for (tokensIterator = sentenceTokens.constBegin(); tokensIterator != sentenceTokens.constEnd();
            ++tokensIterator){
      int  roleNumbers=0;
      QStringList descriptors=cHandler.splitSegment((*tokensIterator),m_descriptorSeparator);
      if (descriptors.size()>=10){
        int conllTokenId=descriptors[0].toInt();
        QString conllToken=descriptors[1];
        if(descriptors[10]!="-"){
          QString verbalClass=descriptors[10];
          QString vClass=descriptors[10];
          LinguisticGraphVertex limaTokenId=cHandler.getLimaTokenId(conllTokenId, sentenceI, limaConllMapping);
          m_verbalClasses[classIndex]=make_pair(limaTokenId, vClass);
          classIndex++;
          continue;
        }
        else{
          for (int roleTargetFieldIndex=0; roleTargetFieldIndex<m_verbalClassNb;roleTargetFieldIndex++){
            if (descriptors[11+roleTargetFieldIndex]!="-"){
              QString semanticRoleLabel=descriptors[11+roleTargetFieldIndex];
              LinguisticGraphVertex limaTokenId=cHandler.getLimaTokenId(conllTokenId, sentenceI,   limaConllMapping);
              std::vector<std::pair<LinguisticGraphVertex,QString>> sRoles;
              m_semanticRoles[roleTargetFieldIndex].push_back(make_pair(limaTokenId,semanticRoleLabel));
              roleNumbers++;
            }
          }
        }
      }
    }
    return classIndex;
  }
}

QStringList SemanticRoleLabelingLoader::ConllHandler::splitSegment(const QString & segment, QRegExp separator){
  QStringList segmentsSplited;
  segmentsSplited =segment.split(QRegExp(separator),QString::SkipEmptyParts);
  return segmentsSplited;
}

LinguisticGraphVertex SemanticRoleLabelingLoader::ConllHandler::getLimaTokenId(int conllTokenId, int sentenceI, LimaConllTokenIdMapping* limaConllMapping){
  SEMANTICANALYSISLOGINIT;
  std::map< int,std::map< int,LinguisticGraphVertex>>::iterator limaConllMappingIt;
  limaConllMappingIt=limaConllMapping->find(sentenceI);
  if (limaConllMappingIt == limaConllMapping->end()) {
    LERROR << "Sentence " << sentenceI << " not found";
    // TODO exit or raise an exception
  }
  std::map< int,LinguisticGraphVertex> limaConllId=(*limaConllMappingIt).second;
  std::map< int,LinguisticGraphVertex>::iterator limaConllIdIt=limaConllId.find(conllTokenId);
  if (limaConllIdIt==limaConllId.end()) {
    LERROR << "Conll token id " << conllTokenId << " not found";
    // TODO exit or raise an exception
  }
  LinguisticGraphVertex limaTokenId=limaConllIdIt->second;
  return limaTokenId;
}

}
}
} // end namespace

<|endoftext|>