<commit_before>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/elementaryFluxModes/CSSAMethod.cpp,v $
//   $Revision: 1.7 $
//   $Name:  $
//   $Author: shoops $
//   $Date: 2009/08/17 19:56:49 $
// End CVS Header

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

/**
 *  CSSAMethod class.
 *  Methods to conduct Stoichiometric Stability Analysis.-
 */

#include "copasi.h"

#include "blaswrap.h"
#include "clapackwrap.h"

#include "elementaryFluxModes/CSSAMethod.h"
#include "elementaryFluxModes/CEFMTask.h"
#include "utilities/CCopasiProblem.h"
#include "elementaryFluxModes/CEFMMethod.h"
#include "elementaryFluxModes/CFluxMode.h"

#include "model/CModel.h"
#include "model/CState.h"
#include "utilities/CProcessReport.h"

/**
 *  Copy constructor.
 *  @param "const CSSAMethod &" src
 */
CSSAMethod::CSSAMethod(const CSSAMethod & src,
                       const CCopasiContainer * pParent):
    CEFMAlgorithm(src, pParent)
{}

CSSAMethod::CSSAMethod(const CCopasiContainer * pParent) :
    CEFMAlgorithm(CCopasiMethod::stoichiometricStabilityAnalysis, pParent)
{}

// taken from CEFMAlgorithm, modified to make reactions reversible, implicitely,
//  i.e. without changing the model itself.
bool CSSAMethod::initialize()
{
  CEFMTask * pTask = dynamic_cast< CEFMTask *>(getObjectParent());

  if (pTask == NULL) return false;

  mpModel = pTask->getProblem()->getModel();

  if (mpModel == NULL) return false;

  mFluxModes.clear();
  mReactions.cleanup();

  /* ModelStoi is the transpose of the models stoichiometry matrix */
  const CTransposeView< CMatrix< C_FLOAT64 > > ModelStoi(mpModel->getRedStoi());

  unsigned C_INT32 row, numRows = ModelStoi.numRows();
  unsigned C_INT32 col, numCols = ModelStoi.numCols();

  /* Get the reactions from the model */
  /* Note: We have as many reactions as we have rows in ModelStoi */
  CCopasiVectorNS < CReaction > & Reaction = mpModel->getReactions();

  /* Reversible reaction counter */
  mReversible = 0;

  for (row = 0; row < numRows; row++)
    {
      if (Reaction[row]->isReversible())
        mReversible++;
    }

  unsigned C_INT32 numOrigRows = numRows;
  numRows += mReversible;
  mNumReactions = numRows;

  mReversible = 0;
  /* Size the stoichiometry matrix passed to the algorithm */
  mStoi.resize(numRows);
  std::vector< std::vector< C_FLOAT64 > >::iterator it = mStoi.begin();
  std::vector< std::vector< C_FLOAT64 > >::iterator end = mStoi.end();

  for (; it != end; ++it)
    it->resize(numCols);

  /* Vector to keep track of the rearrangements necessary to put the */
  /* reversible reactions to the top of stoichiometry matrix */
  mReorderedReactions.resize(numRows);
  mIsBackwardReaction.resize(numRows);

  unsigned C_INT32 Insert;
  unsigned C_INT32 InsertReversible = 0;
  unsigned C_INT32 InsertIrreversible = numRows - 1;

  /* Build the transpose of the stoichiometry matrix, */

  /* sort reversible reactions to the top, count them */

  /* and keep track of the rearrangement */

  //for (row = 0; row < numOrigRows; row++)
  for (row = 0; row < numOrigRows; row++)
    {
      if (Reaction[row]->isReversible())
        {
          Insert = InsertReversible++;
          mIsBackwardReaction[Insert] = true;

          mReversible++;
        }
      else
        {
          Insert = InsertIrreversible--;
          mIsBackwardReaction[Insert] = false;
        }

      mReorderedReactions[Insert] = Reaction[row];

      for (col = 0; col < numCols; col++)
        {
          mStoi[Insert][col] = ModelStoi(row, col);

          if (Reaction[row]->isReversible())
            mStoi[InsertReversible - 1][col] = - ModelStoi(row, col);
        }
    }

#ifdef COPASI_DEBUG
  std::cout << "mStoi:\n";

  for (int i = 0; i < numRows; ++i)
    {
      for (int j = 0; j < numCols; ++j)
        {
          std::cout << mStoi[i][j];
          std::cout << " ";
        }

      std::cout << std::endl;
    }

#endif

  mStep = 0;
  mMaxStep = numCols;

  if (mpCallBack)
    mhSteps =
      mpCallBack->addItem("Current Step",
                          CCopasiParameter::UINT,
                          & mStep,
                          & mMaxStep);

  return true;
}

bool CSSAMethod::process(CProcessReport *)
{
  return false;
}

bool
CSSAMethod::calculate()
{
  if (!initialize()) return false;

  if (!mpModel) return false;

  //initialize matrices for calculation;
  //  if (mpModel->compileIfNecessary(NULL))
  //    {
  buildStoichiometry();
  buildKineticMatrix();
  buildExtremeCurrents();
  //}
  //  else
  //    return false;

  if (!testForMixingStability())
    return false;

  return true;
}

TriLogic
CSSAMethod::isMixingStable(int indexEC)
{return mIsMixingStable[indexEC];}

bool
CSSAMethod::isReactionReversed(int index) const
{return mIsBackwardReaction[index];}

bool
CSSAMethod::testForMixingStability()
{
  decomposeJacobian();

  C_INT32 numECs = mExtremeCurrents.size();

  C_INT32 ijmax = mTransformedSubJacobians[0].numRows();

  mIsMixingStable.clear();

  C_FLOAT64 outarray[ijmax*ijmax];
  memset(outarray, 0, ijmax*ijmax*sizeof(C_FLOAT64));

  for (int ecIndex = 0; ecIndex < numECs; ++ecIndex)
    {
      C_FLOAT64 *inarray = mTransformedSubJacobians[ecIndex].array();

      // add matrix and its extremeCurrent - upper triangle only
      for (int i = 0; i < ijmax; ++i)
        for (int j = i; j < ijmax; ++j)
          outarray[i + j*ijmax] = inarray[i + j * ijmax] + inarray[j + i * ijmax];

      // get the eigenvalues AND eigenvectors:
      // input to dsyev_()
      char jobz = 'V';
      char uplo = 'U';
      C_INT32 n = ijmax;
      C_FLOAT64 *A = outarray;
      C_INT32 lda = ijmax;
      C_INT32 lwork = 64 * ijmax;
      // dsyev_() output
      C_FLOAT64 eigenvalues[ijmax];
      C_FLOAT64 work[lwork];
      C_INT32 info;

      dsyev_(&jobz, &uplo, &n, A, &lda, eigenvalues, work, &lwork, &info);

      if (info)
        return false;  // maybe raise an exception here, to discriminate from the sane case

      CVector<C_FLOAT64> EC = mExtremeCurrents[ecIndex];

      // set the state to 'stable' (1 - stable; 0 - unknown; -1 - not mixing stable)
      TriLogic state = TriTrue;

      int partMetabs[ijmax];
      memset(&partMetabs, 0, ijmax*sizeof(int));

      for (int j = 0; j < EC.size(); ++j)
        {
          if (EC[j])
            {
              // if one reaction's kinetic function is not Mass Action Law,
              //  this method is not valid and we can say nothing definite
              //  about the stability of this EC.
              std::string type = mReorderedReactions[j]->getFunction()->getObjectName();
              // std::cout << "Reaction type: " << type << std::endl;

              if (type.find("Mass action") == std::string::npos &&
                  type.find("Constant flux") == std::string::npos)
                {
                  state = TriUnspecified;
                  break;
                }

              for (int i = 0; i < ijmax; ++i)
                {
                  if (mStoi[j][i])
                    {
                      partMetabs[i] = 1;
                      break;
                    }
                }
            }
        }

      if (state == TriTrue)
        {
          // eigenvalues are sorted in rising order, and if the last ev is
          //   not positive, we have still to look after zero evs.
          if (eigenvalues[ijmax - 1] > 0)
            state = TriFalse;
          else
            {
              int zeroes = 0;

              for (int i = 0; i < ijmax && state == 1; ++i)
                {
                  // only count zero eigenvals if the eigenvector contains a reaction
                  //  that is participating in this extreme current.
                  if (eigenvalues[i] == 0)
                    {
                      for (int j = 0; j < ijmax; ++ j)
                        if (partMetabs[j] && outarray[i*ijmax + j])
                          if (++zeroes)
                            break;

                      if (zeroes == 2)
                        state = TriFalse;
                    }
                }
            }
        }

#ifdef COPASI_DEBUG
      std::cout << std::endl << std::endl;
      std::cout << "EC" << std::endl << "  (";

      for (int j = 0; j < mExtremeCurrents[0].size(); ++j)
        std::cout << mExtremeCurrents[ecIndex][j] << " ";

      std::cout << ")" << std::endl << std::endl;

      std::cout << "sub-jacobian #" << ecIndex + 1 << ":\n" << mTransformedSubJacobians[ecIndex] << "\n";

      std::cout << "\nEigenval\tEigenvector\tParticipating" << std::endl;

      for (int i = 0; i < ijmax; ++i)
        {
          std::cout << eigenvalues[i] << std::endl;

          for (int j = 0; j < ijmax; ++j)
            std::cout << "  \t\t\t" << outarray[i*ijmax + j] << "\t\t" << partMetabs[j] << std::endl;

          std::cout << std::endl;
        }

      if (state == TriUnspecified)
        std::cout << "unknown";
      else if (state == TriFalse)
        std::cout << "not mixing stable";
      else
        std::cout << "mixing stable";

      std::cout << std::endl << std::endl;
#endif // COPASI_DEBUG
      mIsMixingStable.push_back(state);
    }

#ifdef COPASI_DEBUG
  std::cout << std::endl;
  std::cout << "There is/are " << mIsMixingStable.size()
            << " extreme current(s) not mixing stable!" << std::endl;
#endif //COPASI_DEBUG

  return true;
}

