<commit_before>/********** tell emacs we use -*- c++ -*- style comments *******************
 $Revision: 1.12 $  $Author: trey $  $Date: 2006-10-19 19:31:16 $

 @file    HDP.cc
 @brief   Implementation of Bonet and Geffner's HDP algorithm.

 Copyright (c) 2006, Trey Smith. All rights reserved.

 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.

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

/**********************************************************************
  This is my implementation of the HDP algorithm, based on the paper

    "Faster heuristic Search Algorithms for Planning with
       Uncertainty and Full Feedback."
    B. Bonet and H. Geffner. In Proc. of IJCAI, 2003.

  Inevitably they could not include all the details of the algorithm in
  their paper, so it is possible that my implementation differs from
  theirs in important ways.  They have not signed off on this
  implementation: use at your own risk.  (And please inform me if you
  find any errors!)

  This code also implements my variant HDP+L algorithm [not yet
  published] when the compile-time flag '-DUSE_HDP_LOWER_BOUND=1' is
  set.  In addition to the usual upper bound, HDP+L keeps a lower bound
  and uses that to generate the output policy.  Empirically, this
  improves anytime performance when the upper and lower bounds have not
  yet converged.

  -Trey Smith, Feb. 2006
 **********************************************************************/

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <assert.h>

#include <iostream>
#include <fstream>
#include <stack>

#include "zmdpCommonDefs.h"
#include "zmdpCommonTime.h"
#include "MatrixUtils.h"
#include "Pomdp.h"
#include "HDP.h"

using namespace std;
using namespace sla;
using namespace MatrixUtils;

namespace zmdp {

HDP::HDP(void)
{}

void HDP::getNodeHandler(MDPNode& cn)
{
  HDPExtraNodeData* searchData = new HDPExtraNodeData;
  cn.searchData = searchData;
  searchData->isSolved = cn.isTerminal;
  searchData->idx = RT_IDX_PLUS_INFINITY;
}

void HDP::staticGetNodeHandler(MDPNode& s, void* handlerData)
{
  HDP* x = (HDP *) handlerData;
  x->getNodeHandler(s);
}

bool& HDP::getIsSolved(const MDPNode& cn)
{
  return ((HDPExtraNodeData *) cn.searchData)->isSolved;
}

int& HDP::getLow(const MDPNode& cn)
{
  return ((HDPExtraNodeData *) cn.searchData)->low;
}

int& HDP::getIdx(const MDPNode& cn)
{
  return ((HDPExtraNodeData *) cn.searchData)->idx;
}

void HDP::cacheQ(MDPNode& cn)
{
  double oldUBVal = cn.ubVal;
  // bounds->update() changes both Q values and cn.ubVal
  bounds->update(cn, NULL);
  trackBackup(cn);
  // keep the changes to Q but undo the change to cn.ubVal
  cn.ubVal = oldUBVal;
}

// assumes correct Q values are already cached (using cacheQ)
double HDP::residual(MDPNode& cn)
{
  int maxUBAction = bounds->getMaxUBAction(cn);
  return fabs(cn.ubVal - cn.Q[maxUBAction].ubVal);
}

void HDP::updateInternal(MDPNode& cn)
{
  cacheQ(cn);
  int maxUBAction = bounds->getMaxUBAction(cn);
  cn.ubVal = cn.Q[maxUBAction].ubVal;
}

bool HDP::trialRecurse(MDPNode& cn, int depth)
{
#if USE_DEBUG_PRINT
  printf("  trialRecurse: depth=%d ubVal=%g\n",
	 depth, cn.ubVal);
  printf("  trialRecurse: s=%s\n", sparseRep(cn.s).c_str());
#endif

  // base case
  if (getIsSolved(cn)) {
#if USE_DEBUG_PRINT
    printf("  trialRecurse: solved node (terminating)\n");
#endif
    return false;
  }

  // check residual
  cacheQ(cn);
  int maxUBAction = bounds->getMaxUBAction(cn);
  // FIX do not recalculate maxUBAction in residual()
  if (residual(cn) > targetPrecision) {
    cn.ubVal = cn.Q[maxUBAction].ubVal;

#if USE_DEBUG_PRINT
    printf("  trialRecurse: big residual (terminating)\n");
#endif
    return true;
  }

  // mark state as active
  visited.push(&cn);
  nodeStack.push(&cn);
  getIdx(cn) = getLow(cn) = index;
  index++;

  // recursive call
  bool flag = false;
  MDPQEntry& Qa = cn.Q[maxUBAction];
  //printf("    pre low=%d idx=%d\n", getLow(cn), getIdx(cn));
  FOR (o, Qa.getNumOutcomes()) {
    MDPEdge* e = Qa.outcomes[o];
    if (NULL != e) {
      MDPNode& sn = *e->nextState;
      //printf("      a=%d o=%d sn=[%s] sn.idx=%d\n", maxUBAction, o, denseRep(sn.s).c_str(), getIdx(sn));
      if (RT_IDX_PLUS_INFINITY == getIdx(sn)) {
	if (trialRecurse(sn, depth+1)) {
	  flag = true;
	}
	getLow(cn) = std::min(getLow(cn), getLow(sn));
      } else if (nodeStack.contains(&sn)) {
	getLow(cn) = std::min(getLow(cn), getLow(sn));
      }
    }
  }
  //printf("    post low=%d idx=%d\n", getLow(cn), getIdx(cn));

  // update if necessary
  if (flag) {
    bounds->update(cn, NULL);
    trackBackup(cn);
    return true;
  }

  // try to label
  else if (getIdx(cn) == getLow(cn)) {
    printf("  marking %d nodes solved\n", (int)nodeStack.size());
    while (nodeStack.top() != &cn) {
      MDPNode& sn = *nodeStack.pop();
      getIsSolved(sn) = true;
    }
    nodeStack.pop();
    getIsSolved(cn) = true;
  }

  return flag;
}

bool HDP::doTrial(MDPNode& cn)
{
  if (getIsSolved(cn)) {
    printf("-*- doTrial: root node is solved, terminating\n");
    return true;
  }

#if USE_DEBUG_PRINT
  printf("-*- doTrial: trial %d\n", (numTrials+1));
#endif

  index = 0;
  trialRecurse(cn, 0);
  // reset idx to +infinity for visited states
  while (!visited.empty()) {
    getIdx(*visited.top()) = RT_IDX_PLUS_INFINITY;
    visited.pop();
  }
  nodeStack.clear();
  RT_CLEAR_STD_STACK(visited);

  numTrials++;

  return false;
}

void HDP::derivedClassInit(void)
{
  bounds->setGetNodeHandler(&HDP::staticGetNodeHandler, this);
}

}; // namespace zmdp

/***************************************************************************
 * REVISION HISTORY:
 * $Log: not supported by cvs2svn $
 * Revision 1.11  2006/06/14 00:22:40  trey
 * fixed printf format warning
 *
 * Revision 1.10  2006/05/20 03:50:54  trey
 * fixed printf format to avoid warning
 *
 * Revision 1.9  2006/04/28 17:57:41  trey
 * changed to use apache license
 *
 * Revision 1.8  2006/04/07 19:41:30  trey
 * removed initLowerBound, initUpperBound arguments to constructor
 *
 * Revision 1.7  2006/04/06 04:14:50  trey
 * changed how bounds are initialized
 *
 * Revision 1.6  2006/04/04 17:23:58  trey
 * modified to use IncrementalBounds methods
 *
 * Revision 1.5  2006/03/17 20:06:13  trey
 * fixed compile warning
 *
 * Revision 1.4  2006/02/27 20:12:36  trey
 * cleaned up meta-information in header
 *
 * Revision 1.3  2006/02/20 00:04:49  trey
 * added optional lower bound use
 *
 * Revision 1.2  2006/02/19 18:33:36  trey
 * targetPrecision now stared as a field rather than passed around recursively
 *
 * Revision 1.1  2006/02/17 18:20:55  trey
 * initial check-in
 *
 *
 ***************************************************************************/
<commit_msg>removed obsolete comment<commit_after>/********** tell emacs we use -*- c++ -*- style comments *******************
 $Revision: 1.13 $  $Author: trey $  $Date: 2006-10-20 04:56:35 $

 @file    HDP.cc
 @brief   Implementation of Bonet and Geffner's HDP algorithm.

 Copyright (c) 2006, Trey Smith. All rights reserved.

 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.

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

/**********************************************************************
  This is my implementation of the HDP algorithm, based on the paper

    "Faster heuristic Search Algorithms for Planning with
       Uncertainty and Full Feedback."
    B. Bonet and H. Geffner. In Proc. of IJCAI, 2003.

  Inevitably they could not include all the details of the algorithm in
  their paper, so it is possible that my implementation differs from
  theirs in important ways.  They have not signed off on this
  implementation: use at your own risk.  (And please inform me if you
  find any errors!)

  -Trey Smith, Feb. 2006
 **********************************************************************/

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <assert.h>

#include <iostream>
#include <fstream>
#include <stack>

#include "zmdpCommonDefs.h"
#include "zmdpCommonTime.h"
#include "MatrixUtils.h"
#include "Pomdp.h"
#include "HDP.h"

using namespace std;
using namespace sla;
using namespace MatrixUtils;

