<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This library 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 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library 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 library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* This component is open-source                                               *
*                                                                             *
* Authors: Damien Marchal                                                     *
*          Bruno Carrez                                                       *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
/*****************************************************************************
* User of this library should read the documentation
* in the messaging.h file.
******************************************************************************/
#include <sstream>
using std::ostringstream ;

#include <iostream>
using std::endl ;

#include <vector>
using std::vector ;

#include <string>
using std::string ;

#include <algorithm>
using std::remove ;

#include "MessageDispatcher.h"

#include "MessageHandler.h"
#include "ConsoleMessageHandler.h"

#include <sofa/core/objectmodel/Base.h>

#include <sofa/helper/logging/RichConsoleStyleMessageFormatter.h>
using sofa::helper::logging::RichConsoleStyleMessageFormatter;

#include <mutex>
using std::lock_guard ;
using std::mutex;

namespace sofa
{

namespace helper
{

namespace logging
{

MessageHandler* getDefaultMessageHandler(){
    static ConsoleMessageHandler s_consoleMessageHandler(new RichConsoleStyleMessageFormatter());
    return &s_consoleMessageHandler ;
}

class MessageDispatcherImpl
{
public:
    std::vector<MessageHandler*> m_messageHandlers { getDefaultMessageHandler() } ;

    std::vector<MessageHandler*>& getHandlers()
    {
        return m_messageHandlers ;
    }

    int addHandler(MessageHandler* o)
    {
        if( std::find(m_messageHandlers.begin(), m_messageHandlers.end(), o) == m_messageHandlers.end())
        {
            m_messageHandlers.push_back(o) ;
            return (int)(m_messageHandlers.size()-1);
        }
        return -1;
    }

    int rmHandler(MessageHandler* o)
    {
        m_messageHandlers.erase(remove(m_messageHandlers.begin(), m_messageHandlers.end(), o), m_messageHandlers.end());
        return (int)(m_messageHandlers.size()-1);
    }

    void clearHandlers()
    {
        m_messageHandlers.clear() ;
    }

