<commit_before>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/xml/ListOfUnsupportedAnnotations.cpp,v $
//   $Revision: 1.1 $
//   $Name:  $
//   $Author: shoops $
//   $Date: 2012/05/25 12:13:29 $
// End CVS Header

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

/*
 * ListOfUnsupportedAnnotations.cpp
 *
 *  Created on: May 24, 2012
 *      Author: shoops
 */

#include "copasi.h"

#include "CExpat.h"
#include "CCopasiXMLParser.h"
#include "CCopasiXMLInterface.h"

#define START_ELEMENT   -1
#define UNKNOWN_ELEMENT -2

CCopasiXMLParser::UnsupportedAnnotationElement::UnsupportedAnnotationElement(CCopasiXMLParser & parser,
    SCopasiXMLParserCommon & common):
    CXMLElementHandler< CCopasiXMLParser, SCopasiXMLParserCommon >(parser, common),
    mName(),
    mXML(),
    mLevel(0),
    mElementEmpty()
{}

// virtual
CCopasiXMLParser::UnsupportedAnnotationElement::~UnsupportedAnnotationElement()
{}

// virtual
void CCopasiXMLParser::UnsupportedAnnotationElement::start(const XML_Char *pszName,
    const XML_Char **papszAttrs)
{
  mCurrentElement++; /* We should always be on the next element */
  const XML_Char ** ppAttrs;

  if (mLevel) mCurrentElement = Content;

  switch (mCurrentElement)
    {
      case UnsupportedAnnotation:

        if (strcmp(pszName, "UnsupportedAnnotation"))
          CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 10,
                         pszName, "UnsupportedAnnotation", mParser.getCurrentLineNumber());

        mName = mParser.getAttributeValue("name", papszAttrs);
        mXML.str("");
        mLevel = 0;
        mParser.enableCharacterDataHandler();
        mElementEmpty.push(false);
        break;

      case Content:

        if (mElementEmpty.top() == true)
          {
            mXML << ">";
            mElementEmpty.top() = false;
          }

        mXML << CCopasiXMLInterface::encode(mParser.getCharacterData(), CCopasiXMLInterface::character);
        mXML << "<" << pszName;

        for (ppAttrs = papszAttrs; *ppAttrs && **ppAttrs; ppAttrs += 2)
          mXML << " " << *ppAttrs << "=\""
          << CCopasiXMLInterface::encode(*(ppAttrs + 1), CCopasiXMLInterface::attribute) << "\"";

        mLevel++;
        mElementEmpty.push(true);

        mParser.enableCharacterDataHandler();
        break;

      default:
        mLastKnownElement = mCurrentElement - 1;
        mCurrentElement = UNKNOWN_ELEMENT;
        mParser.pushElementHandler(&mParser.mUnknownElement);
        mParser.onStartElement(pszName, papszAttrs);
        break;
    }

  return;
}

// virtual
void CCopasiXMLParser::UnsupportedAnnotationElement::end(const XML_Char *pszName)
{
  std::string XML;

  switch (mCurrentElement)
    {
      case UnsupportedAnnotation:

        if (strcmp(pszName, "UnsupportedAnnotation"))
          CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 11,
                         pszName, "UnsupportedAnnotation", mParser.getCurrentLineNumber());

        mXML << CCopasiXMLInterface::encode(mParser.getCharacterData(), CCopasiXMLInterface::character);

        XML = mXML.str();

        {
          // remove leading whitepsaces
          std::string::size_type pos = XML.find_first_not_of("\x0a\x0d\t ");

          if (pos != 0) XML.erase(0, pos);

          // remove trailing whitepsace
          pos = XML.find_last_not_of("\x0a\x0d\t ");

          if (pos < XML.length())
            XML = XML.substr(0, pos + 1);
        }

        mXML.str(XML);

        mParser.popElementHandler();
        mCurrentElement = START_ELEMENT;
        mElementEmpty.pop();

        deleteCurrentHandler();

        /* Tell the parent element we are done. */
        mParser.onEndElement(pszName);
        break;

      case Content:
        XML = mParser.getCharacterData();

        // Check whether and how we need to close the element
        if (mElementEmpty.top() == true)
          {
            if (XML != "")
              {
                mElementEmpty.top() = false;
                mXML << ">";
              }
            else
              mXML << " />";
          }

        if (XML != "")
          mXML << CCopasiXMLInterface::encode(XML, CCopasiXMLInterface::character);

        if (mElementEmpty.top() == false)
          mXML << "</" << pszName << ">";

        mElementEmpty.pop();
        mElementEmpty.top() = false;
        mLevel--;

        if (!mLevel) mCurrentElement = UnsupportedAnnotation;

        mParser.enableCharacterDataHandler();
        break;

      case UNKNOWN_ELEMENT:
        mCurrentElement = mLastKnownElement;
        break;

      default:
        CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 11,
                       pszName, "???", mParser.getCurrentLineNumber());
        break;
    }

  return;
}

const std::string & CCopasiXMLParser::UnsupportedAnnotationElement::getName() const
{
  return mName;
}

std::string CCopasiXMLParser::UnsupportedAnnotationElement::getXML() const
{
  return mXML.str();
}

CCopasiXMLParser::ListOfUnsupportedAnnotationsElement::ListOfUnsupportedAnnotationsElement(CCopasiXMLParser & parser,
    SCopasiXMLParserCommon & common):
    CXMLElementHandler< CCopasiXMLParser, SCopasiXMLParserCommon >(parser, common),
    mUnsupportedAnnotations(),
    mpUnsupportedAnnotationElement(NULL)
{}

// virtual
CCopasiXMLParser::ListOfUnsupportedAnnotationsElement::~ListOfUnsupportedAnnotationsElement()
{
  pdelete(mpUnsupportedAnnotationElement);
}

// virtual
void CCopasiXMLParser::ListOfUnsupportedAnnotationsElement::start(const XML_Char *pszName,
    const XML_Char **papszAttrs)
{
  mpCurrentHandler = NULL;
  mCurrentElement = mLastKnownElement;

  while (mpCurrentHandler == NULL)
    {
      mCurrentElement++; /* We should always be on the next element */

      switch (mCurrentElement)
        {
          case ListOfUnsupportedAnnotations:

            if (strcmp(pszName, "ListOfUnsupportedAnnotations"))
              CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 10,
                             pszName, "ListOfUnsupportedAnnotations", mParser.getCurrentLineNumber());

            mLastKnownElement = ListOfUnsupportedAnnotations;
            mUnsupportedAnnotations.clear();

            return;

          case UnsupportedAnnotation:

            if (!strcmp(pszName, "UnsupportedAnnotation"))
              {
                /* If we do not have a ModelParameterSet element handler we create one. */
                if (!mpUnsupportedAnnotationElement)
                  mpUnsupportedAnnotationElement = new UnsupportedAnnotationElement(mParser, mCommon);

                mpCurrentHandler = mpUnsupportedAnnotationElement;
              }

            break;

          default:
            mCurrentElement = UNKNOWN_ELEMENT;
            mpCurrentHandler = &mParser.mUnknownElement;
            break;
        }
    }

  mParser.pushElementHandler(mpCurrentHandler);

  if (mpCurrentHandler != &mParser.mUnknownElement)
    {
      mLastKnownElement = mCurrentElement;
    }

  mParser.onStartElement(pszName, papszAttrs);
}

// virtual
void CCopasiXMLParser::ListOfUnsupportedAnnotationsElement::end(const XML_Char *pszName)
{
  switch (mCurrentElement)
    {
      case ListOfUnsupportedAnnotations:

        if (strcmp(pszName, "ListOfUnsupportedAnnotations"))
          CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 11,
                         pszName, "ListOfUnsupportedAnnotations", mParser.getCurrentLineNumber());

        mParser.popElementHandler();
        mCurrentElement = START_ELEMENT;

        /* Tell the parent element we are done. */
        mParser.onEndElement(pszName);
        break;

      case UnsupportedAnnotation:

        if (strcmp(pszName, "UnsupportedAnnotation"))
          CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 11,
                         pszName, "UnsupportedAnnotation", mParser.getCurrentLineNumber());

        if (mpUnsupportedAnnotationElement != NULL)
          {
            mUnsupportedAnnotations[mpUnsupportedAnnotationElement->getName()] =
              mpUnsupportedAnnotationElement->getXML();
          }

        mCurrentElement = ListOfUnsupportedAnnotations;
        break;

      case UNKNOWN_ELEMENT:
        mCurrentElement = mLastKnownElement;
        break;

      default:
        CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 11,
                       pszName, "???", mParser.getCurrentLineNumber());
        break;
    }

  return;
}

const CAnnotation::UnsupportedAnnotation & CCopasiXMLParser::ListOfUnsupportedAnnotationsElement::getUnsupportedAnnotations() const
{
  return mUnsupportedAnnotations;
}
<commit_msg>- first attempt of fixing the issue of reading unsupported annotations<commit_after>// Copyright (C) 2012 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

/*
 * ListOfUnsupportedAnnotations.cpp
 *
 *  Created on: May 24, 2012
 *      Author: shoops
 */

#include "copasi.h"

#include "CExpat.h"
#include "CCopasiXMLParser.h"
#include "CCopasiXMLInterface.h"

#define START_ELEMENT   -1
#define UNKNOWN_ELEMENT -2

CCopasiXMLParser::UnsupportedAnnotationElement::UnsupportedAnnotationElement(CCopasiXMLParser & parser,
    SCopasiXMLParserCommon & common):
  CXMLElementHandler< CCopasiXMLParser, SCopasiXMLParserCommon >(parser, common),
  mName(),
  mXML(),
  mLevel(0),
  mElementEmpty()
{}

// virtual
CCopasiXMLParser::UnsupportedAnnotationElement::~UnsupportedAnnotationElement()
{}

// virtual
void CCopasiXMLParser::UnsupportedAnnotationElement::start(const XML_Char *pszName,
    const XML_Char **papszAttrs)
{
  mCurrentElement++; /* We should always be on the next element */
  const XML_Char ** ppAttrs;

  if (mLevel) mCurrentElement = Content;

  switch (mCurrentElement)
    {
      case UnsupportedAnnotation:

        if (strcmp(pszName, "UnsupportedAnnotation"))
          CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 10,
                         pszName, "UnsupportedAnnotation", mParser.getCurrentLineNumber());

        mName = mParser.getAttributeValue("name", papszAttrs);
        mXML.str("");
        mLevel = 0;
        mParser.enableCharacterDataHandler();
        mElementEmpty.push(false);
        break;

      case Content:

        if (mElementEmpty.top() == true)
          {
            mXML << ">";
            mElementEmpty.top() = false;
          }

        mXML << CCopasiXMLInterface::encode(mParser.getCharacterData(), CCopasiXMLInterface::character);
        mXML << "<" << pszName;

        for (ppAttrs = papszAttrs; *ppAttrs && **ppAttrs; ppAttrs += 2)
          mXML << " " << *ppAttrs << "=\""
               << CCopasiXMLInterface::encode(*(ppAttrs + 1), CCopasiXMLInterface::attribute) << "\"";

        mLevel++;
        mElementEmpty.push(true);

        mParser.enableCharacterDataHandler();
        break;

      default:
        mLastKnownElement = mCurrentElement - 1;
        mCurrentElement = UNKNOWN_ELEMENT;
        mParser.pushElementHandler(&mParser.mUnknownElement);
        mParser.onStartElement(pszName, papszAttrs);
        break;
    }

  return;
}