bool
CSSAMethod::decomposeJacobian()
{
  mTransformedSubJacobians.clear();

  // parameters for the double matrix multiplication with dgemm_
  char cN = 'N';                         // don't transpose matrices
  C_INT m = mStoichiometry.numRows();    // the leading dimension of the Stoi.M. and of the resulting M.
  C_INT n = mStoichiometry.numCols();    // the dimensions of matrix diagE, also used as 'k'.

  C_FLOAT64 alpha = 1.;
  C_FLOAT64 beta = 0.;

  CMatrix< C_FLOAT64 > product;
  product.resize(m, m);

  std::vector< CVector<C_FLOAT64> >::iterator iter;

  for (iter = mExtremeCurrents.begin(); iter != mExtremeCurrents.end(); ++iter)
    {
      CMatrix<C_FLOAT64> diagE = diag(*iter);

      // compute N*Ei*kappa^T:
      // As the representation of the matrices in their arrays is in
      // transposed (mathematical) order, we compute kappa*Ei*N^T,
      // which corresponds to
      // (mTransposedKineticMatrix*diagE)*mStoichiometry
      C_FLOAT64 dummy[m*n];
      dgemm_(&cN, &cN,
             &m, &n, &n, &alpha,
             mTransposedKineticMatrix.array(), &m ,
             diagE.array(), &n,
             &beta, dummy, &m);
      dgemm_(&cN, &cN,
             &m, &m, &n, &alpha,
             dummy, &m,
             mStoichiometry.array(), &n,
             &beta, product.array(), &m);

      mTransformedSubJacobians.push_back(product);
    }

  return true;
}

bool
CSSAMethod::buildStoichiometry()
{
  if (!mpModel) return false;

  //rebuild the stoichiometric matrix with reversible reactions divided into two.

  // build the _transposed_ of stoichiometry, with expanded reversible reactions
  int numRows = mStoi[0].size();
  int numCols = mStoi.size();

  mStoichiometry.resize(numRows, numCols);
  memset(mStoichiometry.array(), 0, numRows*numCols*sizeof(C_FLOAT64));

  for (int i = 0; i < numRows; ++i)
    for (int j = 0; j < numCols; ++j)
      mStoichiometry(i, j) = mStoi[j][i];

#ifdef COPASI_DEBUG
  std::cout << std::endl << std::endl << "new stoichiometry:" << std::endl << mStoichiometry << std::endl;
#endif

  return true;
}

bool
CSSAMethod::buildKineticMatrix()
{
  if (!mpModel) return false;

  C_FLOAT64 num_metabolites = mpModel->getNumIndependentReactionMetabs();

  C_FLOAT64 num_reactions = mNumReactions;

  mTransposedKineticMatrix.resize((C_INT64)num_reactions, (C_INT64)num_metabolites);
  memset(mTransposedKineticMatrix.array(), 0, (int)(num_metabolites*num_reactions*sizeof(C_FLOAT64)));

  CCopasiVector< CMetab > & metabOrder = mpModel->getMetabolitesX();

  for (int ireac = 0; ireac < mIsBackwardReaction.size(); ++ireac)
    {
      CCopasiVector< CChemEqElement > substrates;

      if (mIsBackwardReaction[ireac])
        substrates = mReorderedReactions[ireac]->getChemEq().getProducts();
      else
        substrates = mReorderedReactions[ireac]->getChemEq().getSubstrates();

      for (int jsubst = 0; jsubst < substrates.size(); ++jsubst)
        {
          CCopasiVector< CMetab >::iterator found = find(metabOrder.begin(),
              metabOrder.end(),
              substrates[jsubst]->getMetabolite());

          if ((*found)->isDependent()) continue;

          int kmetab = std::distance(metabOrder.begin(), found);
          mTransposedKineticMatrix[ireac][kmetab] = substrates[jsubst]->getMultiplicity();
        }
    }

#ifdef COPASI_DEBUG
  std::cout << "transposed kinetic matrix: " << std::endl
            << mTransposedKineticMatrix << std::endl
            << std::endl;
#endif // COPASI_DEBUG

  return true;
}

bool
CSSAMethod::buildExtremeCurrents()
{
  mExtremeCurrents.clear();

  calculateFluxModes();

  std::vector< CFluxMode > fluxmodes = getFluxModes();

  CVector< C_FLOAT64 > extremecurrent;
  extremecurrent.resize(mNumReactions);

  std::vector< CFluxMode >::iterator iter;

  for (iter = fluxmodes.begin(); iter != fluxmodes.end(); ++iter)
    {
      memset(extremecurrent.array(), 0, extremecurrent.size()*sizeof(C_FLOAT64));
      unsigned C_INT32 i;

      for (i = 0; i < iter->size(); ++i)
        {
          extremecurrent[iter->getReactionIndex(i)] = iter->getMultiplier(i);
        }

#ifdef COPASI_DEBUG
      std::cout << "extreme current #" << distance(fluxmodes.begin(), iter) << std::endl
                << "  " << extremecurrent << std::endl << std::endl;
      mExtremeCurrents.push_back(extremecurrent);
#endif
    }

  return true;
}
<commit_msg>Removed debugging output.<commit_after>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/elementaryFluxModes/CSSAMethod.cpp,v $
//   $Revision: 1.8 $
//   $Name:  $
//   $Author: shoops $
//   $Date: 2009/09/22 14:58:11 $
// End CVS Header

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

/**
 *  CSSAMethod class.
 *  Methods to conduct Stoichiometric Stability Analysis.-
 */

#include "copasi.h"

#include "blaswrap.h"
#include "clapackwrap.h"

#include "elementaryFluxModes/CSSAMethod.h"
#include "elementaryFluxModes/CEFMTask.h"
#include "utilities/CCopasiProblem.h"
#include "elementaryFluxModes/CEFMMethod.h"
#include "elementaryFluxModes/CFluxMode.h"

#include "model/CModel.h"
#include "model/CState.h"
#include "utilities/CProcessReport.h"

/**
 *  Copy constructor.
 *  @param "const CSSAMethod &" src
 */
CSSAMethod::CSSAMethod(const CSSAMethod & src,
                       const CCopasiContainer * pParent):
    CEFMAlgorithm(src, pParent)
{}

CSSAMethod::CSSAMethod(const CCopasiContainer * pParent) :
    CEFMAlgorithm(CCopasiMethod::stoichiometricStabilityAnalysis, pParent)
{}

// taken from CEFMAlgorithm, modified to make reactions reversible, implicitely,
//  i.e. without changing the model itself.
bool CSSAMethod::initialize()
{
  CEFMTask * pTask = dynamic_cast< CEFMTask *>(getObjectParent());

  if (pTask == NULL) return false;

  mpModel = pTask->getProblem()->getModel();

  if (mpModel == NULL) return false;

  mFluxModes.clear();
  mReactions.cleanup();

  /* ModelStoi is the transpose of the models stoichiometry matrix */
  const CTransposeView< CMatrix< C_FLOAT64 > > ModelStoi(mpModel->getRedStoi());

  unsigned C_INT32 row, numRows = ModelStoi.numRows();
  unsigned C_INT32 col, numCols = ModelStoi.numCols();

  /* Get the reactions from the model */
  /* Note: We have as many reactions as we have rows in ModelStoi */
  CCopasiVectorNS < CReaction > & Reaction = mpModel->getReactions();

  /* Reversible reaction counter */
  mReversible = 0;

  for (row = 0; row < numRows; row++)
    {
      if (Reaction[row]->isReversible())
        mReversible++;
    }

  unsigned C_INT32 numOrigRows = numRows;
  numRows += mReversible;
  mNumReactions = numRows;

  mReversible = 0;
  /* Size the stoichiometry matrix passed to the algorithm */
  mStoi.resize(numRows);
  std::vector< std::vector< C_FLOAT64 > >::iterator it = mStoi.begin();
  std::vector< std::vector< C_FLOAT64 > >::iterator end = mStoi.end();

  for (; it != end; ++it)
    it->resize(numCols);

  /* Vector to keep track of the rearrangements necessary to put the */
  /* reversible reactions to the top of stoichiometry matrix */
  mReorderedReactions.resize(numRows);
  mIsBackwardReaction.resize(numRows);

  unsigned C_INT32 Insert;
  unsigned C_INT32 InsertReversible = 0;
  unsigned C_INT32 InsertIrreversible = numRows - 1;

  /* Build the transpose of the stoichiometry matrix, */

  /* sort reversible reactions to the top, count them */

  /* and keep track of the rearrangement */

  //for (row = 0; row < numOrigRows; row++)
  for (row = 0; row < numOrigRows; row++)
    {
      if (Reaction[row]->isReversible())
        {
          Insert = InsertReversible++;
          mIsBackwardReaction[Insert] = true;

          mReversible++;
        }
      else
        {
          Insert = InsertIrreversible--;
          mIsBackwardReaction[Insert] = false;
        }

      mReorderedReactions[Insert] = Reaction[row];

      for (col = 0; col < numCols; col++)
        {
          mStoi[Insert][col] = ModelStoi(row, col);

          if (Reaction[row]->isReversible())
            mStoi[InsertReversible - 1][col] = - ModelStoi(row, col);
        }
    }

  mStep = 0;
  mMaxStep = numCols;

  if (mpCallBack)
    mhSteps =
      mpCallBack->addItem("Current Step",
                          CCopasiParameter::UINT,
                          & mStep,
                          & mMaxStep);

  return true;
}

bool CSSAMethod::process(CProcessReport *)
{
  return false;
}

bool
CSSAMethod::calculate()
{
  if (!initialize()) return false;

  if (!mpModel) return false;

  //initialize matrices for calculation;
  //  if (mpModel->compileIfNecessary(NULL))
  //    {
  buildStoichiometry();
  buildKineticMatrix();
  buildExtremeCurrents();
  //}
  //  else
  //    return false;

  if (!testForMixingStability())
    return false;

  return true;
}

TriLogic
CSSAMethod::isMixingStable(int indexEC)
{return mIsMixingStable[indexEC];}

bool
CSSAMethod::isReactionReversed(int index) const
{return mIsBackwardReaction[index];}