namespace zmdp {

HDP::HDP(void)
{}

void HDP::getNodeHandler(MDPNode& cn)
{
  HDPExtraNodeData* searchData = new HDPExtraNodeData;
  cn.searchData = searchData;
  searchData->isSolved = cn.isTerminal;
  searchData->idx = RT_IDX_PLUS_INFINITY;
}

void HDP::staticGetNodeHandler(MDPNode& s, void* handlerData)
{
  HDP* x = (HDP *) handlerData;
  x->getNodeHandler(s);
}

bool& HDP::getIsSolved(const MDPNode& cn)
{
  return ((HDPExtraNodeData *) cn.searchData)->isSolved;
}

int& HDP::getLow(const MDPNode& cn)
{
  return ((HDPExtraNodeData *) cn.searchData)->low;
}

int& HDP::getIdx(const MDPNode& cn)
{
  return ((HDPExtraNodeData *) cn.searchData)->idx;
}

void HDP::cacheQ(MDPNode& cn)
{
  double oldUBVal = cn.ubVal;
  // bounds->update() changes both Q values and cn.ubVal
  bounds->update(cn, NULL);
  trackBackup(cn);
  // keep the changes to Q but undo the change to cn.ubVal
  cn.ubVal = oldUBVal;
}

// assumes correct Q values are already cached (using cacheQ)
double HDP::residual(MDPNode& cn)
{
  int maxUBAction = bounds->getMaxUBAction(cn);
  return fabs(cn.ubVal - cn.Q[maxUBAction].ubVal);
}

void HDP::updateInternal(MDPNode& cn)
{
  cacheQ(cn);
  int maxUBAction = bounds->getMaxUBAction(cn);
  cn.ubVal = cn.Q[maxUBAction].ubVal;
}

bool HDP::trialRecurse(MDPNode& cn, int depth)
{
#if USE_DEBUG_PRINT
  printf("  trialRecurse: depth=%d ubVal=%g\n",
	 depth, cn.ubVal);
  printf("  trialRecurse: s=%s\n", sparseRep(cn.s).c_str());
#endif

  // base case
  if (getIsSolved(cn)) {
#if USE_DEBUG_PRINT
    printf("  trialRecurse: solved node (terminating)\n");
#endif
    return false;
  }

  // check residual
  cacheQ(cn);
  int maxUBAction = bounds->getMaxUBAction(cn);
  // FIX do not recalculate maxUBAction in residual()
  if (residual(cn) > targetPrecision) {
    cn.ubVal = cn.Q[maxUBAction].ubVal;

#if USE_DEBUG_PRINT
    printf("  trialRecurse: big residual (terminating)\n");
#endif
    return true;
  }

  // mark state as active
  visited.push(&cn);
  nodeStack.push(&cn);
  getIdx(cn) = getLow(cn) = index;
  index++;

  // recursive call
  bool flag = false;
  MDPQEntry& Qa = cn.Q[maxUBAction];
  //printf("    pre low=%d idx=%d\n", getLow(cn), getIdx(cn));
  FOR (o, Qa.getNumOutcomes()) {
    MDPEdge* e = Qa.outcomes[o];
    if (NULL != e) {
      MDPNode& sn = *e->nextState;
      //printf("      a=%d o=%d sn=[%s] sn.idx=%d\n", maxUBAction, o, denseRep(sn.s).c_str(), getIdx(sn));
      if (RT_IDX_PLUS_INFINITY == getIdx(sn)) {
	if (trialRecurse(sn, depth+1)) {
	  flag = true;
	}
	getLow(cn) = std::min(getLow(cn), getLow(sn));
      } else if (nodeStack.contains(&sn)) {
	getLow(cn) = std::min(getLow(cn), getLow(sn));
      }
    }
  }
  //printf("    post low=%d idx=%d\n", getLow(cn), getIdx(cn));

  // update if necessary
  if (flag) {
    bounds->update(cn, NULL);
    trackBackup(cn);
    return true;
  }

  // try to label
  else if (getIdx(cn) == getLow(cn)) {
    printf("  marking %d nodes solved\n", (int)nodeStack.size());
    while (nodeStack.top() != &cn) {
      MDPNode& sn = *nodeStack.pop();
      getIsSolved(sn) = true;
    }
    nodeStack.pop();
    getIsSolved(cn) = true;
  }

  return flag;
}

bool HDP::doTrial(MDPNode& cn)
{
  if (getIsSolved(cn)) {
    printf("-*- doTrial: root node is solved, terminating\n");
    return true;
  }

#if USE_DEBUG_PRINT
  printf("-*- doTrial: trial %d\n", (numTrials+1));
#endif

  index = 0;
  trialRecurse(cn, 0);
  // reset idx to +infinity for visited states
  while (!visited.empty()) {
    getIdx(*visited.top()) = RT_IDX_PLUS_INFINITY;
    visited.pop();
  }
  nodeStack.clear();
  RT_CLEAR_STD_STACK(visited);

  numTrials++;

  return false;
}

void HDP::derivedClassInit(void)
{
  bounds->setGetNodeHandler(&HDP::staticGetNodeHandler, this);
}

}; // namespace zmdp

/***************************************************************************
 * REVISION HISTORY:
 * $Log: not supported by cvs2svn $
 * Revision 1.12  2006/10/19 19:31:16  trey
 * added support for backup logging
 *
 * Revision 1.11  2006/06/14 00:22:40  trey
 * fixed printf format warning
 *
 * Revision 1.10  2006/05/20 03:50:54  trey
 * fixed printf format to avoid warning
 *
 * Revision 1.9  2006/04/28 17:57:41  trey
 * changed to use apache license
 *
 * Revision 1.8  2006/04/07 19:41:30  trey
 * removed initLowerBound, initUpperBound arguments to constructor
 *
 * Revision 1.7  2006/04/06 04:14:50  trey
 * changed how bounds are initialized
 *
 * Revision 1.6  2006/04/04 17:23:58  trey
 * modified to use IncrementalBounds methods
 *
 * Revision 1.5  2006/03/17 20:06:13  trey
 * fixed compile warning
 *
 * Revision 1.4  2006/02/27 20:12:36  trey
 * cleaned up meta-information in header
 *
 * Revision 1.3  2006/02/20 00:04:49  trey
 * added optional lower bound use
 *
 * Revision 1.2  2006/02/19 18:33:36  trey
 * targetPrecision now stared as a field rather than passed around recursively
 *
 * Revision 1.1  2006/02/17 18:20:55  trey
 * initial check-in
 *
 *
 ***************************************************************************/
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include "stan/prob/distributions_multinomial.hpp"
#include <Eigen/Dense>

using Eigen::Matrix;
using Eigen::Dynamic;

TEST(ProbDistributions,Multinomial) {
  std::vector<int> ns;
  ns.push_back(1);
  ns.push_back(2);
  ns.push_back(3);
  Matrix<double,Dynamic,1> theta(3,1);
  theta << 0.2, 0.3, 0.5;
  EXPECT_FLOAT_EQ(-2.002481, stan::prob::multinomial_log(ns,theta));
}
TEST(ProbDistributions,MultinomialPropto) {
  std::vector<int> ns;
  ns.push_back(1);
  ns.push_back(2);
  ns.push_back(3);
  Matrix<double,Dynamic,1> theta(3,1);
  theta << 0.2, 0.3, 0.5;
  EXPECT_FLOAT_EQ(0.0, stan::prob::multinomial_log<true>(ns,theta));
}
<commit_msg>cleanup<commit_after>#include <gtest/gtest.h>
#include "stan/prob/distributions_multinomial.hpp"

using Eigen::Matrix;
using Eigen::Dynamic;