// virtual
void CCopasiXMLParser::UnsupportedAnnotationElement::end(const XML_Char *pszName)
{
  std::string XML;

  switch (mCurrentElement)
    {
      case UnsupportedAnnotation:

        if (strcmp(pszName, "UnsupportedAnnotation"))
          CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 11,
                         pszName, "UnsupportedAnnotation", mParser.getCurrentLineNumber());

        mXML << CCopasiXMLInterface::encode(mParser.getCharacterData(), CCopasiXMLInterface::character);

        XML = mXML.str();

        {
          // remove leading whitepsaces
          std::string::size_type pos = XML.find_first_not_of("\x0a\x0d\t ");

          if (pos != 0) XML.erase(0, pos);

          // remove trailing whitepsace
          pos = XML.find_last_not_of("\x0a\x0d\t ");

          if (pos < XML.length())
            XML = XML.substr(0, pos + 1);
        }

        mXML.str(XML);

        mParser.popElementHandler();
        mCurrentElement = START_ELEMENT;
        mElementEmpty.pop();

        deleteCurrentHandler();

        /* Tell the parent element we are done. */
        mParser.onEndElement(pszName);
        break;

      case Content:
        XML = mParser.getCharacterData();

        // Check whether and how we need to close the element
        if (mElementEmpty.top() == true)
          {
            if (XML != "")
              {
                mElementEmpty.top() = false;
                mXML << ">";
              }
            else
              mXML << " />";
          }

        if (XML != "")
          mXML << CCopasiXMLInterface::encode(XML, CCopasiXMLInterface::character);

        if (mElementEmpty.top() == false)
          mXML << "</" << pszName << ">";

        mElementEmpty.pop();
        mElementEmpty.top() = false;
        mLevel--;

        if (!mLevel) mCurrentElement = UnsupportedAnnotation;

        mParser.enableCharacterDataHandler();
        break;

      case UNKNOWN_ELEMENT:
        mCurrentElement = mLastKnownElement;
        break;

      default:
        CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 11,
                       pszName, "???", mParser.getCurrentLineNumber());
        break;
    }

  return;
}

const std::string & CCopasiXMLParser::UnsupportedAnnotationElement::getName() const
{
  return mName;
}

std::string CCopasiXMLParser::UnsupportedAnnotationElement::getXML() const
{
  return mXML.str();
}

CCopasiXMLParser::ListOfUnsupportedAnnotationsElement::ListOfUnsupportedAnnotationsElement(CCopasiXMLParser & parser,
    SCopasiXMLParserCommon & common):
  CXMLElementHandler< CCopasiXMLParser, SCopasiXMLParserCommon >(parser, common),
  mUnsupportedAnnotations(),
  mpUnsupportedAnnotationElement(NULL)
{}

// virtual
CCopasiXMLParser::ListOfUnsupportedAnnotationsElement::~ListOfUnsupportedAnnotationsElement()
{
  pdelete(mpUnsupportedAnnotationElement);
}

// virtual
void CCopasiXMLParser::ListOfUnsupportedAnnotationsElement::start(const XML_Char *pszName,
    const XML_Char **papszAttrs)
{
  mpCurrentHandler = NULL;
  mCurrentElement = mLastKnownElement;

  while (mpCurrentHandler == NULL)
    {
      mCurrentElement++; /* We should always be on the next element */

      switch (mCurrentElement)
        {
          case ListOfUnsupportedAnnotations:

            if (strcmp(pszName, "ListOfUnsupportedAnnotations"))
              CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 10,
                             pszName, "ListOfUnsupportedAnnotations", mParser.getCurrentLineNumber());

            mLastKnownElement = ListOfUnsupportedAnnotations;
            mUnsupportedAnnotations.clear();

            return;

          case UnsupportedAnnotation:

            if (!strcmp(pszName, "UnsupportedAnnotation"))
              {
                /* If we do not have a ModelParameterSet element handler we create one. */
                if (!mpUnsupportedAnnotationElement)
                  mpUnsupportedAnnotationElement = new UnsupportedAnnotationElement(mParser, mCommon);

                mpCurrentHandler = mpUnsupportedAnnotationElement;
              }

            break;

          default:
            mCurrentElement = UNKNOWN_ELEMENT;
            mpCurrentHandler = &mParser.mUnknownElement;
            break;
        }
    }

  mParser.pushElementHandler(mpCurrentHandler);

  if (mpCurrentHandler != &mParser.mUnknownElement)
    {
      mLastKnownElement = mCurrentElement;
    }

  mParser.onStartElement(pszName, papszAttrs);
}

// virtual
void CCopasiXMLParser::ListOfUnsupportedAnnotationsElement::end(const XML_Char *pszName)
{
  switch (mCurrentElement)
    {
      case ListOfUnsupportedAnnotations:

        if (strcmp(pszName, "ListOfUnsupportedAnnotations"))
          CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 11,
                         pszName, "ListOfUnsupportedAnnotations", mParser.getCurrentLineNumber());

        mParser.popElementHandler();
        mCurrentElement = START_ELEMENT;

        /* Tell the parent element we are done. */
        mParser.onEndElement(pszName);
        break;

      case UnsupportedAnnotation:

        if (strcmp(pszName, "UnsupportedAnnotation"))
          CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 11,
                         pszName, "UnsupportedAnnotation", mParser.getCurrentLineNumber());

        if (mpUnsupportedAnnotationElement != NULL)
          {
            mUnsupportedAnnotations[mpUnsupportedAnnotationElement->getName()] =
              mpUnsupportedAnnotationElement->getXML();
          }

        mLastKnownElement = ListOfUnsupportedAnnotations;
        mCurrentElement = ListOfUnsupportedAnnotations;
        break;

      case UNKNOWN_ELEMENT:
        mCurrentElement = mLastKnownElement;
        break;

      default:
        CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 11,
                       pszName, "???", mParser.getCurrentLineNumber());
        break;
    }

  return;
}