bool
CSSAMethod::testForMixingStability()
{
  decomposeJacobian();

  C_INT32 numECs = mExtremeCurrents.size();

  C_INT32 ijmax = mTransformedSubJacobians[0].numRows();

  mIsMixingStable.clear();

  C_FLOAT64 outarray[ijmax*ijmax];
  memset(outarray, 0, ijmax*ijmax*sizeof(C_FLOAT64));

  for (int ecIndex = 0; ecIndex < numECs; ++ecIndex)
    {
      C_FLOAT64 *inarray = mTransformedSubJacobians[ecIndex].array();

      // add matrix and its extremeCurrent - upper triangle only
      for (int i = 0; i < ijmax; ++i)
        for (int j = i; j < ijmax; ++j)
          outarray[i + j*ijmax] = inarray[i + j * ijmax] + inarray[j + i * ijmax];

      // get the eigenvalues AND eigenvectors:
      // input to dsyev_()
      char jobz = 'V';
      char uplo = 'U';
      C_INT32 n = ijmax;
      C_FLOAT64 *A = outarray;
      C_INT32 lda = ijmax;
      C_INT32 lwork = 64 * ijmax;
      // dsyev_() output
      C_FLOAT64 eigenvalues[ijmax];
      C_FLOAT64 work[lwork];
      C_INT32 info;

      dsyev_(&jobz, &uplo, &n, A, &lda, eigenvalues, work, &lwork, &info);

      if (info)
        return false;  // maybe raise an exception here, to discriminate from the sane case

      CVector<C_FLOAT64> EC = mExtremeCurrents[ecIndex];

      // set the state to 'stable' (1 - stable; 0 - unknown; -1 - not mixing stable)
      TriLogic state = TriTrue;

      int partMetabs[ijmax];
      memset(&partMetabs, 0, ijmax*sizeof(int));

      for (int j = 0; j < EC.size(); ++j)
        {
          if (EC[j])
            {
              // if one reaction's kinetic function is not Mass Action Law,
              //  this method is not valid and we can say nothing definite
              //  about the stability of this EC.
              std::string type = mReorderedReactions[j]->getFunction()->getObjectName();

              if (type.find("Mass action") == std::string::npos &&
                  type.find("Constant flux") == std::string::npos)
                {
                  state = TriUnspecified;
                  break;
                }

              for (int i = 0; i < ijmax; ++i)
                {
                  if (mStoi[j][i])
                    {
                      partMetabs[i] = 1;
                      break;
                    }
                }
            }
        }

      if (state == TriTrue)
        {
          // eigenvalues are sorted in rising order, and if the last ev is
          //   not positive, we have still to look after zero evs.
          if (eigenvalues[ijmax - 1] > 0)
            state = TriFalse;
          else
            {
              int zeroes = 0;

              for (int i = 0; i < ijmax && state == 1; ++i)
                {
                  // only count zero eigenvals if the eigenvector contains a reaction
                  //  that is participating in this extreme current.
                  if (eigenvalues[i] == 0)
                    {
                      for (int j = 0; j < ijmax; ++ j)
                        if (partMetabs[j] && outarray[i*ijmax + j])
                          if (++zeroes)
                            break;

                      if (zeroes == 2)
                        state = TriFalse;
                    }
                }
            }
        }

      mIsMixingStable.push_back(state);
    }

  return true;
}

bool
CSSAMethod::decomposeJacobian()
{
  mTransformedSubJacobians.clear();

  // parameters for the double matrix multiplication with dgemm_
  char cN = 'N';                         // don't transpose matrices
  C_INT m = mStoichiometry.numRows();    // the leading dimension of the Stoi.M. and of the resulting M.
  C_INT n = mStoichiometry.numCols();    // the dimensions of matrix diagE, also used as 'k'.

  C_FLOAT64 alpha = 1.;
  C_FLOAT64 beta = 0.;

  CMatrix< C_FLOAT64 > product;
  product.resize(m, m);

  std::vector< CVector<C_FLOAT64> >::iterator iter;

  for (iter = mExtremeCurrents.begin(); iter != mExtremeCurrents.end(); ++iter)
    {
      CMatrix<C_FLOAT64> diagE = diag(*iter);

      // compute N*Ei*kappa^T:
      // As the representation of the matrices in their arrays is in
      // transposed (mathematical) order, we compute kappa*Ei*N^T,
      // which corresponds to
      // (mTransposedKineticMatrix*diagE)*mStoichiometry
      C_FLOAT64 dummy[m*n];
      dgemm_(&cN, &cN,
             &m, &n, &n, &alpha,
             mTransposedKineticMatrix.array(), &m ,
             diagE.array(), &n,
             &beta, dummy, &m);
      dgemm_(&cN, &cN,
             &m, &m, &n, &alpha,
             dummy, &m,
             mStoichiometry.array(), &n,
             &beta, product.array(), &m);

      mTransformedSubJacobians.push_back(product);
    }

  return true;
}

bool
CSSAMethod::buildStoichiometry()
{
  if (!mpModel) return false;

  //rebuild the stoichiometric matrix with reversible reactions divided into two.

  // build the _transposed_ of stoichiometry, with expanded reversible reactions
  int numRows = mStoi[0].size();
  int numCols = mStoi.size();

  mStoichiometry.resize(numRows, numCols);
  memset(mStoichiometry.array(), 0, numRows*numCols*sizeof(C_FLOAT64));

  for (int i = 0; i < numRows; ++i)
    for (int j = 0; j < numCols; ++j)
      mStoichiometry(i, j) = mStoi[j][i];

  return true;
}

bool
CSSAMethod::buildKineticMatrix()
{
  if (!mpModel) return false;

  C_FLOAT64 num_metabolites = mpModel->getNumIndependentReactionMetabs();

  C_FLOAT64 num_reactions = mNumReactions;

  mTransposedKineticMatrix.resize((C_INT64)num_reactions, (C_INT64)num_metabolites);
  memset(mTransposedKineticMatrix.array(), 0, (int)(num_metabolites*num_reactions*sizeof(C_FLOAT64)));

  CCopasiVector< CMetab > & metabOrder = mpModel->getMetabolitesX();

  for (int ireac = 0; ireac < mIsBackwardReaction.size(); ++ireac)
    {
      CCopasiVector< CChemEqElement > substrates;

      if (mIsBackwardReaction[ireac])
        substrates = mReorderedReactions[ireac]->getChemEq().getProducts();
      else
        substrates = mReorderedReactions[ireac]->getChemEq().getSubstrates();

      for (int jsubst = 0; jsubst < substrates.size(); ++jsubst)
        {
          CCopasiVector< CMetab >::iterator found = find(metabOrder.begin(),
              metabOrder.end(),
              substrates[jsubst]->getMetabolite());

          if ((*found)->isDependent()) continue;

          int kmetab = std::distance(metabOrder.begin(), found);
          mTransposedKineticMatrix[ireac][kmetab] = substrates[jsubst]->getMultiplicity();
        }
    }

  return true;
}

bool
CSSAMethod::buildExtremeCurrents()
{
  mExtremeCurrents.clear();

  calculateFluxModes();

  std::vector< CFluxMode > fluxmodes = getFluxModes();

  CVector< C_FLOAT64 > extremecurrent;
  extremecurrent.resize(mNumReactions);

  std::vector< CFluxMode >::iterator iter;

  for (iter = fluxmodes.begin(); iter != fluxmodes.end(); ++iter)
    {
      memset(extremecurrent.array(), 0, extremecurrent.size()*sizeof(C_FLOAT64));
      unsigned C_INT32 i;

      for (i = 0; i < iter->size(); ++i)
        {
          extremecurrent[iter->getReactionIndex(i)] = iter->getMultiplier(i);
        }
    }

  return true;
}
<|endoftext|>


<commit_before>/*
 * This file is part of the CN24 semantic segmentation software,
 * copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com).
 *
 * For licensing information, see the LICENSE file included with this project.
 */
/**
 * @file runBenchmark.cpp
 *
 * @author Clemens-Alexander Brust (ikosa dot de at gmail dot com)
 */

#include <iostream>
#include <fstream>
#include <cstring>
#include <sstream>
#include <chrono>

#include <cn24.h>

std::string hardcoded_net = "# Sample CNN for LabelMeFacade Dataset \n\
#anual rfx=34 rfy=34 factorx=4 factory=4 \n\
 \n\
# Network configuration \n\
?convolutional kernels=16 size=7x7 \n\
?maxpooling size=4x4 \n\
?tanh \n\
 \n\
?convolutional kernels=12 size=5x5 \n\
?maxpooling size=2x2 \n\
?tanh \n\
 \n\
?convolutional kernels=96 size=5x5 \n\
?tanh \n\
 \n\
?fullyconnected neurons=512 \n\
?tanh \n\
 \n\
?fullyconnected neurons=192 \n\
?tanh \n\
 \n\
?fullyconnected neurons=(o) \n\
?output \n\
 \n\
# Learning settings \n\
l1=0.000 \n\
l2=0.0008 \n\
lr=0.02 \n\
gamma=0.003 \n\
momentum=0.9 \n\
exponent=0.75 \n\
iterations=100 \n\
sbatchsize=24 \n\
pbatchsize=2 \n\
mu=1.75 \n\
eta=0.1 \n\
";

std::string hardcoded_net_ci = "# Sample CNN for LabelMeFacade Dataset \n\
#anual rfx=34 rfy=34 factorx=4 factory=4 \n\
 \n\
# Network configuration \n\
?convolutional kernels=8 size=7x7 \n\
?maxpooling size=2x2 \n\
 \n\
?convolutional kernels=4 size=5x5 \n\
?tanh \n\
 \n\
?convolutional kernels=12 size=5x5 \n\
?tanh \n\
 \n\
?fullyconnected neurons=64 \n\
?tanh \n\
 \n\
?fullyconnected neurons=(o) \n\
?output \n\
 \n\
# Learning settings \n\
l1=0.000 \n\
l2=0.0008 \n\
lr=0.02 \n\
gamma=0.003 \n\
momentum=0.9 \n\
exponent=0.75 \n\
iterations=100 \n\
sbatchsize=24 \n\
pbatchsize=2 \n\
mu=1.75 \n\
eta=0.1 \n\
";