    void process(sofa::helper::logging::Message& m)
    {
        for( size_t i=0 ; i<m_messageHandlers.size() ; i++ )
            m_messageHandlers[i]->process(m) ;
    }
};

mutex s_dispatchermutex ;
MessageDispatcherImpl s_messagedispatcher ;

/*
static std::vector<MessageHandler*> setDefaultMessageHandler()
{
    /// This static function of the dispatcher has to be protected against concurent access
    /// This is done by a mutex and a scoped_guard as in Use the http://en.cppreference.com/w/cpp/thread/lock_guard
    //lock_guard<mutex> guard(s_dispatchermutex) ;

    std::vector<MessageHandler*> messageHandlers;
    messageHandlers.push_back(&s_consoleMessageHandler);
    return messageHandlers;
}*/

std::vector<MessageHandler*>& MessageDispatcher::getHandlers()
{
    //lock_guard<mutex> guard(s_dispatchermutex) ;

    return s_messagedispatcher.getHandlers();
}

int MessageDispatcher::addHandler(MessageHandler* o){
    //lock_guard<mutex> guard(s_dispatchermutex) ;

    return s_messagedispatcher.addHandler(o);
}

int MessageDispatcher::rmHandler(MessageHandler* o){
    //lock_guard<mutex> guard(s_dispatchermutex) ;

    return s_messagedispatcher.rmHandler(o);
}

void MessageDispatcher::clearHandlers(){
    //lock_guard<mutex> guard(s_dispatchermutex) ;

    s_messagedispatcher.clearHandlers();
}

void MessageDispatcher::process(sofa::helper::logging::Message& m){
    //lock_guard<mutex> guard(s_dispatchermutex) ;

    s_messagedispatcher.process(m);
}

MessageDispatcher::LoggerStream MessageDispatcher::log(Message::Class mclass, Message::Type type, const std::string& sender, const FileInfo::SPtr& fileInfo) {
    return MessageDispatcher::LoggerStream( mclass, type, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::log(Message::Class mclass, Message::Type type, const sofa::core::objectmodel::Base* sender, const  FileInfo::SPtr& fileInfo) {
    return MessageDispatcher::LoggerStream(mclass, type, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::info(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Info, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::info(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Info, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::deprecated(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Deprecated, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::deprecated(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Deprecated, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::warning(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Warning, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::warning(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Warning, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::error(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Error, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::error(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Error, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::fatal(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Fatal, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::fatal(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Fatal, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::advice(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Advice, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::advice(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Advice, sender, fileInfo);
}

MessageDispatcher::LoggerStream::LoggerStream(Message::Class mclass, Message::Type type,
             const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo)
    : m_message( mclass
                 , type
                 , sender->getClassName()
                 // temporary, until Base object reference kept in the message itself ->
                 // (mattn) not sure it is a good idea, the Message could be kept after the Base is deleted
                 // TODO(dmarchal): by converting this to a string we are not able anymore to
                 // display rich information like the component name or location in the scene tree while these
                 // information are really usefull. I have to make small experiment to see what could be a nice
                 // approach without too much overhead.
                 , fileInfo

//TODO(dmarchal): this is a dirty fix to make the source code compile on windows which fail at link
//time. More fundamentally this function should'nt be in the message dispatcher class that is supposed
//to have no link to sofa::core::objectmodel::Base
#ifdef WIN32
                 , ComponentInfo::SPtr( new ComponentInfo("", "")) )
#else
                 , ComponentInfo::SPtr( new ComponentInfo("" /*sender->getName()*/, "")) )
#endif //WIN32
{
}

MessageDispatcher::LoggerStream::~LoggerStream()
{
    if ( !m_message.empty() ) MessageDispatcher::process(m_message);
}

} // logging
} // helper
} // sofa

<commit_msg>[SofaKernel] logger: back with the DefaultStyleMessageFormatter by default. RichConsoleStyleMessageFormatter is too verbose, and it uses more resources, it cannot be imposed by default. Anyway it is easy to switch to it in your own app.<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This library 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 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library 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 library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* This component is open-source                                               *
*                                                                             *
* Authors: Damien Marchal                                                     *
*          Bruno Carrez                                                       *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
/*****************************************************************************
* User of this library should read the documentation
* in the messaging.h file.
******************************************************************************/
#include <sstream>
using std::ostringstream ;

#include <iostream>
using std::endl ;

#include <vector>
using std::vector ;

#include <string>
using std::string ;

#include <algorithm>
using std::remove ;

#include "MessageDispatcher.h"

#include "MessageHandler.h"
#include "ConsoleMessageHandler.h"

#include <sofa/core/objectmodel/Base.h>

#include <sofa/helper/logging/DefaultStyleMessageFormatter.h>
using sofa::helper::logging::DefaultStyleMessageFormatter;

#include <mutex>
using std::lock_guard ;
using std::mutex;

namespace sofa
{

namespace helper
{

namespace logging
{

MessageHandler* getDefaultMessageHandler(){
    static ConsoleMessageHandler s_consoleMessageHandler(&DefaultStyleMessageFormatter::getInstance());
    return &s_consoleMessageHandler ;
}

class MessageDispatcherImpl
{
public:
    std::vector<MessageHandler*> m_messageHandlers { getDefaultMessageHandler() } ;

    std::vector<MessageHandler*>& getHandlers()
    {
        return m_messageHandlers ;
    }

    int addHandler(MessageHandler* o)
    {
        if( std::find(m_messageHandlers.begin(), m_messageHandlers.end(), o) == m_messageHandlers.end())
        {
            m_messageHandlers.push_back(o) ;
            return (int)(m_messageHandlers.size()-1);
        }
        return -1;
    }

    int rmHandler(MessageHandler* o)
    {
        m_messageHandlers.erase(remove(m_messageHandlers.begin(), m_messageHandlers.end(), o), m_messageHandlers.end());
        return (int)(m_messageHandlers.size()-1);
    }

    void clearHandlers()
    {
        m_messageHandlers.clear() ;
    }

    void process(sofa::helper::logging::Message& m)
    {
        for( size_t i=0 ; i<m_messageHandlers.size() ; i++ )
            m_messageHandlers[i]->process(m) ;
    }
};

mutex s_dispatchermutex ;
MessageDispatcherImpl s_messagedispatcher ;

/*
static std::vector<MessageHandler*> setDefaultMessageHandler()
{
    /// This static function of the dispatcher has to be protected against concurent access
    /// This is done by a mutex and a scoped_guard as in Use the http://en.cppreference.com/w/cpp/thread/lock_guard
    //lock_guard<mutex> guard(s_dispatchermutex) ;

    std::vector<MessageHandler*> messageHandlers;
    messageHandlers.push_back(&s_consoleMessageHandler);
    return messageHandlers;
}*/

std::vector<MessageHandler*>& MessageDispatcher::getHandlers()
{
    //lock_guard<mutex> guard(s_dispatchermutex) ;

    return s_messagedispatcher.getHandlers();
}

int MessageDispatcher::addHandler(MessageHandler* o){
    //lock_guard<mutex> guard(s_dispatchermutex) ;

    return s_messagedispatcher.addHandler(o);
}

int MessageDispatcher::rmHandler(MessageHandler* o){
    //lock_guard<mutex> guard(s_dispatchermutex) ;

    return s_messagedispatcher.rmHandler(o);
}

void MessageDispatcher::clearHandlers(){
    //lock_guard<mutex> guard(s_dispatchermutex) ;

    s_messagedispatcher.clearHandlers();
}

void MessageDispatcher::process(sofa::helper::logging::Message& m){
    //lock_guard<mutex> guard(s_dispatchermutex) ;

    s_messagedispatcher.process(m);
}

MessageDispatcher::LoggerStream MessageDispatcher::log(Message::Class mclass, Message::Type type, const std::string& sender, const FileInfo::SPtr& fileInfo) {
    return MessageDispatcher::LoggerStream( mclass, type, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::log(Message::Class mclass, Message::Type type, const sofa::core::objectmodel::Base* sender, const  FileInfo::SPtr& fileInfo) {
    return MessageDispatcher::LoggerStream(mclass, type, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::info(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Info, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::info(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Info, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::deprecated(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Deprecated, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::deprecated(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Deprecated, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::warning(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Warning, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::warning(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Warning, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::error(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Error, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::error(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Error, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::fatal(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Fatal, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::fatal(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Fatal, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::advice(Message::Class mclass, const std::string& sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Advice, sender, fileInfo);
}

MessageDispatcher::LoggerStream MessageDispatcher::advice(Message::Class mclass, const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo) {
    return log(mclass, Message::Advice, sender, fileInfo);
}

MessageDispatcher::LoggerStream::LoggerStream(Message::Class mclass, Message::Type type,
             const sofa::core::objectmodel::Base* sender, const FileInfo::SPtr& fileInfo)
    : m_message( mclass
                 , type
                 , sender->getClassName()
                 // temporary, until Base object reference kept in the message itself ->
                 // (mattn) not sure it is a good idea, the Message could be kept after the Base is deleted
                 // TODO(dmarchal): by converting this to a string we are not able anymore to
                 // display rich information like the component name or location in the scene tree while these
                 // information are really usefull. I have to make small experiment to see what could be a nice
                 // approach without too much overhead.
                 , fileInfo

//TODO(dmarchal): this is a dirty fix to make the source code compile on windows which fail at link
//time. More fundamentally this function should'nt be in the message dispatcher class that is supposed
//to have no link to sofa::core::objectmodel::Base
#ifdef WIN32
                 , ComponentInfo::SPtr( new ComponentInfo("", "")) )
#else
                 , ComponentInfo::SPtr( new ComponentInfo("" /*sender->getName()*/, "")) )
#endif //WIN32
{
}

MessageDispatcher::LoggerStream::~LoggerStream()
{
    if ( !m_message.empty() ) MessageDispatcher::process(m_message);
}

} // logging
} // helper
} // sofa

<|endoftext|>


<commit_before>#include "data-general.hpp"
#include "data-course.hpp"
#include "data-student.hpp"
using namespace std;

vector<Course> all_courses;
Student user;

void loadCourses() {
	ifstream infile("data/2012-13-s2-csv.csv");
	string str; // read in the header line
	getline(infile, str);
	while (infile.peek() != -1){
		Course incourse(infile);
		all_courses.push_back(incourse);
		// cout << incourse << endl;
	}
	// for (vector<Course>::iterator c = all_courses.begin(); c != all_courses.end(); ++c)
	// 	if (c->getProfessor()[1] == ' ')
	// 		if (c->getProfessor()[2] == '0' || c->getProfessor()[2] == '1')
	// 			c->displayMany();
}

void welcome() {
	string name, yearS = "", yearE = "", majors;
	cout << "Welcome!" << endl;
	cout << "What is your name? ";
	getline(cin, name);
	cout << "What year do you graduate? ";
	getline(cin, yearE);
	cout << "What are your majors (ex. CSCI, ASIAN) ";
	getline(cin, majors);
	user = Student(name, yearS, yearE, majors);
}

void getCourses() {
	string courses;
	cout << "What are some courses that you have taken? (ex. CSCI125, STAT 110)" << endl;
	getline(cin, courses);
	user.addCourses(courses);
}

int main(int argc, const char *argv[]) {
	loadCourses();
	// welcome();
	// getCourses();
	Student user("data/user.txt");
	user.display();

	cout << "Question: Has the user taken CSCI 251? " << user.hasTakenCourse("CSCI251") << endl;

	return 0;
}

// TODO: Add concentrations to Student
<commit_msg>Add/name methods of triggering data-entry<commit_after>#include "data-general.hpp"
#include "data-course.hpp"
#include "data-student.hpp"
using namespace std;

vector<Course> all_courses;
Student user;

void loadCourses() {
	ifstream infile("data/2012-13-s2-csv.csv");
	string str; // read in the header line
	getline(infile, str);
	while (infile.peek() != -1){
		Course incourse(infile);
		all_courses.push_back(incourse);
		// cout << incourse << endl;
	}
	// for (vector<Course>::iterator c = all_courses.begin(); c != all_courses.end(); ++c)
	// 	if (c->getProfessor()[1] == ' ')
	// 		if (c->getProfessor()[2] == '0' || c->getProfessor()[2] == '1')
	// 			c->displayMany();
}

void welcome() {
	string name, yearS = "", yearE = "", majors;
	cout << "Welcome!" << endl;
	cout << "What is your name? ";
	getline(cin, name);
	cout << "What year do you graduate? ";
	getline(cin, yearE);
	cout << "What are your majors (ex. CSCI, ASIAN) ";
	getline(cin, majors);
	user = Student(name, yearS, yearE, majors);
}

void getCourses() {
	string courses;
	cout << "What are some courses that you have taken? (ex. CSCI125, STAT 110)" << endl;
	getline(cin, courses);
	user.addCourses(courses);
}

int main(int argc, const char *argv[]) {
	loadCourses();

	// Method 1: Dynamic.
	// welcome();
	// getCourses();

	// Method 2: Hard-coded file path.
	// Student user("data/user.txt");

	// Method 3: File path as an argument.
	Student user(argv[1]);

	user.display();

	cout << "Question: Has the user taken CSCI 251? ";
	cout << user.hasTakenCourse("CSCI251") << endl;

	return 0;
}

// TODO: Add concentrations to Student
<|endoftext|>


<commit_before>#include <stdio.h>
#include <math.h>

#define  COPASI_TRACE_CONSTRUCTION

#include "copasi.h"
#include "utilities/CCopasiMessage.h"
#include "CMoiety.h"
#include "CCompartment.h"
#include "utilities/utilities.h"

CMoiety::CMoiety()
{
  CONSTRUCTOR_TRACE;
}

CMoiety::CMoiety(const CMoiety & src)
{
  CONSTRUCTOR_TRACE;
  mName = src.mName;
  mNumber = src.mNumber;
  mINumber = src.mINumber;
  mEquation = CCopasiVector < CChemEqElement >(src.mEquation);
}

CMoiety::CMoiety(const string & name)
{
  CONSTRUCTOR_TRACE;
  mName = name;
}

CMoiety::~CMoiety()
{
  DESTRUCTOR_TRACE;
}

void CMoiety::add
  (C_FLOAT64 value, CMetab & metabolite)
  {
    CChemEqElement * element = new CChemEqElement;
    element->setMultiplicity(value);
    element->setMetabolite(metabolite);

    mEquation.add(element);
  }

void CMoiety::add
  (C_FLOAT64 value, CMetab * metabolite)
  {
    add
      (value, *metabolite);
  }

void CMoiety::cleanup()
{
  mEquation.cleanup();
}

C_FLOAT64 CMoiety::dependentNumber()
{
  mNumber = mINumber;

  for (unsigned C_INT32 i = 1; i < mEquation.size(); i++)
    mNumber -= mEquation[i]->getMultiplicity() *
               mEquation[i]->getMetabolite().getNumberDbl();

  return mNumber;
}

C_FLOAT64 CMoiety::dependentRate()
{
  C_FLOAT64 Rate = 0.0;

  for (unsigned C_INT32 i = 1; i < mEquation.size(); i++)
    Rate -= mEquation[i]->getMultiplicity() *
            mEquation[i]->getMetabolite().getRate() *
            mEquation[i]->getMetabolite().getCompartment()->getVolumeInv();

  return Rate * mEquation[0]->getMetabolite().getCompartment()->getVolume();
}

string CMoiety::getName() const
  {
    return mName;
  }

string CMoiety::getDescription() const
  {
    string Description;
    for (unsigned C_INT32 i = 0; i < mEquation.size(); i++)
      {
        if (i)
          {
            if (mEquation[i]->getMultiplicity() < 0.0)
              Description += " - ";
            else
              Description += " + ";
          }
        if (fabs(mEquation[i]->getMultiplicity()) != 1.0)
          Description += StringPrint("%3.1f * ",
                                     fabs(mEquation[i]->getMultiplicity()));
        Description += mEquation[i]->getMetaboliteName();
        Description += "{" + mEquation[i]->getCompartmentName() + "}";
      }
    return Description;
  }

void CMoiety::setName(const string name)
{
  mName = name;
}

void CMoiety::setInitialValue()
{
  mINumber = 0;

  for (unsigned C_INT32 i = 0; i < mEquation.size(); i++)
    mINumber += ((C_INT32) mEquation[i]->getMultiplicity()) *
                mEquation[i]->getMetabolite().getInitialNumberDbl();
  return;
}

/**
 * Return the number value Wei Sun
 */
C_FLOAT64 CMoiety::getNumber() const
  {
    return mINumber;
  }

/**
 * Returns the address of mNumber
 */
void * CMoiety::getNumberAddr()
{
  return &mINumber;
}

/**
 * Saves in Gepasi 3.21 format
 */
C_INT32 CMoiety::saveOld(CWriteConfig & configBuffer)
{
  C_INT32 c = 0, t = 7, Fail = 0;

  Fail = configBuffer.setVariable("Metabolite", "string", (void *) & mEquation);
  if (Fail)
    return Fail;
  // we write mNumber instead of concentration, which is ok because Gepasi recalculates this itself
  Fail = configBuffer.setVariable("Concentration", "C_FLOAT64", (void *) & mNumber);
  if (Fail)
    return Fail;
  Fail = configBuffer.setVariable("Compartment", "C_INT32", (void *) & c);
  if (Fail)
    return Fail;
  Fail = configBuffer.setVariable("Type", "C_INT32", (void *) & t);
  return Fail;
}
<commit_msg>Fixed bug in setInitialValue.<commit_after>#include <stdio.h>
#include <math.h>

#define  COPASI_TRACE_CONSTRUCTION

#include "copasi.h"
#include "utilities/CCopasiMessage.h"
#include "CMoiety.h"
#include "CCompartment.h"
#include "utilities/utilities.h"

CMoiety::CMoiety()
{
  CONSTRUCTOR_TRACE;
}

CMoiety::CMoiety(const CMoiety & src)
{
  CONSTRUCTOR_TRACE;
  mName = src.mName;
  mNumber = src.mNumber;
  mINumber = src.mINumber;
  mEquation = CCopasiVector < CChemEqElement >(src.mEquation);
}

CMoiety::CMoiety(const string & name)
{
  CONSTRUCTOR_TRACE;
  mName = name;
}

CMoiety::~CMoiety()
{
  DESTRUCTOR_TRACE;
}

void CMoiety::add
  (C_FLOAT64 value, CMetab & metabolite)
  {
    CChemEqElement * element = new CChemEqElement;
    element->setMultiplicity(value);
    element->setMetabolite(metabolite);

    mEquation.add(element);
  }

void CMoiety::add
  (C_FLOAT64 value, CMetab * metabolite)
  {
    add
      (value, *metabolite);
  }

void CMoiety::cleanup()
{
  mEquation.cleanup();
}

C_FLOAT64 CMoiety::dependentNumber()
{
  mNumber = mINumber;

  for (unsigned C_INT32 i = 1; i < mEquation.size(); i++)
    mNumber -= mEquation[i]->getMultiplicity() *
               mEquation[i]->getMetabolite().getNumberDbl();

  return mNumber;
}

C_FLOAT64 CMoiety::dependentRate()
{
  C_FLOAT64 Rate = 0.0;

  for (unsigned C_INT32 i = 1; i < mEquation.size(); i++)
    Rate -= mEquation[i]->getMultiplicity() *
            mEquation[i]->getMetabolite().getRate() *
            mEquation[i]->getMetabolite().getCompartment()->getVolumeInv();

  return Rate * mEquation[0]->getMetabolite().getCompartment()->getVolume();
}

string CMoiety::getName() const
  {
    return mName;
  }

string CMoiety::getDescription() const
  {
    string Description;
    for (unsigned C_INT32 i = 0; i < mEquation.size(); i++)
      {
        if (i)
          {
            if (mEquation[i]->getMultiplicity() < 0.0)
              Description += " - ";
            else
              Description += " + ";
          }
        if (fabs(mEquation[i]->getMultiplicity()) != 1.0)
          Description += StringPrint("%3.1f * ",
                                     fabs(mEquation[i]->getMultiplicity()));
        Description += mEquation[i]->getMetaboliteName();
        Description += "{" + mEquation[i]->getCompartmentName() + "}";
      }
    return Description;
  }

void CMoiety::setName(const string name)
{
  mName = name;
}

void CMoiety::setInitialValue()
{
  mINumber = 0;

  for (unsigned C_INT32 i = 0; i < mEquation.size(); i++)
    mINumber += mEquation[i]->getMultiplicity() *
                mEquation[i]->getMetabolite().getInitialNumberDbl();
  return;
}

/**
 * Return the number value Wei Sun
 */
C_FLOAT64 CMoiety::getNumber() const
  {
    return mINumber;
  }

/**
 * Returns the address of mNumber
 */
void * CMoiety::getNumberAddr()
{
  return &mINumber;
}

/**
 * Saves in Gepasi 3.21 format
 */
C_INT32 CMoiety::saveOld(CWriteConfig & configBuffer)
{
  C_INT32 c = 0, t = 7, Fail = 0;

  Fail = configBuffer.setVariable("Metabolite", "string", (void *) & mEquation);
  if (Fail)
    return Fail;
  // we write mNumber instead of concentration, which is ok because Gepasi recalculates this itself
  Fail = configBuffer.setVariable("Concentration", "C_FLOAT64", (void *) & mNumber);
  if (Fail)
    return Fail;
  Fail = configBuffer.setVariable("Compartment", "C_INT32", (void *) & c);
  if (Fail)
    return Fail;
  Fail = configBuffer.setVariable("Type", "C_INT32", (void *) & t);
  return Fail;
}
<|endoftext|>


<commit_before>#include <boost/property_tree/ptree.hpp>

void put_default_parameters(boost::property_tree::ptree & params)
{
    params.put("material_properties.separator_heat_capacity",            1.2528e3 );
    params.put("material_properties.electrode_heat_capacity",            0.93e3   );
    params.put("material_properties.collector_heat_capacity",            2.7e3    );
    params.put("material_properties.separator_density",                  3.2e3    );
    params.put("material_properties.electrode_density",                  2.3e3    );
    params.put("material_properties.collector_density",                  2.70e3   );
    params.put("material_properties.electrolyte_mass_density",           1.2e3    );
    params.put("material_properties.separator_thermal_conductivity",     0.0019e2 );
    params.put("material_properties.electrode_thermal_conductivity",     0.0011e2 );
    params.put("material_properties.collector_thermal_conductivity",   237.0      );
    params.put("material_properties.alpha",                              0.0      );
    params.put("material_properties.differential_capacitance",           0.03134  );
    params.put("material_properties.separator_void_volume_fraction",     0.6      );
    params.put("material_properties.electrode_void_volume_fraction",     0.67     );
    params.put("material_properties.electrolyte_conductivity",           0.067    );
    params.put("material_properties.solid_phase_conductivity",          52.1      );
    params.put("material_properties.collector_electrical_resistivity",  28.2e-9   );
    params.put("material_properties.bruggemans_coefficient",             1.5      );
    params.put("material_properties.electrode_tortuosity_factor",        2.3      );
    params.put("material_properties.separator_tortuosity_factor",        1.29     );
    params.put("material_properties.pores_characteristic_dimension",     1.5e-9   );
    params.put("material_properties.pores_geometry_factor",              2.0      );

    params.put("boundary_values.charge_potential",                       2.2      );
    params.put("boundary_values.discharge_potential",                    1.4      );
    params.put("boundary_values.charge_current_density",               324.65     );
    params.put("boundary_values.discharge_current_density",           -324.65     );
    params.put("boundary_values.initial_potential",                      1.6      );

    params.put("boundary_values.ambient_temperature",                  300.0      );
    params.put("boundary_values.heat_transfer_coefficient",              8.0e-2   );

    // USUALLY YOU WILL NOT WANT TO MESS WITH THE THESE ONES
    params.put("solid_potential_component",  0);
    params.put("liquid_potential_component", 1);
    params.put("temperature_component",      2);

    params.put("material_properties.separator_material_id",         2);
    params.put("material_properties.anode_electrode_material_id",   1);
    params.put("material_properties.anode_collector_material_id",   4);
    params.put("material_properties.cathode_electrode_material_id", 3);
    params.put("material_properties.cathode_collector_material_id", 5);

    params.put("boundary_values.separator_material_id",         2);
    params.put("boundary_values.anode_electrode_material_id",   1);
    params.put("boundary_values.anode_collector_material_id",   4);
    params.put("boundary_values.cathode_electrode_material_id", 3);
    params.put("boundary_values.cathode_collector_material_id", 5);

    params.put("boundary_values.cathode_boundary_id",           1);
    params.put("boundary_values.anode_boundary_id",             2);
    params.put("boundary_values.upper_boundary_id",             3);
    params.put("boundary_values.lower_boundary_id",             4);
    params.put("boundary_values.other_boundary_id",             5);

    params.put("geometry.electrode_width", 50.0e-6);
    params.put("geometry.separator_width", 25.0e-6);
    params.put("geometry.collector_width",  5.0e-6);
    params.put("geometry.sandwich_height",  5.0e-6);

}

std::shared_ptr<boost::property_tree::ptree> initialize_database()
{
    std::shared_ptr<boost::property_tree::ptree> database(new boost::property_tree::ptree);
    database->put("verbose",                    true);
    database->put("solid_potential_component",     0);
    database->put("liquid_potential_component",    1);
    database->put("temperature_component",         2);
    database->put("electrochemical_block",         0);
    database->put("thermal_block",                 1);
    database->put("separator_material_id",         2);
    database->put("anode_electrode_material_id",   1);
    database->put("anode_collector_material_id",   4);
    database->put("cathode_electrode_material_id", 3);
    database->put("cathode_collector_material_id", 5);
    database->put("cathode_boundary_id",           1);
    database->put("anode_boundary_id",             2);
    database->put("upper_boundary_id",             3);
    database->put("lower_boundary_id",             4);
    database->put("other_boundary_id",             5);
    return database;
}
<commit_msg>fixed typo in the domain dimensions<commit_after>#include <boost/property_tree/ptree.hpp>

void put_default_parameters(boost::property_tree::ptree & params)
{
    params.put("material_properties.separator_heat_capacity",            1.2528e3 );
    params.put("material_properties.electrode_heat_capacity",            0.93e3   );
    params.put("material_properties.collector_heat_capacity",            2.7e3    );
    params.put("material_properties.separator_density",                  3.2e3    );
    params.put("material_properties.electrode_density",                  2.3e3    );
    params.put("material_properties.collector_density",                  2.70e3   );
    params.put("material_properties.electrolyte_mass_density",           1.2e3    );
    params.put("material_properties.separator_thermal_conductivity",     0.0019e2 );
    params.put("material_properties.electrode_thermal_conductivity",     0.0011e2 );
    params.put("material_properties.collector_thermal_conductivity",   237.0      );
    params.put("material_properties.alpha",                              0.0      );
    params.put("material_properties.differential_capacitance",           0.03134  );
    params.put("material_properties.separator_void_volume_fraction",     0.6      );
    params.put("material_properties.electrode_void_volume_fraction",     0.67     );
    params.put("material_properties.electrolyte_conductivity",           0.067    );
    params.put("material_properties.solid_phase_conductivity",          52.1      );
    params.put("material_properties.collector_electrical_resistivity",  28.2e-9   );
    params.put("material_properties.bruggemans_coefficient",             1.5      );
    params.put("material_properties.electrode_tortuosity_factor",        2.3      );
    params.put("material_properties.separator_tortuosity_factor",        1.29     );
    params.put("material_properties.pores_characteristic_dimension",     1.5e-9   );
    params.put("material_properties.pores_geometry_factor",              2.0      );

    params.put("boundary_values.charge_potential",                       2.2      );
    params.put("boundary_values.discharge_potential",                    1.4      );
    params.put("boundary_values.charge_current_density",               324.65     );
    params.put("boundary_values.discharge_current_density",           -324.65     );
    params.put("boundary_values.initial_potential",                      1.6      );

    params.put("boundary_values.ambient_temperature",                  300.0      );
    params.put("boundary_values.heat_transfer_coefficient",              8.0e-2   );

    // USUALLY YOU WILL NOT WANT TO MESS WITH THE THESE ONES
    params.put("solid_potential_component",  0);
    params.put("liquid_potential_component", 1);
    params.put("temperature_component",      2);

    params.put("material_properties.separator_material_id",         2);
    params.put("material_properties.anode_electrode_material_id",   1);
    params.put("material_properties.anode_collector_material_id",   4);
    params.put("material_properties.cathode_electrode_material_id", 3);
    params.put("material_properties.cathode_collector_material_id", 5);

    params.put("boundary_values.separator_material_id",         2);
    params.put("boundary_values.anode_electrode_material_id",   1);
    params.put("boundary_values.anode_collector_material_id",   4);
    params.put("boundary_values.cathode_electrode_material_id", 3);
    params.put("boundary_values.cathode_collector_material_id", 5);

    params.put("boundary_values.cathode_boundary_id",           1);
    params.put("boundary_values.anode_boundary_id",             2);
    params.put("boundary_values.upper_boundary_id",             3);
    params.put("boundary_values.lower_boundary_id",             4);
    params.put("boundary_values.other_boundary_id",             5);

    params.put("geometry.electrode_width", 50.0e-6);
    params.put("geometry.separator_width", 25.0e-6);
    params.put("geometry.collector_width",  5.0e-6);
    params.put("geometry.sandwich_height", 25.0e-6);

}

std::shared_ptr<boost::property_tree::ptree> initialize_database()
{
    std::shared_ptr<boost::property_tree::ptree> database(new boost::property_tree::ptree);
    database->put("verbose",                    true);
    database->put("solid_potential_component",     0);
    database->put("liquid_potential_component",    1);
    database->put("temperature_component",         2);
    database->put("electrochemical_block",         0);
    database->put("thermal_block",                 1);
    database->put("separator_material_id",         2);
    database->put("anode_electrode_material_id",   1);
    database->put("anode_collector_material_id",   4);
    database->put("cathode_electrode_material_id", 3);
    database->put("cathode_collector_material_id", 5);
    database->put("cathode_boundary_id",           1);
    database->put("anode_boundary_id",             2);
    database->put("upper_boundary_id",             3);
    database->put("lower_boundary_id",             4);
    database->put("other_boundary_id",             5);
    return database;
}
<|endoftext|>


<commit_before>/*
 * BitTest.cpp
 *
 *  Created on: 10 Aug 2013
 *      Author: nicholas
 */
#include <gtest/gtest.h>
#include <limits>
#include "../../include/util/Bit.hpp"

TEST(BitTest, ZeroRotateSigned) {
	int64_t testValue = 0;
	int64_t result = -1;

	result = Bit::rotateLeft(testValue);

	ASSERT_EQ(0, result);
}

TEST(BitTest, OneRotateSigned) {
	int64_t testValue = 1;
	int64_t result = -1;

	result = Bit::rotateLeft(testValue);

	ASSERT_EQ(2, result);
}

TEST(BitTest, DoubleRotateSigned) {
	int64_t testValue = 1;
	int64_t result = -5;

	result = Bit::rotateLeft(testValue);
	result = Bit::rotateLeft(result);

	ASSERT_EQ(4, result);
}

TEST(BitTest, MinusOneRotateSigned) {
	int64_t testValue = -1;
	int64_t result = 0;

	result = Bit::rotateLeft(testValue);

	ASSERT_EQ(-1, result);
}

TEST(BitTest, MinusTwoRotateSigned) {
	int64_t testValue = -2;
	int64_t result = 0;

	result = Bit::rotateLeft(testValue);

	ASSERT_EQ(-3, result);
}

TEST(BitTest, MaxNegativeRotateSigned) {
	int64_t testValue = std::numeric_limits<int64_t>::min();
	int64_t result = -2;

	result = Bit::rotateLeft(testValue);

	ASSERT_EQ(1, result);
}

TEST(BitTest, Rotate31Signed) {
	int64_t testValue = 1;
	int64_t result = -2;
	int i = 0;

	result = testValue;

	for(i = 0; i < 31; i++) {
		result = Bit::rotateLeft(result);
	}

	ASSERT_EQ(2147483648, result);
}

TEST(BitTest, Rotate32Signed) {
	int64_t testValue = 1;
	int64_t result = -2;
	int i = 0;

	result = testValue;

	for(i = 0; i < 32; i++) {
		result = Bit::rotateLeft(result);
	}

	ASSERT_EQ(4294967296, result);
}

TEST(BitTest, Rotate63Signed) {
	int64_t testValue = 1;
	int64_t result = -2;
	int64_t expected = std::numeric_limits<int64_t>::min();

	int i = 0;

	result = testValue;

	for(i = 0; i < 63; i++) {
		result = Bit::rotateLeft(result);
	}

	ASSERT_EQ(expected, result);
}

TEST(BitTest, Rotate64Signed) {
	int64_t testValue = 1;
	int64_t result = -2;
	int i = 0;

	result = testValue;

	for(i = 0; i < 64; i++) {
		result = Bit::rotateLeft(result);
	}

	ASSERT_EQ(1, result);
}

TEST(BitTest, RotateUnsigned) {
	uint64_t testValue = 1;
	uint64_t result = -2;
	int i = 0;

	result = testValue;
	result = Bit::rotateLeft(result);

	ASSERT_EQ(2, result);
}

TEST(BitTest, Rotate63Unsigned) {
	uint64_t testValue = 1;
	uint64_t result = -2;
	uint64_t expected = 9223372036854775808;
	int i = 0;

	result = testValue;

	for(i = 0; i < 63; i++) {
		result = Bit::rotateLeft(result);
	}
	ASSERT_EQ(expected, result);
}

TEST(BitTest, Rotate64Unsigned) {
	uint64_t testValue = 1;
	uint64_t result = -2;
	int i = 0;

	result = testValue;

	for(i = 0; i < 64; i++) {
		result = Bit::rotateLeft(result);
	}

	ASSERT_EQ(1, result);
}
<commit_msg>Fixed warnings<commit_after>/*
 * BitTest.cpp
 *
 *  Created on: 10 Aug 2013
 *      Author: nicholas
 */
#include <gtest/gtest.h>
#include <limits>
#include "../../include/util/Bit.hpp"

TEST(BitTest, ZeroRotateSigned) {
	int64_t testValue = 0;
	int64_t result = -1;

	result = Bit::rotateLeft(testValue);

	ASSERT_EQ(0, result);
}

TEST(BitTest, OneRotateSigned) {
	int64_t testValue = 1;
	int64_t result = -1;

	result = Bit::rotateLeft(testValue);

	ASSERT_EQ(2, result);
}

TEST(BitTest, DoubleRotateSigned) {
	int64_t testValue = 1;
	int64_t result = -5;

	result = Bit::rotateLeft(testValue);
	result = Bit::rotateLeft(result);

	ASSERT_EQ(4, result);
}

TEST(BitTest, MinusOneRotateSigned) {
	int64_t testValue = -1;
	int64_t result = 0;

	result = Bit::rotateLeft(testValue);

	ASSERT_EQ(-1, result);
}

TEST(BitTest, MinusTwoRotateSigned) {
	int64_t testValue = -2;
	int64_t result = 0;

	result = Bit::rotateLeft(testValue);

	ASSERT_EQ(-3, result);
}

TEST(BitTest, MaxNegativeRotateSigned) {
	int64_t testValue = std::numeric_limits<int64_t>::min();
	int64_t result = -2;

	result = Bit::rotateLeft(testValue);

	ASSERT_EQ(1, result);
}

TEST(BitTest, Rotate31Signed) {
	int64_t testValue = 1;
	int64_t result = -2;
	int i = 0;

	result = testValue;

	for(i = 0; i < 31; i++) {
		result = Bit::rotateLeft(result);
	}

	ASSERT_EQ(2147483648, result);
}

TEST(BitTest, Rotate32Signed) {
	int64_t testValue = 1;
	int64_t result = -2;
	int i = 0;

	result = testValue;

	for(i = 0; i < 32; i++) {
		result = Bit::rotateLeft(result);
	}

	ASSERT_EQ(4294967296, result);
}

TEST(BitTest, Rotate63Signed) {
	int64_t testValue = 1;
	int64_t result = -2;
	int64_t expected = std::numeric_limits<int64_t>::min();

	int i = 0;

	result = testValue;

	for(i = 0; i < 63; i++) {
		result = Bit::rotateLeft(result);
	}

	ASSERT_EQ(expected, result);
}

TEST(BitTest, Rotate64Signed) {
	int64_t testValue = 1;
	int64_t result = -2;
	int i = 0;

	result = testValue;

	for(i = 0; i < 64; i++) {
		result = Bit::rotateLeft(result);
	}

	ASSERT_EQ(1, result);
}

TEST(BitTest, RotateUnsigned) {
	uint64_t testValue = 1;
	uint64_t result = -2;

	result = testValue;
	result = Bit::rotateLeft(result);

	ASSERT_EQ(2, result);
}

TEST(BitTest, Rotate63Unsigned) {
	uint64_t testValue = 1;
	uint64_t result = -2;
	uint64_t expected = 9223372036854775808ul;
	int i = 0;

	result = testValue;

	for(i = 0; i < 63; i++) {
		result = Bit::rotateLeft(result);
	}
	ASSERT_EQ(expected, result);
}

TEST(BitTest, Rotate64Unsigned) {
	uint64_t testValue = 1;
	uint64_t result = -2;
	int i = 0;

	result = testValue;

	for(i = 0; i < 64; i++) {
		result = Bit::rotateLeft(result);
	}

	ASSERT_EQ(1, result);
}
<|endoftext|>


<commit_before>#include "Graphics.h"
#include "sfwindow.h"
#include <SFML/Graphics.hpp>
#include "utility/misc.h"

#define GRAPHICS WalrusRPG::Graphics

sf::RenderWindow window;
sf::View view;
sf::RenderTexture buffer;

void GRAPHICS::init()
{
    window.create(sf::VideoMode::getDesktopMode(), "WalrusRPG", sf::Style::Fullscreen);
    window.setVerticalSyncEnabled(true);
    window.setFramerateLimit(60);
    view = sf::View(window.getDefaultView());
    buffer.create(320, 240);
}

void GRAPHICS::deinit()
{
    window.close();
}

void GRAPHICS::frame_begin()
{
    window.clear(sf::Color::Black);
}

void GRAPHICS::frame_end()
{
    sf::Sprite sprite(buffer.getTexture());
    sf::Vector2u winsize = window.getSize();
    sf::Event event;
    float scale = min(winsize.x / 320.f, winsize.y / 240.f);

    while (window.pollEvent(event))
    {
    }

    window.setView(view = sf::View(sf::FloatRect(0, 0, winsize.x, winsize.y)));

    buffer.display();
    window.clear();
    sprite.setScale(scale, scale);
    sprite.setPosition((winsize.x - 320.f * scale) / 2, (winsize.y - 240.f * scale) / 2);
    window.draw(sprite);
    window.display();
}

void GRAPHICS::put_sprite(const Texture &sheet, int x, int y,
                          const WalrusRPG::Utils::Rect &window)
{
    sf::Sprite sprite;
    sprite.setTexture(sheet.data);
    sprite.setTextureRect(sf::IntRect(window.x, window.y, window.width, window.height));
    sprite.setPosition(x, y);
    buffer.draw(sprite);
}

void GRAPHICS::fill(const WalrusRPG::Graphics::Pixel &color)
{
    UNUSED(color);
}
<commit_msg>SFML: disable vsync for now<commit_after>#include "Graphics.h"
#include "sfwindow.h"
#include <SFML/Graphics.hpp>
#include "utility/misc.h"

#define GRAPHICS WalrusRPG::Graphics

sf::RenderWindow window;
sf::View view;
sf::RenderTexture buffer;

void GRAPHICS::init()
{
    window.create(sf::VideoMode::getDesktopMode(), "WalrusRPG", sf::Style::Fullscreen);
    window.setFramerateLimit(60);
    view = sf::View(window.getDefaultView());
    buffer.create(320, 240);
}

void GRAPHICS::deinit()
{
    window.close();
}

void GRAPHICS::frame_begin()
{
    window.clear(sf::Color::Black);
}

void GRAPHICS::frame_end()
{
    sf::Sprite sprite(buffer.getTexture());
    sf::Vector2u winsize = window.getSize();
    sf::Event event;
    float scale = min(winsize.x / 320.f, winsize.y / 240.f);

    while (window.pollEvent(event))
    {
    }

    window.setView(view = sf::View(sf::FloatRect(0, 0, winsize.x, winsize.y)));

    buffer.display();
    window.clear();
    sprite.setScale(scale, scale);
    sprite.setPosition((winsize.x - 320.f * scale) / 2, (winsize.y - 240.f * scale) / 2);
    window.draw(sprite);
    window.display();
}

void GRAPHICS::put_sprite(const Texture &sheet, int x, int y,
                          const WalrusRPG::Utils::Rect &window)
{
    sf::Sprite sprite;
    sprite.setTexture(sheet.data);
    sprite.setTextureRect(sf::IntRect(window.x, window.y, window.width, window.height));
    sprite.setPosition(x, y);
    buffer.draw(sprite);
}

void GRAPHICS::fill(const WalrusRPG::Graphics::Pixel &color)
{
    UNUSED(color);
}
<|endoftext|>


<commit_before>/*************************************************************************/
/*  godot_x11.cpp                                                        */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include <limits.h>
#include <locale.h>
#include <stdlib.h>
#include <unistd.h>

#include "main/main.h"
#include "os_x11.h"

int main(int argc, char *argv[]) {

	OS_X11 os;

	setlocale(LC_CTYPE, "");

	char *cwd = (char *)malloc(PATH_MAX);
	char *ret = getcwd(cwd, PATH_MAX);

	Error err = Main::setup(argv[0], argc - 1, &argv[1]);
	if (err != OK) {
		free(cwd);
		return 255;
	}

	if (Main::start())
		os.run(); // it is actually the OS that decides how to run
	Main::cleanup();

	if (ret)
		chdir(cwd);
	free(cwd);

	return os.get_exit_code();
}
<commit_msg>Linux: Check return value of chdir on cleanup<commit_after>/*************************************************************************/
/*  godot_x11.cpp                                                        */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include <limits.h>
#include <locale.h>
#include <stdlib.h>
#include <unistd.h>

#include "main/main.h"
#include "os_x11.h"

int main(int argc, char *argv[]) {

	OS_X11 os;

	setlocale(LC_CTYPE, "");

	char *cwd = (char *)malloc(PATH_MAX);
	char *ret = getcwd(cwd, PATH_MAX);

	Error err = Main::setup(argv[0], argc - 1, &argv[1]);
	if (err != OK) {
		free(cwd);
		return 255;
	}

	if (Main::start())
		os.run(); // it is actually the OS that decides how to run
	Main::cleanup();

	if (ret) { // Previous getcwd was successful
		if (chdir(cwd) != 0) {
			ERR_PRINT("Couldn't return to previous working directory.");
		}
	}
	free(cwd);

	return os.get_exit_code();
}
<|endoftext|>


<commit_before>/*************************************************************************/
/*  godot_x11.cpp                                                        */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur.                 */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#include <unistd.h>
#include <limits.h>

#include "main/main.h"
#include "os_x11.h"

int main(int argc, char* argv[]) {

	OS_X11 os;

	char *cwd = (char*)malloc(PATH_MAX);
	getcwd(cwd, PATH_MAX);

	Error err  = Main::setup(argv[0],argc-1,&argv[1]);
	if (err!=OK)
		return 255;

	if (Main::start())
		os.run(); // it is actually the OS that decides how to run
	Main::cleanup();

	chdir(cwd);
	free(cwd);

	return os.get_exit_code();
}
<commit_msg>Fix failing build on mageia v6 x64 linux.<commit_after>/*************************************************************************/
/*  godot_x11.cpp                                                        */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur.                 */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#include <unistd.h>
#include <limits.h>
#include <stdlib.h>

#include "main/main.h"
#include "os_x11.h"

int main(int argc, char* argv[]) {

	OS_X11 os;

	char *cwd = (char*)malloc(PATH_MAX);
	getcwd(cwd, PATH_MAX);

	Error err  = Main::setup(argv[0],argc-1,&argv[1]);
	if (err!=OK)
		return 255;

	if (Main::start())
		os.run(); // it is actually the OS that decides how to run
	Main::cleanup();

	chdir(cwd);
	free(cwd);

	return os.get_exit_code();
}
<|endoftext|>


<commit_before>/*
 * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
 *
 * 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 <iostream>
#include <fstream>
#include <boost/format.hpp>
#include <votca/csg/csgapplication.h>

using namespace votca::csg;
using namespace std;
using boost::format;

/**
    \brief class for writing dlpoly topology files

    This class encapsulates the dlpoly topology writing functions

*/

class DLPTopolApp
    : public CsgApplication
{
public:
    string ProgramName() { return "csg_dlptopol"; }
    void HelpText(ostream &out) {
        out << "Create a dlpoly topology template based on an existing (atomistic) topology and \n"
	    << "a mapping xml-file. The conventional file extensions of other simulation engines, \n"
            << "e.g. Gromacs, are recognized in the input (option --top), whereas <name>.dlpf must \n"
            << "be used for DL_POLY topology files. By convention, <name> can be omitted, in which \n"
            << "case '.dlpf' implies 'using standard naming': FIELD as input or FIELD_CGV as output. \n"
	    << "- NOTE: the created template file needs to be inspected and amended by the user!\n\n"
	    << "Examples:\n"
	    << "* csg_dlptopol --top .dlpf --out .dlpf --cg cg-map.xml\n  - convert FIELD to FIELD_CGV using cg-map.xml\n"
	    << "* csg_dlptopol --top FA-dlpoly.dlpf --out CG-dlpoly.dlpf --cg cg-map.xml\n  - convert FA-dlpoly.dlpf to CG-dlpoly.dlpf\n"
	    << "* csg_dlptopol --top FA-gromacs.tpr --out FA-dlpoly.dlpf --no-map\n  - convert FA-gromacs.tpr to FA-dlpoly.dlpf";
    }

    bool DoMapping(void) { return true; }

    void Initialize(void);
    bool EvaluateOptions(void) {
        CsgApplication::EvaluateOptions();
        CheckRequired("out", "no output topology specified");
        return true;
    }
    bool EvaluateTopology(Topology *top, Topology *top_ref);

protected:
    void WriteMoleculeAtoms(ostream &out, Molecule &cg);
    void WriteMoleculeInteractions(ostream &out, Molecule &cg);
    void WriteVDWInteractions(ostream &out, Molecule &cg);
    void WriteMolecularType(ostream &out, Molecule &cg, int nummol);
};

void DLPTopolApp::Initialize(void)
{
    CsgApplication::Initialize();
    //AddProgramOptions()
    //("top", boost::program_options::value<string>(),
    //"  input topology in any known format:\n  <name>.dlpf for dlpoly, <name>.tpr for gromacs\n  (convention: '.dlpf'='use FIELD')");
    AddProgramOptions()
      ("out", boost::program_options::value<string>(),
       "  output topology in dlpoly format; examples:\n"
       "  - <name>.dlpf, .dlpf (convention: '.dlpf'='use FIELD_CGV')");
}

bool DLPTopolApp::EvaluateTopology(Topology *top, Topology *top_ref)
{
  // check the file names from options

  string fname=OptionsMap()["top"].as<string>();

  if( fname == ".dlpf" ) {
    fname = "FIELD";
  }

  cout << "input  file-name: " << fname << endl;

  fname=OptionsMap()["out"].as<string>();

#ifdef DEBUG
  cout << "output file-name given: " << fname << endl;
#endif

  if( fname == ".dlpf" ) {
    fname = "FIELD_CGV";
  }

#ifdef DEBUG
  cout << "output file-name actual: " << fname << endl;
#else
  cout << "output file-name: " << fname << endl;
#endif

  // do CG mapping

  MoleculeContainer &mols = top->Molecules();
  MoleculeContainer MolecularTypes;
  MoleculeContainer::iterator iter;

  int prv_mol_number = 1;
  string prv_mol_name;
  vector<int> nummols;

  vector<string> vdw_pairs;

  // find all unique molecular types

  for(iter=mols.begin(); iter!=mols.end(); ++iter) {
    Molecule *mol = *iter;

    // molecules are ignored during the mapping stage
    // i.e. the ignored ones do not enter the CG topology (*top) - ?
    //if( IsIgnored(mol->getName()) ) continue;

    if( mol->getName()==prv_mol_name ) {
      prv_mol_number++;
      continue;
    }

    nummols.push_back(prv_mol_number);
    prv_mol_number = 1;
    prv_mol_name   = mol->getName();

    //#ifdef DEBUG
    cout << "'" << mol->getName() << "' added to CG molecular types" << endl;
    //#endif

    MolecularTypes.push_back(mol);

    // collect unique bead pairs over all molecular types found

    for(int ib1=0; ib1<mol->BeadCount(); ib1++) {
      string bead_name1 = mol->getBead(ib1)->getType()->getName();
      bead_name1 = bead_name1.substr(0,bead_name1.find_first_of("#")); // skip #index of atom from its name

      for(int imt=0; imt<MolecularTypes.size(); imt++) {

	for(int ib2=0; ib2<MolecularTypes[imt]->BeadCount(); ib2++) {

	  string bead_name2 = MolecularTypes[imt]->getBead(ib2)->getType()->getName();
	  bead_name2 = bead_name2.substr(0,bead_name2.find_first_of("#")); // skip #index of atom from its name

	  stringstream ss_bp1,ss_bp2;

	  ss_bp1 << format("%8s%8s" ) % bead_name1 % bead_name2;
	  ss_bp2 << format("%8s%8s" ) % bead_name2 % bead_name1;

          bool is_new_pair=true;

	  for(int ibp=0; ibp<vdw_pairs.size(); ibp++) {
	    if( ss_bp1.str()==vdw_pairs[ibp] || ss_bp2.str()==vdw_pairs[ibp] ) {
	      is_new_pair=false;
	      break;
	    }
	  }
	  if( is_new_pair ) {
	    vdw_pairs.push_back(ss_bp1.str());
#ifdef DEBUG
	    cout << "'" << ss_bp1.str() << "' added to CG vdw pairs" << endl;
#endif
	  }
	}
      }
    }
  }
  nummols.push_back(prv_mol_number);

  if(MolecularTypes.size() > 1)
    cout << "WARNING: creation of topology for multiple molecular types "
      "is experimental at this stage\n";

  ofstream fl;
  fl.open(fname.c_str());

  fl << "From VOTCA with love" << " # check/amend this file if needed!\n";
  fl << "units kJ\n";
  fl << "molecular types " << MolecularTypes.size() << endl;

  for(int i=0; i<MolecularTypes.size(); i++) {
    WriteMolecularType(fl, *(MolecularTypes[i]), nummols[i+1]);
  }

  // vdw seciton (pairwise vdw/CG interactions)

  if( vdw_pairs.size()>0 ) {

    fl << "vdw "<< vdw_pairs.size() << endl;

    for(int ibp=0; ibp<vdw_pairs.size(); ibp++) {
      fl << vdw_pairs[ibp] << " tab   1.00000  0.00000\n";
    }
  }

  fl << "close" << endl;

  cout << "Created template for dlpoly topology - please, check & amend if needed!" << endl;

  fl.close();
  return true;
}

void DLPTopolApp::WriteMoleculeAtoms(ostream &out, Molecule &cg)
{
  out << "atoms " << cg.BeadCount() << endl;
    out << "# name  mass  charge  nrept  ifrozen (optional: ngroup, index, name/type, type/residue, index/res-ID) \n";
    for(int i=0; i<cg.BeadCount(); ++i) {
        Bead *b=cg.getBead(i);

        string bname=b->getName();
        string btype=b->getType()->getName();

        bname = bname.substr(0,bname.find_first_of("#")); // skip #index of atom from its name
        btype = btype.substr(0,btype.find_first_of("#")); // skip #index of atom from its type

        out << format("%8s  %10f  %10f     1     0     1 %10d  %8s  %8s %10d \n")
            % bname % b->getM() % b->getQ() % (i+1) % btype % bname % (i+1);
	//% b->getType()->getName() % b->getM() % b->getQ() % (i+1) % b->getType()->getName() % b->getName() % (i+1);
    }
}

void DLPTopolApp::WriteMoleculeInteractions(ostream &out, Molecule &cg)
{
    InteractionContainer ics=cg.Interactions();
    vector<Interaction *>::iterator iter;

    stringstream sout;

    int n_entries = 0;
    int nb=-1;

    for(iter=ics.begin(); iter!=ics.end(); ++iter) {
        Interaction *ic = *iter;
        if(nb != ic->BeadCount()) {

	    if(sout.str()!="")
	      out << n_entries << endl << sout.str();

	    sout.str("");
	    n_entries = 0;

            nb=ic->BeadCount();
            switch(nb) {
                case 2:
		  out << "bonds ";
                    break;
                case 3:
                    out << "angles ";
                    break;
                case 4:
                    out << "dihedrals ";
                    break;
                default:
                    throw runtime_error(string("cannot handle number of beads in interaction:") +
                            ic->getName());
            }
        }
	n_entries++;
	// to do: is it possible to use bond/angle/dihedral function types for 1:1 mapping? (CG map overwrites ic->Group anyway)
        //sout << ic->getInteractionFunc(); // something like that (only for 1:1 mapping!)
        sout << " tab ";
        for(int i=0; i<nb; ++i)
	  sout << ic->getBeadId(i)+1 << " ";
        sout << "   1.00000  0.00000" << " # " << ic->getName() << endl;
        //sout << "   1.00000  0.00000" << " # " << ic->getGroup() << endl;
    }
    if(sout.str()!="") out << n_entries << endl << sout.str();
}

void DLPTopolApp::WriteMolecularType(ostream &out, Molecule &cg, int nummol)
{
    out << cg.getName() << endl;
    out << "nummols " << nummol << endl;

    WriteMoleculeAtoms(out, cg);
    WriteMoleculeInteractions(out, cg);

    out << "finish" << endl;
}

int main(int argc, char** argv)
{
    DLPTopolApp app;
    return app.Exec(argc, argv);
}

<commit_msg>csg_dlptopol: shorten help<commit_after>/*
 * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
 *
 * 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 <iostream>
#include <fstream>
#include <boost/format.hpp>
#include <votca/csg/csgapplication.h>

using namespace votca::csg;
using namespace std;
using boost::format;

/**
    \brief class for writing dlpoly topology files

    This class encapsulates the dlpoly topology writing functions

*/

class DLPTopolApp
    : public CsgApplication
{
public:
    string ProgramName() { return "csg_dlptopol"; }
    void HelpText(ostream &out) {
        out << "Create a dlpoly topology template based on an existing (atomistic) topology and \n"
	    << "a mapping xml-file. The created template file needs to be inspected and amended by the user!\n\n"
	    << "Examples:\n"
	    << "* csg_dlptopol --top .dlpf --out .dlpf --cg cg-map.xml\n  convert FIELD to FIELD_CGV using cg-map.xml\n"
	    << "* csg_dlptopol --top FA-dlpoly.dlpf --out CG-dlpoly.dlpf --cg cg-map.xml\n"
	    << "* csg_dlptopol --top FA-gromacs.tpr --out FA-dlpoly.dlpf --no-map\n";
    }

    bool DoMapping(void) { return true; }

    void Initialize(void);
    bool EvaluateOptions(void) {
        CsgApplication::EvaluateOptions();
        CheckRequired("out", "no output topology specified");
        return true;
    }
    bool EvaluateTopology(Topology *top, Topology *top_ref);

protected:
    void WriteMoleculeAtoms(ostream &out, Molecule &cg);
    void WriteMoleculeInteractions(ostream &out, Molecule &cg);
    void WriteVDWInteractions(ostream &out, Molecule &cg);
    void WriteMolecularType(ostream &out, Molecule &cg, int nummol);
};

void DLPTopolApp::Initialize(void)
{
    CsgApplication::Initialize();
    //AddProgramOptions()
    //("top", boost::program_options::value<string>(),
    //"  input topology in any known format:\n  <name>.dlpf for dlpoly, <name>.tpr for gromacs\n  (convention: '.dlpf'='use FIELD')");
    AddProgramOptions()
      ("out", boost::program_options::value<string>(),
       "  output topology in dlpoly format");
}

bool DLPTopolApp::EvaluateTopology(Topology *top, Topology *top_ref)
{
  // check the file names from options

  string fname=OptionsMap()["top"].as<string>();

  if( fname == ".dlpf" ) {
    fname = "FIELD";
  }

  cout << "input  file-name: " << fname << endl;

  fname=OptionsMap()["out"].as<string>();

#ifdef DEBUG
  cout << "output file-name given: " << fname << endl;
#endif

  if( fname == ".dlpf" ) {
    fname = "FIELD_CGV";
  }

#ifdef DEBUG
  cout << "output file-name actual: " << fname << endl;
#else
  cout << "output file-name: " << fname << endl;
#endif

  // do CG mapping

  MoleculeContainer &mols = top->Molecules();
  MoleculeContainer MolecularTypes;
  MoleculeContainer::iterator iter;

  int prv_mol_number = 1;
  string prv_mol_name;
  vector<int> nummols;

  vector<string> vdw_pairs;

  // find all unique molecular types

  for(iter=mols.begin(); iter!=mols.end(); ++iter) {
    Molecule *mol = *iter;

    // molecules are ignored during the mapping stage
    // i.e. the ignored ones do not enter the CG topology (*top) - ?
    //if( IsIgnored(mol->getName()) ) continue;

    if( mol->getName()==prv_mol_name ) {
      prv_mol_number++;
      continue;
    }

    nummols.push_back(prv_mol_number);
    prv_mol_number = 1;
    prv_mol_name   = mol->getName();

    //#ifdef DEBUG
    cout << "'" << mol->getName() << "' added to CG molecular types" << endl;
    //#endif

    MolecularTypes.push_back(mol);

    // collect unique bead pairs over all molecular types found

    for(int ib1=0; ib1<mol->BeadCount(); ib1++) {
      string bead_name1 = mol->getBead(ib1)->getType()->getName();
      bead_name1 = bead_name1.substr(0,bead_name1.find_first_of("#")); // skip #index of atom from its name

      for(int imt=0; imt<MolecularTypes.size(); imt++) {

	for(int ib2=0; ib2<MolecularTypes[imt]->BeadCount(); ib2++) {

	  string bead_name2 = MolecularTypes[imt]->getBead(ib2)->getType()->getName();
	  bead_name2 = bead_name2.substr(0,bead_name2.find_first_of("#")); // skip #index of atom from its name

	  stringstream ss_bp1,ss_bp2;

	  ss_bp1 << format("%8s%8s" ) % bead_name1 % bead_name2;
	  ss_bp2 << format("%8s%8s" ) % bead_name2 % bead_name1;

          bool is_new_pair=true;

	  for(int ibp=0; ibp<vdw_pairs.size(); ibp++) {
	    if( ss_bp1.str()==vdw_pairs[ibp] || ss_bp2.str()==vdw_pairs[ibp] ) {
	      is_new_pair=false;
	      break;
	    }
	  }
	  if( is_new_pair ) {
	    vdw_pairs.push_back(ss_bp1.str());
#ifdef DEBUG
	    cout << "'" << ss_bp1.str() << "' added to CG vdw pairs" << endl;
#endif
	  }
	}
      }
    }
  }
  nummols.push_back(prv_mol_number);

  if(MolecularTypes.size() > 1)
    cout << "WARNING: creation of topology for multiple molecular types "
      "is experimental at this stage\n";

  ofstream fl;
  fl.open(fname.c_str());

  fl << "From VOTCA with love" << " # check/amend this file if needed!\n";
  fl << "units kJ\n";
  fl << "molecular types " << MolecularTypes.size() << endl;

  for(int i=0; i<MolecularTypes.size(); i++) {
    WriteMolecularType(fl, *(MolecularTypes[i]), nummols[i+1]);
  }

  // vdw seciton (pairwise vdw/CG interactions)

  if( vdw_pairs.size()>0 ) {

    fl << "vdw "<< vdw_pairs.size() << endl;

    for(int ibp=0; ibp<vdw_pairs.size(); ibp++) {
      fl << vdw_pairs[ibp] << " tab   1.00000  0.00000\n";
    }
  }

  fl << "close" << endl;

  cout << "Created template for dlpoly topology - please, check & amend if needed!" << endl;

  fl.close();
  return true;
}

void DLPTopolApp::WriteMoleculeAtoms(ostream &out, Molecule &cg)
{
  out << "atoms " << cg.BeadCount() << endl;
    out << "# name  mass  charge  nrept  ifrozen (optional: ngroup, index, name/type, type/residue, index/res-ID) \n";
    for(int i=0; i<cg.BeadCount(); ++i) {
        Bead *b=cg.getBead(i);

        string bname=b->getName();
        string btype=b->getType()->getName();

        bname = bname.substr(0,bname.find_first_of("#")); // skip #index of atom from its name
        btype = btype.substr(0,btype.find_first_of("#")); // skip #index of atom from its type

        out << format("%8s  %10f  %10f     1     0     1 %10d  %8s  %8s %10d \n")
            % bname % b->getM() % b->getQ() % (i+1) % btype % bname % (i+1);
	//% b->getType()->getName() % b->getM() % b->getQ() % (i+1) % b->getType()->getName() % b->getName() % (i+1);
    }
}

void DLPTopolApp::WriteMoleculeInteractions(ostream &out, Molecule &cg)
{
    InteractionContainer ics=cg.Interactions();
    vector<Interaction *>::iterator iter;

    stringstream sout;

    int n_entries = 0;
    int nb=-1;

    for(iter=ics.begin(); iter!=ics.end(); ++iter) {
        Interaction *ic = *iter;
        if(nb != ic->BeadCount()) {

	    if(sout.str()!="")
	      out << n_entries << endl << sout.str();

	    sout.str("");
	    n_entries = 0;

            nb=ic->BeadCount();
            switch(nb) {
                case 2:
		  out << "bonds ";
                    break;
                case 3:
                    out << "angles ";
                    break;
                case 4:
                    out << "dihedrals ";
                    break;
                default:
                    throw runtime_error(string("cannot handle number of beads in interaction:") +
                            ic->getName());
            }
        }
	n_entries++;
	// to do: is it possible to use bond/angle/dihedral function types for 1:1 mapping? (CG map overwrites ic->Group anyway)
        //sout << ic->getInteractionFunc(); // something like that (only for 1:1 mapping!)
        sout << " tab ";
        for(int i=0; i<nb; ++i)
	  sout << ic->getBeadId(i)+1 << " ";
        sout << "   1.00000  0.00000" << " # " << ic->getName() << endl;
        //sout << "   1.00000  0.00000" << " # " << ic->getGroup() << endl;
    }
    if(sout.str()!="") out << n_entries << endl << sout.str();
}

void DLPTopolApp::WriteMolecularType(ostream &out, Molecule &cg, int nummol)
{
    out << cg.getName() << endl;
    out << "nummols " << nummol << endl;

    WriteMoleculeAtoms(out, cg);
    WriteMoleculeInteractions(out, cg);

    out << "finish" << endl;
}

int main(int argc, char** argv)
{
    DLPTopolApp app;
    return app.Exec(argc, argv);
}

<|endoftext|>


<commit_before>#include <atomic>
#include "../shell.h"
#include "../coroutine.h"
#include <teelogging/teelogging.h>
#include <gtest/gtest.h>

class CoroTest : testing::Test { };

using namespace cu;

TEST(CoroTest, Test_run_ls_strip_quote_grep)
{
	cmd(
			  run("ls .")
			, strip()
			, quote()
			, grep("shell_exe")
			, assert_count(1)
			, assert_string("\"shell_exe\"")
	);

	cmd(
			  ls(".")
			, strip()
			, quote()
			, grep("shell_exe")
			, assert_count(1)
			, assert_string("\"shell_exe\"")
	);
}

TEST(CoroTest, Test_run_ls_sort_grep_uniq_join)
{
	std::string out_subproces;
	cmd(run("ls ."), strip(), sort(), grep("libfes|libasyncply"), uniq(), join(), out(out_subproces));
	//
	std::string out_ls;
	cmd(ls("."), sort(), grep("libfes|libasyncply"), uniq(), join(), out(out_ls));
	//
	ASSERT_STREQ(out_subproces.c_str(), out_ls.c_str());
}

TEST(CoroTest, TestCut)
{
	cmd(
			  in("hello big world")
			, assert_count(1)
			, split()
			, assert_count(3)
			, join()
			, assert_count(1)
			, cut(0)
			, assert_count(1)
			, assert_string("hello")
	);
	cmd(
			  in("hello big world")
			, assert_count(1)
			, split()
			, assert_count(3)
			, join()
			, assert_count(1)
			, cut(1)
			, assert_count(1)
			, assert_string("big")
	);
	cmd(
			  in("hello big world")
			, assert_count(1)
			, split()
			, assert_count(3)
			, join()
			, assert_count(1)
			, cut(2)
			, assert_count(1)
			, assert_string("world")
	);
}

TEST(CoroTest, TestGrep)
{
	cmd(
			  in("line1\nline2\nline3")
			, split("\n")
			, assert_count(3)
			, grep("line2")
			, assert_count(1)
			, assert_string("line2")
	);
}

TEST(CoroTest, TestGrep2)
{
	cmd(
			  in("line1\nline2\nline3\n")
			, split("\n")
			, assert_count(4)
	);
}

namespace cu {

class scheduler {
public:
	using control_type = void;

	template <typename Function>
	void spawn(Function&& func)
	{
		_running.emplace_back(cu::make_generator<control_type>(
			[f = std::move(func)](auto& yield) {
				yield();
				f(yield);
			}
		));
	}

	/*
	return true if any is updated
	*/
	bool run()
	{
		bool any_updated = false;
		_pid = 0;
		LOGD("total = %d", _running.size());

		auto i = std::begin(_running);
		while (i != std::end(_running)) {
			LOGD("ticking = %d", getpid());
			auto c = *i;
			if(*c)
			{
				_move_to_blocked = false;
				(*c)();
				any_updated = true;
			}
			++_pid;
			if (move_to_blocked)
			{
				_blocked.emplace_back(std::move(c));
				i = inv.erase(i);
			}
			else
			{
				++i;
			}
		}

		return any_updated;
	}

	/*
	return true if have pending work
	*/
	// run_forever()
	// run_until_complete()
	void run_until_complete()
	{
		bool any_updated = true;
		while(any_updated)
		{
			any_updated = run();
		}
	}

	void run_forever()
	{
		while(true)
		{
			run();
		}
	}

	int getpid() const {return _pid;}

	inline void lock()
	{
		_move_to_blocked = true;
	}

	// auto create_semaphore();

	// each semaphore have 2 channels and ret code

protected:
	// normal running
	std::vector<cu::pull_type_ptr<control_type> > _running;
	// locked
	std::vector<cu::pull_type_ptr<control_type> > _blocked;
private:
	int _pid;
	bool _move_to_blocked;
};

class semaphore
{
public:
	explicit semaphore(scheduler& sche, int count = 0, int count_max = 1)
		: _sche(sche)
		, _count(count)
		, _count_max(count_max)
	{
		assert((1 <= count_max) || (0 <= count));
		assert(count <= count_max);
	}

	///
	/// Reduce el valor del semaforo. Bloquea la regi�n critica. Esta operaci�n tiene m�ltiples
	/// nombres.
	///  * wait (s)
	///	 * {
	///		  if s > 0
	///				s--
	///		  else // s == 0
	///				bloqueo
	///		}
	///
	///		esperar / wait / lock / down / sleep / P
	///
	inline void lock()
	{
		if(_count > 0)
		{
			--_count;
		}
		else
		{
			// bloquear esta cpproutine
			_sche.lock(); // (*this)
		}
	}
	///
	/// Aumenta el semaforo. Libera la region critica.
	///    signal(s)
	///    {
	///        if s == 0
	///            s++
	///        else // s > 0
	///            if s < MAX
	///                s++
	///    }
	///
	///	avisar / signal / unlock / up / wakeup / release / V
	///
	inline void unlock()
	{
		if((_count == 0) || (_count < _count_max))
		{
			++_count;
		}
		else
		{
			// ejecutar al primero que se bloqueo
		}
	}
protected:
	scheduler& _sche;
	int _count;
	int _count_max;
};

}

TEST(CoroTest, TestScheduler)
{
	const int N = 16;
	cu::scheduler sch;
	for(int i=0; i<N; ++i)
	{
		sch.spawn([&sch, i](auto& yield) {
			std::cout << "create " << i << " - pid: " << sch.getpid() << std::endl;
			yield();
			std::cout << "download " << i << " - pid: " << sch.getpid() << std::endl;
			yield();
			std::cout << "patching " << i << " - pid: " << sch.getpid() << std::endl;
			yield();
			if(i == 5)
			{
				sch.lock();
			}
			std::cout << "compile " << i << " - pid: " << sch.getpid() << std::endl;
			yield();
			std::cout << "tests " << i << " - pid: " << sch.getpid() << std::endl;
			yield();
			std::cout << "packing " << i << " - pid: " << sch.getpid() << std::endl;
			yield();
			std::cout << "destroy " << i << " - pid: " << sch.getpid() << std::endl;
		});
	}
	sch.run_until_complete();
}

<commit_msg>Update test_shell.cpp<commit_after>#include <atomic>
#include "../shell.h"
#include "../coroutine.h"
#include <teelogging/teelogging.h>
#include <gtest/gtest.h>

class CoroTest : testing::Test { };

using namespace cu;

TEST(CoroTest, Test_run_ls_strip_quote_grep)
{
	cmd(
			  run("ls .")
			, strip()
			, quote()
			, grep("shell_exe")
			, assert_count(1)
			, assert_string("\"shell_exe\"")
	);

	cmd(
			  ls(".")
			, strip()
			, quote()
			, grep("shell_exe")
			, assert_count(1)
			, assert_string("\"shell_exe\"")
	);
}

TEST(CoroTest, Test_run_ls_sort_grep_uniq_join)
{
	std::string out_subproces;
	cmd(run("ls ."), strip(), sort(), grep("libfes|libasyncply"), uniq(), join(), out(out_subproces));
	//
	std::string out_ls;
	cmd(ls("."), sort(), grep("libfes|libasyncply"), uniq(), join(), out(out_ls));
	//
	ASSERT_STREQ(out_subproces.c_str(), out_ls.c_str());
}

TEST(CoroTest, TestCut)
{
	cmd(
			  in("hello big world")
			, assert_count(1)
			, split()
			, assert_count(3)
			, join()
			, assert_count(1)
			, cut(0)
			, assert_count(1)
			, assert_string("hello")
	);
	cmd(
			  in("hello big world")
			, assert_count(1)
			, split()
			, assert_count(3)
			, join()
			, assert_count(1)
			, cut(1)
			, assert_count(1)
			, assert_string("big")
	);
	cmd(
			  in("hello big world")
			, assert_count(1)
			, split()
			, assert_count(3)
			, join()
			, assert_count(1)
			, cut(2)
			, assert_count(1)
			, assert_string("world")
	);
}

TEST(CoroTest, TestGrep)
{
	cmd(
			  in("line1\nline2\nline3")
			, split("\n")
			, assert_count(3)
			, grep("line2")
			, assert_count(1)
			, assert_string("line2")
	);
}

TEST(CoroTest, TestGrep2)
{
	cmd(
			  in("line1\nline2\nline3\n")
			, split("\n")
			, assert_count(4)
	);
}

namespace cu {

class scheduler {
public:
	using control_type = void;

	template <typename Function>
	void spawn(Function&& func)
	{
		_running.emplace_back(cu::make_generator<control_type>(
			[f = std::move(func)](auto& yield) {
				yield();
				f(yield);
			}
		));
	}

	/*
	return true if any is updated
	*/
	bool run()
	{
		bool any_updated = false;
		_pid = 0;
		LOGD("total = %d", _running.size());

		auto i = std::begin(_running);
		while (i != std::end(_running))
		{
			LOGD("ticking = %d", getpid());
			auto c = *i;
			if(*c)
			{
				_move_to_blocked = false;
				(*c)();
				any_updated = true;
			}
			++_pid;
			if (move_to_blocked)
			{
				_blocked.emplace_back(std::move(c));
				i = inv.erase(i);
			}
			else
			{
				++i;
			}
		}

		return any_updated;
	}

	/*
	return true if have pending work
	*/
	// run_forever()
	// run_until_complete()
	void run_until_complete()
	{
		bool any_updated = true;
		while(any_updated)
		{
			any_updated = run();
		}
	}

	void run_forever()
	{
		while(true)
		{
			run();
		}
	}

	int getpid() const {return _pid;}

	inline void lock()
	{
		_move_to_blocked = true;
	}

	// auto create_semaphore();

	// each semaphore have 2 channels and ret code

protected:
	// normal running
	std::vector<cu::pull_type_ptr<control_type> > _running;
	// locked
	std::vector<cu::pull_type_ptr<control_type> > _blocked;
private:
	int _pid;
	bool _move_to_blocked;
};

class semaphore
{
public:
	explicit semaphore(scheduler& sche, int count = 0, int count_max = 1)
		: _sche(sche)
		, _count(count)
		, _count_max(count_max)
	{
		assert((1 <= count_max) || (0 <= count));
		assert(count <= count_max);
	}

	///
	/// Reduce el valor del semaforo. Bloquea la regi�n critica. Esta operaci�n tiene m�ltiples
	/// nombres.
	///  * wait (s)
	///	 * {
	///		  if s > 0
	///				s--
	///		  else // s == 0
	///				bloqueo
	///		}
	///
	///		esperar / wait / lock / down / sleep / P
	///
	inline void lock()
	{
		if(_count > 0)
		{
			--_count;
		}
		else
		{
			// bloquear esta cpproutine
			_sche.lock(); // (*this)
		}
	}
	///
	/// Aumenta el semaforo. Libera la region critica.
	///    signal(s)
	///    {
	///        if s == 0
	///            s++
	///        else // s > 0
	///            if s < MAX
	///                s++
	///    }
	///
	///	avisar / signal / unlock / up / wakeup / release / V
	///
	inline void unlock()
	{
		if((_count == 0) || (_count < _count_max))
		{
			++_count;
		}
		else
		{
			// ejecutar al primero que se bloqueo
		}
	}
protected:
	scheduler& _sche;
	int _count;
	int _count_max;
};

}

TEST(CoroTest, TestScheduler)
{
	const int N = 16;
	cu::scheduler sch;
	semaphore sem(sch);
	for(int i=0; i<N; ++i)
	{
		sch.spawn([&sch, &sem, i](auto& yield) {
			std::cout << "create " << i << " - pid: " << sch.getpid() << std::endl;
			yield();
			std::cout << "download " << i << " - pid: " << sch.getpid() << std::endl;
			yield();
			std::cout << "patching " << i << " - pid: " << sch.getpid() << std::endl;
			yield();
			if(i == 5)
			{
				sem.lock();
			}
			std::cout << "compile " << i << " - pid: " << sch.getpid() << std::endl;
			yield();
			std::cout << "tests " << i << " - pid: " << sch.getpid() << std::endl;
			yield();
			std::cout << "packing " << i << " - pid: " << sch.getpid() << std::endl;
			yield();
			std::cout << "destroy " << i << " - pid: " << sch.getpid() << std::endl;
			if(i == 5)
			{
				sem.unlock();
			}
		});
	}
	sch.run_until_complete();
}

<|endoftext|>