const CAnnotation::UnsupportedAnnotation & CCopasiXMLParser::ListOfUnsupportedAnnotationsElement::getUnsupportedAnnotations() const
{
  return mUnsupportedAnnotations;
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

//-----------------------------------------------------------------------------
/// \class AliMUONGlobalTriggerBoard
/// Global trigger implementation:
/// - inputs are regional responses
/// - output is a 12-bit word
/// - 4 bits per trigger level
///
/// \author Rachid Guernane (LPCCFd),
/// Corrected by Christian Finck (Subatech)
//-----------------------------------------------------------------------------

#include "AliMUONGlobalTriggerBoard.h"
#include "AliLog.h"
#include "TBits.h"

#include <Riostream.h>

/// \cond CLASSIMP
ClassImp(AliMUONGlobalTriggerBoard)
/// \endcond

//___________________________________________
AliMUONGlobalTriggerBoard::AliMUONGlobalTriggerBoard(): AliMUONTriggerBoard()
{
/// Default constructor

   for (Int_t i=0;i<16;i++) fRegionalResponse[i] = 0;
   for (Int_t i=0;i< 4;i++) fGlobalInput[i] = 0;
   for (Int_t i=0;i< 4;i++) fMask[i] = 0xffffffff;
}

//___________________________________________
AliMUONGlobalTriggerBoard::AliMUONGlobalTriggerBoard(const char *name, Int_t a) : AliMUONTriggerBoard(name, a)
{
/// Standard constructor

   for (Int_t i=0;i<16;i++) fRegionalResponse[i] = 0;
   for (Int_t i=0;i< 4;i++) fGlobalInput[i] = 0;
   for (Int_t i=0;i< 4;i++) fMask[i] = 0xffffffff;
}

//___________________________________________
AliMUONGlobalTriggerBoard::~AliMUONGlobalTriggerBoard()
{
/// Destructor
}

//___________________________________________
void AliMUONGlobalTriggerBoard::Mask(Int_t index, UInt_t mask)
{
  /// mask global trigger board input index with value mask
  if ( index >= 0 && index < 4 )
  {
    fMask[index]=mask;
  }
  else
  {
    AliError(Form("Index %d out of bounds (max %d)",index,3));
  }
}

//___________________________________________
void AliMUONGlobalTriggerBoard::Response()
{
   /// compute the global trigger board
   /// response according to the algo() method
// output from global trigger algorithm
// [+, -, US, LS] * [Hpt, Lpt]
// transformed to [usHpt, usLpt, lsHpt, lsLpt, sHpt, sLpt] according
// to Global Trigger Unit user manual

   Int_t t[16];

   BuildGlobalInput();
   MaskGlobalInput();

   for (Int_t i = 0; i < 16; ++i)
   {
     t[i] = fRegionalResponse[i];
   }

   Int_t rank = 8;

   for (Int_t i=0;i<4;i++)
   {
      Int_t ip = 0;

      for (Int_t j=0;j<rank;j++)
      {
         UShort_t lthres = Algo(t[2*j],t[2*j+1],"LPT");

         UShort_t hthres = Algo(t[2*j],t[2*j+1],"HPT"); hthres <<= 4;

         t[ip] = lthres | hthres;

         ip++;
      }

      rank /= 2;
   }
   UChar_t sLpt, sHpt, lsLpt, lsHpt, usLpt, usHpt;
   sLpt  = ((t[0] & 0xC)  != 0);
   sHpt  = ((t[0] & 0xC0) != 0);
   lsLpt = ((t[0] & 0x1)  != 0);
   lsHpt = ((t[0] & 0x10) != 0);
   usLpt = ((t[0] & 0x2 ) != 0);
   usHpt = ((t[0] & 0x20) != 0);

   // LSB is zero (trigger choice to send to CTP: sLpt or sHpt)

   sLpt  <<= 1;
   sHpt  <<= 2;
   lsLpt <<= 3;
   lsHpt <<= 4;
   usLpt <<= 5;
   usHpt <<= 6;

   fResponse = sLpt | sHpt | lsLpt | lsHpt | usLpt |usHpt;

}

//___________________________________________
UShort_t AliMUONGlobalTriggerBoard::Algo(UShort_t i, UShort_t j, const char *thres)
{
/// global trigger algorithm
///   a ,b = reg  response  =  Hpt (+|-|us|ls) |  Lpt (+|-|us|ls)

   TBits a(8), b(8); a.Set(8,&i); b.Set(8,&j);

   TBits trg1(2), trg2(2), trg(2);

   if (!strcmp(thres,"LPT"))
   {
      trg1[0] = a[2]; trg1[1] = a[3];
      trg2[0] = b[2]; trg2[1] = b[3];
   }
   else
   {
      trg1[0] = a[6]; trg1[1] = a[7];
      trg2[0] = b[6]; trg2[1] = b[7];
   }

   TBits trgLS1(1), trgUS1(1), trgLS2(1), trgUS2(1), trgLS(1), trgUS(1);

   if (!strcmp(thres,"LPT"))
   {
      trgLS1[0] = a[0]; trgUS1[0] = a[1];
      trgLS2[0] = b[0]; trgUS2[0] = b[1];
   }
   else
   {
      trgLS1[0] = a[4]; trgUS1[0] = a[5];
      trgLS2[0] = b[4]; trgUS2[0] = b[5];
   }

   trgLS[0] = ( trg1[0] & trg2[0] ) | ( trg1[1] & trg2[1] ) | trgLS1[0] | trgLS2[0];
   trgUS[0] = ( trg1[0] & trg2[1] ) | ( trg1[1] & trg2[0] ) | trgUS1[0] | trgUS2[0];

   trg[0] = trg1[0] | trg2[0];
   trg[1] = trg1[1] | trg2[1];

   TBits v(4);

   v[0] = trgLS[0];
   v[1] = trgUS[0];
   v[2] = trg[0];
   v[3] = trg[1];

   UShort_t rv = 0;
   v.Get(&rv);

   return rv;
}

//___________________________________________
void AliMUONGlobalTriggerBoard::BuildGlobalInput()
{
  /// build the 4 words (32bits) global input from the regional responses
  /// the order of regional responses is:
  /// 1R, 2R, 2-3R, 3R, 4R, 5R, 6R, 7R, 1L, 2L, 2-3L, 3L, 4L, 5L, 6L, 7L

  for (Int_t i=0;i< 4;i++) fGlobalInput[i] = 0;

  UShort_t regRespInv;
  TBits rs(8), rsi(8);
  for (Int_t iReg = 0; iReg < 16; iReg++) {

    // invert bits in regional response ?
    rs.Set(8,&fRegionalResponse[iReg]);
    for (Int_t i = 0; i < 4; i++) {
      // ... YES
      //rsi[2*i]   = rs[2*i+1];
      //rsi[2*i+1] = rs[2*i];
      // ... NO
      rsi[2*i]   = rs[2*i];
      rsi[2*i+1] = rs[2*i+1];
    }
    regRespInv = 0;
    rsi.Get(&regRespInv);

    if (iReg < 8) {    // right
      // Lpt word
      fGlobalInput[0] |=  (regRespInv & 0x0F)       << (4*iReg);
      // Hpt word
      fGlobalInput[2] |= ((regRespInv & 0xF0) >> 4) << (4*iReg);
    } else {           // left
      // Lpt word
      fGlobalInput[1] |=  (regRespInv & 0x0F)       << (4*(iReg-8));
      // Hpt word
      fGlobalInput[3] |= ((regRespInv & 0xF0) >> 4) << (4*(iReg-8));
    }

  }

}

//___________________________________________
void AliMUONGlobalTriggerBoard::MaskGlobalInput()
{
  /// Apply masks to global input and recalculate regional inputs before
  /// applying the global response

  UShort_t regRespInv;
  TBits rs(8), rsi(8);

  // global input with masks applied
  UInt_t gitmp[4];

  for (Int_t i = 0; i < 4; i++) {
    gitmp[i] = fGlobalInput[i];
    gitmp[i] &= fMask[i];
  }

  for (Int_t iReg = 0; iReg < 16; iReg++) {
    fRegionalResponse[iReg] = 0;
    if (iReg < 8) {    // right
      // Lpt
      fRegionalResponse[iReg] |=  (gitmp[0] >> (4*iReg))     & 0xF;
      // Hpt
      fRegionalResponse[iReg] |= ((gitmp[2] >> (4*iReg))     & 0xF) << 4;
    } else {           // left
      // Lpt
      fRegionalResponse[iReg] |=  (gitmp[1] >> (4*(iReg-8))) & 0xF;
      // Hpt
      fRegionalResponse[iReg] |= ((gitmp[3] >> (4*(iReg-8))) & 0xF) << 4;
    }
    // invert bits in regional response ?
    rs.Set(8,&fRegionalResponse[iReg]);
    for (Int_t i = 0; i < 4; i++) {
      rsi[2*i]   = rs[2*i+1];
      rsi[2*i+1] = rs[2*i];
    }
    regRespInv = 0;
    rsi.Get(&regRespInv);
    // uncomment if ... YES
    //fRegionalResponse[iReg] = regRespInv;
  }

}

//___________________________________________
void AliMUONGlobalTriggerBoard::Scan(Option_t*) const
{
  /// print global trigger output
  TBits w(7); w.Set(7,&fResponse);

// TRG[1:0]
// 00 noth
// 01 negative track
// 10 positive track
// 11 undef

   Int_t iS[2] = {0,0};

   iS[0] = (Int_t)w.TestBitNumber(1);
   iS[1] = (Int_t)w.TestBitNumber(2);

   Int_t iPU[2] = {w[5],w[6]};
   Int_t iPL[2] = {w[3],w[4]};

   printf("============================================\n");
   printf(" Global Trigger output       Low pt  High pt\n");
   printf(" number of Single           :\t");
   for (Int_t i=0; i<2; i++) printf("%i\t",iS[i]);
   printf("\n");
   printf(" number of UnlikeSign pair  :\t");
   for (Int_t i=0; i<2; i++) printf("%i\t",iPU[i]);
   printf("\n");
   printf(" number of LikeSign pair    :\t");
   for (Int_t i=0; i<2; i++) printf("%i\t",iPL[i]);
   printf("\n");
   printf("===================================================\n");
   printf("\n");
}

<commit_msg>Invert bits in regional response according to hardware<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

//-----------------------------------------------------------------------------
/// \class AliMUONGlobalTriggerBoard
/// Global trigger implementation:
/// - inputs are regional responses
/// - output is a 12-bit word
/// - 4 bits per trigger level
///
/// \author Rachid Guernane (LPCCFd),
/// Corrected by Christian Finck (Subatech)
//-----------------------------------------------------------------------------

#include "AliMUONGlobalTriggerBoard.h"
#include "AliLog.h"
#include "TBits.h"

#include <Riostream.h>

/// \cond CLASSIMP
ClassImp(AliMUONGlobalTriggerBoard)
/// \endcond

//___________________________________________
AliMUONGlobalTriggerBoard::AliMUONGlobalTriggerBoard(): AliMUONTriggerBoard()
{
/// Default constructor

   for (Int_t i=0;i<16;i++) fRegionalResponse[i] = 0;
   for (Int_t i=0;i< 4;i++) fGlobalInput[i] = 0;
   for (Int_t i=0;i< 4;i++) fMask[i] = 0xffffffff;
}

//___________________________________________
AliMUONGlobalTriggerBoard::AliMUONGlobalTriggerBoard(const char *name, Int_t a) : AliMUONTriggerBoard(name, a)
{
/// Standard constructor

   for (Int_t i=0;i<16;i++) fRegionalResponse[i] = 0;
   for (Int_t i=0;i< 4;i++) fGlobalInput[i] = 0;
   for (Int_t i=0;i< 4;i++) fMask[i] = 0xffffffff;
}

//___________________________________________
AliMUONGlobalTriggerBoard::~AliMUONGlobalTriggerBoard()
{
/// Destructor
}

//___________________________________________
void AliMUONGlobalTriggerBoard::Mask(Int_t index, UInt_t mask)
{
  /// mask global trigger board input index with value mask
  if ( index >= 0 && index < 4 )
  {
    fMask[index]=mask;
  }
  else
  {
    AliError(Form("Index %d out of bounds (max %d)",index,3));
  }
}

//___________________________________________
void AliMUONGlobalTriggerBoard::Response()
{
   /// compute the global trigger board
   /// response according to the algo() method
// output from global trigger algorithm
// [+, -, US, LS] * [Hpt, Lpt]
// transformed to [usHpt, usLpt, lsHpt, lsLpt, sHpt, sLpt] according
// to Global Trigger Unit user manual

   Int_t t[16];

   BuildGlobalInput();
   MaskGlobalInput();

   for (Int_t i = 0; i < 16; ++i)
   {
     t[i] = fRegionalResponse[i];
   }

   Int_t rank = 8;

   for (Int_t i=0;i<4;i++)
   {
      Int_t ip = 0;

      for (Int_t j=0;j<rank;j++)
      {
         UShort_t lthres = Algo(t[2*j],t[2*j+1],"LPT");

         UShort_t hthres = Algo(t[2*j],t[2*j+1],"HPT"); hthres <<= 4;

         t[ip] = lthres | hthres;

         ip++;
      }

      rank /= 2;
   }
   UChar_t sLpt, sHpt, lsLpt, lsHpt, usLpt, usHpt;
   sLpt  = ((t[0] & 0xC)  != 0);
   sHpt  = ((t[0] & 0xC0) != 0);
   lsLpt = ((t[0] & 0x1)  != 0);
   lsHpt = ((t[0] & 0x10) != 0);
   usLpt = ((t[0] & 0x2 ) != 0);
   usHpt = ((t[0] & 0x20) != 0);

   // LSB is zero (trigger choice to send to CTP: sLpt or sHpt)

   sLpt  <<= 1;
   sHpt  <<= 2;
   lsLpt <<= 3;
   lsHpt <<= 4;
   usLpt <<= 5;
   usHpt <<= 6;

   fResponse = sLpt | sHpt | lsLpt | lsHpt | usLpt |usHpt;

}

//___________________________________________
UShort_t AliMUONGlobalTriggerBoard::Algo(UShort_t i, UShort_t j, const char *thres)
{
/// global trigger algorithm
///   a ,b = reg  response  =  Hpt (+|-|us|ls) |  Lpt (+|-|us|ls)

   TBits a(8), b(8); a.Set(8,&i); b.Set(8,&j);

   TBits trg1(2), trg2(2), trg(2);

   if (!strcmp(thres,"LPT"))
   {
      trg1[0] = a[2]; trg1[1] = a[3];
      trg2[0] = b[2]; trg2[1] = b[3];
   }
   else
   {
      trg1[0] = a[6]; trg1[1] = a[7];
      trg2[0] = b[6]; trg2[1] = b[7];
   }

   TBits trgLS1(1), trgUS1(1), trgLS2(1), trgUS2(1), trgLS(1), trgUS(1);

   if (!strcmp(thres,"LPT"))
   {
      trgLS1[0] = a[0]; trgUS1[0] = a[1];
      trgLS2[0] = b[0]; trgUS2[0] = b[1];
   }
   else
   {
      trgLS1[0] = a[4]; trgUS1[0] = a[5];
      trgLS2[0] = b[4]; trgUS2[0] = b[5];
   }

   trgLS[0] = ( trg1[0] & trg2[0] ) | ( trg1[1] & trg2[1] ) | trgLS1[0] | trgLS2[0];
   trgUS[0] = ( trg1[0] & trg2[1] ) | ( trg1[1] & trg2[0] ) | trgUS1[0] | trgUS2[0];

   trg[0] = trg1[0] | trg2[0];
   trg[1] = trg1[1] | trg2[1];

   TBits v(4);

   v[0] = trgLS[0];
   v[1] = trgUS[0];
   v[2] = trg[0];
   v[3] = trg[1];

   UShort_t rv = 0;
   v.Get(&rv);

   return rv;
}

//___________________________________________
void AliMUONGlobalTriggerBoard::BuildGlobalInput()
{
  /// build the 4 words (32bits) global input from the regional responses
  /// the order of regional responses is:
  /// 1R, 2R, 2-3R, 3R, 4R, 5R, 6R, 7R, 1L, 2L, 2-3L, 3L, 4L, 5L, 6L, 7L

  for (Int_t i=0;i< 4;i++) fGlobalInput[i] = 0;

  UShort_t regRespInv;
  TBits rs(8), rsi(8);
  for (Int_t iReg = 0; iReg < 16; iReg++) {

    // invert "pair" bits in regional response
    // [+, -, US, LS] becomes [+, -, LS, US]
    rs.Set(8,&fRegionalResponse[iReg]);
    for (Int_t i = 0; i < 4; i++) {
      if (i%2 == 0) {
	rsi[2*i]   = rs[2*i+1];
	rsi[2*i+1] = rs[2*i];
      } else {
	rsi[2*i]   = rs[2*i];
	rsi[2*i+1] = rs[2*i+1];
      }
    }
    regRespInv = 0;
    rsi.Get(&regRespInv);

    if (iReg < 8) {    // right
      // Lpt word
      fGlobalInput[0] |=  (regRespInv & 0x0F)       << (4*iReg);
      // Hpt word
      fGlobalInput[2] |= ((regRespInv & 0xF0) >> 4) << (4*iReg);
    } else {           // left
      // Lpt word
      fGlobalInput[1] |=  (regRespInv & 0x0F)       << (4*(iReg-8));
      // Hpt word
      fGlobalInput[3] |= ((regRespInv & 0xF0) >> 4) << (4*(iReg-8));
    }

  }

}

//___________________________________________
void AliMUONGlobalTriggerBoard::MaskGlobalInput()
{
  /// Apply masks to global input and recalculate regional inputs before
  /// applying the global response

  UShort_t regRespInv;
  TBits rs(8), rsi(8);

  UInt_t gitmp[4];
  for (Int_t i = 0; i < 4; i++) {
    fGlobalInput[i] &= fMask[i];
    gitmp[i] = fGlobalInput[i];
  }

  for (Int_t iReg = 0; iReg < 16; iReg++) {
    fRegionalResponse[iReg] = 0;
    if (iReg < 8) {    // right
      // Lpt
      fRegionalResponse[iReg] |=  (gitmp[0] >> (4*iReg))     & 0xF;
      // Hpt
      fRegionalResponse[iReg] |= ((gitmp[2] >> (4*iReg))     & 0xF) << 4;
    } else {           // left
      // Lpt
      fRegionalResponse[iReg] |=  (gitmp[1] >> (4*(iReg-8))) & 0xF;
      // Hpt
      fRegionalResponse[iReg] |= ((gitmp[3] >> (4*(iReg-8))) & 0xF) << 4;
    }
    // invert "pair" bits in regional response
    // [+, -, US, LS] becomes [+, -, LS, US]
    rs.Set(8,&fRegionalResponse[iReg]);
    for (Int_t i = 0; i < 4; i++) {
      if (i%2 == 0) {
	rsi[2*i]   = rs[2*i+1];
	rsi[2*i+1] = rs[2*i];
      } else {
	rsi[2*i]   = rs[2*i];
	rsi[2*i+1] = rs[2*i+1];
      }
    }
    regRespInv = 0;
    rsi.Get(&regRespInv);
    fRegionalResponse[iReg] = regRespInv;
  }

}

//___________________________________________
void AliMUONGlobalTriggerBoard::Scan(Option_t*) const
{
  /// print global trigger output
  TBits w(7); w.Set(7,&fResponse);

// TRG[1:0]
// 00 noth
// 01 negative track
// 10 positive track
// 11 undef

   Int_t iS[2] = {0,0};

   iS[0] = (Int_t)w.TestBitNumber(1);
   iS[1] = (Int_t)w.TestBitNumber(2);

   Int_t iPU[2] = {w[5],w[6]};
   Int_t iPL[2] = {w[3],w[4]};

   printf("============================================\n");
   printf(" Global Trigger output       Low pt  High pt\n");
   printf(" number of Single           :\t");
   for (Int_t i=0; i<2; i++) printf("%i\t",iS[i]);
   printf("\n");
   printf(" number of UnlikeSign pair  :\t");
   for (Int_t i=0; i<2; i++) printf("%i\t",iPU[i]);
   printf("\n");
   printf(" number of LikeSign pair    :\t");
   for (Int_t i=0; i<2; i++) printf("%i\t",iPL[i]);
   printf("\n");
   printf("===================================================\n");
   printf("\n");
}

<|endoftext|>


<commit_before>//
//  RenderFunctions.cpp
//
//  Created by Soso Limited on 7/13/15.
//
//

#include "RenderFunctions.h"

#include "Transform.h"
#include "Circle.h"
#include "RenderLayer.h"
#include "entityx/Entity.h"
#include "cinder/gl/gl.h"

using namespace soso;
using namespace cinder;

void soso::renderAllEntitiesAsCircles(entityx::EntityManager &entities)
{
  gl::ScopedDepth depth(true, true);

  entityx::ComponentHandle<Transform> transform;
  for (auto __unused e : entities.entities_with_components(transform)) {
    gl::ScopedModelMatrix mat;
    gl::multModelMatrix(transform->worldTransform());
    gl::drawSolidCircle(vec2(0), 12.0f);
  }
}

void soso::renderCircles(entityx::EntityManager &entities)
{
  gl::ScopedDepth depth(true, true);

  entityx::ComponentHandle<Transform> transform;
  entityx::ComponentHandle<Circle>    circle;

  auto billboard_xf = [] (Transform::Handle transform) {
    auto q = inverse(normalize(quat_cast(transform->worldTransform())));
    return transform->worldTransform() * glm::mat4_cast(q);
  };

  gl::ScopedColor color(Color(1.0f, 1.0f, 1.0f));
  for (auto __unused e : entities.entities_with_components(transform, circle)) {
    gl::ScopedModelMatrix mat;
    gl::multModelMatrix(billboard_xf(transform));
    gl::color(circle->color);

    gl::drawSolidCircle(vec2(0), circle->radius);
  }
}

void soso::renderCirclesDepthSorted(entityx::EntityManager &entities)
{
  struct RenderInfo {
    ci::vec3  position;
    float      scale;
    float      radius = 1.0f;
    ci::Color color;

  };
  std::vector<RenderInfo> circles;

  auto insertion_point = [&circles] (float depth) {
      auto iter = circles.begin();
      while (iter != circles.end() && depth < iter->position.z) {
        ++iter;
      }
      return iter;
    };

  entityx::ComponentHandle<Transform> transform;
  entityx::ComponentHandle<Circle>    circle;

  for (auto __unused e : entities.entities_with_components(transform, circle)) {
    auto pos = vec3(transform->worldTransform() * vec4(0, 0, 0, 1));
    auto scale = length(vec3(transform->worldTransform() * vec4(1, 0, 0, 0)));
    circles.insert(insertion_point(pos.z), RenderInfo{pos, scale, circle->radius, circle->color});
  }

  gl::ScopedColor color(Color(1.0f, 1.0f, 1.0f));
  for (auto &c : circles) {
    gl::ScopedModelMatrix mat;
    gl::translate(c.position);
    gl::scale(vec3(c.scale));
    gl::color(c.color);

    gl::drawSolidCircle(vec2(0), c.radius);
  }

}

void soso::renderCirclesHierarchically(entityx::EntityManager &entities)
{
  entityx::ComponentHandle<Transform> transform;
  entityx::ComponentHandle<Circle>    circle;
  auto xf = mat4(1);

  const auto billboard_xf = [] (const Transform &transform) {
    auto q = inverse(normalize(quat_cast(transform.localTransform())));
    return transform.localTransform() * glm::mat4_cast(q);
  };

  using function = std::function<void (Transform::Handle)>;
  function draw_recursively = [&billboard_xf, &draw_recursively] (Transform::Handle transform) {
      gl::ScopedModelMatrix mat;
      gl::multModelMatrix(transform->localTransform());

      auto circle = transform->entity().component<Circle>();
      if (circle)
      {
        // billboard the circles (mostly works)
        gl::ScopedModelMatrix mat;
        gl::multModelMatrix(glm::mat4_cast(inverse(normalize(quat_cast(transform->worldTransform())))));
        gl::color(circle->color);
        gl::drawSolidCircle(vec2(0), circle->radius);
      }

      for (auto &child: transform->children())
      {
        draw_recursively(child);
      }
  };

  gl::ScopedColor        color(Color::white());
  gl::ScopedDepth        depth(false);
  for (auto __unused e : entities.entities_with_components(transform, circle)) {
    if (transform->isRoot())
    {
      draw_recursively(transform);
    }
  }
}

void soso::renderCirclesByLayer(entityx::EntityManager &entities)
{
  // Data types for collecting render information into layers.
  struct DataPoint
  {
    mat4  transform;
    Color  color;
    float  radius;
  };

  using RenderData = std::vector<DataPoint>;
  using RenderDataRef = std::unique_ptr<RenderData>;
  struct RenderDataLayer {
    RenderDataLayer(int layer)
    : layer(layer)
    {}
    int            layer = 0;
    RenderDataRef render_data = std::make_unique<RenderData>();
  };

  // Our layers for rendering
  std::vector<RenderDataLayer> layers;

  // Returns the requested render layer, creating it if necessary.
  auto get_layer = [&layers] (int layer) -> RenderData& {
    for (auto &l : layers) {
      if (l.layer == layer) {
        return *l.render_data;
      }
    }
    layers.emplace_back(RenderDataLayer(layer));
    return *layers.back().render_data;
  };

  // Billboards a transform matrix.
  auto billboard_xf = [] (Transform::Handle transform) {
    auto q = inverse(normalize(quat_cast(transform->worldTransform())));
    return transform->worldTransform() * glm::mat4_cast(q);
  };

  // Recursive function to properly capture render layer changes.
  using function = std::function<void (Transform::Handle, int)>;
  function gather_recursively = [&gather_recursively, &get_layer, &billboard_xf] (Transform::Handle transform, int layer) {

    auto rlc = entityx::ComponentHandle<soso::RenderLayer>();
    auto circle = entityx::ComponentHandle<Circle>();
    auto e = transform->entity();
    e.unpack(rlc, circle);

    if (rlc)
    {
      if (rlc->relative())
      {
        layer += rlc->layer();
      }
      else
      {
        layer = rlc->layer();
      }
    }

    if (circle)
    {
      get_layer(layer).push_back({ billboard_xf(transform), circle->color, circle->radius });
    }

    for (auto &c : transform->children())
    {
      gather_recursively(c, layer);
    }
  };

  entityx::ComponentHandle<Transform> transform;
  for (auto __unused e : entities.entities_with_components(transform))
  {
    // gather trees for rendering
    if (transform->isRoot())
    {
      gather_recursively(transform, 0);
    }
  }

  // In case we encountered layers out of order, put them into order.
  std::sort(layers.begin(), layers.end(), [] (const RenderDataLayer &lhs, const RenderDataLayer &rhs) {
    return lhs.layer < rhs.layer;
  });

  // Draw everything we gathered, by layer.
  gl::ScopedModelMatrix mat;
  gl::ScopedColor color(Color::white());
  for (auto &layer : layers)
  {
    for (auto &data : *layer.render_data)
    {
      gl::setModelMatrix(data.transform);
      gl::color(data.color);
      gl::drawSolidCircle(vec2(0), data.radius);
    }
  }
}
<commit_msg>Update use of gl::ScopedDepth.<commit_after>//
//  RenderFunctions.cpp
//
//  Created by Soso Limited on 7/13/15.
//
//

#include "RenderFunctions.h"

#include "Transform.h"
#include "Circle.h"
#include "RenderLayer.h"
#include "entityx/Entity.h"
#include "cinder/gl/gl.h"

using namespace soso;
using namespace cinder;

void soso::renderAllEntitiesAsCircles(entityx::EntityManager &entities)
{
  gl::ScopedDepth depth(true);

  entityx::ComponentHandle<Transform> transform;
  for (auto __unused e : entities.entities_with_components(transform)) {
    gl::ScopedModelMatrix mat;
    gl::multModelMatrix(transform->worldTransform());
    gl::drawSolidCircle(vec2(0), 12.0f);
  }
}

void soso::renderCircles(entityx::EntityManager &entities)
{
  gl::ScopedDepth depth(true);

  entityx::ComponentHandle<Transform> transform;
  entityx::ComponentHandle<Circle>    circle;

  auto billboard_xf = [] (Transform::Handle transform) {
    auto q = inverse(normalize(quat_cast(transform->worldTransform())));
    return transform->worldTransform() * glm::mat4_cast(q);
  };

  gl::ScopedColor color(Color(1.0f, 1.0f, 1.0f));
  for (auto __unused e : entities.entities_with_components(transform, circle)) {
    gl::ScopedModelMatrix mat;
    gl::multModelMatrix(billboard_xf(transform));
    gl::color(circle->color);

    gl::drawSolidCircle(vec2(0), circle->radius);
  }
}

void soso::renderCirclesDepthSorted(entityx::EntityManager &entities)
{
  struct RenderInfo {
    ci::vec3  position;
    float      scale;
    float      radius = 1.0f;
    ci::Color color;

  };
  std::vector<RenderInfo> circles;

  auto insertion_point = [&circles] (float depth) {
      auto iter = circles.begin();
      while (iter != circles.end() && depth < iter->position.z) {
        ++iter;
      }
      return iter;
    };

  entityx::ComponentHandle<Transform> transform;
  entityx::ComponentHandle<Circle>    circle;

  for (auto __unused e : entities.entities_with_components(transform, circle)) {
    auto pos = vec3(transform->worldTransform() * vec4(0, 0, 0, 1));
    auto scale = length(vec3(transform->worldTransform() * vec4(1, 0, 0, 0)));
    circles.insert(insertion_point(pos.z), RenderInfo{pos, scale, circle->radius, circle->color});
  }

  gl::ScopedColor color(Color(1.0f, 1.0f, 1.0f));
  for (auto &c : circles) {
    gl::ScopedModelMatrix mat;
    gl::translate(c.position);
    gl::scale(vec3(c.scale));
    gl::color(c.color);

    gl::drawSolidCircle(vec2(0), c.radius);
  }

}

void soso::renderCirclesHierarchically(entityx::EntityManager &entities)
{
  entityx::ComponentHandle<Transform> transform;
  entityx::ComponentHandle<Circle>    circle;
  auto xf = mat4(1);

  const auto billboard_xf = [] (const Transform &transform) {
    auto q = inverse(normalize(quat_cast(transform.localTransform())));
    return transform.localTransform() * glm::mat4_cast(q);
  };

  using function = std::function<void (Transform::Handle)>;
  function draw_recursively = [&billboard_xf, &draw_recursively] (Transform::Handle transform) {
      gl::ScopedModelMatrix mat;
      gl::multModelMatrix(transform->localTransform());

      auto circle = transform->entity().component<Circle>();
      if (circle)
      {
        // billboard the circles (mostly works)
        gl::ScopedModelMatrix mat;
        gl::multModelMatrix(glm::mat4_cast(inverse(normalize(quat_cast(transform->worldTransform())))));
        gl::color(circle->color);
        gl::drawSolidCircle(vec2(0), circle->radius);
      }

      for (auto &child: transform->children())
      {
        draw_recursively(child);
      }
  };

  gl::ScopedColor        color(Color::white());
  gl::ScopedDepth        depth(false);
  for (auto __unused e : entities.entities_with_components(transform, circle)) {
    if (transform->isRoot())
    {
      draw_recursively(transform);
    }
  }
}

void soso::renderCirclesByLayer(entityx::EntityManager &entities)
{
  // Data types for collecting render information into layers.
  struct DataPoint
  {
    mat4  transform;
    Color  color;
    float  radius;
  };

  using RenderData = std::vector<DataPoint>;
  using RenderDataRef = std::unique_ptr<RenderData>;
  struct RenderDataLayer {
    RenderDataLayer(int layer)
    : layer(layer)
    {}
    int            layer = 0;
    RenderDataRef render_data = std::make_unique<RenderData>();
  };

  // Our layers for rendering
  std::vector<RenderDataLayer> layers;

  // Returns the requested render layer, creating it if necessary.
  auto get_layer = [&layers] (int layer) -> RenderData& {
    for (auto &l : layers) {
      if (l.layer == layer) {
        return *l.render_data;
      }
    }
    layers.emplace_back(RenderDataLayer(layer));
    return *layers.back().render_data;
  };

  // Billboards a transform matrix.
  auto billboard_xf = [] (Transform::Handle transform) {
    auto q = inverse(normalize(quat_cast(transform->worldTransform())));
    return transform->worldTransform() * glm::mat4_cast(q);
  };

  // Recursive function to properly capture render layer changes.
  using function = std::function<void (Transform::Handle, int)>;
  function gather_recursively = [&gather_recursively, &get_layer, &billboard_xf] (Transform::Handle transform, int layer) {

    auto rlc = entityx::ComponentHandle<soso::RenderLayer>();
    auto circle = entityx::ComponentHandle<Circle>();
    auto e = transform->entity();
    e.unpack(rlc, circle);

    if (rlc)
    {
      if (rlc->relative())
      {
        layer += rlc->layer();
      }
      else
      {
        layer = rlc->layer();
      }
    }

    if (circle)
    {
      get_layer(layer).push_back({ billboard_xf(transform), circle->color, circle->radius });
    }

    for (auto &c : transform->children())
    {
      gather_recursively(c, layer);
    }
  };

  entityx::ComponentHandle<Transform> transform;
  for (auto __unused e : entities.entities_with_components(transform))
  {
    // gather trees for rendering
    if (transform->isRoot())
    {
      gather_recursively(transform, 0);
    }
  }

  // In case we encountered layers out of order, put them into order.
  std::sort(layers.begin(), layers.end(), [] (const RenderDataLayer &lhs, const RenderDataLayer &rhs) {
    return lhs.layer < rhs.layer;
  });

  // Draw everything we gathered, by layer.
  gl::ScopedModelMatrix mat;
  gl::ScopedColor color(Color::white());
  for (auto &layer : layers)
  {
    for (auto &data : *layer.render_data)
    {
      gl::setModelMatrix(data.transform);
      gl::color(data.color);
      gl::drawSolidCircle(vec2(0), data.radius);
    }
  }
}
<|endoftext|>


<commit_before>/* +------------------------------------------------------------------------+
   |                     Mobile Robot Programming Toolkit (MRPT)            |
   |                          http://www.mrpt.org/                          |
   |                                                                        |
   | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file     |
   | See: http://www.mrpt.org/Authors - All rights reserved.                |
   | Released under BSD License. See details in http://www.mrpt.org/License |
   +------------------------------------------------------------------------+ */

/*  Plane-based Map (PbMap) library
 *  Construction of plane-based maps and localization in it from RGBD Images.
 *  Writen by Eduardo Fernandez-Moral. See docs for mrpt-pbmap
 */
#include <mrpt/pbmap.h>  // precomp. hdr

#include <mrpt/io/CFileGZInputStream.h>
#include <mrpt/io/CFileGZOutputStream.h>
#include <mrpt/system/os.h>
#include <pcl/io/io.h>
#include <pcl/io/pcd_io.h>
#include <iostream>

using namespace std;
using namespace mrpt::system;
using namespace mrpt::pbmap;

string path("/home/edu/Libraries/mrpt-svn/share/mrpt/datasets/pbmap-demos/");

void printHelp()
{
	cout << "./pbmap_test reads a set of pairs pointCloud+Pose to build a "
			"PbMap\n";
}

void testPbMapConstruction(const string& config_file)
{
	printHelp();

	// Reconstructed PointCloud
	pcl::PointCloud<PointT> globalCloud;

	PbMapMaker pbmap_maker(config_file);

	// Read in the cloud data
	pcl::PCDReader reader;

	unsigned N = 3;  // Read the 5 sample pairs pointClouds+Pose
	string cloudFile, poseFile;
	for (unsigned i = 0; i <= N; i++)
	{
		// Read frame
		frameRGBDandPose cloudAndPose;
		cloudAndPose.cloudPtr.reset(new pcl::PointCloud<PointT>);
		cloudFile = mrpt::format("pointcloud%i.pcd", i);
		ASSERT_FILE_EXISTS_(path + cloudFile)
		reader.read(path + cloudFile, *cloudAndPose.cloudPtr);

		// Read pose
		mrpt::io::CFileGZInputStream serialized_pose;
		poseFile = path + mrpt::format("pose%i.mat", i);

		if (serialized_pose.open(poseFile))
		{
			serialized_pose.ReadBufferFixEndianness<Eigen::Matrix4f::Scalar>(
				&cloudAndPose.pose(0), 16);
		}
		else
			cout << "Error: cannot open " << poseFile << "\n";
		serialized_pose.close();

		// Detect planes and build PbMap
		pbmap_maker.frameQueue.push_back(cloudAndPose);

		pcl::PointCloud<PointT>::Ptr alignedCloudPtr(
			new pcl::PointCloud<PointT>);
		pcl::transformPointCloud(
			*cloudAndPose.cloudPtr, *alignedCloudPtr, cloudAndPose.pose);
		globalCloud += *alignedCloudPtr;

		std::this_thread::sleep_for(1000ms);  // sleep to visualize the map
		// creation from the keyframes in
		// slow motion
	}

	// Serialize PbMap
	mrpt::io::CFileGZOutputStream serialize_pbmap("test.pbmap");
	serialize_pbmap << pbmap_maker.getPbMap();
	serialize_pbmap.close();

	// Save reconstructed point cloud
	pcl::io::savePCDFile("reconstructed_cloud.pcd", globalCloud);

	double total_area = 0.0;
	for (unsigned i = 0; i < pbmap_maker.getPbMap().vPlanes.size(); i++)
		total_area += pbmap_maker.getPbMap().vPlanes[i].areaHull;
	cout << "This PbMap contains " << pbmap_maker.getPbMap().vPlanes.size()
		 << " planes, covering a total area of " << total_area << " m2" << endl;

	std::this_thread::sleep_for(10000ms);
}

int main(int argc, char** argv)
{
	try
	{
		bool showHelp = argc > 1 && !os::_strcmp(argv[1], "--help");

		// Process arguments:
		if (argc < 2 || showHelp)
		{
			printf("Usage: %s <config_file.ini>\n\n", argv[0]);
			if (!showHelp)
			{
				mrpt::system::pause();
				return -1;
			}
			else
				return 0;
		}

		const string INI_FILENAME = string(argv[1]);

		testPbMapConstruction(INI_FILENAME);

		return 0;
	}
	catch (exception& e)
	{
		cout << "MRPT exception caught: " << e.what() << endl;
		return -1;
	}
	catch (...)
	{
		printf("Another exception!!");
		return -1;
	}
}
<commit_msg>Missing ';' after ASSERT_FILE_EXISTS_<commit_after>/* +------------------------------------------------------------------------+
   |                     Mobile Robot Programming Toolkit (MRPT)            |
   |                          http://www.mrpt.org/                          |
   |                                                                        |
   | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file     |
   | See: http://www.mrpt.org/Authors - All rights reserved.                |
   | Released under BSD License. See details in http://www.mrpt.org/License |
   +------------------------------------------------------------------------+ */

/*  Plane-based Map (PbMap) library
 *  Construction of plane-based maps and localization in it from RGBD Images.
 *  Writen by Eduardo Fernandez-Moral. See docs for mrpt-pbmap
 */
#include <mrpt/pbmap.h>  // precomp. hdr

#include <mrpt/io/CFileGZInputStream.h>
#include <mrpt/io/CFileGZOutputStream.h>
#include <mrpt/system/os.h>
#include <pcl/io/io.h>
#include <pcl/io/pcd_io.h>
#include <iostream>

using namespace std;
using namespace mrpt::system;
using namespace mrpt::pbmap;

string path("/home/edu/Libraries/mrpt-svn/share/mrpt/datasets/pbmap-demos/");

void printHelp()
{
	cout << "./pbmap_test reads a set of pairs pointCloud+Pose to build a "
			"PbMap\n";
}

void testPbMapConstruction(const string& config_file)
{
	printHelp();

	// Reconstructed PointCloud
	pcl::PointCloud<PointT> globalCloud;

	PbMapMaker pbmap_maker(config_file);

	// Read in the cloud data
	pcl::PCDReader reader;

	unsigned N = 3;  // Read the 5 sample pairs pointClouds+Pose
	string cloudFile, poseFile;
	for (unsigned i = 0; i <= N; i++)
	{
		// Read frame
		frameRGBDandPose cloudAndPose;
		cloudAndPose.cloudPtr.reset(new pcl::PointCloud<PointT>);
		cloudFile = mrpt::format("pointcloud%i.pcd", i);
		ASSERT_FILE_EXISTS_(path + cloudFile);
		reader.read(path + cloudFile, *cloudAndPose.cloudPtr);

		// Read pose
		mrpt::io::CFileGZInputStream serialized_pose;
		poseFile = path + mrpt::format("pose%i.mat", i);

		if (serialized_pose.open(poseFile))
		{
			serialized_pose.ReadBufferFixEndianness<Eigen::Matrix4f::Scalar>(
				&cloudAndPose.pose(0), 16);
		}
		else
			cout << "Error: cannot open " << poseFile << "\n";
		serialized_pose.close();

		// Detect planes and build PbMap
		pbmap_maker.frameQueue.push_back(cloudAndPose);

		pcl::PointCloud<PointT>::Ptr alignedCloudPtr(
			new pcl::PointCloud<PointT>);
		pcl::transformPointCloud(
			*cloudAndPose.cloudPtr, *alignedCloudPtr, cloudAndPose.pose);
		globalCloud += *alignedCloudPtr;

		std::this_thread::sleep_for(1000ms);  // sleep to visualize the map
		// creation from the keyframes in
		// slow motion
	}

	// Serialize PbMap
	mrpt::io::CFileGZOutputStream serialize_pbmap("test.pbmap");
	serialize_pbmap << pbmap_maker.getPbMap();
	serialize_pbmap.close();

	// Save reconstructed point cloud
	pcl::io::savePCDFile("reconstructed_cloud.pcd", globalCloud);

	double total_area = 0.0;
	for (unsigned i = 0; i < pbmap_maker.getPbMap().vPlanes.size(); i++)
		total_area += pbmap_maker.getPbMap().vPlanes[i].areaHull;
	cout << "This PbMap contains " << pbmap_maker.getPbMap().vPlanes.size()
		 << " planes, covering a total area of " << total_area << " m2" << endl;

	std::this_thread::sleep_for(10000ms);
}

int main(int argc, char** argv)
{
	try
	{
		bool showHelp = argc > 1 && !os::_strcmp(argv[1], "--help");

		// Process arguments:
		if (argc < 2 || showHelp)
		{
			printf("Usage: %s <config_file.ini>\n\n", argv[0]);
			if (!showHelp)
			{
				mrpt::system::pause();
				return -1;
			}
			else
				return 0;
		}

		const string INI_FILENAME = string(argv[1]);

		testPbMapConstruction(INI_FILENAME);

		return 0;
	}
	catch (exception& e)
	{
		cout << "MRPT exception caught: " << e.what() << endl;
		return -1;
	}
	catch (...)
	{
		printf("Another exception!!");
		return -1;
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: XMLExportSharedData.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-23 12:50:50 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SC_XMLEXPORTSHAREDDATA_HXX
#define SC_XMLEXPORTSHAREDDATA_HXX

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif

#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_
#include <com/sun/star/drawing/XDrawPage.hpp>
#endif

#ifndef __SGI_STL_VECTOR
#include <vector>
#endif
#ifndef __SGI_STL_LIST
#include <list>
#endif

struct ScMyDrawPage
{
    com::sun::star::uno::Reference<com::sun::star::drawing::XDrawPage> xDrawPage;
    sal_Bool bHasForms;

    ScMyDrawPage() : bHasForms(sal_False) {}
};

typedef std::list< com::sun::star::uno::Reference<com::sun::star::drawing::XShape> > ScMyTableXShapes;
typedef std::vector<ScMyTableXShapes> ScMyTableShapes;
typedef std::vector<ScMyDrawPage> ScMyDrawPages;

class ScMyShapesContainer;
class ScMyDetectiveObjContainer;
struct ScMyShape;
class ScMyNoteShapesContainer;

class ScMySharedData
{
    std::vector<sal_Int32>      nLastColumns;
    std::vector<sal_Int32>      nLastRows;
    ScMyTableShapes*            pTableShapes;
    ScMyDrawPages*              pDrawPages;
    ScMyShapesContainer*        pShapesContainer;
    ScMyDetectiveObjContainer*  pDetectiveObjContainer;
    ScMyNoteShapesContainer*    pNoteShapes;
    sal_Int32                   nTableCount;
public:
    ScMySharedData(const sal_Int32 nTableCount);
    ~ScMySharedData();

    void SetLastColumn(const sal_Int32 nTable, const sal_Int32 nCol);
    void SetLastRow(const sal_Int32 nTable, const sal_Int32 nRow);
    sal_Int32 GetLastColumn(const sal_Int32 nTable);
    sal_Int32 GetLastRow(const sal_Int32 nTable);
    void AddDrawPage(const ScMyDrawPage& aDrawPage, const sal_Int32 nTable);
    void SetDrawPageHasForms(const sal_Int32 nTable, sal_Bool bHasForms);
    com::sun::star::uno::Reference<com::sun::star::drawing::XDrawPage> GetDrawPage(const sal_Int32 nTable);
    sal_Bool HasDrawPage() { return pDrawPages != NULL; }
    sal_Bool HasForm(const sal_Int32 nTable, com::sun::star::uno::Reference<com::sun::star::drawing::XDrawPage>& xDrawPage);
    void AddNewShape(const ScMyShape& aMyShape);
    void SortShapesContainer();
    ScMyShapesContainer* GetShapesContainer() { return pShapesContainer; }
    sal_Bool HasShapes();
    void AddTableShape(const sal_Int32 nTable, const com::sun::star::uno::Reference<com::sun::star::drawing::XShape>& xShape);
    ScMyTableShapes* GetTableShapes() { return pTableShapes; }
    ScMyDetectiveObjContainer* GetDetectiveObjContainer() { return pDetectiveObjContainer; }
    void AddNoteObj(const com::sun::star::uno::Reference<com::sun::star::drawing::XShape>& xShape, const ScAddress& rPos);
    void SortNoteShapes();
    ScMyNoteShapesContainer* GetNoteShapes() { return pNoteShapes; }
};

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.7.116); FILE MERGED 2005/09/05 15:03:25 rt 1.7.116.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLExportSharedData.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 19:56:35 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SC_XMLEXPORTSHAREDDATA_HXX
#define SC_XMLEXPORTSHAREDDATA_HXX

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif

#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_
#include <com/sun/star/drawing/XDrawPage.hpp>
#endif

#ifndef __SGI_STL_VECTOR
#include <vector>
#endif
#ifndef __SGI_STL_LIST
#include <list>
#endif

struct ScMyDrawPage
{
    com::sun::star::uno::Reference<com::sun::star::drawing::XDrawPage> xDrawPage;
    sal_Bool bHasForms;

    ScMyDrawPage() : bHasForms(sal_False) {}
};

typedef std::list< com::sun::star::uno::Reference<com::sun::star::drawing::XShape> > ScMyTableXShapes;
typedef std::vector<ScMyTableXShapes> ScMyTableShapes;
typedef std::vector<ScMyDrawPage> ScMyDrawPages;

class ScMyShapesContainer;
class ScMyDetectiveObjContainer;
struct ScMyShape;
class ScMyNoteShapesContainer;

class ScMySharedData
{
    std::vector<sal_Int32>      nLastColumns;
    std::vector<sal_Int32>      nLastRows;
    ScMyTableShapes*            pTableShapes;
    ScMyDrawPages*              pDrawPages;
    ScMyShapesContainer*        pShapesContainer;
    ScMyDetectiveObjContainer*  pDetectiveObjContainer;
    ScMyNoteShapesContainer*    pNoteShapes;
    sal_Int32                   nTableCount;
public:
    ScMySharedData(const sal_Int32 nTableCount);
    ~ScMySharedData();

    void SetLastColumn(const sal_Int32 nTable, const sal_Int32 nCol);
    void SetLastRow(const sal_Int32 nTable, const sal_Int32 nRow);
    sal_Int32 GetLastColumn(const sal_Int32 nTable);
    sal_Int32 GetLastRow(const sal_Int32 nTable);
    void AddDrawPage(const ScMyDrawPage& aDrawPage, const sal_Int32 nTable);
    void SetDrawPageHasForms(const sal_Int32 nTable, sal_Bool bHasForms);
    com::sun::star::uno::Reference<com::sun::star::drawing::XDrawPage> GetDrawPage(const sal_Int32 nTable);
    sal_Bool HasDrawPage() { return pDrawPages != NULL; }
    sal_Bool HasForm(const sal_Int32 nTable, com::sun::star::uno::Reference<com::sun::star::drawing::XDrawPage>& xDrawPage);
    void AddNewShape(const ScMyShape& aMyShape);
    void SortShapesContainer();
    ScMyShapesContainer* GetShapesContainer() { return pShapesContainer; }
    sal_Bool HasShapes();
    void AddTableShape(const sal_Int32 nTable, const com::sun::star::uno::Reference<com::sun::star::drawing::XShape>& xShape);
    ScMyTableShapes* GetTableShapes() { return pTableShapes; }
    ScMyDetectiveObjContainer* GetDetectiveObjContainer() { return pDetectiveObjContainer; }
    void AddNoteObj(const com::sun::star::uno::Reference<com::sun::star::drawing::XShape>& xShape, const ScAddress& rPos);
    void SortNoteShapes();
    ScMyNoteShapesContainer* GetNoteShapes() { return pNoteShapes; }
};

#endif

<|endoftext|>


<commit_before>#include "Gillespie_TwoStrain_Network_Sim.h"

int main(int argc,char *argv[]) {
    if(argc != 5) {
            printf("Wrong Number of Arguments\n");
            exit(0);
    }

    //double alpha1 = argv[1]-0.0;
    double alpha1, alpha2, beta1, beta2, gamma1, gamma2, phi1, phi2;
    alpha1 = alpha2 = atof( argv[1] );
    beta1 = 0.35;
    beta2 = atof( argv[2] );
    gamma1 = gamma2 = 1.0/5.0;
    phi1 = phi2 = atof( argv[4]);
    int intro_time;
    intro_time = atoi( argv[3] );

    int num_reps = 1000;

    Network net = Network("gillespie toy", Network::Undirected);
    net.populate(10000);
    vector<int> degrees(10000, 5);
    net.rand_connect_explicit(degrees);
    for(int i =1; i <= num_reps; i++){
        Gillespie_TwoStrain_Network_Sim sim(&net, alpha1, alpha2, gamma1, gamma2, beta1, beta2, phi1, phi2, intro_time);
        cout << "Simulation number: " << i << endl;
        sim.reset();
        sim.rand_infect(5, 1);
        sim.run_simulation(10000.0);
    }
    return 0;
}

<commit_msg>uniform network<commit_after>#include "Gillespie_TwoStrain_Network_Sim.h"

int main(int argc,char *argv[]) {
    if(argc != 5) {
            printf("Wrong Number of Arguments\n");
            exit(0);
    }

    //double alpha1 = argv[1]-0.0;
    double alpha1, alpha2, beta1, beta2, gamma1, gamma2, phi1, phi2;
    alpha1 = alpha2 = atof( argv[1] );
    beta1 = 0.35;
    beta2 = atof( argv[2] );
    gamma1 = gamma2 = 1.0/5.0;
    phi1 = phi2 = atof( argv[4]);
    int intro_time;
    intro_time = atoi( argv[3] );

    int num_reps = 1000;

    Network net = Network("gillespie toy", Network::Undirected);
    net.populate(10000);
    vector<int> degrees(10000, 4);
    net.rand_connect_explicit(degrees);
    for(int i =1; i <= num_reps; i++){
        Gillespie_TwoStrain_Network_Sim sim(&net, alpha1, alpha2, gamma1, gamma2, beta1, beta2, phi1, phi2, intro_time);
        cout << "Simulation number: " << i << endl;
        sim.reset();
        sim.rand_infect(5, 1);
        sim.run_simulation(10000.0);
    }
    return 0;
}

<|endoftext|>


<commit_before>#include "OccTest.hpp"

#include "MechanicsFwd.hpp"
#include "OccContactShape.hpp"
#include "OccContactFace.hpp"
#include "OccContactEdge.hpp"
#include "ContactShapeDistance.hpp"

#include <TopoDS_Shape.hxx>
#include <BRepPrimAPI_MakeSphere.hxx>
#include <BRepTools.hxx>
#include <TopExp_Explorer.hxx>
#include <TopoDS.hxx>
#include <gp_XYZ.hxx>
#include <gp_Quaternion.hxx>

#include <cmath>
#include <boost/math/constants/constants.hpp>

#include <iostream>

CPPUNIT_TEST_SUITE_REGISTRATION(OccTest);

void OccTest::setUp()
{
}

void OccTest::tearDown()
{
}

void OccTest::exportBRepAsString()
{

  BRepPrimAPI_MakeSphere mksphere(1.0);

  OccContactShape sphere(mksphere.Shape());

  std::string s1 = sphere.exportBRepToString();

  std::stringstream out;

  BRepTools::Write(mksphere.Shape(), out);

  CPPUNIT_ASSERT(out.str() == s1);

}

void OccTest::computeUVBounds()
{

  TopExp_Explorer exp;
  BRepPrimAPI_MakeSphere mksphere(1.0);

  OccContactShape sphere_shape = OccContactShape(mksphere.Shape());

  OccContactFace sphere_face(sphere_shape, 0);

  sphere_face.computeUVBounds();

  CPPUNIT_ASSERT(std::abs(sphere_face.bsup1[0] - 6.28319) < 1e-4);
  CPPUNIT_ASSERT(std::abs(sphere_face.bsup1[1] - 1.5708) < 1e-4);

  CPPUNIT_ASSERT(std::abs(sphere_face.binf1[0] - 0.) < 1e-4);
  CPPUNIT_ASSERT(std::abs(sphere_face.binf1[1] + 1.5708) < 1e-4);

  std::cout << sphere_face.bsup1[0] << "," << sphere_face.bsup1[1] << std::endl;
  std::cout << sphere_face.binf1[0] << "," << sphere_face.binf1[1] << std::endl;

}

#include <SiconosVector.hpp>
#include <SimpleMatrix.hpp>
#include <OccBody.hpp>
void OccTest::move()
{
  BRepPrimAPI_MakeSphere mksphere(1.0);

  TopExp_Explorer exp;

  exp.Init(mksphere.Shape(), TopAbs_SHELL);

  TopoDS_Shell shell = TopoDS::Shell(exp.Current().Composed(mksphere.Shape().Orientation()));

  exp.Init(shell, TopAbs_FACE);

  TopoDS_Face face = TopoDS::Face(exp.Current().Composed(shell.Orientation()));

  OccContactShape sphere(mksphere.Shape());
  OccContactFace sphere_contact(sphere, 0);

  SP::SiconosVector position(new SiconosVector(7));
  SP::SiconosVector velocity(new SiconosVector(6));
  SP::SimpleMatrix inertia(new SimpleMatrix(3,3));
  position->zero();
  (*position)(0) = 1.;
  (*position)(1) = 2.;
  (*position)(2) = 3.;

  /* unit quaternion from 4,5,6,7 */
  (*position)(3) = 0.35634832254989918;
  (*position)(4) = 0.44543540318737401;
  (*position)(5) = 0.53452248382484879;
  (*position)(6) = 0.62360956446232352;

  velocity->zero();
  inertia->eye();

  SP::OccBody body(new OccBody(position, velocity, 1, inertia));

  body->addContactShape(createSPtrOccContactShape(sphere_contact));

  gp_XYZ translat = body->contactShape(0).data().Location().Transformation().
    TranslationPart();

  std::cout << translat.X() << "," << translat.Y() << "," << translat.Z()
            << std::endl;

  CPPUNIT_ASSERT(translat.X() == 1.);
  CPPUNIT_ASSERT(translat.Y() == 2.);
  CPPUNIT_ASSERT(translat.Z() == 3.);

  gp_Quaternion rotat = body->contactShape(0).data().Location().Transformation().
    GetRotation();

  CPPUNIT_ASSERT(abs(rotat.X() - 0.44543540318737401) < 1e-9);
  CPPUNIT_ASSERT(abs(rotat.Y() - 0.53452248382484879) < 1e-9);
  CPPUNIT_ASSERT(abs(rotat.Z() - 0.62360956446232352) < 1e-9);
  CPPUNIT_ASSERT(abs(rotat.W() - 0.35634832254989918) < 1e-9);

}

void OccTest::distance()
{
  const double pi = boost::math::constants::pi<double>();

  BRepPrimAPI_MakeSphere mksphere1(1, pi);
  BRepPrimAPI_MakeSphere mksphere2(1, pi);

  OccContactShape sphere1(mksphere1.Shape());
  OccContactShape sphere2(mksphere2.Shape());

  OccContactFace sphere1_contact(sphere1, 0);
  OccContactFace sphere2_contact(sphere2, 0);

  SP::SiconosVector position1(new SiconosVector(7));
  SP::SiconosVector position2(new SiconosVector(7));
  SP::SiconosVector velocity(new SiconosVector(6));
  SP::SimpleMatrix inertia(new SimpleMatrix(3,3));
  position1->zero();
  (*position1)(0) = 0.;
  (*position1)(1) = 0.;
  (*position1)(2) = 0.;

  (*position1)(3) = 1;

  position2->zero();
  (*position2)(0) = 3.;
  (*position2)(1) = 0.;
  (*position2)(2) = 0.;

  (*position2)(3) = cos(pi/2.);
  (*position2)(5) = sin(pi/2.);

  velocity->zero();
  inertia->eye();

  SP::OccBody body1(new OccBody(position1, velocity, 1, inertia));
  SP::OccBody body2(new OccBody(position2, velocity, 1, inertia));

  body1->addContactShape(createSPtrOccContactShape(sphere1_contact));
  body2->addContactShape(createSPtrOccContactShape(sphere2_contact));

  std::cout << "umin1:" << body1->contactShape(0).binf1[0] << std::endl;
  std::cout << "umax1:" << body1->contactShape(0).bsup1[0] << std::endl;
  std::cout << "vmin1:" << body1->contactShape(0).binf1[1] << std::endl;
  std::cout << "vmax1:" << body1->contactShape(0).bsup1[1] << std::endl;

  std::cout << "umin2:" << body2->contactShape(0).binf1[0] << std::endl;
  std::cout << "umax2:" << body2->contactShape(0).bsup1[0] << std::endl;
  std::cout << "vmin2:" << body2->contactShape(0).binf1[1] << std::endl;
  std::cout << "vmax2:" << body2->contactShape(0).bsup1[1] << std::endl;

  gp_XYZ translat1 = body1->contactShape(0).data().Location().Transformation().
    TranslationPart();

  std::cout << translat1.X() << "," << translat1.Y() << "," << translat1.Z()
            << std::endl;

  gp_XYZ translat2 = body2->contactShape(0).data().Location().Transformation().
    TranslationPart();

  std::cout << translat2.X() << "," << translat2.Y() << "," << translat2.Z()
            << std::endl;

  SP::ContactShapeDistance pdist =
    body1->contactShape(0).distance(body2->contactShape(0));

  ContactShapeDistance& dist = *pdist;

  std::cout << dist.value << std::endl;

  std::cout << dist.x1 << "," << dist.y1 << "," << dist.z1 << std::endl;

  std::cout << dist.x2 << "," << dist.y2 << "," << dist.z2 << std::endl;

  std::cout << dist.nx << "," << dist.ny << "," << dist.nz << std::endl;

  CPPUNIT_ASSERT(abs(dist.value - 1.0) < 1e-9);

}
<commit_msg>Remove some warnings<commit_after>#include "OccTest.hpp"

#include "MechanicsFwd.hpp"
#include "OccContactShape.hpp"
#include "OccContactFace.hpp"
#include "OccContactEdge.hpp"
#include "ContactShapeDistance.hpp"

#include <TopoDS_Shape.hxx>
#include <BRepPrimAPI_MakeSphere.hxx>
#include <BRepTools.hxx>
#include <TopExp_Explorer.hxx>
#include <TopoDS.hxx>
#include <gp_XYZ.hxx>
#include <gp_Quaternion.hxx>

#include <cmath>
#include <boost/math/constants/constants.hpp>

#include <iostream>

CPPUNIT_TEST_SUITE_REGISTRATION(OccTest);

void OccTest::setUp()
{
}

void OccTest::tearDown()
{
}

void OccTest::exportBRepAsString()
{

  BRepPrimAPI_MakeSphere mksphere(1.0);

  OccContactShape sphere(mksphere.Shape());

  std::string s1 = sphere.exportBRepToString();

  std::stringstream out;

  BRepTools::Write(mksphere.Shape(), out);

  CPPUNIT_ASSERT(out.str() == s1);

}

void OccTest::computeUVBounds()
{

  TopExp_Explorer exp;
  BRepPrimAPI_MakeSphere mksphere(1.0);

  OccContactShape sphere_shape = OccContactShape(mksphere.Shape());

  OccContactFace sphere_face(sphere_shape, 0);

  sphere_face.computeUVBounds();

  CPPUNIT_ASSERT(std::abs(sphere_face.bsup1[0] - 6.28319) < 1e-4);
  CPPUNIT_ASSERT(std::abs(sphere_face.bsup1[1] - 1.5708) < 1e-4);

  CPPUNIT_ASSERT(std::abs(sphere_face.binf1[0] - 0.) < 1e-4);
  CPPUNIT_ASSERT(std::abs(sphere_face.binf1[1] + 1.5708) < 1e-4);

  std::cout << sphere_face.bsup1[0] << "," << sphere_face.bsup1[1] << std::endl;
  std::cout << sphere_face.binf1[0] << "," << sphere_face.binf1[1] << std::endl;

}

#include <SiconosVector.hpp>
#include <SimpleMatrix.hpp>
#include <OccBody.hpp>
void OccTest::move()
{
  BRepPrimAPI_MakeSphere mksphere(1.0);

  TopExp_Explorer exp;

  exp.Init(mksphere.Shape(), TopAbs_SHELL);

  TopoDS_Shell shell = TopoDS::Shell(exp.Current().Composed(mksphere.Shape().Orientation()));

  exp.Init(shell, TopAbs_FACE);

  TopoDS_Face face = TopoDS::Face(exp.Current().Composed(shell.Orientation()));

  OccContactShape sphere(mksphere.Shape());
  OccContactFace sphere_contact(sphere, 0);

  SP::SiconosVector position(new SiconosVector(7));
  SP::SiconosVector velocity(new SiconosVector(6));
  SP::SimpleMatrix inertia(new SimpleMatrix(3,3));
  position->zero();
  (*position)(0) = 1.;
  (*position)(1) = 2.;
  (*position)(2) = 3.;

  /* unit quaternion from 4,5,6,7 */
  (*position)(3) = 0.35634832254989918;
  (*position)(4) = 0.44543540318737401;
  (*position)(5) = 0.53452248382484879;
  (*position)(6) = 0.62360956446232352;

  velocity->zero();
  inertia->eye();

  SP::OccBody body(new OccBody(position, velocity, 1, inertia));

  body->addContactShape(createSPtrOccContactShape(sphere_contact));

  gp_XYZ translat = body->contactShape(0).data().Location().Transformation().
    TranslationPart();

  std::cout << translat.X() << "," << translat.Y() << "," << translat.Z()
            << std::endl;

  CPPUNIT_ASSERT(translat.X() == 1.);
  CPPUNIT_ASSERT(translat.Y() == 2.);
  CPPUNIT_ASSERT(translat.Z() == 3.);

  gp_Quaternion rotat = body->contactShape(0).data().Location().Transformation().
    GetRotation();

  CPPUNIT_ASSERT(std::abs(rotat.X() - 0.44543540318737401) < 1e-9);
  CPPUNIT_ASSERT(std::abs(rotat.Y() - 0.53452248382484879) < 1e-9);
  CPPUNIT_ASSERT(std::abs(rotat.Z() - 0.62360956446232352) < 1e-9);
  CPPUNIT_ASSERT(std::abs(rotat.W() - 0.35634832254989918) < 1e-9);

}

void OccTest::distance()
{
  const double pi = boost::math::constants::pi<double>();

  BRepPrimAPI_MakeSphere mksphere1(1, pi);
  BRepPrimAPI_MakeSphere mksphere2(1, pi);

  OccContactShape sphere1(mksphere1.Shape());
  OccContactShape sphere2(mksphere2.Shape());

  OccContactFace sphere1_contact(sphere1, 0);
  OccContactFace sphere2_contact(sphere2, 0);

  SP::SiconosVector position1(new SiconosVector(7));
  SP::SiconosVector position2(new SiconosVector(7));
  SP::SiconosVector velocity(new SiconosVector(6));
  SP::SimpleMatrix inertia(new SimpleMatrix(3,3));
  position1->zero();
  (*position1)(0) = 0.;
  (*position1)(1) = 0.;
  (*position1)(2) = 0.;

  (*position1)(3) = 1;

  position2->zero();
  (*position2)(0) = 3.;
  (*position2)(1) = 0.;
  (*position2)(2) = 0.;

  (*position2)(3) = cos(pi/2.);
  (*position2)(5) = sin(pi/2.);

  velocity->zero();
  inertia->eye();

  SP::OccBody body1(new OccBody(position1, velocity, 1, inertia));
  SP::OccBody body2(new OccBody(position2, velocity, 1, inertia));

  body1->addContactShape(createSPtrOccContactShape(sphere1_contact));
  body2->addContactShape(createSPtrOccContactShape(sphere2_contact));

  std::cout << "umin1:" << body1->contactShape(0).binf1[0] << std::endl;
  std::cout << "umax1:" << body1->contactShape(0).bsup1[0] << std::endl;
  std::cout << "vmin1:" << body1->contactShape(0).binf1[1] << std::endl;
  std::cout << "vmax1:" << body1->contactShape(0).bsup1[1] << std::endl;

  std::cout << "umin2:" << body2->contactShape(0).binf1[0] << std::endl;
  std::cout << "umax2:" << body2->contactShape(0).bsup1[0] << std::endl;
  std::cout << "vmin2:" << body2->contactShape(0).binf1[1] << std::endl;
  std::cout << "vmax2:" << body2->contactShape(0).bsup1[1] << std::endl;

  gp_XYZ translat1 = body1->contactShape(0).data().Location().Transformation().
    TranslationPart();

  std::cout << translat1.X() << "," << translat1.Y() << "," << translat1.Z()
            << std::endl;

  gp_XYZ translat2 = body2->contactShape(0).data().Location().Transformation().
    TranslationPart();

  std::cout << translat2.X() << "," << translat2.Y() << "," << translat2.Z()
            << std::endl;

  SP::ContactShapeDistance pdist =
    body1->contactShape(0).distance(body2->contactShape(0));

  ContactShapeDistance& dist = *pdist;

  std::cout << dist.value << std::endl;

  std::cout << dist.x1 << "," << dist.y1 << "," << dist.z1 << std::endl;

  std::cout << dist.x2 << "," << dist.y2 << "," << dist.z2 << std::endl;

  std::cout << dist.nx << "," << dist.ny << "," << dist.nz << std::endl;

  CPPUNIT_ASSERT(std::abs(dist.value - 1.0) < 1e-9);

}
<|endoftext|>


<commit_before>
#include "MainWidget1.h"
#include <QtGui>

MainWidget1::MainWidget1(QWidget* parent)
    : QWidget(parent)
{
    MainButton_1 = new QPushButton("MainButton_1", this);
    setFixedSize(500, 500);
    setWindowTitle("MainWindow");
    MainButton_1->setFixedSize(200, 100);
    connect(MainButton_1, &QPushButton::clicked, this, &MainWidget1::sub_Send);

    setWindowIcon(QIcon("/home/sf/pose.jpg"));
    setWindowTitle("sss");

    this->setAutoFillBackground(true);
    QPixmap pixmap;
    bool bb = pixmap.load("./pose.jpg"); //设定图片
    Q_ASSERT(bb == true);
    QPalette palette = this->palette();                       //创建一个调色板对象
    palette.setBrush(this->backgroundRole(), QBrush(pixmap)); //用调色板的画笔把映射到pixmap上的图片画到frame.backgroundRole()这个背景上
    this->setPalette(palette);
}
void MainWidget1::sub_Send(void)
{
    // emit Send_Open();
    MainButton_1->setText("aaaaa中文 中文aassa");
}

void MainWidget1::paintEvent(QPaintEvent* p)

{
#if 0
    QPixmap pixmap;
    bool bb = pixmap.load("./pose.jpg"); //设定图片
    Q_ASSERT(bb == true);
    // QPalette palette = this->palette();                       //创建一个调色板对象
    // palette.setBrush(this->backgroundRole(), QBrush(pixmap)); //用调色板的画笔把映射到pixmap上的图片画到frame.backgroundRole()这个背景上
    // connect(this,&MainWidget::Send_Open,&w2,&Sec_Widget::Cao_1);
    QPainter painter(this);

    painter.drawPixmap(0, 0, 500, 500, pixmap);

    painter.setPen(QPen(Qt::blue, 2, Qt::SolidLine, Qt::RoundCap));
    painter.drawLine(0, 28, this->width(), 28);
    painter.drawLine(1006, 28, 1006, this->height());
#endif
}<commit_msg>cplussharp vscode qttest QLabel绘制<commit_after>
#include "MainWidget1.h"
#include <QtGui>
#include <QLabel>

MainWidget1::MainWidget1(QWidget* parent)
    : QWidget(parent)
{
    MainButton_1 = new QPushButton("MainButton_1", this);
    // setFixedSize(500, 500);
    setWindowTitle("MainWindow");
    MainButton_1->setFixedSize(200, 100);
    connect(MainButton_1, &QPushButton::clicked, this, &MainWidget1::sub_Send);

    setWindowIcon(QIcon("/home/sf/pose.jpg"));
    setWindowTitle("sss");

    QLabel* qlabel = new QLabel(this);
    qlabel->setPixmap(QPixmap("./pose.jpg"));
    qlabel->setScaledContents(true);
    qlabel->setFixedSize(100, 100);
    qlabel->move(400, 400);

    this->setAutoFillBackground(true);
    QPixmap pixmap;
    bool bb = pixmap.load("./pose.jpg"); //设定图片
    Q_ASSERT(bb == true);
    QPalette palette = this->palette();                       //创建一个调色板对象
    palette.setBrush(this->backgroundRole(), QBrush(pixmap)); //用调色板的画笔把映射到pixmap上的图片画到frame.backgroundRole()这个背景上
    // this->setPalette(palette);
}
void MainWidget1::sub_Send(void)
{
    // emit Send_Open();
    MainButton_1->setText("aaaaa中文 中文aassa");
}

void MainWidget1::paintEvent(QPaintEvent* p)

{
#if 1
    QPixmap pixmap;
    bool bb = pixmap.load("./pose.jpg"); //设定图片
    Q_ASSERT(bb == true);
    // QPalette palette = this->palette();                       //创建一个调色板对象
    // palette.setBrush(this->backgroundRole(), QBrush(pixmap)); //用调色板的画笔把映射到pixmap上的图片画到frame.backgroundRole()这个背景上
    // connect(this,&MainWidget::Send_Open,&w2,&Sec_Widget::Cao_1);
    QPainter painter(this);

    painter.drawPixmap(0, 0, this->width(), this->height(), pixmap);

    // painter.setPen(QPen(Qt::blue, 2, Qt::SolidLine, Qt::RoundCap));
    // painter.drawLine(0, 28, this->width(), 28);
    // painter.drawLine(1006, 28, 1006, this->height());
#endif
}<|endoftext|>