int main (int argc, char* argv[]) {
  // Initialize stat descriptor
  Conv::StatDescriptor fps;
  fps.nullable = false;
  fps.description = "Throughput";
  fps.unit = "frames/s";
  fps.init_function = [] (Conv::Stat& stat) {
    stat.is_null = false;
    stat.value = 0.0;
  };
  fps.output_function = [] (Conv::HardcodedStats& hc_stats, Conv::Stat& stat) {
    Conv::Stat return_stat = stat;
    return_stat.value = stat.value / hc_stats.seconds_elapsed;
    return return_stat;
  };
  fps.update_function = [] (Conv::Stat& stat, double user_value) {
    stat.value += user_value;
  };

  // Initialize CN24
  Conv::System::Init();

  // Register ConsoleStatSink
  Conv::ConsoleStatSink sink;
  Conv::System::stat_aggregator->RegisterSink(&sink);

  // Register fps counter
  Conv::System::stat_aggregator->RegisterStat(&fps);

  // Capture command line arguments
  std::string net_config_fname;
  if(argc > 1) {
    net_config_fname = std::string(argv[1]);
    LOGDEBUG << "Using user specified net: " << net_config_fname;
  }

  // Set benchmark arguments
  unsigned int CLASSES = 10;
  unsigned int INPUTMAPS = 3;
	unsigned int BENCHMARK_PASSES_FWD = 30;
	unsigned int BENCHMARK_PASSES_BWD = 15;
  unsigned int width = 512;
  unsigned int height = 512;

  std::istream* net_config_stream;

  if(argc > 1 && net_config_fname.compare(0,4,"--ci") != 0) {
    // Open network and dataset configuration files
    std::ifstream* net_config_file = new std::ifstream(net_config_fname,std::ios::in);

    if(!net_config_file->good()) {
      FATAL("Cannot open net configuration file!");
    }
      net_config_stream = net_config_file;
  } else {
    if(net_config_fname.compare(0,4,"--ci") == 0) {
      LOGINFO << "Using hardcoded net for continuous integration.";
      std::stringstream* ss = new std::stringstream(hardcoded_net_ci);
      net_config_stream = ss;
      width = 64;
      height = 64;
    } else {
      LOGINFO << "Using hardcoded net.";
      std::stringstream* ss = new std::stringstream(hardcoded_net);
      net_config_stream = ss;
    }
  }

  // Parse network configuration file
  Conv::ConfigurableFactory* factory = new Conv::ConfigurableFactory(*net_config_stream, 238238, false);

  Conv::Tensor data_tensor(factory->optimal_settings().pbatchsize, width, height, INPUTMAPS);
  data_tensor.Clear();

  // Assemble net
	Conv::NetGraph graph;
  Conv::InputLayer input_layer(data_tensor);

	Conv::NetGraphNode input_node(&input_layer);
  input_node.is_input = true;

	graph.AddNode(&input_node);
	bool complete = factory->AddLayers(graph, Conv::NetGraphConnection(&input_node), CLASSES);
	if (!complete)
    FATAL("Failed completeness check, inspect model!");
	factory->InitOptimalSettings();

	LOGINFO << "Initializing net, this may take a while..." << std::flush;
	graph.Initialize();
  graph.SetIsTesting(true);

  // Initialize StatAggregator
  Conv::System::stat_aggregator->Initialize();

  graph.FeedForward();
	graph.BackPropagate();

	LOGINFO << "Benchmark information";
	LOGINFO << "=====================";

	LOGINFO << "Input width    : " << width;
	LOGINFO << "Input height   : " << height;
	LOGINFO << "Parallel inputs: " << factory->optimal_settings().pbatchsize;
	LOGINFO << "=====================";

	LOGINFO << "Running forward benchmark...\n" << std::flush;
  Conv::System::stat_aggregator->StartRecording();
	{
		for(unsigned int p = 0; p < BENCHMARK_PASSES_FWD; p++) {
			graph.FeedForward();
      Conv::System::stat_aggregator->Update(fps.stat_id, (double)(factory->optimal_settings().pbatchsize));
			std::cout << "." << std::flush;
		}
		std::cout << "\n";
	}
  Conv::System::stat_aggregator->StopRecording();
  Conv::System::stat_aggregator->Generate();
	Conv::System::stat_aggregator->Reset();

  graph.SetIsTesting(false);
	LOGINFO << "Running forward+backward benchmark...\n" << std::flush;
  Conv::System::stat_aggregator->StartRecording();
	{
		for(unsigned int p = 0; p < BENCHMARK_PASSES_BWD; p++) {
			graph.FeedForward();
			graph.BackPropagate();
      Conv::System::stat_aggregator->Update(fps.stat_id, (double)(factory->optimal_settings().pbatchsize));
			std::cout << "." << std::flush;
		}
		std::cout << "\n";
	}
  Conv::System::stat_aggregator->StopRecording();
  Conv::System::stat_aggregator->Generate();
  Conv::System::stat_aggregator->Reset();

  // Gradient check
	LOGINFO << "Running sparse gradient check..." << std::flush;
  auto start_time = std::chrono::system_clock::now();
  Conv::GradientTester::TestGradient(graph, 999, true);

  auto stop_time = std::chrono::system_clock::now();
  std::chrono::duration<double> t_diff = stop_time - start_time;
  LOGRESULT << "Gradient check took " << t_diff.count() << " seconds." << LOGRESULTEND;

  LOGINFO << "DONE!";
  LOGEND;
  return 0;
}
<commit_msg>runBenchmark: Added random content<commit_after>/*
 * This file is part of the CN24 semantic segmentation software,
 * copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com).
 *
 * For licensing information, see the LICENSE file included with this project.
 */

/**
 * @file runBenchmark.cpp
 *
 * @author Clemens-Alexander Brust (ikosa dot de at gmail dot com)
 */

#include <iostream>
#include <fstream>
#include <cstring>
#include <sstream>
#include <chrono>
#include <random>

#include <cn24.h>

std::string hardcoded_net = "# Sample CNN for LabelMeFacade Dataset \n\
#anual rfx=34 rfy=34 factorx=4 factory=4 \n\
 \n\
# Network configuration \n\
?convolutional kernels=16 size=7x7 \n\
?maxpooling size=4x4 \n\
?tanh \n\
 \n\
?convolutional kernels=12 size=5x5 \n\
?maxpooling size=2x2 \n\
?tanh \n\
 \n\
?convolutional kernels=96 size=5x5 \n\
?tanh \n\
 \n\
?fullyconnected neurons=512 \n\
?tanh \n\
 \n\
?fullyconnected neurons=192 \n\
?tanh \n\
 \n\
?fullyconnected neurons=(o) \n\
?output \n\
 \n\
# Learning settings \n\
l1=0.000 \n\
l2=0.0008 \n\
lr=0.02 \n\
gamma=0.003 \n\
momentum=0.9 \n\
exponent=0.75 \n\
iterations=100 \n\
sbatchsize=24 \n\
pbatchsize=2 \n\
mu=1.75 \n\
eta=0.1 \n\
";

std::string hardcoded_net_ci = "# Sample CNN for LabelMeFacade Dataset \n\
#anual rfx=34 rfy=34 factorx=4 factory=4 \n\
 \n\
# Network configuration \n\
?convolutional kernels=8 size=7x7 \n\
?maxpooling size=2x2 \n\
 \n\
?convolutional kernels=4 size=5x5 \n\
?tanh \n\
 \n\
?convolutional kernels=12 size=5x5 \n\
?tanh \n\
 \n\
?fullyconnected neurons=64 \n\
?tanh \n\
 \n\
?fullyconnected neurons=(o) \n\
?output \n\
 \n\
# Learning settings \n\
l1=0.000 \n\
l2=0.0008 \n\
lr=0.02 \n\
gamma=0.003 \n\
momentum=0.9 \n\
exponent=0.75 \n\
iterations=100 \n\
sbatchsize=24 \n\
pbatchsize=2 \n\
mu=1.75 \n\
eta=0.1 \n\
";

int main (int argc, char* argv[]) {
  // Initialize stat descriptor
  Conv::StatDescriptor fps;
  fps.nullable = false;
  fps.description = "Throughput";
  fps.unit = "frames/s";
  fps.init_function = [] (Conv::Stat& stat) {
    stat.is_null = false;
    stat.value = 0.0;
  };
  fps.output_function = [] (Conv::HardcodedStats& hc_stats, Conv::Stat& stat) {
    Conv::Stat return_stat = stat;
    return_stat.value = stat.value / hc_stats.seconds_elapsed;
    return return_stat;
  };
  fps.update_function = [] (Conv::Stat& stat, double user_value) {
    stat.value += user_value;
  };

  // Initialize CN24
  Conv::System::Init();

  // Register ConsoleStatSink
  Conv::ConsoleStatSink sink;
  Conv::System::stat_aggregator->RegisterSink(&sink);

  // Register fps counter
  Conv::System::stat_aggregator->RegisterStat(&fps);

  // Capture command line arguments
  std::string net_config_fname;
  if(argc > 1) {
    net_config_fname = std::string(argv[1]);
    LOGDEBUG << "Using user specified net: " << net_config_fname;
  }

  // Set benchmark arguments
  unsigned int CLASSES = 10;
  unsigned int INPUTMAPS = 3;
	unsigned int BENCHMARK_PASSES_FWD = 30;
	unsigned int BENCHMARK_PASSES_BWD = 15;
  unsigned int width = 512;
  unsigned int height = 512;

  std::istream* net_config_stream;

  if(argc > 1 && net_config_fname.compare(0,4,"--ci") != 0) {
    // Open network and dataset configuration files
    std::ifstream* net_config_file = new std::ifstream(net_config_fname,std::ios::in);

    if(!net_config_file->good()) {
      FATAL("Cannot open net configuration file!");
    }
      net_config_stream = net_config_file;
  } else {
    if(net_config_fname.compare(0,4,"--ci") == 0) {
      LOGINFO << "Using hardcoded net for continuous integration.";
      std::stringstream* ss = new std::stringstream(hardcoded_net_ci);
      net_config_stream = ss;
      width = 64;
      height = 64;
    } else {
      LOGINFO << "Using hardcoded net.";
      std::stringstream* ss = new std::stringstream(hardcoded_net);
      net_config_stream = ss;
    }
  }

  // Parse network configuration file
  Conv::ConfigurableFactory* factory = new Conv::ConfigurableFactory(*net_config_stream, 238238, false);

  Conv::Tensor data_tensor(factory->optimal_settings().pbatchsize, width, height, INPUTMAPS);
  data_tensor.Clear();

  // Generate random contents
  std::mt19937 rand(1337);
  std::uniform_real_distribution<Conv::datum> dist (0.0, 1.0);
  for(unsigned int e = 0; e < data_tensor.elements(); e++) {
    (data_tensor.data_ptr())[e] = dist(rand);
  }

  // Assemble net
	Conv::NetGraph graph;
  Conv::InputLayer input_layer(data_tensor);

	Conv::NetGraphNode input_node(&input_layer);
  input_node.is_input = true;

	graph.AddNode(&input_node);
	bool complete = factory->AddLayers(graph, Conv::NetGraphConnection(&input_node), CLASSES);
	if (!complete)
    FATAL("Failed completeness check, inspect model!");
	factory->InitOptimalSettings();

	LOGINFO << "Initializing net, this may take a while..." << std::flush;
	graph.Initialize();
  graph.SetIsTesting(true);

  // Initialize StatAggregator
  Conv::System::stat_aggregator->Initialize();

  graph.FeedForward();
	graph.BackPropagate();

	LOGINFO << "Benchmark information";
	LOGINFO << "=====================";

	LOGINFO << "Input width    : " << width;
	LOGINFO << "Input height   : " << height;
	LOGINFO << "Parallel inputs: " << factory->optimal_settings().pbatchsize;
	LOGINFO << "=====================";

	LOGINFO << "Running forward benchmark...\n" << std::flush;
  Conv::System::stat_aggregator->StartRecording();
	{
		for(unsigned int p = 0; p < BENCHMARK_PASSES_FWD; p++) {
			graph.FeedForward();
      Conv::System::stat_aggregator->Update(fps.stat_id, (double)(factory->optimal_settings().pbatchsize));
			std::cout << "." << std::flush;
		}
		std::cout << "\n";
	}
  Conv::System::stat_aggregator->StopRecording();
  Conv::System::stat_aggregator->Generate();
	Conv::System::stat_aggregator->Reset();

  graph.SetIsTesting(false);
	LOGINFO << "Running forward+backward benchmark...\n" << std::flush;
  Conv::System::stat_aggregator->StartRecording();
	{
		for(unsigned int p = 0; p < BENCHMARK_PASSES_BWD; p++) {
			graph.FeedForward();
			graph.BackPropagate();
      Conv::System::stat_aggregator->Update(fps.stat_id, (double)(factory->optimal_settings().pbatchsize));
			std::cout << "." << std::flush;
		}
		std::cout << "\n";
	}
  Conv::System::stat_aggregator->StopRecording();
  Conv::System::stat_aggregator->Generate();
  Conv::System::stat_aggregator->Reset();

  // Gradient check
	LOGINFO << "Running sparse gradient check..." << std::flush;
  auto start_time = std::chrono::system_clock::now();
  Conv::GradientTester::TestGradient(graph, 999, true);

  auto stop_time = std::chrono::system_clock::now();
  std::chrono::duration<double> t_diff = stop_time - start_time;
  LOGRESULT << "Gradient check took " << t_diff.count() << " seconds." << LOGRESULTEND;

  LOGINFO << "DONE!";
  LOGEND;
  return 0;
}
<|endoftext|>