TEST(ProbDistributions,Multinomial) {
  std::vector<int> ns;
  ns.push_back(1);
  ns.push_back(2);
  ns.push_back(3);
  Matrix<double,Dynamic,1> theta(3,1);
  theta << 0.2, 0.3, 0.5;
  EXPECT_FLOAT_EQ(-2.002481, stan::prob::multinomial_log(ns,theta));
}
TEST(ProbDistributions,MultinomialPropto) {
  std::vector<int> ns;
  ns.push_back(1);
  ns.push_back(2);
  ns.push_back(3);
  Matrix<double,Dynamic,1> theta(3,1);
  theta << 0.2, 0.3, 0.5;
  EXPECT_FLOAT_EQ(0.0, stan::prob::multinomial_log<true>(ns,theta));
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: cachedata.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-19 16:19:41 $
 *
 *  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 CONFIGMGR_CACHEDATA_HXX
#define CONFIGMGR_CACHEDATA_HXX

#ifndef CONFIGMGR_CACHELINE_HXX
#include "cacheline.hxx"
#endif

#ifndef INCLUDED_MAP
#include <map>
#define INCLUDED_MAP
#endif

#ifndef INCLUDED_VECTOR
#include <vector>
#define INCLUDED_VECTOR
#endif

namespace configmgr
{
////////////////////////////////////////////////////////////////////////////////
    using ::rtl::OUString;

    namespace backend
    {
        struct NodeInstance;
        struct TemplateInstance;
        struct UpdateInstance;
        struct ConstUpdateInstance;
    }

////////////////////////////////////////////////////////////////////////////////
    /** A collection of CacheLines
    */

    class CacheData
    {
    public:
        typedef CacheLine        Module;
        typedef CacheLineRef     ModuleRef;
        typedef CacheLine::Path     Path;
        typedef CacheLine::Name     ModuleName;
    public:
        CacheData(memory::HeapManager & _rHeapManager);
        ~CacheData();

        /// retrieve the module tree name for the given path
        static ModuleName extractModuleName(Path const& _aPath);

        /// check if the given module exists already (and is not empty)
        bool hasModule(ModuleName const & _aModule) const;
        /// checks if the given module exists and has defaults available
        bool hasModuleDefaults(memory::Accessor const & _aAccessor, ModuleName const & _aModule) const;

        /// creates a new data segment reference for the given path if exists
        memory::Segment * attachDataSegment(memory::SegmentAddress const & _aLocation, ModuleName const & _aModule);
        /// gets a data segment reference for the given path if it exists
        memory::Segment * getDataSegment(ModuleName const & _aModule);
        /// gets a data segment address for the given module if it exists
        memory::SegmentAddress getDataSegmentAddress(ModuleName const & _aModule) const;

        /// checks whether a certain node exists in the tree
        bool  hasNode(memory::Accessor const & _aAccessor, Path const & _aLocation) const;

        /// retrieve the given node without changing its ref count
        data::NodeAddress   getNode(memory::Accessor const & _aAccessor, Path const & _rPath);
        /// retrieve the given template tree without changing its ref count
        data::TreeAddress   getTemplateTree(memory::Accessor const & _aAccessor, Path const & aTemplateName ) const;

        /// retrieve the subtree at _aPath and clientAcquire() it
        data::NodeAddress acquireNode(memory::Accessor const & _aAccessor, Path const & _aPath );
        /// retrieve the subtree at _aPath and clientAcquire() it
        data::TreeAddress acquireModule( ModuleName const & _aModule );
        /// clientRelease() the tree at aComponentName, and return the resulting reference count
        CacheLine::RefCount releaseModule( ModuleName const & _aModule, bool _bKeepDeadModule = false );

        bool insertDefaults( memory::UpdateAccessor& _aAccessToken,
                             backend::NodeInstance const & _aDefaultInstance
                           ) CFG_UNO_THROW_RTE();

        /// merge the given changes into this tree - reflects old values to _anUpdate
        void applyUpdate(   memory::UpdateAccessor& _aUpdateToken,
                            backend::UpdateInstance & _anUpdate) CFG_UNO_THROW_RTE(  );

        // low-level interface for cache management
        typedef std::map<ModuleName, ModuleRef> ModuleList;
        ModuleList& accessModuleList() { return m_aModules; }

        memory::HeapManager & getHeapManager() const { return m_rHeapManager; }
    protected:
        virtual ModuleRef doCreateAttachedModule(memory::HeapManager & _rHeapManager, const memory::SegmentAddress & _aLocation, const ModuleName& _aName) CFG_UNO_THROW_RTE(  );

        data::TreeAddress internalGetPartialTree(memory::Accessor const & _aAccessor, Path const & _aPath ) const;
        data::NodeAddress internalGetNode(memory::Accessor const & _aAccessor, const Path& _rPath) const;

        ModuleRef internalAttachModule(const memory::SegmentAddress & _aLocation, const ModuleName& _aName) CFG_UNO_THROW_RTE(  );
        void internalAddModule(ModuleName const & _aName, ModuleRef const & _aModule);

        ModuleRef internalGetModule(const ModuleName& _aName) const;
        ModuleRef internalGetModule(const Path& _aLocation) const;

        memory::HeapManager & internalHeapManager() { return m_rHeapManager; }
    private:
        ModuleList m_aModules;

        memory::HeapManager & m_rHeapManager;
    };
////////////////////////////////////////////////////////////////////////////////
    /** A collection of CacheLines for templates
    */

    class TemplateCacheData : public CacheData
    {
    public:
        TemplateCacheData(memory::HeapManager & _rHeapManager)
        : CacheData(_rHeapManager)
        {
        }

        /// gets a data segment reference for the given path - creates if necessary
        memory::Segment * createDataSegment(ModuleName const & _aModule);

        /** add the given template tree at the given location,
            return the tree that is now pertinent and clientAcquire() it once
        */
        data::TreeAddress addTemplates( memory::UpdateAccessor& _aAccessToken,
                                        backend::ComponentData const & _aComponentInstance
                                       ) CFG_UNO_THROW_RTE();

    private:
        virtual ModuleRef doCreateAttachedModule(memory::HeapManager & _rHeapManager, const memory::SegmentAddress & _aLocation, const ModuleName& _aName) CFG_UNO_THROW_RTE(  );

        CacheLineRef implNewCacheLine(ModuleName const & _aModule) CFG_UNO_THROW_RTE(  );
    };
//-----------------------------------------------------------------------------
    /** A collection of CacheLines
    */

    class ExtendedCacheData : public CacheData
    {
    public:
        ExtendedCacheData(memory::HeapManager & _rHeapManager)
        : CacheData(_rHeapManager)
        {
        }

        /// gets a data segment reference for the given path - creates if necessary
        memory::Segment * createDataSegment(ModuleName const & _aModule);

        /** add the given subtree at the given location,
            return the tree that is now pertinent and clientAcquire() it once
        */
        data::TreeAddress addComponentData( memory::UpdateAccessor& _aAccessToken,
                                            backend::ComponentInstance const & _aComponentInstance,
                                            bool _bWithDefaults
                                           ) CFG_UNO_THROW_RTE();

        typedef std::vector< ModuleName >  PendingModuleList;
        /// find the modules having pending changes
        bool hasPending(ModuleName const & _aModule);
        /// find the modules having pending changes
        void findPendingModules( PendingModuleList & _rPendingList );

        /// add or merge the given subtreechange at the given location
        void addPending(backend::ConstUpdateInstance const & _anUpdate) CFG_UNO_THROW_RTE(  );
        /// remove and return pending changes for the given component
        std::auto_ptr<SubtreeChange> releasePending(ModuleName const & _aModule) CFG_UNO_THROW_RTE(  );
    private:
        virtual ModuleRef doCreateAttachedModule(memory::HeapManager & _rHeapManager, const memory::SegmentAddress & _aLocation, const ModuleName& _aName) CFG_UNO_THROW_RTE(  );

        ExtendedCacheLineRef implNewCacheLine(ModuleName const & _aModule) CFG_UNO_THROW_RTE(  );

        ExtendedCacheLineRef implExtended(ModuleRef const & _aSimpleRef) const;
    };
//-----------------------------------------------------------------------------

} // namespace configmgr

#endif

<commit_msg>INTEGRATION: CWS cfgcleanup (1.5.70); FILE MERGED 2004/02/09 15:30:32 jb 1.5.70.1: #i25025# Eliminate warnings from gcc<commit_after>/*************************************************************************
 *
 *  $RCSfile: cachedata.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2004-03-23 10:30:25 $
 *
 *  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 CONFIGMGR_CACHEDATA_HXX
#define CONFIGMGR_CACHEDATA_HXX

#ifndef CONFIGMGR_CACHELINE_HXX
#include "cacheline.hxx"
#endif

#ifndef INCLUDED_MAP
#include <map>
#define INCLUDED_MAP
#endif

#ifndef INCLUDED_VECTOR
#include <vector>
#define INCLUDED_VECTOR
#endif

namespace configmgr
{
////////////////////////////////////////////////////////////////////////////////
    using ::rtl::OUString;

    namespace backend
    {
        struct NodeInstance;
        struct TemplateInstance;
        struct UpdateInstance;
        struct ConstUpdateInstance;
    }

////////////////////////////////////////////////////////////////////////////////
    /** A collection of CacheLines
    */

    class CacheData
    {
    public:
        typedef CacheLine        Module;
        typedef CacheLineRef     ModuleRef;
        typedef CacheLine::Path     Path;
        typedef CacheLine::Name     ModuleName;
    public:
        CacheData(memory::HeapManager & _rHeapManager);
        virtual ~CacheData();

        /// retrieve the module tree name for the given path
        static ModuleName extractModuleName(Path const& _aPath);

        /// check if the given module exists already (and is not empty)
        bool hasModule(ModuleName const & _aModule) const;
        /// checks if the given module exists and has defaults available
        bool hasModuleDefaults(memory::Accessor const & _aAccessor, ModuleName const & _aModule) const;

        /// creates a new data segment reference for the given path if exists
        memory::Segment * attachDataSegment(memory::SegmentAddress const & _aLocation, ModuleName const & _aModule);
        /// gets a data segment reference for the given path if it exists
        memory::Segment * getDataSegment(ModuleName const & _aModule);
        /// gets a data segment address for the given module if it exists
        memory::SegmentAddress getDataSegmentAddress(ModuleName const & _aModule) const;

        /// checks whether a certain node exists in the tree
        bool  hasNode(memory::Accessor const & _aAccessor, Path const & _aLocation) const;

        /// retrieve the given node without changing its ref count
        data::NodeAddress   getNode(memory::Accessor const & _aAccessor, Path const & _rPath);
        /// retrieve the given template tree without changing its ref count
        data::TreeAddress   getTemplateTree(memory::Accessor const & _aAccessor, Path const & aTemplateName ) const;

        /// retrieve the subtree at _aPath and clientAcquire() it
        data::NodeAddress acquireNode(memory::Accessor const & _aAccessor, Path const & _aPath );
        /// retrieve the subtree at _aPath and clientAcquire() it
        data::TreeAddress acquireModule( ModuleName const & _aModule );
        /// clientRelease() the tree at aComponentName, and return the resulting reference count
        CacheLine::RefCount releaseModule( ModuleName const & _aModule, bool _bKeepDeadModule = false );

        bool insertDefaults( memory::UpdateAccessor& _aAccessToken,
                             backend::NodeInstance const & _aDefaultInstance
                           ) CFG_UNO_THROW_RTE();

        /// merge the given changes into this tree - reflects old values to _anUpdate
        void applyUpdate(   memory::UpdateAccessor& _aUpdateToken,
                            backend::UpdateInstance & _anUpdate) CFG_UNO_THROW_RTE(  );

        // low-level interface for cache management
        typedef std::map<ModuleName, ModuleRef> ModuleList;
        ModuleList& accessModuleList() { return m_aModules; }

        memory::HeapManager & getHeapManager() const { return m_rHeapManager; }
    protected:
        virtual ModuleRef doCreateAttachedModule(memory::HeapManager & _rHeapManager, const memory::SegmentAddress & _aLocation, const ModuleName& _aName) CFG_UNO_THROW_RTE(  );

        data::TreeAddress internalGetPartialTree(memory::Accessor const & _aAccessor, Path const & _aPath ) const;
        data::NodeAddress internalGetNode(memory::Accessor const & _aAccessor, const Path& _rPath) const;

        ModuleRef internalAttachModule(const memory::SegmentAddress & _aLocation, const ModuleName& _aName) CFG_UNO_THROW_RTE(  );
        void internalAddModule(ModuleName const & _aName, ModuleRef const & _aModule);

        ModuleRef internalGetModule(const ModuleName& _aName) const;
        ModuleRef internalGetModule(const Path& _aLocation) const;

        memory::HeapManager & internalHeapManager() { return m_rHeapManager; }
    private:
        ModuleList m_aModules;

        memory::HeapManager & m_rHeapManager;
    };
////////////////////////////////////////////////////////////////////////////////
    /** A collection of CacheLines for templates
    */

    class TemplateCacheData : public CacheData
    {
    public:
        TemplateCacheData(memory::HeapManager & _rHeapManager)
        : CacheData(_rHeapManager)
        {
        }

        /// gets a data segment reference for the given path - creates if necessary
        memory::Segment * createDataSegment(ModuleName const & _aModule);

        /** add the given template tree at the given location,
            return the tree that is now pertinent and clientAcquire() it once
        */
        data::TreeAddress addTemplates( memory::UpdateAccessor& _aAccessToken,
                                        backend::ComponentData const & _aComponentInstance
                                       ) CFG_UNO_THROW_RTE();

    private:
        virtual ModuleRef doCreateAttachedModule(memory::HeapManager & _rHeapManager, const memory::SegmentAddress & _aLocation, const ModuleName& _aName) CFG_UNO_THROW_RTE(  );

        CacheLineRef implNewCacheLine(ModuleName const & _aModule) CFG_UNO_THROW_RTE(  );
    };
//-----------------------------------------------------------------------------
    /** A collection of CacheLines
    */

    class ExtendedCacheData : public CacheData
    {
    public:
        ExtendedCacheData(memory::HeapManager & _rHeapManager)
        : CacheData(_rHeapManager)
        {
        }

        /// gets a data segment reference for the given path - creates if necessary
        memory::Segment * createDataSegment(ModuleName const & _aModule);

        /** add the given subtree at the given location,
            return the tree that is now pertinent and clientAcquire() it once
        */
        data::TreeAddress addComponentData( memory::UpdateAccessor& _aAccessToken,
                                            backend::ComponentInstance const & _aComponentInstance,
                                            bool _bWithDefaults
                                           ) CFG_UNO_THROW_RTE();

        typedef std::vector< ModuleName >  PendingModuleList;
        /// find the modules having pending changes
        bool hasPending(ModuleName const & _aModule);
        /// find the modules having pending changes
        void findPendingModules( PendingModuleList & _rPendingList );

        /// add or merge the given subtreechange at the given location
        void addPending(backend::ConstUpdateInstance const & _anUpdate) CFG_UNO_THROW_RTE(  );
        /// remove and return pending changes for the given component
        std::auto_ptr<SubtreeChange> releasePending(ModuleName const & _aModule) CFG_UNO_THROW_RTE(  );
    private:
        virtual ModuleRef doCreateAttachedModule(memory::HeapManager & _rHeapManager, const memory::SegmentAddress & _aLocation, const ModuleName& _aName) CFG_UNO_THROW_RTE(  );

        ExtendedCacheLineRef implNewCacheLine(ModuleName const & _aModule) CFG_UNO_THROW_RTE(  );

        ExtendedCacheLineRef implExtended(ModuleRef const & _aSimpleRef) const;
    };
//-----------------------------------------------------------------------------

} // namespace configmgr

#endif

<|endoftext|>


<commit_before>//---------------------------------------------------------------------------//
/*
  Copyright (c) 2012, Stuart R. Slattery
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:

  *: Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.

  *: Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

  *: Neither the name of the University of Wisconsin - Madison nor the
  names of its contributors may be used to endorse or promote products
  derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//---------------------------------------------------------------------------//
/*!
 * \file MCLS_EpetraAdapater.hpp
 * \author Stuart R. Slattery
 * \brief Epetra Helpers.
 */
//---------------------------------------------------------------------------//

#ifndef MCLS_EPETRAHELPERS_HPP
#define MCLS_EPETRAHELPERS_HPP

#include <MCLS_DBC.hpp>

#include <Teuchos_RCP.hpp>
#include <Teuchos_Array.hpp>
#include <Teuchos_ArrayView.hpp>
#include <Teuchos_as.hpp>

#include <Epetra_Map.h>
#include <Epetra_RowMatrix.h>
#include <Epetra_CrsMatrix.h>
#include <Epetra_Export.h>
#include <Epetra_RowMatrixTransposer.h>

#include <EpetraExt_MatrixMatrix.h>

//---------------------------------------------------------------------------//
/*!
 * \class UndefinedEpetraHelpers
 * \brief Class for undefined EpetraHelper functions.
 *
 * Will throw a compile-time error if these traits are not specialized.
 */
template<class Matrix>
struct UndefinedEpetraHelpers
{
    static inline void notDefined()
    {
	return Matrix::this_type_is_missing_a_specialization();
    }
};

namespace MCLS
{
//---------------------------------------------------------------------------//
/*!
 * \class EpetraMatrixHelpers
 * \brief Helper functions for Epetra implementations.
 */
template<class Matrix>
class EpetraMatrixHelpers
{
  public:

    //@{
    //! Typedefs.
    typedef Matrix                                  matrix_type;
    //@}

    /*!
     * \brief Get the on-process global matrix column indices that, as global
     * row indices, are off-process.
     */
    static Teuchos::Array<int> getOffProcColsAsRows( const Matrix& matrix )
    {
	UndefinedEpetraHelpers<Matrix>::notDefined();
	return Teuchos::Array<int>(0);
    }

    /*!
     * \brief Get a copy of the transpose of a matrix.
     */
    static Teuchos::RCP<matrix_type> copyTranspose( const matrix_type& matrix )
    {
	UndefinedEpetraHelpers<Matrix>::notDefined();
	return Teuchos::null;
    }

    /*
     * \brief Create a reference-counted pointer to a new matrix with a
     * specified number of off-process nearest-neighbor global rows.
     */
    static Teuchos::RCP<matrix_type> copyNearestNeighbors(
    	const matrix_type& matrix, const int& num_neighbors )
    {
	UndefinedEpetraHelpers<Matrix>::notDefined();
	return Teuchos::null;
    }

    /*!
     * \brief Matrix-Matrix multiply C = A*B
     */
    static void multiply( const Teuchos::RCP<const matrix_type>& A,
			  const Teuchos::RCP<const matrix_type>& B,
			  const Teuchos::RCP<matrix_type>& C )
    { UndefinedEpetraHelpers<Matrix>::notDefined(); }
};

//---------------------------------------------------------------------------//
/*!
 * \class EpetraMatrixHelpers
 * \brief EpetraMatrixHelpers specialization for Epetra_RowMatrix.
 */
template<>
class EpetraMatrixHelpers<Epetra_RowMatrix>
{
  public:

    //@{
    //! Typedefs.
    typedef Epetra_RowMatrix               matrix_type;
    //@}

    /*!
     * \brief Get the on-process global matrix column indices that, as global
     * row indices, are off-process.
     */
    static Teuchos::Array<int> getOffProcColsAsRows( const matrix_type& matrix )
    {
	MCLS_REQUIRE( matrix.Filled() );

	const Epetra_Map& row_map = matrix.RowMatrixRowMap();
	const Epetra_Map& col_map = matrix.RowMatrixColMap();

	Teuchos::ArrayView<const int> global_cols( col_map.MyGlobalElements(),
						   col_map.NumMyElements() );

	Teuchos::Array<int> off_proc_cols(0);
	Teuchos::ArrayView<const int>::const_iterator global_col_it;
	for ( global_col_it = global_cols.begin();
	      global_col_it != global_cols.end();
	      ++global_col_it )
	{
	    if ( !row_map.MyGID( *global_col_it ) )
	    {
		off_proc_cols.push_back( *global_col_it );
	    }
	}

	return off_proc_cols;
    }

    /*!
     * \brief Get a copy of the transpose of a matrix.
     */
    static Teuchos::RCP<matrix_type> copyTranspose( const matrix_type& matrix )
    {
	Epetra_RowMatrixTransposer transposer( const_cast<matrix_type*>(&matrix) );

	Epetra_CrsMatrix* transpose_matrix;
	int error = transposer.CreateTranspose( false, transpose_matrix );
        MCLS_CHECK( 0 == error );

	MCLS_ENSURE( transpose_matrix->Filled() );
	return Teuchos::RCP<matrix_type>( transpose_matrix );
    }

    /*
     * \brief Create a reference-counted pointer to a new matrix with a
     * specified number of off-process nearest-neighbor global rows.
     */
    static Teuchos::RCP<matrix_type> copyNearestNeighbors(
    	const matrix_type& matrix, const int& num_neighbors )
    {
	MCLS_REQUIRE( num_neighbors >= 0 );

	// Setup for neighbor construction.
	Teuchos::RCP<const Epetra_Map> empty_map = Teuchos::rcp(
	    new Epetra_Map( 0, 0, matrix.Comm() ) );
	Teuchos::RCP<Epetra_CrsMatrix> neighbor_matrix =
	    Teuchos::rcp( new Epetra_CrsMatrix( Copy, *empty_map, 0 ) );
	int error = neighbor_matrix->FillComplete();
        MCLS_CHECK( 0 == error );

	Teuchos::ArrayView<const int> global_rows;
	Teuchos::ArrayView<const int>::const_iterator global_rows_it;
	Teuchos::Array<int>::iterator ghost_global_bound;

	// Get the initial off proc columns.
	Teuchos::Array<int> ghost_global_rows = getOffProcColsAsRows( matrix );

	// Build the neighbors by traversing the graph.
	for ( int i = 0; i < num_neighbors; ++i )
	{
	    // Get rid of the global rows that belong to the original
	    // matrix. We don't need to store these, just the neighbors.
	    global_rows = Teuchos::ArrayView<const int>(
		matrix.RowMatrixRowMap().MyGlobalElements(),
		matrix.RowMatrixRowMap().NumMyElements() );
	    for ( global_rows_it = global_rows.begin();
		  global_rows_it != global_rows.end();
		  ++global_rows_it )
	    {
		ghost_global_bound = std::remove( ghost_global_rows.begin(),
						  ghost_global_rows.end(),
						  *global_rows_it );
		ghost_global_rows.resize( std::distance(ghost_global_rows.begin(),
							ghost_global_bound) );
	    }

	    // Get the current set of global rows in the neighbor matrix.
	    global_rows = Teuchos::ArrayView<const int>(
		neighbor_matrix->RowMatrixRowMap().MyGlobalElements(),
		neighbor_matrix->RowMatrixRowMap().NumMyElements() );

	    // Append the on proc neighbor columns to the off proc columns.
	    for ( global_rows_it = global_rows.begin();
		  global_rows_it != global_rows.end();
		  ++global_rows_it )
	    {
		ghost_global_rows.push_back( *global_rows_it );
	    }

	    // Make a new map of the combined global rows and off proc columns.
	    Teuchos::RCP<const Epetra_Map> ghost_map = Teuchos::rcp(
		new Epetra_Map( -1,
				Teuchos::as<int>(ghost_global_rows.size()),
				ghost_global_rows.getRawPtr(),
				0,
				neighbor_matrix->Comm() ) );

	    // Export the neighbor matrix with the new neighbor.
	    Epetra_Export ghost_exporter( matrix.RowMatrixRowMap(), *ghost_map );

	    neighbor_matrix = Teuchos::rcp(
		new Epetra_CrsMatrix( Copy, *ghost_map, 0 ) );

	    neighbor_matrix->Export( matrix, ghost_exporter, Insert );
	    error = neighbor_matrix->FillComplete();
            MCLS_CHECK( 0 == error );

	    // Get the next rows in the graph.
	    ghost_global_rows = getOffProcColsAsRows( *neighbor_matrix );
	}

	MCLS_ENSURE( !neighbor_matrix.is_null() );
	MCLS_ENSURE( neighbor_matrix->Filled() );
	return neighbor_matrix;
    }

    /*!
     * \brief Matrix-Matrix multiply C = A*B
     */
    static void multiply( const Teuchos::RCP<const matrix_type>& A,
			  const Teuchos::RCP<const matrix_type>& B,
			  const Teuchos::RCP<matrix_type>& C )
    {
	Teuchos::RCP<const Epetra_CrsMatrix> A_crs =
	    Teuchos::rcp_dynamic_cast<const Epetra_CrsMatrix>( A );

	Teuchos::RCP<const Epetra_CrsMatrix> B_crs =
	    Teuchos::rcp_dynamic_cast<const Epetra_CrsMatrix>( B );

	Teuchos::RCP<Epetra_CrsMatrix> C_crs =
	    Teuchos::rcp_dynamic_cast<Epetra_CrsMatrix>( C );

	if ( Teuchos::is_null(A_crs) )
	{
	    A_crs = createCrsMatrix( A );
	}

	if ( Teuchos::is_null(B_crs) )
	{
	    B_crs = createCrsMatrix( B );
	}

	if ( Teuchos::is_null(C_crs) )
	{
	    C_crs = Teuchos::rcp(
		new Epetra_CrsMatrix(Copy, A->RowMatrixRowMap(), 0) );
	}

	EpetraExt::MatrixMatrix::Multiply(
	    *A_crs, false, *B_crs, false, *C_crs );
    }

    /*!
     * \brief Create a copy of a RowMatrix in a CrsMatrix.
     */
    static Teuchos::RCP<Epetra_CrsMatrix>
    createCrsMatrix( const Teuchos::RCP<const matrix_type>& A )
    {
        const Epetra_Map &row_map = A->RowMatrixRowMap();
        const Epetra_Map &col_map = A->RowMatrixColMap();

        Teuchos::RCP<Epetra_CrsMatrix> A_crs = Teuchos::rcp(
            new Epetra_CrsMatrix( Copy, row_map, col_map, 0 ) );

        int num_local_rows = row_map.NumMyElements();
        Teuchos::Array<int> my_global_rows( num_local_rows );
        row_map.MyGlobalElements( my_global_rows.getRawPtr() );

        int num_local_cols = col_map.NumMyElements() ;
        Teuchos::Array<int> my_global_cols( num_local_cols );
        col_map.MyGlobalElements( my_global_cols.getRawPtr() );

        int max_entries = A->MaxNumEntries();
        int num_entries = 0;
        Teuchos::Array<int> local_indices(max_entries);
        Teuchos::Array<int> global_indices(max_entries);
        Teuchos::Array<double> values(max_entries);

        int error = 0;
        for( int local_row = 0; local_row < num_local_rows; ++local_row )
        {
            error = A->ExtractMyRowCopy( local_row,
                                             max_entries,
                                             num_entries,
                                             values.getRawPtr(),
                                             local_indices.getRawPtr() );
            MCLS_CHECK( 0 == error );

            for (int j = 0 ; j < num_entries; ++j )
            {
                global_indices[j] = my_global_cols[ local_indices[j] ];
            }

            error = A_crs->InsertGlobalValues( my_global_rows[local_row],
                                                   num_entries,
                                                   values.getRawPtr(),
                                                   global_indices.getRawPtr() );
            MCLS_CHECK( 0 == error );
        }

        error = A_crs->FillComplete();
        MCLS_CHECK( 0 == error );
        return A_crs;
    }
};

//---------------------------------------------------------------------------//

} // end namespace MCLS

#endif // end MCLS_EPETRAHELPERS_HPP

//---------------------------------------------------------------------------//
// end MCLS_EpetraHelpers.hpp
//---------------------------------------------------------------------------//
<commit_msg>reverting transpose construction to contiguous storage for better performance<commit_after>//---------------------------------------------------------------------------//
/*
  Copyright (c) 2012, Stuart R. Slattery
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:

  *: Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.

  *: Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

  *: Neither the name of the University of Wisconsin - Madison nor the
  names of its contributors may be used to endorse or promote products
  derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//---------------------------------------------------------------------------//
/*!
 * \file MCLS_EpetraAdapater.hpp
 * \author Stuart R. Slattery
 * \brief Epetra Helpers.
 */
//---------------------------------------------------------------------------//

#ifndef MCLS_EPETRAHELPERS_HPP
#define MCLS_EPETRAHELPERS_HPP

#include <MCLS_DBC.hpp>

#include <Teuchos_RCP.hpp>
#include <Teuchos_Array.hpp>
#include <Teuchos_ArrayView.hpp>
#include <Teuchos_as.hpp>

#include <Epetra_Map.h>
#include <Epetra_RowMatrix.h>
#include <Epetra_CrsMatrix.h>
#include <Epetra_Export.h>
#include <Epetra_RowMatrixTransposer.h>

#include <EpetraExt_MatrixMatrix.h>

//---------------------------------------------------------------------------//
/*!
 * \class UndefinedEpetraHelpers
 * \brief Class for undefined EpetraHelper functions.
 *
 * Will throw a compile-time error if these traits are not specialized.
 */
template<class Matrix>
struct UndefinedEpetraHelpers
{
    static inline void notDefined()
    {
	return Matrix::this_type_is_missing_a_specialization();
    }
};

namespace MCLS
{
//---------------------------------------------------------------------------//
/*!
 * \class EpetraMatrixHelpers
 * \brief Helper functions for Epetra implementations.
 */
template<class Matrix>
class EpetraMatrixHelpers
{
  public:

    //@{
    //! Typedefs.
    typedef Matrix                                  matrix_type;
    //@}

    /*!
     * \brief Get the on-process global matrix column indices that, as global
     * row indices, are off-process.
     */
    static Teuchos::Array<int> getOffProcColsAsRows( const Matrix& matrix )
    {
	UndefinedEpetraHelpers<Matrix>::notDefined();
	return Teuchos::Array<int>(0);
    }

    /*!
     * \brief Get a copy of the transpose of a matrix.
     */
    static Teuchos::RCP<matrix_type> copyTranspose( const matrix_type& matrix )
    {
	UndefinedEpetraHelpers<Matrix>::notDefined();
	return Teuchos::null;
    }

    /*
     * \brief Create a reference-counted pointer to a new matrix with a
     * specified number of off-process nearest-neighbor global rows.
     */
    static Teuchos::RCP<matrix_type> copyNearestNeighbors(
    	const matrix_type& matrix, const int& num_neighbors )
    {
	UndefinedEpetraHelpers<Matrix>::notDefined();
	return Teuchos::null;
    }

    /*!
     * \brief Matrix-Matrix multiply C = A*B
     */
    static void multiply( const Teuchos::RCP<const matrix_type>& A,
			  const Teuchos::RCP<const matrix_type>& B,
			  const Teuchos::RCP<matrix_type>& C )
    { UndefinedEpetraHelpers<Matrix>::notDefined(); }
};

//---------------------------------------------------------------------------//
/*!
 * \class EpetraMatrixHelpers
 * \brief EpetraMatrixHelpers specialization for Epetra_RowMatrix.
 */
template<>
class EpetraMatrixHelpers<Epetra_RowMatrix>
{
  public:

    //@{
    //! Typedefs.
    typedef Epetra_RowMatrix               matrix_type;
    //@}

    /*!
     * \brief Get the on-process global matrix column indices that, as global
     * row indices, are off-process.
     */
    static Teuchos::Array<int> getOffProcColsAsRows( const matrix_type& matrix )
    {
	MCLS_REQUIRE( matrix.Filled() );

	const Epetra_Map& row_map = matrix.RowMatrixRowMap();
	const Epetra_Map& col_map = matrix.RowMatrixColMap();

	Teuchos::ArrayView<const int> global_cols( col_map.MyGlobalElements(),
						   col_map.NumMyElements() );

	Teuchos::Array<int> off_proc_cols(0);
	Teuchos::ArrayView<const int>::const_iterator global_col_it;
	for ( global_col_it = global_cols.begin();
	      global_col_it != global_cols.end();
	      ++global_col_it )
	{
	    if ( !row_map.MyGID( *global_col_it ) )
	    {
		off_proc_cols.push_back( *global_col_it );
	    }
	}

	return off_proc_cols;
    }

    /*!
     * \brief Get a copy of the transpose of a matrix.
     */
    static Teuchos::RCP<matrix_type> copyTranspose( const matrix_type& matrix )
    {
	Epetra_RowMatrixTransposer transposer( const_cast<matrix_type*>(&matrix) );

	Epetra_CrsMatrix* transpose_matrix;
	int error = transposer.CreateTranspose( true, transpose_matrix );
        MCLS_CHECK( 0 == error );

	MCLS_ENSURE( transpose_matrix->Filled() );
	return Teuchos::RCP<matrix_type>( transpose_matrix );
    }

    /*
     * \brief Create a reference-counted pointer to a new matrix with a
     * specified number of off-process nearest-neighbor global rows.
     */
    static Teuchos::RCP<matrix_type> copyNearestNeighbors(
    	const matrix_type& matrix, const int& num_neighbors )
    {
	MCLS_REQUIRE( num_neighbors >= 0 );

	// Setup for neighbor construction.
	Teuchos::RCP<const Epetra_Map> empty_map = Teuchos::rcp(
	    new Epetra_Map( 0, 0, matrix.Comm() ) );
	Teuchos::RCP<Epetra_CrsMatrix> neighbor_matrix =
	    Teuchos::rcp( new Epetra_CrsMatrix( Copy, *empty_map, 0 ) );
	int error = neighbor_matrix->FillComplete();
        MCLS_CHECK( 0 == error );

	Teuchos::ArrayView<const int> global_rows;
	Teuchos::ArrayView<const int>::const_iterator global_rows_it;
	Teuchos::Array<int>::iterator ghost_global_bound;

	// Get the initial off proc columns.
	Teuchos::Array<int> ghost_global_rows = getOffProcColsAsRows( matrix );

	// Build the neighbors by traversing the graph.
	for ( int i = 0; i < num_neighbors; ++i )
	{
	    // Get rid of the global rows that belong to the original
	    // matrix. We don't need to store these, just the neighbors.
	    global_rows = Teuchos::ArrayView<const int>(
		matrix.RowMatrixRowMap().MyGlobalElements(),
		matrix.RowMatrixRowMap().NumMyElements() );
	    for ( global_rows_it = global_rows.begin();
		  global_rows_it != global_rows.end();
		  ++global_rows_it )
	    {
		ghost_global_bound = std::remove( ghost_global_rows.begin(),
						  ghost_global_rows.end(),
						  *global_rows_it );
		ghost_global_rows.resize( std::distance(ghost_global_rows.begin(),
							ghost_global_bound) );
	    }

	    // Get the current set of global rows in the neighbor matrix.
	    global_rows = Teuchos::ArrayView<const int>(
		neighbor_matrix->RowMatrixRowMap().MyGlobalElements(),
		neighbor_matrix->RowMatrixRowMap().NumMyElements() );

	    // Append the on proc neighbor columns to the off proc columns.
	    for ( global_rows_it = global_rows.begin();
		  global_rows_it != global_rows.end();
		  ++global_rows_it )
	    {
		ghost_global_rows.push_back( *global_rows_it );
	    }

	    // Make a new map of the combined global rows and off proc columns.
	    Teuchos::RCP<const Epetra_Map> ghost_map = Teuchos::rcp(
		new Epetra_Map( -1,
				Teuchos::as<int>(ghost_global_rows.size()),
				ghost_global_rows.getRawPtr(),
				0,
				neighbor_matrix->Comm() ) );

	    // Export the neighbor matrix with the new neighbor.
	    Epetra_Export ghost_exporter( matrix.RowMatrixRowMap(), *ghost_map );

	    neighbor_matrix = Teuchos::rcp(
		new Epetra_CrsMatrix( Copy, *ghost_map, 0 ) );

	    neighbor_matrix->Export( matrix, ghost_exporter, Insert );
	    error = neighbor_matrix->FillComplete();
            MCLS_CHECK( 0 == error );

	    // Get the next rows in the graph.
	    ghost_global_rows = getOffProcColsAsRows( *neighbor_matrix );
	}

	MCLS_ENSURE( !neighbor_matrix.is_null() );
	MCLS_ENSURE( neighbor_matrix->Filled() );
	return neighbor_matrix;
    }

    /*!
     * \brief Matrix-Matrix multiply C = A*B
     */
    static void multiply( const Teuchos::RCP<const matrix_type>& A,
			  const Teuchos::RCP<const matrix_type>& B,
			  const Teuchos::RCP<matrix_type>& C )
    {
	Teuchos::RCP<const Epetra_CrsMatrix> A_crs =
	    Teuchos::rcp_dynamic_cast<const Epetra_CrsMatrix>( A );

	Teuchos::RCP<const Epetra_CrsMatrix> B_crs =
	    Teuchos::rcp_dynamic_cast<const Epetra_CrsMatrix>( B );

	Teuchos::RCP<Epetra_CrsMatrix> C_crs =
	    Teuchos::rcp_dynamic_cast<Epetra_CrsMatrix>( C );

	if ( Teuchos::is_null(A_crs) )
	{
	    A_crs = createCrsMatrix( A );
	}

	if ( Teuchos::is_null(B_crs) )
	{
	    B_crs = createCrsMatrix( B );
	}

	if ( Teuchos::is_null(C_crs) )
	{
	    C_crs = Teuchos::rcp(
		new Epetra_CrsMatrix(Copy, A->RowMatrixRowMap(), 0) );
	}

	EpetraExt::MatrixMatrix::Multiply(
	    *A_crs, false, *B_crs, false, *C_crs );
    }

    /*!
     * \brief Create a copy of a RowMatrix in a CrsMatrix.
     */
    static Teuchos::RCP<Epetra_CrsMatrix>
    createCrsMatrix( const Teuchos::RCP<const matrix_type>& A )
    {
        const Epetra_Map &row_map = A->RowMatrixRowMap();
        const Epetra_Map &col_map = A->RowMatrixColMap();

        Teuchos::RCP<Epetra_CrsMatrix> A_crs = Teuchos::rcp(
            new Epetra_CrsMatrix( Copy, row_map, col_map, 0 ) );

        int num_local_rows = row_map.NumMyElements();
        Teuchos::Array<int> my_global_rows( num_local_rows );
        row_map.MyGlobalElements( my_global_rows.getRawPtr() );

        int num_local_cols = col_map.NumMyElements() ;
        Teuchos::Array<int> my_global_cols( num_local_cols );
        col_map.MyGlobalElements( my_global_cols.getRawPtr() );

        int max_entries = A->MaxNumEntries();
        int num_entries = 0;
        Teuchos::Array<int> local_indices(max_entries);
        Teuchos::Array<int> global_indices(max_entries);
        Teuchos::Array<double> values(max_entries);

        int error = 0;
        for( int local_row = 0; local_row < num_local_rows; ++local_row )
        {
            error = A->ExtractMyRowCopy( local_row,
                                             max_entries,
                                             num_entries,
                                             values.getRawPtr(),
                                             local_indices.getRawPtr() );
            MCLS_CHECK( 0 == error );

            for (int j = 0 ; j < num_entries; ++j )
            {
                global_indices[j] = my_global_cols[ local_indices[j] ];
            }

            error = A_crs->InsertGlobalValues( my_global_rows[local_row],
                                                   num_entries,
                                                   values.getRawPtr(),
                                                   global_indices.getRawPtr() );
            MCLS_CHECK( 0 == error );
        }

        error = A_crs->FillComplete();
        MCLS_CHECK( 0 == error );
        return A_crs;
    }
};

//---------------------------------------------------------------------------//

} // end namespace MCLS

#endif // end MCLS_EPETRAHELPERS_HPP

//---------------------------------------------------------------------------//
// end MCLS_EpetraHelpers.hpp
//---------------------------------------------------------------------------//
<|endoftext|>


<commit_before>#include <sirius.h>
#include <fstream>
#include <string>

using namespace sirius;

void test_hloc(std::vector<int> mpi_grid_dims__, double cutoff__, int num_bands__, int reduce_gvec__,
               int use_gpu__, int gpu_ptr__)
{
    device_t pu = static_cast<device_t>(use_gpu__);

    matrix3d<double> M = {{10, 0, 0}, {0, 10, 0}, {0, 0, 10}};

    for (int i = 0; i < 3; i++) {
        printf("  a%1i : %18.10f %18.10f %18.10f \n", i + 1, M(0, i), M(1, i), M(2, i));
    }

    Simulation_context params;
    params.set_processing_unit(pu);
    params.unit_cell().set_lattice_vectors(M);
    params.mpi_grid_dims(mpi_grid_dims__);
    params.pw_cutoff(cutoff__ + 1);
    params.gk_cutoff(cutoff__ / 2);
    params.electronic_structure_method("pseudopotential");
    params.use_symmetry(false);
    params.initialize();

    auto& gvec = params.gvec();
    auto& gvecp = params.gvec_partition();
    auto& fft = params.spfft();

    if (Communicator::world().rank() == 0) {
        printf("total number of G-vectors: %i\n", gvec.num_gvec());
        printf("local number of G-vectors: %i\n", gvec.gvec_count(0));
        printf("FFT grid size: %i %i %i\n", fft.dim_x(), fft.dim_y(), fft.dim_z());
        printf("number of FFT threads: %i\n", omp_get_max_threads());
        printf("number of FFT groups: %i\n", params.comm_ortho_fft().size());
        //printf("MPI grid: %i %i\n", mpi_grid.communicator(1 << 0).size(), mpi_grid.communicator(1 << 1).size());
        printf("number of z-columns: %i\n", gvec.num_zcol());
    }

    Local_operator hloc(params, fft, gvecp);

    //Wave_functions phi(gvecp, 4 * num_bands__, memory_t::host);
    //for (int i = 0; i < 4 * num_bands__; i++) {
    //    for (int j = 0; j < phi.pw_coeffs(0).num_rows_loc(); j++) {
    //        phi.pw_coeffs(0).prime(j, i) = utils::random<double_complex>();
    //    }
    //    phi.pw_coeffs(0).prime(0, i) = 1.0;
    //}
    //Wave_functions hphi(gvecp, 4 * num_bands__, memory_t::host);

    //if (pu == device_t::GPU) {
    //    phi.pw_coeffs(0).allocate(memory_t::device);
    //    phi.pw_coeffs(0).copy_to(memory_t::device, 0, 4 * num_bands__);
    //    hphi.pw_coeffs(0).allocate(memory_t::device);
    //}
    //hloc.prepare(gvecp);
    //Communicator::world().barrier();
    //utils::timer t1("h_loc");
    //for (int i = 0; i < 4; i++) {
    //    hloc.apply_h(fft, spin_range(0), phi, hphi, i * num_bands__, num_bands__);
    //}
    //Communicator::world().barrier();
    //t1.stop();
    //hloc.dismiss();

    //double diff{0};
    //for (int i = 0; i < 4 * num_bands__; i++) {
    //    for (int j = 0; j < phi.pw_coeffs(0).num_rows_loc(); j++) {
    //        int ig = gvec.offset() + j;
    //        auto gc = gvec.gvec_cart<index_domain_t::global>(ig);
    //        diff += std::pow(std::abs((2.71828 + 0.5 * dot(gc, gc)) * phi.pw_coeffs(0).prime(j, i) - hphi.pw_coeffs(0).prime(j, i)), 2);
    //    }
    //}
    //if (diff != diff) {
    //    TERMINATE("NaN");
    //}
    //Communicator::world().allreduce(&diff, 1);
    //diff = std::sqrt(diff / 4 / num_bands__ / gvec.num_gvec());
    //if (Communicator::world().rank() == 0) {
    //    printf("RMS: %18.16f\n", diff);
    //}
    //if (diff > 1e-12) {
    //    TERMINATE("RMS is too large");
    //}
}

int main(int argn, char** argv)
{
    cmd_args args;
    args.register_key("--mpi_grid_dims=", "{int int} dimensions of MPI grid");
    args.register_key("--cutoff=", "{double} wave-functions cutoff");
    args.register_key("--reduce_gvec=", "{int} 0: use full set of G-vectors, 1: use reduced set of G-vectors");
    args.register_key("--num_bands=", "{int} number of bands");
    args.register_key("--use_gpu=", "{int} 0: CPU only, 1: hybrid CPU+GPU");
    args.register_key("--gpu_ptr=", "{int} 0: start from CPU, 1: start from GPU");
    args.register_key("--repeat=", "{int} number of repetitions");
    args.register_key("--t_file=", "{string} name of timing output file");

    args.parse_args(argn, argv);
    if (args.exist("help")) {
        printf("Usage: %s [options]\n", argv[0]);
        args.print_help();
        return 0;
    }
    auto mpi_grid_dims = args.value< std::vector<int> >("mpi_grid_dims", {1, 1});
    auto cutoff = args.value<double>("cutoff", 10.0);
    auto reduce_gvec = args.value<int>("reduce_gvec", 0);
    auto num_bands = args.value<int>("num_bands", 10);
    auto use_gpu = args.value<int>("use_gpu", 0);
    auto gpu_ptr = args.value<int>("gpu_ptr", 0);
    auto repeat = args.value<int>("repeat", 3);
    auto t_file = args.value<std::string>("t_file", std::string(""));

    sirius::initialize(1);
    for (int i = 0; i < repeat; i++) {
        test_hloc(mpi_grid_dims, cutoff, num_bands, reduce_gvec, use_gpu, gpu_ptr);
    }
    int my_rank = Communicator::world().rank();

    sirius::finalize(1);

    if (my_rank == 0)  {
        const auto timing_result = ::utils::global_rtgraph_timer.process();
        std::cout << timing_result.print();
        //if (!t_file.empty()) {
        //    std::ofstream json_file(t_file);
        //    json_file << std::setw(2) << utils::timer::serialize() << std::endl;
        //}
    }
}
<commit_msg>restore test_hloc<commit_after>#include <sirius.h>
#include <fstream>
#include <string>

using namespace sirius;

void test_hloc(std::vector<int> mpi_grid_dims__, double cutoff__, int num_bands__, int reduce_gvec__,
               int use_gpu__, int gpu_ptr__)
{
    device_t pu = static_cast<device_t>(use_gpu__);

    matrix3d<double> M = {{10, 0, 0}, {0, 10, 0}, {0, 0, 10}};

    for (int i = 0; i < 3; i++) {
        printf("  a%1i : %18.10f %18.10f %18.10f \n", i + 1, M(0, i), M(1, i), M(2, i));
    }

    Simulation_context params;
    params.set_processing_unit(pu);
    params.unit_cell().set_lattice_vectors(M);
    params.mpi_grid_dims(mpi_grid_dims__);
    params.pw_cutoff(cutoff__ + 1);
    params.gk_cutoff(cutoff__ / 2);
    params.electronic_structure_method("pseudopotential");
    params.use_symmetry(false);
    params.initialize();

    auto& gvec = params.gvec();
    auto& gvecp = params.gvec_partition();
    auto& fft = params.spfft();

    if (Communicator::world().rank() == 0) {
        printf("total number of G-vectors: %i\n", gvec.num_gvec());
        printf("local number of G-vectors: %i\n", gvec.gvec_count(0));
        printf("FFT grid size: %i %i %i\n", fft.dim_x(), fft.dim_y(), fft.dim_z());
        printf("number of FFT threads: %i\n", omp_get_max_threads());
        printf("number of FFT groups: %i\n", params.comm_ortho_fft().size());
        //printf("MPI grid: %i %i\n", mpi_grid.communicator(1 << 0).size(), mpi_grid.communicator(1 << 1).size());
        printf("number of z-columns: %i\n", gvec.num_zcol());
    }

    Local_operator hloc(params, fft, gvecp);

    Wave_functions phi(gvecp, 4 * num_bands__, memory_t::host);
    for (int i = 0; i < 4 * num_bands__; i++) {
        for (int j = 0; j < phi.pw_coeffs(0).num_rows_loc(); j++) {
            phi.pw_coeffs(0).prime(j, i) = utils::random<double_complex>();
        }
        phi.pw_coeffs(0).prime(0, i) = 1.0;
    }
    Wave_functions hphi(gvecp, 4 * num_bands__, memory_t::host);

    if (pu == device_t::GPU) {
        phi.pw_coeffs(0).allocate(memory_t::device);
        phi.pw_coeffs(0).copy_to(memory_t::device, 0, 4 * num_bands__);
        hphi.pw_coeffs(0).allocate(memory_t::device);
    }
    hloc.prepare_k(gvecp);
    for (int i = 0; i < 4; i++) {
        hloc.apply_h(fft, gvecp, spin_range(0), phi, hphi, i * num_bands__, num_bands__);
    }
    //hloc.dismiss();

    double diff{0};
    for (int i = 0; i < 4 * num_bands__; i++) {
        for (int j = 0; j < phi.pw_coeffs(0).num_rows_loc(); j++) {
            int ig = gvec.offset() + j;
            auto gc = gvec.gvec_cart<index_domain_t::global>(ig);
            diff += std::pow(std::abs((2.71828 + 0.5 * dot(gc, gc)) * phi.pw_coeffs(0).prime(j, i) - hphi.pw_coeffs(0).prime(j, i)), 2);
        }
    }
    if (diff != diff) {
        TERMINATE("NaN");
    }
    Communicator::world().allreduce(&diff, 1);
    diff = std::sqrt(diff / 4 / num_bands__ / gvec.num_gvec());
    if (Communicator::world().rank() == 0) {
        printf("RMS: %18.16f\n", diff);
    }
    if (diff > 1e-12) {
        TERMINATE("RMS is too large");
    }
}

int main(int argn, char** argv)
{
    cmd_args args;
    args.register_key("--mpi_grid_dims=", "{int int} dimensions of MPI grid");
    args.register_key("--cutoff=", "{double} wave-functions cutoff");
    args.register_key("--reduce_gvec=", "{int} 0: use full set of G-vectors, 1: use reduced set of G-vectors");
    args.register_key("--num_bands=", "{int} number of bands");
    args.register_key("--use_gpu=", "{int} 0: CPU only, 1: hybrid CPU+GPU");
    args.register_key("--gpu_ptr=", "{int} 0: start from CPU, 1: start from GPU");
    args.register_key("--repeat=", "{int} number of repetitions");
    args.register_key("--t_file=", "{string} name of timing output file");

    args.parse_args(argn, argv);
    if (args.exist("help")) {
        printf("Usage: %s [options]\n", argv[0]);
        args.print_help();
        return 0;
    }
    auto mpi_grid_dims = args.value< std::vector<int> >("mpi_grid_dims", {1, 1});
    auto cutoff = args.value<double>("cutoff", 10.0);
    auto reduce_gvec = args.value<int>("reduce_gvec", 0);
    auto num_bands = args.value<int>("num_bands", 10);
    auto use_gpu = args.value<int>("use_gpu", 0);
    auto gpu_ptr = args.value<int>("gpu_ptr", 0);
    auto repeat = args.value<int>("repeat", 3);
    auto t_file = args.value<std::string>("t_file", std::string(""));

    sirius::initialize(1);
    for (int i = 0; i < repeat; i++) {
        test_hloc(mpi_grid_dims, cutoff, num_bands, reduce_gvec, use_gpu, gpu_ptr);
    }
    int my_rank = Communicator::world().rank();

    sirius::finalize(1);

    if (my_rank == 0)  {
        const auto timing_result = ::utils::global_rtgraph_timer.process();
        std::cout << timing_result.print();
        //if (!t_file.empty()) {
        //    std::ofstream json_file(t_file);
        //    json_file << std::setw(2) << utils::timer::serialize() << std::endl;
        //}
    }
}
<|endoftext|>


<commit_before><commit_msg>Remove net/url_request/fraudulent_certificate_reporter.cc.<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: myucp_datasupplier.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: ihi $ $Date: 2007-06-05 14:39:46 $
 *
 *  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 DBA_DATASUPPLIER_HXX
#define DBA_DATASUPPLIER_HXX

#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
#ifndef _UCBHELPER_RESULTSET_HXX
#include <ucbhelper/resultset.hxx>
#endif
#ifndef _DBA_COREDATAACCESS_DOCUMENTCONTAINER_HXX_
#include "documentcontainer.hxx"
#endif
#include <memory>

namespace dbaccess {

struct DataSupplier_Impl;
class OContentHelper;

class DataSupplier : public ucbhelper::ResultSetDataSupplier
{
    ::std::auto_ptr<DataSupplier_Impl> m_pImpl;

public:
    DataSupplier( const com::sun::star::uno::Reference<
                      com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
                    const rtl::Reference< ODocumentContainer >& rxContent,
                  sal_Int32 nOpenMode );
    virtual ~DataSupplier();

    virtual rtl::OUString queryContentIdentifierString( sal_uInt32 nIndex );
    virtual com::sun::star::uno::Reference<
                com::sun::star::ucb::XContentIdentifier >
    queryContentIdentifier( sal_uInt32 nIndex );
    virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContent >
    queryContent( sal_uInt32 nIndex );

    virtual sal_Bool getResult( sal_uInt32 nIndex );

    virtual sal_uInt32 totalCount();
    virtual sal_uInt32 currentCount();
    virtual sal_Bool isCountFinal();

    virtual com::sun::star::uno::Reference< com::sun::star::sdbc::XRow >
    queryPropertyValues( sal_uInt32 nIndex  );
    virtual void releasePropertyValues( sal_uInt32 nIndex );

    virtual void close();

    virtual void validate()
        throw( com::sun::star::ucb::ResultSetException );
};

}

#endif // DBA_DATASUPPLIER_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.5.166); FILE MERGED 2008/03/31 13:26:47 rt 1.5.166.1: #i87441# Change license header to LPGL v3.<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: myucp_datasupplier.hxx,v $
 * $Revision: 1.6 $
 *
 * 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.
 *
 ************************************************************************/

#ifndef DBA_DATASUPPLIER_HXX
#define DBA_DATASUPPLIER_HXX

#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
#ifndef _UCBHELPER_RESULTSET_HXX
#include <ucbhelper/resultset.hxx>
#endif
#ifndef _DBA_COREDATAACCESS_DOCUMENTCONTAINER_HXX_
#include "documentcontainer.hxx"
#endif
#include <memory>

namespace dbaccess {

struct DataSupplier_Impl;
class OContentHelper;

class DataSupplier : public ucbhelper::ResultSetDataSupplier
{
    ::std::auto_ptr<DataSupplier_Impl> m_pImpl;

public:
    DataSupplier( const com::sun::star::uno::Reference<
                      com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
                    const rtl::Reference< ODocumentContainer >& rxContent,
                  sal_Int32 nOpenMode );
    virtual ~DataSupplier();

    virtual rtl::OUString queryContentIdentifierString( sal_uInt32 nIndex );
    virtual com::sun::star::uno::Reference<
                com::sun::star::ucb::XContentIdentifier >
    queryContentIdentifier( sal_uInt32 nIndex );
    virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContent >
    queryContent( sal_uInt32 nIndex );

    virtual sal_Bool getResult( sal_uInt32 nIndex );

    virtual sal_uInt32 totalCount();
    virtual sal_uInt32 currentCount();
    virtual sal_Bool isCountFinal();

    virtual com::sun::star::uno::Reference< com::sun::star::sdbc::XRow >
    queryPropertyValues( sal_uInt32 nIndex  );
    virtual void releasePropertyValues( sal_uInt32 nIndex );

    virtual void close();

    virtual void validate()
        throw( com::sun::star::ucb::ResultSetException );
};

}

#endif // DBA_DATASUPPLIER_HXX
<|endoftext|>


<commit_before>#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "chplalloc.h"
#include "misc.h"
#include "stringutil.h"

char* glomstrings(int numstrings, ...) {
  int i;

  char** stringlist = (char**)MALLOC(numstrings * sizeof(char*));
  va_list ap;
  va_start(ap, numstrings);
  for (i=0; i<numstrings; i++) {
    stringlist[i] = va_arg(ap, char*);
  }
  va_end(ap);

  unsigned int totlen = 0;
  for (i=0; i<numstrings; i++) {
    totlen += strlen(stringlist[i]);
  }

  char* newstring = (char*)MALLOC((totlen + 1)*sizeof(char));
  newstring[0] = '\0';
  for (i=0; i<numstrings; i++) {
    strcat(newstring, stringlist[i]);
  }

  if (strlen(newstring) > totlen) {
    INT_FATAL("glomstrings() buffer overflow");
  }

  return newstring;
}

char* copystring(char* str) {
  return glomstrings(1, str);
}

char* intstring(int i) {
  char scratch[8];

  sprintf(scratch, "%d", i);
  return glomstrings(1, scratch);
}
<commit_msg><commit_after>#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "chplalloc.h"
#include "misc.h"
#include "stringutil.h"

char* glomstrings(int numstrings, ...) {
  int i;

  char** stringlist = (char**)MALLOC(numstrings * sizeof(char*));
  va_list ap;
  va_start(ap, numstrings);
  for (i=0; i<numstrings; i++) {
    stringlist[i] = va_arg(ap, char*);
  }
  va_end(ap);

  unsigned int totlen = 0;
  for (i=0; i<numstrings; i++) {
    totlen += strlen(stringlist[i]);
  }

  char* newstring = (char*)MALLOC((totlen + 1)*sizeof(char));
  newstring[0] = '\0';
  for (i=0; i<numstrings; i++) {
    strcat(newstring, stringlist[i]);
  }

  if (strlen(newstring) > totlen) {
    INT_FATAL("glomstrings() buffer overflow");
  }

  return newstring;
}

char* copystring(char* str) {
  return glomstrings(1, str);
}

char* intstring(int i) {
  const size_t size = 64;
  char scratch[size];
  size_t charsWritten = snprintf(scratch, size, "%d", i);

  if (charsWritten > size) {
    INT_FATAL("intstring() buffer overflow");
  }

  return glomstrings(1, scratch);
}
<|endoftext|>


<commit_before>/*!
  \copyright (c) RDO-Team, 2012
  \file      main.cpp
  \author      (lord.tiran@gmail.com)
  \date      13.05.2012
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#include <iostream>
#include <boost/format.hpp>
#define BOOST_TEST_MODULE RDORealFormatTest
#include <boost/test/included/unit_test.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
// --------------------------------------------------------------------------------

BOOST_AUTO_TEST_SUITE(RDORealFormatTest)

BOOST_AUTO_TEST_CASE(MantissaPrecision)
{
	double value = 10e+237;
	std::stringstream stream;
	stream << boost::format("%1$.10E") % value;

	std::string str = stream.str();
	std::cout << str << std::endl;

	BOOST_CHECK(stream.str() == "1.0000000000E+238");
}

BOOST_AUTO_TEST_SUITE_END() // RDORealFormatTest
<commit_msg> - другое число<commit_after>/*!
  \copyright (c) RDO-Team, 2012
  \file      main.cpp
  \author      (lord.tiran@gmail.com)
  \date      13.05.2012
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#include <iostream>
#include <boost/format.hpp>
#define BOOST_TEST_MODULE RDORealFormatTest
#include <boost/test/included/unit_test.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
// --------------------------------------------------------------------------------

BOOST_AUTO_TEST_SUITE(RDORealFormatTest)

BOOST_AUTO_TEST_CASE(MantissaPrecision)
{
	double value = 10e+37;
	std::stringstream stream;
	stream << boost::format("%1$.10E") % value;

	std::string str = stream.str();
	std::cout << str << std::endl;

	BOOST_CHECK(stream.str() == "1.0000000000E+038");
}

BOOST_AUTO_TEST_SUITE_END() // RDORealFormatTest
<|endoftext|>


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

#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif

#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <inttypes.h>
#include <unistd.h>

#include "font.h"
#include "cpuTrace.h"

//-------------------------------------------------------------------------

void
CCpuTrace::
getCpuStats(
    SCpuStats& cpuStats)
{
    FILE *fp = fopen("/proc/stat", "r");

    if (fp == 0)
    {
        perror("unable to open /proc/stat");
        exit(EXIT_FAILURE);
    }

    fscanf(fp, "%*s");
    fscanf(fp, "%" SCNu32, &(cpuStats.user));
    fscanf(fp, "%" SCNu32, &(cpuStats.nice));
    fscanf(fp, "%" SCNu32, &(cpuStats.system));
    fscanf(fp, "%" SCNu32, &(cpuStats.idle));
    fscanf(fp, "%" SCNu32, &(cpuStats.iowait));
    fscanf(fp, "%" SCNu32, &(cpuStats.irq));
    fscanf(fp, "%" SCNu32, &(cpuStats.softirq));
    fscanf(fp, "%" SCNu32, &(cpuStats.steal));
    fscanf(fp, "%" SCNu32, &(cpuStats.guest));
    fscanf(fp, "%" SCNu32, &(cpuStats.guest_nice));

    fclose(fp);
}

//-------------------------------------------------------------------------

void
CCpuTrace::
diffCpuStats(
    const SCpuStats& lhs,
    const SCpuStats& rhs,
    SCpuStats& result)
{
    result.user = lhs.user - rhs.user;
    result.nice = lhs.nice - rhs.nice;
    result.system = lhs.system - rhs.system;
    result.idle = lhs.idle - rhs.idle;
    result.iowait = lhs.iowait - rhs.iowait;
    result.irq = lhs.irq - rhs.irq;
    result.softirq = lhs.softirq - rhs.softirq;
    result.steal = lhs.steal - rhs.steal;
    result.guest = lhs.guest - rhs.guest;
    result.guest_nice = lhs.guest_nice - rhs.guest_nice;
}

//-------------------------------------------------------------------------

CCpuTrace::
CCpuTrace(
    int16_t width,
    int16_t traceHeight,
    int16_t yPosition,
    int16_t gridHeight)
:
    CTrace(width,
           traceHeight,
		   yPosition,
		   gridHeight,
		   3,
		   "CPU",
		   std::vector<std::string>{"user", "nice", "system"},
		   std::vector<CRGB565>{{4,90,141},{116,169,207},{241,238,246}}),
    m_traceHeight{traceHeight}
{
    getCpuStats(m_currentStats);
}

//-------------------------------------------------------------------------

void
CCpuTrace::
show(
    const CFrameBuffer565& fb,
    time_t now)
{
    SCpuStats diff;

    memcpy(&m_previousStats, &m_currentStats, sizeof(m_previousStats));

    getCpuStats(m_currentStats);

    diffCpuStats(m_currentStats, m_previousStats, diff);

    uint32_t totalCpu = diff.user
                      + diff.nice
                      + diff.system
                      + diff.idle
                      + diff.iowait
                      + diff.irq
                      + diff.softirq
                      + diff.steal
                      + diff.guest
                      + diff.guest_nice;

    int8_t user = (diff.user * m_traceHeight) / totalCpu;
    int8_t nice = (diff.nice * m_traceHeight) / totalCpu;
    int8_t system = (diff.system * m_traceHeight) / totalCpu;

	update(std::vector<int8_t>{user, nice, system}, now);

    putImage(fb);
}

<commit_msg>tabs -> 4 spaces<commit_after>//-------------------------------------------------------------------------
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Andrew Duncan
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-------------------------------------------------------------------------

#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif

#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <inttypes.h>
#include <unistd.h>

#include "font.h"
#include "cpuTrace.h"

//-------------------------------------------------------------------------

void
CCpuTrace::
getCpuStats(
    SCpuStats& cpuStats)
{
    FILE *fp = fopen("/proc/stat", "r");

    if (fp == 0)
    {
        perror("unable to open /proc/stat");
        exit(EXIT_FAILURE);
    }

    fscanf(fp, "%*s");
    fscanf(fp, "%" SCNu32, &(cpuStats.user));
    fscanf(fp, "%" SCNu32, &(cpuStats.nice));
    fscanf(fp, "%" SCNu32, &(cpuStats.system));
    fscanf(fp, "%" SCNu32, &(cpuStats.idle));
    fscanf(fp, "%" SCNu32, &(cpuStats.iowait));
    fscanf(fp, "%" SCNu32, &(cpuStats.irq));
    fscanf(fp, "%" SCNu32, &(cpuStats.softirq));
    fscanf(fp, "%" SCNu32, &(cpuStats.steal));
    fscanf(fp, "%" SCNu32, &(cpuStats.guest));
    fscanf(fp, "%" SCNu32, &(cpuStats.guest_nice));

    fclose(fp);
}

//-------------------------------------------------------------------------

void
CCpuTrace::
diffCpuStats(
    const SCpuStats& lhs,
    const SCpuStats& rhs,
    SCpuStats& result)
{
    result.user = lhs.user - rhs.user;
    result.nice = lhs.nice - rhs.nice;
    result.system = lhs.system - rhs.system;
    result.idle = lhs.idle - rhs.idle;
    result.iowait = lhs.iowait - rhs.iowait;
    result.irq = lhs.irq - rhs.irq;
    result.softirq = lhs.softirq - rhs.softirq;
    result.steal = lhs.steal - rhs.steal;
    result.guest = lhs.guest - rhs.guest;
    result.guest_nice = lhs.guest_nice - rhs.guest_nice;
}

//-------------------------------------------------------------------------

CCpuTrace::
CCpuTrace(
    int16_t width,
    int16_t traceHeight,
    int16_t yPosition,
    int16_t gridHeight)
:
    CTrace(width,
           traceHeight,
           yPosition,
           gridHeight,
           3,
           "CPU",
           std::vector<std::string>{"user", "nice", "system"},
           std::vector<CRGB565>{{4,90,141},{116,169,207},{241,238,246}}),
    m_traceHeight{traceHeight}
{
    getCpuStats(m_currentStats);
}

//-------------------------------------------------------------------------

void
CCpuTrace::
show(
    const CFrameBuffer565& fb,
    time_t now)
{
    SCpuStats diff;

    memcpy(&m_previousStats, &m_currentStats, sizeof(m_previousStats));

    getCpuStats(m_currentStats);

    diffCpuStats(m_currentStats, m_previousStats, diff);

    uint32_t totalCpu = diff.user
                      + diff.nice
                      + diff.system
                      + diff.idle
                      + diff.iowait
                      + diff.irq
                      + diff.softirq
                      + diff.steal
                      + diff.guest
                      + diff.guest_nice;

    int8_t user = (diff.user * m_traceHeight) / totalCpu;
    int8_t nice = (diff.nice * m_traceHeight) / totalCpu;
    int8_t system = (diff.system * m_traceHeight) / totalCpu;

    update(std::vector<int8_t>{user, nice, system}, now);

    putImage(fb);
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: CustomAnimationCreateDialog.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: kz $ $Date: 2008-04-02 09:43:49 $
 *
 *  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 _SD_CUSTOMANIMATIONCREATEDIALOG_HXX
#define _SD_CUSTOMANIMATIONCREATEDIALOG_HXX

#ifndef _SD_CUSTOMANIMATIONPRESET_HXX
#include "CustomAnimationPreset.hxx"
#endif

#ifndef _SV_TABDLG_HXX
#include <vcl/tabdlg.hxx>
#endif

enum PathKind { NONE, CURVE, POLYGON, FREEFORM };

class TabControl;
class OKButton;
class CancelButton;
class HelpButton;

namespace sd {

// --------------------------------------------------------------------

class CustomAnimationCreateTabPage;
class CustomAnimationPane;

class CustomAnimationCreateDialog : public TabDialog
{
    friend class CustomAnimationCreateTabPage;
public:
    CustomAnimationCreateDialog( ::Window* pParent, CustomAnimationPane* pPane, const std::vector< ::com::sun::star::uno::Any >& rTargets, bool bHasText, const ::rtl::OUString& rsPresetId, double fDuration );
    ~CustomAnimationCreateDialog();

    PathKind getCreatePathKind() const;
    CustomAnimationPresetPtr getSelectedPreset() const;
    double getSelectedDuration() const;

private:
    CustomAnimationCreateTabPage* getCurrentPage() const;
    void preview( const CustomAnimationPresetPtr& pPreset ) const;
    void setPosition();
    void storePosition();

    DECL_LINK( implActivatePagekHdl, Control* );
    DECL_LINK( implDeactivatePagekHdl, Control* );

private:
    CustomAnimationPane* mpPane;
    const std::vector< ::com::sun::star::uno::Any >& mrTargets;

    double mfDuration;
    bool mbIsPreview;

    TabControl* mpTabControl;
    OKButton* mpOKButton;
    CancelButton* mpCancelButton;
    HelpButton* mpHelpButton;

    CustomAnimationCreateTabPage* mpTabPages[4];
};

}

#endif // _SD_CUSTOMANIMATIONCREATEDIALOG_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.7.166); FILE MERGED 2008/04/01 15:34:09 thb 1.7.166.3: #i85898# Stripping all external header guards 2008/04/01 12:38:35 thb 1.7.166.2: #i85898# Stripping all external header guards 2008/03/31 13:56:55 rt 1.7.166.1: #i87441# Change license header to LPGL v3.<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: CustomAnimationCreateDialog.hxx,v $
 * $Revision: 1.9 $
 *
 * 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.
 *
 ************************************************************************/

#ifndef _SD_CUSTOMANIMATIONCREATEDIALOG_HXX
#define _SD_CUSTOMANIMATIONCREATEDIALOG_HXX

#include "CustomAnimationPreset.hxx"
#include <vcl/tabdlg.hxx>

enum PathKind { NONE, CURVE, POLYGON, FREEFORM };

class TabControl;
class OKButton;
class CancelButton;
class HelpButton;

namespace sd {

// --------------------------------------------------------------------

class CustomAnimationCreateTabPage;
class CustomAnimationPane;

class CustomAnimationCreateDialog : public TabDialog
{
    friend class CustomAnimationCreateTabPage;
public:
    CustomAnimationCreateDialog( ::Window* pParent, CustomAnimationPane* pPane, const std::vector< ::com::sun::star::uno::Any >& rTargets, bool bHasText, const ::rtl::OUString& rsPresetId, double fDuration );
    ~CustomAnimationCreateDialog();

    PathKind getCreatePathKind() const;
    CustomAnimationPresetPtr getSelectedPreset() const;
    double getSelectedDuration() const;

private:
    CustomAnimationCreateTabPage* getCurrentPage() const;
    void preview( const CustomAnimationPresetPtr& pPreset ) const;
    void setPosition();
    void storePosition();

    DECL_LINK( implActivatePagekHdl, Control* );
    DECL_LINK( implDeactivatePagekHdl, Control* );

private:
    CustomAnimationPane* mpPane;
    const std::vector< ::com::sun::star::uno::Any >& mrTargets;

    double mfDuration;
    bool mbIsPreview;

    TabControl* mpTabControl;
    OKButton* mpOKButton;
    CancelButton* mpCancelButton;
    HelpButton* mpHelpButton;

    CustomAnimationCreateTabPage* mpTabPages[4];
};

}

#endif // _SD_CUSTOMANIMATIONCREATEDIALOG_HXX
<|endoftext|>