<commit_before>#include <memory>
#include <iostream>

#include <eventLoop.hxx>

#include <THandle.hxx>
#include <TG4Trajectory.hxx>

/// User code for the event loop.  This can be copied and used as a skeleton
/// for generic user loop programs.
class TUserLoop: public CP::TEventLoopFunction {
public:
    /// Initialize any class specific variables, but most of the work can be
    /// done in Initialize.  Don't create histograms here!
    TUserLoop() {}
    virtual ~TUserLoop() {};

    /// Print a usage message.  This is generally called when there is a
    /// command line input error.
    void Usage(void) {
    }

    /// Set an option and return true if it is valid.  This is called by the
    /// event loop command line argument processing code for each "-O
    /// [name]=[value]" option found on the command line.  If the command line
    /// has "-O [name]" without a value, then the value string will be equal
    /// to "".  This must return false if the option was not correctly
    /// processed.
    virtual bool SetOption(std::string option,std::string value="") {
        return false;
    }

    /// Called for each event inside the event loop, and returns true if the
    /// event should be saved to the output file.  If the remainder of the
    /// current file should be skipped, this should through the
    /// ENextEventLoopFile exception.  If the daughter class defines this
    /// operator, it should not define the Process() method.
    bool operator () (CP::TEvent& event) {
        CP::THandle<CP::TG4TrajectoryContainer> trajectories
            = event.Get<CP::TG4TrajectoryContainer>("truth/G4Trajectories");
        if (!trajectories) {
            std::cout << "No Trajectory container" << std::endl;
            return false;
        }
        trajectories->ls();
        CP::THandle<CP::TG4Trajectory> traj = trajectories->GetTrajectory(1);
        if (!traj) {
            std::cout << "No Trajectories" << std::endl;
        }
        std::cout << "Print the trajectory" << std::endl;
        traj->ls();
        std::cout << "Get the initial position" << std::endl;
        std::cout << " x " << traj->GetInitialPosition().X() << std::endl;
        std::cout << " y " << traj->GetInitialPosition().Y() << std::endl;
        std::cout << " z " << traj->GetInitialPosition().Z() << std::endl;
        std::cout << "Get the final position" << std::endl;
        std::cout << " x " << traj->GetFinalPosition().X() << std::endl;
        std::cout << " y " << traj->GetFinalPosition().Y() << std::endl;
        std::cout << " z " << traj->GetFinalPosition().Z() << std::endl;

        return true;
    }

    /// Called after the arguments are processed but before reading the first
    /// event.  The output file is open so any histograms will be added to the
    /// output file.
    virtual void Initialize(void) {
    }

    /// Called after reading the last event.  The output file is still open,
    /// so you can add extra information.  Because of an ideosyncracy in the
    /// way root handles histograms, objects created in Initialize() will
    /// already be stored in the output file.
    virtual void Finalize(CP::TRootOutput* output) {
    }

private:

};

int main(int argc, char **argv) {
    TUserLoop userLoop;
    CP::eventLoop(argc,argv,userLoop);
}
<commit_msg>Add example of how to write to a text file.<commit_after>#include <memory>
#include <iostream>
#include <fstream>

#include <eventLoop.hxx>

#include <THandle.hxx>
#include <TG4Trajectory.hxx>

/// User code for the event loop.  This can be copied and used as a skeleton
/// for generic user loop programs.
class TUserLoop: public CP::TEventLoopFunction {
public:
    /// Initialize any class specific variables, but most of the work can be
    /// done in Initialize.  Don't create histograms here!
    TUserLoop() {}
    virtual ~TUserLoop() {};

    /// Print a usage message.  This is generally called when there is a
    /// command line input error.
    void Usage(void) {
    }

    /// Set an option and return true if it is valid.  This is called by the
    /// event loop command line argument processing code for each "-O
    /// [name]=[value]" option found on the command line.  If the command line
    /// has "-O [name]" without a value, then the value string will be equal
    /// to "".  This must return false if the option was not correctly
    /// processed.
    virtual bool SetOption(std::string option,std::string value="") {
        return false;
    }

    /// Called for each event inside the event loop, and returns true if the
    /// event should be saved to the output file.  If the remainder of the
    /// current file should be skipped, this should through the
    /// ENextEventLoopFile exception.  If the daughter class defines this
    /// operator, it should not define the Process() method.
    bool operator () (CP::TEvent& event) {
        CP::THandle<CP::TG4TrajectoryContainer> trajectories
            = event.Get<CP::TG4TrajectoryContainer>("truth/G4Trajectories");
        if (!trajectories) {
            std::cout << "No Trajectory container" << std::endl;
            return false;
        }
        trajectories->ls();
        CP::THandle<CP::TG4Trajectory> traj = trajectories->GetTrajectory(1);
        if (!traj) {
            std::cout << "No Trajectories" << std::endl;
        }
        std::cout << "Print the trajectory" << std::endl;
        traj->ls();
        std::cout << "Get the initial position" << std::endl;
        std::cout << " x " << traj->GetInitialPosition().X() << std::endl;
        std::cout << " y " << traj->GetInitialPosition().Y() << std::endl;
        std::cout << " z " << traj->GetInitialPosition().Z() << std::endl;
        std::cout << "Get the final position" << std::endl;
        std::cout << " x " << traj->GetFinalPosition().X() << std::endl;
        std::cout << " y " << traj->GetFinalPosition().Y() << std::endl;
        std::cout << " z " << traj->GetFinalPosition().Z() << std::endl;

        double dx = traj->GetFinalPosition().X()-traj->GetInitialPosition().X();
        double dy = traj->GetFinalPosition().Y()-traj->GetInitialPosition().Y();
        double dz = traj->GetFinalPosition().Z()-traj->GetInitialPosition().Z();

        double length = std::sqrt(dx*dx + dy*dy + dz*dz);

        std::cout << length << std::endl;

        fOutput << length << std::endl;

        return true;
    }

    /// Called after the arguments are processed but before reading the first
    /// event.  The output file is open so any histograms will be added to the
    /// output file.
    virtual void Initialize(void) {
        fOutput.open("proton100.data");
    }

    /// Called after reading the last event.  The output file is still open,
    /// so you can add extra information.  Because of an ideosyncracy in the
    /// way root handles histograms, objects created in Initialize() will
    /// already be stored in the output file.
    virtual void Finalize(CP::TRootOutput* output) {
        fOutput.close();
    }

private:

    std::ofstream fOutput;

};

int main(int argc, char **argv) {
    TUserLoop userLoop;
    CP::eventLoop(argc,argv,userLoop);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include <string>

#include <itkImage.h>
#include <itkLinearInterpolateImageFunction.h>
#include <itkNearestNeighborInterpolateImageFunction.h>
#include <itkLabelImageGaussianInterpolateImageFunction.h>
#include <itkBSplineInterpolateImageFunction.h>
#include <itkResampleImageFilter.h>
#include <itkVersorRigid3DTransform.h>
#include <itkImageFileWriter.h>
#include <itkImageFileReader.h>
#include <itkTestingComparisonImageFilter.h>
#include <itkTimeProbe.h>

#include "itkLabelImageGenericInterpolateImageFunction.h"
#include "itkLabelSelectionAdaptor.h"

/* This demo is a torture test for interpolators: it takes an input label map,
 * rotates it one full turn in ten steps, and writes the result */

template <class ImageType>
void
RotateNTimes(typename ImageType::Pointer input,
    typename itk::InterpolateImageFunction<ImageType,double>* interpolator,
    unsigned int number_of_rotations, std::string outputFilename) {
	typedef itk::VersorRigid3DTransform<double> TransformType;
	typedef itk::ResampleImageFilter<ImageType,ImageType> ResampleFilterType;
	TransformType::AxisType axis;
	axis[0]=0;
	axis[1]=1;
	axis[2]=0;
	TransformType::InputPointType center;
	center[0] = 144;
	center[1] = 86;
	center[2] = 101;
	TransformType::Pointer rot = TransformType::New();
	rot->SetCenter(center);
	rot->SetRotation(axis,2.*M_PI/number_of_rotations);

	typename ResampleFilterType::Pointer rs = ResampleFilterType::New();
	rs->SetInput( input );
	rs->SetReferenceImage( input );
	rs->SetUseReferenceImage(true);
	rs->SetTransform(rot);
	//interp->SetSigma(0.3); // Used for the gaussian interpolator
	rs->SetInterpolator(interpolator);
	typename ImageType::Pointer out ;
  itk::TimeProbe timer; timer.Start();
	for (unsigned i = 0; i<number_of_rotations; ++i) {
		rs->SetReferenceImage( input );
		rs->SetUseReferenceImage(true);
		rs->Update();
		out = rs->GetOutput();
		out->DisconnectPipeline();
		rs->SetInput(out);
		rs->SetTransform(rot);
	}
  timer.Stop();
  typedef itk::Testing::ComparisonImageFilter<ImageType,ImageType> ComparisonFilterType;
  typename ComparisonFilterType::Pointer compare = ComparisonFilterType::New();
  compare->SetValidInput( input );
  compare->SetTestInput( out );
  compare->Update();
  std::cout << "Pixels with differences: " << std::setw(8) << compare->GetNumberOfPixelsWithDifferences() <<
    " ( " << std::fixed << std::setprecision(2) << static_cast<double>(compare->GetNumberOfPixelsWithDifferences()) /
    input->GetLargestPossibleRegion().GetNumberOfPixels() * 100.<<
    "% ) in " << timer.GetTotal() << "s" << std::endl;
	typedef  itk::ImageFileWriter< ImageType  > WriterType;
	typename WriterType::Pointer writer = WriterType::New();
	writer->SetUseCompression(true);
	writer->SetInput( out );
	writer->SetFileName(outputFilename);
	writer->Write();
}

// The BSpline interpolator has more arguments than other interpolators, so we set the additional parameter to the default value
using namespace std;
template<class TImage,typename TCoordRep> class BSplineInterpolator : public itk::BSplineInterpolateImageFunction<TImage,TCoordRep> {};

int main(int argc, char *argv[])
{
	string outputFilename = "resampled.mha";
	string inputFilename = "../Source/classification.mha";

	typedef unsigned char     PixelType;
	const   unsigned int    Dimension = 3;
	typedef itk::Image< PixelType, Dimension >  ImageType;

	typedef itk::ImageFileReader<ImageType> ReaderType;
	ReaderType::Pointer r = ReaderType::New();
	r->SetFileName(inputFilename);
	r->Update();

	for( unsigned number_of_rotations=3; number_of_rotations <=7;
      number_of_rotations+=2 ) {
    std::cout << "Testing with " << number_of_rotations << " rotations..." << std::endl << std::endl;

    std::cout << "Nearest neighbor interpolator...                        " << std::flush;
    typedef itk::NearestNeighborInterpolateImageFunction<ImageType,double> NNInterpolatorType;
    NNInterpolatorType::Pointer nn_interp = NNInterpolatorType::New();
    RotateNTimes<ImageType>(r->GetOutput(), nn_interp, number_of_rotations, "nearest.mha");

    std::cout << "Linear interpolator...                                  " << std::flush;
    typedef itk::LinearInterpolateImageFunction<ImageType,double> LInterpolatorType;
    LInterpolatorType::Pointer l_interp = LInterpolatorType::New();
    RotateNTimes<ImageType>(r->GetOutput(), l_interp, number_of_rotations, "linear.mha");

    std::cout << "Label Gaussian interpolator type...                     " << std::flush;
    typedef itk::LabelImageGaussianInterpolateImageFunction<ImageType,double> LGInterpolatorType;
    LGInterpolatorType::Pointer lg_interp = LGInterpolatorType::New();
    lg_interp->SetSigma(0.3);
    RotateNTimes<ImageType>(r->GetOutput(), lg_interp, number_of_rotations, "label_gaussian.mha");

    std::cout << "Generic label interpolator with nearest neighbor...     " << std::flush;
    typedef itk::LabelImageGenericInterpolateImageFunction<ImageType,itk::NearestNeighborInterpolateImageFunction> GNNInterpolatorType;
    GNNInterpolatorType::Pointer gnn_interp = GNNInterpolatorType::New();
    RotateNTimes<ImageType>(r->GetOutput(), gnn_interp, number_of_rotations, "gl_nearest.mha");

    std::cout << "Generic label interpolator with linear interpolation... " << std::flush;
    typedef itk::LabelImageGenericInterpolateImageFunction<ImageType,itk::LinearInterpolateImageFunction> GLInterpolatorType;
    GLInterpolatorType::Pointer gl_interp = GLInterpolatorType::New();
    RotateNTimes<ImageType>(r->GetOutput(), gl_interp, number_of_rotations, "gl_linear.mha");

    std::cout << "Generic label interpolator with B-Spline...             " << std::flush;
    typedef itk::LabelImageGenericInterpolateImageFunction<ImageType,BSplineInterpolator> GBSInterpolatorType;
    GBSInterpolatorType::Pointer gbs_interp = GBSInterpolatorType::New();
    RotateNTimes<ImageType>(r->GetOutput(), gbs_interp, number_of_rotations, "gl_bspline.mha");

    std::cout << std::endl;
  }

	return EXIT_SUCCESS;
}
<commit_msg>clean output and add gaussian interpolation with the Generic interpolator<commit_after>#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>

#include <itkImage.h>
#include <itkLinearInterpolateImageFunction.h>
#include <itkNearestNeighborInterpolateImageFunction.h>
#include <itkLabelImageGaussianInterpolateImageFunction.h>
#include <itkBSplineInterpolateImageFunction.h>
#include <itkResampleImageFilter.h>
#include <itkVersorRigid3DTransform.h>
#include <itkImageFileWriter.h>
#include <itkImageFileReader.h>
#include <itkTestingComparisonImageFilter.h>
#include <itkTimeProbe.h>

#include "itkLabelImageGenericInterpolateImageFunction.h"
#include "itkLabelSelectionAdaptor.h"

/* This demo is a torture test for interpolators: it takes an input label map,
 * rotates it one full turn in ten steps, and writes the result */

template <class ImageType>
void
RotateNTimes(typename ImageType::Pointer input,
    typename itk::InterpolateImageFunction<ImageType,double>* interpolator,
    unsigned int number_of_rotations, std::string filename_prefix) {
	typedef itk::VersorRigid3DTransform<double> TransformType;
	typedef itk::ResampleImageFilter<ImageType,ImageType> ResampleFilterType;
	TransformType::AxisType axis;
	axis[0]=0;
	axis[1]=1;
	axis[2]=0;
	TransformType::InputPointType center;
	center[0] = 144;
	center[1] = 86;
	center[2] = 101;
	TransformType::Pointer rot = TransformType::New();
	rot->SetCenter(center);
	rot->SetRotation(axis,2.*M_PI/number_of_rotations);

	typename ResampleFilterType::Pointer rs = ResampleFilterType::New();
	rs->SetInput( input );
	rs->SetReferenceImage( input );
	rs->SetUseReferenceImage(true);
	rs->SetTransform(rot);
	rs->SetInterpolator(interpolator);
	typename ImageType::Pointer out ;
  itk::TimeProbe timer; timer.Start();
	for (unsigned i = 0; i<number_of_rotations; ++i) {
		rs->SetReferenceImage( input );
		rs->SetUseReferenceImage(true);
		rs->Update();
		out = rs->GetOutput();
		out->DisconnectPipeline();
		rs->SetInput(out);
		rs->SetTransform(rot);
	}
  timer.Stop();
  typedef itk::Testing::ComparisonImageFilter<ImageType,ImageType> ComparisonFilterType;
  typename ComparisonFilterType::Pointer compare = ComparisonFilterType::New();
  compare->SetValidInput( input );
  compare->SetTestInput( out );
  compare->Update();
  std::cout << "Pixels with differences: " << std::setw(8) << compare->GetNumberOfPixelsWithDifferences() <<
    " ( " << std::fixed << std::setprecision(2) << static_cast<double>(compare->GetNumberOfPixelsWithDifferences()) /
    input->GetLargestPossibleRegion().GetNumberOfPixels() * 100.<<
    "% ) in " << timer.GetTotal() << "s" << std::endl;
	typedef  itk::ImageFileWriter< ImageType  > WriterType;
	typename WriterType::Pointer writer = WriterType::New();
	writer->SetUseCompression(true);
	writer->SetInput( out );
  std::ostringstream fname_stream;
  fname_stream << "output/" << filename_prefix << "_" << number_of_rotations << ".mha";
	writer->SetFileName(fname_stream.str());
	writer->Write();
}

// The BSpline interpolator has more arguments than other interpolators, so we set the additional parameter to the default value
using namespace std;
template<class TImage,typename TCoordRep> class BSplineInterpolator : public itk::BSplineInterpolateImageFunction<TImage,TCoordRep> {};

int main(int argc, char *argv[])
{
	string inputFilename = "../Source/classification.mha";

	typedef unsigned char     PixelType;
	const   unsigned int    Dimension = 3;
	typedef itk::Image< PixelType, Dimension >  ImageType;

	typedef itk::ImageFileReader<ImageType> ReaderType;
	ReaderType::Pointer r = ReaderType::New();
	r->SetFileName(inputFilename);
	r->Update();

	for( unsigned number_of_rotations=3; number_of_rotations <=7;
      number_of_rotations+=2 ) {
    std::cout << "Testing with " << number_of_rotations << " rotations..." << std::endl << std::endl;

    std::cout << "Nearest neighbor interpolator...                        " << std::flush;
    typedef itk::NearestNeighborInterpolateImageFunction<ImageType,double> NNInterpolatorType;
    NNInterpolatorType::Pointer nn_interp = NNInterpolatorType::New();
    RotateNTimes<ImageType>(r->GetOutput(), nn_interp, number_of_rotations, "nearest");

    std::cout << "Linear interpolator...                                  " << std::flush;
    typedef itk::LinearInterpolateImageFunction<ImageType,double> LInterpolatorType;
    LInterpolatorType::Pointer l_interp = LInterpolatorType::New();
    RotateNTimes<ImageType>(r->GetOutput(), l_interp, number_of_rotations, "linear");

    std::cout << "Label Gaussian interpolator type...                     " << std::flush;
    typedef itk::LabelImageGaussianInterpolateImageFunction<ImageType,double> LGInterpolatorType;
    LGInterpolatorType::Pointer lg_interp = LGInterpolatorType::New();
    lg_interp->SetSigma(0.3);
    RotateNTimes<ImageType>(r->GetOutput(), lg_interp, number_of_rotations, "label_gaussian");

    std::cout << "Generic label interpolator with nearest neighbor...     " << std::flush;
    typedef itk::LabelImageGenericInterpolateImageFunction<ImageType,itk::NearestNeighborInterpolateImageFunction> GNNInterpolatorType;
    GNNInterpolatorType::Pointer gnn_interp = GNNInterpolatorType::New();
    RotateNTimes<ImageType>(r->GetOutput(), gnn_interp, number_of_rotations, "gl_nearest");

    std::cout << "Generic label interpolator with linear interpolation... " << std::flush;
    typedef itk::LabelImageGenericInterpolateImageFunction<ImageType,itk::LinearInterpolateImageFunction> GLInterpolatorType;
    GLInterpolatorType::Pointer gl_interp = GLInterpolatorType::New();
    RotateNTimes<ImageType>(r->GetOutput(), gl_interp, number_of_rotations, "gl_linear");

    std::cout << "Generic label interpolator with B-Spline interpolation...             " << std::flush;
    typedef itk::LabelImageGenericInterpolateImageFunction<ImageType,BSplineInterpolator> GBSInterpolatorType;
    GBSInterpolatorType::Pointer gbs_interp = GBSInterpolatorType::New();
    RotateNTimes<ImageType>(r->GetOutput(), gbs_interp, number_of_rotations, "gl_bspline");

    std::cout << "Generic label interpolator with Gaussian interpolation...             " << std::flush;
    typedef itk::LabelImageGenericInterpolateImageFunction<ImageType,itk::GaussianInterpolateImageFunction> GGInterpolatorType;
    GGInterpolatorType::Pointer gg_interp = GGInterpolatorType::New();
    RotateNTimes<ImageType>(r->GetOutput(), gg_interp, number_of_rotations, "gl_gaussian");

    std::cout << std::endl;
  }

	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2017, ARM Limited, All Rights Reserved
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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 "mbed.h"
#include "greentea-client/test_env.h"
#include "unity.h"
#include "utest.h"
#include "wifi_tests.h"

using namespace utest::v1;

#if defined(MBED_CONF_APP_WIFI_SECURE_SSID)

void wifi_connect_params_channel_fail(void)
{
    WiFiInterface *wifi = get_interface();

    if (wifi->set_channel(1) == NSAPI_ERROR_UNSUPPORTED && wifi->set_channel(36) == NSAPI_ERROR_UNSUPPORTED) {
        TEST_IGNORE_MESSAGE("set_channel() not supported");
        return;
    }

    nsapi_error_t error = wifi->connect(MBED_CONF_APP_WIFI_SECURE_SSID, MBED_CONF_APP_WIFI_PASSWORD, get_security(), MBED_CONF_APP_WIFI_CH_SECURE);
    TEST_ASSERT(error==NSAPI_ERROR_CONNECTION_TIMEOUT || error==NSAPI_ERROR_NO_CONNECTION);
}

#endif // defined(MBED_CONF_APP_WIFI_SECURE_SSID)
<commit_msg>Fix WIFI-CONNECT-PARAMS-CHANNEL-FAIL Greentea test case<commit_after>/*
 * Copyright (c) 2017, ARM Limited, All Rights Reserved
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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 "mbed.h"
#include "greentea-client/test_env.h"
#include "unity.h"
#include "utest.h"
#include "wifi_tests.h"

using namespace utest::v1;

#if defined(MBED_CONF_APP_WIFI_SECURE_SSID)

void wifi_connect_params_channel_fail(void)
{
    WiFiInterface *wifi = get_interface();

    if (wifi->set_channel(1) == NSAPI_ERROR_UNSUPPORTED && wifi->set_channel(36) == NSAPI_ERROR_UNSUPPORTED) {
        TEST_IGNORE_MESSAGE("set_channel() not supported");
        return;
    }

    nsapi_error_t error = wifi->connect(MBED_CONF_APP_WIFI_SECURE_SSID, MBED_CONF_APP_WIFI_PASSWORD, get_security(), MBED_CONF_APP_WIFI_CH_UNSECURE);
    TEST_ASSERT(error==NSAPI_ERROR_CONNECTION_TIMEOUT || error==NSAPI_ERROR_NO_CONNECTION);
}

#endif // defined(MBED_CONF_APP_WIFI_SECURE_SSID)
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: TableWindowAccess.cxx,v $
 * $Revision: 1.13 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#ifndef DBACCESS_TABLEWINDOWACCESS_HXX
#include "TableWindowAccess.hxx"
#endif
#ifndef DBACCESS_JACCESS_HXX
#include "JAccess.hxx"
#endif
#ifndef DBAUI_TABLEWINDOW_HXX
#include "TableWindow.hxx"
#endif
#ifndef DBAUI_TABLEWINDOWLISTBOX_HXX
#include "TableWindowListBox.hxx"
#endif
#ifndef DBAUI_JOINDESIGNVIEW_HXX
#include "JoinDesignView.hxx"
#endif
#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLERELATIONTYPE_HPP_
#include <com/sun/star/accessibility/AccessibleRelationType.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_
#include <com/sun/star/accessibility/AccessibleEventId.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _DBU_QRY_HRC_
#include "dbu_qry.hrc"
#endif

namespace dbaui
{
    using namespace ::com::sun::star::accessibility;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::lang;
    //  using namespace ::com::sun::star::awt;
    using namespace ::com::sun::star;

    OTableWindowAccess::OTableWindowAccess(OTableWindow* _pTable)
        :VCLXAccessibleComponent(_pTable->GetComponentInterface().is() ? _pTable->GetWindowPeer() : NULL)
        ,m_pTable(_pTable)
    {
    }
    // -----------------------------------------------------------------------------
    void SAL_CALL OTableWindowAccess::disposing()
    {
        m_pTable = NULL;
        VCLXAccessibleComponent::disposing();
    }
    // -----------------------------------------------------------------------------
    Any SAL_CALL OTableWindowAccess::queryInterface( const Type& aType ) throw (RuntimeException)
    {
        Any aRet(VCLXAccessibleComponent::queryInterface( aType ));
        return aRet.hasValue() ? aRet : OTableWindowAccess_BASE::queryInterface( aType );
    }
    // -----------------------------------------------------------------------------
    Sequence< Type > SAL_CALL OTableWindowAccess::getTypes(  ) throw (RuntimeException)
    {
        return ::comphelper::concatSequences(VCLXAccessibleComponent::getTypes(),OTableWindowAccess_BASE::getTypes());
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OTableWindowAccess::getImplementationName() throw(RuntimeException)
    {
        return getImplementationName_Static();
    }
    // -----------------------------------------------------------------------------
    Sequence< ::rtl::OUString > SAL_CALL OTableWindowAccess::getSupportedServiceNames() throw(RuntimeException)
    {
        return getSupportedServiceNames_Static();
    }
    // -----------------------------------------------------------------------------
    // XServiceInfo - static methods
    Sequence< ::rtl::OUString > OTableWindowAccess::getSupportedServiceNames_Static(void) throw( RuntimeException )
    {
        Sequence< ::rtl::OUString > aSupported(2);
        aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.accessibility.Accessible");
        aSupported[1] = ::rtl::OUString::createFromAscii("com.sun.star.accessibility.AccessibleContext");
        return aSupported;
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString OTableWindowAccess::getImplementationName_Static(void) throw( RuntimeException )
    {
        return ::rtl::OUString::createFromAscii("org.openoffice.comp.dbu.TableWindowAccessibility");
    }
    // -----------------------------------------------------------------------------
    // XAccessibleContext
    sal_Int32 SAL_CALL OTableWindowAccess::getAccessibleChildCount(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex );
        sal_Int32 nCount = 0;
        if(m_pTable)
        {
            if(m_pTable->GetTitleCtrl())
                ++nCount;
            if(m_pTable->GetListBox())
                ++nCount;
        }
        return nCount;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessible > SAL_CALL OTableWindowAccess::getAccessibleChild( sal_Int32 i ) throw (IndexOutOfBoundsException,RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex );
        Reference< XAccessible > aRet;
        if(m_pTable)
        {
            switch(i)
            {
                case 0:
                    if(m_pTable->GetTitleCtrl())
                    {
                        aRet = m_pTable->GetTitleCtrl()->GetAccessible();
                        break;
                    } // fall through if title control does not exist
                case 1:
                    if(m_pTable->GetListBox())
                        aRet = m_pTable->GetListBox()->GetAccessible();
                    break;
                default:
                    throw IndexOutOfBoundsException();
            }
        }
        return aRet;
    }
    // -----------------------------------------------------------------------------
    sal_Int32 SAL_CALL OTableWindowAccess::getAccessibleIndexInParent(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        sal_Int32 nIndex = -1;
        if( m_pTable )
        {
            // search the postion of our table window in the table window map
            OJoinTableView::OTableWindowMap* pMap = m_pTable->getTableView()->GetTabWinMap();
            OJoinTableView::OTableWindowMap::iterator aIter = pMap->begin();
            for (nIndex = 0; aIter != pMap->end() && aIter->second != m_pTable; ++nIndex,++aIter)
                ;
            nIndex = aIter != pMap->end() ? nIndex : -1;
        }
        return nIndex;
    }
    // -----------------------------------------------------------------------------
    sal_Int16 SAL_CALL OTableWindowAccess::getAccessibleRole(  ) throw (RuntimeException)
    {
        return AccessibleRole::PANEL; // ? or may be an AccessibleRole::WINDOW
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessibleRelationSet > SAL_CALL OTableWindowAccess::getAccessibleRelationSet(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        return this;
    }
    // -----------------------------------------------------------------------------
    // XAccessibleComponent
    Reference< XAccessible > SAL_CALL OTableWindowAccess::getAccessibleAtPoint( const awt::Point& _aPoint ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Reference< XAccessible > aRet;
        if( m_pTable )
        {
            Point aPoint(_aPoint.X,_aPoint.Y);
            Rectangle aRect(m_pTable->GetDesktopRectPixel());
            if( aRect.IsInside(aPoint) )
                aRet = this;
            else if( m_pTable->GetListBox()->GetDesktopRectPixel().IsInside(aPoint))
                aRet = m_pTable->GetListBox()->GetAccessible();
        }
        return aRet;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessible > OTableWindowAccess::getParentChild(sal_Int32 _nIndex)
    {
        Reference< XAccessible > xReturn;
        Reference< XAccessible > xParent = getAccessibleParent();
        if ( xParent.is() )
        {
            Reference< XAccessibleContext > xParentContext = xParent->getAccessibleContext();
            if ( xParentContext.is() )
            {
                xReturn = xParentContext->getAccessibleChild(_nIndex);
            }
        }
        return xReturn;
    }
    // -----------------------------------------------------------------------------

    sal_Int32 SAL_CALL OTableWindowAccess::getRelationCount(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        return m_pTable ? m_pTable->getTableView()->getConnectionCount(m_pTable) : sal_Int32(0);
    }
    // -----------------------------------------------------------------------------
    AccessibleRelation SAL_CALL OTableWindowAccess::getRelation( sal_Int32 nIndex ) throw (IndexOutOfBoundsException, RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        if( nIndex < 0 || nIndex >= getRelationCount() )
            throw IndexOutOfBoundsException();

        AccessibleRelation aRet;
        if( m_pTable )
        {
            OJoinTableView* pView = m_pTable->getTableView();
            ::std::vector<OTableConnection*>::const_iterator aIter = pView->getTableConnections(m_pTable) + nIndex;
            aRet.TargetSet.realloc(1);
            aRet.TargetSet[0] = getParentChild(aIter - pView->getTableConnections()->begin());
            aRet.RelationType = AccessibleRelationType::CONTROLLER_FOR;
        }
        return aRet;
    }
    // -----------------------------------------------------------------------------
    sal_Bool SAL_CALL OTableWindowAccess::containsRelation( sal_Int16 aRelationType ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        return      AccessibleRelationType::CONTROLLER_FOR == aRelationType
                &&  m_pTable->getTableView()->ExistsAConn(m_pTable);
    }
    // -----------------------------------------------------------------------------
    AccessibleRelation SAL_CALL OTableWindowAccess::getRelationByType( sal_Int16 aRelationType ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        if( AccessibleRelationType::CONTROLLER_FOR == aRelationType && m_pTable)
        {
            OJoinTableView* pView = m_pTable->getTableView();
            const ::std::vector<OTableConnection*>* pConnectionList = pView->getTableConnections();

            ::std::vector<OTableConnection*>::const_iterator aIter = pView->getTableConnections(m_pTable);
            ::std::vector< Reference<XInterface> > aRelations;
            aRelations.reserve(5); // just guessing
            for (; aIter != pConnectionList->end() ; ++aIter )
                aRelations.push_back(getParentChild(aIter - pConnectionList->begin()));

            Reference<XInterface> *pRelations = aRelations.empty() ? 0 : &aRelations[0];
            Sequence< Reference<XInterface> > aSeq(pRelations, aRelations.size());
            return AccessibleRelation(AccessibleRelationType::CONTROLLER_FOR,aSeq);
        }
        return AccessibleRelation();
    }
    // -----------------------------------------------------------------------------
    sal_Bool OTableWindowAccess::isEditable() const
    {
        return m_pTable && !m_pTable->getTableView()->getDesignView()->getController()->isReadOnly();
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OTableWindowAccess::getTitledBorderText(  ) throw (RuntimeException)
    {
        return getAccessibleName(  );
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OTableWindowAccess::getAccessibleName(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        ::rtl::OUString sAccessibleName;
        if ( m_pTable )
            sAccessibleName = m_pTable->getTitle();
        return sAccessibleName;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessibleContext > SAL_CALL OTableWindowAccess::getAccessibleContext(  ) throw (::com::sun::star::uno::RuntimeException)
    {
        return this;
    }
    // -----------------------------------------------------------------------------

}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS dba30d (1.13.30); FILE MERGED 2008/05/29 11:30:22 fs 1.13.30.1: during #i80943#: refactoring: IController now passed around as reference, not as pointer<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: TableWindowAccess.cxx,v $
 * $Revision: 1.14 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#ifndef DBACCESS_TABLEWINDOWACCESS_HXX
#include "TableWindowAccess.hxx"
#endif
#ifndef DBACCESS_JACCESS_HXX
#include "JAccess.hxx"
#endif
#ifndef DBAUI_TABLEWINDOW_HXX
#include "TableWindow.hxx"
#endif
#ifndef DBAUI_TABLEWINDOWLISTBOX_HXX
#include "TableWindowListBox.hxx"
#endif
#ifndef DBAUI_JOINDESIGNVIEW_HXX
#include "JoinDesignView.hxx"
#endif
#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLERELATIONTYPE_HPP_
#include <com/sun/star/accessibility/AccessibleRelationType.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_
#include <com/sun/star/accessibility/AccessibleEventId.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _DBU_QRY_HRC_
#include "dbu_qry.hrc"
#endif

namespace dbaui
{
    using namespace ::com::sun::star::accessibility;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::lang;
    //  using namespace ::com::sun::star::awt;
    using namespace ::com::sun::star;

    OTableWindowAccess::OTableWindowAccess(OTableWindow* _pTable)
        :VCLXAccessibleComponent(_pTable->GetComponentInterface().is() ? _pTable->GetWindowPeer() : NULL)
        ,m_pTable(_pTable)
    {
    }
    // -----------------------------------------------------------------------------
    void SAL_CALL OTableWindowAccess::disposing()
    {
        m_pTable = NULL;
        VCLXAccessibleComponent::disposing();
    }
    // -----------------------------------------------------------------------------
    Any SAL_CALL OTableWindowAccess::queryInterface( const Type& aType ) throw (RuntimeException)
    {
        Any aRet(VCLXAccessibleComponent::queryInterface( aType ));
        return aRet.hasValue() ? aRet : OTableWindowAccess_BASE::queryInterface( aType );
    }
    // -----------------------------------------------------------------------------
    Sequence< Type > SAL_CALL OTableWindowAccess::getTypes(  ) throw (RuntimeException)
    {
        return ::comphelper::concatSequences(VCLXAccessibleComponent::getTypes(),OTableWindowAccess_BASE::getTypes());
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OTableWindowAccess::getImplementationName() throw(RuntimeException)
    {
        return getImplementationName_Static();
    }
    // -----------------------------------------------------------------------------
    Sequence< ::rtl::OUString > SAL_CALL OTableWindowAccess::getSupportedServiceNames() throw(RuntimeException)
    {
        return getSupportedServiceNames_Static();
    }
    // -----------------------------------------------------------------------------
    // XServiceInfo - static methods
    Sequence< ::rtl::OUString > OTableWindowAccess::getSupportedServiceNames_Static(void) throw( RuntimeException )
    {
        Sequence< ::rtl::OUString > aSupported(2);
        aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.accessibility.Accessible");
        aSupported[1] = ::rtl::OUString::createFromAscii("com.sun.star.accessibility.AccessibleContext");
        return aSupported;
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString OTableWindowAccess::getImplementationName_Static(void) throw( RuntimeException )
    {
        return ::rtl::OUString::createFromAscii("org.openoffice.comp.dbu.TableWindowAccessibility");
    }
    // -----------------------------------------------------------------------------
    // XAccessibleContext
    sal_Int32 SAL_CALL OTableWindowAccess::getAccessibleChildCount(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex );
        sal_Int32 nCount = 0;
        if(m_pTable)
        {
            if(m_pTable->GetTitleCtrl())
                ++nCount;
            if(m_pTable->GetListBox())
                ++nCount;
        }
        return nCount;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessible > SAL_CALL OTableWindowAccess::getAccessibleChild( sal_Int32 i ) throw (IndexOutOfBoundsException,RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex );
        Reference< XAccessible > aRet;
        if(m_pTable)
        {
            switch(i)
            {
                case 0:
                    if(m_pTable->GetTitleCtrl())
                    {
                        aRet = m_pTable->GetTitleCtrl()->GetAccessible();
                        break;
                    } // fall through if title control does not exist
                case 1:
                    if(m_pTable->GetListBox())
                        aRet = m_pTable->GetListBox()->GetAccessible();
                    break;
                default:
                    throw IndexOutOfBoundsException();
            }
        }
        return aRet;
    }
    // -----------------------------------------------------------------------------
    sal_Int32 SAL_CALL OTableWindowAccess::getAccessibleIndexInParent(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        sal_Int32 nIndex = -1;
        if( m_pTable )
        {
            // search the postion of our table window in the table window map
            OJoinTableView::OTableWindowMap* pMap = m_pTable->getTableView()->GetTabWinMap();
            OJoinTableView::OTableWindowMap::iterator aIter = pMap->begin();
            for (nIndex = 0; aIter != pMap->end() && aIter->second != m_pTable; ++nIndex,++aIter)
                ;
            nIndex = aIter != pMap->end() ? nIndex : -1;
        }
        return nIndex;
    }
    // -----------------------------------------------------------------------------
    sal_Int16 SAL_CALL OTableWindowAccess::getAccessibleRole(  ) throw (RuntimeException)
    {
        return AccessibleRole::PANEL; // ? or may be an AccessibleRole::WINDOW
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessibleRelationSet > SAL_CALL OTableWindowAccess::getAccessibleRelationSet(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        return this;
    }
    // -----------------------------------------------------------------------------
    // XAccessibleComponent
    Reference< XAccessible > SAL_CALL OTableWindowAccess::getAccessibleAtPoint( const awt::Point& _aPoint ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Reference< XAccessible > aRet;
        if( m_pTable )
        {
            Point aPoint(_aPoint.X,_aPoint.Y);
            Rectangle aRect(m_pTable->GetDesktopRectPixel());
            if( aRect.IsInside(aPoint) )
                aRet = this;
            else if( m_pTable->GetListBox()->GetDesktopRectPixel().IsInside(aPoint))
                aRet = m_pTable->GetListBox()->GetAccessible();
        }
        return aRet;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessible > OTableWindowAccess::getParentChild(sal_Int32 _nIndex)
    {
        Reference< XAccessible > xReturn;
        Reference< XAccessible > xParent = getAccessibleParent();
        if ( xParent.is() )
        {
            Reference< XAccessibleContext > xParentContext = xParent->getAccessibleContext();
            if ( xParentContext.is() )
            {
                xReturn = xParentContext->getAccessibleChild(_nIndex);
            }
        }
        return xReturn;
    }
    // -----------------------------------------------------------------------------

    sal_Int32 SAL_CALL OTableWindowAccess::getRelationCount(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        return m_pTable ? m_pTable->getTableView()->getConnectionCount(m_pTable) : sal_Int32(0);
    }
    // -----------------------------------------------------------------------------
    AccessibleRelation SAL_CALL OTableWindowAccess::getRelation( sal_Int32 nIndex ) throw (IndexOutOfBoundsException, RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        if( nIndex < 0 || nIndex >= getRelationCount() )
            throw IndexOutOfBoundsException();

        AccessibleRelation aRet;
        if( m_pTable )
        {
            OJoinTableView* pView = m_pTable->getTableView();
            ::std::vector<OTableConnection*>::const_iterator aIter = pView->getTableConnections(m_pTable) + nIndex;
            aRet.TargetSet.realloc(1);
            aRet.TargetSet[0] = getParentChild(aIter - pView->getTableConnections()->begin());
            aRet.RelationType = AccessibleRelationType::CONTROLLER_FOR;
        }
        return aRet;
    }
    // -----------------------------------------------------------------------------
    sal_Bool SAL_CALL OTableWindowAccess::containsRelation( sal_Int16 aRelationType ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        return      AccessibleRelationType::CONTROLLER_FOR == aRelationType
                &&  m_pTable->getTableView()->ExistsAConn(m_pTable);
    }
    // -----------------------------------------------------------------------------
    AccessibleRelation SAL_CALL OTableWindowAccess::getRelationByType( sal_Int16 aRelationType ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        if( AccessibleRelationType::CONTROLLER_FOR == aRelationType && m_pTable)
        {
            OJoinTableView* pView = m_pTable->getTableView();
            const ::std::vector<OTableConnection*>* pConnectionList = pView->getTableConnections();

            ::std::vector<OTableConnection*>::const_iterator aIter = pView->getTableConnections(m_pTable);
            ::std::vector< Reference<XInterface> > aRelations;
            aRelations.reserve(5); // just guessing
            for (; aIter != pConnectionList->end() ; ++aIter )
                aRelations.push_back(getParentChild(aIter - pConnectionList->begin()));

            Reference<XInterface> *pRelations = aRelations.empty() ? 0 : &aRelations[0];
            Sequence< Reference<XInterface> > aSeq(pRelations, aRelations.size());
            return AccessibleRelation(AccessibleRelationType::CONTROLLER_FOR,aSeq);
        }
        return AccessibleRelation();
    }
    // -----------------------------------------------------------------------------
    sal_Bool OTableWindowAccess::isEditable() const
    {
        return m_pTable && !m_pTable->getTableView()->getDesignView()->getController().isReadOnly();
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OTableWindowAccess::getTitledBorderText(  ) throw (RuntimeException)
    {
        return getAccessibleName(  );
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OTableWindowAccess::getAccessibleName(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        ::rtl::OUString sAccessibleName;
        if ( m_pTable )
            sAccessibleName = m_pTable->getTitle();
        return sAccessibleName;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessibleContext > SAL_CALL OTableWindowAccess::getAccessibleContext(  ) throw (::com::sun::star::uno::RuntimeException)
    {
        return this;
    }
    // -----------------------------------------------------------------------------

}
// -----------------------------------------------------------------------------

<|endoftext|>