diff --git a/CMakeLists.txt b/CMakeLists.txt index 2fd7aed..4e60958 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -33,6 +33,8 @@ if (NOT DEFINED OPENTURNS_PYTHON_MODULE_PATH) set (OPENTURNS_PYTHON_MODULE_PATH ${OPENTURNS_PYTHON3_MODULE_PATH}) endif () +find_package (Mixmod REQUIRED) + if (NOT BUILD_SHARED_LIBS) list ( APPEND OTMIXMOD_DEFINITIONS "-DOTMIXMOD_STATIC" ) endif () diff --git a/ChangeLog b/ChangeLog index 8a97c5b..fab1bbd 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ += 0.16 release (in-progress) + +- Depend on mixmod library (https://github.com/mixmod) +- Removed MixtureClassifierFactory + = 0.15 release (2023-11-15) * Maintenance release diff --git a/cmake/FindMixmod.cmake b/cmake/FindMixmod.cmake new file mode 100644 index 0000000..02c1e14 --- /dev/null +++ b/cmake/FindMixmod.cmake @@ -0,0 +1,87 @@ +# - Find Mixmod +# Classification with Mixture Modelling +# available at https://github.com/mixmod +# +# The module defines the following variables: +# MIXMOD_FOUND - the system has LibSVM +# MIXMOD_INCLUDE_DIR - where to find svm.h +# MIXMOD_INCLUDE_DIRS - libsvm includes +# MIXMOD_LIBRARY - where to find the LibSVM library +# MIXMOD_LIBRARIES - aditional libraries +# MIXMOD_MAJOR_VERSION - major version +# MIXMOD_MINOR_VERSION - minor version +# MIXMOD_VERSION_STRING - version (ex. 2.9.0) +# MIXMOD_ROOT_DIR - root dir (ex. /usr/local) + +#============================================================================= +# Copyright 2010-2023, Julien Schueller +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# 2. 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. +# +# 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 OWNER 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. + +# The views and conclusions contained in the software and documentation are those +# of the authors and should not be interpreted as representing official policies, +# either expressed or implied, of the FreeBSD Project. +#============================================================================= + +# set MIXMOD_INCLUDE_DIR +find_path (MIXMOD_INCLUDE_DIR + NAMES + mixmod.h +) + + +# set MIXMOD_INCLUDE_DIRS +set (MIXMOD_INCLUDE_DIRS ${MIXMOD_INCLUDE_DIR}) + +# set MIXMOD_LIBRARY +find_library (MIXMOD_LIBRARY + NAMES + mixmod + DOC + "Mixmod library location" +) + +# set MIXMOD_LIBRARIES +set (MIXMOD_LIBRARIES ${MIXMOD_LIBRARY}) + + + +# try to guess root dir from include dir +if (MIXMOD_INCLUDE_DIR) + string (REGEX REPLACE "(.*)/include.*" "\\1" MIXMOD_ROOT_DIR ${MIXMOD_INCLUDE_DIR}) +# try to guess root dir from library dir +elseif (MIXMOD_LIBRARY) + string (REGEX REPLACE "(.*)/lib[/|32|64].*" "\\1" MIXMOD_ROOT_DIR ${MIXMOD_LIBRARY}) +endif () + + +# handle REQUIRED and QUIET options +include (FindPackageHandleStandardArgs) +find_package_handle_standard_args (Mixmod REQUIRED_VARS MIXMOD_LIBRARY MIXMOD_INCLUDE_DIR) + +mark_as_advanced ( + MIXMOD_LIBRARY + MIXMOD_LIBRARIES + MIXMOD_INCLUDE_DIR + MIXMOD_INCLUDE_DIRS + MIXMOD_ROOT_DIR +) diff --git a/lib/src/CMakeLists.txt b/lib/src/CMakeLists.txt index e001541..50e80e5 100644 --- a/lib/src/CMakeLists.txt +++ b/lib/src/CMakeLists.txt @@ -1,12 +1,7 @@ - -add_subdirectory ( mixmod ) - ot_add_current_dir_to_include_dirs () -ot_add_source_file ( MixtureClassifierFactory.cxx ) ot_add_source_file ( MixtureFactory.cxx ) -ot_install_header_file ( MixtureClassifierFactory.hxx ) ot_install_header_file ( MixtureFactory.hxx ) include_directories ( ${INTERNAL_INCLUDE_DIRS} ) @@ -21,6 +16,10 @@ endif () set_target_properties ( otmixmod PROPERTIES VERSION ${LIB_VERSION} ) set_target_properties ( otmixmod PROPERTIES SOVERSION ${LIB_SOVERSION} ) target_link_libraries (otmixmod ${OPENTURNS_LIBRARY}) + +target_include_directories(otmixmod PRIVATE ${MIXMOD_INCLUDE_DIRS}) +target_link_libraries (otmixmod ${MIXMOD_LIBRARIES}) + set_target_properties (otmixmod PROPERTIES UNITY_BUILD OFF) # Add targets to the build-tree export set diff --git a/lib/src/MixtureClassifierFactory.cxx b/lib/src/MixtureClassifierFactory.cxx deleted file mode 100644 index 4570047..0000000 --- a/lib/src/MixtureClassifierFactory.cxx +++ /dev/null @@ -1,69 +0,0 @@ -// -*- C++ -*- -/** - * @brief Factory for MixMod distribution - * - * Copyright 2005-2018 Airbus-EDF-IMACS-Phimeca - * - * OTMixmod is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OTMixmod 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OTMixmod. If not, see . - * - */ - -#include "otmixmod/MixtureClassifierFactory.hxx" - -namespace OTMIXMOD -{ - -CLASSNAMEINIT (MixtureClassifierFactory) - -/* Default constructor */ -MixtureClassifierFactory::MixtureClassifierFactory () - : OT::Object() - , mixtureFactory_() -{ - // Nothing to do -} - -/* Parameters constructor */ -MixtureClassifierFactory::MixtureClassifierFactory (const MixtureFactory & mixtureFactory) - : OT::Object() - , mixtureFactory_(mixtureFactory) -{ - // Nothing to do -} - -/* Virtual constructor */ -MixtureClassifierFactory * MixtureClassifierFactory::clone () const -{ - return new MixtureClassifierFactory(*this); -} - -/* Build a classifier from a sample using the mixture factory */ -OT::MixtureClassifier MixtureClassifierFactory::build(const OT::Sample & sample) const -{ - return OT::MixtureClassifier(mixtureFactory_.buildAsMixture(sample)); -} - - -/* MixtureClassifier accessors */ -MixtureFactory MixtureClassifierFactory::getMixtureFactory() const -{ - return mixtureFactory_; -} - -void MixtureClassifierFactory::setMixtureFactory(const MixtureFactory & mixtureFactory) -{ - mixtureFactory_ = mixtureFactory; -} - -} // namespace OTMIXMOD diff --git a/lib/src/MixtureFactory.cxx b/lib/src/MixtureFactory.cxx index dd3d987..d677a4b 100644 --- a/lib/src/MixtureFactory.cxx +++ b/lib/src/MixtureFactory.cxx @@ -27,11 +27,17 @@ #include #include -#include "XEMGaussianData.h" -#include "XEMClusteringInput.h" -#include "XEMClusteringOutput.h" -#include "XEMClusteringMain.h" -#include "XEMGaussianEDDAParameter.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include namespace OTMIXMOD { @@ -100,33 +106,33 @@ OT::Mixture MixtureFactory::buildAsMixture(const OT::Sample & sample, for (OT::UnsignedInteger j = 0; j < dimension; ++j) matrix[i][j] = sample[i][j]; - XEMGaussianData * gaussianData = new XEMGaussianData(sampleSize, dimension, matrix); + XEM::GaussianData * gaussianData = new XEM::GaussianData(sampleSize, dimension, matrix); for (OT::UnsignedInteger i = 0; i < sampleSize; ++i) delete [] matrix[i]; delete [] matrix; // Create a Mixmod description - XEMDataDescription dataDescription(gaussianData); + XEM::DataDescription dataDescription(gaussianData); vector nbCluster; nbCluster.push_back(atomsNumber_); // Prepare Mixmod for clustering - XEMClusteringInput * clusteringInput(new XEMClusteringInput(nbCluster, dataDescription)); - XEMModelType modelType(StringToXEMModelName(covarianceModel_)); + XEM::ClusteringInput * clusteringInput(new XEM::ClusteringInput(nbCluster, dataDescription)); + XEM::ModelType modelType(XEM::StringToModelName(covarianceModel_)); clusteringInput->setModelType(&modelType, 0); clusteringInput->finalize(); // Do the computation - XEMClusteringMain clusteringMain(clusteringInput); - clusteringMain.run(); + XEM::ClusteringMain clusteringMain(clusteringInput); + clusteringMain.run(seed_); // Extract the results - XEMClusteringOutput * clusteringOutput(clusteringMain.getClusteringOutput()); + XEM::ClusteringOutput * clusteringOutput(clusteringMain.getOutput()); - XEMClusteringModelOutput * clusteringModelOutput(clusteringOutput->getClusteringModelOutput(0)); - XEMParameterDescription * paramDescription(clusteringModelOutput->getParameterDescription()); + XEM::ClusteringModelOutput * clusteringModelOutput(clusteringOutput->getClusteringModelOutput(0)); + XEM::ParameterDescription * paramDescription(clusteringModelOutput->getParameterDescription()); if (paramDescription == NULL) throw OT::InternalException(HERE) << "Error: Mixmod is unable to estimate a mixture with the given data and the current number of atoms. You may have repeated points in your data, a situation not well handled by Mixmod."; - XEMParameter * paramTmp(paramDescription->getParameter()); - XEMGaussianEDDAParameter * param = dynamic_cast< XEMGaussianEDDAParameter * >(paramTmp); + XEM::Parameter * paramTmp(paramDescription->getParameter()); + XEM::GaussianEDDAParameter *param = dynamic_cast< XEM::GaussianEDDAParameter * >(paramTmp); OT::Mixture::DistributionCollection coll(0); for (OT::UnsignedInteger i = 0; i < atomsNumber_; ++i) @@ -149,17 +155,15 @@ OT::Mixture MixtureFactory::buildAsMixture(const OT::Sample & sample, atom.setWeight(w); coll.add(atom); } - XEMLabelDescription * labelDescription(clusteringModelOutput->getLabelDescription()); + XEM::LabelDescription * labelDescription(clusteringModelOutput->getLabelDescription()); labels = OT::Indices(sampleSize); // Labels run from 1 to nbAtoms, we want indices in {0,\dots,nbAtoms-1} // getTabLabel() returns a copy of original vector, it must be destroyed explicitly int64_t * tabLabels = labelDescription->getLabel()->getTabLabel(); for (OT::UnsignedInteger i = 0; i < sampleSize; ++i) labels[i] = tabLabels[i] - 1; delete [] tabLabels; - BICLogLikelihood = OT::Point(3); - BICLogLikelihood[0] = param->getModel()->getLogLikelihood(false); - BICLogLikelihood[1] = param->getModel()->getCompletedLogLikelihood(); - BICLogLikelihood[2] = param->getModel()->getEntropy(); + + BICLogLikelihood = {clusteringModelOutput->getLikelihood()}; return OT::Mixture(coll); } @@ -182,7 +186,7 @@ OT::UnsignedInteger MixtureFactory::getAtomsNumber () const /* MixmodCovariance model accessors */ void MixtureFactory::setCovarianceModel (const OT::String covarianceModel) { - (void) StringToXEMModelName(covarianceModel); + (void) XEM::StringToModelName(covarianceModel); covarianceModel_ = covarianceModel; } @@ -209,10 +213,9 @@ MixtureFactory::SampleCollection MixtureFactory::BuildClusters(const OT::Sample } /* Mixmod PRNG state accessor */ -void MixtureFactory::setState(const OT::UnsignedInteger yState, - const OT::UnsignedInteger zState) +void MixtureFactory::setSeed(const OT::SignedInteger seed) { - setSeed(yState, zState); + seed_ = seed; } } // namespace OTMIXMOD diff --git a/lib/src/mixmod/CMakeLists.txt b/lib/src/mixmod/CMakeLists.txt deleted file mode 100644 index ce25d0c..0000000 --- a/lib/src/mixmod/CMakeLists.txt +++ /dev/null @@ -1,2 +0,0 @@ -add_subdirectory ( MIXMOD ) -add_subdirectory ( NEWMAT ) diff --git a/lib/src/mixmod/MIXMOD/CMakeLists.txt b/lib/src/mixmod/MIXMOD/CMakeLists.txt deleted file mode 100644 index 6fd6a6d..0000000 --- a/lib/src/mixmod/MIXMOD/CMakeLists.txt +++ /dev/null @@ -1,79 +0,0 @@ - -ot_add_current_dir_to_include_dirs () - -ot_add_source_file ( XEMAlgo.cpp ) -ot_add_source_file ( XEMBICCriterion.cpp ) -ot_add_source_file ( XEMBinaryData.cpp ) -ot_add_source_file ( XEMBinaryEjParameter.cpp ) -ot_add_source_file ( XEMBinaryEkjhParameter.cpp ) -ot_add_source_file ( XEMBinaryEkjParameter.cpp ) -ot_add_source_file ( XEMBinaryEkParameter.cpp ) -ot_add_source_file ( XEMBinaryEParameter.cpp ) -ot_add_source_file ( XEMBinaryParameter.cpp ) -ot_add_source_file ( XEMBinarySample.cpp ) -ot_add_source_file ( XEMCEMAlgo.cpp ) -ot_add_source_file ( XEMClusteringInput.cpp ) -ot_add_source_file ( XEMClusteringMain.cpp ) -ot_add_source_file ( XEMClusteringModelOutput.cpp ) -ot_add_source_file ( XEMClusteringOutput.cpp ) -ot_add_source_file ( XEMClusteringStrategy.cpp ) -ot_add_source_file ( XEMClusteringStrategyInit.cpp ) -ot_add_source_file ( XEMColumnDescription.cpp ) -ot_add_source_file ( XEMCondExe.cpp ) -ot_add_source_file ( XEMCriterion.cpp ) -ot_add_source_file ( XEMCriterionOutput.cpp ) -ot_add_source_file ( XEMCVCriterion.cpp ) -ot_add_source_file ( XEMData.cpp ) -ot_add_source_file ( XEMDataDescription.cpp ) -ot_add_source_file ( XEMDCVCriterion.cpp ) -ot_add_source_file ( XEMDescription.cpp ) -ot_add_source_file ( XEMDiagMatrix.cpp ) -ot_add_source_file ( XEMEMAlgo.cpp ) -ot_add_source_file ( XEMError.cpp ) -ot_add_source_file ( XEMEstimation.cpp ) -ot_add_source_file ( XEMGaussianData.cpp ) -ot_add_source_file ( XEMGaussianDiagParameter.cpp ) -ot_add_source_file ( XEMGaussianEDDAParameter.cpp ) -ot_add_source_file ( XEMGaussianGeneralParameter.cpp ) -ot_add_source_file ( XEMGaussianHDDAParameter.cpp ) -ot_add_source_file ( XEMGaussianParameter.cpp ) -ot_add_source_file ( XEMGaussianSample.cpp ) -ot_add_source_file ( XEMGaussianSphericalParameter.cpp ) -ot_add_source_file ( XEMGeneralMatrix.cpp ) -ot_add_source_file ( XEMICLCriterion.cpp ) -ot_add_source_file ( XEMIndividualColumnDescription.cpp ) -ot_add_source_file ( XEMInputControler.cpp ) -ot_add_source_file ( XEMInput.cpp ) -ot_add_source_file ( XEMLabel.cpp ) -ot_add_source_file ( XEMLabelDescription.cpp ) -ot_add_source_file ( XEMLikelihoodOutput.cpp ) -ot_add_source_file ( XEMMain.cpp ) -ot_add_source_file ( XEMMAlgo.cpp ) -ot_add_source_file ( XEMMAPAlgo.cpp ) -ot_add_source_file ( XEMMatrix.cpp ) -ot_add_source_file ( XEMModel.cpp ) -ot_add_source_file ( XEMModelOutput.cpp ) -ot_add_source_file ( XEMModelType.cpp ) -ot_add_source_file ( XEMNECCriterion.cpp ) -ot_add_source_file ( XEMOldInput.cpp ) -ot_add_source_file ( XEMOldModelOutput.cpp ) -ot_add_source_file ( XEMOutputControler.cpp ) -ot_add_source_file ( XEMOutput.cpp ) -ot_add_source_file ( XEMParameter.cpp ) -ot_add_source_file ( XEMParameterDescription.cpp ) -ot_add_source_file ( XEMPartition.cpp ) -ot_add_source_file ( XEMProba.cpp ) -ot_add_source_file ( XEMProbaDescription.cpp ) -ot_add_source_file ( XEMProbaOutput.cpp ) -ot_add_source_file ( XEMQualitativeColumnDescription.cpp ) -ot_add_source_file ( XEMQuantitativeColumnDescription.cpp ) -ot_add_source_file ( XEMRandom.cpp ) -ot_add_source_file ( XEMSample.cpp ) -ot_add_source_file ( XEMSelection.cpp ) -ot_add_source_file ( XEMSEMAlgo.cpp ) -ot_add_source_file ( XEMSphericalMatrix.cpp ) -ot_add_source_file ( XEMStrategy.cpp ) -ot_add_source_file ( XEMStrategyInit.cpp ) -ot_add_source_file ( XEMSymmetricMatrix.cpp ) -ot_add_source_file ( XEMUtil.cpp ) -ot_add_source_file ( XEMWeightColumnDescription.cpp ) diff --git a/lib/src/mixmod/MIXMOD/XEMAlgo.cpp b/lib/src/mixmod/MIXMOD/XEMAlgo.cpp deleted file mode 100644 index c0b2522..0000000 --- a/lib/src/mixmod/MIXMOD/XEMAlgo.cpp +++ /dev/null @@ -1,203 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMAlgo.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMAlgo.h" -#include "XEMEMAlgo.h" -#include "XEMModel.h" -#include "XEMBinaryData.h" -#include "XEMGaussianParameter.h" - - -//----------- -//Constructor -//----------- -XEMAlgo::XEMAlgo(){ - _indexIteration = 0; - _algoStopName = defaultAlgoStopName; - _epsilon = defaultEpsilon; - _nbIteration = defaultNbIteration; - _xml_old = 0; - _xml = 0; -} - - -// copy constructor -XEMAlgo::XEMAlgo(const XEMAlgo & algo){ - _indexIteration = algo._indexIteration; - _algoStopName = algo._algoStopName; - _epsilon = algo._epsilon; - _nbIteration = algo._nbIteration; - _xml_old = algo._xml_old; - _xml = algo._xml; -} - - - -XEMAlgo::XEMAlgo(XEMAlgoStopName algoStopName, double espsilon, int64_t nbIteration){ - _indexIteration = 1; - _algoStopName = algoStopName; - setEpsilon(espsilon); - setNbIteration(nbIteration); - _xml_old = 0; - _xml = 0; -} - - - -//---------- -//Destructor -//---------- -XEMAlgo::~XEMAlgo(){ -} - - - -//-------------- -// continueAgain -//-------------- -/* Stopping rule for algorithm : continueAgain */ -bool XEMAlgo::continueAgain(){ - //cout<<"XEMAlgo::continueAgain"<maxNbIteration){ - result = false; - return result; - } - else{ - switch (_algoStopName){ - case NBITERATION : - result = (_indexIteration<=_nbIteration); break; - - case EPSILON : - if (_indexIteration<=3){ - result = true; - } - else { - diff = fabs(_xml - _xml_old); - result = (diff >= _epsilon); - } - break; - - case NBITERATION_EPSILON : - res1 = (_indexIteration<=_nbIteration); - if (_indexIteration<=3){ - res2 =true; - } - else { - diff = fabs(_xml - _xml_old); - res2 = (diff >= _epsilon); - }; - result = (res1 && res2); - break; - - default : result = (_indexIteration<=_nbIteration); - } - return result; - } - } -} - - - -//----------- -// ostream << -//----------- -ostream & operator << (ostream & fo, XEMAlgo & algo){ - XEMAlgoName algoName = algo.getAlgoName(); - fo<<"\t Type : "<. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMALGO_H -#define XEMALGO_H - -#include "XEMModel.h" -#include "XEMUtil.h" -#include "XEMData.h" -#include "XEMPartition.h" - - -/** - @brief Base class for Algorithm(s) - @author F Langrognet & A Echenim -*/ - -class XEMAlgo -{ - - public: - - /// Default constructor - XEMAlgo(); - - /// copy constructor - XEMAlgo(const XEMAlgo & algo); - - /// Constructor - XEMAlgo ( XEMAlgoStopName algoStopName, double epsilon, int64_t nbIteration); - - /// Destructor - virtual ~XEMAlgo(); - - /// clone - virtual XEMAlgo * clone() = 0; - - /// Run method - virtual void run(XEMModel *& model) = 0; - - - void edit(ofstream & oFile); - - virtual const XEMAlgoStopName getAlgoStopName() const; - - virtual const XEMAlgoName getAlgoName() const = 0; - - virtual void setAlgoStopName(XEMAlgoStopName algoStopName); - - virtual void setNbIteration(int64_t nbIteration); - - virtual const int64_t getNbIteration() const; - - virtual void setEpsilon(double epsilon); - - virtual const double getEpsilon() const; - - friend ostream & operator << (ostream & fo, XEMAlgo & algo); - - protected : - - - /// Type of stopping rule of the algorithm - XEMAlgoStopName _algoStopName; - - /// Number of iterations - int64_t _nbIteration; - - /// Current iteration number - int64_t _indexIteration; - - /// Value of Epsilon (default 1.e-4) - double _epsilon; - - - - /** @brief Selector - @return 1 if algorithm not reached else 0 - */ - bool continueAgain(); - - double _xml_old; - - double _xml ; - -#if SAVE_ALL_MODELS - XEMModel ** _tabModel; // aggregate -#endif - -}; - -inline void XEMAlgo::setAlgoStopName(XEMAlgoStopName algoStopName){ - _algoStopName = algoStopName; -} - -inline void XEMAlgo::setNbIteration(int64_t nbIteration){ - if (nbIterationmaxNbIteration){ - throw nbIterationTooLarge; - } - else{ - _nbIteration = nbIteration; - } -} - - -inline const int64_t XEMAlgo::getNbIteration() const{ - return _nbIteration; -} - -inline void XEMAlgo::setEpsilon(double epsilon){ - if (epsilonmaxEpsilon){ - throw epsilonTooLarge; - } - else{ - _epsilon = epsilon; - } -} - - -inline const double XEMAlgo::getEpsilon() const{ - return _epsilon; -} - -inline const XEMAlgoStopName XEMAlgo::getAlgoStopName() const{ - return _algoStopName; -} - - -// others fucntions -XEMAlgo * createDefaultClusteringAlgo(); - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMBICCriterion.cpp b/lib/src/mixmod/MIXMOD/XEMBICCriterion.cpp deleted file mode 100644 index 61874ac..0000000 --- a/lib/src/mixmod/MIXMOD/XEMBICCriterion.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMBICCriterion.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMBICCriterion.h" - - - -//----------- -//Constructor -//----------- -XEMBICCriterion::XEMBICCriterion(){ -} - - - -//---------- -//Destructor -//---------- -XEMBICCriterion::~XEMBICCriterion(){} - - - - -//--- -//run -//--- -/* Compute BIC Criterion */ -void XEMBICCriterion::run(XEMModel * model, double & value, XEMErrorType & error, bool quiet){ - - double loglikelihood; - int64_t freeParameter; - double logN; - error = noError; - try{ - loglikelihood = model->getLogLikelihood(false); // false : to not compute fik because already done - freeParameter = model->getFreeParameter(); - logN = model->getLogN(); - value = (-2*loglikelihood)+(freeParameter*logN); - } - catch (XEMErrorType & e){ - error = e; - } -} - - diff --git a/lib/src/mixmod/MIXMOD/XEMBICCriterion.h b/lib/src/mixmod/MIXMOD/XEMBICCriterion.h deleted file mode 100644 index 477693f..0000000 --- a/lib/src/mixmod/MIXMOD/XEMBICCriterion.h +++ /dev/null @@ -1,58 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMBICCriterion.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMBICCRITERION_H -#define XEMBICCRITERION_H - -#include "XEMCriterion.h" -#include "XEMModel.h" - -/** - @brief Derived class of XEMCriterion for BIC Criterion - @author F Langrognet & A Echenim -*/ - -class XEMBICCriterion : public XEMCriterion{ - - public: - - /// Default Constructor - XEMBICCriterion(); - - - /// Destructor - virtual ~XEMBICCriterion(); - - XEMCriterionName getCriterionName() const; - - /// Run method - void run(XEMModel * model, double & value, XEMErrorType & error, bool quiet=true); - -}; - -inline XEMCriterionName XEMBICCriterion::getCriterionName() const{ - return BIC; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMBinaryData.cpp b/lib/src/mixmod/MIXMOD/XEMBinaryData.cpp deleted file mode 100644 index b94e472..0000000 --- a/lib/src/mixmod/MIXMOD/XEMBinaryData.cpp +++ /dev/null @@ -1,609 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMBinaryData.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMBinaryData.h" -#include - - - -//------------ -// Constructor -//------------ -XEMBinaryData::XEMBinaryData(){ -} - - -//------------ -// Constructor -//------------ -XEMBinaryData::XEMBinaryData(const XEMBinaryData & iData):XEMData(iData){ - int64_t j; - int64_t i; - - XEMSample ** matrix = iData._matrix; - - _matrix = new XEMSample*[_nbSample]; - for (i=0; i<_nbSample; i++) - _matrix[i] = new XEMBinarySample((XEMBinarySample*)matrix[i]); - - _tabNbModality = new int64_t[_pbDimension]; - recopyTab(iData._tabNbModality,_tabNbModality,_pbDimension); - /*for (j=0; j<_pbDimension; j++) - _tabNbModality[j] = iData->_tabNbModality[j];*/ -} - - -//------------ -// Constructor -//------------ -XEMBinaryData::XEMBinaryData(int64_t nbSample, int64_t pbDimension, vector nbModality):XEMData(nbSample,pbDimension){ - int64_t j; - int64_t i; - - _matrix = new XEMSample*[_nbSample]; - for (i=0; i<_nbSample; i++){ - _matrix[i] = new XEMBinarySample(_pbDimension); - } - - _tabNbModality = new int64_t[_pbDimension]; - for (j=0; j<_pbDimension; j++){ - _tabNbModality[j] = nbModality[j]; - } - -} - - - -//------------ -// Constructor -//------------ -XEMBinaryData::XEMBinaryData(int64_t nbSample, int64_t pbDimension, vector nbModality, int64_t ** matrix):XEMData(nbSample,pbDimension){ - - int64_t j; - int64_t i; - - _matrix = new XEMSample*[_nbSample]; - for (i=0; i<_nbSample; i++){ - _matrix[i] = new XEMBinarySample(_pbDimension, matrix[i]); - } - - _tabNbModality = new int64_t[_pbDimension]; - for (j=0; j<_pbDimension; j++){ - _tabNbModality[j] = nbModality[j]; - } -} - - - -//------------ -// Constructor -//------------ -XEMBinaryData::XEMBinaryData(int64_t nbSample, int64_t pbDimension, const string & dataFileName, int64_t * tabNbModality):XEMData(nbSample,pbDimension){ - int64_t j; - int64_t i; - - _matrix = new XEMSample*[_nbSample]; - for (i=0; i<_nbSample; i++){ - _matrix[i] = new XEMBinarySample(_pbDimension); - } - - _tabNbModality = new int64_t[_pbDimension]; - for (j=0; j<_pbDimension; j++) - _tabNbModality[j] = tabNbModality[j]; - - ifstream dataFileStream(dataFileName.c_str(), ios::in); - if (! dataFileStream.is_open()){ - dataFileStream.close(); - throw wrongDataFileName; - } - input(dataFileStream); - dataFileStream.close(); - _fileNameData = dataFileName; -} - - -//------------ -// Constructor -//------------ -XEMBinaryData::XEMBinaryData(int64_t nbSample, int64_t pbDimension, int64_t * tabNbModality, double weightTotal, XEMSample **& matrix, double * weight):XEMData(nbSample,pbDimension,weightTotal,weight){ - _matrix = matrix; - _tabNbModality = new int64_t[_pbDimension]; - for( int64_t i=0; i<_pbDimension; i++){ - _tabNbModality[i] = tabNbModality[i]; - } -} - - - -//------------ -// Constructor (used in DCV context) -//------------ -// originalData contains all the data set -XEMBinaryData::XEMBinaryData(int64_t nbSample, int64_t pbDimension, XEMData * originalData, XEMCVBlock & block):XEMData(nbSample, pbDimension){ - XEMBinaryData * origData = (XEMBinaryData *)(originalData); - XEMSample ** origMatrix = origData->_matrix ; - - _tabNbModality = new int64_t[_pbDimension]; - for (int64_t j=0; j<_pbDimension; j++) - _tabNbModality[j] = origData->_tabNbModality[j]; - - _weightTotal = block._weightTotal; - _matrix = new XEMSample*[_nbSample] ; - - for (int64_t i=0; i<_nbSample; i++){ - _matrix[i] = new XEMBinarySample(pbDimension,((XEMBinarySample *)origMatrix[block._tabWeightedIndividual[i].val])->getTabValue()); - //cout<<"ind : "<>curSampleValue[j]; - - // Test data value // - if (curSampleValue[j]>_tabNbModality[j] || curSampleValue[j]<=0){ - throw wrongValueInMultinomialCase; - } - }// end j - ((XEMBinarySample*)_matrix[i])->setDataTabValue(curSampleValue); - _weight[i]=1; - } - _weightTotal = _nbSample; - - delete [] curSampleValue; - - -} - - - - -//------ -// input -//------ -void XEMBinaryData::input(const XEMDataDescription & dataDescription){ - int64_t i; - int64_t j; - int64_t * curSampleValue = new int64_t[_pbDimension]; - double tmp; - _weightTotal = 0; - - _fileNameData = dataDescription.getFileName(); - ifstream fi((_fileNameData).c_str(), ios::in); - if (! fi.is_open()){ - throw wrongDataFileName; - } - - int64_t g=0; - for (i=0; i<_nbSample; i++){ - g=0; - for(j=0; j>curSampleValue[g]; - // Test data value // - if (curSampleValue[g]>_tabNbModality[g] || curSampleValue[g]<=0){ - throw wrongValueInMultinomialCase; - } - g++; - } - else{ - if (typeid(*(dataDescription.getColumnDescription(j)))==typeid(XEMWeightColumnDescription)){ - fi>>_weight[i]; - } - else{ - if (typeid(*(dataDescription.getColumnDescription(j)))==typeid(XEMIndividualColumnDescription)){ - string stringTmp; - fi>>stringTmp; - // cout<>tmp; // on avance ! - } - } - } - }// end j - ((XEMBinarySample*)_matrix[i])->setDataTabValue(curSampleValue); - _weightTotal += _weight[i]; - } // end i - - delete [] curSampleValue; - -} - - - -//------- -// output -//------- -void XEMBinaryData:: output(ostream & fo){ - fo<<"Sample size: "<<_nbSample; - fo<<" Dimension: "<<_pbDimension; - fo<<" values : "< & correspondcenceOriginDataToReduceData, XEMPartition * knownPartition, XEMPartition * initPartition, XEMPartition *& oKnownPartition, XEMPartition *& oInitPartition){ - int64_t rOld, value; - int64_t * tabBaseMj = new int64_t[_nbSample]; - int64_t j, k, sizeTabFactor; - int64_t idxDim; - int64_t idxSample, sizeList, i; - double * weight; - //XEMSample ** data; - - correspondcenceOriginDataToReduceData.resize(_nbSample); - - // test for int64_t limit - double maxTabFactor = 1; - for (j=1; j<_pbDimension; j++){ - maxTabFactor = maxTabFactor* _tabNbModality[j-1]; - } - if (knownPartition && initPartition){ - maxTabFactor = maxTabFactor * _tabNbModality[_pbDimension-1]; - maxTabFactor = maxTabFactor * (knownPartition->_nbCluster + 1); - } - if ( (knownPartition && !initPartition) || (!knownPartition && initPartition) ){ - maxTabFactor = maxTabFactor * _tabNbModality[_pbDimension-1]; - } - if (maxTabFactor > int64_t_max){ - throw int64_t_max_error; - } - - - list listDiffIndiv; - list::iterator listIterator; - list::iterator listBegin; - list::iterator listEnd; - - // tab of multiplicator value to set sample in base mj // - //-----------------------------------------------------// - sizeTabFactor = _pbDimension; - if (knownPartition) - sizeTabFactor++; - if (initPartition) - sizeTabFactor++; - int64_t * tabFactor = new int64_t[sizeTabFactor]; - tabFactor[0] = 1; - for (j=1; j<_pbDimension; j++){ - tabFactor[j] = tabFactor[j-1]* _tabNbModality[j-1]; - //cout<<"_tabNbModality["<_nbCluster + 1); - //cout<<"tabFactor["<<_pbDimension+1<<"] : "<getDataValue(j) - 1 ) * tabFactor[j] ; - - if (knownPartition && initPartition){ - value += (knownPartition->getGroupNumber(i)+1) * tabFactor[_pbDimension]; - value += (initPartition->getGroupNumber(i)+1) * tabFactor[_pbDimension+1]; - } - if (knownPartition && !initPartition) - value += (knownPartition->getGroupNumber(i)+1) * tabFactor[_pbDimension]; - if (!knownPartition && initPartition) - value += (initPartition->getGroupNumber(i)+1) * tabFactor[_pbDimension]; - - //cout<<"value de l'indvidu "< (*listIterator)->val)) - listIterator++; - - // list empty // - if (listBegin==listEnd){ - TWeightedIndividual * elem = new TWeightedIndividual; - elem->val = value; - elem->weight = _weight[i]; - - listDiffIndiv.push_front(elem); - sizeList++; - } - - else{ - // if elemn in end of list // - if (listIterator==listEnd){ - listIterator--; - if ((*listIterator)->val==value) - (*listIterator)->weight += _weight[i]; - else{ - TWeightedIndividual * elem = new TWeightedIndividual; - elem->val = value; - elem->weight = _weight[i]; - - listDiffIndiv.push_back(elem); - sizeList++; - } - } - - // elemen in begin or in middle of list // - else{ - if ((*listIterator)->val==value) - (*listIterator)->weight += _weight[i]; - else{ - TWeightedIndividual * elem = new TWeightedIndividual; - elem->val = value; - elem->weight = _weight[i]; - - if (listIterator == listDiffIndiv.begin()) - listDiffIndiv.push_front(elem); - else - listDiffIndiv.insert(listIterator,1,elem); - - sizeList++; - } - } - } - } // end for i - - - - // Create reduce matrix with reduce weight // - //-----------------------------------------// - weight = new double[sizeList]; - XEMSample ** data = new XEMSample *[sizeList]; - idxSample = 0; - listBegin = listDiffIndiv.begin(); - listEnd = listDiffIndiv.end(); - for (listIterator = listBegin; listIterator != listEnd; listIterator++){ - - data[idxSample] = new XEMBinarySample(_pbDimension); - weight[idxSample] = (*listIterator)->weight; - - idxDim = _pbDimension-1; - rOld = (*listIterator)->val; - // knownLabel and initLabel included in computation of base Mj // - if (knownPartition && initPartition){ - rOld = rOld % tabFactor[_pbDimension+1]; - rOld = rOld % tabFactor[_pbDimension]; - } - // knownLabel or initLabel included in computation of base Mj // - if ( (knownPartition && !initPartition) || (!knownPartition && initPartition) ) - rOld = rOld % tabFactor[_pbDimension]; - - XEMBinarySample * curDataSample = (XEMBinarySample*)data[idxSample]; - while (idxDim>=0){ - curDataSample->setDataValue(idxDim,1 + rOld/tabFactor[idxDim]); - rOld = rOld % tabFactor[idxDim]; - idxDim--; - } - idxSample++; - - } - - // Set array of correspondence // - for (i=0; i<_nbSample; i++){ - listIterator = listBegin; - idxSample = 0; - while ( (listIterator != listEnd) && (tabBaseMj[i] != (*listIterator)->val)){ - listIterator++; - idxSample++; - } - correspondcenceOriginDataToReduceData[i] = idxSample; - //cout<_nbCluster; - oInitPartition = new XEMPartition(); - oInitPartition->setDimension(sizeList, nbCluster); - oInitPartition->_tabValue = new int64_t*[sizeList]; - for (i=0; i_tabValue[i] = new int64_t[nbCluster]; - } - // l'algo suivant peut �re optimis�(on fait eventuellement plusieurs fois la m�e chose) - for (i=0; i<_nbSample; i++){ - for (k=0; k_tabValue[correspondcenceOriginDataToReduceData[i]][k] = initPartition->_tabValue[i][k]; - } - //oInitLabel->_complete = true; - } - - if (knownPartition){ - nbCluster = knownPartition->_nbCluster; - oKnownPartition = new XEMPartition(); - oKnownPartition->setDimension(sizeList, nbCluster); - oKnownPartition->_tabValue = new int64_t*[sizeList]; - for (i=0; i_tabValue[i] = new int64_t[nbCluster]; - // l'algo suivant peut �re optimis�(on fait eventuellement plusieurs fois la m�e chose) - for (i=0; i<_nbSample; i++){ - for (k=0; k_tabValue[correspondcenceOriginDataToReduceData[i]][k] = knownPartition->_tabValue[i][k]; - } - //oKnownLabel->_complete = true; - } - - - - /////////////////////////////////////////////// - /*cout<val<<" "<<(*listIterator)->weight<getDataValue(j)<<" "; - } - cout<<" | "; - if (knownPartition){ - cout<getGroupNumber(i)+1; - }// 0 if unknown - cout<<" | "; - if (initPartition){ - cout<getGroupNumber(i)+1; - }// 0 if unknown - cout<<" | "; - cout<. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMBINARYDATA_H -#define XEMBINARYDATA_H - -#include "XEMUtil.h" -#include "XEMPartition.h" -#include "XEMData.h" -#include "XEMBinarySample.h" -#include "XEMOldInput.h" - - -/** - @brief Base class for Binary Data - @author F Langrognet & A Echenim -*/ - -class XEMBinaryData : public XEMData{ - - public: - - /// Default constructor - XEMBinaryData(); - - /// Constructor - XEMBinaryData(const XEMBinaryData & iData); - - /// Constructor - XEMBinaryData(int64_t nbSample, int64_t pbDimension, const string & dataFileName, int64_t * tabNbModality); - - /// Constructor - XEMBinaryData(int64_t nbSample, int64_t pbDimension, vector nbModality); - - /// Constructor - XEMBinaryData(int64_t nbSample, int64_t pbDimension, vector nbModality, int64_t ** matrix); - - /// Constructor for dataReduce - XEMBinaryData(int64_t nbSample, int64_t pbDimension, int64_t * tabNbModality, double weightTotal, XEMSample **& matrix, double * weight); - - - /// Constructor (used in DCV context) - XEMBinaryData(int64_t nbSample, int64_t pbDimension, XEMData * originalData, XEMCVBlock & block); - - /// Desctructor - virtual ~XEMBinaryData(); - - - - void input(const XEMDataDescription & dataDescription); - - /** @brief copy - @return A copy of data - */ - XEMData * clone() const; - - /** @brief Copy - @return A copy data matrix - */ - XEMSample ** cloneMatrix(); - - /** @brief Read data from binary data file - @param fi Binary Data file to read - */ - void input(ifstream & fi); - - /** @brief Write binary data in output file - @param fo Output file to write into - */ - void output(ostream & fo); - - - bool verify()const; - - /** @brief Get matrix of data Sample - @return A vector of XEMSample - */ - XEMSample ** getDataMatrix() const; - - /** @brief Get matrix of data Sample - @param idxSample Index of sample to get values - @return A vector of XEMSample - */ - int64_t * getDataTabValue(int64_t idxSample) const; - - /** @brief Get tab modality - @return A vector of number of modality - */ - int64_t * getTabNbModality() const; - - XEMData * reduceData(vector & correspondcenceOriginDataToReduceData, XEMPartition * knownPartition, XEMPartition * initPartition, XEMPartition *& oKnownPartition, XEMPartition *& oInitPartition); - - - protected : - - /// Array of modality for each dimension - int64_t * _tabNbModality; - -}; - - - -//--------------- -// inline methods -//--------------- - -inline XEMSample ** XEMBinaryData::getDataMatrix() const{ - return _matrix; -} - -inline int64_t * XEMBinaryData::getDataTabValue(int64_t idxSample) const{ - return ((XEMBinarySample*)_matrix[idxSample])->getTabValue(); -} - -inline int64_t * XEMBinaryData::getTabNbModality() const{ - return _tabNbModality; -} - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMBinaryEParameter.cpp b/lib/src/mixmod/MIXMOD/XEMBinaryEParameter.cpp deleted file mode 100644 index b3934c8..0000000 --- a/lib/src/mixmod/MIXMOD/XEMBinaryEParameter.cpp +++ /dev/null @@ -1,382 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMBinaryEParameter.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMBinaryEParameter.h" -#include "XEMBinaryData.h" -#include "XEMModel.h" - -//-------------------- -// Default constructor -//-------------------- -XEMBinaryEParameter::XEMBinaryEParameter(){ - throw wrongConstructorType; -} - - -//------------------------------- -// Constructor called by XEMModel -//------------------------------- -XEMBinaryEParameter::XEMBinaryEParameter(XEMModel * iModel, XEMModelType * iModelType, int64_t * tabNbModality):XEMBinaryParameter(iModel, iModelType, tabNbModality){ - _scatter = 0; - -} - - - -//----------------- -// copy Constructor -//----------------- -XEMBinaryEParameter::XEMBinaryEParameter(const XEMBinaryEParameter * iParameter):XEMBinaryParameter(iParameter){ - _scatter = iParameter->getScatter(); -} - - - -//--------- -// clone -//--------- -XEMParameter * XEMBinaryEParameter::clone() const{ - XEMBinaryEParameter * newParam = new XEMBinaryEParameter(this); - return(newParam); -} - - - - -//----------- -// Destructor -//----------- -XEMBinaryEParameter::~XEMBinaryEParameter(){ -} - - - - -//------------------------ -// reset to default values -//------------------------ -void XEMBinaryEParameter::reset(){ - _scatter = 0.0; - XEMBinaryParameter::reset(); -} - -//----------- -// getFreeParameter -//----------- -int64_t XEMBinaryEParameter::getFreeParameter() const{ - int64_t nbFreeParameter = 1; - if (_freeProportion){ - nbFreeParameter += _nbCluster - 1; - } - return nbFreeParameter; -} - - - -//------- -// getPdf -//------- -double XEMBinaryEParameter::getPdf(int64_t iSample, int64_t kCluster) const{ - int64_t j; - double bernPdf = 1.0; - XEMBinaryData * data = (XEMBinaryData*)_model->getData(); - XEMBinarySample * curSample = (XEMBinarySample*)data->_matrix[iSample]; - - - for (j=0; j<_pbDimension; j++){ - // iSample have major modality ?// - if ( curSample->getDataValue(j) == _tabCenter[kCluster][j] ){ - bernPdf *= 1.0 - _scatter; - } - else{ - bernPdf *= _scatter / (_tabNbModality[j] - 1.0); - } - } - return bernPdf; -} - - -//---------- -// getLogPdf -//---------- -long double XEMBinaryEParameter::getLogPdf(int64_t iSample, int64_t kCluster) const{ - int64_t j; - double bernPdf = 0.0; - XEMBinaryData * data = (XEMBinaryData*)_model->getData(); - XEMBinarySample * curSample = (XEMBinarySample*)data->_matrix[iSample]; - - - for (j=0; j<_pbDimension; j++){ - // iSample have major modality ?// - if ( curSample->getDataValue(j) == _tabCenter[kCluster][j] ){ - bernPdf += log(1.0 - _scatter); - } - else{ - bernPdf += log(_scatter / (_tabNbModality[j] - 1.0)); - } - } - return bernPdf; -} - - - -//------- -// getPdf -//------- -/* Compute normal probability density function - for x vector and kCluster th cluster -*/ -double XEMBinaryEParameter::getPdf(XEMSample * x, int64_t kCluster) const{ - int64_t j; - double bernPdf = 1.0; - XEMBinarySample * binaryX = (XEMBinarySample*) x; - - for (j=0; j<_pbDimension; j++){ - // iSample have major modality ? // - if ( binaryX->getDataValue(j) == _tabCenter[kCluster][j] ){ - bernPdf *= 1.0 - _scatter; - } - else{ - bernPdf *= _scatter / (_tabNbModality[j] - 1.0); - } - } - return bernPdf; -} - - - - -//-------------------- -// getlogLikelihoodOne (one cluster) -//-------------------- -double XEMBinaryEParameter::getLogLikelihoodOne() const{ - int64_t i; - int64_t j; - double logLikelihoodOne = 0.0, value, pdf, Scatter; - int64_t * Center = new int64_t[_pbDimension]; - double* tabNbSampleInMajorModality = new double[_pbDimension]; - int64_t nbSample = _model->getNbSample(); - XEMBinaryData * data = (XEMBinaryData*)(_model->getData()); - - // Compute Center fo One cluster // - getTabCenterIfOneCluster(Center, tabNbSampleInMajorModality); - - // Compute Scatter for One cluster // - value = 0.0; - for (j=0; j<_pbDimension; j++){ - //value += tabNbSampleInMajorModality[j]; - value += tabNbSampleInMajorModality[j] + 1./_tabNbModality[j]; - } - Scatter = 1 - ( value / ((data->_weightTotal +1 ) * _pbDimension)); - - // Compute the log-likelihood for one cluster (k=1) // - //--------------------------------------------------// - for (i=0; i_matrix[i], Center, Scatter, _tabNbModality); - logLikelihoodOne += log(pdf) * data->_weight[i]; - } - - delete[] Center; - delete[] tabNbSampleInMajorModality; - - return logLikelihoodOne; -} - - - - -//---------------- -// Compute scatter -//---------------- -void XEMBinaryEParameter::computeScatter(){ - int64_t j, k; - int64_t i; - double ** tabCik = _model->getTabCik(); - - XEMBinaryData * data = (XEMBinaryData*)(_model->getData()); - XEMSample ** dataMatrix = data->getDataMatrix(); - XEMBinarySample * curSample; - double totalWeight = data->_weightTotal; - int64_t nbSample = _model->getNbSample(); - - double e = 0.0; // nb d'individus prenant la modalit�majoritaire (pour toutes les classes, pour toutes les variables) - for (k=0; k<_nbCluster; k++){ - for (j=0; j<_pbDimension; j++){ - for (i=0; igetDataValue(j) == _tabCenter[k][j] ){ - e += (tabCik[i][k] * data->_weight[i]); - } - } // end for i - e += 1./_tabNbModality[j]; - } // end for j - } // end for k - //_scatter = 1- (e / (totalWeight *_pbDimension)); - _scatter = 1- (e / ((totalWeight + _nbCluster)*_pbDimension)); - -} - -//---------------------------------------------------- -// Compute scatter(s) as if there was only one cluster -//--------------------------------------------------- -/*void XEMBinaryEParameter::computeScatterIfOneCluster(double totalWeight, double * tabNbSampleInMajorModality, double ** tabNbSamplePerModality){ - double value = 0.0; - for (int64_t j=0; j<_pbDimension; j++){ - cout<<"tabNbSampleInMajorModality[j] : "<getScatter(); - _scatter = iScatter; -} - - - - -//--------------- -//create scatter from Scatter Ekjh -//--------------- -//on fait une moyenne -void XEMBinaryEParameter::createScatter(double *** scatter){ - _scatter = 0.0; - int64_t k,j,h; - for (k=0; k<_nbCluster; k++){ - for (j=0; j<_pbDimension; j++){ - h = _tabCenter[k][j]; - _scatter += scatter[k][j][h-1]; - } - } - _scatter /= (_nbCluster*_pbDimension); -} - - - - -//------------ -// editScatter (for debug) -//------------ -void XEMBinaryEParameter::editScatter(int64_t k){ - int64_t j,h; - for (j=0; j<_pbDimension; j++){ - for (h=1; h<=_tabNbModality[j]; h++){ - if (h == _tabCenter[k][j]){ - cout<<"\t"<<_scatter; - } - else{ - cout<<"\t"<<_scatter/(_tabNbModality[j]-1); - } - } - cout<. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMBINARYEPARAMETER_H -#define XEMBINARYEPARAMETER_H - -#include "XEMBinaryParameter.h" -/** - @author Florent LANGROGNET & Anwuli ECHENIM -*/ -class XEMBinaryEParameter : public XEMBinaryParameter{ - public: - /// Default constructor - XEMBinaryEParameter(); - - /// Constructor - // called by XEMModel - XEMBinaryEParameter(XEMModel * iModel, XEMModelType * iModelType, int64_t * tabNbModality); - - /// Constructor - XEMBinaryEParameter(const XEMBinaryEParameter * iParameter); - - /// Destructor - ~XEMBinaryEParameter(); - - /// reset to default values - virtual void reset(); - - /// clone - XEMParameter * clone() const; - - - /// selector : return scatter value - double getScatter() const; - - /// getFreeParameter - int64_t getFreeParameter() const; - - double getPdf(int64_t iSample, int64_t kCluster) const; - - long double getLogPdf(int64_t iSample, int64_t kCluster) const; - - /** Compute probability density function - for x vector and kCluster th cluster - */ - double getPdf(XEMSample * x, int64_t kCluster) const; - - /// getlogLikelihoodOne (one cluster) - double getLogLikelihoodOne() const; - - /// Compute scatter(s) - void computeScatter(); - - /// Compute random scatter(s) - void computeRandomScatter(); - - ///recopy scatter from param (used for init : USER) - void recopyScatter(XEMParameter * iParam); - - ///create Scatter from "Binary Parameter Ekjh" - void createScatter(double *** scatter); - - - /// editScatter (for debug) - void editScatter(int64_t k); - - /// editScatter - void editScatter(ofstream & oFile, int64_t k, bool text=false); - - // Read Scatter in input file - void inputScatter(ifstream & fi); - double *** scatterToArray() const; - - - private : - /// scatter - double _scatter; - -}; - - - -//--------------- -// inline methods -//--------------- - -inline double XEMBinaryEParameter::getScatter() const{ - return _scatter; -} - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMBinaryEjParameter.cpp b/lib/src/mixmod/MIXMOD/XEMBinaryEjParameter.cpp deleted file mode 100644 index 7cf76d9..0000000 --- a/lib/src/mixmod/MIXMOD/XEMBinaryEjParameter.cpp +++ /dev/null @@ -1,399 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMBinaryEjParameter.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMBinaryEjParameter.h" -#include "XEMBinaryData.h" -#include "XEMModel.h" - -//-------------------- -// Default constructor -//-------------------- -XEMBinaryEjParameter::XEMBinaryEjParameter(){ - throw wrongConstructorType; -} - - -//------------------------------- -// Constructor called by XEMModel -//------------------------------- -XEMBinaryEjParameter::XEMBinaryEjParameter(XEMModel * iModel, XEMModelType * iModelType, int64_t * tabNbModality):XEMBinaryParameter(iModel, iModelType, tabNbModality){ - _scatter = new double[_pbDimension]; - for (int64_t j=0; j<_pbDimension; j++){ - _scatter[j] = 0; - } -} - - - - -//----------------- -// copy Constructor -//----------------- -XEMBinaryEjParameter::XEMBinaryEjParameter(const XEMBinaryEjParameter * iParameter):XEMBinaryParameter(iParameter){ - _scatter = new double[_pbDimension]; - double * iScatter = iParameter->getScatter(); - for (int64_t j=0; j<_pbDimension; j++){ - _scatter[j] = iScatter[j]; - } - - -} - - -//------------------------ -// reset to default values -//------------------------ -void XEMBinaryEjParameter::reset(){ - for (int64_t j=0; j<_pbDimension; j++){ - _scatter[j] = 0; - } - XEMBinaryParameter::reset(); -} - - - -//--------- -// clone -//--------- -XEMParameter * XEMBinaryEjParameter::clone() const{ - XEMBinaryEjParameter * newParam = new XEMBinaryEjParameter(this); - return(newParam); -} - - - -//----------- -// Destructor -//----------- -XEMBinaryEjParameter::~XEMBinaryEjParameter(){ - if (_scatter){ - delete [] _scatter; - } -} - - - - -//----------- -// getFreeParameter -//----------- -int64_t XEMBinaryEjParameter::getFreeParameter() const{ - int64_t nbFreeParameter = _pbDimension; - if (_freeProportion){ - nbFreeParameter += _nbCluster - 1; - } - return nbFreeParameter; -} - - - - -//------- -// getPdf -//------- -double XEMBinaryEjParameter::getPdf(int64_t iSample, int64_t kCluster) const{ - int64_t j; - double bernPdf = 1.0; - XEMBinaryData * data = (XEMBinaryData*)_model->getData(); - XEMBinarySample * curSample = (XEMBinarySample*)data->_matrix[iSample]; - - for (j=0; j<_pbDimension; j++){ - // iSample have major modality ?// - if ( curSample->getDataValue(j) == _tabCenter[kCluster][j] ){ - bernPdf *= 1.0 - _scatter[j]; - } - else{ - bernPdf *= _scatter[j] / (_tabNbModality[j] - 1.0); - } - } - return bernPdf; -} - - - -//---------- -// getLogPdf -//---------- -long double XEMBinaryEjParameter::getLogPdf(int64_t iSample, int64_t kCluster) const{ - int64_t j; - long double bernPdf = 0.0; - XEMBinaryData * data = (XEMBinaryData*)_model->getData(); - XEMBinarySample * curSample = (XEMBinarySample*)data->_matrix[iSample]; - - for (j=0; j<_pbDimension; j++){ - // iSample have major modality ?// - if ( curSample->getDataValue(j) == _tabCenter[kCluster][j] ){ - bernPdf += log( 1.0 - _scatter[j]); - } - else{ - bernPdf += log (_scatter[j] / (_tabNbModality[j] - 1.0)); - } - } - return bernPdf; -} - - - -//------- -// getPdf -//------- -/* Compute normal probability density function - for x vector and kCluster th cluster -*/ -double XEMBinaryEjParameter::getPdf(XEMSample * x, int64_t kCluster) const{ - int64_t j; - double bernPdf = 1.0; - XEMBinarySample * binaryX = (XEMBinarySample*) x; - - for (j=0; j<_pbDimension; j++){ - // iSample have major modality ? // - if ( binaryX->getDataValue(j) == _tabCenter[kCluster][j] ){ - bernPdf *= 1.0 - _scatter[j]; - } - else{ - bernPdf *= _scatter[j] / (_tabNbModality[j] - 1.0); - } - } - return bernPdf; -} - - - - -//-------------------- -// getlogLikelihoodOne (one cluster) -//-------------------- -double XEMBinaryEjParameter::getLogLikelihoodOne() const{ - int64_t i; - int64_t j; - double logLikelihoodOne = 0.0, pdf, * Scatter; - Scatter = new double[_pbDimension]; - int64_t * Center = new int64_t[_pbDimension]; - double * tabNbSampleInMajorModality = new double[_pbDimension]; - int64_t nbSample = _model->getNbSample(); - XEMBinaryData * data = (XEMBinaryData*)(_model->getData()); - - // Compute Center fo One cluster // - getTabCenterIfOneCluster(Center, tabNbSampleInMajorModality); - - // Compute Scatter for One cluster // - for (j=0; j<_pbDimension; j++){ - //Scatter[j] = 1- (tabNbSampleInMajorModality[j] / data->_weightTotal); - Scatter[j] = 1- ((tabNbSampleInMajorModality[j] + (1./_tabNbModality[j])) / (data->_weightTotal + 1)); - } - - // Compute the log-likelihood for one cluster (k=1) // - for (i=0; i_matrix[i], Center, Scatter, _tabNbModality); - logLikelihoodOne += log(pdf) * data->_weight[i]; - } - - delete[] Center; - delete[] Scatter; - delete[] tabNbSampleInMajorModality; - - return logLikelihoodOne; -} - - - - -//---------------- -// Compute scatter -//---------------- -void XEMBinaryEjParameter::computeScatter(){ - int64_t j, k; - int64_t i; - double ej; // nb d'individus prenant la modalit�majoritaire sur la variable j - double ** tabCik = _model->getTabCik(); - - XEMBinaryData * data = (XEMBinaryData*)(_model->getData()); - XEMSample ** dataMatrix = data->getDataMatrix(); - XEMBinarySample * curSample; - double totalWeight = data->_weightTotal; - int64_t nbSample = _model->getNbSample(); - - for (j=0; j<_pbDimension; j++){ - ej = 0.0; - for (k=0; k<_nbCluster; k++){ - for (i=0; igetDataValue(j) == _tabCenter[k][j] ){ - ej += (tabCik[i][k] * data->_weight[i]); - } - } // end for i - } // end for k - //_scatter[j] = 1 - (ej / totalWeight); - _scatter[j] = 1 - ((ej + ((_nbCluster*1.)/_tabNbModality[j])) / (totalWeight + _nbCluster)); - } // end for j - - /* - Version issue directement des formules mais moins rapide : - for (j=0; j<_pbDimension; j++){ - ej = 0.0; - for (k=0; k<_nbCluster; k++){ - for (i=0; igetDataValue(j) == _tabCenter[k][j] ){ - if (tabZikKnown[i]) - ej += (tabZik[i][k] * data->_weight[i]); - else - ej += (tabTik[i][k] * data->_weight[i]); - } - } // end for i - ej += 1./_tabNbModality[j]; - } // end for k - //_scatter[j] = 1 - (ej / totalWeight); - _scatter[j] = 1 - (ej / (totalWeight + _nbCluster)); - } // end for j - */ - -} - - -//-------------------------- -// Compute random scatter(s) -//-------------------------- -void XEMBinaryEjParameter::computeRandomScatter(){ - // tirage d'une valeur comprise entre 0 et 1/_tabNbModality[j] - for (int64_t j=0; j<_pbDimension; j++){ - _scatter[j] = rnd()/_tabNbModality[j]; - } -} - - - - -//--------------- -//recopy scatter from iParam -//--------------- -// Note : iParam must be a XEMBinaryEjParameter* -void XEMBinaryEjParameter::recopyScatter(XEMParameter * iParam){ - if (typeid(*iParam) != typeid(*this)){ - throw badXEMBinaryParamterClass; - } - double * iScatter = ((XEMBinaryEjParameter*)iParam)->getScatter(); - for( int64_t j=0; j<_pbDimension; j++){ - _scatter[j] = iScatter[j]; - } -} - - - - -//--------------- -//create scatter from Scatter Ekjh -//--------------- -//on fait une moyenne -void XEMBinaryEjParameter::createScatter(double *** scatter){ - int64_t k,j,h; - for (j=0; j<_pbDimension; j++){ - _scatter[j] = 0.0; - for (k=0; k<_nbCluster; k++){ - h = _tabCenter[k][j]; - _scatter[j] += scatter[k][j][h-1]; - } - _scatter[j] /= _nbCluster; - } -} - - - - - - -//------------ -// editScatter (for debug) -//------------ -void XEMBinaryEjParameter::editScatter(int64_t k){ - int64_t j,h; - for (j=0; j<_pbDimension; j++){ - for (h=1; h<=_tabNbModality[j]; h++){ - if (h == _tabCenter[k][j]){ - cout<<"\t"<<_scatter[j]; - } - else{ - cout<<"\t"<<_scatter[j]/(_tabNbModality[j]-1); - } - } - cout<. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMBinaryEjParameter_H -#define XEMBinaryEjParameter_H - -#include "XEMBinaryParameter.h" -/** - @author Florent LANGROGNET & Anwuli ECHENIM -*/ -class XEMBinaryEjParameter : public XEMBinaryParameter{ - public: - /// Default constructor - XEMBinaryEjParameter(); - - /// Constructor - // called by XEMModel - XEMBinaryEjParameter(XEMModel * iModel, XEMModelType * iModelType, int64_t * tabNbModality); - - /// Constructor copy - XEMBinaryEjParameter(const XEMBinaryEjParameter * iParameter); - - /// Destructor - ~XEMBinaryEjParameter(); - - /// reset to default values - virtual void reset(); - - /// clone - XEMParameter * clone() const; - - /// selector : return scatter value - double * getScatter() const; - - /// getFreeParameter(); - int64_t getFreeParameter() const; - - double getPdf(int64_t iSample, int64_t kCluster) const; - - long double getLogPdf(int64_t iSample, int64_t kCluster) const; - - /** Compute normal probability density function - for x vector and kCluster th cluster - */ - double getPdf(XEMSample * x, int64_t kCluster) const; - - /// getlogLikelihoodOne (one cluster) - double getLogLikelihoodOne() const; - - /// Compute scatter(s) - void computeScatter(); - - /// Compute random scatter(s) - void computeRandomScatter(); - - ///recopy scatter from param (used for init : USER) - void recopyScatter(XEMParameter * iParam); - - ///create Scatter from "Binary Parameter Ekjh" - void createScatter(double *** scatter); - - - /// editScatter (for debug) - void editScatter(int64_t k); - - /// editScatter - void editScatter(ofstream & oFile, int64_t k, bool text=false); - - // Read Scatter in input file - void inputScatter(ifstream & fi); - - double *** scatterToArray() const; - - - private : - /// scatter - double * _scatter; - -}; - - - -//--------------- -// inline methods -//--------------- - -inline double * XEMBinaryEjParameter::getScatter() const{ - return _scatter; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMBinaryEkParameter.cpp b/lib/src/mixmod/MIXMOD/XEMBinaryEkParameter.cpp deleted file mode 100644 index 708902c..0000000 --- a/lib/src/mixmod/MIXMOD/XEMBinaryEkParameter.cpp +++ /dev/null @@ -1,389 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMBinaryEkParameter.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMBinaryEkParameter.h" -#include "XEMBinaryData.h" -#include "XEMModel.h" - -//-------------------- -// Default constructor -//-------------------- -XEMBinaryEkParameter::XEMBinaryEkParameter(){ - throw wrongConstructorType; -} - - -//------------------------------- -// Constructor called by XEMModel -//------------------------------- -XEMBinaryEkParameter::XEMBinaryEkParameter(XEMModel * iModel, XEMModelType * iModelType, int64_t * tabNbModality):XEMBinaryParameter(iModel, iModelType, tabNbModality){ - _scatter = new double[_nbCluster]; - int64_t k; - for (k=0; k<_nbCluster; k++){ - _scatter[k] = 0.0; - } - -} - - - -//----------------- -// copy Constructor -//----------------- -XEMBinaryEkParameter::XEMBinaryEkParameter(const XEMBinaryEkParameter * iParameter):XEMBinaryParameter(iParameter){ - _scatter = new double[_nbCluster]; - double * iScatter = iParameter->getScatter(); - for (int64_t k=0; k<_nbCluster; k++){ - _scatter[k] = iScatter[k]; - } - -} - - - -//--------- -// clone -//--------- -XEMParameter * XEMBinaryEkParameter::clone() const{ - XEMBinaryEkParameter * newParam = new XEMBinaryEkParameter(this); - return(newParam); -} - - - - -//----------- -// Destructor -//----------- -XEMBinaryEkParameter::~XEMBinaryEkParameter(){ - if (_scatter){ - delete [] _scatter; - } -} - - - -//------------------------ -// reset to default values -//------------------------ -void XEMBinaryEkParameter::reset(){ - int64_t k; - for (k=0; k<_nbCluster; k++){ - _scatter[k] = 0.0; - } - XEMBinaryParameter::reset(); -} - -//----------- -// getFreeParameter -//----------- -int64_t XEMBinaryEkParameter::getFreeParameter() const{ - int64_t nbFreeParameter = _nbCluster; - if (_freeProportion){ - nbFreeParameter += _nbCluster - 1; - } - return nbFreeParameter; -} - - - -//------- -// getPdf -//------- -double XEMBinaryEkParameter::getPdf(int64_t iSample, int64_t kCluster) const{ - int64_t j; - double bernPdf = 1.0; - XEMBinaryData * data = (XEMBinaryData*)_model->getData(); - XEMBinarySample * curSample = (XEMBinarySample*)data->_matrix[iSample]; - - for (j=0; j<_pbDimension; j++){ - // iSample have major modality ?// - if ( curSample->getDataValue(j) == _tabCenter[kCluster][j] ){ - bernPdf *= 1.0 - _scatter[kCluster]; - } - else{ - bernPdf *= _scatter[kCluster] / (_tabNbModality[j] - 1.0); - } - } - return bernPdf; -} - - -//---------- -// getLogPdf -//---------- -long double XEMBinaryEkParameter::getLogPdf(int64_t iSample, int64_t kCluster) const{ - int64_t j; - double bernPdf = 0.0; - XEMBinaryData * data = (XEMBinaryData*)_model->getData(); - XEMBinarySample * curSample = (XEMBinarySample*)data->_matrix[iSample]; - - for (j=0; j<_pbDimension; j++){ - // iSample have major modality ?// - if ( curSample->getDataValue(j) == _tabCenter[kCluster][j] ){ - bernPdf += log(1.0 - _scatter[kCluster]); - } - else{ - bernPdf += log(_scatter[kCluster] / (_tabNbModality[j] - 1.0)); - } - } - return bernPdf; -} - - - -//------- -// getPdf -//------- -/* Compute normal probability density function - for x vector and kCluster th cluster -*/ -double XEMBinaryEkParameter::getPdf(XEMSample * x, int64_t kCluster) const{ - int64_t j; - double bernPdf = 1.0; - XEMBinarySample * binaryX = (XEMBinarySample*) x; - - for (j=0; j<_pbDimension; j++){ - // iSample have major modality ? // - if ( binaryX->getDataValue(j) == _tabCenter[kCluster][j] ){ - bernPdf *= 1.0 - _scatter[kCluster]; - } - else{ - bernPdf *= _scatter[kCluster] / (_tabNbModality[j] - 1.0); - } - } - return bernPdf; -} - - - - - -//-------------------- -// getlogLikelihoodOne (one cluster) -//-------------------- -double XEMBinaryEkParameter::getLogLikelihoodOne() const{ - int64_t i; - int64_t j; - double logLikelihoodOne = 0.0, value, pdf, Scatter; - int64_t * Center = new int64_t[_pbDimension]; - double * tabNbSampleInMajorModality = new double[_pbDimension]; - int64_t nbSample = _model->getNbSample(); - XEMBinaryData * data = (XEMBinaryData*)(_model->getData()); - - // Compute Center fo One cluster // - getTabCenterIfOneCluster(Center, tabNbSampleInMajorModality); - - // Compute Scatter for One cluster // - value = 0.0; - for (j=0; j<_pbDimension; j++){ - //value += tabNbSampleInMajorModality[j]; - value += tabNbSampleInMajorModality[j] + 1./_tabNbModality[j]; - } - //Scatter = 1- ( value /(data->_weightTotal * _pbDimension)); - Scatter = 1- ( value / ((data->_weightTotal + 1) * _pbDimension)); - - // Compute the log-likelihood for one cluster (k=1) // - //--------------------------------------------------// - for (i=0; i_matrix[i], Center, Scatter, _tabNbModality); - logLikelihoodOne += log(pdf) * data->_weight[i]; - } - - delete[] Center; - delete[] tabNbSampleInMajorModality; - - return logLikelihoodOne; -} - - - - -//---------------- -// Compute scatter -//---------------- -void XEMBinaryEkParameter::computeScatter(){ - int64_t j, k; - int64_t i; - double ek; // nb d'individus de la classe k prenant la modalit�majoritaire (quelque soit la variable) - double * tabNk = _model->getTabNk(); - double ** tabCik = _model->getTabCik(); - - XEMBinaryData * data = (XEMBinaryData*)(_model->getData()); - XEMSample ** dataMatrix = data->getDataMatrix(); - XEMBinarySample * curSample = NULL; - int64_t nbSample = _model->getNbSample(); - - for (k=0; k<_nbCluster; k++){ - ek = 0.0; - for (j=0; j<_pbDimension; j++){ - for (i=0; igetDataValue(j) == _tabCenter[k][j] ){ - ek += (tabCik[i][k] * data->_weight[i]); - } - }// end for i - ek += 1./_tabNbModality[j]; - } // end for j - _scatter[k] = 1 - (ek / ((tabNk[k] + 1)*_pbDimension)); - //_scatter[k] = 1 - (ek / ((tabNk[k] )*_pbDimension)); - } // end for k - -} - - - -//-------------------------- -// Compute random scatter(s) -//-------------------------- -void XEMBinaryEkParameter::computeRandomScatter(){ - int64_t minNbModality = _tabNbModality[0]; - for (int64_t j=1; j<_pbDimension; j++){ - if (_tabNbModality[j] < minNbModality){ - minNbModality = _tabNbModality[j]; - } - } - - // tirage d'une valeur comprise entre 0 et 1/minNbModality - for (int64_t k=0; k<_nbCluster; k++){ - _scatter[k] = rnd()/minNbModality; - } -} - - - -//--------------- -//recopy scatter from iParam -//--------------- -// Note : iParam must be a XEMBinaryEkParameter* -void XEMBinaryEkParameter::recopyScatter(XEMParameter * iParam){ - if (typeid(*iParam) != typeid(*this)){ - throw badXEMBinaryParamterClass; - } - double * iScatter = ((XEMBinaryEkParameter*)iParam)->getScatter(); - for( int64_t k=0; k<_nbCluster; k++){ - _scatter[k] = iScatter[k]; - } -} - - - - -//--------------- -//create scatter from Scatter Ekjh -//--------------- -//on fait une moyenne -void XEMBinaryEkParameter::createScatter(double *** scatter){ - int64_t k,j,h; - for (k=0; k<_nbCluster; k++){ - _scatter[k] = 0.0; - for (j=0; j<_pbDimension; j++){ - h = _tabCenter[k][j]; - _scatter[k] += scatter[k][j][h-1]; - } - _scatter[k] /= _pbDimension; - } -} - - - - - -//------------ -// editScatter (for debug) -//------------ -void XEMBinaryEkParameter::editScatter(int64_t k){ - int64_t j,h; - for (j=0; j<_pbDimension; j++){ - for (h=1; h<=_tabNbModality[j]; h++){ - if (h == _tabCenter[k][j]){ - cout<<"\t"<<_scatter[k]; - } - else{ - cout<<"\t"<<_scatter[k]/(_tabNbModality[j]-1); - } - } - cout<. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMBinaryEkParameter_H -#define XEMBinaryEkParameter_H - -#include "XEMBinaryParameter.h" -/** - @author Florent LANGROGNET & Anwuli Echenim -*/ -class XEMBinaryEkParameter : public XEMBinaryParameter{ - public: - /// Default constructor - XEMBinaryEkParameter(); - - /// Constructor - // called by XEMModel - XEMBinaryEkParameter(XEMModel * iModel, XEMModelType * iModelType, int64_t * tabNbModality); - - /// Constructor - XEMBinaryEkParameter(const XEMBinaryEkParameter * iParameter); - - /// Destructor - ~XEMBinaryEkParameter(); - - /// reset to default values - virtual void reset(); - - /// clone - XEMParameter * clone() const; - - /// selector : return scatter value - double * getScatter() const; - - /// getFreeParameter - int64_t getFreeParameter() const; - - - double getPdf(int64_t iSample, int64_t kCluster) const; - - long double getLogPdf(int64_t iSample, int64_t kCluster) const; - - /** Compute normal probability density function - for x vector and kCluster th cluster - */ - double getPdf(XEMSample * x, int64_t kCluster) const; - - /// getlogLikelihoodOne (one cluster) - double getLogLikelihoodOne() const; - - /// Compute scatter(s) - void computeScatter(); - - /// Compute random scatter(s) - void computeRandomScatter(); - - ///recopy scatter from param (used for init : USER) - void recopyScatter(XEMParameter * iParam); - - ///create Scatter from "Binary Parameter Ekjh" - void createScatter(double *** scatter); - - - - /// editScatter (for debug) - void editScatter(int64_t k); - - /// editScatter - void editScatter(ofstream & oFile, int64_t k, bool text=false); - - // Read Scatter in input file - void inputScatter(ifstream & fi); - - double *** scatterToArray() const; - - private : - /// scatter - double * _scatter; - -}; - - - -//--------------- -// inline methods -//--------------- - -inline double * XEMBinaryEkParameter::getScatter() const{ - return _scatter; -} - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMBinaryEkjParameter.cpp b/lib/src/mixmod/MIXMOD/XEMBinaryEkjParameter.cpp deleted file mode 100644 index 4c1004a..0000000 --- a/lib/src/mixmod/MIXMOD/XEMBinaryEkjParameter.cpp +++ /dev/null @@ -1,411 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMBinaryEkjParameter.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMBinaryEkjParameter.h" -#include "XEMBinaryData.h" -#include "XEMModel.h" - -//-------------------- -// Default constructor -//-------------------- -XEMBinaryEkjParameter::XEMBinaryEkjParameter(){ - throw wrongConstructorType; -} - - -//------------------------------- -// Constructor called by XEMModel -//------------------------------- -XEMBinaryEkjParameter::XEMBinaryEkjParameter(XEMModel * iModel, XEMModelType * iModelType, int64_t * tabNbModality):XEMBinaryParameter(iModel, iModelType, tabNbModality){ - _scatter = new double*[_nbCluster]; - for (int64_t k=0; k<_nbCluster; k++){ - _scatter[k] = new double[_pbDimension]; - for (int64_t j=0; j<_pbDimension; j++){ - _scatter[k][j] = 0.0; - } - } -} - - - -//----------------- -// copy Constructor -//----------------- -XEMBinaryEkjParameter::XEMBinaryEkjParameter(const XEMBinaryEkjParameter * iParameter):XEMBinaryParameter(iParameter){ - _scatter = new double*[_nbCluster]; - for (int64_t k=0; k<_nbCluster; k++){ - _scatter[k] = new double[_pbDimension]; - } - double ** iScatter = iParameter->getScatter(); - for (int64_t k=0; k<_nbCluster; k++){ - for (int64_t j=0; j<_pbDimension; j++){ - _scatter[k][j] = iScatter[k][j]; - } - } - -} - - - -//--------- -// clone -//--------- -XEMParameter * XEMBinaryEkjParameter::clone() const{ - XEMBinaryEkjParameter * newParam = new XEMBinaryEkjParameter(this); - return(newParam); -} - - - -//----------- -// Destructor -//----------- -XEMBinaryEkjParameter::~XEMBinaryEkjParameter(){ - if (_scatter){ - for (int64_t k=0; k<_nbCluster; k++){ - delete [] _scatter[k]; - } - } - delete [] _scatter; - _scatter = NULL; -} - - - - -//------------------------ -// reset to default values -//------------------------ -void XEMBinaryEkjParameter::reset(){ - int64_t k,j; - for (k=0; k<_nbCluster; k++){ - for (j=0; j<_pbDimension; j++){ - _scatter[k][j] = 0.0; - } - } - XEMBinaryParameter::reset(); -} - - - -//----------- -// getFreeParameter -//----------- -int64_t XEMBinaryEkjParameter::getFreeParameter() const{ - int64_t nbFreeParameter = _pbDimension * _nbCluster; - if (_freeProportion){ - nbFreeParameter += _nbCluster - 1; - } - return nbFreeParameter; -} - - - - - - -//------- -// getPdf -//------- -double XEMBinaryEkjParameter::getPdf(int64_t iSample, int64_t kCluster) const{ - //cout<<" XEMBinaryEkjParameter::getPdf"<getData(); - XEMBinarySample * curSample = (XEMBinarySample*)data->_matrix[iSample]; - - for (j=0; j<_pbDimension; j++){ - //cout<<"curSample : "<getDataValue(j)<getDataValue(j) == _tabCenter[kCluster][j] ){ - bernPdf *= 1.0 - _scatter[kCluster][j]; - } - else{ - bernPdf *= _scatter[kCluster][j] / (_tabNbModality[j] - 1.0); - } - } - return bernPdf; -} - - - -//---------- -// getLogPdf -//---------- -long double XEMBinaryEkjParameter::getLogPdf(int64_t iSample, int64_t kCluster) const{ - //cout<<" XEMBinaryEkjParameter::getPdf"<getData(); - XEMBinarySample * curSample = (XEMBinarySample*)data->_matrix[iSample]; - - for (j=0; j<_pbDimension; j++){ - //cout<<"curSample : "<getDataValue(j)<getDataValue(j) == _tabCenter[kCluster][j] ){ - bernPdf += log(1.0 - _scatter[kCluster][j]); - } - else{ - bernPdf += log(_scatter[kCluster][j] / (_tabNbModality[j] - 1.0)); - } - } - return bernPdf; -} - - - -//------- -// getPdf -//------- -/* Compute normal probability density function - for x vector and kCluster th cluster -*/ -double XEMBinaryEkjParameter::getPdf(XEMSample * x, int64_t kCluster) const{ - int64_t j; - double bernPdf = 1.0; - XEMBinarySample * binaryX = (XEMBinarySample*) x; - - for (j=0; j<_pbDimension; j++){ - // iSample have major modality ? // - if ( binaryX->getDataValue(j) == _tabCenter[kCluster][j] ){ - bernPdf *= 1.0 - _scatter[kCluster][j]; - } - else{ - bernPdf *= _scatter[kCluster][j] / (_tabNbModality[j] - 1.0); - } - } - return bernPdf; -} - - - - -//-------------------- -// getlogLikelihoodOne (one cluster) -//-------------------- -double XEMBinaryEkjParameter::getLogLikelihoodOne() const{ - int64_t i; - int64_t j; - double logLikelihoodOne = 0.0, pdf, * Scatter; - Scatter = new double[_pbDimension]; - int64_t * Center = new int64_t[_pbDimension]; - double * tabNbSampleInMajorModality = new double[_pbDimension]; - int64_t nbSample = _model->getNbSample(); - XEMBinaryData * data = (XEMBinaryData*)(_model->getData()); - - // Compute Center fo One cluster // - getTabCenterIfOneCluster(Center, tabNbSampleInMajorModality); - - // Compute Scatter for One cluster // - for (j=0; j<_pbDimension; j++) - //Scatter[j] = 1- (tabNbSampleInMajorModality[j] / data->_weightTotal); - Scatter[j] = 1- ((tabNbSampleInMajorModality[j] + 1./_tabNbModality[j]) / (data->_weightTotal + 1)); - - // Compute the log-likelihood for one cluster (k=1) // - //--------------------------------------------------// - for (i=0; i_matrix[i], Center, Scatter, _tabNbModality); - logLikelihoodOne += log(pdf) * data->_weight[i]; - } - - delete[] Center; - delete[] Scatter; - delete[] tabNbSampleInMajorModality; - - return logLikelihoodOne; -} - - - - -//---------------- -// Compute scatter -//---------------- -void XEMBinaryEkjParameter::computeScatter(){ - int64_t j, k; - int64_t i; - double ekj; // nb d'individus de la classe k prenant la modalit�maj sur la variable j - double * tabNk = _model->getTabNk(); - double ** tabCik = _model->getTabCik(); - - XEMBinaryData * data = (XEMBinaryData*)(_model->getData()); - XEMSample ** dataMatrix = data->getDataMatrix(); - XEMBinarySample * curSample; - int64_t nbSample = _model->getNbSample(); - - for (k=0; k<_nbCluster; k++){ - for (j=0; j<_pbDimension; j++){ - ekj = 0.0; - for (i=0; igetDataValue(j) == _tabCenter[k][j] ){ - ekj += (tabCik[i][k] * data->_weight[i]); - } - } - //_scatter[k][j] = 1 - (ekj / tabNk[k]); - _scatter[k][j] = 1 - ((ekj + 1./_tabNbModality[j]) / (tabNk[k] + 1)); - } // end for j - } // end for k -} - - -//-------------------------------------------------- -// Compute scatter(s) as if there was only one cluster -//--------------------------------------------------- -/*void XEMBinaryEkjParameter::computeScatterIfOneCluster(double totalWeight, double * tabNbSampleInMajorModality, double ** tabNbSamplePerModality){ - for (int64_t k=0; k<_nbCluster; k++){ - for (int64_t j=0; j<_pbDimension; j++){ - _scatter[k][j] = 1 - (tabNbSampleInMajorModality[j] / totalWeight); - } - } - }*/ - - - -//-------------------------- -// Compute random scatter(s) -//-------------------------- -void XEMBinaryEkjParameter::computeRandomScatter(){ - for (int64_t k=0; k<_nbCluster; k++){ - // tirage d'une valeur comprise entre 0 et 1./_tabNbModality[j] - for (int64_t j=0; j<_pbDimension; j++){ - _scatter[k][j] = rnd()/_tabNbModality[j]; - } - } -} - - -//--------------- -//recopy scatter from iParam -//--------------- -// Note : iParam must be a XEMBinaryEkjParameter* -void XEMBinaryEkjParameter::recopyScatter(XEMParameter * iParam){ - if (typeid(*iParam) != typeid(*this)){ - throw badXEMBinaryParamterClass; - } - double ** iScatter = ((XEMBinaryEkjParameter*)iParam)->getScatter(); - for( int64_t k=0; k<_nbCluster; k++){ - for( int64_t j=0; j<_pbDimension; j++){ - _scatter[k][j] = iScatter[k][j]; - } - } -} - - - - -//--------------- -//create scatter from Scatter Ekjh -//--------------- -void XEMBinaryEkjParameter::createScatter(double *** scatter){ - int64_t k,j,h; - for (k=0; k<_nbCluster; k++){ - for (j=0; j<_pbDimension; j++){ - h = _tabCenter[k][j]; - _scatter[k][j] = scatter[k][j][h-1]; - } - } -} - - - - - -//------------ -// editScatter (for debug) -//------------ -void XEMBinaryEkjParameter::editScatter(int64_t k){ - int64_t j,h; - for (j=0; j<_pbDimension; j++){ - for (h=1; h<=_tabNbModality[j]; h++){ - if (h == _tabCenter[k][j]){ - cout<<"\t"<<_scatter[k][j]; - } - else{ - cout<<"\t"<<_scatter[k][j]/(_tabNbModality[j]-1); - } - } - cout<. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMBinaryEkjParameter_H -#define XEMBinaryEkjParameter_H - -#include "XEMBinaryParameter.h" -/** - @author Florent LANGROGNET & Anwuli Echenim -*/ -class XEMBinaryEkjParameter : public XEMBinaryParameter{ - public: - /// Default constructor - XEMBinaryEkjParameter(); - - /// Constructor - // called by XEMModel - XEMBinaryEkjParameter(XEMModel * iModel, XEMModelType * iModelType, int64_t * tabNbModality); - - /// Constructor - XEMBinaryEkjParameter(const XEMBinaryEkjParameter * iParameter); - - /// Destructor - ~XEMBinaryEkjParameter(); - - - /// reset to default values - virtual void reset(); - - /// clone - XEMParameter * clone() const; - - /// selector : return scatter value - double ** getScatter() const; - - /// getFreeParameter - int64_t getFreeParameter() const; - - - double getPdf(int64_t iSample, int64_t kCluster) const; - - long double getLogPdf(int64_t iSample, int64_t kCluster) const; - - /** Compute normal probability density function - for x vector and kCluster th cluster - */ - double getPdf(XEMSample * x, int64_t kCluster) const; - - /// getlogLikelihoodOne (one cluster) - double getLogLikelihoodOne() const; - - /// Compute scatter(s) - void computeScatter(); - - /// Compute random scatter(s) - void computeRandomScatter(); - - ///recopy scatter from param (used for init : USER) - void recopyScatter(XEMParameter * iParam); - - ///create Scatter from "Binary Parameter Ekjh" - void createScatter(double *** scatter); - - - /// editScatter (for debug) - void editScatter(int64_t k); - - /// editScatter - void editScatter(ofstream & oFile, int64_t k, bool text=false); - - // Read Scatter in input file - void inputScatter(ifstream & fi); - double *** scatterToArray() const; - - - private : - /// scatter - double ** _scatter; - -}; - - -//--------------- -// inline methods -//--------------- - -inline double ** XEMBinaryEkjParameter::getScatter() const{ - return _scatter; -} - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMBinaryEkjhParameter.cpp b/lib/src/mixmod/MIXMOD/XEMBinaryEkjhParameter.cpp deleted file mode 100644 index 802fcbb..0000000 --- a/lib/src/mixmod/MIXMOD/XEMBinaryEkjhParameter.cpp +++ /dev/null @@ -1,509 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMBinaryEkjhParameter.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org - ***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMBinaryEkjhParameter.h" -#include "XEMBinaryData.h" -#include "XEMModel.h" - -//-------------------- -// Default constructor -//-------------------- -XEMBinaryEkjhParameter::XEMBinaryEkjhParameter(){ - throw wrongConstructorType; -} - - -//------------------------------- -// Constructor called by XEMModel -//------------------------------- -XEMBinaryEkjhParameter::XEMBinaryEkjhParameter(XEMModel * iModel, XEMModelType * iModelType, int64_t * tabNbModality):XEMBinaryParameter(iModel, iModelType, tabNbModality){ - _scatter = new double**[_nbCluster]; - - int64_t k,j,h; - for (k=0; k<_nbCluster; k++){ - _scatter[k] = new double*[_pbDimension]; - for (j=0; j<_pbDimension; j++){ - _scatter[k][j] = new double[_tabNbModality[j]]; - for (h=0; h<_tabNbModality[j]; h++){ - _scatter[k][j][h] = 0.0; - } - } - } -} - - - -//----------------- -// copy Constructor -//----------------- -XEMBinaryEkjhParameter::XEMBinaryEkjhParameter(const XEMBinaryEkjhParameter * iParameter):XEMBinaryParameter(iParameter){ - int64_t k,j,h; - _scatter = new double**[_nbCluster]; - - for (k=0; k<_nbCluster; k++){ - _scatter[k] = new double*[_pbDimension]; - for (j=0; j<_pbDimension; j++){ - _scatter[k][j] = new double[_tabNbModality[j]]; - } - } - double *** iScatter = iParameter->getScatter(); - for (k=0; k<_nbCluster; k++){ - for (j=0; j<_pbDimension; j++){ - for (h=0; h<_tabNbModality[j]; h++){ - _scatter[k][j][h] = iScatter[k][j][h]; - } - } - } -} - - - - -//------------ -// Constructor -// called by XEMStrategyType if USER partition -//------------ -XEMBinaryEkjhParameter::XEMBinaryEkjhParameter(int64_t iNbCluster, int64_t iPbDimension, XEMModelType * iModelType, int64_t * tabNbModality, string & iFileName):XEMBinaryParameter(iNbCluster,iPbDimension,iModelType,tabNbModality){ - _scatter = new double**[_nbCluster]; - for (int64_t k=0; k<_nbCluster; k++){ - _scatter[k] = new double*[_pbDimension]; - for (int64_t j=0; j<_pbDimension; j++){ - _scatter[k][j] = new double[_tabNbModality[j]]; - } - } - - if (iFileName.compare("") != 0){ - ifstream paramFile(iFileName.c_str(), ios::in); - if (! paramFile.is_open()){ - throw wrongParamFileName; - } - input(paramFile); - paramFile.close(); - } - -} - - -//--------- -// clone -//--------- -XEMParameter * XEMBinaryEkjhParameter::clone() const{ - XEMBinaryEkjhParameter * newParam = new XEMBinaryEkjhParameter(this); - return(newParam); -} - - - - -//----------- -// Destructor -//----------- -XEMBinaryEkjhParameter::~XEMBinaryEkjhParameter(){ - if (_scatter){ - for (int64_t k=0; k<_nbCluster; k++){ - for (int64_t j=0; j<_pbDimension; j++){ - delete [] _scatter[k][j]; - } - delete [] _scatter[k]; - } - delete [] _scatter; - } - _scatter = NULL; -} - - -//------------------------ -// reset to default values -//------------------------ -void XEMBinaryEkjhParameter::reset(){ - int64_t k,j,h; - for (k=0; k<_nbCluster; k++){ - for (j=0; j<_pbDimension; j++){ - for (h=0; h<_tabNbModality[j]; h++){ - _scatter[k][j][h] = 0.0; - } - } - } - XEMBinaryParameter::reset(); -} - - -//----------- -// getFreeParameter -//----------- -int64_t XEMBinaryEkjhParameter::getFreeParameter() const{ - int64_t nbFreeParameter = 0; - for (int64_t j=0; j<_pbDimension; j++){ - nbFreeParameter += _tabNbModality[j] - 1; - } - nbFreeParameter *= _nbCluster; - if (_freeProportion){ - nbFreeParameter += _nbCluster - 1; - } - return nbFreeParameter; -} - - - - -//------- -// getPdf -//------- -double XEMBinaryEkjhParameter::getPdf(int64_t iSample, int64_t kCluster) const{ - int64_t j; - double bernPdf = 1.0; - XEMBinaryData * data = (XEMBinaryData*)_model->getData(); - XEMBinarySample * curSample = (XEMBinarySample*)data->_matrix[iSample]; - int64_t value; - - for (j=0; j<_pbDimension; j++){ - // iSample have major modality ?// - value = curSample->getDataValue(j); - if ( value == _tabCenter[kCluster][j] ){ - bernPdf *= 1.0 - _scatter[kCluster][j][value-1]; - } - else{ - bernPdf *= _scatter[kCluster][j][value-1]; - } - } - return bernPdf; -} - - - -//---------- -// getLogPdf -//---------- -long double XEMBinaryEkjhParameter::getLogPdf(int64_t iSample, int64_t kCluster) const{ - int64_t j; - double bernPdf = 0.0; - XEMBinaryData * data = (XEMBinaryData*)_model->getData(); - XEMBinarySample * curSample = (XEMBinarySample*)data->_matrix[iSample]; - int64_t value; - - for (j=0; j<_pbDimension; j++){ - // iSample have major modality ?// - value = curSample->getDataValue(j); - if ( value == _tabCenter[kCluster][j] ){ - bernPdf += log(1.0 - _scatter[kCluster][j][value-1]); - } - else{ - bernPdf += log(_scatter[kCluster][j][value-1]); - } - } - return bernPdf; -} - - - -//------- -// getPdf -//------- -/* Compute normal probability density function - for x vector and kCluster th cluster - */ -double XEMBinaryEkjhParameter::getPdf(XEMSample * x, int64_t kCluster) const{ - int64_t j; - double bernPdf = 1.0; - XEMBinarySample * binaryX = (XEMBinarySample*) x; - int64_t value; - - for (j=0; j<_pbDimension; j++){ - value = binaryX->getDataValue(j) ; - // iSample have major modality ? // - if ( value == _tabCenter[kCluster][j] ){ - bernPdf *= 1.0 - _scatter[kCluster][j][value-1]; - } - else{ - bernPdf *= _scatter[kCluster][j][value-1]; - } - } - return bernPdf; -} - - - - -//-------------------- -// getlogLikelihoodOne (one cluster) -//-------------------- -double XEMBinaryEkjhParameter::getLogLikelihoodOne() const{ - int64_t i; - int64_t j, h; - double logLikelihoodOne = 0.0, pdf, ** Scatter; - Scatter = new double*[_pbDimension]; - for (j=0; j<_pbDimension; j++){ - Scatter[j] = new double[_tabNbModality[j]]; - } - int64_t * Center = new int64_t[_pbDimension]; - double * tabNbSampleInMajorModality = new double [_pbDimension]; - double ** tabNbSamplePerModality = new double * [_pbDimension]; - for (j=0; j<_pbDimension; j++){ - tabNbSamplePerModality[j] = new double[_tabNbModality[j]]; - } - int64_t nbSample = _model->getNbSample(); - XEMBinaryData * data = (XEMBinaryData*)(_model->getData()); - - // Compute Center fo One cluster // - getTabCenterIfOneCluster(Center, tabNbSampleInMajorModality, tabNbSamplePerModality); - - - // Compute Scatter for One cluster // - for (j=0; j<_pbDimension; j++){ - for (h=0; h<_tabNbModality[j]; h++){ - if (h+1 == Center[j]){ - //Scatter[j][h] = 1 - (tabNbSampleInMajorModality[j] / data->_weightTotal); - Scatter[j][h] = 1 - (tabNbSampleInMajorModality[j] + (1./_tabNbModality[j]) ) / (data->_weightTotal + 1); - } - else{ - //Scatter[j][h] = tabNbSamplePerModality[j][h] / data->_weightTotal; - Scatter[j][h] = (tabNbSamplePerModality[j][h]+ (1./_tabNbModality[j])) / (data->_weightTotal + 1); - } - } - } - - // Compute the log-likelihood for one cluster (k=1) // - //--------------------------------------------------// - for (i=0; i_matrix[i], Center, Scatter, _tabNbModality); - logLikelihoodOne += log(pdf) * data->_weight[i]; - } - - delete[] Center; - for (j=0; j<_pbDimension; j++){ - delete[] Scatter[j]; - } - delete [] Scatter; - for (j=0; j<_pbDimension; j++){ - delete[] tabNbSamplePerModality[j]; - } - delete[] tabNbSamplePerModality; - delete[] tabNbSampleInMajorModality; - - return logLikelihoodOne; -} - - - -//---------------- -// Compute scatter -//---------------- - -void XEMBinaryEkjhParameter::computeScatter(){ - int64_t j, k, h; - int64_t i; - double valueScatter; - double * tabNk = _model->getTabNk(); - double ** tabCik = _model->getTabCik(); - - XEMBinaryData * data = (XEMBinaryData*)(_model->getData()); - XEMSample ** dataMatrix = data->getDataMatrix(); - XEMBinarySample * curSample; - int64_t nbSample = _model->getNbSample(); - int64_t value; - - for (k=0; k<_nbCluster; k++){ - for (j=0; j<_pbDimension; j++){ - for (h=0; h<_tabNbModality[j]; h++){ - valueScatter = 0.0; - for (i=0; igetDataValue(j); - if ( value == h+1 ){ - valueScatter += (tabCik[i][k] * data->_weight[i]); - } - } - if (h+1 == _tabCenter[k][j]){ - //_scatter[k][j][h] = (tabNk[k] - valueScatter) / tabNk[k]; - _scatter[k][j][h] = 1 -(( valueScatter+ 1./_tabNbModality[j]) / (tabNk[k] + 1)); - } - else{ - //_scatter[k][j][h] = valueScatter / tabNk[k]; - _scatter[k][j][h] = (valueScatter + 1./_tabNbModality[j]) / (tabNk[k] + 1); - } - }// end for h - } // end for j - } // end for k - -} - - - -//-------------------------- -// Compute random scatter(s) -//-------------------------- -void XEMBinaryEkjhParameter::computeRandomScatter(){ - for (int64_t k=0; k<_nbCluster; k++){ - for (int64_t j=0; j<_pbDimension; j++){ - double scatterKJOnMajorModality = rnd() / _tabNbModality[j]; - for (int64_t h=0; h<_tabNbModality[j]; h++){ - if (h+1 == _tabCenter[k][j]){// on est sur le centre - _scatter[k][j][h] = scatterKJOnMajorModality; - } - else{ - _scatter[k][j][h] = scatterKJOnMajorModality / (_tabNbModality[j]-1); - } - } - } - } -} - - - -//--------------- -//recopy scatter from iParam -//--------------- -// Note : iParam must be a XEMBinaryEkjhParameter* -void XEMBinaryEkjhParameter::recopyScatter(XEMParameter * iParam){ - if (typeid(*iParam) != typeid(*this)){ - throw badXEMBinaryParamterClass; - } - double *** iScatter = ((XEMBinaryEkjhParameter*)iParam)->getScatter(); - int64_t k,j,h; - for(k=0; k<_nbCluster; k++){ - for (j=0; j<_pbDimension; j++){ - for (h=0; h<_tabNbModality[j]; h++){ - _scatter[k][j][h] = iScatter[k][j][h]; - } - } - } -} - - -//--------------- -//create scatter from Scatter Ekjh -//--------------- -//on fait une moyenne -void XEMBinaryEkjhParameter::createScatter(double *** scatter){ - int64_t k,j,h; - for(k=0; k<_nbCluster; k++){ - for (j=0; j<_pbDimension; j++){ - for (h=0; h<_tabNbModality[j]; h++){ - _scatter[k][j][h] = scatter[k][j][h]; - } - } - } -} - - - - - -//------------ -// editScatter (for debug) -//------------ -void XEMBinaryEkjhParameter::editScatter(int64_t k){ - int64_t j,h; - for (j=0; j<_pbDimension; j++){ - for (h=0; h<_tabNbModality[j]; h++){ - cout<<"\t"<<_scatter[k][j][h]; - } - cout<>tmp){ // retourne NULL si on est �la fin - cpt++; - } - int64_t goodValue = _nbCluster;//proportions - goodValue += _nbCluster * _pbDimension; // centers - goodValue += _nbCluster * _totalNbModality; // scatters - - if(cpt != goodValue){ - throw errorInitParameter; - } - - fi.clear(); - fi.seekg(0, ios::beg); - - for (k=0; k<_nbCluster; k++){ - // Proportions // - fi >> _tabProportion[k]; - - // Center // - for (j=0; j<_pbDimension; j++){ - fi >> _tabCenter[k][j]; - } - - // Scatter // - for (j=0; j<_pbDimension; j++){ - for (h=0; h<_tabNbModality[j]; h++){ - fi >> _scatter[k][j][h]; - } - } - } // end for k - -} - -double*** XEMBinaryEkjhParameter::scatterToArray() const{ - double *** tabScatter = new double**[_nbCluster]; - int64_t k,j,h; - for (k=0 ; k<_nbCluster;++k){ - tabScatter[k] = new double*[_pbDimension]; - for (j=0 ; j<_pbDimension ; ++j){ - tabScatter[k][j] = new double [_tabNbModality[j]]; - recopyTab(_scatter[k][j], tabScatter[k][j],_tabNbModality[j] ); - } - } - - return tabScatter; -} - - - - - diff --git a/lib/src/mixmod/MIXMOD/XEMBinaryEkjhParameter.h b/lib/src/mixmod/MIXMOD/XEMBinaryEkjhParameter.h deleted file mode 100644 index 6e18b9d..0000000 --- a/lib/src/mixmod/MIXMOD/XEMBinaryEkjhParameter.h +++ /dev/null @@ -1,115 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMBinaryEkjhParameter.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMBinaryEkjhParameter_H -#define XEMBinaryEkjhParameter_H - -#include "XEMBinaryParameter.h" -/** - @author Florent LANGROGNET & Anwuli Echenim -*/ -class XEMBinaryEkjhParameter : public XEMBinaryParameter{ - public: - /// Default constructor - XEMBinaryEkjhParameter(); - - /// Constructor - // called by XEMModel - XEMBinaryEkjhParameter(XEMModel * iModel, XEMModelType * iModelType, int64_t * tabNbModality); - - /// Constructor - // called by XEMStrategyType if USER partition - XEMBinaryEkjhParameter(int64_t iNbCluster, int64_t iPbDimension, XEMModelType * iModelType, int64_t * tabNbModality, string & iFileName); - - /// Constructor - XEMBinaryEkjhParameter(const XEMBinaryEkjhParameter * iParameter); - - /// Destructor - ~XEMBinaryEkjhParameter(); - - /// reset to default values - virtual void reset(); - - /// clone - XEMParameter * clone() const; - - /// selector : return scatter value - double *** getScatter() const; - - /// getFreeParameter - int64_t getFreeParameter() const; - - double getPdf(int64_t iSample, int64_t kCluster) const; - - long double getLogPdf(int64_t iSample, int64_t kCluster) const; - - /** Compute normal probability density function - for x vector and kCluster th cluster - */ - double getPdf(XEMSample * x, int64_t kCluster) const; - - /// getlogLikelihoodOne (one cluster) - double getLogLikelihoodOne() const; - - /// Compute scatter(s) - void computeScatter(); - - /// Compute random scatter(s) - void computeRandomScatter(); - - ///recopy scatter from param (used for init : USER) - void recopyScatter(XEMParameter * iParam); - - ///create Scatter from "Binary Parameter Ekjh" - void createScatter(double *** scatter); - - - /// editScatter (for debug) - void editScatter(int64_t k); - - /// editScatter - void editScatter(ofstream & oFile, int64_t k, bool text=false); - - // Read Scatter in input file - void inputScatter(ifstream & fi); - - double *** scatterToArray() const; - - private : - /// scatter - double *** _scatter; - -}; - - -//--------------- -// inline methods -//--------------- - -inline double *** XEMBinaryEkjhParameter::getScatter() const{ - return _scatter; -} - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMBinaryParameter.cpp b/lib/src/mixmod/MIXMOD/XEMBinaryParameter.cpp deleted file mode 100644 index cc5bc05..0000000 --- a/lib/src/mixmod/MIXMOD/XEMBinaryParameter.cpp +++ /dev/null @@ -1,731 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMBinaryParameter.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMBinaryParameter.h" -#include "XEMBinaryEkjhParameter.h" -#include "XEMBinaryData.h" -#include "XEMModel.h" -#include "XEMRandom.h" - - - - -////////////////////////////////// -// // -// constructor/destructor // -// // -////////////////////////////////// - - - -//------------ -// Constructor -//------------ -// Default constructor -XEMBinaryParameter::XEMBinaryParameter():XEMParameter(){ - throw wrongConstructorType; -} - - - -//------------ -// Constructor -//------------ -XEMBinaryParameter::XEMBinaryParameter(XEMModel * iModel, XEMModelType * iModelType, int64_t * tabNbModality):XEMParameter(iModel,iModelType){ - int64_t j, k; - - // complete scatter - // tab modality // - _tabNbModality = copyTab(tabNbModality,_pbDimension); - - // total number of modality // - _totalNbModality = 0; - for (j=0; j<_pbDimension; j++){ - _totalNbModality += _tabNbModality[j]; - } - - // Centers - _tabCenter = new int64_t*[_nbCluster]; - for (k=0; k<_nbCluster; k++){ - _tabCenter[k] = new int64_t[_pbDimension]; - for (j=0; j<_pbDimension; j++){ - _tabCenter[k][j] = 0; - } - } - - if (hasFreeProportion(iModelType->_nameModel)) { - _freeProportion = true; - } - else{ - _freeProportion = false; - } - - -} - - - -//------------ -// Constructor (if USER initialisation) -//------------ -XEMBinaryParameter::XEMBinaryParameter(int64_t iNbCluster, int64_t iPbDimension, XEMModelType * iModelType, int64_t * tabNbModality):XEMParameter(iNbCluster,iPbDimension,iModelType){ - int64_t j, k; - - // tab modality // - _tabNbModality = copyTab(tabNbModality,_pbDimension); - - // total number of modality // - _totalNbModality = 0; - for (j=0; j<_pbDimension; j++){ - _totalNbModality += _tabNbModality[j]; - } - - // Centers - _tabCenter = new int64_t*[_nbCluster]; - for (k=0; k<_nbCluster; k++){ - _tabCenter[k] = new int64_t[_pbDimension]; - for (j=0; j<_pbDimension; j++){ - _tabCenter[k][j] = 0; - } - } - - if (hasFreeProportion(iModelType->_nameModel)) { - _freeProportion = true; - } - else{ - _freeProportion = false; - } - -} - - - - - -//------------ -// Constructor -//------------ -// copy constructor -XEMBinaryParameter::XEMBinaryParameter(const XEMBinaryParameter * iParameter):XEMParameter(iParameter){ - - // tab modality // - _tabNbModality = copyTab(iParameter->getTabNbModality(), _pbDimension); - - // total number of modality // - _totalNbModality = iParameter->getTotalNbModality(); - - // Centers - _tabCenter = copyTab(iParameter->getTabCenter(), _nbCluster, _pbDimension); - -} - - - -//----------- -// Destructor -//----------- -XEMBinaryParameter::~XEMBinaryParameter(){ - int64_t k; - - if (_tabCenter){ - for (k=0; k<_nbCluster; k++){ - delete[] _tabCenter[k]; - _tabCenter[k] = NULL; - } - delete[] _tabCenter; - _tabCenter = NULL; - } - - if (_tabNbModality){ - delete[] _tabNbModality; - _tabNbModality = NULL; - } -} - -//------------------------- -// reset to default values -//------------------------ -void XEMBinaryParameter::reset(){ - int64_t k,j; - for (k=0; k<_nbCluster; k++){ - for (j=0; j<_pbDimension; j++){ - _tabCenter[k][j] = 0; - } - } - XEMParameter::reset(); -} - - - - -//------------------------------------------------------ -// getTabCenterIfOneCluster -//------------------------------------------------------ -// Compute Center for One cluster -// _tabCenter will not be changed -void XEMBinaryParameter::getTabCenterIfOneCluster(int64_t * tabCenter, double * tabNbSampleInMajorModality, double ** tabNbSamplePerModality)const{ - int64_t i; - int64_t j, h; - double max, nbSamplePerModality; - int64_t nbSample = _model->getNbSample(); - - XEMData * data = _model->getData(); - XEMSample ** dataMatrix = data->_matrix; - XEMBinarySample * curSample; - - for (j=0; j<_pbDimension; j++){ - max = 0.0; - for (h=1; h<=_tabNbModality[j]; h++){ - nbSamplePerModality = 0.0; - for(i=0; igetDataValue(j)==h) - nbSamplePerModality += data->_weight[i]; - } - // test if it is majority modality // - if (nbSamplePerModality > max){ - max = nbSamplePerModality; - tabCenter[j] = h; - } - if (tabNbSamplePerModality != NULL){ - tabNbSamplePerModality[j][h-1] = nbSamplePerModality; - } - } - tabNbSampleInMajorModality[j] = max; - } -} - - - - -////////////////////////////////// -// // -// compute method // -// // -////////////////////////////////// - -void XEMBinaryParameter::getAllPdf(double** tabFik,double* tabProportion)const{ - int64_t nbSample = _model->getNbSample(); - int64_t i; - int64_t k; - - for(i=0 ; i_tabSumF[i] pour ith sample = 0 -// i : 0 ->_nbSample-1 -//----------------------------------------- -void XEMBinaryParameter::computeTikUnderflow(int64_t i, double ** tabTik){ - throw sumFiNullInMultinomialCase; - /* - long double * lnFk = new long double[_nbCluster]; - long double * lnFkPrim = new long double[_nbCluster]; - long double * fkPrim = new long double[_nbCluster]; - double * tabTik_i = tabTik[i]; - int64_t k,k0; - long double lnFkMax, fkTPrim; - - for (k=0; k<_nbCluster; k++){ - lnFk[k] = getLogPdf(i,k); - } - - lnFkMax = lnFk[0]; - for (k=1; k<_nbCluster; k++){ - if (lnFk[k] > lnFkMax){ - lnFkMax = lnFk[k]; - } - } - - fkTPrim = 0.0; - for (k=0; k<_nbCluster; k++){ - lnFkPrim[k] = lnFk[k] - lnFkMax; - fkPrim[k] = exp(lnFkPrim[k]); - fkTPrim += fkPrim[k]; - } - - // compute tabTik - if (fkTPrim == 0){ - throw sumFiNullAndfkTPrimNull; - // reset tabTik - // initToZero(tabTik_i, _nbCluster); - // k0 = XEMGaussianParameter::computeClassAssigment(i); - // tabTik_i[k0] = 1.0; - } - else{ - for (k=0; k<_nbCluster; k++){ - tabTik_i[k] = fkPrim[k] / fkTPrim; - } - } - - delete [] lnFk; - delete [] lnFkPrim; - delete [] fkPrim;*/ - -} - - - - - -//----------------------------------------------------- -// Compute table of centers of samples for each cluster -// outputs : -// - nbInitializedCluster -// - tabInitializedCluster (array of size _nbCluster) -//----------------------------------------------------- -void XEMBinaryParameter::computeTabCenterInitUSER_PARTITION(int64_t & nbInitializedCluster, bool * tabInitializedCluster, XEMPartition * initPartition){ - int64_t j, k, h; - int64_t i; - double argMax, bestArgMax; - - double ** tabTik = _model->getTabTik(); - int64_t ** initPartitionValue = initPartition->_tabValue; - XEMBinaryData * data = (XEMBinaryData*)(_model->getData()); - XEMSample ** dataMatrix = data->getDataMatrix(); - XEMBinarySample * curSample; - int64_t * tabNbModality = data->getTabNbModality(); - int64_t nbSample = _model->getNbSample(); - - for (k=0; k<_nbCluster; k++){ - //cout<<"k = "<>_tabProportion[k]; - - // Centers // - for (j=0; j<_pbDimension; j++){ - fi>>_tabCenter[k][j]; - } - - // Scatters // - inputScatter(fi); // virtual - } -} - - - - -//------------------------------------------ -//------------------------------------------ -void XEMBinaryParameter::updateForCV(XEMModel * originalModel, XEMCVBlock & CVBlock){ - //updates tabProportion, tabCenter and tabScatter - // Mstep could be could to do that - // even if this is a few slower function versus a real update - MStep(); -} - - - -//------------------// -// Others functions // -//------------------// -// compute Pdf in case nbCluster=1 (Scatter is a scalar) -double computePdfOneCluster(XEMSample * x, int64_t * Center, double Scatter, int64_t * tabNbModality){ - double bernPdf = 1.0; - int64_t j; - int64_t pbDimension = x->getPbDimension(); - for (j=0; jgetDataValue(j)==Center[j] ) - bernPdf *= 1.0 - Scatter; - else - bernPdf *= Scatter/(tabNbModality[j]-1); - } - return bernPdf; -} - - -// compute Pdf in case nbCluster=1 (Scatter is a array of double, depends on variables) -double computePdfOneCluster(XEMSample * x, int64_t * Center, double * Scatter, int64_t * tabNbModality){ - double bernPdf = 1.0; - int64_t j; - int64_t pbDimension = x->getPbDimension(); - for (j=0; jgetDataValue(j)==Center[j] ) - bernPdf *= 1.0 - Scatter[j]; - else - bernPdf *= Scatter[j]/(tabNbModality[j]-1); - } - return bernPdf; -} - - -// compute Pdf in case nbCluster=1 (Scatter is a array of double*double, depends on variables and modalities) -double computePdfOneCluster(XEMSample * x, int64_t * Center, double ** Scatter, int64_t * tabNbModality){ - double bernPdf = 1.0; - int64_t j; - int64_t pbDimension = x->getPbDimension(); - int64_t value; - for (j=0; jgetDataValue(j); - if ( value == Center[j] ) - bernPdf *= 1.0 - Scatter[j][value-1]; - else - bernPdf *= Scatter[j][value-1]; - } - return bernPdf; -} - - - - -void XEMBinaryParameter::recopy(XEMParameter * otherParameter){ - - XEMBinaryParameter * iParameter = (XEMBinaryParameter *)otherParameter; - - // tab modality // - recopyTab(iParameter->getTabNbModality(), _tabNbModality, _pbDimension); - - // total number of modality // - _totalNbModality = iParameter->getTotalNbModality(); - - // Centers - recopyTab(iParameter->getTabCenter() , _tabCenter , _nbCluster, _pbDimension); - - // Scatters - recopyScatter(otherParameter); // virtual -} - - diff --git a/lib/src/mixmod/MIXMOD/XEMBinaryParameter.h b/lib/src/mixmod/MIXMOD/XEMBinaryParameter.h deleted file mode 100644 index 3604de5..0000000 --- a/lib/src/mixmod/MIXMOD/XEMBinaryParameter.h +++ /dev/null @@ -1,255 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMBinaryParameter.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMBinaryParameter_H -#define XEMBinaryParameter_H - -#include "XEMUtil.h" -#include "XEMRandom.h" -#include "XEMParameter.h" -#include "XEMPartition.h" - - - -/** - @brief Base class for XEMBinaryParameter(s) - @authors A. Echenim & F. Langrognet & Y. Vernaz -*/ - -class XEMBinaryParameter : public XEMParameter{ - - public : - - - //---------------------------- - // constructors / desctructors - // --------------------------- - - /// Default constructor - XEMBinaryParameter(); - - /// Constructor - // called by XEMModel (via XEMBinary...Parameter) - XEMBinaryParameter(XEMModel * iModel, XEMModelType * iModelType, int64_t * tabNbModality); - - // constructor - // called if USER initialisation - XEMBinaryParameter(int64_t iNbCluster, int64_t iPbDimension, XEMModelType * iModelType, int64_t * tabNbModality); - - /// Constructor - XEMBinaryParameter(const XEMBinaryParameter * iParameter); - - - - /// Destructor - virtual ~XEMBinaryParameter(); - - - /// reset to default values - virtual void reset(); - - /// create the same parameter than this but after updating because without xi0 - XEMParameter * createParameter(XEMModel * iModel, int64_t i0, int64_t ki0) ; - - - //---------- - // selectors - //---------- - - /// get TabCenter - int64_t ** getTabCenter() const; - - /// get _tabNbModality - int64_t * getTabNbModality() const ; - - /// get total number of modality - int64_t getTotalNbModality() const; - - //---------------- - // compute methods - //---------------- - - void getAllPdf(double ** tabFik, double * tabProportion) const; - - /** @brief Compute probability density - @param iSample Probability for sample iSample - @param kCluster Probability in class kCluster - */ - - virtual double getPdf(int64_t iSample, int64_t kCluster) const = 0; - - /** @brief Compute log probability density - @param iSample Probability for sample iSample - @param kCluster Probability in class kCluster - */ - virtual long double getLogPdf(int64_t iSample, int64_t kCluster) const = 0; - - /** Compute normal probability density function - for x vector and kCluster th cluster - */ - //double getPdf(RowVector x, int64_t kCluster); - virtual double getPdf(XEMSample * x, int64_t kCluster) const = 0; - - /// getlogLikelihoodOne (one cluster) - virtual double getLogLikelihoodOne() const = 0; - - /// compute Tik for xi (i=0 -> _nbSample-1) when underflow - virtual void computeTikUnderflow(int64_t i, double ** tabTik); - - /// Compute table of centers of the samples for each cluster - void computeTabCenter(); - - /// Compute scatter(s) - virtual void computeScatter() = 0; - - /// Compute random scatter(s) - virtual void computeRandomScatter() = 0; - - ///recopy scatter from param (used for init : USER) - virtual void recopyScatter(XEMParameter * iParam) = 0; - - - //--------------- - // initialization - //--------------- - - /// init user - void initUSER(XEMParameter * iParam); - - /// updateForInitRANDOMorUSER_PARTITION - void updateForInitRANDOMorUSER_PARTITION(XEMSample ** tabSampleForInit, bool * tabClusterToInitialize); - - /// initialize attributes before an InitRandom - void initForInitRANDOM(); - - - /// initialize attributes for init USER_PARTITION - /// outputs : - /// - nbInitializedCluster - /// - tabNotInitializedCluster (array of size _nbCluster) - void initForInitUSER_PARTITION(int64_t & nbInitializedCluster, bool * tabNotInitializedCluster, XEMPartition * initPartition); - - - /// computeTabCenterInitUSER_PARTITIONoutputs : - /// - nbInitializedCluster - /// - tabNotInitializedCluster (array of size _nbCluster) - void computeTabCenterInitUSER_PARTITION(int64_t & nbInitializedCluster, bool * tabNotInitializedCluster, XEMPartition * initPartition); - - - //----------- - // Algorithms - //----------- - - /// Maximum a posteriori step method - void MAPStep(); - - /// Expectation step method - //void EStep(); - - /// Maximization step method - void MStep(); - - - - //--------------- - // input / output - //--------------- - - // edit (for debug) - void edit(); - - /// editScatter (for debug) - virtual void editScatter(int64_t k) = 0; - - /// Edit - void edit(ofstream & oFile, bool text=false); - - /// editScatter - virtual void editScatter(ofstream & oFile, int64_t k, bool text=false) = 0; - - // Read Parameters in input file - void input(ifstream & fi); - - // Read Scatter in input file - virtual void inputScatter(ifstream & fi) = 0; - - - /// recopie sans faire construction / destruction - // utilis� par SMALL_EM, CEM_INIT, SEM ... - void recopy(XEMParameter * otherParameter); - - - ///create Scatter from "Binary Parameter Ekjh" - virtual void createScatter(double *** scatter) = 0; - - virtual double *** scatterToArray() const = 0 ; - - void updateForCV(XEMModel * originalModel, XEMCVBlock & CVBlock) ; - - - protected : - - ///compute TabCenter if there is only One Cluster - // _tabCenter will not be changed - void getTabCenterIfOneCluster(int64_t * tabCenter, double * tabNbSampleInMajorModality, double ** tabNbSamplePerModality=NULL) const; - - /// Table of centers vector of each cluster - int64_t ** _tabCenter; - - /// Table of modality - int64_t * _tabNbModality; - - /// Total number of modality - int64_t _totalNbModality; - -}; - -/// compute Pdf in case nbCluster=1 (Scatter is a scalar) -double computePdfOneCluster(XEMSample * x, int64_t * Center, double Scatter, int64_t * tabNbModality); - -/// compute Pdf in case nbCluster=1 (Scatter is a array of double, depends on variables) -double computePdfOneCluster(XEMSample * x, int64_t * Center, double * Scatter, int64_t * tabNbModality); - -/// compute Pdf in case nbCluster=1 (Scatter is a array of double*double, depends on variables and modalities) -double computePdfOneCluster(XEMSample * x, int64_t * Center, double ** Scatter, int64_t * tabNbModality); - - -//--------------- -// inline methods -//--------------- - -inline int64_t ** XEMBinaryParameter::getTabCenter() const{ - return _tabCenter; -} - -inline int64_t * XEMBinaryParameter::getTabNbModality() const{ - return _tabNbModality; -} - -inline int64_t XEMBinaryParameter::getTotalNbModality() const{ - return _totalNbModality; -} - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMBinarySample.cpp b/lib/src/mixmod/MIXMOD/XEMBinarySample.cpp deleted file mode 100644 index 837134d..0000000 --- a/lib/src/mixmod/MIXMOD/XEMBinarySample.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMBinarySample.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMBinarySample.h" - - - -//------------ -// Constructor -//------------ -XEMBinarySample::XEMBinarySample():XEMSample(){ - _value = NULL; -} - - - -//------------ -// Constructor -//------------ -XEMBinarySample::XEMBinarySample(int64_t pbDimension):XEMSample(pbDimension){ - _value = new int64_t[_pbDimension]; -} - - - -//------------ -// Constructor -//------------ -XEMBinarySample::XEMBinarySample(XEMBinarySample * iSample):XEMSample(iSample){ - _value = copyTab(iSample->_value, _pbDimension); -} - - - -//------------ -// Constructor -//------------ -XEMBinarySample::XEMBinarySample(int64_t pbDimension, int64_t * tabValue):XEMSample(pbDimension){ - _value = copyTab(tabValue, _pbDimension); -} - - - -//----------- -// Destructor -//----------- -XEMBinarySample::~XEMBinarySample(){ - if(_value){ - delete[] _value; - _value = NULL; - } -} - - - -//------------- -// set tab value -//-------------- -void XEMBinarySample::setDataTabValue(int64_t * tabValue){ - int64_t j; - for(j=0; j<_pbDimension; j++) - _value[j] = tabValue[j]; -} - - - -//---------- -// set value -//---------- -void XEMBinarySample::setDataValue(int64_t idxDim, int64_t iValue){ - _value[idxDim] = iValue; -} - - - diff --git a/lib/src/mixmod/MIXMOD/XEMBinarySample.h b/lib/src/mixmod/MIXMOD/XEMBinarySample.h deleted file mode 100644 index 4ad03ab..0000000 --- a/lib/src/mixmod/MIXMOD/XEMBinarySample.h +++ /dev/null @@ -1,92 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMBinarySample.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMBINARYSample_H -#define XEMBINARYSample_H - -#include "XEMSample.h" - - -/** - @brief Base class for Sample - @author F Langrognet & A. Echenim -*/ - -class XEMBinarySample : public XEMSample{ - - public: - - /// Constructor - XEMBinarySample(); - - /// Constructor - XEMBinarySample(int64_t pbDimension); - - /// Constructor - XEMBinarySample(XEMBinarySample * iSample); - - /// Constructor - XEMBinarySample(int64_t pbDimension, int64_t * tabValue); - - /// Destructor - virtual ~XEMBinarySample(); - - - /// Set value vector of sample - void setDataTabValue(int64_t * tabValue); - - /// Set one value of sample - void setDataValue(int64_t idxDim, int64_t iValue); - - /// get value vector of sample - int64_t * getTabValue() const; - - /// get one value of sample - int64_t getDataValue(int64_t idxDim) const; - - - protected : - - /// Vector of sample value - int64_t * _value; - - -}; - - - -//--------------- -// inline methods -//--------------- - -inline int64_t * XEMBinarySample::getTabValue() const{ - return _value; -} - - -inline int64_t XEMBinarySample::getDataValue(int64_t idxDim) const{ - return _value[idxDim]; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMCEMAlgo.cpp b/lib/src/mixmod/MIXMOD/XEMCEMAlgo.cpp deleted file mode 100644 index 8009710..0000000 --- a/lib/src/mixmod/MIXMOD/XEMCEMAlgo.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMCEMAlgo.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMCEMAlgo.h" - -//----------- -//Constructor -//----------- -XEMCEMAlgo::XEMCEMAlgo(){ -} - - -/// Copy constructor -XEMCEMAlgo::XEMCEMAlgo(const XEMCEMAlgo & cemAlgo):XEMAlgo(cemAlgo){ -} - -XEMCEMAlgo::XEMCEMAlgo(XEMAlgoStopName algoStopName, double epsilon, int64_t nbIteration) - :XEMAlgo(algoStopName, epsilon, nbIteration){ -} - - - -//---------- -//Destructor -//---------- -XEMCEMAlgo::~XEMCEMAlgo(){} - - - -// clone -//------ -XEMAlgo * XEMCEMAlgo::clone(){ - return (new XEMCEMAlgo(*this)); -} - -//--- -//run -//--- -void XEMCEMAlgo::run(XEMModel *& model){ - _indexIteration = 1; - model = model; - model->setAlgoName(CEM); - -#if DEBUG > 0 - cout<<"Debut de l'ago CEM :"<editDebugInformation(); -#endif - - while (continueAgain()){ - model->Estep(); /* E Step */ - model->Cstep(); /* C Step */ - model->Mstep(); /* M Step */ -#if DEBUG > 0 - cout<<"Apres la "<<_indexIteration<<" eme iteration de CEM :"<editDebugInformation(); -#endif - _indexIteration++; - _xml_old = _xml; - _xml = model->getCompletedLogLikelihood(); - } - - //to update tik, fik - model->Estep(); - //to compute Cik - model->Cstep(); - -} - diff --git a/lib/src/mixmod/MIXMOD/XEMCEMAlgo.h b/lib/src/mixmod/MIXMOD/XEMCEMAlgo.h deleted file mode 100644 index 687702f..0000000 --- a/lib/src/mixmod/MIXMOD/XEMCEMAlgo.h +++ /dev/null @@ -1,64 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMCEMAlgo.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMCEMALGO_H -#define XEMCEMALGO_H - -#include "XEMAlgo.h" - -/** - @brief Derived class of XEMAlgo for CEM Algorithm(s) - @author F Langrognet & A Echenim -*/ - -class XEMCEMAlgo : public XEMAlgo{ - - public: - - /// Default constructor - XEMCEMAlgo(); - - /// Copy constructor - XEMCEMAlgo(const XEMCEMAlgo & cemAlgo); - - /// Constructor - XEMCEMAlgo(XEMAlgoStopName algoStopName, double epsilon,int64_t nbIteration); - - /// Destructor - virtual ~XEMCEMAlgo(); - - /// clone - XEMAlgo * clone(); - - /// Run method - virtual void run(XEMModel *& model); - - const XEMAlgoName getAlgoName() const; -}; - -inline const XEMAlgoName XEMCEMAlgo::getAlgoName() const{ - return CEM; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMCVCriterion.cpp b/lib/src/mixmod/MIXMOD/XEMCVCriterion.cpp deleted file mode 100644 index fc3e2a7..0000000 --- a/lib/src/mixmod/MIXMOD/XEMCVCriterion.cpp +++ /dev/null @@ -1,415 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMCVCriterion.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMCVCriterion.h" -#include "XEMGaussianData.h" -#include "XEMRandom.h" -#include - - - -//------------ -// Constructor -//------------ -XEMCVCriterion::XEMCVCriterion(){ - _tabCVBlock = NULL; - _nbCVBlock = 0; - _CVinitBlocks = defaultCVinitBlocks; -} - - -//----------- -// Constructor -//------------ -XEMCVCriterion::XEMCVCriterion(XEMOldInput * input){ - //updates _CVinitBlocks and _nbCVBlocks - _CVinitBlocks = input->_CVinitBlocks; - // _nbCVBlock is initialzed to the numberOfCVBlocks that the user wanted (issued from input)(or the default value) - // this value could chane if nbSample is too small (will be done in createCVBlock) - _nbCVBlock = input->_numberOfCVBlocks; - _tabCVBlock = NULL; -} - - -//---------- -//Destructor -//---------- -XEMCVCriterion::~XEMCVCriterion(){ - - if (_tabCVBlock != NULL){ - for (int64_t v=0; v<_nbCVBlock; v++){ - delete [] _tabCVBlock[v]._tabWeightedIndividual; - } - delete [] _tabCVBlock; - } -} - - - -//--- -//run -//--- -void XEMCVCriterion::run(XEMModel * model, double & value, int64_t *& cvLabel, XEMErrorType & error,bool quiet){ - /* Compute CV (Cross Validation Criterion) */ - error = noError; - XEMModel * CVModel = new XEMModel(model); - cvLabel = new int64_t[model->getNbSample()]; - - try{ - /*cout<getParameter())->edit();*/ - double missClass = 0.0; - XEMData * data = model->getData(); - XEMSample * x; - int64_t i, known_ki, v; - - //cout<<"weight XEMCVCriterion "<editFik();*/ - CVModel->updateForCV(model, _tabCVBlock[v]); - /* cout<<"fik sur le modele modifi�:"<editFik();*/ - /*cout<<"parametre du modele modifi�:"<getParameter()->edit();*/ - - - for (int64_t ii=0; ii<_tabCVBlock[v]._nbSample; ii++){ - i = _tabCVBlock[v]._tabWeightedIndividual[ii].val; - //cout<<"individu : "<getKnownLabel(i); - x = data->_matrix[i]; - cvLabel[i] = CVModel->computeLabel(x); - if (cvLabel[i] != known_ki){ - /*cout<<"labels differents dans CV pour l'individu : "<_weightTotal; - } - catch(XEMErrorType & e){ - error = e; - delete CVModel; - delete [] cvLabel; - } -} - - - -//------------------- -//- CreateCVBlock -//------------------- -void XEMCVCriterion::createCVBlocks(XEMModel * model){ - int64_t i, v, index; - XEMData * data = model->getData(); - double * weight = data->_weight; - int64_t weightTotal = (int64_t) data->_weightTotal; - int64_t nbSample = model->getNbSample(); - double sumWeight = 0.0; - int64_t value = 0, sizeList; - - - if(_nbCVBlock > weightTotal){ - _nbCVBlock = weightTotal; - } - _tabCVBlock = new XEMCVBlock[_nbCVBlock]; - - // creation of blocks - if(_nbCVBlock == weightTotal){ - v = 0; - for(i=0; i _nbCVBlocks - if (_CVinitBlocks == CV_RANDOM){ - //cout<<"XEMCVCriterion CV_RANDOM"< listCVBlock; - list::iterator listIterator; - list::iterator listBegin; - list::iterator listEnd; - sizeList = 0; - - if (remaining > 0){ - weightTotalInCVBlock++ ; - remaining--; - } - - for (i=0; i (*listIterator)->val)){ - listIterator++; - } - // list empty // - if (listBegin==listEnd){ - TWeightedIndividual * elem = new TWeightedIndividual; - elem->val = value; - elem->weight = 1; - listCVBlock.push_front(elem); - sizeList++; - } - else{ - // if elemn in end of list // - if (listIterator==listEnd){ - listIterator--; - if ((*listIterator)->val==value) - (*listIterator)->weight += 1; - else{ - TWeightedIndividual * elem = new TWeightedIndividual; - elem->val = value; - elem->weight = 1; - listCVBlock.push_back(elem); - sizeList++; - } - } - // elemen in begin or in middle of list // - else{ - if ((*listIterator)->val==value) - (*listIterator)->weight += 1; - else{ - TWeightedIndividual * elem = new TWeightedIndividual; - elem->val = value; - elem->weight = 1; - - if (listIterator == listCVBlock.begin()) - listCVBlock.push_front(elem); - else - listCVBlock.insert(listIterator,1,elem); - - sizeList++; - } - } - } - - index ++; - } - - // update _tabCVBlock - _tabCVBlock[v]._nbSample = sizeList; - _tabCVBlock[v]._weightTotal = weightTotalInCVBlock; - _tabCVBlock[v]._tabWeightedIndividual = new TWeightedIndividual[_tabCVBlock[v]._nbSample]; - - listBegin = listCVBlock.begin(); - listEnd = listCVBlock.end(); - listIterator = listBegin; - i=0; - while ( (listIterator != listEnd) && i<_tabCVBlock[v]._nbSample){ - _tabCVBlock[v]._tabWeightedIndividual[i].val = (*listIterator)->val; - _tabCVBlock[v]._tabWeightedIndividual[i].weight = (*listIterator)->weight; - listIterator++; - i++; - } - if (i != _tabCVBlock[v]._nbSample){ - //cout<<"cout erreur 6 ds XEMCVCriterion"< * listCVBlock = new list [_nbCVBlock]; - - list::iterator listIterator; - list::iterator listBegin; - list::iterator listEnd; - - - int64_t v = 0, i, w, nbTraited=0; - for (i=0; i (*listIterator)->val)){ - listIterator++; - } - // list empty // - if (listBegin==listEnd){ - TWeightedIndividual * elem = new TWeightedIndividual; - elem->val = i; - elem->weight = 1; - listCVBlock[v].push_front(elem); - } - else{ - // if elemn in end of list // - if (listIterator==listEnd){ - listIterator--; - if ((*listIterator)->val==i) - (*listIterator)->weight += 1; - else{ - TWeightedIndividual * elem = new TWeightedIndividual; - elem->val = i; - elem->weight = 1; - listCVBlock[v].push_back(elem); - } - } - // elemen in begin or in middle of list // - else{ - if ((*listIterator)->val==i) - (*listIterator)->weight += 1; - else{ - TWeightedIndividual * elem = new TWeightedIndividual; - elem->val = i; - elem->weight = 1; - - if (listIterator == listCVBlock[v].begin()) - listCVBlock[v].push_front(elem); - else - listCVBlock[v].insert(listIterator,1,elem); - } - } - - } - - v++; - if (v == _nbCVBlock){ - v = 0; - } - nbTraited++; - } - } - if (nbTraited != weightTotal){ - //cout<<"cout erreur 1 ds XEMCVCriterion"<val; - _tabCVBlock[v]._tabWeightedIndividual[i].weight = (*listIterator)->weight; - weightTotalBlockV += _tabCVBlock[v]._tabWeightedIndividual[i].weight; - listIterator++; - i++; - } - _tabCVBlock[v]._weightTotal = weightTotalBlockV; - if (i != _tabCVBlock[v]._nbSample){ - //cout<<"cout erreur 2 ds XEMCVCriterion"< _nbCVBlocks) - - - /* for (v=0; v<_nbCVBlock; v++){ - cout<. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMCVCRITERION_H -#define XEMCVCRITERION_H - - -#include "XEMCriterion.h" -#include "XEMModel.h" -#include "XEMClusteringInput.h" - -/** - @brief Derived class of XEMCriterion for CV Criterion - @author F Langrognet & A Echenim -*/ - -class XEMCVCriterion : public XEMCriterion{ - - public: - - /// Default constructor - XEMCVCriterion(); - - - /// Constructor - XEMCVCriterion(XEMOldInput * input); - - /// Destructor - virtual ~XEMCVCriterion(); - - XEMCriterionName getCriterionName() const; - - /// Run method - void run(XEMModel * model, double & value, XEMErrorType & error, bool quiet=true); - - /// Run method - void run(XEMModel * model, double & value, int64_t *& cvLabel, XEMErrorType & error, bool quiet=true); - - - private : - - - void createCVBlocks(XEMModel * model); - - /// Table of XEMCVBlock : testBlock - XEMCVBlock * _tabCVBlock; - - // number of CV Blocks - int64_t _nbCVBlock; - - // initialisation method of cv blocks - XEMCVinitBlocks _CVinitBlocks; -}; - -inline void XEMCVCriterion::run(XEMModel * model, double & value, XEMErrorType & error, bool quiet){ - throw internalMixmodError; -} - -inline XEMCriterionName XEMCVCriterion::getCriterionName() const{ - return CV; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMClusteringInput.cpp b/lib/src/mixmod/MIXMOD/XEMClusteringInput.cpp deleted file mode 100644 index 703090a..0000000 --- a/lib/src/mixmod/MIXMOD/XEMClusteringInput.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMClusteringInput.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMClusteringInput.h" - - - -//-------------------- -// Default Constructor -//-------------------- -XEMClusteringInput::XEMClusteringInput(){ - _strategy = new XEMClusteringStrategy(); -} - - -//----------------- -// Copy constructor -//----------------- -XEMClusteringInput::XEMClusteringInput(const XEMClusteringInput & cInput ) : XEMInput(cInput){ - _strategy = new XEMClusteringStrategy(*(cInput.getStrategy())); // copy constructor -} - - - -//--------------------------- -// Initialisation Constructor -//--------------------------- -XEMClusteringInput::XEMClusteringInput(const vector & iNbCluster, const XEMDataDescription & iDataDescription) : XEMInput(iNbCluster, iDataDescription){ - _strategy = new XEMClusteringStrategy(); -} - - - - -//----------- -// Destructor -//----------- -XEMClusteringInput::~XEMClusteringInput(){ - if (_strategy){ - delete _strategy; - } -} - - - -// ---------------- -// Verif -//----------------- -bool XEMClusteringInput::verif(){ - bool res = XEMInput::verif(); - - if (res){ - res = _strategy->verify(); - } - return res; -} - - diff --git a/lib/src/mixmod/MIXMOD/XEMClusteringInput.h b/lib/src/mixmod/MIXMOD/XEMClusteringInput.h deleted file mode 100644 index 86439be..0000000 --- a/lib/src/mixmod/MIXMOD/XEMClusteringInput.h +++ /dev/null @@ -1,82 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMClusteringInput.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMCLUSTERINGINPUT_H -#define XEMCLUSTERINGINPUT_H - - -#include "XEMUtil.h" -#include "XEMInput.h" - -using namespace std; - -class XEMClusteringInput : public XEMInput{ - - public: - - /// Default Constructor - XEMClusteringInput(); - - /// Copy Constructor - XEMClusteringInput(const XEMClusteringInput & CInput); - - /// Initialisation constructor - XEMClusteringInput(const vector & iNbCluster, const XEMDataDescription & iDataDescription); - - /// Destructor - virtual ~XEMClusteringInput(); - - - // getStrategy - XEMClusteringStrategy * getStrategy() const; - - // setStrategy - void setStrategy(XEMClusteringStrategy * strat); - - protected : - /// verif - virtual bool verif(); - - - - - - //friend class XEMIOStreamInput; - - // private - private : - XEMClusteringStrategy * _strategy; -}; - -inline XEMClusteringStrategy * XEMClusteringInput::getStrategy() const{ - return _strategy; -} - -inline void XEMClusteringInput::setStrategy(XEMClusteringStrategy * strat){ - delete _strategy; - _strategy = new XEMClusteringStrategy(*strat); -} - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMClusteringMain.cpp b/lib/src/mixmod/MIXMOD/XEMClusteringMain.cpp deleted file mode 100644 index da9d33c..0000000 --- a/lib/src/mixmod/MIXMOD/XEMClusteringMain.cpp +++ /dev/null @@ -1,283 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMClusteringMain.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMError.h" -#include "XEMClusteringMain.h" -#include "XEMRandom.h" -#include "XEMOldInput.h" -#include "XEMBinaryData.h" -#include "XEMClusteringOutput.h" - - -//------------ -// Constructor -//------------ -XEMClusteringMain::XEMClusteringMain(){ - throw internalMixmodError; -} - - - -//------------ -// Constructor -//------------ -XEMClusteringMain::XEMClusteringMain(XEMClusteringInput * input, XEMClusteringOutput * output){ - _input = input; - _output = output; -} - - - - - -//----------- -// Destructor -//----------- -XEMClusteringMain::~XEMClusteringMain(){ - if (_output){ - delete _output; - } - if (_input){ - delete _input; - } -} - - - -//---------------- -// getDCVCriterion -//---------------- -//TODO -// XEMDCVCriterion * XEMClusteringMain::getDCVCriterion(){ -// XEMDCVCriterion * res = NULL; -// int64_t iSelection=0; -// while (iSelection<_nbSelection && res==NULL){ -// if (_tabSelection[iSelection]->getCriterionName() == DCV){ -// XEMCriterion * tmp = _tabSelection[iSelection]->getCriterion(); -// res = dynamic_cast< XEMDCVCriterion*> (tmp); -// } -// iSelection++; -// } -// return res; -// } - - - - - - - - - - - - - - - -//--- -//run -//--- -void XEMClusteringMain::run(bool quiet){ - - //---------------------- - // 1. Create Estimations - //---------------------- - if (!_input){ - throw nullPointerError; - } - if (! _input->isFinalized()){ - throw inputNotFinalized; - } - - vector criterionName = _input->getCriterionName(); - - // _nbCriterion = _input->getNbCriterionName(); - int64_t nbModelType = _input->getNbModelType(); - vector vNbCluster = _input->getNbCluster(); - int64_t nbNbCluster = vNbCluster.size(); - int64_t nbEstimation = nbNbCluster * nbModelType; - vector estimations(nbEstimation); - - int64_t iNbCluster, iModelType, nbCluster; - XEMModelType * modelType; - - // data - XEMData * inputData = (_input->getDataDescription()).getData(); - XEMData * workingData = inputData; - - //Strategy - XEMClusteringStrategy * inputStrategy = NULL; - XEMClusteringStrategy * workingStrategy = NULL; - - // knownPartition - XEMPartition * inputKnownPartition = NULL; - XEMPartition * workingKnownPartition = NULL; - - int64_t iEstimation = 0; // counting the estimations - inputStrategy = _input->getStrategy(); - workingStrategy = inputStrategy; - - - for (iNbCluster=0 ; iNbClustergetKnownPartition(); - workingKnownPartition = inputKnownPartition ; - vector correspondenceOriginDataToReduceData; - -#if DATA_REDUCE == 1 - //Reduce Data - //------------ - if (_input->isBinaryData()){ - XEMBinaryData * bData = dynamic_cast(inputData); - - // initPartition - XEMPartition * inputInitPartition = NULL; - XEMPartition * workingInitPartition = NULL; - if (inputStrategy->getStrategyInit()->getStrategyInitName() == USER_PARTITION){ - inputInitPartition = inputStrategy->getStrategyInit()->getPartition(iNbCluster); - } - try{ - //TODO RD : data ne doit pas forcément etre recréé - workingData = bData->reduceData(correspondenceOriginDataToReduceData, inputKnownPartition, inputInitPartition, workingKnownPartition, workingInitPartition); - workingStrategy = new XEMClusteringStrategy(*inputStrategy); - if (workingInitPartition - ){ - workingStrategy->setInitPartition(workingInitPartition, iNbCluster); - } - /* TODO ?: - if inputKnownPartition : delete workingKnownPartition - if inputInitPartition : delete workingStrategy, workingInitPartition - - */ - } - catch(XEMErrorType errorType){ - workingData = NULL; - throw errorType; - } - } - // fin de ReduceData -#endif - - // create tabEstmation[iEstimation] - //-------------------------------- - for (iModelType=0 ; iModelTypegetModelType(iModelType); - estimations[iEstimation] = new XEMEstimation(workingStrategy, modelType, nbCluster, workingData, criterionName, workingKnownPartition, correspondenceOriginDataToReduceData); - iEstimation++; - } - } // end for iNbCluster - - - - - - - //------------------- - // 2. run Estimations - //------------------- - - - - // Estimation - //----------- - //_tabEstimation : run - int64_t todo = nbEstimation-1; - int64_t j; - iEstimation = 0; - if(!quiet){ - cout << "...running" << endl; - } - - while (iEstimation < nbEstimation){ - if(!quiet){ - - cout << " |"<< flush; - - j = iEstimation+1; - while(j){ - cout << "-" << flush; - j--; - } - j= todo; - while(j){ - cout << " " << flush; - j--; - } - - - cout << "| \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b" << flush; - printModelType(estimations[iEstimation]->getModelType()); - cout << " (k=" << estimations[iEstimation]->getNbCluster() << ")\r" << flush; - } - - - try{ - estimations[iEstimation]->run(); - } - - catch (XEMErrorType errorType){ - estimations[iEstimation]->setErrorType(errorType); - XEMError error(errorType); - if(!quiet) error.run(); - } - iEstimation++; - - if(!quiet){ - todo--; - } - - } - - - if(!quiet){ - j = nbEstimation; - cout << " |"<< flush; - while(j){ - cout << "-" << flush; - j--; - } - cout << "| " << flush; - - cout << endl; - - } - - //---------------- - // 3. create Output - //----------------- - _output = new XEMClusteringOutput(estimations); - _output->sort(_input->getCriterionName()[0]); - - // TODO - // _output->sort(_input->getCriterionName(0)); - - -} - - - - diff --git a/lib/src/mixmod/MIXMOD/XEMClusteringMain.h b/lib/src/mixmod/MIXMOD/XEMClusteringMain.h deleted file mode 100644 index 3099c5a..0000000 --- a/lib/src/mixmod/MIXMOD/XEMClusteringMain.h +++ /dev/null @@ -1,98 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMClusteringMain.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMCLUSTERINGMMAIN_H -#define XEMCLUSTERINGMMAIN_H - -/*#include */ - -#include "XEMClusteringInput.h" -#include "XEMOutput.h" -#include "XEMEstimation.h" -#include "XEMSelection.h" -#include "XEMError.h" -#include "XEMDCVCriterion.h" - -class XEMClusteringOutput; - -class XEMClusteringMain{ - - public: - - /// Default constructor - XEMClusteringMain(); - - /// Constructor - XEMClusteringMain(XEMClusteringInput * cInput, XEMClusteringOutput * output = NULL); - - /// Destructor - virtual ~XEMClusteringMain(); - - - /** @brief Selector - @return XEMClusteringOutput - */ - XEMClusteringOutput * getClusteringOutput() const; - - // get Input - XEMInput * getInput(); - - /// Run method - void run(bool quiet=true); - void setOutputNull(); - - /// getDCVCriterion - // XEMDCVCriterion * getDCVCriterion(); - - private : - - - XEMClusteringInput * _input; - - XEMClusteringOutput * _output; - - -}; - -inline XEMClusteringOutput * XEMClusteringMain::getClusteringOutput() const{ - return _output; -} - -inline XEMInput * XEMClusteringMain::getInput(){ - if (_input){ - return _input; - } - else{ - throw nullPointerError; - } -} - -inline void XEMClusteringMain::setOutputNull() -{ - _output = NULL; -} - - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMClusteringModelOutput.cpp b/lib/src/mixmod/MIXMOD/XEMClusteringModelOutput.cpp deleted file mode 100644 index 11a07fe..0000000 --- a/lib/src/mixmod/MIXMOD/XEMClusteringModelOutput.cpp +++ /dev/null @@ -1,77 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMClusteringModelOutput.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMClusteringModelOutput.h" - - - -//-------------------- -// Default Constructor -//-------------------- -XEMClusteringModelOutput::XEMClusteringModelOutput(){ -} - - -//----------------- -// Copy constructor -//----------------- -XEMClusteringModelOutput::XEMClusteringModelOutput(const XEMClusteringModelOutput & cModelOutput){ - throw internalMixmodError; -} - - - -//----------------- -// Initialization Constructor -//----------------- -XEMClusteringModelOutput::XEMClusteringModelOutput(XEMEstimation * estimation) : XEMModelOutput(estimation){ -} - -//----------------- -// Initialization Constructor -//----------------- -XEMClusteringModelOutput::XEMClusteringModelOutput(XEMModelType& modelType, int64_t nbCluster, vector< XEMCriterionOutput >& criterionOutput, double likelihood, XEMParameterDescription& parameterDescription, XEMLabelDescription& labelDescription, XEMProbaDescription& probaDescription):XEMModelOutput(modelType, nbCluster, criterionOutput, likelihood, parameterDescription, labelDescription, probaDescription) -{ - -} - -//----------------- -// Initialization Constructor -//----------------- -XEMClusteringModelOutput::XEMClusteringModelOutput(XEMModelType& modelType, int64_t nbCluster, XEMErrorType error): XEMModelOutput(modelType, nbCluster, error) -{ - -} - -//----------- -// Destructor -//----------- -XEMClusteringModelOutput::~XEMClusteringModelOutput(){ - -} - - - - - diff --git a/lib/src/mixmod/MIXMOD/XEMClusteringModelOutput.h b/lib/src/mixmod/MIXMOD/XEMClusteringModelOutput.h deleted file mode 100644 index fe4cb46..0000000 --- a/lib/src/mixmod/MIXMOD/XEMClusteringModelOutput.h +++ /dev/null @@ -1,61 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMClusteringModelOutput.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMCLUSTERINGMODELOUTPUT_H -#define XEMCLUSTERINGMODELOUTPUT_H - - -#include "XEMModelOutput.h" -#include "XEMEstimation.h" - - -using namespace std; - -class XEMClusteringModelOutput : public XEMModelOutput{ - - public: - - /// Default Constructor - XEMClusteringModelOutput(); - - /// Initialization Constructor 1 - XEMClusteringModelOutput(XEMEstimation * estimation); - - /// Initialization Constructor 2 - XEMClusteringModelOutput(XEMModelType & modelType, int64_t nbCluster, vector & criterionOutput, double likelihood, XEMParameterDescription & parameterDescription, XEMLabelDescription & labelDescription, XEMProbaDescription & probaDescription); - - /// Initialization Constructor 3 - XEMClusteringModelOutput(XEMModelType & modelType, int64_t nbCluster, XEMErrorType error); - - /// Copy Constructor - XEMClusteringModelOutput(const XEMClusteringModelOutput & cModelOutput); - - - /// Destructor - virtual ~XEMClusteringModelOutput(); - -}; - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMClusteringOutput.cpp b/lib/src/mixmod/MIXMOD/XEMClusteringOutput.cpp deleted file mode 100644 index 3713a24..0000000 --- a/lib/src/mixmod/MIXMOD/XEMClusteringOutput.cpp +++ /dev/null @@ -1,238 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMClusteringOutput.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMClusteringOutput.h" - - - -//-------------------- -// Default Constructor -//-------------------- -XEMClusteringOutput::XEMClusteringOutput(){ - -} - - -//----------------- -// Copy constructor -//----------------- -XEMClusteringOutput::XEMClusteringOutput(const XEMClusteringOutput & cOutput){ - _clusteringModelOutput.resize(cOutput.getNbClusteringModelOutput()); - for (int64_t i=0; i<_clusteringModelOutput.size() ; i++){ - XEMClusteringModelOutput * cMOuput = cOutput.getClusteringModelOutput(i); - XEMEstimation * estimation = cMOuput->getEstimation(); - _clusteringModelOutput[i] = new XEMClusteringModelOutput(estimation); - } - _error = cOutput.getError(); -} - - -//--------------------------- -// Initialisation Constructor -//--------------------------- -XEMClusteringOutput::XEMClusteringOutput(vector & estimations){ - int64_t sizeEstimation = estimations.size(); - - _clusteringModelOutput.resize(sizeEstimation); - for (int64_t i=0; igetStrategyRunError() == noError ){ - res = true; - } - i++; - } - return res; -} - - -//----- -// sort -//----- -void XEMClusteringOutput::sort(XEMCriterionName criterionName){ - int64_t i,j; - i=0; - - //find indexCriterion - int64_t indexCriterion = -1; - XEMEstimation * estimation0 = _clusteringModelOutput[0]->_estimation; - while (igetCriterionSize()){ - if (estimation0->getCriterionOutput(i).getCriterionName() == criterionName){ - indexCriterion = i; - break; - } - else{ - i++; - } - } - if (i==estimation0->getCriterionSize()){ - throw internalMixmodError; - } - - - // treatment criterion Error - //-------------------------- - int64_t nbCriterionError = 0; - for (i=0; i<_clusteringModelOutput.size()-nbCriterionError; i++){ - vector criterionOutput = _clusteringModelOutput[i]->getCriterionOutput(); - if (criterionOutput[indexCriterion].getError() != noError){ - XEMClusteringModelOutput * tmp = _clusteringModelOutput[i]; - _clusteringModelOutput.erase(_clusteringModelOutput.begin()+i); - _clusteringModelOutput.push_back(tmp); - nbCriterionError++; - } - } - - for (i=0; i<_clusteringModelOutput.size()-nbCriterionError; i++){ - //find bestCriterionValue - //cout<<"i : "< criterionOutput = _clusteringModelOutput[bestIndex]->getCriterionOutput(); - double bestCriterionValue = criterionOutput[indexCriterion].getValue(); - for (j=i+1; j<_clusteringModelOutput.size(); j++){ - vector criterionOutputJ = _clusteringModelOutput[j]->getCriterionOutput(); - if (criterionOutputJ[indexCriterion].getError() == noError){ - double criterionValueJ = criterionOutputJ[indexCriterion].getValue(); - if (bestCriterionValue > criterionValueJ){ - // cout<<"if ... bestCriterionValue : "<getEstimation(); - bestEstimation = _clusteringModelOutput[bestIndex]->getEstimation(); - } - catch (XEMError & e){ - throw wrongSortCallInXEMModelOutput; - } - int64_t freeParameterJ = estimationJ->getModel()->getFreeParameter(); - int64_t bestFreeParameter = bestEstimation->getModel()->getFreeParameter(); - if (freeParameterJ < bestFreeParameter){ - // if this Estimation is better - // cout<<"if ... bestCriterionValue : "<_estimation->getCriterionOutput())[indexCriterion])->_criterionName<_estimation->getCriterionOutput())[indexCriterion])->_value< clusteringModelOutputTmp; - clusteringModelOutputTmp.resize(_clusteringModelOutput.size()); - for (i=0; i<_clusteringModelOutput.size(); i++){ - clusteringModelOutputTmp[i] = _clusteringModelOutput[i]; - } - - for (i=0; i<_clusteringModelOutput.size(); i++){ - // cout<<"i = "< criterionOutput = clusteringModelOutputTmp[bestIndex]->getCriterionOutput(); - double bestCriterionValue = criterionOutput[indexCriterion]->_value; - // cout<<"bestCriterionValue : "< criterionOutputJ = clusteringModelOutputTmp[j]->getCriterionOutput(); - double criterionValueJ = criterionOutputJ[indexCriterion]->_value; - // cout<<"j : "< criterionValueJ){ - // cout<<"if ... bestCriterionValue : "<_estimation->getCriterionOutput())[indexCriterion])->_criterionName<_estimation->getCriterionOutput())[indexCriterion])->_value< & clusteringModelOutput){ - for (int64_t i=0; i<_clusteringModelOutput.size(); i++){ - delete _clusteringModelOutput[i]; - } - _clusteringModelOutput = clusteringModelOutput; -} - diff --git a/lib/src/mixmod/MIXMOD/XEMClusteringOutput.h b/lib/src/mixmod/MIXMOD/XEMClusteringOutput.h deleted file mode 100644 index 2dd050d..0000000 --- a/lib/src/mixmod/MIXMOD/XEMClusteringOutput.h +++ /dev/null @@ -1,107 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMClusteringOutput.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMCLUSTERINGOUTPUT_H -#define XEMCLUSTERINGOUTPUT_H - - -#include "XEMUtil.h" -#include "XEMClusteringMain.h" -#include "XEMEstimation.h" -#include "XEMClusteringModelOutput.h" - -using namespace std; - -class XEMClusteringOutput{ - - public: - - /// Default Constructor - XEMClusteringOutput(); - - - /// Copy Constructor - XEMClusteringOutput(const XEMClusteringOutput & cOutput); - - /// Initialisation constructor - XEMClusteringOutput(vector & estimations); - - /// Destructor - virtual ~XEMClusteringOutput(); - - - bool atLeastOneEstimationNoError() const; - - /// sort vector of XEMClusteringModelOutput (with the ith criterion value) - void sort(XEMCriterionName criterionName); - - void editFile() const; - - /// return the index'th' ClusteringModelOutput - /// Note : index is between 0 and size(ClusteringModelOutput)-1 - XEMClusteringModelOutput * getClusteringModelOutput(int64_t index) const; - - int64_t getNbClusteringModelOutput() const; - - - XEMErrorType getError() const; - - void setError(XEMErrorType & error); - - void setClusteringModelOutput(vector & clusteringModelOutput); - - - private : - vector _clusteringModelOutput; - - XEMErrorType _error; - -}; - - - -inline XEMErrorType XEMClusteringOutput::getError() const{ - return _error; -} - -inline void XEMClusteringOutput::setError(XEMErrorType & error){ - _error = error; -} - -inline XEMClusteringModelOutput * XEMClusteringOutput::getClusteringModelOutput(int64_t index) const{ - if (index>=0 && index<_clusteringModelOutput.size()) { - return _clusteringModelOutput[index]; - } - else{ - throw wrongIndexInGetMethod; - } -} - -// -inline int64_t XEMClusteringOutput::getNbClusteringModelOutput() const{ - return _clusteringModelOutput.size(); -} - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMClusteringStrategy.cpp b/lib/src/mixmod/MIXMOD/XEMClusteringStrategy.cpp deleted file mode 100644 index e748577..0000000 --- a/lib/src/mixmod/MIXMOD/XEMClusteringStrategy.cpp +++ /dev/null @@ -1,615 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMClusteringStrategy.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#include "XEMClusteringStrategy.h" -#include "XEMAlgo.h" -#include "XEMEMAlgo.h" -#include "XEMCEMAlgo.h" -#include "XEMSEMAlgo.h" -#include "XEMUtil.h" -#include "XEMGaussianParameter.h" -#include "XEMGaussianSphericalParameter.h" -#include "XEMGaussianDiagParameter.h" -#include "XEMGaussianGeneralParameter.h" -#include "XEMGaussianHDDAParameter.h" -#include "XEMBinaryEkjhParameter.h" -#include "XEMBinaryData.h" - - -//----------- -//Constructor -//----------- -XEMClusteringStrategy::XEMClusteringStrategy(){ - _nbTry = defaultNbTryInStrategy; - _strategyInit = new XEMClusteringStrategyInit(); - _nbAlgo = defaultNbAlgo; - _tabAlgo = new XEMAlgo * [_nbAlgo]; - for (int64_t i=0; i<_nbAlgo; i++){ - _tabAlgo[i] = createDefaultAlgo(); - } -} - - -XEMClusteringStrategy::XEMClusteringStrategy(const XEMClusteringStrategy & strategy){ - _nbTry = strategy.getNbTry(); - _strategyInit = new XEMClusteringStrategyInit(*(strategy.getStrategyInit())); - _nbAlgo = strategy.getNbAlgo(); - _tabAlgo = new XEMAlgo * [_nbAlgo]; - XEMAlgo ** tabA = strategy.getTabAlgo(); - for (int64_t i=0; i<_nbAlgo; i++){ - _tabAlgo[i] = tabA[i]->clone(); - } - -} - - - -//---------- -//Destructor -//---------- -XEMClusteringStrategy::~XEMClusteringStrategy(){ - - if (_tabAlgo){ - for (int64_t i=0; i<_nbAlgo ;i++){ - delete _tabAlgo[i]; - _tabAlgo[i] = NULL; - } - delete [] _tabAlgo; - _tabAlgo = NULL; - } -} - - - -void XEMClusteringStrategy::setAlgoEpsilon(int64_t position, double epsilonValue){ - _tabAlgo[position]->setEpsilon(epsilonValue); -} - -// setAlgoStopRuleTypeValue -void XEMClusteringStrategy::setAlgoStopRule(XEMAlgoStopName stopName, int64_t position){ - _tabAlgo[position]->setAlgoStopName(stopName); -} - -void XEMClusteringStrategy::setAlgoIteration( int64_t position, int64_t nbIterationValue){ - _tabAlgo[position]->setNbIteration(nbIterationValue); -} - - -// setAlgo -void XEMClusteringStrategy::setAlgo(XEMAlgoName algoName, int64_t position){ - if (_tabAlgo[position] != NULL){ - delete _tabAlgo[position]; - } - switch (algoName) { - case EM : - _tabAlgo[position] = new XEMEMAlgo(); - break; - case CEM : - _tabAlgo[position] = new XEMCEMAlgo(); - break; - case SEM : - _tabAlgo[position] = new XEMSEMAlgo(); - break; - default : - throw internalMixmodError; - } -} - - - -// set init parameter -void XEMClusteringStrategy::setInitParam(string & paramFileName, int64_t position){ - _strategyInit->setInitParam(paramFileName, position); -} - -void XEMClusteringStrategy::setTabInitParameter(XEMParameter ** tabInitParameter, int64_t nbInitParameter){ - _strategyInit->setTabInitParameter(tabInitParameter, nbInitParameter); -} - -// set init partition -void XEMClusteringStrategy::setInitPartition(string & partitionFileName, int64_t position){ - _strategyInit->setPartition(partitionFileName, position); -} - - -// set init partition -void XEMClusteringStrategy::setInitPartition(XEMPartition * part, int64_t position){ - _strategyInit->setPartition(part, position); -} - -void XEMClusteringStrategy::setTabPartition(XEMPartition ** tabPartition, int64_t nbPartition){ - _strategyInit->setTabPartition(tabPartition, nbPartition); -} - -// removeAlgo -void XEMClusteringStrategy::removeAlgo(int64_t position){ - XEMAlgo ** tabAlgo = new XEMAlgo*[_nbAlgo-1]; - recopyTab(_tabAlgo, tabAlgo, position); - for (int64_t i=position ; i<(_nbAlgo-1);i++){ - tabAlgo[i] = _tabAlgo[i+1]; - } - _nbAlgo--; - - delete [] _tabAlgo; - _tabAlgo = NULL; - _tabAlgo = tabAlgo; - -} - -//-------------------- -// setStrategyInit -//-------------------- -void XEMClusteringStrategy::setStrategyInit(XEMClusteringStrategyInit * iStrategyInit){ - _strategyInit = iStrategyInit; //copy constructor -} - - -void XEMClusteringStrategy::setStrategyInit(XEMStrategyInitName initName, XEMData *& data, int64_t nbNbCluster, int64_t * tabNbCluster, XEMModelType * modelType){ - int64_t nbSample = data->_nbSample; - int64_t pbDimension = data->_pbDimension; - string fileName = ""; - XEMParameter ** tabInitParameter = NULL; - XEMPartition ** tabInitPartition = NULL; - - switch (initName){ - case RANDOM : - case CEM_INIT : - case SEM_MAX : - case SMALL_EM : - _strategyInit->setStrategyInitName(initName); - break; - - case USER : - _strategyInit->setStrategyInitName(initName); - tabInitParameter = new XEMParameter * [nbNbCluster]; - - for (int64_t k=0; k_nameModel)){ - tabInitParameter[k] = new XEMGaussianGeneralParameter(tabNbCluster[k], pbDimension, modelType, fileName); - } - else if (isBinary(modelType->_nameModel)){ - int64_t * tabNbModality = dynamic_cast(data)->getTabNbModality(); - tabInitParameter[k] = new XEMBinaryEkjhParameter(tabNbCluster[k], pbDimension, modelType, tabNbModality, fileName); - } - else if (isHD(modelType->_nameModel)){ - tabInitParameter[k] = new XEMGaussianHDDAParameter(tabNbCluster[k], pbDimension, modelType, fileName); - } - else throw internalMixmodError; - } - _strategyInit->setTabInitParameter(tabInitParameter, nbNbCluster); - break; - - case USER_PARTITION : - _strategyInit->setStrategyInitName(initName); - tabInitPartition = new XEMPartition * [nbNbCluster]; - for (int64_t k=0; ksetTabPartition(tabInitPartition, nbNbCluster); - break; - } -} - -//------------- -// setNbTry -//------------- -void XEMClusteringStrategy::setNbTry(int64_t nbTry){ - if ((_strategyInit->getStrategyInitName() == USER) || - (_strategyInit->getStrategyInitName() == USER_PARTITION)){ - throw badSetNbTry; - } - if (nbTrymaxNbTryInStrategy){ - throw nbTryInStrategyTooLarge; - } - else{ - _nbTry = nbTry; - } -} - - - - - - -//--- -//run -//--- -void XEMClusteringStrategy::run(XEMModel *& model){ - //cout<<"XEMClusteringStrategy Init, nbTry="<<_nbTry<getCompletedLogLikelihoodOrLogLikelihood(); - // others tries - for (i=1; i<_nbTry; i++){ - delete currentModel; - currentModel = new XEMModel(model); - oneTry(currentModel); - double lastLLorCLL = currentModel->getCompletedLogLikelihoodOrLogLikelihood(); - if (lastLLorCLL > bestLLorCLL){ - delete bestModel; - bestModel = new XEMModel(currentModel); - bestLLorCLL = currentModel->getCompletedLogLikelihoodOrLogLikelihood(); - } - } - //cout<<"fin de XEMClusteringStrategy Init, nb d'essais effectues="<getStrategyInitName()){ - case RANDOM : - model->initRANDOM(_strategyInit->getNbTry()); - break; - - case USER :{ // get initPartition - int64_t nbCluster = model->getNbCluster(); - int64_t index=0; - bool ok = false; - int64_t nbInitParameter = _strategyInit->getNbInitParameter(); - while (ok==false && indexgetInitParameter(index)->getNbCluster(); - if (nbCluster==nbClusterOfInitParameter){ - ok = true; - } - else{ - index++; - } - } - if (!ok) - throw internalMixmodError; - XEMParameter * initParameter =_strategyInit->getInitParameter(index); - model->initUSER(initParameter); - } - break; - - case USER_PARTITION :{ - // get initPartition - int64_t nbCluster = model->getNbCluster(); - int64_t index=0; - bool ok = false; - int64_t nbPartition = _strategyInit->getNbPartition(); - while (ok==false && indexgetPartition(index)->_nbCluster; - if (nbCluster == nbClusterOfInitPartition){ - ok = true; - } - else{ - index++; - } - } - if (!ok) - throw internalMixmodError; - XEMPartition * initPartition = _strategyInit->getPartition(index); - int64_t nbTyInInit = _strategyInit->getNbTry(); - model->initUSER_PARTITION(initPartition, nbTyInInit); - } - break; - - case SMALL_EM : - model->initSMALL_EM(_strategyInit); break; - - case CEM_INIT : - model->initCEM_INIT(_strategyInit); break; - - case SEM_MAX : - model->initSEM_MAX(_strategyInit); break; - - default : - cout << "XEMAlgo Error: Strategy Initialization Type Unknown";break; - } - - model->setAlgoName(UNKNOWN_ALGO_NAME); - - // model->getParameter()->edit(); - -#if DEBUG > 0 - cout<<"After initialization :"<editDebugInformation(); -#endif - - // runs algos - _tabAlgo[0]->run(model); - for (int64_t i=1; i<_nbAlgo ;i++){ - _tabAlgo[i]->run(model); - } -} - - - -// insert algo -void XEMClusteringStrategy::insertAlgo(XEMAlgo * algo,int64_t position){ - XEMAlgo ** tabAlgo = new XEMAlgo*[_nbAlgo+1]; - recopyTab(_tabAlgo, tabAlgo, position); - tabAlgo[position] = algo; - - for (int64_t k=position; k<_nbAlgo;++k){ - tabAlgo[k+1] = _tabAlgo[k]; - } - - _nbAlgo++; - - delete [] _tabAlgo; - _tabAlgo = NULL; - _tabAlgo = tabAlgo; -} - - - - -//------- -// verify -//------- -bool XEMClusteringStrategy::verify(){ - - int64_t i; - bool res = true; - - // Test - //----- - // nbAlogType > 0 - if (_nbAlgo<1 || _tabAlgo==NULL){ - res = false; - throw nbAlgoTypeTooSmall; - } - if (_nbTrymaxNbTryInStrategy){ - res=false; - throw nbTryInStrategyTooLarge; - } - - if (res){ - res = _strategyInit->verify(); - } - - return res; - -} - - - - -//--------------- -// Input strategy -// TODO XEMInput : a enlever -//--------------- -void XEMClusteringStrategy::input_FLAT_FORMAT(ifstream & fi, XEMData *& data, int64_t nbNbCluster, int64_t * tabNbCluster, XEMModelType * modelType){ - int64_t k, j; - string keyWord = ""; - int64_t nbSample = data->_nbSample; - int64_t pbDimension = data->_pbDimension; - bool alreadyRead = false; - string a =""; - - // nbTry - //------ - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if(keyWord.compare("nbtry")==0){ - int64_t nbTry; - fi>>nbTry; - setNbTry(nbTry); - } - - // StrategyInit - //----------------- - _strategyInit->input(fi, data, nbNbCluster, tabNbCluster, modelType, alreadyRead); - - - // Algos - //------- - /* Number of algorithms */ - moveUntilReach(fi,"nbAlgorithm"); - if(!fi.eof()){ - for (j=0; j<_nbAlgo; j++){ - delete _tabAlgo[j]; - } - delete[] _tabAlgo; - - fi>>_nbAlgo; - if (_nbAlgo > maxNbAlgo){ - throw nbAlgoTooLarge; - } - else if (_nbAlgo <= 0){ - throw nbAlgoTooSmall; - } - - _tabAlgo = new XEMAlgo * [_nbAlgo]; - - for (j=0; j<_nbAlgo; j++){ - fi>>keyWord; - ConvertBigtoLowString(keyWord); - - if(keyWord.compare("algorithm")==0){ - // tabAlgoType._type - fi>>a; - - if (a.compare("CEM")==0){ - _tabAlgo[j] = new XEMCEMAlgo(); - } - else if (a.compare("EM")==0){ - _tabAlgo[j] = new XEMEMAlgo(); - } - else if (a.compare("SEM")==0){ - _tabAlgo[j] = new XEMSEMAlgo(); - } - else{ - throw wrongAlgoType; - } - - fi>>keyWord; - ConvertBigtoLowString(keyWord); - - if(keyWord.compare("stoprule")==0){ - fi>>a; - - if (a.compare("NBITERATION")==0){ - _tabAlgo[j]->setAlgoStopName(NBITERATION); - } - - else if (a.compare("EPSILON")==0){ - _tabAlgo[j]->setAlgoStopName(EPSILON); - } - - else if (a.compare("NBITERATION_EPSILON")==0){ - _tabAlgo[j]->setAlgoStopName(NBITERATION_EPSILON); - } - else{ - throw wrongAlgoStopName; - } - // nbIteration && epsilon - fi>>keyWord; - ConvertBigtoLowString(keyWord); - - if(keyWord.compare("stoprulevalue")==0){ - if (_tabAlgo[j]->getAlgoStopName() == NBITERATION){ - int64_t nbIteration; - fi>>nbIteration; - _tabAlgo[j]->setNbIteration(nbIteration); - //_tabAlgo[j]->setEpsilon(minEpsilon); - } - else if (_tabAlgo[j]->getAlgoStopName() == EPSILON){ - double epsilon; - fi>>epsilon; - _tabAlgo[j]->setEpsilon(epsilon); - // _tabAlgo[j]->setNbIteration(maxNbIteration); - } - else if (_tabAlgo[j]->getAlgoStopName() == NBITERATION_EPSILON){ - int64_t nbIteration; - double epsilon; - fi>>nbIteration; - _tabAlgo[j]->setNbIteration(nbIteration); - fi>>epsilon; - _tabAlgo[j]->setEpsilon(epsilon); - } - - }// end if stopRuleValue - else{ - throw errorStopRuleValue; - } - - }// end if StopRule - else{ - throw errorStopRule; - } - - - }// end if algorithm - else{ - throw errorAlgo; - } - - }// end for jgetStrategyInitName()); - oFile<edit(oFile); - } - //oFile<<"\tNumber of strategy repetitions : "<<_nbStrategyTry<. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMClusteringStrategy_H -#define XEMClusteringStrategy_H - -#include "XEMAlgo.h" -#include "XEMData.h" -#include "XEMPartition.h" -#include "XEMClusteringStrategyInit.h" -#include "XEMModel.h" - -/** - @brief Base class for Strategy(s) - @author F Langrognet -*/ - -class XEMClusteringStrategy{ - - public: - - /// Default constructor - XEMClusteringStrategy(); - - /// Constructor - XEMClusteringStrategy(const XEMClusteringStrategy & strategy); - - - /// Destructor - virtual ~XEMClusteringStrategy(); - - ///getStrategyInit - const XEMClusteringStrategyInit * getStrategyInit() const; - - ///getAlgo[i] - const XEMAlgo * getAlgo(int64_t index) const; - - /// setStrategyInit - void setStrategyInit(XEMClusteringStrategyInit * iStrategyInit); - - /// setStrategyInit - void setStrategyInit(XEMStrategyInitName initName,XEMData *& data, int64_t nbNbCluster, int64_t * tabNbCluster, XEMModelType * modelType); - - /// setStrategyInitName - void setStrategyInitName(XEMStrategyInitName initName); - - /// setInitParam - void setInitParam(string & paramFileName, int64_t position); - - /// setInitParam - void setTabInitParameter(XEMParameter ** tabInitParameter, int64_t nbInitParameter); - - /// setInitPartition - void setInitPartition(string & partitionFileName, int64_t position); - - /// setInitPartition - void setInitPartition(XEMPartition * part, int64_t position); - - /// setTabPartition - void setTabPartition(XEMPartition ** tabPartition, int64_t nbPartition); - - /// getNbTryInInit - const int64_t getNbTryInInit() const; - - /// setNbTryInInit - void setNbTryInInit(int64_t nbTry); - - /// getNbIterationInInit - const int64_t getNbIterationInInit() const; - - /// set NbIterationInInit - void setNbIterationInInit(int64_t nbIteration); - - /// getEpsilonInInit - const double getEpsilonInInit() const; - - /// setEpsilonInInit - void setEpsilonInInit(double epsilon); - - /// getStopNameInInit - const XEMAlgoStopName getStopNameInInit() const; - - /// setStopNameInInit - void setStopNameInInit(XEMAlgoStopName stopName); - - - - - /// setAlgo - void setAlgo(XEMAlgoName algoName, int64_t position); - - /// removeAlgo - void removeAlgo(int64_t position); - - /// getTabAlgo - XEMAlgo ** getTabAlgo() const; - - /// insertAlgo - void insertAlgo(XEMAlgo * algo, int64_t position); - - - /// setAlgoStopRuleTypeValue - void setAlgoStopRule(XEMAlgoStopName stopName, int64_t position); - void setAlgoIteration( int64_t position, int64_t nbIterationValue); - void setAlgoEpsilon( int64_t position, double epsilonValue); - - ///nbTry - const int64_t getNbTry()const; - void setNbTry(int64_t nbTry); - - const int64_t getNbAlgo() const; - - /// Input strategy (FLAT FORMAT) - // TODO XEMInput : a enlever - void input_FLAT_FORMAT(ifstream & fi, XEMData *& data, int64_t nbNbCluster, int64_t * tabNbCluster, XEMModelType * modelType); - - /// Run method - void run(XEMModel *& model); - - bool verify(); - - void edit(ofstream & oFile); - - - friend ostream & operator << (ostream & fo, XEMClusteringStrategy & strategy); - - - private : - - /// Number of try in the strategy - int64_t _nbTry; - - /// strategyInit - XEMClusteringStrategyInit * _strategyInit; - - /// Number of algorithm in the strategy - int64_t _nbAlgo; - - /// Table of algorithm - XEMAlgo ** _tabAlgo; // aggregate - - void oneTry(XEMModel *& model); - -}; - - -inline const XEMClusteringStrategyInit * XEMClusteringStrategy::getStrategyInit() const{ - return _strategyInit; -} - -inline const XEMAlgo * XEMClusteringStrategy::getAlgo(int64_t index) const{ - return _tabAlgo[index]; -} - -inline XEMAlgo ** XEMClusteringStrategy::getTabAlgo() const{ - return _tabAlgo; -} - -inline const int64_t XEMClusteringStrategy::getNbAlgo() const{ - return _nbAlgo; -} -inline const int64_t XEMClusteringStrategy::getNbTry()const{ - return _nbTry; -} - -inline const int64_t XEMClusteringStrategy::getNbTryInInit() const{ - return _strategyInit->getNbTry(); -} - -inline const int64_t XEMClusteringStrategy::getNbIterationInInit() const{ - return _strategyInit->getNbIteration(); -} - -inline const double XEMClusteringStrategy::getEpsilonInInit() const{ - return _strategyInit->getEpsilon(); -} - -inline void XEMClusteringStrategy::setNbTryInInit(int64_t nbTry){ - _strategyInit->setNbTry(nbTry); -} - -inline void XEMClusteringStrategy::setStrategyInitName(XEMStrategyInitName initName){ - _strategyInit->setStrategyInitName(initName); -} - -inline void XEMClusteringStrategy::setNbIterationInInit(int64_t nbIteration){ - _strategyInit->setNbIteration(nbIteration); -} - -inline void XEMClusteringStrategy::setEpsilonInInit(double epsilon){ - _strategyInit->setEpsilon(epsilon); -} - -inline const XEMAlgoStopName XEMClusteringStrategy::getStopNameInInit() const{ - return(_strategyInit->getStopName()); -} - -inline void XEMClusteringStrategy::setStopNameInInit(XEMAlgoStopName stopName){ - _strategyInit->setStopName(stopName); -} - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMClusteringStrategyInit.cpp b/lib/src/mixmod/MIXMOD/XEMClusteringStrategyInit.cpp deleted file mode 100644 index 3588b59..0000000 --- a/lib/src/mixmod/MIXMOD/XEMClusteringStrategyInit.cpp +++ /dev/null @@ -1,593 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMClusteringStrategyInit.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#include "XEMClusteringStrategyInit.h" -#include "XEMGaussianParameter.h" -#include "XEMGaussianSphericalParameter.h" -#include "XEMGaussianDiagParameter.h" -#include "XEMGaussianGeneralParameter.h" -#include "XEMGaussianHDDAParameter.h" -#include "XEMBinaryEkjhParameter.h" -#include "XEMBinaryData.h" -//#include - -//------------ -// Constructor -//------------ -XEMClusteringStrategyInit::XEMClusteringStrategyInit(){ - _strategyInitName = defaultStrategyInitName; - _nbInitParameter = 0; - _tabInitParameter = NULL; - _nbPartition = 0; - _tabPartition = NULL; - _deleteTabParameter= false; - - _nbTry = defaultNbTryInInit; - _nbIteration = defaultNbIterationInInit; - _epsilon = defaultEpsilonInInit; - setStopName(NBITERATION_EPSILON); -} - - -//------------------ -// Copy constructor -//------------------ -XEMClusteringStrategyInit::XEMClusteringStrategyInit(const XEMClusteringStrategyInit & strategyInit){ - _strategyInitName = strategyInit.getStrategyInitName(); - _nbInitParameter = strategyInit.getNbInitParameter(); - - _nbPartition = strategyInit.getNbPartition(); - _tabPartition = NULL; - if (_nbPartition !=0){ - _tabPartition = new XEMPartition*[_nbPartition]; - const XEMPartition ** iPartition = strategyInit.getTabPartition(); - for (int64_t i=0; i<_nbPartition; i++){ - _tabPartition[i] = new XEMPartition(*(iPartition[i])); //copy constructor - } - } - - _nbInitParameter = strategyInit.getNbInitParameter(); - _tabInitParameter = NULL; - if (_nbInitParameter !=0){ - _tabInitParameter = new XEMParameter*[_nbInitParameter]; - const XEMParameter ** iParameter = strategyInit.getTabInitParameter(); - for (int64_t i=0; i<_nbInitParameter; i++){ - _tabInitParameter[i] = (iParameter[i])->clone(); - } - } - - _deleteTabParameter= false; // TODO ? - - _nbTry = strategyInit.getNbTry(); - _nbIteration = strategyInit.getNbIteration(); - _epsilon = strategyInit.getEpsilon(); - _stopName = strategyInit.getStopName(); - -} - - - - -//----------- -// Destructor -//----------- -XEMClusteringStrategyInit::~XEMClusteringStrategyInit(){ - int64_t i; - if (_tabInitParameter && _deleteTabParameter){ - for (i=0; i<_nbInitParameter; i++){ - delete _tabInitParameter[i]; - } - delete [] _tabInitParameter; - _tabInitParameter = NULL; - } - - if (_tabPartition){ - for (i=0; i<_nbPartition; i++){ - delete _tabPartition[i]; - _tabPartition[i] = NULL; - } - delete [] _tabPartition; - _tabPartition = NULL; - } -} - - - -//--------------------- -// setStrategyInitName -//--------------------- -void XEMClusteringStrategyInit::setStrategyInitName(XEMStrategyInitName initName){ - - // delete ? - int64_t i; - if (_tabInitParameter && _deleteTabParameter){ - for (i=0; i<_nbInitParameter; i++){ - delete _tabInitParameter[i]; - } - delete [] _tabInitParameter; - _tabInitParameter = NULL; - } - - if (_tabPartition){ - for (i=0; i<_nbPartition; i++){ - delete _tabPartition[i]; - _tabPartition[i] = NULL; - } - delete [] _tabPartition; - _tabPartition = NULL; - } - - // - _strategyInitName = initName; - _nbInitParameter = 0; - _tabInitParameter = NULL; - _nbPartition = 0; - _tabPartition = NULL; - _deleteTabParameter= false; - - _nbTry = defaultNbTryInInit; - _nbIteration = defaultNbIterationInInit; - if (_strategyInitName == SEM_MAX){ - _nbIteration = defaultNbIterationInInitForSemMax; - setStopName(NBITERATION); - } - if (_strategyInitName == USER || _strategyInitName == USER_PARTITION){ - _nbTry = 1; - } - _epsilon = defaultEpsilonInInit; - -} - - - - -//------------------- -// set init parameter -//------------------- -void XEMClusteringStrategyInit::setInitParam(string & paramFileName, int64_t position){ - ifstream paramFile(paramFileName.c_str(), ios::in); - if (! paramFile.is_open()){ - throw wrongParamFileName; - } - if (_tabInitParameter != NULL){ - _tabInitParameter[position]->input(paramFile); - paramFile.close(); - } - else{ - throw internalMixmodError; - } -} - - - -//---------------- -// setTabInitParam -//---------------- -void XEMClusteringStrategyInit::setTabInitParameter(XEMParameter ** tabInitParameter, int64_t nbInitParameter){ - int64_t i; - if (_tabInitParameter && _deleteTabParameter){ - for (i=0; i<_nbInitParameter; i++){ - delete _tabInitParameter[i]; - } - delete [] _tabInitParameter; - _tabInitParameter = NULL; - } - - _tabInitParameter = tabInitParameter; - _nbInitParameter = nbInitParameter; -} - - - - -//------------------ -//set Init Partition -//------------------ -void XEMClusteringStrategyInit::setPartition(XEMPartition * part, int64_t position){ - if (part != NULL && _tabPartition!=NULL){ - _tabPartition[position] = part; - } - else{ - throw internalMixmodError; - } -} - - -//------------------ -//set Init Partition -//---------------- -void XEMClusteringStrategyInit::setPartition(string & partitionFileName, int64_t position){ - ifstream partitionFile(partitionFileName.c_str(), ios::in); - if (! partitionFile.is_open()){ - throw wrongPartitionFileName; - } - try{ - partitionFile>>(*_tabPartition[position]); - partitionFile.close(); - }catch(XEMErrorType errorType){ - throw badInitPart; - } -} - - - -//---------------- -// setTabPartition -//---------------- -void XEMClusteringStrategyInit::setTabPartition(XEMPartition ** tabPartition, int64_t nbPartition){ - int64_t i; - if (_tabPartition){ - for (i=0; i<_nbPartition; i++){ - delete _tabPartition[i]; - _tabPartition[i] = NULL; - } - delete [] _tabPartition; - _tabPartition = NULL; - } - - _tabPartition = tabPartition; - _nbPartition = nbPartition; -} - - -//------------ -// setStopName -//------------- -void XEMClusteringStrategyInit::setStopName(XEMAlgoStopName stopName){ - if (_strategyInitName == SMALL_EM){ - _stopName = stopName; - }else if (_strategyInitName == SEM_MAX && stopName==NBITERATION){ - _stopName = NBITERATION; - }else{ - throw badSetStopNameInInit; - } -} - - - -//--------- -// setNbTry -//--------- -void XEMClusteringStrategyInit::setNbTry(int64_t nbTry){ - if (_strategyInitName==SMALL_EM || _strategyInitName==CEM_INIT || _strategyInitName==RANDOM){ - if (nbTry > maxNbTryInInit){ - throw nbTryInInitTooLarge; - } - else if (nbTry < minNbTryInInit){ - throw nbTryInInitTooSmall; - } - else{ - _nbTry = nbTry; - } - } - else{ - throw badSetNbTryInInit; - } -} - - - -//---------------- -// set NbIteration -//---------------- -void XEMClusteringStrategyInit::setNbIteration(int64_t nbIteration){ - if (_strategyInitName==SMALL_EM || _strategyInitName==SEM_MAX){ - if (nbIteration > maxNbIterationInInit){ - throw nbIterationInInitTooLarge; - } - else if (nbIteration < minNbIterationInInit){ - throw nbIterationInInitTooSmall; - } - else{ - _nbIteration = nbIteration; - } - } - else{ - throw badSetNbIterationInInit; - } -} - - -//----------- -// setEpsilon -//----------- -void XEMClusteringStrategyInit::setEpsilon(double epsilon){ - if (_strategyInitName==SMALL_EM){ - if (epsilon > maxEpsilonInInit){ - throw epsilonInInitTooLarge; - } - else if (epsilon < minEpsilonInInit){ - throw epsilonInInitTooSmall; - } - else{ - _epsilon = epsilon; - } - } - else{ - throw badSetEpsilonInInit; - } -} - - - -//------- -// verify -//------- -bool XEMClusteringStrategyInit::verify() const{ - bool res = true; - //if init is USER or PARTITION, nbTry must be 1 - if ((_strategyInitName == USER_PARTITION || _strategyInitName == USER_PARTITION) && _nbTry != 1){ - res = false; - throw wrongNbStrategyTryValue; - } - - return res; -} - - - - -// input -void XEMClusteringStrategyInit::input(ifstream & fi, XEMData *& data, int64_t nbNbCluster, int64_t * tabNbCluster, XEMModelType * modelType, bool & alreadyRead){ - string keyWord = ""; - string a =""; - int64_t k; - int64_t pbDimension = data->_pbDimension; - int64_t nbSample = data->_nbSample; - - moveUntilReach(fi,"inittype"); - if(!fi.eof()){ - - fi >> a; - if (a.compare("RANDOM")==0){ - setStrategyInitName(RANDOM); - // nbTryInInit - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if(keyWord.compare("nbtryininit")==0){ - int64_t nbTry; - fi>>nbTry; - setNbTry(nbTry); - } - else{ - alreadyRead = true; - } - } - - // USER init type // - else if (a.compare("USER")==0){ - setStrategyInitName(USER); - - // tabInitFileName - fi >> keyWord; - ConvertBigtoLowString(keyWord); - - if(keyWord.compare("initfile")==0){ - // _strategyInit->_nbInitParameter = nbNbCluster; - XEMParameter ** tabInitParameter = new XEMParameter * [nbNbCluster]; - string * tabFileName = new string[nbNbCluster]; - for (k=0; k_nameModel)){ - tabInitParameter[k] = new XEMGaussianGeneralParameter(tabNbCluster[k], pbDimension, modelType, tabFileName[k]); - } - else if (isBinary(modelType->_nameModel)){ - int64_t * tabNbModality = ((XEMBinaryData*)data)->getTabNbModality(); - tabInitParameter[k] = new XEMBinaryEkjhParameter(tabNbCluster[k], pbDimension, modelType, tabNbModality, tabFileName[k]); - } - else if (isHD(modelType->_nameModel)){ - tabInitParameter[k] = new XEMGaussianHDDAParameter(tabNbCluster[k], pbDimension, modelType, tabFileName[k]); - } - else throw internalMixmodError; - } - setTabInitParameter(tabInitParameter, nbNbCluster); - delete[] tabFileName; - } - else{ - throw errorInitFile; - } - } - - // USER_PARTITION init type // - - else if (a.compare("USER_PARTITION")==0){ - setStrategyInitName(USER_PARTITION); - - //label - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if(keyWord.compare("initfile")==0){ - //_strategyInit->_nbPartition = nbNbCluster; - XEMPartition ** tabPartition = new XEMPartition * [nbNbCluster]; - string * tabFileName = new string[nbNbCluster]; - for (k=0; k>keyWord; - ConvertBigtoLowString(keyWord); - if(keyWord.compare("nbtryininit")==0){ - int64_t nbTry; - fi>>nbTry; - setNbTry(nbTry); - } - else{ - alreadyRead = true; - } - - bool nbIteration = false; - bool epsilon = false; - //nbIterationInInit - if (!alreadyRead){ - fi>>keyWord; - } - ConvertBigtoLowString(keyWord); - if(keyWord.compare("nbiterationininit")==0){ - nbIteration = true; - int64_t nbIteration; - fi>>nbIteration; - setNbIteration(nbIteration); - alreadyRead = false; - } - else{ - alreadyRead = true; - } - - //epsilonInInit - if (!alreadyRead){ - fi>>keyWord; - alreadyRead = false; - } - ConvertBigtoLowString(keyWord); - if(keyWord.compare("epsilonininit")==0){ - epsilon = true; - double epsilon; - fi>>epsilon; - setEpsilon(epsilon); - alreadyRead = false; - } - else{ - alreadyRead = true; - } - if (nbIteration && epsilon){ - setStopName(NBITERATION_EPSILON); - } - if (nbIteration && !epsilon){ - setStopName(NBITERATION); - } - if (!nbIteration && epsilon){ - setStopName(EPSILON); - } - if (!nbIteration && !epsilon){ - setStopName(NBITERATION_EPSILON); - } - } - - else if (a.compare("CEM_INIT")==0){ - setStrategyInitName(CEM_INIT); - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if(keyWord.compare("nbtryininit")==0){ - int64_t nbTry; - fi>>nbTry; - setNbTry(nbTry); - } - else{ - alreadyRead = true; - } - } - - else if (a.compare("SEM_MAX")==0){ - setStrategyInitName(SEM_MAX); - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if(keyWord.compare("nbiterationininit")==0){ - int64_t nbIteration; - fi>>nbIteration; - setNbIteration(nbIteration); - } - else{ - alreadyRead = true; - } - } - - else{ - throw wrongStrategyInitName; - } - } -} - - - - - - -// ostream << -//----------- -ostream & operator << (ostream & fo, XEMClusteringStrategyInit & strategyInit){ - //strategyInitType - string init = XEMStrategyInitNameToString(strategyInit._strategyInitName); - fo<<"\t strategyInitName : "<. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMClusteringStrategyInit_H -#define XEMClusteringStrategyInit_H - -#include "XEMUtil.h" -#include "XEMParameter.h" -#include "XEMPartition.h" - -/** - @brief Base class for StrategyInitType(s) - @author F Langrognet -*/ - -class XEMClusteringStrategyInit{ - - public: - - /// Default constructor - XEMClusteringStrategyInit(); - - /// Copy constructor - XEMClusteringStrategyInit(const XEMClusteringStrategyInit & strategyInit); - - /// Destructor - virtual ~XEMClusteringStrategyInit(); - - - /// getStrategyInitName - const XEMStrategyInitName & getStrategyInitName() const; - - /// setStrategyInitName - void setStrategyInitName(XEMStrategyInitName initName); - - - - /// getNbTry - const int64_t getNbTry() const; - - /// setNbTry - void setNbTry(int64_t nbTry); - - - - /// getNbIteration - const int64_t getNbIteration() const; - - /// set NbIteration - void setNbIteration(int64_t nbIteration); - - - - /// getEpsilon - const double getEpsilon() const; - - /// setEpsilon - void setEpsilon(double epsilon); - - - /// getStopName - const XEMAlgoStopName getStopName() const; - - /// setStopName - void setStopName(XEMAlgoStopName stopName); - - /* Parameter */ - //-----------// - /// getNbInitParameter - const int64_t & getNbInitParameter() const; - - /// getTabInitParameter - const XEMParameter ** getTabInitParameter() const; - - /// getTabInitParameter - XEMParameter * getInitParameter(int64_t index) const; - - /// setInitParam - void setInitParam(string & paramFileName, int64_t position); - - /// setTabInitParam - void setTabInitParameter(XEMParameter ** tabInitParameter, int64_t nbInitParameter); - - - /* Partition */ - //-----------// - /// getNbPartition - const int64_t & getNbPartition() const; - - /// getTabPartition - const XEMPartition ** getTabPartition() const; - - /// getTabPartition - XEMPartition * getPartition(int64_t index) const; - - ///set Init Partition - void setPartition(XEMPartition * part, int64_t position); - - ///set Init Partition - void setPartition(string & paramFileName, int64_t position); - - /// setTabPartition - void setTabPartition(XEMPartition ** tabPartition, int64_t nbPartition); - - - // input - void input(ifstream & fi,XEMData *& data, int64_t nbNbCluster, int64_t * tabNbCluster, XEMModelType * modelType, bool & alreadyRead); - - bool verify() const; - - - friend ostream & operator << (ostream & fo, XEMClusteringStrategyInit & strategyInit); - - //friend class XEMStrategy; - - - private : - - /// Initialization strategy type - XEMStrategyInitName _strategyInitName; - - /// nbTry - int64_t _nbTry; - - /// stopName (for smallEm & sem_max) - XEMAlgoStopName _stopName; - - /// nbIteration - int64_t _nbIteration; - - /// epsilon - double _epsilon; - - - /* USER */ - /// number of InitParameter - int64_t _nbInitParameter; - - /// Init Parameters to initialize strategy - XEMParameter ** _tabInitParameter; - - - /* USER_PARTITION */ - /// number of Partition - int64_t _nbPartition; - - /// Labels to initialize strategy - XEMPartition ** _tabPartition; - - - bool _deleteTabParameter ; - -}; - -inline const XEMStrategyInitName & XEMClusteringStrategyInit::getStrategyInitName() const{ - return _strategyInitName; -} - -inline const XEMAlgoStopName XEMClusteringStrategyInit::getStopName() const{ - return _stopName; -} - -inline const int64_t & XEMClusteringStrategyInit::getNbInitParameter() const{ - return _nbInitParameter; -} - -inline const int64_t & XEMClusteringStrategyInit::getNbPartition() const{ - return _nbPartition; -} - -inline const XEMParameter ** XEMClusteringStrategyInit::getTabInitParameter() const{ - return const_cast(_tabInitParameter); -} - -inline XEMParameter * XEMClusteringStrategyInit::getInitParameter(int64_t index) const{ - return _tabInitParameter[index]; -} - -inline const XEMPartition** XEMClusteringStrategyInit::getTabPartition() const{ - return const_cast(_tabPartition); -} - -inline XEMPartition* XEMClusteringStrategyInit::getPartition(int64_t index) const{ - return _tabPartition[index]; -} - - -inline const int64_t XEMClusteringStrategyInit::getNbTry() const{ - return _nbTry; -} - -inline const int64_t XEMClusteringStrategyInit::getNbIteration() const{ - return _nbIteration; -} - -inline const double XEMClusteringStrategyInit::getEpsilon() const{ - return _epsilon; -} - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMColumnDescription.cpp b/lib/src/mixmod/MIXMOD/XEMColumnDescription.cpp deleted file mode 100644 index 38b5b1e..0000000 --- a/lib/src/mixmod/MIXMOD/XEMColumnDescription.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMColumnDescription.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#include "XEMColumnDescription.h" - -//------------ -// Constructor -//------------ -XEMColumnDescription::XEMColumnDescription():_index(0), _name(""){ -} - - -//------------ -// Initialization Constructor -//------------ -XEMColumnDescription::XEMColumnDescription(int64_t index):_index(index), _name(""){ -} - -//------------ -// Destructor -//------------ -XEMColumnDescription::~XEMColumnDescription(){ - -} diff --git a/lib/src/mixmod/MIXMOD/XEMColumnDescription.h b/lib/src/mixmod/MIXMOD/XEMColumnDescription.h deleted file mode 100644 index 6b53321..0000000 --- a/lib/src/mixmod/MIXMOD/XEMColumnDescription.h +++ /dev/null @@ -1,81 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMColumnDescription.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMCOLUMNDESCRIPTION_H -#define XEMCOLUMNDESCRIPTION_H - -#include "XEMUtil.h" - -class XEMColumnDescription -{ - public : - /// Default constructor - XEMColumnDescription(); - - /// Initialization constructor - XEMColumnDescription(int64_t index); - - /// Destructor - virtual ~XEMColumnDescription(); - - // - virtual string editType()=0; - - - virtual XEMColumnDescription * clone()const = 0; - - ///selector - - ///get index of column - const int64_t & getIndex()const ; - - ///get name of column - const string & getName()const; - - ///set name of column - void setName(string & strName); - - protected : - - ///index of column (0 to XEMDataDescription::_nbColumn-1) - int64_t _index; - - ///name of column (optional) - string _name; -}; - -inline const int64_t & XEMColumnDescription::getIndex()const{ - return _index; -} - -inline const string & XEMColumnDescription::getName()const{ - return _name; -} - -inline void XEMColumnDescription::setName(string & strName){ - _name = strName; -} - - -#endif // XEMCOLUMNDESCRIPTION_H diff --git a/lib/src/mixmod/MIXMOD/XEMCondExe.cpp b/lib/src/mixmod/MIXMOD/XEMCondExe.cpp deleted file mode 100644 index 14828e2..0000000 --- a/lib/src/mixmod/MIXMOD/XEMCondExe.cpp +++ /dev/null @@ -1,251 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMCondExe.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMCondExe.h" -#include "XEMUtil.h" -#include "XEMClusteringOutput.h" -#include - -//------------ -// Constructor -//------------ -// Default constructor -XEMCondExe::XEMCondExe(){ - _data = NULL; - _weight = NULL; - _nbSample = 0; - _pbDimension = 0; - _nbNbCluster = 0; - _tabNbCluster = NULL; - _nbCriterion = 0; - _tabCriterionName = NULL; - _nbModel = 0; - _tabModel = NULL; - _strategy = NULL; - _cStrategy = NULL; - _knownPartition = NULL; - _tabEstimationError = NULL; - _tabCriterionError = NULL; - _tabSelectionError = NULL; - _errorMixmod = noError; -} - - - -//------------ -// Constructor -//------------ -XEMCondExe::XEMCondExe(XEMOldInput * input, XEMEstimation ** tabEstimation, int64_t nbEstimation){ - int64_t i,j; - - if (input == NULL || tabEstimation == NULL || nbEstimation < 1) - throw internalMixmodError; - - _data = input->_data; - _weight = _data->_weight; - _nbSample = input->_nbSample; - _weightTotal = input->_data->_weightTotal; - _pbDimension = input->_pbDimension; - _nbNbCluster = input->_nbNbCluster; - _tabNbCluster = input->_tabNbCluster; - _nbCriterion = input->_nbCriterionName; - _tabCriterionName = input->_tabCriterionName; - _nbModel = input->_nbModelType; - _tabModel = input->_tabModelType; - XEMStrategy ** tabStra = input->_tabStrategy; - _strategy = tabStra[0]; - _cStrategy = NULL; - - XEMPartition ** tabKnownPartition = input->_tabKnownPartition; - if (tabKnownPartition){ - _knownPartition = tabKnownPartition[0]; - } - else{ - _knownPartition = NULL; - } - - // _errorMixmod - _errorMixmod = noError; - - // _tabEstimationError - _tabEstimationError = new XEMErrorType[nbEstimation]; - for (i=0; igetNbClusteringModelOutput(); - - // if (input == NULL || tabEstimation == NULL || nbEstimation < 1) - // throw internalMixmodError; - - _data = (input->getDataDescription()).getData(); - _weight = _data->_weight; - _nbSample = input->getNbSample(); - _weightTotal = _data->_weightTotal; - _pbDimension = input->getPbDimension(); - vector vNbCluster = input->getNbCluster(); - _nbNbCluster = vNbCluster.size(); - _tabNbCluster = new int64_t[_nbNbCluster]; - for (int64_t i=0; i<_nbNbCluster; i++){ - _tabNbCluster[i] = vNbCluster[i]; - } - _nbCriterion = input->getNbCriterionName(); - _tabCriterionName = new XEMCriterionName[_nbCriterion]; - for (int64_t i=0; i<_nbCriterion; i++){ - _tabCriterionName[i] = input->getCriterionName(i); - } - _nbModel = input->getNbModelType(); - _tabModel = new XEMModelType*[_nbModel]; - for (int64_t i=0; i<_nbModel; i++){ - _tabModel[i] = input->getModelType(i); - } - - _strategy=NULL; - _cStrategy = input->getStrategy(); - - _knownPartition = input->getKnownPartition(); - - // _errorMixmod - _errorMixmod = noError; - - // _tabEstimationError - _tabEstimationError = new XEMErrorType[nbEstimation]; - for (i=0; igetClusteringModelOutput(i); - _tabEstimationError[i] = cMOutput->getStrategyRunError(); - } - - // _tabSelectionError - _tabSelectionError = new XEMErrorType[_nbCriterion]; - for (i=0; i<_nbCriterion; i++){ - _tabSelectionError[i] = noError; - } - - _tabCriterionError = new XEMErrorType*[_nbCriterion]; - for(i=0; i<_nbCriterion; i++){ - _tabCriterionError[i] = new XEMErrorType[nbEstimation]; - for (j=0; jgetClusteringModelOutput(j); - _tabCriterionError[i][j] = cMOutput->getStrategyRunError(); - if (_tabCriterionError[i][j] == noError){ - _tabCriterionError[i][j] = cMOutput->getEstimation()->getCriterionOutput(i).getError(); - } - } - } - -} - - -//---------- -//Destructor -//---------- -XEMCondExe::~XEMCondExe(){ - int64_t i; - - if (_tabEstimationError){ - delete [] _tabEstimationError; - } - if (_tabSelectionError){ - delete [] _tabSelectionError; - } - if (_tabCriterionError){ - for(i=0; i<_nbCriterion;i++){ - delete[] _tabCriterionError[i]; - _tabCriterionError[i] = NULL; - } - delete [] _tabCriterionError; - } -} - - - -//----------------------- -// editTabEstimationError -//----------------------- -void XEMCondExe::editTabEstimationError(ofstream & oFile){ - int64_t i; - int64_t n = _nbNbCluster*_nbModel; - for (i=0; igetErrorType(); - } - for (i=0; igetErrorType(); - } - for (i=0; igetCriterionErrorType(j); - _tabCriterionError[i][j] = criterionErrorType; - } - } - -} diff --git a/lib/src/mixmod/MIXMOD/XEMCondExe.h b/lib/src/mixmod/MIXMOD/XEMCondExe.h deleted file mode 100644 index 640f60b..0000000 --- a/lib/src/mixmod/MIXMOD/XEMCondExe.h +++ /dev/null @@ -1,121 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMCondExe.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMCondExe_H -#define XEMCondExe_H - -#include "XEMUtil.h" -#include "XEMOldInput.h" -#include "XEMClusteringInput.h" -#include "XEMEstimation.h" -#include "XEMSelection.h" -class XEMClusteringOutput; - -/** - @brief Base class for XEMCondExe(s) - @author F Langrognet & A Echenim -*/ - -class XEMCondExe{ - - public: - - /// Default constructor - XEMCondExe(); - - /// constructor - XEMCondExe(XEMOldInput * input, XEMEstimation ** tabEstimation, int64_t nbEstimation); - - /// constructor - XEMCondExe(XEMClusteringInput * input, XEMClusteringOutput * clusteringOutput); - - /// Destructor - virtual ~XEMCondExe(); - - - /// editTabEstimationError - void editTabEstimationError(ofstream & oFile); - - /// editTabCriterionError - void editTabCriterionError(ofstream & oFile, int64_t iCrit); - - ///update - void update(int64_t nbEstimation, XEMEstimation ** tabEstimation, int64_t nbSelection, XEMSelection ** tabSelection); - - - /// data - XEMData * _data; - - /// weight - double * _weight; - - /// Number of (different) samples - int64_t _nbSample; - - ///Weight total (number of all samples) - double _weightTotal; - - /// Problem dimension - int64_t _pbDimension; - - /// Number of numbers of cluster - int64_t _nbNbCluster; - - /// Table of numbers of cluster - int64_t * _tabNbCluster; - - /// Number of criteria - int64_t _nbCriterion; - - /// Table of criterion name - XEMCriterionName * _tabCriterionName; - - /// Number of models - int64_t _nbModel; - - /// Table of model type - XEMModelType ** _tabModel; - - /// Strategy - XEMStrategy * _strategy; - /// Strategy - XEMClusteringStrategy * _cStrategy; - - /// knownPartition - XEMPartition * _knownPartition; - - /// Error code for each estimation (nbModel * nbNbCluster) - XEMErrorType * _tabEstimationError; - - /// Error code for each selection (size : nbCriterion) - XEMErrorType * _tabSelectionError; - - /// Error code for each criterion and for each estimation : table in 2 dimensions - XEMErrorType ** _tabCriterionError; - - /// Global Mixmod Error - XEMErrorType _errorMixmod; - -}; -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMCriterion.cpp b/lib/src/mixmod/MIXMOD/XEMCriterion.cpp deleted file mode 100644 index d67ac54..0000000 --- a/lib/src/mixmod/MIXMOD/XEMCriterion.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMCriterion.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMCriterion.h" - - -//----------- -//Constructor -//----------- -XEMCriterion::XEMCriterion(){ -} - - - - - -//---------- -//Destructor -//---------- -XEMCriterion::~XEMCriterion(){ -} - - - - - - diff --git a/lib/src/mixmod/MIXMOD/XEMCriterion.h b/lib/src/mixmod/MIXMOD/XEMCriterion.h deleted file mode 100644 index 4418b99..0000000 --- a/lib/src/mixmod/MIXMOD/XEMCriterion.h +++ /dev/null @@ -1,78 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMCriterion.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMCriterion_H -#define XEMCriterion_H - -#include "XEMModel.h" -#include - - -/** - @brief Base class for Criterion - @author F Langrognet & A Echenim -*/ - -//----------------------------------- -// best value are always the samllest -//----------------------------------- - -class XEMCriterion{ - - public: - - /// Default constructor - XEMCriterion(); - - /// Destructor - virtual ~XEMCriterion(); - - - /**@brief Selector - @return The value of the criterion - */ - double getValue(); - - - /** @brief Set the error type criterion - @param errorType Type of error to set - */ - void setErrorType(XEMErrorType errorType); - - /** @brief Selector - @return The type of the error - */ - XEMErrorType getErrorType(); - - virtual XEMCriterionName getCriterionName()const=0 ; - - /// Run method - virtual void run(XEMModel * model, double & value, XEMErrorType & error, bool quiet=true)=0; - - -}; - - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMCriterionOutput.cpp b/lib/src/mixmod/MIXMOD/XEMCriterionOutput.cpp deleted file mode 100644 index 95e9966..0000000 --- a/lib/src/mixmod/MIXMOD/XEMCriterionOutput.cpp +++ /dev/null @@ -1,144 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMCriterionOutput.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMCriterionOutput.h" - - -//------------ -// Constructor -//------------ -XEMCriterionOutput::XEMCriterionOutput(){ - _criterionName = UNKNOWN_CRITERION_NAME; - _value = 0; - _error = noError; -} - -//------------ -// Constructor -//------------ -XEMCriterionOutput::XEMCriterionOutput(XEMCriterionName criterionName){ - _value = 0;; - _criterionName = criterionName; - _error = noError; -} - - -//------------ -// Constructor -//------------ -XEMCriterionOutput::XEMCriterionOutput(XEMCriterionName criterionName, double criterionValue, XEMErrorType criterionErrorType){ - _value = criterionValue; - _criterionName = criterionName; - _error = criterionErrorType; -} - - -//----------- -// Destructor -//----------- -XEMCriterionOutput::~XEMCriterionOutput(){ -} - - - -//---------- -// edit Type -//---------- -void XEMCriterionOutput::editType(ofstream & oFile){ - oFile<<"Criterion Name : "; - if (_criterionName == BIC){ - oFile<<"BIC"; - } - else if (_criterionName == CV){ - oFile<<"CV"; - } - else if (_criterionName == DCV){ - oFile<<"DCV"; - } - else if (_criterionName == NEC){ - oFile<<"NEC"; - } - else if (_criterionName == ICL){ - oFile<<"ICL"; - } - oFile<>>>>>>>>>" << << endl; - oFile<<"numeric Error"<. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMCriterionOutput_H -#define XEMCriterionOutput_H - -#include "XEMUtil.h" -#include "XEMCriterion.h" - - - -/** @brief Base class for Label(s) - @author F Langrognet & A Echenim -*/ - -class XEMCriterionOutput{ - - public: - - /// Default constructor - XEMCriterionOutput(); - - /// constructor - XEMCriterionOutput(XEMCriterionName criterionName); - - /// Constructor - XEMCriterionOutput(XEMCriterionName criterionName, double criterionValue, XEMErrorType criterionErrorType); - - /// Destructor - virtual ~XEMCriterionOutput(); - - ///editType - void editType(ofstream & oFile); - - ///editValue - void editValue(ofstream & oFile, bool text=false); - - /// editTypeAndValue - void editTypeAndValue(ofstream & oFile); - - //-------------- - // get - //-------------- - /// getCriterionName - XEMCriterionName getCriterionName() const; - - /// getValue - double getValue() const; - - /// getError - XEMErrorType getError() const; - - //-------------- - // set - //-------------- - /// setCriterionName - void setCriterionName(XEMCriterionName criterionName); - - /// setValue - void setValue(double value); - - /// setError - void setError(XEMErrorType e); - - - //------ - private : - //------ - /// Criterion value - double _value; - - /// Error type in calculation of criterion value - XEMErrorType _error; - - /// criterion name - XEMCriterionName _criterionName; - - -}; - -inline XEMCriterionName XEMCriterionOutput::getCriterionName() const{ - return _criterionName; -} - -inline double XEMCriterionOutput::getValue() const{ - return _value; -} - -inline XEMErrorType XEMCriterionOutput::getError() const{ - return _error; -} - - -inline void XEMCriterionOutput::setCriterionName(XEMCriterionName criterionName){ - _criterionName = criterionName; -} - -inline void XEMCriterionOutput::setValue(double value){ - _value = value; -} - -inline void XEMCriterionOutput::setError(XEMErrorType e){ - _error = e; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMDCVCriterion.cpp b/lib/src/mixmod/MIXMOD/XEMDCVCriterion.cpp deleted file mode 100644 index d3d1b5a..0000000 --- a/lib/src/mixmod/MIXMOD/XEMDCVCriterion.cpp +++ /dev/null @@ -1,896 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMDCVCriterion.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMDCVCriterion.h" -#include "XEMGaussianSample.h" -#include "XEMMain.h" -#include - -// Defaul constructor : never used -XEMDCVCriterion::XEMDCVCriterion(){ - _tabLearningBlock = NULL; - _tabTestBlock = NULL; - _originalInput = NULL; - _tabCriterionValueForEachEstimation = NULL; - _tabCriterionErrorForEachEstimation = NULL; - _tabDCVErrorForEachEstimation = NULL; - _tabEstimation = NULL; - _tabIndexOfBestEstimation = NULL; - _tabCVValueOnBestModel = NULL; - - _data = NULL; - _weight = NULL; - _weightTotal = 0; - _value = 0; - - _DCVinitBlocks = defaultDCVinitBlocks; -} - - -XEMDCVCriterion::XEMDCVCriterion(XEMEstimation **& tabEstimation, int64_t nbEstimation, XEMOldInput * originalInput){ - - _value = 0; - _originalInput = originalInput; - _tabEstimation = tabEstimation, - _nbEstimation = nbEstimation; - - _tabCriterionValueForEachEstimation = new double[_nbEstimation]; - _tabCriterionErrorForEachEstimation = new XEMErrorType[_nbEstimation]; - - - _DCVinitBlocks = originalInput->_DCVinitBlocks; - _nbDCVBlock = originalInput->_numberOfDCVBlocks; - _tabDCVErrorForEachEstimation = new XEMErrorType[_nbDCVBlock]; - // _nbDCVBlock is initialzed to the numberOfDCVBlocks that the user wanted (issued from input)(or the default value) - // this value could chane if nbSample is too small (will be done in createDCVBlock) - - if (nbEstimation > 0){ - _data = tabEstimation[0]->getData(); - _weight = _data->_weight; - _weightTotal = _data->_weightTotal; - if (_weightTotal-_data->_weightTotal != 0){ - throw weightTotalIsNotAnInteger; - } - } - else{ - throw internalMixmodError; - } - - - _tabIndexOfBestEstimation = new int64_t [_nbDCVBlock]; - _tabCVValueOnBestModel = new double[_nbDCVBlock]; -} - - - -XEMDCVCriterion::~XEMDCVCriterion(){ - if (_tabTestBlock){ - for (int64_t v=0; v<_nbDCVBlock; v++){ - delete [] _tabTestBlock[v]._tabWeightedIndividual; - } - delete [] _tabTestBlock; - _tabTestBlock = NULL; - } - - if (_tabLearningBlock){ - for (int64_t v=0; v<_nbDCVBlock; v++){ - delete [] _tabLearningBlock[v]._tabWeightedIndividual; - } - delete [] _tabLearningBlock; - _tabLearningBlock = NULL; - } - - if (_tabIndexOfBestEstimation){ - delete [] _tabIndexOfBestEstimation; - } - - if (_tabCVValueOnBestModel){ - delete [] _tabCVValueOnBestModel; - } - - if (_tabCriterionValueForEachEstimation){ - delete [] _tabCriterionValueForEachEstimation; - } - - if (_tabCriterionErrorForEachEstimation){ - delete [] _tabCriterionErrorForEachEstimation; - } - - if (_tabDCVErrorForEachEstimation){ - delete [] _tabDCVErrorForEachEstimation; - } -} - - - - -//--------- -// setModel -//--------- -void XEMDCVCriterion::setModel(XEMModel * model){ - throw internalMixmodError; -} - - - -//----------- -// getCVLabelOfBestEstimation -//----------- -/*int64_t * XEMDCVCriterion::getCVLabelOfBestEstimation(){ - int64_t i; - int64_t nbSample = _originalInput->getNbSample(); - int64_t * res = new int64_t[nbSample]; - for (i=0; igetErrorType(); - //cout<<"error for "<getErrorType()<getErrorType(); - if (selectionStepVError == errorAllEstimation){ - for (i=0; i<_nbEstimation; i++){ - nbErrorForEachEstimation[i]++; - } - } - } - - _tabDCVErrorForEachEstimation[v] = selectionStepVError; - //cout<<_tabDCVErrorForEachEstimation[v]<getTabCriterionValueForEachEstimation(); - tabCriterionErrorForEachEstimationStepV = selectionStepV->getTabCriterionErrorForEachEstimation(); - for (i=0; i<_nbEstimation; i++){ - //cout<<"block "<getBestIndexEstimation(); - - - if ( _tabDCVErrorForEachEstimation[v] == noError){ - bestEstimationStepV = _tabEstimation[_tabIndexOfBestEstimation[v]]; - //bestModelTypeStepV = bestEstimationStepV->getModelType(); - bestModelStepV = bestEstimationStepV->getModel(); // the best model - NbClusterOfBestModelV = bestModelStepV->getNbCluster(); - // search rankOfNbClusterOfBestModelV - for (rankOfNbClusterOfBestModelV=0; rankOfNbClusterOfBestModelV<_originalInput->_nbNbCluster; rankOfNbClusterOfBestModelV++){ - if (NbClusterOfBestModelV == _originalInput->_tabNbCluster[rankOfNbClusterOfBestModelV]) break; - } - knownPartitionForBestModelV = _originalInput->_tabKnownPartition[rankOfNbClusterOfBestModelV]; - _tabCVValueOnBestModel[v] = 0; - - - for (int64_t ii=0; ii<_tabTestBlock[v]._nbSample; ii++){ - i = _tabTestBlock[v]._tabWeightedIndividual[ii].val; // i : ith sample in the original data - - curSample = _data->_matrix[i]; - int64_t computedLabelForCurSampleOnBestModelStepV = bestModelStepV->computeLabel(curSample); - known_ki = knownPartitionForBestModelV->getGroupNumber(i); - - // cout<<"known label : "<getModelType()); - - //for (i=0 ; i<_nbEstimation; i++){ - // cout<<"CV error rate for "<_nbSample; - - // each learning block must contains at least 10 individuals - if (_nbDCVBlock *10 >= _weightTotal){ - _nbDCVBlock = _weightTotal / 10; - } - // _nbDCVBlock must be > 1 - if (_nbDCVBlock <= 1) - throw NbDCVBlocksTooSmall; - //cout<<"_nbDCVBlock : "<<_nbDCVBlock< listTestBlock; - list listLearningBlock; - list::iterator listIterator; - list::iterator listBegin; - list::iterator listEnd; - sizeTestList = 0; - sizeLearningList = 0; - - if (remaining > 0){ - weightTotalInTestBlock++ ; - remaining--; - } - - lastIndexOfTestBlock = firstIndexOfTestBlock + weightTotalInTestBlock -1 ; - for (i=0; i<_weightTotal; i++){ - //cout<<"individu : "<= firstIndexOfTestBlock ) && (i <= lastIndexOfTestBlock)){ - // add individual tabIndex[i] in listTestBlock[v] - //--------------------------------------------- - //cout<<" dans listTestBlock"< (*listIterator)->val)){ - listIterator++; - } - // list empty // - if (listBegin==listEnd){ - TWeightedIndividual * elem = new TWeightedIndividual; - elem->val = value; - elem->weight = 1; - listTestBlock.push_front(elem); - sizeTestList++; - } - else{ - // if elemn in end of list // - if (listIterator==listEnd){ - listIterator--; - if ((*listIterator)->val==value) - (*listIterator)->weight += 1; - else{ - TWeightedIndividual * elem = new TWeightedIndividual; - elem->val = value; - elem->weight = 1; - listTestBlock.push_back(elem); - sizeTestList++; - } - } - // elemen in begin or in middle of list // - else{ - if ((*listIterator)->val==value) - (*listIterator)->weight += 1; - else{ - TWeightedIndividual * elem = new TWeightedIndividual; - elem->val = value; - elem->weight = 1; - - if (listIterator == listTestBlock.begin()) - listTestBlock.push_front(elem); - else - listTestBlock.insert(listIterator,1,elem); - - sizeTestList++; - } - } - } - - } - else{ - // add individual tabIndex[i] in listLearningBlock[v] - //--------------------------------------------------- - //cout<<" dans listLearningBlock"< (*listIterator)->val)){ - listIterator++; - } - // list empty // - if (listBegin==listEnd){ - TWeightedIndividual * elem = new TWeightedIndividual; - elem->val = value; - elem->weight = 1; - listLearningBlock.push_front(elem); - sizeLearningList++; - } - else{ - // if elemn in end of list // - if (listIterator==listEnd){ - listIterator--; - if ((*listIterator)->val==value) - (*listIterator)->weight += 1; - else{ - TWeightedIndividual * elem = new TWeightedIndividual; - elem->val = value; - elem->weight = 1; - listLearningBlock.push_back(elem); - sizeLearningList++; - } - } - // elemen in begin or in middle of list // - else{ - if ((*listIterator)->val==value) - (*listIterator)->weight += 1; - else{ - TWeightedIndividual * elem = new TWeightedIndividual; - elem->val = value; - elem->weight = 1; - - if (listIterator == listLearningBlock.begin()) - listLearningBlock.push_front(elem); - else - listLearningBlock.insert(listIterator,1,elem); - - sizeLearningList++; - } - } - } - - } - } // end for i - - firstIndexOfTestBlock = lastIndexOfTestBlock + 1; - - // update _tabTestBlock - //--------------------- - _tabTestBlock[v]._nbSample = sizeTestList; - _tabTestBlock[v]._weightTotal = weightTotalInTestBlock; - _tabTestBlock[v]._tabWeightedIndividual = new TWeightedIndividual[_tabTestBlock[v]._nbSample]; - - listBegin = listTestBlock.begin(); - listEnd = listTestBlock.end(); - listIterator = listBegin; - i=0; - while ( (listIterator != listEnd) && i<_tabTestBlock[v]._nbSample){ - _tabTestBlock[v]._tabWeightedIndividual[i].val = (*listIterator)->val; - _tabTestBlock[v]._tabWeightedIndividual[i].weight = (*listIterator)->weight; - listIterator++; - i++; - } - if (i != _tabTestBlock[v]._nbSample){ - //cout<<"cout erreur 1 ds XEMDCVCriterion"<val; - _tabLearningBlock[v]._tabWeightedIndividual[i].weight = (*listIterator)->weight; - listIterator++; - i++; - } - if (i != _tabLearningBlock[v]._nbSample){ - //cout<<"cout erreur 1 ds XEMDCVCriterion"< * listLearningBlock = new list [_nbDCVBlock]; - list * listTestBlock = new list [_nbDCVBlock]; - - list::iterator listIterator; - list::iterator listBegin; - list::iterator listEnd; - - int64_t v = 0; - int64_t i, w, nbTraited = 0; - - // Update listTestBlock[v] - for (i=0; i (*listIterator)->val)){ - listIterator++; - } - // list empty // - if (listBegin==listEnd){ - TWeightedIndividual * elem = new TWeightedIndividual; - elem->val = i; - elem->weight = 1; - listTestBlock[v].push_front(elem); - } - else{ - // if elemn in end of list // - if (listIterator==listEnd){ - listIterator--; - if ((*listIterator)->val==i) - (*listIterator)->weight += 1; - else{ - TWeightedIndividual * elem = new TWeightedIndividual; - elem->val = i; - elem->weight = 1; - listTestBlock[v].push_back(elem); - } - } - // elemen in begin or in middle of list // - else{ - if ((*listIterator)->val==i) - (*listIterator)->weight += 1; - else{ - TWeightedIndividual * elem = new TWeightedIndividual; - elem->val = i; - elem->weight = 1; - - if (listIterator == listTestBlock[v].begin()) - listTestBlock[v].push_front(elem); - else - listTestBlock[v].insert(listIterator,1,elem); - } - } - - } - - v++; - if (v == _nbDCVBlock){ - v = 0; - } - nbTraited++; - } - } - if (nbTraited != _weightTotal){ - //cout<<"cout erreur 1 ds XEMCVCriterion"<val<<" - poids : "<<(*listIterator)->weight<val; - _tabTestBlock[v]._tabWeightedIndividual[i].weight = (*listIterator)->weight; - weightTotalInTestBlockV += _tabTestBlock[v]._tabWeightedIndividual[i].weight; - listIterator++; - i++; - } - _tabTestBlock[v]._weightTotal = weightTotalInTestBlockV; - if (i != _tabTestBlock[v]._nbSample){ - //cout<<"cout erreur 2 ds XEMCVCriterion"< (*listIterator)->val)){ - cout<<" ds while : "<<(*listIterator)->val<val<val){ - search=false; - } - else{ - listIterator++; - } - } - - if (listIterator==listEnd){ - // i is not in listTestList[v] - weightOfCurrentIndividualInCurrentLearningBlock = _weight[i]; - } - else{ - // search=false - if (i == (*listIterator)->val){ - // i is in listTestList[v] - weightOfCurrentIndividualInCurrentLearningBlock = _weight[i] - (*listIterator)->weight ; - } - else{ - // i is not in listTestList[v] - weightOfCurrentIndividualInCurrentLearningBlock = _weight[i]; - } - } - - if (weightOfCurrentIndividualInCurrentLearningBlock != 0){ - // add i in listLearningBlock - TWeightedIndividual * elem = new TWeightedIndividual; - elem->val = i; - elem->weight = weightOfCurrentIndividualInCurrentLearningBlock; - listLearningBlock[v].push_back(elem); - } - - }// end for i - }// end for v - - // update _tabLearningBlock - //------------------------- - for (v=0; v<_nbDCVBlock; v++){ - _tabLearningBlock[v]._nbSample = listLearningBlock[v].size(); - _tabLearningBlock[v]._tabWeightedIndividual = new TWeightedIndividual[_tabLearningBlock[v]._nbSample]; - double weightTotalInTestBlockV = 0; - - listBegin = listLearningBlock[v].begin(); - listEnd = listLearningBlock[v].end(); - listIterator = listBegin; - i=0; - while ( (listIterator != listEnd) && i<_tabLearningBlock[v]._nbSample){ - /*cout<<"listLearning : indiv : "<<(*listIterator)->val<<" - poids : "<<(*listIterator)->weight<val; - _tabLearningBlock[v]._tabWeightedIndividual[i].weight = (*listIterator)->weight; - weightTotalInTestBlockV += _tabLearningBlock[v]._tabWeightedIndividual[i].weight; - listIterator++; - i++; - } - _tabLearningBlock[v]._weightTotal = weightTotalInTestBlockV; - if (i != _tabLearningBlock[v]._nbSample){ - //cout<<"cout erreur 2 ds XEMCVCriterion"<getModelType(), fi); - fi << "\n"<<"selected nbCluster : " << flush; - fi <<_tabEstimation[_tabIndexOfBestEstimation[v]]->getNbCluster() ; - fi << "\n" - << "error rate on test samples : " << _tabCVValueOnBestModel[v] << "\n" << endl; - fi << "----------------------------------------------------" << endl; - } - //fi << "----------------------------------------------------" << endl; - } -} - - - -//-------------------------- -// editNumeric -//-------------------------- -void XEMDCVCriterion::editNumeric(ofstream & fi){ - //number of blocks - fi <<_nbDCVBlock << "\n"; - - //average error rate - fi<< _value << "\n"; - - int64_t v; - fi<. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMDCVCriterion_H -#define XEMDCVCriterion_H - -#include "XEMOldInput.h" -#include "XEMRandom.h" -#include "XEMCriterion.h" -#include "XEMEstimation.h" - -/** - @brief Derived class of XEMCriterion for DCV Criterion - @author F Langrognet & A Echenim -*/ - -class XEMDCVCriterion : public XEMCriterion{ - - - public : - - /// Constructor - XEMDCVCriterion(); - - /// Constructor - XEMDCVCriterion(XEMEstimation **& tabEstimation, int64_t nbEstimation, XEMOldInput * originalInput); - - /// Destructor - virtual ~XEMDCVCriterion(); - - /**@brief setModel - @param iModel Base model - */ - void setModel(XEMModel * iModel); - - XEMCriterionName getCriterionName() const; - - /// Run method - void run(XEMModel * model, double & value, XEMErrorType & error, bool quiet=true); - - /// - double * getTabCriterionValueForEachEstimation(); - - /// - XEMErrorType * getTabCriterionErrorForEachEstimation(); - - - XEMErrorType * getTabDCVErrorForEachEstimation(); - /// - int64_t getBestIndexEstimation(); - - /// edit - void edit(ofstream & fi); - - /// editNumeric - void editNumeric(ofstream & fi); - - - private : - - /// Table of XEMCVBlock representing 'learning blocks' (S-Si) - XEMCVBlock * _tabLearningBlock; - - // number of DCV Blocks (= number of learning blocks or test blocks) - int64_t _nbDCVBlock; - - /// Table of XEMCVBlock representing 'teste blocks' (Si) - XEMCVBlock * _tabTestBlock; - - /// table of index of best estimation (size : _nbDCVBlock) - int64_t * _tabIndexOfBestEstimation; - - /// Table of CV value (on tests samples) for the all best model (size : _nbDCVBlock) - double * _tabCVValueOnBestModel; - - ///origninal input - XEMOldInput * _originalInput; - - // initialisation method of cv blocks - XEMDCVinitBlocks _DCVinitBlocks; - - // type of best model for the vth block - XEMModelName * _tabBestModelVType; // aggregate - - // - double * _tabCriterionValueForEachEstimation; - - // - XEMErrorType * _tabCriterionErrorForEachEstimation; - - XEMErrorType * _tabDCVErrorForEachEstimation; - // - int64_t _bestIndexEstimation; - - // nbEstimation - int64_t _nbEstimation; - - XEMEstimation ** _tabEstimation; - - void createDCVBlocks(); - - - XEMData * _data; - - double * _weight; - - int64_t _weightTotal; - - double _value; -}; - -//--------------- -// inline methods -//--------------- - -inline XEMErrorType * XEMDCVCriterion::getTabCriterionErrorForEachEstimation(){ - return _tabCriterionErrorForEachEstimation; -} - -inline XEMErrorType * XEMDCVCriterion::getTabDCVErrorForEachEstimation(){ - return _tabDCVErrorForEachEstimation; -} - - -inline double * XEMDCVCriterion::getTabCriterionValueForEachEstimation(){ - return _tabCriterionValueForEachEstimation; -} - -inline int64_t XEMDCVCriterion::getBestIndexEstimation(){ - return _bestIndexEstimation; -} - -inline XEMCriterionName XEMDCVCriterion::getCriterionName() const{ - return DCV; -} - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMData.cpp b/lib/src/mixmod/MIXMOD/XEMData.cpp deleted file mode 100644 index f9e4a92..0000000 --- a/lib/src/mixmod/MIXMOD/XEMData.cpp +++ /dev/null @@ -1,169 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMData.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMData.h" - - -//------------ -// Constructor -//------------ -XEMData::XEMData(){ - throw internalMixmodError; -} - - - -//------------ -// Constructor -//------------ -XEMData::XEMData(const XEMData & iData){ - int64_t i; - _nbSample = iData._nbSample; - _fileNameWeight = iData._fileNameWeight; - _fileNameData = iData._fileNameData; - _weightTotal = iData._weightTotal; - _pbDimension = iData._pbDimension; - _defaultWeight = iData.hasDefaultWeight(); - _weight = copyTab(iData._weight, _nbSample); -} - - - -//------------ -// Constructor -//------------ -XEMData::XEMData(int64_t nbSample, int64_t pbDimension){ - _nbSample = nbSample; - _weightTotal = _nbSample; // true if there is no weight else it will be changed - _pbDimension = pbDimension; - _weight = new double[_nbSample]; - _defaultWeight = true; - setWeightDefault(); - _fileNameWeight=""; - _fileNameData = ""; -} - - - -//------------ -// Constructor for dataReduce -//------------ -XEMData::XEMData(int64_t nbSample, int64_t pbDimension, double weightTotal, double * weight){ - _nbSample = nbSample; - _pbDimension = pbDimension; - _weightTotal = weightTotal; - _weight = new double[_nbSample]; - _defaultWeight = false; // TODO - _weight = copyTab(weight, _nbSample); - _fileNameWeight=""; - _fileNameData=""; -} - - - -//---------- -//Destructor -//---------- -XEMData::~XEMData(){ - if (_weight){ - delete[] _weight; - _weight = NULL; - } -} - - - -//--------- -// selector -//--------- -void XEMData::setWeightTotal(double weightTotal){ - _weightTotal = weightTotal; -} - - - -//---------- -// setWeight -//---------- -void XEMData::setWeight(string weightFileName){ - _defaultWeight = true; - - if (weightFileName.compare("") == 0){ - setWeightDefault(); - }else{ - - _weightTotal = 0.0; - - ifstream weightFile(weightFileName.c_str(), ios::in); - if (! weightFile.is_open()){ - _fileNameWeight=""; - throw wrongWeightFileName; - } - int64_t i=0; - while(i<_nbSample && !weightFile.eof()){ - weightFile>>_weight[i]; - if (_weight[i] != 1){ - _defaultWeight = false; - } - _weightTotal += _weight[i]; - i++; - } - weightFile.close(); - if (i!=_nbSample){ - _fileNameWeight=""; - throw wrongWeightFileName; - } - _fileNameWeight=weightFileName; - } -} - - -//---------- -// setWeightDefault -//---------- -void XEMData::setWeightDefault(){ - _defaultWeight = true; - _fileNameWeight=""; - for (int64_t i=0; i<_nbSample; ++i){ - _weight[i]=1; - } -} - - -bool XEMData::verify() const{ - bool res = true; - - // _weightTotal must be an integer - int64_t iWeightTotal = (int64_t)_weightTotal; - if (_weightTotal - iWeightTotal != 0){ - res = false; - throw weightTotalIsNotAnInteger; - } - - // others verify ? - - return res; - -} - diff --git a/lib/src/mixmod/MIXMOD/XEMData.h b/lib/src/mixmod/MIXMOD/XEMData.h deleted file mode 100644 index 7a619bc..0000000 --- a/lib/src/mixmod/MIXMOD/XEMData.h +++ /dev/null @@ -1,187 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMData.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMDATA_H -#define XEMDATA_H - -#include "XEMUtil.h" -#include "XEMSample.h" -#include "XEMDataDescription.h" - - -/** - @brief Base class for Data - @author F Langrognet & A Echenim -*/ - -class XEMData{ - - public: - - /// Default constructor - XEMData(); - - /// Constructor - XEMData(const XEMData & iData); - - /// Constructor - XEMData(int64_t nbSample, int64_t pbDimension); - - /// Constructor (for dataReduce) - XEMData(int64_t nbSample, int64_t pbDimension, double weightTotal, double * weight); - - /// Desctructor - virtual ~XEMData(); - - - /** @brief Selector - @param weightTotal Value to set total weight of samples - */ - void setWeightTotal(double weightTotal); - - /// setWeight - void setWeight(string weightFileName); - - /// setWeightDefault - void setWeightDefault(); - - /** @brief Read data from data file - @fi Data file to read - */ - virtual void input(ifstream & fi)=0; - - - /** @brief Read data from XEMDataDescription - */ - virtual void input(const XEMDataDescription & dataDescription)=0; - - - /** @brief Write data in output file - @f0 Output file to write into - */ - virtual void output(ostream & fo)=0; - - /** @brief Selector - @return A copy of data - */ - virtual XEMData * clone() const =0; - - virtual XEMSample ** cloneMatrix()=0; - - virtual bool verify() const; - - const string & getFileName()const; - - /// Problem dimension - int64_t _pbDimension; - - /// Number of samples - int64_t _nbSample; - - /// Weight total of samples - double _weightTotal; - - /// Array of samples values (size=nbSample) - XEMSample ** _matrix; - - /// Weight column vector - double * _weight; - - /// getMatrix - const XEMSample** getData() const ; - - /// getMatrix[i] - const XEMSample* getDataI(int64_t index) const ; - - ///getWeight - const double* getWeight() const; - - ///getWeight[i] - const double & getWeightI(int64_t index) const; - - ///get FilenameWeight - const string & getFileNameWeight()const; - - /// get dimension - int64_t getPbDimension()const; - - /// get Number of samples - int64_t getNbSample()const; - - /// hasDefaultWeight - bool hasDefaultWeight() const; - - protected : - - //TODO XEMInput : a enlever - ///filename of weight - string _fileNameWeight; - - /// defaultWeight - bool _defaultWeight; - - ///filename of data - string _fileNameData; - -}; - -inline const XEMSample ** XEMData::getData() const{ - return const_cast(_matrix); -} - -inline const string & XEMData::getFileNameWeight() const{ - return _fileNameWeight; -} - -inline const string & XEMData::getFileName() const{ - return _fileNameData; -} - -inline const XEMSample * XEMData::getDataI(int64_t index) const{ - return _matrix[index]; -} - -inline const double * XEMData::getWeight() const{ - return _weight; -} - -inline const double & XEMData::getWeightI(int64_t index) const{ - return _weight[index]; -} -/// get dimension -inline int64_t XEMData::getPbDimension()const{ - return _pbDimension; -} - -/// get Number of samples -inline int64_t XEMData::getNbSample()const{ - return _nbSample; -} -/// hasDefaultWeight -inline bool XEMData::hasDefaultWeight() const{ - return _defaultWeight; -} - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMDataDescription.cpp b/lib/src/mixmod/MIXMOD/XEMDataDescription.cpp deleted file mode 100644 index 1f9a248..0000000 --- a/lib/src/mixmod/MIXMOD/XEMDataDescription.cpp +++ /dev/null @@ -1,234 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMDataDescription.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#include "XEMDataDescription.h" -#include "XEMBinaryData.h" -#include "XEMGaussianData.h" - -//------------ -// Constructor by default -//------------ -XEMDataDescription::XEMDataDescription() : XEMDescription(){ - _data = NULL; -} - - -//------------ -// Constructor by initialization -//------------ -XEMDataDescription::XEMDataDescription(int64_t nbSample, int64_t nbColumn, vector columnDescription, FormatNumeric::XEMFormatNumericFile format, string filename, string infoName) : XEMDescription(nbSample, nbColumn, columnDescription, format, filename, infoName){ - _data = createData(); -} - - - - -//------------ -// Constructor -//------------ -XEMDataDescription::XEMDataDescription(XEMGaussianData * gData){ - _fileName = ""; - _format = FormatNumeric::defaultFormatNumericFile; - _infoName = ""; - _nbSample = gData->getNbSample(); - _nbColumn = gData->getPbDimension(); - _columnDescription.resize(_nbColumn); - for (int64_t i = 0; i<_nbColumn; ++i){ - _columnDescription[i] = new XEMQuantitativeColumnDescription(i); - } - _data = gData->clone(); - - if (!_data->hasDefaultWeight()){ - _columnDescription.push_back(new XEMWeightColumnDescription(_nbColumn)); - } -} - - -//------------ -// Constructor -//------------ -XEMDataDescription::XEMDataDescription(XEMBinaryData * bData){ - _fileName = ""; - _format = FormatNumeric::defaultFormatNumericFile; - _infoName = ""; - _nbSample = bData->getNbSample(); - _nbColumn = bData->getPbDimension(); - _columnDescription.resize(_nbColumn); - int64_t * tabModality = bData->getTabNbModality(); - for (int64_t i = 0; i<_nbColumn; ++i){ - _columnDescription[i] = new XEMQualitativeColumnDescription(i, tabModality[i]); - } - _data = bData->clone(); - - if (!_data->hasDefaultWeight()){ - _columnDescription.push_back(new XEMWeightColumnDescription(_nbColumn)); - } -} - - - - - -//------------ -// Constructor by copy -//------------ -XEMDataDescription::XEMDataDescription(XEMDataDescription & dataDescription){ - (*this) = dataDescription; -} - - -//------------ -// operator = -//------------ -XEMDataDescription & XEMDataDescription::operator=(const XEMDataDescription & dataDescription){ - _fileName = dataDescription._fileName; - _format = dataDescription._format; - _infoName = dataDescription._infoName; - _nbSample = dataDescription._nbSample; - _nbColumn = dataDescription._nbColumn; - const XEMData * data = dataDescription.getData(); - if (data){ - _data = data->clone(); - } - else{ - _data = NULL; - } - _columnDescription.resize(_nbColumn); - for (int64_t i = 0; i<_nbColumn; ++i){ - const XEMColumnDescription * cd = dataDescription.getColumnDescription(i); - _columnDescription[i] = cd->clone(); - } - return *this; -} - -//------------ -// Destructor -//------------ -XEMDataDescription::~XEMDataDescription(){ - if (_data){ - delete _data; - } -} - - - -//---------------------------- -// createData -//---------------------------- -// Create and return XEMData * -XEMData * XEMDataDescription::createData() const{ - // on ne gere pour l'instant que des données toutes qualitatives ou toutes quantitatives - - XEMData * data = NULL; - - vector nbModality; - int64_t nbQualitativeVariable = 0; - int64_t nbQuantitativeVariable = 0; - int64_t weightIndex = -1; - for (int64_t i=0; i<_nbColumn; i++){ - if (typeid(*(_columnDescription[i])) == typeid(XEMQualitativeColumnDescription)){ - nbQualitativeVariable++; - XEMQualitativeColumnDescription * qualitativeColumnDescription = dynamic_cast(_columnDescription[i]); - nbModality.push_back(qualitativeColumnDescription->getNbFactor()); - } - if (typeid(*(_columnDescription[i]))==typeid(XEMQuantitativeColumnDescription)){ - nbQuantitativeVariable++; - } - if (typeid(*(_columnDescription[i]))==typeid(XEMWeightColumnDescription)){ - if (weightIndex == -1){ - weightIndex = i; - } - else{ - throw tooManyWeightColumnDescription; - } - } - } - - if (nbQualitativeVariable == 0){ - if (nbQuantitativeVariable != 0){ - data = new XEMGaussianData(_nbSample, nbQuantitativeVariable); - } - else{ - throw badDataDescription; // nbQuantitativeVariable=0 and nbQualitativeVariable=0 - } - } - else{ // nbQualitativeVariable!=0 - if (nbQuantitativeVariable != 0){ - throw badDataDescription; // nbQuantitativeVariable!=0 and nbQualitativeVariable!=0 - } - else{ - data = new XEMBinaryData(_nbSample, nbQualitativeVariable, nbModality); - } - } - data-> input(*this); - - return data; -} - - - - - -//----------------- -// is binary Data ? -//----------------- -bool XEMDataDescription::isBinaryData() const{ - bool res = false; - // on ne gere pour l'instant que des données toutes qualitatives ou toutes quantitatives - - XEMData * data = NULL; - - int64_t nbQualitativeVariable = 0; - int64_t nbQuantitativeVariable = 0; - for (int64_t i=0; i<_nbColumn; i++){ - if (typeid(*(_columnDescription[i])) == typeid(XEMQualitativeColumnDescription)){ - nbQualitativeVariable++; - } - if (typeid(*(_columnDescription[i]))==typeid(XEMQuantitativeColumnDescription)){ - nbQuantitativeVariable++; - } - } - - if (nbQualitativeVariable != 0){ - if (nbQuantitativeVariable == 0){ - res = true; - } - else{ - throw badDataDescription; - } - } - return res; -} - - - - -//--------------------- -// verify data validity -//--------------------- -bool XEMDataDescription::verifyData() const{ - return _data->verify(); -} - diff --git a/lib/src/mixmod/MIXMOD/XEMDataDescription.h b/lib/src/mixmod/MIXMOD/XEMDataDescription.h deleted file mode 100644 index 73fb187..0000000 --- a/lib/src/mixmod/MIXMOD/XEMDataDescription.h +++ /dev/null @@ -1,89 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMDataDescription.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#ifndef XEMDATADESCRIPTION_H -#define XEMDATADESCRIPTION_H - -#include "XEMDescription.h" - -class XEMData; -class XEMGaussianData; -class XEMBinaryData; - -class XEMDataDescription : public XEMDescription -{ - public: - /// Default constructor - XEMDataDescription(); - - ///constructor by initilization - XEMDataDescription(int64_t nbSample, int64_t nbColumn, vector columnDescription, FormatNumeric::XEMFormatNumericFile format, string filename, string infoName=""); - - /// constructor with a gaussianData - XEMDataDescription(XEMGaussianData * gData); - - /// constructor with a binaryData - XEMDataDescription(XEMBinaryData * bData); - - ///constructor by copy - XEMDataDescription(XEMDataDescription & dataDescription); - - /// Destructor - virtual ~XEMDataDescription(); - - - ///operator= - XEMDataDescription & operator=(const XEMDataDescription & dataDescription); - - XEMData * getData() const; - - /// is binary Data ? - bool isBinaryData() const; - - /// verify data validity - bool verifyData() const; - - void saveNumericValues(string fileName=""); - - private : - - XEMData * _data; - - /// Create and return XEMData * - XEMData * createData() const; -}; - -inline XEMData * XEMDataDescription::getData() const{ - return _data; -} - - -inline void XEMDataDescription::saveNumericValues(string fileName){ - throw internalMixmodError; -} - - - -#endif // XEMDATADESCRIPTION_H diff --git a/lib/src/mixmod/MIXMOD/XEMDescription.cpp b/lib/src/mixmod/MIXMOD/XEMDescription.cpp deleted file mode 100644 index 01571a1..0000000 --- a/lib/src/mixmod/MIXMOD/XEMDescription.cpp +++ /dev/null @@ -1,131 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMDescription.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#include "XEMDescription.h" -//------------ -// Constructor by default -//------------ -XEMDescription::XEMDescription(){ - _fileName = ""; - _format = FormatNumeric::defaultFormatNumericFile; - _infoName = ""; - _nbSample = 0; - _nbColumn = 0; - initializationColumnDescription(); -} - -//------------ -// Constructor by initialization -//------------ -XEMDescription::XEMDescription(int64_t nbSample, int64_t nbColumn, vector columnDescription, FormatNumeric::XEMFormatNumericFile format, string filename, string infoName){ - _fileName = filename; - _format = format; - _infoName = infoName; - _nbSample = nbSample; - _nbColumn = nbColumn; - if (columnDescription.size() != _nbColumn){ - throw errorInColumnDescription; - } - _columnDescription.resize(_nbColumn); - for (int64_t i = 0; i<_nbColumn; ++i){ - _columnDescription[i] = columnDescription[i]->clone(); - } -} - - - - -//------------ -// Constructor by copy -//------------ -XEMDescription::XEMDescription(XEMDescription & description){ - (*this) = description; -} - - -//------------ -// operator = -//------------ -XEMDescription & XEMDescription::operator=(const XEMDescription & description){ - _fileName = description._fileName; - _format = description._format; - _infoName = description._infoName; - _nbSample = description._nbSample; - _nbColumn = description._nbColumn; - _columnDescription.resize(_nbColumn); - for (int64_t i = 0; i<_nbColumn; ++i){ - const XEMColumnDescription * cd = description.getColumnDescription(i); - _columnDescription[i] = cd->clone(); - } - return *this; -} - -//------------ -// Destructor -//------------ -XEMDescription::~XEMDescription(){ - if (_columnDescription.size() != 0){ - for(int64_t i = 0; i< _columnDescription.size() ; ++i){ - delete _columnDescription[i]; - } - } -} - - -void XEMDescription::initializationColumnDescription(){ - _columnDescription.resize(_nbColumn); - for (int64_t i = 0; i<_nbColumn ; ++i){ - // auto_ptr a (new XEMQuantitativeColumnDescription()); - // _columnDescription[i] = a; - _columnDescription[i] = new XEMQuantitativeColumnDescription(i); - } -} - - - - -//------------------------------------------ -// return pbDimension (number of variables) -// -int64_t XEMDescription::getPbDimension() const{ - int64_t res = 0; - int64_t nbVariable = _nbColumn; - for (int64_t i=0; i<_nbColumn; i++){ - if (typeid(*(_columnDescription[i])) == typeid(XEMIndividualColumnDescription)){ - nbVariable--; - } - if (typeid(*(_columnDescription[i]))==typeid(XEMWeightColumnDescription)){ - nbVariable--; - } - } - return nbVariable; - - -} - - - - - diff --git a/lib/src/mixmod/MIXMOD/XEMDescription.h b/lib/src/mixmod/MIXMOD/XEMDescription.h deleted file mode 100644 index 51cf009..0000000 --- a/lib/src/mixmod/MIXMOD/XEMDescription.h +++ /dev/null @@ -1,132 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMDescription.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#ifndef XEMDESCRIPTION_H -#define XEMDESCRIPTION_H - -#include "XEMUtil.h" -#include "XEMWeightColumnDescription.h" -#include "XEMIndividualColumnDescription.h" -#include "XEMQuantitativeColumnDescription.h" -#include "XEMQualitativeColumnDescription.h" - -class XEMDescription -{ - public: - /// Default constructor - XEMDescription(); - - ///constructor by initilization - XEMDescription(int64_t nbSample, int64_t nbColumn, vector columnDescription, FormatNumeric::XEMFormatNumericFile format, string filename, string InfoName=""); - - ///constructor by copy - XEMDescription(XEMDescription & description); - - /// Destructor - virtual ~XEMDescription(); - - ///initialization ColumnDescription by default - void initializationColumnDescription(); - - ///operator= - XEMDescription & operator=(const XEMDescription & description); - - /// get - //get Name - string getInfoName()const; - - //get NbSample - int64_t getNbSample() const; - - //get FileName - string getFileName()const ; - - //get NbColumn - int64_t getNbColumn()const ; - - //get Format - FormatNumeric::XEMFormatNumericFile getFormat() const; - - //get ColumnDescription - const XEMColumnDescription * getColumnDescription(int64_t index)const; - - const vector getAllColumnDescription()const; - - int64_t getPbDimension() const; - - ///set - //set InfoName - void setInfoName(string & iInfoName); - - virtual void saveNumericValues(string fileName="") = 0; - - protected : - - string _infoName; - int64_t _nbSample; - int64_t _nbColumn; - string _fileName; //numeric file name - FormatNumeric::XEMFormatNumericFile _format;//format of numeric file - vector _columnDescription;//each variable has a description - - -}; - -inline string XEMDescription::getInfoName()const { - return _infoName; -} - -inline int64_t XEMDescription::getNbSample()const { - return _nbSample; -} - -inline int64_t XEMDescription::getNbColumn()const{ - return _nbColumn; -} - -inline string XEMDescription::getFileName()const{ - return _fileName; -} - -inline const XEMColumnDescription * XEMDescription::getColumnDescription(int64_t index)const{ - if (index>=0 && index <=_nbColumn) - return _columnDescription[index]; - else throw wrongIndexInGetMethod; -} - -inline const vector XEMDescription::getAllColumnDescription()const{ - return _columnDescription; -} - -inline FormatNumeric::XEMFormatNumericFile XEMDescription::getFormat()const{ - return _format; -} - -inline void XEMDescription::setInfoName(string & iInfoName){ - _infoName = iInfoName; -} - - -#endif // XEMDESCRIPTION_H diff --git a/lib/src/mixmod/MIXMOD/XEMDiagMatrix.cpp b/lib/src/mixmod/MIXMOD/XEMDiagMatrix.cpp deleted file mode 100644 index 6cf81e7..0000000 --- a/lib/src/mixmod/MIXMOD/XEMDiagMatrix.cpp +++ /dev/null @@ -1,421 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMDiagMatrix.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMDiagMatrix.h" -#include "XEMGeneralMatrix.h" -#include "XEMSymmetricMatrix.h" -#include "XEMUtil.h" - -//------------ -// Constructor -//------------ -XEMDiagMatrix::XEMDiagMatrix(){ - _store = NULL; - throw wrongConstructorType; -} - -XEMDiagMatrix::XEMDiagMatrix(int64_t pbDimension, double d):XEMMatrix(pbDimension){ - _store = new double[_s_pbDimension]; - for (int64_t i=0; i<_s_pbDimension; i++){ - _store[i] = d; - } -} - -XEMDiagMatrix::XEMDiagMatrix(XEMDiagMatrix * A):XEMMatrix(A){ - _store = copyTab(A->getStore(), _s_pbDimension); -} - - -//---------- -//Destructor -//---------- -XEMDiagMatrix::~XEMDiagMatrix(){ - if(_store){ - delete[] _store; - } - _store = NULL; -} - -double XEMDiagMatrix::determinant(XEMErrorType errorType){ - int64_t p; - double det = _store[0]; - for(p=1 ; p<_s_pbDimension ; p++){ - det *= _store[p]; - } - - if(detsetDiagonalStore(Inv_store); - - delete [] Inv_store; -} - - -double* XEMDiagMatrix::getDiagonalStore(){ - return(_store); -} - - -double* XEMDiagMatrix::getSymmetricStore(){ - throw wrongMatrixType; -} - -double* XEMDiagMatrix::getGeneralStore(){ - throw wrongMatrixType; -} - -double XEMDiagMatrix::getSphericalStore(){ - throw wrongMatrixType; -} - -double XEMDiagMatrix::norme(double * xMoinsMean){ - int64_t p; - double termesDiag = 0.0; - double xMoinsMean_p; - - for(p=0 ; p<_s_pbDimension ; p++){ - xMoinsMean_p = xMoinsMean[p]; - termesDiag += xMoinsMean_p * xMoinsMean_p * _store[p]; - } - return termesDiag; - -} - -void XEMDiagMatrix::compute_as__multi_O_S_O(double multi, XEMGeneralMatrix* & O, XEMDiagMatrix *& S){ - throw nonImplementedMethod; -} -double XEMDiagMatrix::trace_this_O_Sm1_O(XEMGeneralMatrix* & O, XEMDiagMatrix* & S){ - throw nonImplementedMethod; -} -double XEMDiagMatrix::compute_trace_W_C(XEMMatrix * C){ - throw nonImplementedMethod; -} -void XEMDiagMatrix::computeShape_as__diag_Ot_this_O(XEMDiagMatrix* & Shape, XEMGeneralMatrix* & Ori, double diviseur){ - throw nonImplementedMethod; -} - - - -double XEMDiagMatrix::putSphericalValueInStore(double & store){ - store = 0.0; - int64_t p; - for(p=0; p<_s_pbDimension; p++){ - store += _store[p]; - } - store /= _s_pbDimension; - return(store); -} - - -double XEMDiagMatrix::addSphericalValueInStore(double & store){ - int64_t p; - for(p=0; p<_s_pbDimension; p++){ - store += _store[p]; - } - store /= _s_pbDimension; - return(store); -} - - - -double* XEMDiagMatrix::putDiagonalValueInStore(double * store){ - for (int64_t p=0 ; p<_s_pbDimension; p++){ - store[p] = _store[p]; - } - return(store); -} - -double* XEMDiagMatrix::addDiagonalValueInStore(double * store){ - for (int64_t p=0 ; p<_s_pbDimension; p++){ - store[p] += _store[p]; - } - return(store); -} - -double* XEMDiagMatrix::addSymmetricValueInStore(double * store){ - // return the store of of a symmetric matrix with this on the diag - //int64_t dimStore = _s_pbDimension*(_s_pbDimension+1)/2; - // double * store = new double[dimStore]; - - int64_t p,q,r; - for(p=0,r=0; p<_s_pbDimension; p++,r++){ - for(q=0; q

putDiagonalValueInStore(_store); - - int64_t p; - for(p=0; p<_s_pbDimension; p++){ - _store[p] /= d; - } -} - - -void XEMDiagMatrix::equalToMatrixMultiplyByDouble(XEMMatrix* D, double d){ - D->putDiagonalValueInStore(_store); - int64_t p; - for(p=0; p<_s_pbDimension; p++){ - _store[p] *= d; - } -} - - - -// add : cik * xMoinsMean * xMoinsMean' to this -void XEMDiagMatrix::add(double * xMoinsMean, double cik){ - - int64_t p; - double xMoinsMean_p; - - for(p=0; p<_s_pbDimension ; p++){ - xMoinsMean_p = xMoinsMean[p]; - _store[p] += cik * xMoinsMean_p * xMoinsMean_p; - }//end for p - -} - -// add : diag( cik * xMoinsMean * xMoinsMean' ) to this -/*void XEMDiagMatrix::addDiag(double * xMoinsMean, double cik){ - - int64_t p; - double xMoinsMean_p; - - for(p=0; p<_s_pbDimension ; p++){ - xMoinsMean_p = xMoinsMean[p]; - _store[p] += cik * xMoinsMean_p * xMoinsMean_p; - }//end for p - - }*/ - - - -// set the value of (d x Identity) to this -void XEMDiagMatrix::operator=(const double& d){ - int64_t p; - - for(p=0; p<_s_pbDimension; p++){ - _store[p] = d; - } -} - -// divide each element by d -void XEMDiagMatrix::operator/=(const double& d){ - int64_t p; - for(p=0; p<_s_pbDimension; p++){ - _store[p] /= d; - } -} - - -// multiply each element by d -void XEMDiagMatrix::operator*=(const double& d){ - int64_t p; - for(p=0; p<_s_pbDimension; p++){ - _store[p] *= d; - } -} - - -//add M to this -void XEMDiagMatrix::operator+=(XEMMatrix* M){ - M -> addDiagonalValueInStore(_store); -} - - -void XEMDiagMatrix::operator=(XEMMatrix* M){ - M -> putDiagonalValueInStore(_store); -} - - - - - -void XEMDiagMatrix::input(ifstream & fi){ - int64_t p,q; - double garbage; - - for (p=0; p<_s_pbDimension; p++){ - // useless because all are 0 - for (q=0; q> garbage; - } - - // here i==j so we are in the diagonal - fi >> _store[p]; - - // useless because all are 0 - for(q=p+1;q<_s_pbDimension;q++){ - fi >> garbage; - } - } - -} - -double XEMDiagMatrix::detDiag(XEMErrorType errorType){ - return determinant(errorType); -} - -void XEMDiagMatrix ::sortDiagMatrix(){ - int64_t max; - for (int64_t i=0; i<_s_pbDimension; i++){ - max = i; - for (int64_t j=i+1; j<_s_pbDimension; j++){ - if (_store[j] > _store[max]){ - max = j; - } - } - if (max != i ){ // swich - double tmp = _store[i]; - _store[i] = _store[max]; - _store[max] = tmp; - } - } - - /*for (int64_t i=1; i<= _s_pbDimension;i++){ - //search the max eigenvalue - max = i; - for (int64_t j=i; j<_s_pbDimension; j++){ - if (_store[j-1] > _store[max-1]) - max = j; - if (max != i){ - // switch - double tmp = _store[max-1]; - _store[max-1] = _store[i-1]; - _store[i-1] = tmp; - } - } - }*/ - -} - - -double** XEMDiagMatrix::storeToArray() const{ - - int64_t i,j; - double** newStore = new double*[_s_pbDimension]; - for (i=0; i<_s_pbDimension ; ++i){ - newStore[i] = new double[_s_pbDimension]; - } - for (i=0; i<_s_pbDimension ; ++i){ - - for (j=0; j<_s_pbDimension ; ++j){ - if (i == j){ - newStore[i][j] = _store[i]; - } - else { - newStore[i][j] = 0; - } - } - } - - return newStore; - -} - - - - - - - - - - - - - - diff --git a/lib/src/mixmod/MIXMOD/XEMDiagMatrix.h b/lib/src/mixmod/MIXMOD/XEMDiagMatrix.h deleted file mode 100644 index db71b91..0000000 --- a/lib/src/mixmod/MIXMOD/XEMDiagMatrix.h +++ /dev/null @@ -1,169 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMDiagMatrix.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMDIAGMATRIX_H -#define XEMDIAGMATRIX_H - -#include "XEMUtil.h" -#include "XEMMatrix.h" -#include "XEMGeneralMatrix.h" - -/** - @brief class XEMDiagMatrix - @author F Langrognet & A Echenim -*/ - -class XEMDiagMatrix : public XEMMatrix{ - - public: - - /// Default constructor - XEMDiagMatrix(); - - /// contructor : d*Id - /// default value = Id - XEMDiagMatrix(int64_t pbDimension, double d=1.0); - - XEMDiagMatrix(XEMDiagMatrix * A); - - - /// Desctructor - virtual ~XEMDiagMatrix(); - - /// compute determinant of diagonal matrix - double determinant(XEMErrorType errorType); - /// return store of diagonal matrix - double * getStore(); - /// compute inverse of diagonal matrix - void inverse(XEMMatrix * & A); - - void compute_product_Lk_Wk(XEMMatrix* Wk, double L); - - /// compute (x - mean)' this (x - mean) - double norme(double * xMoinsMean); - - /// (this) will be A / d - void equalToMatrixDividedByDouble(XEMMatrix * A, double d); - - /// this = matrix * d - void equalToMatrixMultiplyByDouble(XEMMatrix*D, double d); - - ///compute singular vector decomposition - void computeSVD(XEMDiagMatrix* & S, XEMGeneralMatrix* & O); - - /// compute trace of general matrix - double computeTrace(); - - /// add : cik * xMoinsMean * xMoinsMean' to this - void add(double * xMoinsMean, double cik); - - // add : diag( cik * xMoinsMean * xMoinsMean' ) to this - //void addDiag(double * xMoinsMean, double cik); - - /// set the value of (d x Identity) to this - void operator=(const double& d); - /// this = this / (d * Identity) - void operator/=(const double& d); - /// this = this * (d * Identity) - void operator*=(const double& d); - /// this = this + matrix - void operator+=(XEMMatrix* M); - /// this = matrix - void operator=(XEMMatrix* M); - - /// Return store of a spherical matrix in a diagonal one - double putSphericalValueInStore(double & store); - /// Add store of a spherical matrix in a diagonal one - double addSphericalValueInStore(double & store); - - double getSphericalStore(); - - /// Return store of a diagonal matrix - double* putDiagonalValueInStore(double * store); - /// Add store of a diagonal matrix in a diagonal one - double* addDiagonalValueInStore(double * store); - - double* getDiagonalStore(); - - /// Return store of a diagonal matrix - double* putSymmetricValueInStore(double * store); - /// Add store of a diagonal matrix in a diagonal one - double* addSymmetricValueInStore(double * store); - - double* getSymmetricStore(); - - /// Return store of a diagonal matrix - double* putGeneralValueInStore(double * store); - /// Add store of a diagonal matrix in a diagonal one - double* addGeneralValueInStore(double * store); - - double* getGeneralStore(); - - /// read general matrix in an input file - void input(ifstream & fi); - - ///set store - void setSymmetricStore(double * store); - void setGeneralStore(double * store); - void setDiagonalStore(double * store); - void setSphericalStore(double store); - double** storeToArray() const; - - /// gives : det(diag(this)) - double detDiag(XEMErrorType errorType); - - void compute_as__multi_O_S_O(double multi, XEMGeneralMatrix* & O, XEMDiagMatrix *& S); - double trace_this_O_Sm1_O(XEMGeneralMatrix* & O, XEMDiagMatrix* & S); - double compute_trace_W_C(XEMMatrix * C); - void computeShape_as__diag_Ot_this_O(XEMDiagMatrix* & Shape, XEMGeneralMatrix* & Ori, double diviseur = 1.0); - - ///sort diagonal matrix in decreasing order - void sortDiagMatrix(); - protected : - - double * _store; - -}; - -inline double * XEMDiagMatrix::getStore(){ - return _store; -} - -inline void XEMDiagMatrix::setSymmetricStore(double * store){ - throw wrongMatrixType; -} - -inline void XEMDiagMatrix::setGeneralStore(double * store){ - throw wrongMatrixType; -} - -inline void XEMDiagMatrix::setDiagonalStore(double * store){ - //_store = store; - recopyTab(store,_store,_s_pbDimension); -} - -inline void XEMDiagMatrix::setSphericalStore(double store){ - throw wrongMatrixType; -} -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMEMAlgo.cpp b/lib/src/mixmod/MIXMOD/XEMEMAlgo.cpp deleted file mode 100644 index 23368df..0000000 --- a/lib/src/mixmod/MIXMOD/XEMEMAlgo.cpp +++ /dev/null @@ -1,109 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMEMAlgo.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMEMAlgo.h" -#include "XEMUtil.h" -#include -#include - -//----------- -//Constructor -//----------- -XEMEMAlgo::XEMEMAlgo(){ -} - -XEMEMAlgo::XEMEMAlgo(XEMAlgoStopName algoStopName, double epsilon, int64_t nbIteration) - :XEMAlgo( algoStopName, epsilon, nbIteration){ -} - - -/// Copy constructor -XEMEMAlgo::XEMEMAlgo(const XEMEMAlgo & emAlgo):XEMAlgo(emAlgo){ -} - - -//---------- -//Destructor -//---------- -XEMEMAlgo::~XEMEMAlgo(){ -} - - - -// clone -//------ -XEMAlgo * XEMEMAlgo::clone(){ - return (new XEMEMAlgo(*this)); -} - -//--- -//run -//--- -void XEMEMAlgo::run(XEMModel *& model){ - - /*std::ostringstream numero; - std::string nomfic; - - std::string basestring ="parameter"; - std::string suffix = ".txt" ; - - ofstream likeli("likelihoods.txt", ios::out); - */ - - _indexIteration = 1; - model->setAlgoName(EM); - -#if DEBUG > 0 - cout<<"Debut Algo EM :"<editDebugInformation(); -#endif - - model->Estep(); // E Step - - - model->Mstep(); // M Step - -#if DEBUG > 0 - cout<<"Apres la 1ere iteration de EM :"<editDebugInformation(); -#endif - _indexIteration++; - - while (continueAgain()){ - model->Estep(); // E Step - model->Mstep(); // M Step -#if DEBUG > 0 - cout<<"Apres la "<<_indexIteration<<" eme iteration de EM :"<editDebugInformation(); -#endif - _indexIteration++; - _xml_old = _xml; - _xml = model->getLogLikelihood(true); // true : to compute fik - - } - - model->Estep(); // E step to update Tik an fik - -} - diff --git a/lib/src/mixmod/MIXMOD/XEMEMAlgo.h b/lib/src/mixmod/MIXMOD/XEMEMAlgo.h deleted file mode 100644 index 336087c..0000000 --- a/lib/src/mixmod/MIXMOD/XEMEMAlgo.h +++ /dev/null @@ -1,64 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMEMAlgo.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMEMALGO_H -#define XEMEMALGO_H - -#include "XEMAlgo.h" - -/** - @brief Derived class of XEMAlgo for EM Algorithm(s) - @author F Langrognet & A Echenim -*/ - -class XEMEMAlgo : public XEMAlgo{ - - public: - - /// Default constructor - XEMEMAlgo(); - - /// Copy constructor - XEMEMAlgo(const XEMEMAlgo & emAlgo); - - /// Constructor - XEMEMAlgo(XEMAlgoStopName algoStopName, double epsilon, int64_t nbIteration); - - /// Destructor - ~XEMEMAlgo(); - - /// clone - XEMAlgo * clone(); - - /// Run method - virtual void run(XEMModel *& model); - - const XEMAlgoName getAlgoName() const; -}; - -inline const XEMAlgoName XEMEMAlgo::getAlgoName() const{ - return EM; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMError.cpp b/lib/src/mixmod/MIXMOD/XEMError.cpp deleted file mode 100644 index fd84e97..0000000 --- a/lib/src/mixmod/MIXMOD/XEMError.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMError.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMError.h" - -//----------- -//Constructor -//----------- -XEMError::XEMError(){ -} - - - -//----------- -//Constructor -//----------- -XEMError::XEMError(XEMErrorType errorType){ - _errorType = errorType; -} - - - -//---------- -//Destructor -//---------- -XEMError::~XEMError(){ -} - - - -//--- -//Run -//--- -void XEMError::run(ostream & flux){ - - - flux << "MIXMOD ERROR ("<<_errorType<<") :"<. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMERROR_H -#define XEMERROR_H - -#include "XEMUtil.h" - -/** - @brief Base class for Error(s) - @author F Langrognet & A Echenim -*/ - -class XEMError{ - - public: - - /// Default constructor - XEMError(); - - /// Constructor - XEMError(XEMErrorType errorType); - - /// Destructor - ~XEMError(); - - - /// Run method - void run(ostream & flux=std::cout); - - - private : - - /// Type of error - XEMErrorType _errorType; -}; - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMEstimation.cpp b/lib/src/mixmod/MIXMOD/XEMEstimation.cpp deleted file mode 100644 index 1e8b942..0000000 --- a/lib/src/mixmod/MIXMOD/XEMEstimation.cpp +++ /dev/null @@ -1,169 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMEstimation.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMEstimation.h" -#include "XEMStrategy.h" -#include "XEMClusteringStrategy.h" -#include "XEMBICCriterion.h" -#include "XEMICLCriterion.h" -#include "XEMNECCriterion.h" -#include "XEMCVCriterion.h" -#include "XEMDCVCriterion.h" - - -//------------ -// Constructor -//------------ -XEMEstimation::XEMEstimation(){ - _strategy = NULL; - _cStrategy = NULL; - _modelType = NULL; - _errorType = noError; - _model = NULL; -} - - -//------------------ -// copy constructor -//----------------- -XEMEstimation::XEMEstimation(const XEMEstimation & estimation){ - throw internalMixmodError; -} - - -//------------ -// Constructor -//------------ -XEMEstimation::XEMEstimation(XEMClusteringStrategy *& strategy, XEMModelType * modelType, int64_t nbCluster, XEMData *& data ,vector & criterionName, XEMPartition *& knownPartition, vector corresp){ - _modelType = modelType; - _nbCluster = nbCluster; - _cStrategy = strategy; - _strategy = NULL; - _errorType = noError; - _correspondenceOriginDataToReduceData = corresp; - _model = new XEMModel(modelType, nbCluster, data, knownPartition); - - int64_t nbCriterion = criterionName.size(); - _criterionOutput.resize(nbCriterion); - _criterion.resize(nbCriterion); - for (int64_t i=0; i corresp){ - _modelType = modelType; - _nbCluster = nbCluster; - _strategy = strategy; - _cStrategy = NULL; - _errorType = noError; - _correspondenceOriginDataToReduceData = corresp; - _model = new XEMModel(modelType, nbCluster, data, knownPartition); -} - - - -//----------- -// Destructor -//----------- -XEMEstimation::~XEMEstimation(){ - // if (_strategy){ - // delete _strategy; - // _strategy = NULL; - // } - if (_model){ - delete _model; - _model = NULL; - } -} - - - -//--- -//run -//--- -void XEMEstimation::run(){ - try{ - // compute strategy - //----------------- - if (_strategy){ - _strategy->run(_model); - } - else{ - _cStrategy->run(_model); - } - } - catch(XEMErrorType & e){ - setErrorType(e); - for (int64_t i=0; i<_criterion.size(); i++){ - _criterionOutput[i].setCriterionName(_criterion[i]->getCriterionName()); - _criterionOutput[i].setError(errorEstimationStrategyRun); - _criterionOutput[i].setValue(0); - } - return; - } - - // compute criterion - //------------------ - double value; - XEMErrorType error; - for (int64_t i=0; i<_criterion.size(); i++){ - _criterion[i]->run(_model, value, error); - _criterionOutput[i].setCriterionName(_criterion[i]->getCriterionName()); - _criterionOutput[i].setError(error); - _criterionOutput[i].setValue(value); - } - -} - -//--------- -//set error -//--------- -void XEMEstimation::setErrorType(XEMErrorType errorType){ - _errorType = errorType; -} - - - -//-------------- -//Friend Methods -//-------------- -ostream & operator << (ostream & fo, XEMEstimation & estimation){ - return fo; -} - diff --git a/lib/src/mixmod/MIXMOD/XEMEstimation.h b/lib/src/mixmod/MIXMOD/XEMEstimation.h deleted file mode 100644 index 62bddba..0000000 --- a/lib/src/mixmod/MIXMOD/XEMEstimation.h +++ /dev/null @@ -1,215 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMEstimation.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMESTIMATION_H -#define XEMESTIMATION_H - - -#include "XEMUtil.h" -#include "XEMModel.h" -#include "XEMCriterionOutput.h" -#include "XEMClusteringStrategy.h" - -class XEMCriterion; - -/** - @brief Base class for Estimation(s) - @author F Langrognet & A Echenim -*/ - -class XEMEstimation{ - - public: - - /// Default constructor - XEMEstimation(); - - /// copy constructor - XEMEstimation(const XEMEstimation & estimation); - - - /// Constructor - XEMEstimation(XEMClusteringStrategy *& strategy, XEMModelType * modelType, int64_t nbCluster, XEMData *& data, vector & criterionName, XEMPartition *& knownPartition, vector corresp); - - - /// Constructor - XEMEstimation(XEMStrategy *& strategy, XEMModelType * modelType, int64_t nbCluster, XEMData *& data, XEMPartition *& knownPartition, vector corresp); - - /// Destructor - virtual ~XEMEstimation(); - - - /** @brief Selector - @return The best Model of the current strategy - */ - XEMModel * getModel(); - - - /// get Parameter - XEMParameter * getParameter() const; - - /// get model type - XEMModelType * getModelType(); - - /// get nbCluster - int64_t getNbCluster(); - - /** @brief Set the error type estimation - @param errorType Type of error to set - */ - void setErrorType(XEMErrorType errorType); - - /** @brief Selector - @return The type of the error - */ - XEMErrorType getErrorType(); - - /// get the strategy - XEMClusteringStrategy * getClusteringStrategy(); - /// get the strategy - XEMStrategy * getStrategy(); - - //getcorrespondenceOriginDataToReduceData - const vector & getcorrespondenceOriginDataToReduceData()const; - - /// Run method - void run(); - - /// - int64_t getCriterionSize() const; - - //XEMCriterionName getCriterionName(int64_t index) const; - - /// getCriterionOutput - vector getCriterionOutput() ; - - /// getCriterionOutput(index) - XEMCriterionOutput & getCriterionOutput(int64_t index) ; - - // getData - XEMData * getData(); - - - /// getNbSample - int64_t getNbSample() const; - - /** @brief Friend method - @return Operator << overloaded to write Estimation in output files - */ - friend ostream & operator << (ostream & fo, XEMEstimation & estimation); - - private : - - /// Current strategy - XEMClusteringStrategy * _cStrategy; - - /// Current strategy - XEMStrategy * _strategy; - - /// Number of cluster - int64_t _nbCluster; - - /// Current model type - XEMModelType * _modelType; - - /// Current model error - XEMErrorType _errorType; - - /// model - XEMModel * _model; - - vector _correspondenceOriginDataToReduceData; - - vector _criterion; - vector _criterionOutput; - -}; - - - -//--------------- -// inline methods -//--------------- - -inline XEMModel * XEMEstimation::getModel(){ - return (_model); -} - -inline XEMData * XEMEstimation::getData(){ - return (_model->getData()); -} - -inline XEMModelType * XEMEstimation::getModelType(){ - return _modelType; -} - -inline int64_t XEMEstimation::getNbCluster(){ - return _nbCluster; -} - - -inline int64_t XEMEstimation::getNbSample() const{ - return (_model->getNbSample()); -} - -inline XEMClusteringStrategy * XEMEstimation::getClusteringStrategy(){ - return _cStrategy; -} -inline XEMStrategy * XEMEstimation::getStrategy(){ - return _strategy; -} - -inline XEMErrorType XEMEstimation::getErrorType(){ - return (_errorType); -} - -inline const vector & XEMEstimation::getcorrespondenceOriginDataToReduceData()const{ - return _correspondenceOriginDataToReduceData; -} - -inline XEMParameter * XEMEstimation::getParameter() const{ - if (_model){ - return _model->getParameter(); - } - else{ - throw nullPointerError; - } -} - -inline int64_t XEMEstimation::getCriterionSize() const{ - return _criterion.size(); -} - -inline vector XEMEstimation::getCriterionOutput(){ - return _criterionOutput; -} - -inline XEMCriterionOutput & XEMEstimation::getCriterionOutput(int64_t index){ - if (index>=0 && index<_criterionOutput.size()) - return _criterionOutput[index]; - throw internalMixmodError; -} - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMGaussianData.cpp b/lib/src/mixmod/MIXMOD/XEMGaussianData.cpp deleted file mode 100644 index 6ba7336..0000000 --- a/lib/src/mixmod/MIXMOD/XEMGaussianData.cpp +++ /dev/null @@ -1,355 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMGaussianData.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMGaussianData.h" - - -//----------- -//Constructor -//----------- -XEMGaussianData::XEMGaussianData(){ -} - - - -//------------ -// Constructor -//------------ -XEMGaussianData::XEMGaussianData(const XEMGaussianData & iData):XEMData(iData){ - int64_t i; - XEMSample ** matrix = iData._matrix; - - _matrix = new XEMSample*[_nbSample]; - _yStore = new double* [_nbSample]; - - for (i=0; i<_nbSample; i++){ - _matrix[i] = new XEMGaussianSample((XEMGaussianSample*)matrix[i]); - _yStore[i] = ((XEMGaussianSample *)_matrix[i])->getTabValue() ; - } - _Inv2PiPow = iData.getInv2PiPow(); - _pbDimensionLog2Pi = iData.getPbDimensionLog2Pi(); - _halfPbDimensionLog2Pi = _pbDimensionLog2Pi / 2.0 ; - __tmpTabOfSizePbDimension = new double[_pbDimension]; - _deleteSamples = true; -} - - - -//------------ -// Constructor -//------------ -XEMGaussianData::XEMGaussianData(int64_t nbSample, int64_t pbDimension):XEMData(nbSample,pbDimension){ - int64_t i; - _Inv2PiPow = 1.0 / pow(2.0 * XEMPI, pbDimension/2.0 ); - _pbDimensionLog2Pi = pbDimension * log(2.0 * XEMPI); - _halfPbDimensionLog2Pi = _pbDimensionLog2Pi / 2.0; - __tmpTabOfSizePbDimension = new double[_pbDimension]; - - - _matrix = new XEMSample*[_nbSample]; - _yStore = new double * [_nbSample]; - - for (i=0; i<_nbSample; i++){ - _weight[i] = 1.0; - _matrix[i] = new XEMGaussianSample(_pbDimension); - _yStore[i] = ((XEMGaussianSample *)(_matrix[i]))->getTabValue(); - } - _weightTotal = _nbSample; - -} - - - -//------------ -// Constructor -//------------ -XEMGaussianData::XEMGaussianData(int64_t nbSample, int64_t pbDimension, double ** matrix):XEMData(nbSample,pbDimension){ - int64_t i; - - if (matrix == NULL) throw internalMixmodError; - - _Inv2PiPow = 1.0 / pow(2.0 * XEMPI, pbDimension/2.0 ); - _pbDimensionLog2Pi = pbDimension * log(2.0 * XEMPI); - _halfPbDimensionLog2Pi = _pbDimensionLog2Pi / 2.0; - __tmpTabOfSizePbDimension = new double[_pbDimension]; - - _matrix = new XEMSample*[_nbSample]; - _yStore = new double * [_nbSample]; - - for (i=0; i<_nbSample; i++){ - _weight[i] = 1.0; - _matrix[i] = new XEMGaussianSample(_pbDimension, matrix[i]); - _yStore[i] = ((XEMGaussianSample *)(_matrix[i]))->getTabValue(); - } - _weightTotal = _nbSample; -} - - - -//------------ -// Constructor -//------------ -XEMGaussianData::XEMGaussianData(int64_t nbSample, int64_t pbDimension, const string & dataFileName):XEMData(nbSample,pbDimension){ - int64_t i; - - _Inv2PiPow = 1.0 / pow(2.0 * XEMPI, pbDimension/2.0 ); - _pbDimensionLog2Pi = pbDimension * log(2.0 * XEMPI); - _halfPbDimensionLog2Pi = _pbDimensionLog2Pi / 2.0; - __tmpTabOfSizePbDimension = new double[_pbDimension]; - - - _matrix = new XEMSample*[_nbSample]; - _yStore = new double * [_nbSample]; - - for (i=0; i<_nbSample; i++){ - _matrix[i] = new XEMGaussianSample(_pbDimension); - _yStore[i] = ((XEMGaussianSample *)(_matrix[i]))->getTabValue(); - } - - ifstream dataStream((dataFileName).c_str(), ios::in); - if (! dataStream.is_open()){ - throw wrongDataFileName; - } - input(dataStream); - dataStream.close(); - _deleteSamples = true; - _fileNameData = dataFileName; -} - - - -//------------ -// Constructor for dataReduce -//------------ -XEMGaussianData::XEMGaussianData(int64_t nbSample, int64_t pbDimension, double weightTotal, XEMSample **& matrix, double * weight):XEMData(nbSample,pbDimension,weightTotal,weight){ - - // 1/ (2 * pi)^(d/2) - _Inv2PiPow = 1.0 / pow(2.0 * XEMPI, pbDimension/2.0 ); - _pbDimensionLog2Pi = pbDimension * log(2.0 * XEMPI); - _halfPbDimensionLog2Pi = _pbDimensionLog2Pi / 2.0; - _pbDimensionLog2Pi = pbDimension * log(2.0 * XEMPI); - __tmpTabOfSizePbDimension = new double[_pbDimension]; - - _matrix = matrix; - _yStore = new double *[nbSample]; - int64_t i; - - for (i=0; i<_nbSample; i++){ - _yStore[i] = ((XEMGaussianSample *)(_matrix[i]))->getTabValue(); - } - _deleteSamples = true; -} - - - -//------------ -// Constructor (used in DCV context) -//------------ -XEMGaussianData::XEMGaussianData(int64_t nbSample, int64_t pbDimension, XEMData * originalData, XEMCVBlock & block):XEMData(nbSample, pbDimension){ - - XEMGaussianData * origData = (XEMGaussianData *)(originalData); - XEMSample ** origMatrix = origData->_matrix ; - - // 1/ (2 * pi)^(d/2) - _Inv2PiPow = 1.0 / pow(2.0 * XEMPI, pbDimension/2.0 ); - _pbDimensionLog2Pi = pbDimension * log(2.0 * XEMPI); - _halfPbDimensionLog2Pi = _pbDimensionLog2Pi / 2.0; - __tmpTabOfSizePbDimension = new double[_pbDimension]; - _deleteSamples = false; - - - _weightTotal = block._weightTotal; - _matrix = new XEMSample*[_nbSample] ; - for (int64_t i=0; i<_nbSample; i++){ - _matrix[i] = origMatrix[block._tabWeightedIndividual[i].val]; - //cout<<"ind : "<getTabValue(); - } -} - - - - -//---------- -//Destructor -//---------- -XEMGaussianData::~XEMGaussianData(){ - int64_t i; - if (_matrix){ - - if(_deleteSamples){ - for (i=0; i<_nbSample; i++){ - delete _matrix[i]; - _matrix[i] = NULL; - } - } - - delete[] _matrix; - _matrix = NULL; - } - if(_yStore){ - delete[] _yStore; - _yStore = NULL; - } - if(__tmpTabOfSizePbDimension){ - delete[] __tmpTabOfSizePbDimension; - __tmpTabOfSizePbDimension = NULL; - } - -} - - - -//----------- -// Clone data -//----------- -XEMData * XEMGaussianData::clone() const{ - XEMGaussianData * newData = new XEMGaussianData(*this); - return(newData); -} - - - -//------------------ -// Clone data matrix -//------------------ -XEMSample ** XEMGaussianData::cloneMatrix(){ - int64_t i; - - XEMSample ** newMatrix = new XEMSample*[_nbSample]; - for (i=0; i<_nbSample; i++){ - newMatrix[i] = new XEMGaussianSample((XEMGaussianSample*)_matrix[i]); - } - - return newMatrix; -} - - - -//------ -// input -//------ -void XEMGaussianData:: input(ifstream & fi){ - - int64_t j; - int64_t i; - double ** p_y; - double * p_y_i; - - p_y = _yStore; - for(i=0; i<_nbSample; i++){ - p_y_i = *p_y; - for(j=0; j<_pbDimension; j++){ - if (fi.eof()){ - throw endDataFileReach; - } - fi >> p_y_i[j]; - } - _weight[i] = 1.0; - p_y++; - } - _weightTotal = _nbSample; - -} - - - -//------ -// input -//------ -void XEMGaussianData::input(const XEMDataDescription & dataDescription){ - _fileNameData = dataDescription.getFileName(); - - _weightTotal = 0; - ifstream fi((_fileNameData).c_str(), ios::in); - if (! fi.is_open()){ - throw wrongDataFileName; - } - int64_t j; - int64_t i; - double tmp; - double ** p_y; - double * p_y_i; - - p_y = _yStore; - int64_t g=0; - for(i=0; i<_nbSample; i++){ - _weight[i] = 1.0; - p_y_i = *p_y; - g=0; - for(j=0; j> p_y_i[g]; - g++; - //cout<>_weight[i]; - } - else{ - if (typeid(*(dataDescription.getColumnDescription(j)))==typeid(XEMIndividualColumnDescription)){ - string stringTmp; - fi>>stringTmp; - //cout<>tmp; // on avance ! - } - } - } - }// end j - p_y++; - _weightTotal += _weight[i]; - }// end i -} - - - -// output -//------- -void XEMGaussianData:: output(ostream & fo){ - cout<<"Sample size: "<<_nbSample << endl; - cout<<" Dimension: "<<_pbDimension << endl ; - - editTab(_yStore,_nbSample,_pbDimension," ","",fo); - -} - - -bool XEMGaussianData::verify()const{ - bool res = XEMData::verify(); - - // others verif ? - return res; -} diff --git a/lib/src/mixmod/MIXMOD/XEMGaussianData.h b/lib/src/mixmod/MIXMOD/XEMGaussianData.h deleted file mode 100644 index c9b9e57..0000000 --- a/lib/src/mixmod/MIXMOD/XEMGaussianData.h +++ /dev/null @@ -1,153 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMGaussianData.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMGAUSSIANDATA_H -#define XEMGAUSSIANDATA_H - -#include "XEMUtil.h" -#include "XEMData.h" -#include "XEMGaussianSample.h" -#include "XEMOldInput.h" - -/** - @brief Base class for Gaussian Data - @author F Langrognet & A Echenim -*/ - -class XEMGaussianData : public XEMData{ - - public: - - /// Default constructor - XEMGaussianData(); - - /// Constructor - XEMGaussianData(const XEMGaussianData & iData); - - /// Constructor - XEMGaussianData(int64_t nbSample, int64_t pbDimension, const string & dataFileName); - - /// Constructor (without fill matrix) - XEMGaussianData(int64_t nbSample, int64_t pbDimension); - - /// Constructor (with matrix) - XEMGaussianData(int64_t nbSample, int64_t pbDimension, double ** matrix); - - /// Constructor - XEMGaussianData(int64_t nbSample, int64_t pbDimension, double weightTotal, XEMSample **& matrix, double * weight); - - /// Constructor - // used in DCV context - XEMGaussianData(int64_t nbSample, int64_t pbDimension, XEMData * originalData, XEMCVBlock & block); - - /// Desctructor - virtual ~XEMGaussianData(); - - - /** @brief Selector - @return A copy of data - */ - XEMData * clone() const; - - /** @brief Copy - @return A copy data matrix - */ - XEMSample ** cloneMatrix(); - - - //TODO a enlever XEMInput - /** @brief Read data from gaussian data file - @fi Gaussian Data file to read - */ - void input(ifstream & fi); - - /** @brief Read data from XEMDataDescription - */ - void input(const XEMDataDescription & dataDescription); - - /** @brief Write gaussian data in output file - @f0 Output file to write into - */ - void output(ostream & fo); - - bool verify()const; - - /// pointer to stored values - double ** _yStore ; - - double ** getYStore(); - - double getInv2PiPow() const; - - double getHalfPbDimensionLog2Pi() const; - - double getPbDimensionLog2Pi() const ; - - double * getTmpTabOfSizePbDimension() const; - - - protected : - - /// 1/ (2 * pi)^(d/2) - double _Inv2PiPow ; - - /// 0.5 * p * log(2 * PI) - double _halfPbDimensionLog2Pi; - - double _pbDimensionLog2Pi; - - - // tableau de double longueur _pbDimension - // utilisé pour ne pas avoir à faire sans arret allocation / destruction - // utilisé par XEMnorme, getLogLikeLihoodOne - double * __tmpTabOfSizePbDimension; - - bool _deleteSamples ; - -}; - - -inline double ** XEMGaussianData::getYStore(){ - return _yStore; -} - -inline double XEMGaussianData::getInv2PiPow() const{ - return _Inv2PiPow; -} - -inline double XEMGaussianData::getHalfPbDimensionLog2Pi()const{ - return _halfPbDimensionLog2Pi; -} - -inline double XEMGaussianData::getPbDimensionLog2Pi()const{ - return _pbDimensionLog2Pi; -} - - -inline double* XEMGaussianData::getTmpTabOfSizePbDimension()const{ - return __tmpTabOfSizePbDimension; -} - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMGaussianDiagParameter.cpp b/lib/src/mixmod/MIXMOD/XEMGaussianDiagParameter.cpp deleted file mode 100644 index 142d19a..0000000 --- a/lib/src/mixmod/MIXMOD/XEMGaussianDiagParameter.cpp +++ /dev/null @@ -1,434 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMGaussianDiagParameter.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org - ***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMGaussianDiagParameter.h" -#include "XEMGaussianGeneralParameter.h" -#include "XEMGaussianEDDAParameter.h" -#include "XEMGaussianData.h" -#include "XEMModel.h" - - -/****************/ -/* Constructors */ -/****************/ - -//---------------------------------------------------- -//---------------------------------------------------- -XEMGaussianDiagParameter::XEMGaussianDiagParameter(){ - throw wrongConstructorType; -} - - - -//------------------------------------------------------------------------------------- -// constructor called by XEMModel -//------------------------------------------------------------------------------------- -XEMGaussianDiagParameter::XEMGaussianDiagParameter(XEMModel * iModel, XEMModelType * iModelType): XEMGaussianEDDAParameter(iModel, iModelType){ - int64_t k; - _tabLambda = new double [_nbCluster]; - _tabShape = new XEMDiagMatrix*[_nbCluster]; - _W = new XEMDiagMatrix(_pbDimension); //Id - for (k=0; k<_nbCluster; k++){ - _tabLambda[k] = 1.0; - _tabShape[k] = new XEMDiagMatrix(_pbDimension); //Id - - _tabSigma[k] = new XEMDiagMatrix(_pbDimension); //Id - _tabInvSigma[k] = new XEMDiagMatrix(_pbDimension); //Id - _tabWk[k] = new XEMDiagMatrix(_pbDimension); //Id - } - -} - - - -//--------------------------------------------------------------------- -// copy Constructor -//--------------------------------------------------------------------- -XEMGaussianDiagParameter::XEMGaussianDiagParameter(const XEMGaussianDiagParameter * iParameter):XEMGaussianEDDAParameter(iParameter){ - int64_t k; - _tabLambda = copyTab(iParameter->getTabLambda(), _nbCluster); - _tabShape = new XEMDiagMatrix*[_nbCluster]; - _W = new XEMDiagMatrix(_pbDimension); - (* _W) = iParameter->getW(); - - XEMMatrix ** iTabSigma = iParameter->getTabSigma(); - XEMMatrix ** iTabInvSigma = iParameter->getTabInvSigma(); - XEMMatrix ** iTabWk = iParameter->getTabWk(); - XEMDiagMatrix ** iTabShape = iParameter->getTabShape(); - - for (k=0; k<_nbCluster; k++){ - _tabSigma[k] = new XEMDiagMatrix(_pbDimension); - (* _tabSigma[k]) = iTabSigma[k]; - _tabInvSigma[k] = new XEMDiagMatrix(_pbDimension); - (* _tabInvSigma[k]) = iTabInvSigma[k]; - _tabWk[k] = new XEMDiagMatrix(_pbDimension); - (* _tabWk[k]) = iTabWk[k]; - _tabShape[k] = new XEMDiagMatrix(_pbDimension); - (* _tabShape[k]) = iTabShape[k]; - } -} - - - -/**************/ -/* Destructor */ -/**************/ -XEMGaussianDiagParameter::~XEMGaussianDiagParameter(){ - int64_t k; - - if (_tabLambda){ - delete[] _tabLambda; - _tabLambda = NULL; - } - - if(_tabShape){ - for(k=0; k<_nbCluster; k++){ - delete _tabShape[k]; - _tabShape[k] = NULL; - } - delete[] _tabShape; - _tabShape = NULL; - } - - if (_tabInvSigma){ - for(k=0; k<_nbCluster; k++){ - delete _tabInvSigma[k]; - _tabInvSigma[k] = NULL; - } - } - - if (_tabSigma){ - for(k=0; k<_nbCluster; k++){ - delete _tabSigma[k]; - _tabSigma[k] = NULL; - } - } -} - - - -//------------------------ -// reset to default values -//------------------------ -void XEMGaussianDiagParameter::reset(){ - int64_t k; - for (k=0; k<_nbCluster; k++){ - _tabLambda[k] = 1.0; - *(_tabShape[k]) = 1.0; - } - XEMGaussianEDDAParameter::reset(); -} - - - - -/*********/ -/* clone */ -/*********/ -XEMParameter * XEMGaussianDiagParameter::clone() const{ - XEMGaussianDiagParameter * newParam = new XEMGaussianDiagParameter(this); - return(newParam); -} - - -/************/ -/* initUSER */ -/************/ -void XEMGaussianDiagParameter::initUSER(XEMParameter * iParam){ - XEMGaussianEDDAParameter::initUSER(iParam); - updateTabInvSigmaAndDet(); -} - - - -/*******************/ -/* computeTabSigma */ -/*******************/ -void XEMGaussianDiagParameter::computeTabSigma(){ - - /* Initialization */ - XEMGaussianData * data= (XEMGaussianData*)(_model->getData()); - double * tabNk = _model->getTabNk(); - int64_t k; - XEMDiagMatrix * B = new XEMDiagMatrix(_pbDimension); - XEMDiagMatrix * Bk = new XEMDiagMatrix(_pbDimension); - double detB = 0.0; // Determinant of matrix B - int64_t iter = 5; // Number of iterations in iterative procedure - double detDiagW; // Determinant of diagonal matrix W - double detDiagWk; // Determinant of diagonal matrix Wk - double lambda = 0.0; // Volume - double weightTotal = data->_weightTotal; - double power = 1.0 / _pbDimension; - double det = 0.0; - double logDet = 0.0; - double * W_k = new double[_pbDimension]; - double * Shape_k; - double tmp; - int64_t p; - - - // Compute det[diag(W)] - logDet = _W->determinant(minDeterminantDiagWValueError); - detDiagW = powAndCheckIfNotNull(logDet,power); - - // Variance estimator for each of diagonal model - switch(_modelType->_nameModel){ - - //--------------------- - case (Gaussian_p_L_B) : - case (Gaussian_pk_L_B) : - //--------------------- - for (k=0; k<_nbCluster; k++){ - /*_tabLambda[k] = detDiagW / weightTotal; - if ( _tabLambda[k]< minOverflow) { - throw errorSigmaConditionNumber; - }*/ - _tabSigma[k]->equalToMatrixDividedByDouble(_W, weightTotal); //_tabSigma[k] = _W/weightTtal - } - break; - - - //--------------------- - case (Gaussian_p_L_Bk) : - case (Gaussian_pk_L_Bk) : - //---------------------- - for (k=0; k<_nbCluster; k++){ - det = _tabWk[k]->determinant(minDeterminantDiagWkValueError); - detDiagWk = powAndCheckIfNotNull(det,power); - - _tabShape[k]->equalToMatrixDividedByDouble(_tabWk[k],detDiagWk); //_tabShape[k] = _tabW[k]/detWk - lambda += detDiagWk; - } - - for (k=0; k<_nbCluster; k++){ - _tabLambda[k] = lambda / weightTotal; - if ( _tabLambda[k]< minOverflow) - throw errorSigmaConditionNumber; - - _tabSigma[k]->equalToMatrixMultiplyByDouble(_tabShape[k],_tabLambda[k]); //tabSigma[k] = tabShape[k]*somme(lambda[k]) - } - break; - - - //--------------------- - case (Gaussian_p_Lk_Bk) : - case (Gaussian_pk_Lk_Bk) : - //---------------------- - for (k=0; k<_nbCluster; k++){ - - logDet = _tabWk[k]->determinant( minDeterminantDiagWkValueError); - detDiagWk = powAndCheckIfNotNull(logDet, power); - - _tabLambda[k] = detDiagWk / tabNk[k]; - if ( _tabLambda[k]< minOverflow) - throw errorSigmaConditionNumber; - - _tabShape[k]->equalToMatrixDividedByDouble(_tabWk[k],detDiagWk); //_tabShape[k] = _tabW[k]/detWk - - _tabSigma[k]->equalToMatrixMultiplyByDouble(_tabShape[k],_tabLambda[k]); //tabSigma[k] = tabShape[k]*tabLambda[k] - - } - break; - - - //-------------------- - case (Gaussian_p_Lk_B) : - case (Gaussian_pk_Lk_B) : - //-------------------- - while (iter){ - /* Pb Overflow */ - for (k=0; k<_nbCluster; k++){ - if (_tabLambda[k] < minOverflow) - throw errorSigmaConditionNumber; - } - - /* Compute matrix B */ - (*B)=0.0; - for (k=0; k<_nbCluster; k++){ - Bk->equalToMatrixDividedByDouble(_tabWk[k],_tabLambda[k]); //_tabShape[k] = _tabW[k]/_tabLambda[k] - (*B) += Bk; // B->operator+=(Bk) : B=somme sur k des Bk - } - /* Compute det(B) */ - logDet = B->determinant(minDeterminantBValueError); - detB = powAndCheckIfNotNull(logDet, power); - - /* Compute Shape[k] and Lambda[k] */ - for (k=0; k<_nbCluster; k++){ - // W_k = _tabWk[k]->getDiagonalValue(); - _tabWk[k]->putDiagonalValueInStore(W_k); - _tabShape[k]->equalToMatrixDividedByDouble(B,detB); - Shape_k = _tabShape[k]->getStore(); - tmp = 0.0; - for(p=0; p<_pbDimension ; p++){ - tmp += W_k[p] / Shape_k[p]; - } - tmp /= (_pbDimension*tabNk[k]); - - _tabLambda[k] = tmp; - if ( _tabLambda[k] < minOverflow) - throw errorSigmaConditionNumber; - } - iter--; - } - - for (k=0; k<_nbCluster; k++){ - _tabSigma[k]->equalToMatrixMultiplyByDouble(_tabShape[k],_tabLambda[k]); - } - - break; - - - default : - //------ - throw internalMixmodError; - break; - } - - updateTabInvSigmaAndDet() ; - delete Bk; - delete B; - delete [] W_k; -} - - - - - -//------------------- -//getLogLikelihoodOne -//------------------- -double XEMGaussianDiagParameter::getLogLikelihoodOne() const{ - - /* Compute log-likelihood for one cluster - useful for NEC criterion */ - - /* Initialization */ - int64_t nbSample = _model->getNbSample(); - int64_t i; - XEMGaussianData * data = (XEMGaussianData*)(_model->getData()); - double logLikelihoodOne; // Log-likelihood for k=1 - double * Mean = new double[_pbDimension] ; - double ** y = data->_yStore; - double * yi; - XEMDiagMatrix * Sigma = new XEMDiagMatrix(_pbDimension); - XEMDiagMatrix * W = new XEMDiagMatrix(_pbDimension, 0.0); - double norme, logDet, detDiagW ; - double * weight = data->_weight; - // Mean Estimator (empirical estimator) - double totalWeight = data->_weightTotal; - computeMeanOne(Mean,weight,y,nbSample,totalWeight); - weight = data->_weight; - - /* Compute the Cluster Scattering Matrix W */ - int64_t p; // parcours - double * xiMoinsMuk = data->getTmpTabOfSizePbDimension(); - - for(i=0; iadd(xiMoinsMuk, weight[i]); - } - - /* Compute determinant of diag(W) */ - logDet = W->detDiag(minDeterminantDiagWValueError); // virtual - detDiagW = powAndCheckIfNotNull(logDet ,1.0/_pbDimension); - Sigma->equalToMatrixDividedByDouble(W, totalWeight); // virtual - - // inverse of Sigma - //XEMDiagMatrix * SigmaMoins1 = new XEMDiagMatrix(_pbDimension); - XEMMatrix * SigmaMoins1 = NULL; -// SigmaMoins1->inverse(Sigma);// virtual - Sigma->inverse(SigmaMoins1); //construction de SigmaMoins1 dans la fonction inverse - - double detSigma = Sigma->determinant(minDeterminantSigmaValueError); // virtual - - // Compute the log-likelihood for one cluster (k=1) - logLikelihoodOne = 0.0; - for (i=0; inorme(xiMoinsMuk); // virtual - logLikelihoodOne += norme * weight[i]; - } - - logLikelihoodOne += totalWeight * ( data->getPbDimensionLog2Pi() + log(detSigma)) ; - logLikelihoodOne *= -0.5 ; - - delete W; - delete Sigma; - delete SigmaMoins1; - - delete[] Mean; - return logLikelihoodOne; -} - - - -//---------------- -//getFreeParameter -//---------------- -int64_t XEMGaussianDiagParameter::getFreeParameter() const{ - int64_t nbParameter; // Number of parameters // - int64_t k = _nbCluster; // Sample size // - int64_t d = _pbDimension; // Sample dimension // - - int64_t alphaR = k*d; // alpha for for models with Restrainct proportions (Gaussian_p_...) - int64_t alphaF = (k*d) + k-1; // alpha for models with Free proportions (Gaussian_pk_...) - - switch (_modelType->_nameModel) { - case (Gaussian_p_L_B) : - nbParameter = alphaR + d; - break; - case (Gaussian_p_Lk_B) : - nbParameter = alphaR + d + k - 1; - break; - case (Gaussian_p_L_Bk) : - nbParameter = alphaR + (k*d) - k + 1; - break; - case (Gaussian_p_Lk_Bk) : - nbParameter = alphaR + (k*d); - break; - case (Gaussian_pk_L_B) : - nbParameter = alphaF + d; - break; - case (Gaussian_pk_Lk_B) : - nbParameter = alphaF + d + k - 1; - break; - case (Gaussian_pk_L_Bk) : - nbParameter = alphaF + (k*d) - k + 1; - break; - case (Gaussian_pk_Lk_Bk) : - nbParameter = alphaF + (k*d); - break; - default : - throw internalMixmodError; - break; - } - return nbParameter; -} - diff --git a/lib/src/mixmod/MIXMOD/XEMGaussianDiagParameter.h b/lib/src/mixmod/MIXMOD/XEMGaussianDiagParameter.h deleted file mode 100644 index 4f5091a..0000000 --- a/lib/src/mixmod/MIXMOD/XEMGaussianDiagParameter.h +++ /dev/null @@ -1,99 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMGaussianDiagParameter.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMGaussianDiagParameter_H -#define XEMGaussianDiagParameter_H - -#include "XEMGaussianEDDAParameter.h" -#include "XEMMatrix.h" -#include "XEMDiagMatrix.h" - -/** - @brief Derived class of XEMGaussianParameter for Spherical Gaussian Model(s) - @author F Langrognet & A Echenim -*/ - -class XEMGaussianDiagParameter : public XEMGaussianEDDAParameter{ - - public: - - /// Default constructor - XEMGaussianDiagParameter(); - - /// Constructor - // called by XEMModel - XEMGaussianDiagParameter(XEMModel * iModel, XEMModelType * iModelType); - - /// Constructor (copy) - XEMGaussianDiagParameter(const XEMGaussianDiagParameter * iParameter); - - /// Destructor - virtual ~XEMGaussianDiagParameter(); - - /// reset to default values - virtual void reset(); - - /** @brief Selector - @return A copy of the model - */ - XEMParameter * clone() const; - - /// initialisation USER - void initUSER(XEMParameter * iParam); - - /// Compute table of sigmas of the samples of each cluster - // NB : compute also lambda, shpae, orientation, wk, w - void computeTabSigma(); - - - // SELECTORS - // ------ / -------- // - - double * getTabLambda() const; - - //double ** getTabShape(); - XEMDiagMatrix** getTabShape() const; - - double getLogLikelihoodOne() const; - - int64_t getFreeParameter() const; - - protected : - /// Table of volume of each cluster - double * _tabLambda; /* Volume */ - - //double ** _tabShape; - XEMDiagMatrix** _tabShape; - - -}; - -inline double * XEMGaussianDiagParameter::getTabLambda() const{ - return _tabLambda; -} - -inline XEMDiagMatrix** XEMGaussianDiagParameter::getTabShape() const{ - return _tabShape; -} -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMGaussianEDDAParameter.cpp b/lib/src/mixmod/MIXMOD/XEMGaussianEDDAParameter.cpp deleted file mode 100644 index d09a41d..0000000 --- a/lib/src/mixmod/MIXMOD/XEMGaussianEDDAParameter.cpp +++ /dev/null @@ -1,583 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMGaussianEDDAParameter.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMGaussianEDDAParameter.h" -#include "XEMGaussianParameter.h" -#include "XEMGaussianData.h" -#include "XEMModel.h" - - - -#include "XEMGaussianGeneralParameter.h" -#include "XEMUtil.h" -#include "XEMGaussianData.h" -#include "XEMRandom.h" - -#include "XEMMatrix.h" -#include "XEMDiagMatrix.h" -#include "XEMSphericalMatrix.h" -#include "XEMSymmetricMatrix.h" -#include "XEMGeneralMatrix.h" - -//-------------------- Constructors-------------- - -XEMGaussianEDDAParameter::XEMGaussianEDDAParameter():XEMGaussianParameter(){ - throw wrongConstructorType; -} - - -//-------------- -// constructor -//------------- -XEMGaussianEDDAParameter::XEMGaussianEDDAParameter(XEMModel * iModel, XEMModelType * iModelType): XEMGaussianParameter(iModel, iModelType){ - _tabInvSqrtDetSigma = new double [_nbCluster]; - for (int64_t k=0; k<_nbCluster; k++){ - _tabInvSqrtDetSigma[k] = 1.0; - } - _tabInvSigma = new XEMMatrix* [_nbCluster]; - _tabSigma = new XEMMatrix* [_nbCluster]; -} - - - - -//------------------------------------------ -// constructor called if USER_initialisation -//------------------------------------------- -XEMGaussianEDDAParameter::XEMGaussianEDDAParameter(int64_t iNbCluster, int64_t iPbDimension, XEMModelType * iModelType) : XEMGaussianParameter(iNbCluster, iPbDimension, iModelType){ - _tabInvSqrtDetSigma = new double [_nbCluster]; - for (int64_t k=0; k<_nbCluster; k++){ - _tabInvSqrtDetSigma[k] = 0.0; - } - _tabInvSigma = new XEMMatrix* [_nbCluster]; - _tabSigma = new XEMMatrix* [_nbCluster]; -} - - - -//----------------- -// copy constructor -//----------------- -XEMGaussianEDDAParameter::XEMGaussianEDDAParameter(const XEMGaussianEDDAParameter * iParameter):XEMGaussianParameter(iParameter){ - int64_t k; - _tabInvSqrtDetSigma = new double[_nbCluster]; - double * iTabInvSqrtDetSigma = iParameter->getTabInvSqrtDetSigma(); - for (k=0; k<_nbCluster; k++){ - _tabInvSqrtDetSigma[k] = iTabInvSqrtDetSigma[k]; - } - _tabInvSigma = new XEMMatrix* [_nbCluster]; - _tabSigma = new XEMMatrix* [_nbCluster]; -} - - - - - -/**************/ -/* Destructor */ -/**************/ -XEMGaussianEDDAParameter::~XEMGaussianEDDAParameter(){ - if (_tabInvSqrtDetSigma){ - delete[] _tabInvSqrtDetSigma; - _tabInvSqrtDetSigma = NULL; - } - - if(_tabInvSigma){ - delete[] _tabInvSigma; - _tabInvSigma = NULL; - } - - if(_tabSigma){ - delete[] _tabSigma; - _tabSigma = NULL; - } - -} - - -//------------------------ -// reset to default values -//------------------------ -void XEMGaussianEDDAParameter::reset(){ - for (int64_t k=0; k<_nbCluster; k++){ - _tabInvSqrtDetSigma[k] = 0.0; - *(_tabSigma[k]) = 1.0; - *(_tabInvSigma[k]) = 1.0; - } - XEMGaussianParameter::reset(); -} - - - - -void XEMGaussianEDDAParameter::getAllPdf(double** tabFik,double* tabProportion)const{ - - XEMGaussianData * data = (XEMGaussianData*)(_model->getData()); - int64_t nbSample = _model->getNbSample(); - double * muk ; // to store mu_k - double InvPiInvDetProp; // 1/(pi)^(d/2) * 1/det(\Sigma_k) ^ (.5) * p_k - XEMMatrix * SigmakMoins1; - double ** matrix = data->getYStore(); // to store x_i i=1,...,n - - double ** p_matrix; // pointeur : parcours de y - double ** p_tabFik_i; // pointeur : parcours de tabFik - - double norme; - - // parcours - int64_t i; // parcours des individus - int64_t k; // cluster index - - double * xiMoinsMuk = data->getTmpTabOfSizePbDimension(); - double * xi; - int64_t p; - - for(k=0 ; k<_nbCluster ; k++){ - InvPiInvDetProp = data->getInv2PiPow() * _tabInvSqrtDetSigma[k] * tabProportion[k]; - muk = _tabMean[k]; - SigmakMoins1 = _tabInvSigma[k]; - - //computing - p_matrix = matrix; // pointe sur la premiere ligne des donnees - p_tabFik_i = tabFik; - for(i=0 ; inorme(xiMoinsMuk); // virtual !! - (*p_tabFik_i)[k] = InvPiInvDetProp * exp(-0.5 * norme); - - p_matrix++; - p_tabFik_i++; - } // end for i - } // end for k - -} - - -//------- -// getPdf -//------- -double XEMGaussianEDDAParameter::getPdf(XEMSample * x, int64_t kCluster)const{ - - XEMGaussianData * data = (XEMGaussianData*)(_model->getData()); - - double normPdf = 0.0; /* Normal pdf */ - double invPi = data->getInv2PiPow() ; /* Inverse of (2*Pi)^(d/2) */ - - /* Compute (x-m)*inv(S)*(x-m)' */ - double * ligne = ((XEMGaussianSample*)x)->getTabValue(); - - XEMMatrix * Sigma_kMoins1 = _tabInvSigma[kCluster]; - - double norme; - double * muk = _tabMean[kCluster]; - double * xiMoinsMuk = data->getTmpTabOfSizePbDimension(); - int64_t p; - - for(p=0; p<_pbDimension; p++){ - xiMoinsMuk[p] = ligne[p] - muk[p]; - } - - // calcul de la norme (x-muk)'Sigma_k^{-1} (x-muk) - norme = Sigma_kMoins1->norme(xiMoinsMuk); // virtual - - /* Compute normal density */ - normPdf = invPi * _tabInvSqrtDetSigma[kCluster] * exp( -0.5 * norme); - - return normPdf; -} - - - - - -double XEMGaussianEDDAParameter::getPdf(int64_t iSample, int64_t kCluster)const{ - - XEMGaussianData * data = (XEMGaussianData*)(_model->getData()); - double * x = (data->getYStore())[iSample]; - - XEMMatrix * Sigma_kCluster_moins1 = _tabInvSigma[kCluster]; - - double norme; - - double * xiMoinsMuk = data->getTmpTabOfSizePbDimension(); - double * muk = _tabMean[kCluster]; - - int64_t p; - - for(p=0; p<_pbDimension; p++){ - xiMoinsMuk[p] = x[p] - muk[p]; - } - - // calcul de la norme (x-muk)'Sigma_k^{-1} (x-muk) - norme = Sigma_kCluster_moins1->norme(xiMoinsMuk); // virtual - - double normPdf; - - // Compute normal density - normPdf = data->getInv2PiPow() * _tabInvSqrtDetSigma[kCluster] * exp(-0.5*norme); - - return normPdf; -} - - - - -void XEMGaussianEDDAParameter::updateTabInvSigmaAndDet(){ - int64_t k; - double detSigma; - for (k=0; k<_nbCluster; k++){ - detSigma = _tabSigma[k]->determinant(minDeterminantSigmaValueError); - _tabSigma[k]->inverse(_tabInvSigma[k]); - _tabInvSqrtDetSigma[k] = 1.0 / sqrt(detSigma); - } - -} - - -//--------- -// MAP step -//--------- -// update _tabWk and _W. -// No need for this algo but if CV is the criterion, these values -// must be updated -/*void XEMGaussianEDDAParameter::MAPStep(){ - computeTabWkW(); - }*/ - - - -//-------------------- -// init USER_PARTITION -//-------------------- -void XEMGaussianEDDAParameter::initForInitUSER_PARTITION(int64_t & nbInitializedCluster, bool * tabNotInitializedCluster, XEMPartition * initPartition){ - // init : tabSigma, _tabInvSigma, _tabInvSqrtDetSigma, - XEMDiagMatrix * matrixDataVar = new XEMDiagMatrix(_pbDimension,0.0); - computeGlobalDiagDataVariance(matrixDataVar); - // Vaiance matrix initialization to variance matrix of data (Symmetric, Diag or Spherical) - for (int64_t k=0; k<_nbCluster; k++){ - (*_tabSigma[k]) = matrixDataVar; - } - updateTabInvSigmaAndDet(); - delete matrixDataVar; - - // _tabMean - computeTabMeanInitUSER_PARTITION(nbInitializedCluster, tabNotInitializedCluster, initPartition); -} - - - - - -void XEMGaussianEDDAParameter::initUSER(XEMParameter * iParam){ - /* - updated : _tabMean, _tabWk, _tabSigma, _tabProportion, _tabShape, _tabOrientation, _tabInvSigma, _tabInvSqrtDetSigma - */ - - // recuperation - // we got an XEMGaussianGeneralParameter - // because of the implementation in class XEMStrategyType - // in gaussian cases the init parameters are allways General - XEMGaussianGeneralParameter * param = (XEMGaussianGeneralParameter *) iParam; - double ** iTabMean = param->getTabMean(); - double * iTabProportion = param->getTabProportion(); - XEMMatrix ** iTabWk = param->getTabWk(); - XEMMatrix ** iTabSigma = param->getTabSigma(); - int64_t k; - for (k=0; k<_nbCluster; k++){ - recopyTab(iTabMean[k], _tabMean[k], _pbDimension); - (* _tabWk[k]) = iTabWk[k]; - (* _tabSigma[k]) = iTabSigma[k]; - if (hasFreeProportion(_modelType->_nameModel)) { - _tabProportion[k] = iTabProportion[k]; - } - else{ - _tabProportion[k] = 1.0 / _nbCluster; - } - } -} - - - -void XEMGaussianEDDAParameter::input(ifstream & fi){ - // verify paramFile - double tmp; - int64_t cpt=0; - fi.clear(); - fi.seekg(0, ios::beg); - //while (!fi.eof()){ - while (fi>>tmp){ // retourne NULL si on est �la fin - cpt++; - } - int64_t goodValue = _nbCluster * (1 + _pbDimension + _pbDimension*_pbDimension); - - if(cpt != goodValue){ - throw errorInitParameter; - } - - fi.clear(); - fi.seekg(0, ios::beg); - - int64_t j,k; - double * muk; - for (k=0; k<_nbCluster; k++){ - muk = _tabMean[k]; - // Proportions // - fi >> _tabProportion[k]; - // Center (mean) // - for (j=0; j<_pbDimension; j++){ - fi >> muk[j]; - } - // Variance matrix // - _tabSigma[k]->input(fi) ; // virtual method - } // end for k -} - - - - - -void XEMGaussianEDDAParameter::updateForCV(XEMModel * originalModel, XEMCVBlock & CVBlock){ - XEMGaussianParameter::updateForCV(originalModel,CVBlock); - computeTabSigma(); -} - - - -/*------------------------------------------------------------------------------------------- - M step - ------ - - already updated : - - _model (_tabFik, _tabTik, _tabCik, _tabNk) if Estep is done before - - _model->_tabCik, _model->_tabNk if USER_PARTITION is done before (Disciminant analysis) - In all cases, only _tabCik and _tabNk are needed - - updated in this method : - - in XEMGaussianParameter::MStep : - - _tabProportion - - _tabMean - - _tabWk - - _W - - here : - - _tabSigma - - _tabInvSigma - - _tabInvSqrtDetSigma - --------------------------------------------------------------------------------------------*/ -void XEMGaussianEDDAParameter::MStep(){ - XEMGaussianParameter::MStep(); - computeTabSigma(); -} - - - - - - -//-------------------------------------------- -// initialize attributes before an InitRandom -//-------------------------------------------- -void XEMGaussianEDDAParameter::initForInitRANDOM(){ - XEMDiagMatrix * matrixDataVar = new XEMDiagMatrix(_pbDimension,0.0); - computeGlobalDiagDataVariance(matrixDataVar); - - // Vaiance matrix initialization to variance matrix of data (Symmetric, Diag or Spherical) - // init : tabSigma, _tabInvSigma, _tabInvSqrtDetSigma, - for (int64_t k=0; k<_nbCluster; k++){ - (*_tabSigma[k]) = matrixDataVar; - } - updateTabInvSigmaAndDet(); - - delete matrixDataVar; -} - - - - - -//----------------------------------------- -// computeTik when underflow -// -model->_tabSumF[i] pour ith sample = 0 -// i : 0 ->_nbSample-1 -//----------------------------------------- -void XEMGaussianEDDAParameter::computeTikUnderflow(int64_t i, double ** tabTik){ - - XEMGaussianData * data = (XEMGaussianData*)(_model->getData()); - int64_t * lnFk = new int64_t [_nbCluster]; - long double * lnFkPrim = new long double[_nbCluster]; - long double * fkPrim = new long double[_nbCluster]; - int64_t k,k0; - long double lnFkMax, fkTPrim; - long double detSigma; - - double * ligne = (data->getYStore())[i]; - long double norme; - double ** p_tabMean; - double * tabTik_i = tabTik[i]; - - double * xiMoinsMuk = data->getTmpTabOfSizePbDimension(); - double * muk; - - p_tabMean = _tabMean; - int64_t p; - for (k=0; k<_nbCluster; k++){ - detSigma = (_tabSigma[k])->determinant(minDeterminantSigmaValueError); // virtual method - muk = *p_tabMean; - for(p=0; p<_pbDimension; p++){ - xiMoinsMuk[p] = ligne[p] - muk[p]; - } - norme = (_tabInvSigma[k])->norme(xiMoinsMuk); // virtual method - - // compute lnFik[k] - - lnFk[k] = log(_tabProportion[k]) - data->getHalfPbDimensionLog2Pi() - 0.5*log(detSigma) - 0.5*norme; - - p_tabMean++; - } // end for k - - lnFkMax = lnFk[0]; - for (k=1; k<_nbCluster; k++){ - if (lnFk[k] > lnFkMax){ - lnFkMax = lnFk[k]; - } - } - - - fkTPrim = 0.0; - for (k=0; k<_nbCluster; k++){ - lnFkPrim[k] = lnFk[k] - lnFkMax; - fkPrim[k] = exp(lnFkPrim[k]); - fkTPrim += fkPrim[k]; - } - - // compute tabTik - if (fkTPrim == 0){ - // reset tabTik - initToZero(tabTik_i, _nbCluster); - k0 = XEMGaussianParameter::computeClassAssigment(i); - tabTik_i[k0] = 1.0; - } - else{ - for (k=0; k<_nbCluster; k++){ - tabTik_i[k] = fkPrim[k] / fkTPrim; - } - } - - delete [] lnFk; - delete [] lnFkPrim; - delete [] fkPrim; - -} - - - - -void XEMGaussianEDDAParameter::edit(){ - int64_t k; - for (k=0; k<_nbCluster; k++){ - cout<<"\tcomponent : " << k << endl; - cout<<"\t\tproportion : " << _tabProportion[k]<edit(cout, "\t\t\t"); - - cout<<"\t\tWk : "<edit(cout,"\t\t\t"); - - cout<<"\t\tinvSigma : "<edit(cout,"\t\t\t"); - - cout<<"\t\ttabInvSqrtDetSigma : "<<_tabInvSqrtDetSigma[k]<edit(cout, "\t\t"); - -} - - - - - - -//------ -// Edit -//------- -void XEMGaussianEDDAParameter::edit(ofstream & oFile, bool text){ - int64_t k; - if (text){ - for (k=0; k<_nbCluster; k++){ - oFile<<"\t\t\tComponent "<edit(oFile, "\t\t\t\t"); - - oFile<edit(oFile, ""); - oFile<getTabMean(), _tabMean, _nbCluster, _pbDimension); - // _W->recopy(iParameter->getW()); - (*_W) = iParameter->getW(); - - int64_t k; - XEMMatrix ** iTabSigma = iParameter->getTabSigma(); - XEMMatrix ** iTabInvSigma = iParameter->getTabInvSigma(); - XEMMatrix ** iTabWk = iParameter->getTabWk(); - for(k=0; k<_nbCluster; k++){ - // _tabSigma[k]->recopy(iTabSigma[k]); - (* _tabSigma[k]) = iTabSigma[k]; - // _tabInvSigma[k]->recopy(iTabInvSigma[k]); - (*_tabInvSigma[k]) = iTabInvSigma[k]; - // _tabWk[k]->recopy(iTabWk[k]); - (* _tabWk[k]) = iTabWk[k]; - } - recopyTab(iParameter->getTabInvSqrtDetSigma(), _tabInvSqrtDetSigma, _nbCluster); - -} - diff --git a/lib/src/mixmod/MIXMOD/XEMGaussianEDDAParameter.h b/lib/src/mixmod/MIXMOD/XEMGaussianEDDAParameter.h deleted file mode 100644 index d467896..0000000 --- a/lib/src/mixmod/MIXMOD/XEMGaussianEDDAParameter.h +++ /dev/null @@ -1,156 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMGaussianEDDAParameter.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMGaussianEDDAParameter_H -#define XEMGaussianEDDAParameter_H - -#include "XEMGaussianParameter.h" -#include "XEMMatrix.h" -#include "XEMGeneralMatrix.h" -#include "XEMOldInput.h" - -class XEMGaussianEDDAParameter : public XEMGaussianParameter{ - - public: - - /// Default constructor - XEMGaussianEDDAParameter(); - - /// Constructor - // called by XEMModel - XEMGaussianEDDAParameter(XEMModel * iModel, XEMModelType * iModelType); - - - /// Constructor - // called if USER initialisation - XEMGaussianEDDAParameter(int64_t iNbCluster, int64_t iPbDimension, XEMModelType * iModelType); - - - /// Constructor - XEMGaussianEDDAParameter(const XEMGaussianEDDAParameter * iParameter); - - /// Destructor - virtual ~XEMGaussianEDDAParameter(); - - /// reset to default values - virtual void reset(); - - - /** @brief Selector - @return Table of inverse of sqrt of determinant of covariance matrix for each cluster - */ - double * getTabInvSqrtDetSigma() const; - - /** @brief Selector - @return Table of inverse of covariance matrix for each cluster - */ - XEMMatrix ** getTabInvSigma() const; - - - /** @brief Selector - @return Table of covariance matrix for each cluster - */ - - XEMMatrix ** getTabSigma() const; - - /// Compute normal probability density function - /// for iSample the sample and kCluster th cluster - double getPdf(int64_t iSample, int64_t kCluster) const; - - - /// compute normal probability density function - /// for all i=1,..,n and k=1,..,K - void getAllPdf(double ** tabFik,double * tabProportion) const; - - - /// compute normal probability density function - /// for the line x within the kCluster cluster - double getPdf(XEMSample * x, int64_t kCluster) const; - - void updateTabInvSigmaAndDet() ; - - void computeTikUnderflow(int64_t i, double ** tabTik); - - void edit(); - - void edit(ofstream & oFile, bool text=false); - - void recopy(XEMParameter * otherParameter); - - virtual int64_t getFreeParameter() const= 0; - virtual void computeTabSigma() = 0; - - void updateForCV(XEMModel * originalModel, XEMCVBlock & CVBlock) ; - - - virtual XEMParameter* clone() const = 0 ; - void MStep(); - void MAPStep(); - virtual void input(ifstream & fi); - - - //init - //---- - - /// User initialisation of the parameters of the model - virtual void initUSER(XEMParameter * iParam); - - - /// initialize attributes before an initRANDOM - void initForInitRANDOM(); - - - /// initialize attributes for init USER_PARTITION - /// outputs : - /// - nbInitializedCluster - /// - tabNotInitializedCluster (array of size _nbCluster) - void initForInitUSER_PARTITION(int64_t & nbInitializedCluster, bool * tabNotInitializedCluster, XEMPartition * initPartition); - - protected : - /// Table of inverse of covariance matrix of each cluster - XEMMatrix ** _tabInvSigma; - - /// Table of covariance Matrix of each cluster - XEMMatrix ** _tabSigma; - - /// 1/det(Sigma) - double * _tabInvSqrtDetSigma; - - -}; - - -inline double * XEMGaussianEDDAParameter::getTabInvSqrtDetSigma() const{ - return _tabInvSqrtDetSigma; -} - -inline XEMMatrix ** XEMGaussianEDDAParameter::getTabInvSigma() const{ - return _tabInvSigma; -} - -inline XEMMatrix ** XEMGaussianEDDAParameter::getTabSigma() const{ - return _tabSigma; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMGaussianGeneralParameter.cpp b/lib/src/mixmod/MIXMOD/XEMGaussianGeneralParameter.cpp deleted file mode 100644 index 3e44186..0000000 --- a/lib/src/mixmod/MIXMOD/XEMGaussianGeneralParameter.cpp +++ /dev/null @@ -1,981 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMGaussianGeneralParameter.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMGaussianGeneralParameter.h" -#include "XEMGaussianEDDAParameter.h" -#include "XEMGaussianData.h" -#include "XEMModel.h" -#include "XEMDiagMatrix.h" -#include "XEMSymmetricMatrix.h" -#include "XEMGeneralMatrix.h" - -/****************/ -/* Constructors */ -/****************/ - -//---------------------------------------------------- -//---------------------------------------------------- -XEMGaussianGeneralParameter::XEMGaussianGeneralParameter(){ - throw wrongConstructorType; -} - - - -//------------------------------------------------------------------------------------- -// constructor called by XEMModel -//------------------------------------------------------------------------------------- -XEMGaussianGeneralParameter::XEMGaussianGeneralParameter(XEMModel * iModel, XEMModelType * iModelType): XEMGaussianEDDAParameter(iModel, iModelType){ - int64_t k; - _tabShape = new XEMDiagMatrix*[_nbCluster]; - _tabOrientation = new XEMGeneralMatrix*[_nbCluster]; - _tabLambda = new double [_nbCluster]; - _W = new XEMSymmetricMatrix(_pbDimension); //Id - - for (k=0; k<_nbCluster; k++){ - _tabShape[k] = new XEMDiagMatrix(_pbDimension); // Id - _tabOrientation[k] = new XEMGeneralMatrix(_pbDimension);//Id - _tabLambda[k] = 1.0; - _tabSigma[k] = new XEMSymmetricMatrix(_pbDimension); //Id - _tabInvSigma[k] = new XEMSymmetricMatrix(_pbDimension); //Id - _tabWk[k] = new XEMSymmetricMatrix(_pbDimension); //Id - } - - __storeDim = _pbDimension * (_pbDimension + 1) / 2; -} - - - - -//------------------------------------------------------------------------------------- -//constructeur avec une initialisation USER -//------------------------------------------------------------------------------------- -XEMGaussianGeneralParameter::XEMGaussianGeneralParameter(int64_t iNbCluster, int64_t iPbDimension, XEMModelType * iModelType, string & iFileName) : XEMGaussianEDDAParameter(iNbCluster, iPbDimension, iModelType){ - int64_t k; - __storeDim = _pbDimension * (_pbDimension + 1) / 2; - _tabShape = new XEMDiagMatrix*[_nbCluster]; - _tabOrientation = new XEMGeneralMatrix*[_nbCluster]; - _tabLambda = new double [_nbCluster]; - - for (k=0; k<_nbCluster; k++){ - _tabShape[k] = new XEMDiagMatrix(_pbDimension); //Id - _tabOrientation[k] = new XEMGeneralMatrix(_pbDimension); //Id - _tabLambda[k] = 1.0; - - // _tabSigma, _tabInvSigma, _tabWk will be initialized in XEMGaussianEDDAparameter - _tabInvSigma[k] = new XEMSymmetricMatrix(_pbDimension); //Id - _tabSigma[k] = new XEMSymmetricMatrix(_pbDimension); // Id - _tabWk[k] = new XEMSymmetricMatrix(_pbDimension); //Id - *_tabWk[k] = 1.0; - } - _W = new XEMSymmetricMatrix(_pbDimension); //Id - - // read parameters in file iFileName// - if (iFileName.compare("") != 0){ - ifstream paramFile(iFileName.c_str(), ios::in); - if (! paramFile.is_open()){ - throw wrongParamFileName; - } - input(paramFile); - paramFile.close(); - } - - updateTabInvSigmaAndDet(); // method of XEMGaussianParameter - -} - - - -//------------------------------------------------------------------------------------- -//constructeur par copie -//------------------------------------------------------------------------------------- -XEMGaussianGeneralParameter::XEMGaussianGeneralParameter(const XEMGaussianGeneralParameter * iParameter):XEMGaussianEDDAParameter(iParameter){ - int64_t k; - __storeDim = _pbDimension * (_pbDimension + 1) / 2; - _tabShape = new XEMDiagMatrix*[_nbCluster]; - _tabOrientation = new XEMGeneralMatrix*[_nbCluster]; - _tabLambda = new double[_nbCluster]; - XEMDiagMatrix ** iTabShape = iParameter->getTabShape(); - XEMGeneralMatrix ** iTabOrientation = iParameter->getTabOrientation(); - double * iTabLambda = iParameter->getTabLambda(); - XEMMatrix ** iTabSigma = iParameter->getTabSigma(); - XEMMatrix ** iTabInvSigma = iParameter->getTabInvSigma(); - XEMMatrix ** iTabWk = iParameter->getTabWk(); - _W = new XEMSymmetricMatrix((XEMSymmetricMatrix *)(iParameter->getW())); - - for (k=0; k<_nbCluster; k++){ - //_tabInvSigma[k] = NULL; - _tabShape[k] = new XEMDiagMatrix(iTabShape[k]); // copy constructor - _tabOrientation[k] = new XEMGeneralMatrix(iTabOrientation[k]); // copy constructor - _tabLambda[k] = iTabLambda[k]; - - _tabSigma[k] = new XEMSymmetricMatrix(_pbDimension); - (* _tabSigma[k]) = iTabSigma[k]; - _tabWk[k] = new XEMSymmetricMatrix(_pbDimension); - (* _tabWk[k]) = iTabWk[k]; - _tabInvSigma[k] = new XEMSymmetricMatrix(_pbDimension); - (* _tabInvSigma[k]) = iTabInvSigma[k]; - } -} - - - -/**************/ -/* Destructor */ -/**************/ -XEMGaussianGeneralParameter::~XEMGaussianGeneralParameter(){ - int64_t k; - - if (_tabShape){ - for (k=0;k<_nbCluster;k++){ - delete _tabShape[k]; - _tabShape[k] = NULL; - } - delete[] _tabShape; - _tabShape = NULL; - } - - if (_tabOrientation){ - for (k=0;k<_nbCluster;k++){ - delete _tabOrientation[k]; - _tabOrientation[k] = NULL; - } - delete[] _tabOrientation; - _tabOrientation = NULL; - } - - if (_tabLambda){ - delete[] _tabLambda; - _tabLambda = NULL; - } - - if (_tabInvSigma){ - for(k=0; k<_nbCluster; k++){ - delete _tabInvSigma[k]; - _tabInvSigma[k] = NULL; - } - } - - if (_tabSigma){ - //cout<<"destructeur gaussgene"<getTabShape(); - XEMGeneralMatrix ** iTabOrientation = param->getTabOrientation(); - double * iTabLambda = param->getTabLambda(); - int64_t k; - for (k=0; k<_nbCluster; k++){ - (*_tabShape[k]) = (iTabShape[k]); // copy constructor - (* _tabOrientation[k]) = iTabOrientation[k]; // copy constructor - _tabLambda[k] = iTabLambda[k]; - } - -} - - - -/***********************/ -/* computeTabSigma_L_C */ -/***********************/ -void XEMGaussianGeneralParameter::computeTabSigma_L_C(){ - int64_t k; - double totalWeight = ((XEMGaussianData*)(_model->getData()))->_weightTotal; - for(k=0; k<_nbCluster; k++){ - _tabSigma[k]->equalToMatrixDividedByDouble(_W, totalWeight); // :: Sigma_k = W / totalWeight - } -} - - - -/*************************/ -/* computeTabSigma_Lkk_Ck */ -/*************************/ -void XEMGaussianGeneralParameter::computeTabSigma_Lk_Ck(){ - int64_t k; - double * tabNk = _model->getTabNk(); - for (k=0; k<_nbCluster; k++){ - _tabSigma[k]->equalToMatrixDividedByDouble(_tabWk[k], tabNk[k]); // :: Sigma_k = W_k / n_k - } -} - - - -/************************/ -/* computeTabSigma_L_Ck */ -/************************/ -void XEMGaussianGeneralParameter::computeTabSigma_L_Ck(){ - double lambda = 0.0; - int64_t k; - double logDet; - XEMGaussianData * data = (XEMGaussianData*)(_model->getData()); - double totalWeight = data->_weightTotal; - double detWk_k,tmp; - double * detWk = new double[_nbCluster]; - - try { - for (k=0; k<_nbCluster; k++){ - logDet = _tabWk[k]->determinant(minDeterminantWkValueError ); - detWk_k = powAndCheckIfNotNull(logDet ,1.0/_pbDimension); - lambda += detWk_k; - detWk[k] = detWk_k; - } - - lambda /= totalWeight; // lambda = somme sur k detWk^(1/pbDimension) / totalWeight - if (lambda < minOverflow){ - throw errorSigmaConditionNumber; - } - - for (k=0; k<_nbCluster; k++){ - _tabLambda[k] = lambda; - tmp = detWk[k] / lambda; - _tabSigma[k]->equalToMatrixDividedByDouble(_tabWk[k], tmp); // :: Sigma_k = Wk / tmp - } - - delete [] detWk; - detWk = NULL; - } - catch (XEMErrorType errorType) { - delete [] detWk; - detWk = NULL; - throw errorType; - } -} - - - -/*****************************/ -/* computeTabSigma_L_Dk_A_Dk */ -/*****************************/ -void XEMGaussianGeneralParameter::computeTabSigma_L_Dk_A_Dk(){ - - //Ma modification - int64_t k; - XEMGaussianData * data = (XEMGaussianData*)(_model->getData()); - XEMDiagMatrix* Shape = new XEMDiagMatrix(_pbDimension, 0.0); //0.0 - double logDet; - double detShape; - double totalWeight = data->_weightTotal; - double * tabShape_k_store; - // SVD Decomposition of Cluster Scattering Matrix (Symmetric) Wk: Wk=U*S*U' - - - - try{ - - for (k=0; k<_nbCluster; k++){ - _tabWk[k]->computeSVD(_tabShape[k], _tabOrientation[k]); - tabShape_k_store = _tabShape[k]->getStore(); - (*Shape) += _tabShape[k]; - } - - // Compute determinant of Shape matrix - logDet = Shape->determinant(minDeterminantShapeValueError); - detShape = powAndCheckIfNotNull(logDet , 1.0/_pbDimension); - - for (k=0; k<_nbCluster; k++){ - _tabLambda[k] = detShape / totalWeight; //determinant de la somme sur k de _tabShape[k] / totalWeight - if (_tabLambda[k]equalToMatrixDividedByDouble(Shape,detShape); // _tabShape[k] = somme sur k de _tabShape / determinant de la somme sur k de _tabShape[k] - _tabSigma[k]->compute_as__multi_O_S_O(_tabLambda[k], _tabOrientation[k], _tabShape[k]) ; - } - - delete Shape; - } - catch(XEMErrorType errorType){ - delete Shape; - throw errorType; - } -} - - - -/********************************/ -/* computeTabSigma_Lk_Dk_A_Dk() */ -/********************************/ -void XEMGaussianGeneralParameter::computeTabSigma_Lk_Dk_A_Dk(){ - int64_t k; - int64_t iter = 5; - - XEMDiagMatrix* Shape = new XEMDiagMatrix(_pbDimension); //Id - XEMDiagMatrix* S = new XEMDiagMatrix(_pbDimension);//Id - double * tabNk = _model->getTabNk(); - - XEMDiagMatrix ** tabS = new XEMDiagMatrix*[_nbCluster]; - XEMGeneralMatrix ** tabU = new XEMGeneralMatrix*[_nbCluster]; - for(k=0; k<_nbCluster ; k++){ - tabS[k] = new XEMDiagMatrix(_pbDimension); //Id - tabU[k] = new XEMGeneralMatrix(_pbDimension); //Id - } - - - double logDet; - double detShape; - - try{ - // SVD Decomposition of Cluster Scattering Matrix (Symmetric) Wk: Wk=U*S*U' - for (k=0; k<_nbCluster; k++){ - _tabWk[k] ->computeSVD(tabS[k],tabU[k]); - } - while (iter){ - - (*Shape)=0.0; - for (k=0; k<_nbCluster; k++){ - (S)->equalToMatrixDividedByDouble(tabS[k],_tabLambda[k]); - (*Shape) += S; - } - - - //Compute determinant of Shape matrix - logDet = Shape->determinant(minDeterminantShapeValueError); - detShape = powAndCheckIfNotNull(logDet,1.0/_pbDimension); - - for (k=0; k<_nbCluster; k++){ - _tabShape[k]->equalToMatrixDividedByDouble(Shape,detShape); //A=_tabShape = somme sur k 1/lambdak*Shape - _tabLambda[k] = _tabWk[k]->trace_this_O_Sm1_O(tabU[k], _tabShape[k]); - _tabLambda[k] /= (_pbDimension*tabNk[k]); - - if (_tabLambda[k]trace_this_O_Sm1_O(_tabOrientation[k], _tabShape[k]); //trace(Wk Dk A^(-1) Dk') / pbDimension*tabNk - _tabLambda[k] /= (_pbDimension*tabNk[k]); - - if (_tabLambda[k]compute_as__multi_O_S_O(_tabLambda[k], _tabOrientation[k], _tabShape[k]); - } - - - for(k=0; k<_nbCluster; k++){ - delete tabS[k]; - tabS[k] = NULL; - delete tabU[k]; - tabU[k] = NULL; - } - delete [] tabU; - delete [] tabS; - delete Shape; - delete S; - - } - - catch(XEMErrorType errorType){ - for(k=0; k<_nbCluster; k++){ - delete tabS[k]; - tabS[k] = NULL; - delete tabU[k]; - tabU[k] = NULL; - } - delete [] tabU; - delete [] tabS; - delete Shape; - delete S; - throw errorType; - } -} - - - - - - -/************************/ -/* computeTabSigma_Lk_C */ -/************************/ -void XEMGaussianGeneralParameter::computeTabSigma_Lk_C(){ - - int64_t k; - double * tabNk = _model->getTabNk(); - XEMSymmetricMatrix * C = new XEMSymmetricMatrix(_pbDimension); //Id - XEMMatrix * R = new XEMSymmetricMatrix(_pbDimension); - XEMMatrix * Inv; - Inv = new XEMSymmetricMatrix(_pbDimension); - double logDet, detR; - int64_t iter = 5; - - try { - - while (iter){ - // Inv = NULL; - (*R)=0.0; - for (k=0; k<_nbCluster; k++){ - R->compute_product_Lk_Wk(_tabWk[k], _tabLambda[k]); // on calcule Wk/Lk - } - - logDet = R->determinant(minDeterminantRValueError); - detR = powAndCheckIfNotNull(logDet,1.0/_pbDimension); - C->equalToMatrixDividedByDouble(R,detR); // C = somme sur k de 1/lambdak * Wk / det (somme sur k de 1/lambdak * Wk )^(1/d) - - C->inverse(Inv); - for (k=0; k<_nbCluster; k++){ - _tabLambda[k] = _tabWk[k]->compute_trace_W_C(Inv); //lambdak = trace(Wk C^(-1)) / pbDimension * tabNk - _tabLambda[k] /= (_pbDimension*tabNk[k]); - - if (_tabLambda[k]getData()); - int64_t k; - int64_t iter = 5; - double diff, FOld, F; - double sumTraceM = 0.0; - double lambda, logDet, DetDiagQtmp; - XEMDiagMatrix * Shape_0 = new XEMDiagMatrix(_pbDimension);//Id - - /* Flury algorithm */ - /* SVD Decomposition of Cluster Scattering Matrix (Symmetric) Wk: Wk=U*S*U' */ - /* Orientation matrix initialisation: _tabOrientation */ - try{ - (*Shape_0) = (_tabShape[0]); - _tabWk[0]-> computeSVD(_tabShape[0], _tabOrientation[0]); - (*_tabShape[0]) = ( Shape_0); - - /* Compute Lambda: _lambda */ - /* Mtmp = D*Ak^-1*D'*Wk */ - - - for (k=0; k<_nbCluster; k++){ - sumTraceM += _tabWk[k]->trace_this_O_Sm1_O(_tabOrientation[0], _tabShape[k]); - } - lambda = sumTraceM/(_pbDimension*data->_weightTotal); // lambda = somme sur k de trace(D Ak^(-1) D' Wk) / weightTotal - - diff = 10.0; - FOld = 0.0; - F = 0.0; - /* Iterative procedure 1 */ - while ((iter) && (diff > defaultFluryEpsilon)){ - /* Compute Shape matrix: _tabShape */ - /* Mtmp = D*Wk^-1*D' */ - - F = 0.0; - - for (k=0; k<_nbCluster; k++){ - F += _tabWk[k]->trace_this_O_Sm1_O(_tabOrientation[0], _tabShape[k]); - - _tabWk[k]->computeShape_as__diag_Ot_this_O(_tabShape[k], _tabOrientation[0]); - logDet = _tabShape[k]->determinant(minDeterminantDiagQtmpValueError); - DetDiagQtmp = powAndCheckIfNotNull(logDet ,1.0/_pbDimension); - (*_tabShape[k]) /= DetDiagQtmp; // tabShpaek = Ak = diag(D' Wk D) / det(diag(D' Wk D))^(1/d) - } - - FOld = F; - F = flury(F); - diff = fabs(F-FOld); - iter--; - } - - if (lambda < minOverflow){ - throw errorSigmaConditionNumber; - } - - for (k=0; k<_nbCluster; k++){ - _tabLambda[k] = lambda; - _tabSigma[k]->compute_as__multi_O_S_O(lambda, _tabOrientation[0], _tabShape[k]); - } - delete Shape_0; - - } - catch(XEMErrorType errorType){ - delete Shape_0; - Shape_0 = NULL; - throw errorType; - } - -} - - - - -/*****************************/ -/* computeTabSigma_Lk_D_Ak_D */ -/*****************************/ -void XEMGaussianGeneralParameter::computeTabSigma_Lk_D_Ak_D(){ - - double * tabNk = _model->getTabNk(); - int64_t k, iter = 5; - - /* Flury algorithm */ - /* SVD Decomposition of Cluster Scattering Matrix (Symmetric) Wk: Wk=U*S*U' */ - //((XEMSymmetricMatrix *) _tabWk[0]) -> computeSVD(_tabShape[0], _tabOrientation[0]); - - _tabWk[0] -> computeSVD(_tabShape[0], _tabOrientation[0]); - - double diff = 10.0; - double F = 0.0; - double FOld, logDet; - - /* Iterative procedure 1 */ - while ((iter) && (diff > defaultFluryEpsilon)){ - /* Compute Shape matrix: _tabShape[k] */ - /* Qtmp = D*Wk^-1*D' */ - for (k=0; k<_nbCluster; k++){ - _tabWk[k]->computeShape_as__diag_Ot_this_O(_tabShape[k], _tabOrientation[0], tabNk[k]); // - logDet = (_tabShape[k])->determinant(minDeterminantShapeValueError); - } - FOld = F; - F = flury(F); - diff = fabs(F-FOld); - iter--; - } - - for (k=0; k<_nbCluster; k++){ - - (*_tabOrientation[k]) = _tabOrientation[0]; - //((XEMSymmetricMatrix *)_tabSigma[k])->compute_as__multi_O_S_O(1.0, _tabOrientation[k], _tabShape[k]); - _tabSigma[k]->compute_as__multi_O_S_O(1.0, _tabOrientation[k], _tabShape[k]); - } - -} - - - - -/*******************/ -/* computeTabSigma */ -/*******************/ -//------------------------------------------------/ -/* Variance estimator for each of general model */ -//------------------------------------------------/ -void XEMGaussianGeneralParameter::computeTabSigma(){ - switch (_modelType->_nameModel) { - - case (Gaussian_p_L_C) : - case (Gaussian_pk_L_C) : - computeTabSigma_L_C(); - break; - case (Gaussian_p_Lk_Ck) : - case (Gaussian_pk_Lk_Ck) : - computeTabSigma_Lk_Ck(); - break; - case (Gaussian_p_L_Ck) : - case (Gaussian_pk_L_Ck) : - computeTabSigma_L_Ck(); - break; - case (Gaussian_p_L_Dk_A_Dk) : - case (Gaussian_pk_L_Dk_A_Dk) : - computeTabSigma_L_Dk_A_Dk(); - break; - case (Gaussian_p_Lk_Dk_A_Dk) : - case (Gaussian_pk_Lk_Dk_A_Dk) : - computeTabSigma_Lk_Dk_A_Dk(); - break; - case (Gaussian_p_Lk_C) : - case (Gaussian_pk_Lk_C) : - computeTabSigma_Lk_C(); - break; - case (Gaussian_p_L_D_Ak_D) : - case (Gaussian_pk_L_D_Ak_D) : - computeTabSigma_L_D_Ak_D(); - break; - case (Gaussian_p_Lk_D_Ak_D) : - case (Gaussian_pk_Lk_D_Ak_D) : - computeTabSigma_Lk_D_Ak_D(); - break; - default : - throw internalMixmodError; - break; - } - - updateTabInvSigmaAndDet(); -} - - - -//---------------- -// Flury Algorithm -//---------------- -double XEMGaussianGeneralParameter::flury(double F){ - - // coefficients de la matrice a� diagonaliser - // [ a b ] - // M = [ ] - // [ b c ] - double a, b, c; - // plus petite valeur propre - double eigenValueMoins; - // vecteur propre associe a� eigenValueMoins - double eigenVectorMoins_1; - double eigenVectorMoins_2; - int64_t k,il,im, iter=0; - double diff = 10; - double FOld, tmp, tmp2, termesHorsDiag,termesDiag; - double * Wk_store; - int64_t p,q,r; - double * tabShape_k_store; - double * Ori = _tabOrientation[0]->getStore(); - XEMGaussianData * data = (XEMGaussianData*)(_model->getData()); - double * D_im = data->getTmpTabOfSizePbDimension(); - double * D_il = new double[_pbDimension]; - int64_t il_p, im_p; - double iSim_iSil_k; - - while ((iter < maxFluryIter) && ( diff > defaultFluryEpsilon)){ - - /* Compute orientation matrix: _tabOrientation */ - for (il=0; il<_pbDimension; il++){ - for (im=il+1; im<_pbDimension; im++){ - - /* Extraction of colums dl and dm */ - il_p = il; - im_p = im; - for(p=0;p<_pbDimension;p++){ - D_il[p] = Ori[il_p]; // remplir la colonne 1 : - D_im[p] = Ori[im_p]; // remplir la colonne 2 : - - il_p += _pbDimension; - im_p += _pbDimension; - } - - /* Compute matrix R where q1 is the second eigen vector */ - //RR_store = RR.Store(); - //initToZero(RR_store,4); - - a = 0.0; - b = 0.0; - c = 0.0; - - for (k=0; k<_nbCluster; k++){ - - //Wk_store = ((XEMSymmetricMatrix *)_tabWk[k])->getStore(); - Wk_store = _tabWk[k]->getSymmetricStore(); - tabShape_k_store = _tabShape[k]->getStore(); - iSim_iSil_k = 1.0 / tabShape_k_store[il] - 1.0 / tabShape_k_store[im] ; - - // remplir RR(1,1) - termesHorsDiag = termesDiag = 0.0; - for(p=0,r=0; p<_pbDimension ; p++,r++){ - tmp = D_il[p] ; // Dlm(p+1,1); - for(q=0; q

trace_this_O_Sm1_O(_tabOrientation[0], _tabShape[k]); - F += _tabWk[k]->trace_this_O_Sm1_O(_tabOrientation[0], _tabShape[k]); - } - - diff = fabs(F-FOld); - - iter++; - } - - delete[] D_il; - return F; -} - - - -//------------------- -//getLogLikelihoodOne -//------------------- -double XEMGaussianGeneralParameter::getLogLikelihoodOne() const{ - /* Compute log-likelihood for one cluster - useful for NEC criterion */ - - /* Initialization */ - int64_t nbSample = _model->getNbSample(); - int64_t i; - XEMGaussianData * data = (XEMGaussianData*)(_model->getData()); - double logLikelihoodOne; // Log-likelihood for k=1 - double * Mean = new double[_pbDimension] ; - double ** y = data->_yStore; - double * yi; - XEMSymmetricMatrix * Sigma = new XEMSymmetricMatrix(_pbDimension); //Id - XEMSymmetricMatrix * W = new XEMSymmetricMatrix(_pbDimension, 0.0); // 0.0 - double norme, logDet, detDiagW ; - double * weight = data->_weight; - - // Mean Estimator (empirical estimator) - double totalWeight = data->_weightTotal; - computeMeanOne(Mean,weight,y,nbSample,totalWeight); - weight = data->_weight; - - /* Compute the Cluster Scattering Matrix W */ - - int64_t p; // parcours - double * xiMoinsMuk = data->getTmpTabOfSizePbDimension(); - - for(i=0; iadd(xiMoinsMuk, weight[i]); - } - /* Compute determinant of diag(W) */ - logDet = W->detDiag(minDeterminantDiagWValueError); // virtual - detDiagW = powAndCheckIfNotNull(logDet ,1.0/_pbDimension); - - Sigma->equalToMatrixDividedByDouble(W, totalWeight); // virtual - - // inverse of Sigma - - //XEMSymmetricMatrix * SigmaMoins1 = new XEMSymmetricMatrix(_pbDimension); - XEMMatrix* SigmaMoins1 = NULL; - //SigmaMoins1->inverse(Sigma);// virtual - Sigma->inverse(SigmaMoins1); - - double detSigma = Sigma->determinant(minDeterminantSigmaValueError); // virtual - - - // Compute the log-likelihood for one cluster (k=1) - logLikelihoodOne = 0.0; - for (i=0; inorme(xiMoinsMuk); // virtual - logLikelihoodOne += norme * weight[i]; - } - - logLikelihoodOne += totalWeight * ( data->getPbDimensionLog2Pi() + log(detSigma)) ; - logLikelihoodOne *= -0.5 ; - - delete W; - delete Sigma; - delete SigmaMoins1; - - delete[] Mean; - - return logLikelihoodOne; -} - - -//---------------- -//getFreeParameter -//---------------- -int64_t XEMGaussianGeneralParameter::getFreeParameter() const{ - int64_t nbParameter; // Number of parameters // - int64_t k = _nbCluster; // Sample size // - int64_t d = _pbDimension; // Sample dimension // - - int64_t alphaR = k*d; // alpha for for models with Restrainct proportions (Gaussian_p_...) - int64_t alphaF = (k*d) + k-1; // alpha for models with Free proportions (Gaussian_pk_...) - int64_t beta = d*(d+1)/2; - - switch (_modelType->_nameModel) { - case (Gaussian_p_L_C): - nbParameter = alphaR + beta; - break; - case (Gaussian_p_Lk_C): - nbParameter = alphaR + beta + (k-1); - break; - case (Gaussian_p_L_D_Ak_D): - nbParameter = alphaR + beta + (k-1)*(d-1); - break; - case (Gaussian_p_Lk_D_Ak_D): - nbParameter = alphaR+beta + (k-1)*d; - break; - case (Gaussian_p_L_Dk_A_Dk): - nbParameter = alphaR + (k*beta) - (k-1)*d; - break; - case (Gaussian_p_Lk_Dk_A_Dk): - nbParameter = alphaR + (k*beta) - (k-1)*(d-1); - break; - case (Gaussian_p_L_Ck): - nbParameter = alphaR + (k*beta) - (k-1); - break; - case (Gaussian_p_Lk_Ck): - nbParameter = alphaR + (k*beta); - break; - case (Gaussian_pk_L_C): - nbParameter = alphaF + beta; - break; - case (Gaussian_pk_Lk_C): - nbParameter = alphaF + beta + (k-1); - break; - case (Gaussian_pk_L_D_Ak_D): - nbParameter = alphaF + beta + (k-1)*(d-1); - break; - case (Gaussian_pk_Lk_D_Ak_D): - nbParameter = alphaF + beta + (k-1)*d; - break; - case (Gaussian_pk_L_Dk_A_Dk): - nbParameter = alphaF + (k*beta) - (k-1)*d; - break; - case (Gaussian_pk_Lk_Dk_A_Dk): - nbParameter = alphaF + (k*beta) - (k-1)*(d-1); - break; - case (Gaussian_pk_L_Ck): - nbParameter = alphaF + (k*beta) - (k-1); - break; - case (Gaussian_pk_Lk_Ck): - nbParameter = alphaF + (k*beta); - break; - default : - throw internalMixmodError; - break; - } - return nbParameter; -} - - diff --git a/lib/src/mixmod/MIXMOD/XEMGaussianGeneralParameter.h b/lib/src/mixmod/MIXMOD/XEMGaussianGeneralParameter.h deleted file mode 100644 index 7c0a43d..0000000 --- a/lib/src/mixmod/MIXMOD/XEMGaussianGeneralParameter.h +++ /dev/null @@ -1,138 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMGaussianGeneralParameter.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMGaussianGeneralParameter_H -#define XEMGaussianGeneralParameter_H - -#include "XEMGaussianEDDAParameter.h" -#include "XEMMatrix.h" -#include "XEMGeneralMatrix.h" -#include "XEMSymmetricMatrix.h" - -/** - @brief Derived class of XEMGaussianParameter for Spherical Gaussian Model(s) - @author F Langrognet & A Echenim -*/ - -class XEMGaussianGeneralParameter : public XEMGaussianEDDAParameter{ - - public: - - /// Default constructor - XEMGaussianGeneralParameter(); - - /// Constructor - // called by XEMModel - XEMGaussianGeneralParameter(XEMModel * iModel, XEMModelType * iModelType); - - // Constructor - // called by XEMStrategyType if initialization is USER - XEMGaussianGeneralParameter(int64_t iNbCluster, int64_t iPbDimension, XEMModelType * iModelType, string & iFileName); - - /// Constructor (copy) - XEMGaussianGeneralParameter(const XEMGaussianGeneralParameter * iParameter); - - - /// Destructor - virtual ~XEMGaussianGeneralParameter(); - - /// reset to default values - virtual void reset(); - - /** @brief Selector - @return A copy of the model - */ - XEMParameter * clone() const; - - void initUSER(XEMParameter * iParam); - - /// Compute table of sigmas of the samples of each cluster - // NB : compute also lambda, shape, orientation, wk, w - void computeTabSigma(); - - /// Flury Algorithm - /// return the value of Flury function - double flury(double F); - - - // SELECTORS - // ------ / -------- // - double * getTabLambda() const; - - /** @brief Selector - @return Table of shape matrix for each cluster - */ - XEMDiagMatrix ** getTabShape() const; - - /** @brief Selector - @return Table of orientation matrix for each cluster - */ - XEMGeneralMatrix ** getTabOrientation() const; - - - double getLogLikelihoodOne() const; - - protected : - /// Table of volume of each cluster - double * _tabLambda; /* Volume */ - - - /// Table of shape matrix of each cluster - XEMDiagMatrix ** _tabShape; /* Shape */ - - // Table of orientation matrix of each cluster - XEMGeneralMatrix ** _tabOrientation; /* Orientation */ - - int64_t __storeDim; - - // model dependant methods for computing _tabSigma - void computeTabSigma_L_C(); - void computeTabSigma_Lk_Ck(); - void computeTabSigma_L_Ck(); - void computeTabSigma_L_Dk_A_Dk(); - void computeTabSigma_Lk_Dk_A_Dk(); - void computeTabSigma_Lk_C(); - void computeTabSigma_L_D_Ak_D(); - void computeTabSigma_Lk_D_Ak_D(); - - //void recopySymmetricMatrixInMatrix(SymmetricMatrix & sym, Matrix& mat, double facteur); - - int64_t getFreeParameter() const; - -}; - - -inline XEMDiagMatrix ** XEMGaussianGeneralParameter::getTabShape() const{ - return _tabShape; -} - -inline XEMGeneralMatrix ** XEMGaussianGeneralParameter::getTabOrientation() const{ - return _tabOrientation; -} - -inline double * XEMGaussianGeneralParameter::getTabLambda() const{ - return _tabLambda; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMGaussianHDDAParameter.cpp b/lib/src/mixmod/MIXMOD/XEMGaussianHDDAParameter.cpp deleted file mode 100644 index 8ff7a12..0000000 --- a/lib/src/mixmod/MIXMOD/XEMGaussianHDDAParameter.cpp +++ /dev/null @@ -1,1677 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMGaussianHDDAParameter.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMGaussianHDDAParameter.h" -#include "XEMGaussianParameter.h" -#include "XEMGaussianData.h" -#include "XEMModel.h" - - - -#include "XEMGaussianGeneralParameter.h" -#include "XEMUtil.h" -#include "XEMGaussianData.h" -#include "XEMRandom.h" - -#include "XEMMatrix.h" -#include "XEMDiagMatrix.h" -#include "XEMSphericalMatrix.h" -#include "XEMGeneralMatrix.h" - -/****************/ -/* Constructors */ -/****************/ - -//---------------------------------------------------- -//---------------------------------------------------- -XEMGaussianHDDAParameter::XEMGaussianHDDAParameter():XEMGaussianParameter(){ - throw wrongConstructorType; -} - - - -//------------------------------------------------------------------------------------- -// constructor called by XEMModel -//------------------------------------------------------------------------------------- -XEMGaussianHDDAParameter::XEMGaussianHDDAParameter( XEMModel * iModel, XEMModelType * iModelType): XEMGaussianParameter(iModel, iModelType){ - int64_t k; - - _tabAkj = new double*[_nbCluster]; - _tabBk = new double[_nbCluster]; - _tabShape = new XEMDiagMatrix*[_nbCluster]; - _tabQk = new XEMGeneralMatrix*[_nbCluster]; - _W = new XEMSymmetricMatrix(_pbDimension); //Id - _tabDk = new int64_t [_nbCluster]; - _tabGammak = NULL; - _Gammak = NULL; - - - for (k=0; k<_nbCluster; k++){ - _tabShape[k] = new XEMDiagMatrix(_pbDimension); //Id - _tabQk[k] = new XEMGeneralMatrix(_pbDimension); //Id - _tabWk[k] = new XEMSymmetricMatrix(_pbDimension); // Id - _tabDk[k] = 0; - } - __storeDim = _pbDimension * (_pbDimension + 1) / 2; - - - if ((iModelType->_tabSubDimensionFree !=NULL) && - isFreeSubDimension(iModelType->_nameModel)){ - for (k=0;k<_nbCluster;k++){ - _tabDk[k] = iModelType->_tabSubDimensionFree[k]; - } - } - else if ((iModelType->_subDimensionEqual !=0) && - !isFreeSubDimension(iModelType->_nameModel)){ - for (k=0;k<_nbCluster;k++){ - _tabDk[k] = iModelType->_subDimensionEqual; - } - } - - for (k=0;k<_nbCluster;k++){ - _tabAkj[k] = new double[_tabDk[k]]; - for (int64_t j=0;j<_tabDk[k];j++){ - _tabAkj[k][j] = 1.0; - } - _tabBk[k] = 1.0; // /(_pbDimension - _tabDk[k]); - } - -} - - - -//constructeur avec une initialisation USER -//------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------- -XEMGaussianHDDAParameter::XEMGaussianHDDAParameter(int64_t iNbCluster, int64_t iPbDimension, XEMModelType * iModelType, string & iFileName) : XEMGaussianParameter(iNbCluster, iPbDimension, iModelType){ - int64_t k; - _tabAkj = new double*[_nbCluster]; - _tabBk = new double[_nbCluster]; - _tabDk = new int64_t [_nbCluster]; - _tabGammak = NULL; - _Gammak = NULL; - __storeDim = _pbDimension * (_pbDimension + 1) / 2; - - _tabShape = new XEMDiagMatrix*[_nbCluster]; - _tabQk = new XEMGeneralMatrix*[_nbCluster]; - - - for (k=0; k<_nbCluster; k++){ - _tabShape[k] = new XEMDiagMatrix(_pbDimension); //Id - _tabQk[k] = new XEMGeneralMatrix(_pbDimension); //Id - _tabWk[k] = new XEMSymmetricMatrix(_pbDimension); //Id - _tabAkj[k] = NULL; - } - _W = new XEMSymmetricMatrix(_pbDimension); //Id - - // read parameters in file iFileName// - if (iFileName.compare("") != 0){ - ifstream paramFile(iFileName.c_str(), ios::in); - if (! paramFile.is_open()){ - throw wrongParamFileName; - } - input(paramFile); - paramFile.close(); - } - -} - - -//constructeur par copie -//------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------- -XEMGaussianHDDAParameter::XEMGaussianHDDAParameter(const XEMGaussianHDDAParameter * iParameter):XEMGaussianParameter(iParameter){ - int64_t k; - __storeDim = _pbDimension * (_pbDimension + 1) / 2; - int64_t * iTabD = iParameter->getTabD(); - double ** iTabA = iParameter->getTabA(); - double *iTabB = iParameter->getTabB(); - - _tabShape = new XEMDiagMatrix*[_nbCluster]; - _tabQk = new XEMGeneralMatrix*[_nbCluster]; - _tabDk = new int64_t [_nbCluster]; - _tabAkj = new double*[_nbCluster]; - _tabBk = new double[_nbCluster]; - - XEMDiagMatrix ** iTabShape = iParameter->getTabShape(); - XEMGeneralMatrix ** iTabQ = iParameter->getTabQ(); - XEMMatrix ** iTabWk = iParameter->getTabWk(); - - _tabGammak = NULL; - _Gammak = NULL; - _W = new XEMSymmetricMatrix(_pbDimension);//Id - (* _W) = iParameter->getW(); - - recopyTab(iTabD,_tabDk,_nbCluster); - recopyTab(iTabB,_tabBk,_nbCluster); - - for (k=0; k<_nbCluster; k++){ - _tabAkj[k] = new double[_tabDk[k]]; - recopyTab(iTabA[k], _tabAkj[k],_tabDk[k]); - _tabShape[k] = new XEMDiagMatrix(iTabShape[k]); - _tabQk[k] = new XEMGeneralMatrix(iTabQ[k]); // copy constructor - _tabWk[k] = new XEMSymmetricMatrix(_pbDimension); //Id - (* _tabWk[k]) = iTabWk[k]; - } - -} - - - - - - -/**************/ -/* Destructor */ -/**************/ -XEMGaussianHDDAParameter::~XEMGaussianHDDAParameter(){ - int64_t k; - if (_tabShape){ - for (k=0;k<_nbCluster;k++){ - delete _tabShape[k]; - _tabShape[k] = NULL; - } - delete[] _tabShape; - _tabShape = NULL; - } - - if (_tabQk){ - for (k=0;k<_nbCluster;k++){ - delete _tabQk[k]; - _tabQk[k] = NULL; - } - delete[] _tabQk; - _tabQk = NULL; - } - - if (_tabAkj){ - for (k=0;k<_nbCluster;k++){ - delete[] _tabAkj[k]; - _tabAkj[k] = NULL; - } - delete[] _tabAkj; - _tabAkj = NULL; - } - - if(_tabBk){ - delete[] _tabBk; - _tabBk = NULL; - } - - if (_tabDk){ - delete[] _tabDk; - _tabDk = NULL; - } - - if (_Gammak){ - for (k=0;k<_nbCluster;k++){ - delete[] _Gammak[k]; - _Gammak[k] = NULL; - } - delete[] _Gammak; - _Gammak = NULL; - } - - if(_tabGammak){ - for(k=0; k<_nbCluster; k++){ - delete _tabGammak[k]; - } - delete[] _tabGammak; - _tabGammak = NULL; - } -} - - - - -//------------------------ -// reset to default values -//------------------------ -void XEMGaussianHDDAParameter::reset(){ - throw internalMixmodError; - // faire ensuite : XEMGaussianParameter::reset(); -} - - - - -/*********/ -/* clone */ -/*********/ -XEMParameter * XEMGaussianHDDAParameter::clone() const{ - XEMGaussianHDDAParameter * newParam = new XEMGaussianHDDAParameter(this); - return(newParam); -} - - - - -/*********/ -/* MStep */ -/********/ -void XEMGaussianHDDAParameter::MStep(){ - XEMGaussianParameter::MStep(); - - switch(_modelType->_nameModel){ - case (Gaussian_HD_pk_AkjBkQkDk) : - case (Gaussian_HD_p_AkjBkQkDk) : - case (Gaussian_HD_pk_AkjBkQkD) : - case (Gaussian_HD_p_AkjBkQkD) : - computeAkjBkQk(); - break; - - case (Gaussian_HD_pk_AkBkQkDk) : - case (Gaussian_HD_p_AkBkQkDk) : - case (Gaussian_HD_pk_AkBkQkD) : - case (Gaussian_HD_p_AkBkQkD) : - computeAkBkQk(); - break; - - case (Gaussian_HD_p_AkjBQkD): - case (Gaussian_HD_pk_AkjBQkD): - computeAkjBQk(); - break; - - case (Gaussian_HD_p_AkBQkD): - case (Gaussian_HD_pk_AkBQkD): - computeAkBQk(); - break; - - case (Gaussian_HD_p_AjBkQkD): - case (Gaussian_HD_pk_AjBkQkD): - computeAjBkQk(); - break; - - case (Gaussian_HD_p_AjBQkD): - case (Gaussian_HD_pk_AjBQkD): - computeAjBQk(); - break; - default : throw internalMixmodError; - } - -} - - - -//**********/ -/* getPdf */ -/**********/ -// returns the density of a sample using the cost function property Cost = -2LL -double XEMGaussianHDDAParameter::getPdf(int64_t iSample, int64_t kCluster)const{ - - XEMGaussianData * data = (XEMGaussianData*)(_model->getData()); - double * ligne = (data->getYStore())[iSample]; - double normPdf = 0, K = 0; - - XEMParameter * parameter = _model->getParameter(); - XEMGaussianParameter* gparameter = (XEMGaussianParameter*)parameter; - double ** tabMean = gparameter->getTabMean(); - double* tabProportion = gparameter->getTabProportion(); - double * xiMoinsMuk = new double[_pbDimension]; - double* tabShapek_store = new double[_pbDimension]; - - - //----------------calcul le produit Q*t(Q)--------------- - - XEMSymmetricMatrix* Pk = new XEMSymmetricMatrix(_pbDimension); //Id - Pk->compute_as_M_tM(_tabQk[kCluster], _tabDk[kCluster]); - - //---------------calcul du produit A = Qi_L^-1_t(Qi)------------------ - - XEMSymmetricMatrix* A = new XEMSymmetricMatrix(_pbDimension); //id - - double sum_lambda = 0.0; - for (int64_t j=0;j<_tabDk[kCluster];j++){ - tabShapek_store[j] = 1/_tabAkj[kCluster][j]; - sum_lambda += log(_tabAkj[kCluster][j]); - } - for (int64_t j=_tabDk[kCluster]; j<_pbDimension;j++){ - tabShapek_store[j] = 0.0; - } - A->compute_as_O_S_O(_tabQk[kCluster], tabShapek_store); - - double constante = sum_lambda + (_pbDimension-_tabDk[kCluster])*log(_tabBk[kCluster])-2*log(tabProportion[kCluster])+_pbDimension*log(2*XEMPI); - - - - //-----------soustraction des moyennes - for (int64_t j=0;j<_pbDimension;j++){ - xiMoinsMuk[j] = ligne[j] - tabMean[kCluster][j]; - } - - //-----------produit Qt(Q)(x-muk)---------------------- - - XEMSymmetricMatrix * Pi = new XEMSymmetricMatrix(_pbDimension); //Id - Pi->compute_as_M_V(Pk,xiMoinsMuk); - double * storePi = Pi->getStore(); - - //----------------norme(muk-Pi(x))_A = t(muk-Pi(x))_A_(muk-Pi(x))----------- - double normeA = A->norme(xiMoinsMuk); - - //----------------norme(x-Pi(x))------------------------------ - double norme = 0.0; - for (int64_t i=0;i<_pbDimension;i++){ - storePi[i] += tabMean[kCluster][i]; - norme += (ligne[i] - storePi[i])*(ligne[i] - storePi[i]); - } - - //----------------calcul de normPdf--------- - K = normeA + 1.0/_tabBk[kCluster]*norme + constante; - normPdf = exp(-1/2*K); - - delete Pk; - delete A; - delete Pi; - delete[] xiMoinsMuk; - xiMoinsMuk = NULL; - delete[] tabShapek_store; - tabShapek_store = NULL; - - return normPdf; -} - - - - - -/*************/ -/* getAllPdf */ -/*************/ -// returns the density of all the data (tabFik) -void XEMGaussianHDDAParameter::getAllPdf(double ** tabFik,double * tabProportion)const{ - //cout<<"XEMGaussianHDDAParameter::getAllPdf"<getNbSample(); - - for (int64_t i=0; igetTabValue(); - double normPdf = 0, K = 0; - XEMParameter * parameter = _model->getParameter(); - XEMGaussianParameter* gparameter = (XEMGaussianParameter*)parameter; - double ** tabMean = gparameter->getTabMean(); - double* tabProportion = gparameter->getTabProportion(); - double * xiMoinsMuk = new double[_pbDimension]; - double* tabShapek_store = new double[_pbDimension]; - - - //----------------calcul le produit Q*t(Q)--------------- - - XEMSymmetricMatrix* Pk = new XEMSymmetricMatrix(_pbDimension); //Id - Pk->compute_as_M_tM(_tabQk[kCluster],_tabDk[kCluster]); - - //---------------calcul du produit A = Qi_L^-1_t(Qi)------------------ - - XEMSymmetricMatrix* A = new XEMSymmetricMatrix(_pbDimension); //Id - - - double sum_lambda = 0.0; - for (int64_t j=0;j<_tabDk[kCluster];j++){ - tabShapek_store[j] = 1/_tabAkj[kCluster][j]; - sum_lambda += log(_tabAkj[kCluster][j]); - } - for (int64_t j=_tabDk[kCluster];j<_pbDimension;j++){ - tabShapek_store[j] = 0.0; - } - - A->compute_as_O_S_O(_tabQk[kCluster], tabShapek_store); - - double constante = sum_lambda + (_pbDimension-_tabDk[kCluster])*log(_tabBk[kCluster])-2*log(tabProportion[kCluster])+_pbDimension*log(2*XEMPI); - - //-----------soustraction des moyennes - for (int64_t j=0;j<_pbDimension;j++){ - xiMoinsMuk[j] = ligne[j] - tabMean[kCluster][j]; - } - - //-----------produit Qt(Q)(x-muk)---------------------- - - XEMSymmetricMatrix * Pi = new XEMSymmetricMatrix(_pbDimension); //Id - Pi->compute_as_M_V(Pk,xiMoinsMuk); - double * storePi = Pi->getStore(); - - //----------------norme(muk-Pi(x))_A = t(muk-Pi(x))_A_(muk-Pi(x))----------- - double normeA = A->norme(xiMoinsMuk); - - //----------------norme(x-Pi(x))------------------------------ - double norme = 0.0; - for (int64_t i=0;i<_pbDimension;i++){ - storePi[i] += tabMean[kCluster][i]; - norme += (ligne[i] - storePi[i])*(ligne[i] - storePi[i]); - } - - //----------------calcul de normPdf--------- - K = normeA + 1.0/_tabBk[kCluster]*norme + constante; - normPdf = exp(-1/2*K); - - delete Pk; - delete A; - delete Pi; - delete[] xiMoinsMuk; - xiMoinsMuk = NULL; - delete[] tabShapek_store; - tabShapek_store = NULL; - - return normPdf; -} - - - - -/*********/ -/* input */ -/*********/ -// reads the input data file for HDDA models -void XEMGaussianHDDAParameter::input(ifstream & fi){ - int64_t j,k; - for (k=0; k<_nbCluster; k++){ - // Proportions // - fi >> _tabProportion[k]; - // Center (mean) // - for (j=0; j<_pbDimension; j++){ - fi >> _tabMean[k][j]; - } - - // Sub Dimension // - fi >> _tabDk[k]; - if (_tabAkj[k]){ - //cout<<_tabAkj[k][0]<> _tabAkj[k][j]; - } - - // Parameters Bk // - fi >> _tabBk[k]; - // Orientation matrix // - _tabQk[k]->input(fi,_tabDk[k]) ; // virtual method - } // end for k - -} - - - - -/*****************/ -/* computeTabWkW */ -/*****************/ -//computes W_k and W but also _tabGammak and Gammak -void XEMGaussianHDDAParameter:: computeTabWkW(){ - double* tabNk = _model->getTabNk(); - double ** tabCik = _model->getTabCik(); - int64_t nbSample = _model->getNbSample(); - XEMGaussianData * data = (XEMGaussianData*)(_model->getData()); - double * weight = data->_weight; - int64_t i; - double ** matrix = data->getYStore(); // to store x_i i=1,...,n - int64_t j, k, l, dimStoreG; - - k = 0; - while(k < _nbCluster){ - if(tabNk[k]<_pbDimension){ - _tabGammak = new XEMSymmetricMatrix*[_nbCluster]; - k = _nbCluster; - } - else{ - k++; - } - } - - - XEMGaussianParameter::computeTabWkW(); - - for (k=0;k<_nbCluster;k++){ - if ((tabNk[k]<_pbDimension) && (_tabDk[k] < (tabNk[k]+1))){ - l = 0; - double test = floor(tabNk[k]); - if (test==tabNk[k]){ - _Gammak = new double*[_nbCluster]; - int64_t nk = (int64_t ) tabNk[k]; - _tabGammak[k] = new XEMSymmetricMatrix(nk); //Id - dimStoreG = nk * _pbDimension; - _Gammak[k] = new double[dimStoreG]; - for (i=0;icompute_M_tM(_Gammak[k],dimStoreG); - } - else{ - throw tabNkNotInteger; - } // end test - } - } // fin for k -} - - - - - -//------------------------------------------- -// initialize attributes before an InitRandom -//------------------------------------------- -void XEMGaussianHDDAParameter::initForInitRANDOM(){ - throw internalMixmodError; -} - - - - -//--------------------------- -// initForInitUSER_PARTITION -//-------------------------- -void XEMGaussianHDDAParameter::initForInitUSER_PARTITION(int64_t & nbInitializedCluster, bool * tabNotInitializedCluster, XEMPartition * initPartition){ - computeTabMeanInitUSER_PARTITION(nbInitializedCluster, tabNotInitializedCluster, initPartition); - // initialization of _tabAkj, ;... : - - XEMDiagMatrix * matrixDataVar = new XEMDiagMatrix(_pbDimension,0.0); - computeGlobalDiagDataVariance(matrixDataVar); - matrixDataVar->sortDiagMatrix(); - - double * store = matrixDataVar->getStore(); - double sum_lambda = 0.0; - - for (int64_t k=0; k<_nbCluster; k++){ - *_tabQk[k] = 1.0; - } - - for (int64_t j=0;j<_tabDk[0];j++){ - _tabAkj[0][j] = store[j]; - sum_lambda += _tabAkj[0][j] ; - } - - double trace = matrixDataVar->computeTrace(); - - _tabBk[0] = 1.0/(_pbDimension-_tabDk[0])*(trace-sum_lambda); - - - for (int64_t k=1; k<_nbCluster; k++){ - for (int64_t j=0;j<_tabDk[k];j++){ - _tabAkj[k][j] = store[j]; - } - _tabBk[k] = _tabBk[0]; - } - - if (nbInitializedCluster != _nbCluster){ - /* ca ne devrait pas arriver puisque on a v�rifi� dans XEMOldInput que : - - la partition doit �tre 'compl�te' (y compris que toutes les classes sont repr�sent�es) quand on a l'algo M - - que l'on autorise que M ou MAP pour les mod�les HD - - que MAP => USER (et donc pas 'USER_PARTITION' avec MAP) - */ - throw internalMixmodError; - } - delete matrixDataVar; -} - - - - -/**********************/ -/* initUSER_PARTITION */ -/**********************/ -/*void XEMGaussianHDDAParameter:: initUSER_PARTITION(){ - computeTabMeanInitUSER_PARTITION(); - - - _model->computeNk(); - computeTabWkW(); - if (_tabDk[0]==0){ - computeTabDk(); - } - - switch(_modelType){ - case (Gaussian_HD_pk_AkjBkQkDk) : - case (Gaussian_HD_p_AkjBkQkDk) : - case (Gaussian_HD_pk_AkjBkQkD) : - case (Gaussian_HD_p_AkjBkQkD) : - computeAkjBkQk(); - break; - - case (Gaussian_HD_pk_AkBkQkDk) : - case (Gaussian_HD_p_AkBkQkDk) : - case (Gaussian_HD_pk_AkBkQkD) : - case (Gaussian_HD_p_AkBkQkD) : - computeAkBkQk(); - break; - - case (Gaussian_HD_p_AkjBQkD): - case (Gaussian_HD_pk_AkjBQkD): - computeAkjBQk(); - break; - - case (Gaussian_HD_p_AkBQkD): - case (Gaussian_HD_pk_AkBQkD): - computeAkBQk(); - break; - - case (Gaussian_HD_p_AjBkQkD): - case (Gaussian_HD_pk_AjBkQkD): - computeAjBkQk(); - break; - - case (Gaussian_HD_p_AjBQkD): - case (Gaussian_HD_pk_AjBQkD): - computeAjBQk(); - break; - } - }*/ - - - - - -/************/ -/* initUSER */ -/***********/ -void XEMGaussianHDDAParameter::initUSER(XEMParameter * iParam){ - XEMGaussianHDDAParameter * param = (XEMGaussianHDDAParameter *) iParam; - - double ** iTabMean = param->getTabMean(); - double * iTabProportion = param->getTabProportion(); - XEMMatrix ** iTabWk = param->getTabWk(); - int64_t * iTabDk = param->getTabD(); - double * iTabBk = param->getTabB(); - double ** iTabAkj = param->getTabA(); - XEMGeneralMatrix** iTabQk = param->getTabQ(); - - - - - int64_t k; - recopyTab(iTabBk, _tabBk,_nbCluster); - for (k=0; k<_nbCluster; k++){ - if (_tabDk[k] != iTabDk[k]) { - throw differentSubDimensionsWithMAP; - } - else { - recopyTab(iTabMean[k], _tabMean[k], _pbDimension); - recopyTab(iTabAkj[k],_tabAkj[k],_tabDk[k]); - // recopy _tabWk - (*_tabWk[k]) = iTabWk[k]; - - if (!hasFreeProportion(_modelType->_nameModel)){ - _tabProportion[k] = 1.0 / _nbCluster; - } - else { - _tabProportion[k] = iTabProportion[k]; - } - (*_tabQk[k]) = iTabQk[k]; - } - - } -} - - - - -/***********/ -/* recopy */ -/***********/ -void XEMGaussianHDDAParameter::recopy(XEMParameter * otherParameter){ - - XEMGaussianParameter * iParameter = (XEMGaussianParameter *)otherParameter; - - recopyTab(iParameter->getTabMean(), _tabMean, _nbCluster, _pbDimension); - //_W->recopy(iParameter->getW()); - (* _W) = iParameter->getW(); - - int64_t k; - XEMMatrix ** iTabWk = iParameter->getTabWk(); - for(k=0; k<_nbCluster; k++){ - //_tabWk[k]->recopy(iTabWk[k]); - (* _tabWk[k]) = iTabWk[k]; - } -} - - -//------------------- -//getLogLikelihoodOne -//------------------- -double XEMGaussianHDDAParameter::getLogLikelihoodOne()const{ - cout<<"XEMGaussianHDDAParameter::getLogLikelihoodOne"<getNbSample(); - int64_t i; - XEMGaussianData * data = (XEMGaussianData*)(_model->getData()); - int64_t j, n, l; - double logLikelihoodOne; // Log-likelihood for k=1 - double * Mean = new double[_pbDimension] ; - double ** y = data->_yStore; - double * yi; - // XEMGeneralMatrix * Sigma = new XEMGeneralMatrix(_pbDimension); - XEMSymmetricMatrix * W = new XEMSymmetricMatrix(_pbDimension); - *W = 0.0; - double norme, logDet, detDiagW ; - double * weight = data->_weight; - - // Mean Estimator (empirical estimator) - double totalWeight = data->_weightTotal; - computeMeanOne(Mean,weight,y,nbSample,totalWeight); - weight = data->_weight; - // Compute the Cluster Scattering Matrix W - int64_tp; // parcours - double * xiMoinsMuk = data->getTmpTabOfSizePbDimension(); - double tmp; - for(i=0; iadd(xiMoinsMuk, weight[i]); - } - - //Compute determinant of diag(W) - // logDet = W->detDiag(minDeterminantDiagWValueError); // virtual - detDiagW = powAndCheckIfNotNull(logDet ,1.0/_pbDimension); - - - Sigma->divise(W, totalWeight); // virtual - - - // inverse of Sigma - XEMGeneralMatrix * SigmaMoins1 = new XEMGeneralMatrix(_pbDimension); - SigmaMoins1->inverse(Sigma);// virtual - - double detSigma = Sigma->determinant(minDeterminantSigmaValueError); // virtual - - // Compute the log-likelihood for one cluster (k=1) - logLikelihoodOne = 0.0; - for (i=0; inorme(xiMoinsMuk); // virtual - logLikelihoodOne += norme * weight[i]; - } - - logLikelihoodOne += totalWeight * ( data->getPbDimensionLog2Pi() + log(detSigma)) ; - logLikelihoodOne *= -0.5 ; - - - delete W; - delete Sigma; - delete SigmaMoins1; - - delete[] Mean; - - return logLikelihoodOne;*/ - return 0.0; -} - - - -//Calcule la log-vraismeblance avec la fonction de coût -/*************************/ -/* computeLoglikelihoodK */ -/*************************/ -double* XEMGaussianHDDAParameter::computeLoglikelihoodK(double**K){ - int64_t i,k; - int64_t nbSample = _model->getNbSample(); - int64_t ** tabZikKnown = _model->getTabZikKnown(); - - double* L = new double[_nbCluster]; - for (k=0;k<_nbCluster;k++){ - L[k] = 0.0; - } - - for (i=0;i_nameModel) { - case (Gaussian_HD_pk_AkjBkQkDk): - for (int64_t cls=0;clsedit(cout, "\t\t\t"," ",_tabDk[k]); - - cout<<"\t\tWk : "<edit(cout,"\t\t\t"); - } - - cout<<"\tW : "<edit(cout, "\t\t"); - -} - - - - -/********/ -/* edit */ -/********/ -void XEMGaussianHDDAParameter:: edit(ofstream & oFile, bool text){ - - int64_t k; - - if (text){ - for (k=0; k<_nbCluster; k++){ - oFile<<"\t\t\tComponent "<edit(oFile, "\t\t\t\t\t"," ",_tabDk[k]); - oFile<edit(oFile, ""," ",_tabDk[k]); - oFile<getTabNk(); - int64_tk; - // double* tabShapek_store = new double[_pbDimension]; - for (k=0;k<_nbCluster;k++){ - if (tabNk[k]<_pbDimension){ - int64_tnk = (int) tabNk[k]; - XEMGeneralMatrix * tabQk = new XEMGeneralMatrix(nk); - tabQk->resetToZero(); - _tabQk[k]->resetToZero(); - //W_k = (XEMSymmetricMatrix* )(_tabGammak[k]); - //W_k = _tabGammak[k]; - //W_k -> computeSVD(_tabShape[k], tabQk); - _tabGammak[k] -> computeSVD(_tabShape[k], tabQk); - _tabQk[k]->multiply(_Gammak[k], nk, tabQk); - delete tabQk; - delete _tabGammak[k]; - _tabGammak[k] = NULL; - } - else{ - //W_k = (XEMSymmetricMatrix* )(_tabWk[k]); - //W_k = _tabWk[k]; - //W_k -> computeSVD(_tabShape[k], _tabQk[k]); - _tabWk[k] -> computeSVD(_tabShape[k], _tabQk[k]); - } - double * tabShapek_store = _tabShape[k]->getStore(); - - - - double max_shape = (tabShapek_store[0] - tabShapek_store[1])/tabNk[k]; - int64_ti = 2; - double seuil = 0.1; // � d�cider - while (i<_pbDimension){ - double diff = (tabShapek_store[i-1] - tabShapek_store[i])/tabNk[k]; - - int64_tres = 0; - if( diff < seuil*max_shape){ - int64_tr = i+1; - while (r < _pbDimension){ - double diff2 = (tabShapek_store[r-1] - tabShapek_store[r])/tabNk[k]; - if (diff2getTabNk(); - int64_tnbSample = _model->getNbSample(); - int64_tk; - - for (k=0;k<_nbCluster;k++){ - _tabDk[k] = 1; - } - - double nbFreeParameter;// = getFreeParameter(); - - switch (_modelType){ - case Gaussian_HD_pk_AkjBkQkDk: - case Gaussian_HD_p_AkjBkQkDk: - case Gaussian_HD_pk_AkjBkQkD: - case Gaussian_HD_p_AkjBkQkD: - computeAkjBkQk(); - break; - case Gaussian_HD_pk_AkBkQkDk: - case Gaussian_HD_p_AkBkQkDk: - case Gaussian_HD_pk_AkBkQkD: - case Gaussian_HD_p_AkBkQkD: - computeAkBkQk(); - break; - case Gaussian_HD_pk_AkjBQkD: - case Gaussian_HD_p_AkjBQkD: - computeAkjBQk(); - break; - case Gaussian_HD_pk_AkBQkD: - case Gaussian_HD_p_AkBQkD: - computeAkBQk(); - break; - case Gaussian_HD_pk_AjBQkD: - case Gaussian_HD_p_AjBQkD: - computeAjBQk(); - break; - case Gaussian_HD_pk_AjBkQkD: - case Gaussian_HD_p_AjBkQkD: - computeAjBkQk(); - break; - } // end switch - - double** Cost1 = computeCost(_tabQk); - double* Lk_min = computeLoglikelihoodK(Cost1); - double * BIC_min = new double[_nbCluster]; - double* BIC = new double[_nbCluster]; - int64_t* tabD_min = new int[_nbCluster]; - double* Lk; - double** Cost; - - for (int64_tk=0;k<_nbCluster;k++){ - nbFreeParameter = (_pbDimension+1.0-1.0/_nbCluster) + _tabDk[k]*(_pbDimension-(_tabDk[k]+1.0)/2.0)+_tabDk[k]+2.0; - BIC_min[k] = (-2*Lk_min[k] + nbFreeParameter * log(tabNk[k])) / (tabNk[k]); - // cout<<"d : "<<1<<" BIC_min["<getParameter(); - XEMGaussianParameter* gparameter = (XEMGaussianParameter*)parameter; - double ** tabMean = gparameter->getTabMean(); - double* tabProportion = gparameter->getTabProportion(); - int64_t nbSample = _model->getNbSample(); - XEMGaussianData * data = (XEMGaussianData *)(_model->getData()); - double ** matrix = data->getYStore(); - double * xiMoinsMuk = new double[_pbDimension]; - XEMSymmetricMatrix* Pk = new XEMSymmetricMatrix(_pbDimension); //Id - XEMSymmetricMatrix* A = new XEMSymmetricMatrix(_pbDimension); //Id - XEMSymmetricMatrix * Pi = new XEMSymmetricMatrix(_pbDimension); //id - - for (int64_t classe=0; classe<_nbCluster; classe++){ - double* tabShapek_store = new double[_pbDimension]; - K[classe] = new double[nbSample]; - //----------------calcul le produit Q*t(Q)--------------- - - Pk->compute_as_M_tM(tabQ[classe],_tabDk[classe]); - //---------------calcul du produit A = Qi_L^-1_t(Qi)------------------ - double sum_lambda = 0.0; - for (j=0;j<_tabDk[classe];j++){ - tabShapek_store[j] = 1.0/_tabAkj[classe][j]; - sum_lambda += log(_tabAkj[classe][j]); - } - for (j=_tabDk[classe];j<_pbDimension;j++){ - tabShapek_store[j] = 0.0; - } - A->compute_as_O_S_O(tabQ[classe],tabShapek_store); - double constante = sum_lambda + (_pbDimension-_tabDk[classe])*log(_tabBk[classe])-2*log(tabProportion[classe])+_pbDimension*log(2*XEMPI); - - for (int64_t sample=0; samplecompute_as_M_V(Pk,xiMoinsMuk); - double * storePi = Pi->getStore(); - //----------------norme(muk-Pi(x))_A = t(muk-Pi(x))_A_(muk-Pi(x))----------- - - double normeA = A->norme(xiMoinsMuk); - - //----------------norme(x-Pi(x))------------------------------ - double norme = 0.0; - for (int64_t i=0;i<_pbDimension;i++){ - storePi[i] += tabMean[classe][i]; - norme += (matrix[sample][i] - storePi[i])*(matrix[sample][i] - storePi[i]); - } - - //----------------calcul de K(x)--------- - K[classe][sample] = normeA + 1.0/_tabBk[classe]*norme + constante; - }//fin sample - - delete[] tabShapek_store; - tabShapek_store = NULL; - }//fin classe - - delete Pk; - delete A; - - - delete Pi; - // delete[] storePi; - - - - delete[] xiMoinsMuk; - xiMoinsMuk = NULL;; - - return K; -} - - - - - - -/******************/ -/* computeAkjBkQk */ -/*****************/ - -// Dans mixmod, les matrices Wk ne sont pas divisees par nk alors que dans -//le these de Charles elles le sont. L'expression des parametres dans le code -//est differente de celle de la these car elle rectifie cette difference -void XEMGaussianHDDAParameter::computeAkjBkQk(){ - XEMMatrix* W_k; - double* tabNk = _model->getTabNk(); - - for (int64_t k=0;k<_nbCluster;k++){ - double sum_lambda = 0.0; - if (tabNk[k]<_pbDimension){ - int64_t nk = (int64_t ) tabNk[k]; - XEMGeneralMatrix * tabQk = new XEMGeneralMatrix(nk); //Id - W_k = _tabGammak[k]; - W_k -> computeSVD(_tabShape[k], tabQk); - _tabQk[k]->multiply(_Gammak[k], nk, tabQk); - delete tabQk; - delete _tabGammak[k]; - _tabGammak[k] = NULL; - } - else{ - W_k = _tabWk[k]; - W_k -> computeSVD(_tabShape[k], _tabQk[k]); - } - double * storeShapek = _tabShape[k]->getStore(); - for (int64_t j=0;j<_tabDk[k];j++){ - _tabAkj[k][j] = storeShapek[j]/tabNk[k]; - sum_lambda += _tabAkj[k][j] ; - //cout<<"tabA : "<<_tabAkj[k][j]<computeTrace(); - _tabBk[k] = 1.0/(_pbDimension-_tabDk[k])*(trace/tabNk[k]-sum_lambda); - //cout<<"tabB : "<<_tabBk[k]<getTabNk(); - - _W -> computeSVD(tabShapeW, tabQW); - double trace = _W->computeTrace() / _model->getNbSample(); - double somme = 0.0; - for (int64_t k=0;k<_nbCluster;k++){ - double sum_lambda = 0.0; - if (tabNk[k]<_pbDimension){ - int64_t nk = (int64_t ) tabNk[k]; - XEMGeneralMatrix * tabQk = new XEMGeneralMatrix(nk); //Id - _tabGammak[k]-> computeSVD(_tabShape[k], tabQk); - _tabQk[k]->multiply(_Gammak[k], nk, tabQk); - delete tabQk; - } - else{ - _tabWk[k] -> computeSVD(_tabShape[k], _tabQk[k]); - } - double * storeShapek = _tabShape[k]->getStore(); - for (int64_t j=0;j<_tabDk[k];j++){ - _tabAkj[k][j] = storeShapek[j] / tabNk[k]; - sum_lambda += _tabAkj[k][j]; - //cout<<"tabA : "<<_tabA[k][j]<getNbSample(); - for (int64_t k=0;k<_nbCluster;k++){ - _tabBk[k] = 1.0/(_pbDimension-_tabDk[k])*(trace-somme); - //cout<<"tabB : "<<_tabB[k]<getTabNk(); - _W -> computeSVD(tabShapeW, tabQW); - double * storeShape = tabShapeW->getStore(); - for (int64_t k=0;k<_nbCluster;k++){ - sum_lambda = 0.0; - if (tabNk[k]<_pbDimension){ - int64_t nk = (int64_t ) tabNk[k]; - XEMGeneralMatrix * tabQk = new XEMGeneralMatrix(nk); //Id - W_k = _tabGammak[k]; - W_k -> computeSVD(_tabShape[k], tabQk); - _tabQk[k]->multiply(_Gammak[k], nk, tabQk); - delete tabQk; - } - else{ - W_k = _tabWk[k]; - W_k->computeSVD(_tabShape[k], _tabQk[k]); - } - double * storeShapek = _tabShape[k]->getStore(); - for (int64_t j=0;j<_tabDk[k];j++){ - _tabAkj[k][j] = storeShape[j] / _model->getNbSample(); - sum_lambda += storeShapek[j] / tabNk[k]; - //cout<<"tabAij : "<<_tabA[k][j]<computeTrace() / tabNk[k]; - _tabBk[k] = 1.0/(_pbDimension-_tabDk[k])*(trace-sum_lambda); - //cout<<"tabB : "<<_tabB[k]<getTabNk(); - - double trace = _W->computeTrace() / _model->getNbSample(); - _W -> computeSVD(tabShapeW, tabQW); - double * storeShape = tabShapeW->getStore(); - for (int64_t k=0;k<_nbCluster;k++){ - double sum_lambda = 0.0; - if (tabNk[k]<_pbDimension){ - int64_t nk = (int64_t ) tabNk[k]; - XEMGeneralMatrix * tabQk = new XEMGeneralMatrix(nk); //Id - _tabGammak[k] -> computeSVD(_tabShape[k], tabQk); - _tabQk[k]->multiply(_Gammak[k], nk, tabQk); - delete tabQk; - } - else{ - _tabWk[k] -> computeSVD(_tabShape[k], _tabQk[k]); - } - double * storeShapek = _tabShape[k]->getStore(); - for (int64_t j=0;j<_tabDk[k];j++){ - _tabAkj[k][j] = storeShape[j] / _model->getNbSample(); - sum_lambda += storeShapek[j]; - //cout<<"tabA : "<<_tabA[k][j]<getNbSample(); - for (int64_t k=0;k<_nbCluster;k++){ - _tabBk[k] = 1.0/(_pbDimension-_tabDk[k])*(trace-somme); - // cout<<"tabB : "<<_tabB[k]<getTabNk(); - XEMMatrix * W_k; - for (int64_t k=0;k<_nbCluster;k++){ - sum_lambda = 0.0; - if (tabNk[k]<_pbDimension){ - int64_t nk = (int64_t ) tabNk[k]; - XEMGeneralMatrix * tabQk = new XEMGeneralMatrix(nk); //Id - W_k = _tabGammak[k]; - W_k -> computeSVD(_tabShape[k], tabQk); - _tabQk[k]->multiply(_Gammak[k], nk, tabQk); - delete tabQk; - } - else{ - W_k = _tabWk[k]; - W_k -> computeSVD(_tabShape[k], _tabQk[k]); - } - double * storeShapek = _tabShape[k]->getStore(); - for (int64_t j=0;j<_tabDk[k];j++){ - sum_lambda += storeShapek[j] / tabNk[k]; - } - for (int64_t j=0;j<_tabDk[k];j++){ - _tabAkj[k][j] = 1.0 / _tabDk[k] * sum_lambda ; - //cout<<"tabA : "<<_tabA[k][j]<computeTrace()/ tabNk[k]; - _tabBk[k] = 1.0 / (_pbDimension - _tabDk[k]) * (trace-sum_lambda); - //cout<<"tabB : "<<_tabB[k]<getTabNk(); - - double trace = _W->computeTrace() / _model->getNbSample(); - _W -> computeSVD(tabShapeW, tabQW); - for (int64_t k=0;k<_nbCluster;k++){ - sum_lambda = 0.0; - if (tabNk[k]<_pbDimension){ - int64_t nk = (int64_t ) tabNk[k]; - XEMGeneralMatrix * tabQk = new XEMGeneralMatrix(nk); //Id - _tabGammak[k] -> computeSVD(_tabShape[k], tabQk); - _tabQk[k]->multiply(_Gammak[k], nk, tabQk); - delete tabQk; - } - else{ - _tabWk[k] -> computeSVD(_tabShape[k], _tabQk[k]); - } - double * storeShapek = _tabShape[k]->getStore(); - for (int64_t j=0;j<_tabDk[k];j++){ - sum_lambda +=storeShapek[j] / tabNk[k]; - } - for (int64_t j=0;j<_tabDk[k];j++){ - _tabAkj[k][j] = 1.0 / _tabDk[k] * sum_lambda ; - //cout<<"tabA : "<<_tabA[k][j]<getNbSample(); - for (int64_t k=0;k<_nbCluster;k++){ - _tabBk[k] = 1.0/(_pbDimension-_tabDk[k])*(trace-somme); - //cout<<"tabB : "<<_tabB[k]<. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMGAUSSIANHDDAPARAMETER_H -#define XEMGAUSSIANHDDAPARAMETER_H - - - -#include "XEMGaussianParameter.h" -#include "XEMMatrix.h" -#include "XEMGeneralMatrix.h" -#include "XEMOldInput.h" - -class XEMGaussianHDDAParameter : public XEMGaussianParameter{ - - public: - - /// Default constructor - XEMGaussianHDDAParameter(); - - /// Constructor - // called by XEMModel - XEMGaussianHDDAParameter(XEMModel * iModel, XEMModelType * iModelType); - - /// Constructor - // called by XEMStrategyType - XEMGaussianHDDAParameter(int64_t iNbCluster, int64_t iPbDimension, XEMModelType * iModelType, string & iFileName); - - /// Constructor - XEMGaussianHDDAParameter(const XEMGaussianHDDAParameter * iParameter); - - - /// Destructor - virtual ~XEMGaussianHDDAParameter(); - - /// reset to default values - virtual void reset(); - - - /** @brief Selector - @return A copy of the model - */ - XEMParameter * clone() const; - - - /** @brief Selector - @return Table of shape matrix for each cluster - */ - XEMDiagMatrix ** getTabShape() const; - - /** @brief Selector - @return Table of orientation matrix for each cluster - */ - XEMGeneralMatrix ** getTabQ() const; - - /** @brief Selector - @return Control the shape of the density in the subspace Ei - */ - double** getTabA() const; - - /** @brief Selector - @return Control the shape of the density in the subspace orthogonal to Ei - */ - double* getTabB() const; - - /** @brief Selector - @return Dimension of each subspace - */ - int64_t * getTabD() const; - - XEMSymmetricMatrix ** getTabGammak() const; - - double ** getGamma() const; - - void MStep(); - - // init - //----- - - /// initialize attributes before an InitRandom - virtual void initForInitRANDOM() ; - - - - - - /// initialize attributes for init USER_PARTITION - /// outputs : - /// - nbInitializedCluster - /// - tabNotInitializedCluster (array of size _nbCluster) - void initForInitUSER_PARTITION(int64_t & nbInitializedCluster, bool * tabNotInitializedCluster, XEMPartition * initPartition); - - - - /// User initialisation of the parameters of the model - virtual void initUSER(XEMParameter* iParam); - - - double getLogLikelihoodOne() const; - - void edit(); - - void edit(ofstream & oFile, bool text=false); - - void recopy(XEMParameter * otherParameter); - - double getPdf(int64_t iSample, int64_t kCluster) const; - - void getAllPdf(double ** tabFik,double * tabProportion) const; - - double getPdf(XEMSample * x, int64_t kCluster)const; - - double* computeLoglikelihoodK(double** K); - - - void input(ifstream & fi); - - protected : - /// Table of shape matrix of each cluster - XEMDiagMatrix** _tabShape; - - /// Table of orientation matrix of each cluster - XEMGeneralMatrix ** _tabQk; - - int64_t __storeDim; - ///Table of parameters Akj of each cluster - double ** _tabAkj; - ///Table of parameters Bk of each cluster - double * _tabBk; - ///Table of sub dimension of each cluster - int64_t * _tabDk; - - /// _tabGammak = _Gammak * _Gammak' replaces matrix Wk when tabNk smaller than _pbDimension - XEMSymmetricMatrix ** _tabGammak; // matrice nk * p - /// Array of individuals * weight - mean[k] in class k - double ** _Gammak; - - int64_t getFreeParameter()const; - - void computeTabWkW(); - - ///compute function of cost for each tabQk_k - double ** computeCost(XEMGeneralMatrix ** tabQ)const; - - ///compute parameters for the model AkjBkQk - void computeAkjBkQk(); - ///compute parameters for the model AkjBQk - void computeAkjBQk(); - ///compute parameters for the model AjBkQk - void computeAjBkQk(); - ///compute parameters for the model AjBQk - void computeAjBQk(); - - ///compute parameters for the model AkBkQk - void computeAkBkQk(); - ///compute parameters for the model AkBQk - void computeAkBQk(); - - - /// compute the intrinsic dimension when non given - void computeTabDk(); -}; - -inline XEMDiagMatrix** XEMGaussianHDDAParameter::getTabShape()const{ - return _tabShape; -} - -inline XEMGeneralMatrix ** XEMGaussianHDDAParameter::getTabQ() const{ - return _tabQk; -} - -inline double** XEMGaussianHDDAParameter::getTabA() const{ - return _tabAkj; -} - -inline double* XEMGaussianHDDAParameter::getTabB() const{ - return _tabBk; -} - -inline int64_t * XEMGaussianHDDAParameter::getTabD() const{ - return _tabDk; -} - - - -inline XEMSymmetricMatrix** XEMGaussianHDDAParameter::getTabGammak() const { - return _tabGammak; -} - -inline double ** XEMGaussianHDDAParameter::getGamma() const{ - return _Gammak; -} - -#endif - diff --git a/lib/src/mixmod/MIXMOD/XEMGaussianParameter.cpp b/lib/src/mixmod/MIXMOD/XEMGaussianParameter.cpp deleted file mode 100644 index a5ea49a..0000000 --- a/lib/src/mixmod/MIXMOD/XEMGaussianParameter.cpp +++ /dev/null @@ -1,624 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMGaussianParameter.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMGaussianParameter.h" -#include "XEMGaussianGeneralParameter.h" -#include "XEMUtil.h" -#include "XEMModel.h" -#include "XEMGaussianData.h" - -#include "XEMMatrix.h" -#include "XEMDiagMatrix.h" -#include "XEMSphericalMatrix.h" -#include "XEMGeneralMatrix.h" -#include "XEMSymmetricMatrix.h" - -//------------ -// Constructor -//------------ -// Default constructor -XEMGaussianParameter::XEMGaussianParameter(){ - throw wrongConstructorType; -} - - - -//------------ -// Constructor -//------------ -XEMGaussianParameter::XEMGaussianParameter(XEMModel * iModel, XEMModelType * iModelType):XEMParameter(iModel, iModelType){ - int64_t k, j; - _tabMean = new double*[_nbCluster]; - - _tabWk = new XEMMatrix* [_nbCluster]; - // _tabSigma = new XEMMatrix* [_nbCluster]; - - for (k=0; k<_nbCluster; k++){ - _tabMean[k] = new double[_pbDimension]; - for (j=0; j<_pbDimension; j++){ - _tabMean[k][j] = 0; - } - } - - initFreeProportion(iModelType); -} - - - -//------------ -// Constructor -// called by XEMGaussianEDDAParameter if initialization is USER -//------------ -XEMGaussianParameter::XEMGaussianParameter(int64_t iNbCluster, int64_t iPbDimension, XEMModelType * iModelType):XEMParameter(iNbCluster,iPbDimension, iModelType){ - int64_t k; - _tabMean = new double*[_nbCluster]; - - _tabWk = new XEMMatrix* [_nbCluster]; - // _tabSigma = new XEMMatrix* [_nbCluster]; - - - for (k=0; k<_nbCluster; k++){ - _tabMean[k] = new double[_pbDimension]; - for (int64_t j=0; j<_pbDimension; j++){ - _tabMean[k][j] = 0; - } - } - - initFreeProportion(iModelType); -} - - - - - -//------------ -// Constructor (copy) -//------------ -XEMGaussianParameter::XEMGaussianParameter(const XEMGaussianParameter * iParameter):XEMParameter(iParameter){ - int64_t k; - _tabMean = new double*[_nbCluster]; - double ** iTabMean = iParameter->getTabMean(); - for (k=0; k<_nbCluster; k++){ - _tabMean[k] = copyTab(iTabMean[k],_pbDimension); - } - _tabWk = new XEMMatrix* [_nbCluster]; - //_tabSigma = new XEMMatrix* [_nbCluster]; - -} - - - -//----------- -// Destructor -//----------- -XEMGaussianParameter::~XEMGaussianParameter(){ - int64_t k; - - if (_tabMean){ - for (k=0; k<_nbCluster; k++){ - delete[] _tabMean[k]; - _tabMean[k] = NULL; - } - delete[] _tabMean; - _tabMean = NULL; - } - - if(_W){ - delete _W; - _W = NULL; - } - if(_tabWk){ - for(k=0; k<_nbCluster; k++){ - delete _tabWk[k]; - } - delete[] _tabWk; - _tabWk = NULL; - } - /* if(_tabSigma){ - for(k=0; k<_nbCluster; k++){ - delete _tabSigma[k]; - } - delete[] _tabSigma; - _tabSigma = NULL; - }*/ - -} - -//------------------------ -// reset to default values -//------------------------ -void XEMGaussianParameter::reset(){ - int64_t k,j; - - for (k=0; k<_nbCluster; k++){ - *(_tabWk[k]) = 1.0; - for (j=0; j<_pbDimension; j++){ - _tabMean[k][j] = 0; - } - } - - *(_W) = 1.0; - - XEMParameter::reset(); -} - - - - -//----------------------------- -// updateForOneRunOfInitRANDOM -//----------------------------- -void XEMGaussianParameter::updateForInitRANDOMorUSER_PARTITION(XEMSample ** tabSampleForInit, bool * tabClusterToInitialize){ - double * sampleValue = NULL; - XEMSample * curSample = NULL; - for (int64_t k=0; k<_nbCluster; k++){ - if (tabClusterToInitialize[k]){ - curSample = tabSampleForInit[k]; - sampleValue = ((XEMGaussianSample *)curSample)->getTabValue(); - recopyTab(sampleValue , _tabMean[k], _pbDimension); - } - } -} - - - - -//----------------------------- -//computeGlobalDiagDataVariance -//----------------------------- -void XEMGaussianParameter::computeGlobalDiagDataVariance(XEMDiagMatrix * matrixDiagDataVar){ - int64_t nbSample = _model->getNbSample(); - int64_t p; - int64_t i; - XEMGaussianData * data = (XEMGaussianData*)(_model->getData()); - double totalWeight = data->_weightTotal; - double ** p_yStore = data->getYStore(); - double * p_yStore_i; - double * p_weight = data->_weight; - double * Mean = new double[_pbDimension]; - double wi; - double * xiMoinsMean = data->getTmpTabOfSizePbDimension() ; - - computeMeanOne(Mean,p_weight,p_yStore,nbSample,totalWeight); - - // compute W diagonal - p_yStore = data->getYStore(); - p_weight = data->_weight; - *matrixDiagDataVar = 0.0; - for(i=0 ; iadd(xiMoinsMean, wi); // virtual - p_yStore++; - p_weight++; - } - *matrixDiagDataVar /= totalWeight; // virtual operator - - delete[] Mean; - -} - - - - - - -//-------------- -// Compute TabWk -//-------------- -void XEMGaussianParameter::computeTabWkW(){ - // Compute the cluster scattering matrices Wk and W - - // NB: _tabMean and _zik must be updated - // this method must be called to update Wk and W if _tabMean or _zik have changed - // makes calls to virtual methods - - //recuperation des différents paramètres - - double ** tabCik = _model->getTabCik(); - double ** p_cik; - int64_t nbSample = _model->getNbSample(); - XEMGaussianData * data = (XEMGaussianData*)(_model->getData()); - double ** p_tabMean = _tabMean; - double * weight = data->_weight; - int64_t i; - int64_t k; - // storage - double ** matrix = data->getYStore(); // to store x_i i=1,...,n - double * xiMoinsMuk = data->getTmpTabOfSizePbDimension(); // to store x_i - mu_k at each step - double* muk; - int64_t p; - double cik; - *(_W) = 0.0; - - for(k=0 ; k<_nbCluster ; k++){ - muk = *p_tabMean; - (*_tabWk[k]) = 0.0; // virtual method - p_cik = tabCik; - matrix = data->getYStore(); - for(i=0 ; iadd(xiMoinsMuk, cik); // virtual method - - matrix++; - p_cik++; - } - p_tabMean++; - (*_W) += _tabWk[k]; - } //end for k -} - - - -void XEMGaussianParameter::initFreeProportion(XEMModelType * iModelType){ - - if (hasFreeProportion(iModelType->_nameModel)) { - _freeProportion = true; - } - else{ - _freeProportion = false; - } -} - - -//---------------------------------------------- -// compute class assigment of idxSample element (idxSample : 0->_nbSample-1) -// Note : distance euclidienne -//---------------------------------------------- -int64_t XEMGaussianParameter::computeClassAssigment(int64_t idxSample){ - XEMGaussianData * data = (XEMGaussianData*)(_model->getData()); - - int64_t p, k, k0 = 0; - double bestDist = 0.0; - double * x_idxSample = (data->getYStore())[idxSample]; - - double dist,tmp ; - - double ** p_tabMean = _tabMean; // pointeur pour parcourir _tabMean - double * p_tabMean_k; - - for (k=0; k<_nbCluster; k++){ - p_tabMean_k = *(p_tabMean); - dist = 0.0; - - // calcul - for (p=0 ; p<_pbDimension; p++){ - tmp = x_idxSample[p] - p_tabMean_k[p] ; - dist += tmp * tmp; - } - - // recherche de la plus grande distance et de l'index k0 correspondant - if(dist>bestDist){ - bestDist = dist; - k0 = k; - } - - p_tabMean++; // next mean vector - } - - return k0; - -} - - - -/****************************************************/ -/* computeTabMean in USER_PARTITION initialization*/ -/***************************************************/ -void XEMGaussianParameter::computeTabMeanInitUSER_PARTITION(int64_t & nbInitializedCluster, bool * tabNotInitializedCluster, XEMPartition * initPartition){ - int64_t k; - int64_t i; - int64_t ** initPartitionValue = initPartition->_tabValue; - int64_t nbSample = _model->getNbSample(); - XEMGaussianData * data = (XEMGaussianData*)(_model->getData()); - double ** matrix = data->getYStore(); - double cik = 0.0; - double * tabWeight = data->_weight; - double * tabWeightK = new double[_nbCluster]; - int64_t p; // parcours 0,..., _pbDimension - - for(k=0; k<_nbCluster; k++){ - tabWeightK[k] = 0; - for(p=0;p<_pbDimension;p++){ - _tabMean[k][p] = 0.0; - } - for(i=0; igetTabCik(); - double * tabNk = _model->getTabNk(); - int64_t nbSample = _model->getNbSample(); - XEMGaussianData * data = (XEMGaussianData*)(_model->getData()); - double ** matrix = data->getYStore(); - double * muk; - double cik = 0.0; - // pointeurs - double ** p_matrix; - double ** p_cik; - double ** p_tabMean = _tabMean; - double * p_weight; - int64_t p; // parcours 0,..., _pbDimension - - for(k=0; k<_nbCluster; k++){ - // refresh - muk = *p_tabMean; - for(p=0;p<_pbDimension;p++) - muk[p] = 0.0; - - // initialisations - p_matrix = matrix; - p_cik = tabCik; - p_weight = data->_weight; - - for(i=0; i_tabCik, _model->_tabNk if USER_PARTITION is done before (Disciminant analysis) - In all cases, only _tabCik and _tabNk are needed - - updated in this method : - - _tabProportion - - _tabMean - - _tabWk - - _W - --------------------------------------------------------------------------------------------*/ -void XEMGaussianParameter::MStep(){ - - /* Proportion estimator (if proportions free) */ - computeTabProportion(); - - /* Centers mean estimator */ - computeTabMean(); - - /* Compute Wk W */ - computeTabWkW(); -} - - - - -double XEMGaussianParameter::determinantDiag(double * mat_store, XEMErrorType errorType){ - int64_t p; - double det = mat_store[0]; - for(p=1 ; p<_pbDimension ; p++){ - det *= mat_store[p]; - } - if(detgetParameter()) ; - XEMMatrix ** oTabWk = oParam->getTabWk(); - double ** oTabMean = oParam->getTabMean(); - double * oTabNk = originalModel->getTabNk(); - - int64_t k ; - XEMGaussianData * oData = (XEMGaussianData*)(originalModel->getData()); - double ** matrix = oData->getYStore(); - double * x_i ; - - double * tabNk = _model->getTabNk(); - - double ** tabCik = _model->getTabCik(); - - //--------------------------------- updates the proportions - computeTabProportion(); - - //--------------------------------- updates the means - // mu*_k = (1/n*_k).(n_k.mu_k - sum_{test}(cik wi xi)) - - int64_t p; - int64_t i; - double cik; - - for(k=0; k<_nbCluster; k++){ - for(p=0; p<_pbDimension; p++){ - _tabMean[k][p] = oTabMean[k][p] * oTabNk[k] ; - } - for (int64_t ii=0; iigetTmpTabOfSizePbDimension(); - double * mukMoinsoMuk = new double[_pbDimension]; - - double * xi; - *(_W) = 0.0; - for(k=0; k<_nbCluster; k++){ - // _tabWk[k]->recopy(oTabWk[k]); - (* _tabWk[k]) = oTabWk[k]; - for (int64_t ii=0; iiadd(tmp, cik); - } - - for(p=0; p<_pbDimension; p++){ - mukMoinsoMuk[p] = _tabMean[k][p]-oTabMean[k][p]; - } - _tabWk[k]->add(mukMoinsoMuk, oTabNk[k]); // change : 17/03/06 - (*_W) += _tabWk[k]; - } - delete [] mukMoinsoMuk; - -} diff --git a/lib/src/mixmod/MIXMOD/XEMGaussianParameter.h b/lib/src/mixmod/MIXMOD/XEMGaussianParameter.h deleted file mode 100644 index 8ef4011..0000000 --- a/lib/src/mixmod/MIXMOD/XEMGaussianParameter.h +++ /dev/null @@ -1,235 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMGaussianParameter.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMGaussianParameter_H -#define XEMGaussianParameter_H - -#include "XEMUtil.h" -#include "XEMParameter.h" -#include "XEMDiagMatrix.h" - -class XEMMatrix; -/** - @brief Base class for XEMGaussianParameter(s) - @authors A Echenim & F. Langrognet & Y. Vernaz -*/ -class XEMGaussianParameter : public XEMParameter{ - - public: - - //---------------------------- - // constructors / desctructors - // --------------------------- - - /// Default constructor - XEMGaussianParameter(); - - /// Constructor - // called by XEMModel - XEMGaussianParameter(XEMModel * iModel, XEMModelType * iModelType); - - /// Constructor - // called by XEMGaussianEDDAParameter if initialization is USER - XEMGaussianParameter(int64_t iNbCluster, int64_t iPbDimension, XEMModelType * iModelType); - - - /// Constructor - XEMGaussianParameter(const XEMGaussianParameter * iParameter); - - /// Destructor - virtual ~XEMGaussianParameter(); - - virtual XEMParameter* clone()const =0 ; - - /// reset to default values - virtual void reset(); - //---------- - // selectors - //---------- - - /// get TabMean - double ** getTabMean() const ; - - //---------------- - // compute methods - //---------------- - - ///computeDiagGlobalDataVariance - void computeGlobalDiagDataVariance(XEMDiagMatrix * matrixDiagDataVar); - - /// Compute table of cluster scattering matrices Wk and W - virtual void computeTabWkW(); - - - /// compute label of idxSample - int64_t computeClassAssigment(int64_t idxSample); - - /// Compute table of means of the samples for each cluster - void computeTabMean(); - - /// Compute table of means of the samples for each cluster in initUSER_PARTITION case - /// outputs : - /// - nbInitializedCluster - /// - tabNotInitializedCluster (array of size _nbCluster) - void computeTabMeanInitUSER_PARTITION(int64_t & nbInitializedCluster, bool * tabNotInitializedCluster, XEMPartition * initPartition); - - /// Compute table of sigmas of the samples for each cluster - // NB : compute also lambda, shape, orientation, wk, w - //virtual void computeTabSigma(); - - - //Compute normal probability density function - // for iSample the sample and kCluster th cluster - virtual double getPdf(int64_t iSample, int64_t kCluster) const = 0; - - - // compute normal probability density function - // for all i=1,..,n and k=1,..,K - virtual void getAllPdf(double ** tabFik,double * tabProportion) const = 0; - - // compute normal probability density function - // for the line x within the kCluster cluster - virtual double getPdf(XEMSample * x, int64_t kCluster) const = 0; - - - //----------- - // Algorithms - //----------- - - /// Maximum a posteriori step method - void MAPStep(); - - /// Maximization step method - virtual void MStep(); - - - // SELECTORS for square matrices - - /// get TabSigma - //XEMMatrix ** getTabSigma(); - - /** @brief Selector - @return Table of cluster scattering matrices Wk - */ - XEMMatrix ** getTabWk() const; - - /** @brief Selector - @return Scattering matrix W - */ - XEMMatrix * getW() const; - - - // edit (for debug) - virtual void edit() = 0; - - /// Edit - virtual void edit(ofstream & oFile, bool text=false) = 0; - - virtual void input(ifstream & fi) = 0; - - virtual double getLogLikelihoodOne() const = 0; - - /// recopie sans faire construction / destruction - // utilisé par SMALL_EM, CEM_INIT - virtual void recopy(XEMParameter * otherParameter) = 0; - - - virtual void updateForCV(XEMModel * originalModel, XEMCVBlock & CVBlock) ; - - - - //init - //---- - void updateForInitRANDOMorUSER_PARTITION(XEMSample ** tabSampleForInit, bool * tabClusterToInitialize); - - - /// init user - virtual void initUSER(XEMParameter * iParam) = 0; - - protected : - - // Square matrices - // Table of covariance Matrix of each cluster - //XEMMatrix ** _tabSigma; - - // Table of inverse of covariance matrix of each cluster - //XEMMatrix ** _tabInvSigma; - - /// Table of cluster scattering matrix Wk - XEMMatrix ** _tabWk; - - /// Scattering matrix W - XEMMatrix * _W; - - // 1/det(Sigma) - //double * _tabInvSqrtDetSigma; - - - /// Table of means vector of each cluster - double ** _tabMean; - - - // called by constructor - // update _freeProportion - void initFreeProportion(XEMModelType * iModelType); - - - /// compute Mean when only one cluster - /// called by initRANDOM, getLogLikelihoodOne - void computeMeanOne(double * Mean, double * weight, double** y_Store, int64_t nbSample, double totalWeight)const; - - - void putIdentityInDiagonalMatrix(double * mat_store); - - void putIdentityInMatrix(double * mat_store); - - void initDiagonalMatrixToZero(double * A_store); - - double determinantDiag(double * mat_store, XEMErrorType errorType); - -}; - - -//--------------- -// inline methods -//--------------- - -inline double ** XEMGaussianParameter::getTabMean() const { - return this->_tabMean; -} - -/*inline XEMMatrix ** XEMGaussianParameter::getTabSigma(){ - return _tabSigma; - }*/ - - -inline XEMMatrix ** XEMGaussianParameter::getTabWk() const{ - return _tabWk; -} - -inline XEMMatrix * XEMGaussianParameter::getW() const{ - return _W; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMGaussianSample.cpp b/lib/src/mixmod/MIXMOD/XEMGaussianSample.cpp deleted file mode 100644 index 6719b39..0000000 --- a/lib/src/mixmod/MIXMOD/XEMGaussianSample.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMGaussianSample.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMGaussianSample.h" - - - -//------------ -// Constructor -//------------ -XEMGaussianSample::XEMGaussianSample():XEMSample(){ - _value = NULL; -} - - - -//------------ -// Constructor -//------------ -XEMGaussianSample::XEMGaussianSample(int64_t pbDimension):XEMSample(pbDimension){ - _value = new double[pbDimension]; - initToZero(_value,pbDimension); -} - - - -//------------ -// Constructor -//------------ -XEMGaussianSample::XEMGaussianSample(XEMGaussianSample * iSample):XEMSample(iSample){ - _value = copyTab(iSample->_value,_pbDimension); -} - - - -//------------ -// Constructor -//------------ -XEMGaussianSample::XEMGaussianSample(int64_t pbDimension, double * tabValue):XEMSample(pbDimension){ - _value = copyTab( tabValue, pbDimension); -} - - - -//----------- -// Destructor -//----------- -XEMGaussianSample::~XEMGaussianSample(){ - if(_value) - delete[] _value; - _value = NULL; -} - - - -//-------------- -// set tab value -//-------------- -void XEMGaussianSample::setDataTabValue(double * tabValue){ - recopyTab(tabValue,_value,_pbDimension); -} - - - -//---------- -// set value -//---------- -void XEMGaussianSample::setDataValue(int64_t idxDim, double value){ - _value[idxDim] = value; -} - - diff --git a/lib/src/mixmod/MIXMOD/XEMGaussianSample.h b/lib/src/mixmod/MIXMOD/XEMGaussianSample.h deleted file mode 100644 index d7394c2..0000000 --- a/lib/src/mixmod/MIXMOD/XEMGaussianSample.h +++ /dev/null @@ -1,92 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMGaussianSample.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMGAUSSIANSample_H -#define XEMGAUSSIANSample_H - -#include "XEMSample.h" - - -/** - @brief Base class for Sample - @author F Langrognet & A Echenim -*/ - -class XEMGaussianSample : public XEMSample{ - - public: - - /// Constructor - XEMGaussianSample(); - - /// Constructor - XEMGaussianSample(int64_t pbDimension); - - /// Constructor - XEMGaussianSample(XEMGaussianSample * iSample); - - /// Constructor - XEMGaussianSample(int64_t pbDimension, double * tabValue); - - /// Destructor - virtual ~XEMGaussianSample(); - - - /// Set value vector of sample - void setDataTabValue(double * tabValue); - - /// Set one value of sample - void setDataValue(int64_t idxDim, double value); - - /// get value vector of sample - double * getTabValue() const; - - /// get one value of sample - double getDataValue(int64_t idxDim) const; - - - protected : - - /// Vector of sample value - double * _value; - - -}; - - - -//--------------- -// inline methods -//--------------- - -inline double * XEMGaussianSample::getTabValue() const{ - return _value; -} - - -inline double XEMGaussianSample::getDataValue(int64_t idxDim) const{ - return _value[idxDim]; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMGaussianSphericalParameter.cpp b/lib/src/mixmod/MIXMOD/XEMGaussianSphericalParameter.cpp deleted file mode 100644 index b71b206..0000000 --- a/lib/src/mixmod/MIXMOD/XEMGaussianSphericalParameter.cpp +++ /dev/null @@ -1,297 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMGaussianSphericalParameter.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMGaussianSphericalParameter.h" -#include "XEMGaussianGeneralParameter.h" -#include "XEMGaussianEDDAParameter.h" -#include "XEMGaussianData.h" -#include "XEMModel.h" - -#include "XEMSphericalMatrix.h" - -/****************/ -/* Constructors */ -/****************/ - - - -//---------------------------------------------------- -//---------------------------------------------------- -XEMGaussianSphericalParameter::XEMGaussianSphericalParameter(){ - throw wrongConstructorType; -} - - - -//------------------------------------------------------------------------------------- -// constructor called by XEMModel -//------------------------------------------------------------------------------------- -XEMGaussianSphericalParameter::XEMGaussianSphericalParameter(XEMModel * iModel, XEMModelType * iModelType): XEMGaussianEDDAParameter(iModel, iModelType){ - int64_t k; - _W = new XEMSphericalMatrix(_pbDimension); - for (k=0; k<_nbCluster; k++){ - _tabSigma[k] = new XEMSphericalMatrix(_pbDimension); //Id - _tabInvSigma[k] = new XEMSphericalMatrix(_pbDimension); //Id - _tabWk[k] = new XEMSphericalMatrix(_pbDimension); //Id - } - -} - - - - -//--------------------------------------------------------------------- -// copy constructor -//--------------------------------------------------------------------- -XEMGaussianSphericalParameter::XEMGaussianSphericalParameter(const XEMGaussianSphericalParameter * iParameter):XEMGaussianEDDAParameter(iParameter){ - int64_t k; - - _W = new XEMSphericalMatrix((XEMSphericalMatrix *)(iParameter->getW())); // copy constructor - - - XEMMatrix ** iTabWk = iParameter->getTabWk(); - XEMMatrix ** iTabSigma = iParameter->getTabSigma(); - XEMMatrix ** iTabInvSigma = iParameter->getTabInvSigma(); - - for(k=0; k<_nbCluster; k++){ - _tabWk[k] = new XEMSphericalMatrix(_pbDimension); - (* _tabWk[k]) = iTabWk[k]; - _tabSigma[k] = new XEMSphericalMatrix(_pbDimension); - (* _tabSigma[k]) = iTabSigma[k]; - _tabInvSigma[k] = new XEMSphericalMatrix(_pbDimension); - (*_tabInvSigma[k]) = iTabInvSigma[k]; - } - -} - - - -/**************/ -/* Destructor */ -/**************/ -XEMGaussianSphericalParameter::~XEMGaussianSphericalParameter(){ - - if (_tabSigma){ - for (int64_t k=0;k<_nbCluster;k++){ - delete _tabSigma[k]; - //_tabSigma[k] = NULL; - } - } - - if (_tabInvSigma){ - for (int64_t k=0;k<_nbCluster;k++){ - delete _tabInvSigma[k]; - // _tabInvSigma[k] = NULL; - } - } -} - - - -/*********/ -/* clone */ -/*********/ -XEMParameter * XEMGaussianSphericalParameter::clone() const{ - XEMGaussianSphericalParameter * newParam = new XEMGaussianSphericalParameter(this); - return(newParam); -} - - -/************/ -/* initUSER */ -/************/ -void XEMGaussianSphericalParameter::initUSER(XEMParameter * iParam){ - XEMGaussianEDDAParameter::initUSER(iParam); - updateTabInvSigmaAndDet(); -} - - - -/*******************/ -/* computeTabSigma */ -/*******************/ -void XEMGaussianSphericalParameter::computeTabSigma(){ - - // Initialization - XEMGaussianData * data = (XEMGaussianData*)(_model->getData()); - double * tabNk = _model->getTabNk(); - int64_t k; - double sigmaValue; - - double totalWeight = data->_weightTotal; - - - // Variance estimator for each of spherical model - switch (_modelType->_nameModel) { - - case (Gaussian_p_L_I) : - case (Gaussian_pk_L_I) : - //--------------------- - _W->putSphericalValueInStore(sigmaValue);// / totalWeight; - sigmaValue /= totalWeight; - if (sigmaValue < minOverflow){ - throw errorSigmaConditionNumber; - } - for(k=0; k<_nbCluster; k++){ - *(_tabSigma[k]) = sigmaValue; - } - - break; - - - case (Gaussian_p_Lk_I) : - case (Gaussian_pk_Lk_I) : - //---------------------- - for(k=0; k<_nbCluster; k++){ - _tabWk[k]->putSphericalValueInStore(sigmaValue); - sigmaValue /= tabNk[k]; - if (sigmaValue < minOverflow) - throw errorSigmaConditionNumber; - *(_tabSigma[k]) = sigmaValue; - } - - break; - - default : - throw internalMixmodError; - break; - } - - updateTabInvSigmaAndDet() ; - -} - - - - -//------------------- -//getLogLikelihoodOne -//------------------- -double XEMGaussianSphericalParameter::getLogLikelihoodOne() const{ - - /* Compute log-likelihood for one cluster - useful for NEC criterion */ - - /* Initialization */ - int64_t nbSample = _model->getNbSample(); - int64_t i; - XEMGaussianData * data = (XEMGaussianData*)(_model->getData()); - double logLikelihoodOne; // Log-likelihood for k=1 - double * Mean = new double[_pbDimension] ; - double ** y = data->_yStore; - double * yi; - XEMSphericalMatrix * Sigma = new XEMSphericalMatrix(_pbDimension); - XEMSphericalMatrix * W = new XEMSphericalMatrix(_pbDimension); - double norme, logDet, detDiagW ; - double * weight = data->_weight; - - // Mean Estimator (empirical estimator) - double totalWeight = data->_weightTotal; - computeMeanOne(Mean,weight,y,nbSample,totalWeight); - weight = data->_weight; - - /* Compute the Cluster Scattering Matrix W */ - int64_t p; // parcours - double * xiMoinsMuk = data->getTmpTabOfSizePbDimension(); - for(i=0; iadd(xiMoinsMuk, weight[i]); - } - - /* Compute determinant of diag(W) */ - logDet = W->detDiag(minDeterminantDiagWValueError); // virtual - detDiagW = powAndCheckIfNotNull(logDet ,1.0/_pbDimension); - Sigma->equalToMatrixDividedByDouble(W, totalWeight); // virtual - - // inverse of Sigma - //XEMSphericalMatrix * SigmaMoins1 = new XEMSphericalMatrix( _pbDimension); - XEMMatrix * SigmaMoins1 = NULL; - //SigmaMoins1->inverse(Sigma);// virtual - //cout<<"S"<edit(cout,""); - - Sigma->inverse(SigmaMoins1); - //cout<<"S-1"<edit(cout,""); - double detSigma = Sigma->determinant(minDeterminantSigmaValueError); // virtual - - // Compute the log-likelihood for one cluster (k=1) - logLikelihoodOne = 0.0; - for (i=0; inorme(xiMoinsMuk); // virtual - logLikelihoodOne += norme * weight[i]; - } - - logLikelihoodOne += totalWeight * ( data->getPbDimensionLog2Pi() + log(detSigma)) ; - logLikelihoodOne *= -0.5 ; - - delete[] Mean; - - delete W; - delete Sigma; - delete SigmaMoins1; - - return logLikelihoodOne; -} - - - -//---------------- -//getFreeParameter -//---------------- -int64_t XEMGaussianSphericalParameter::getFreeParameter() const{ - int64_t nbParameter; // Number of parameters // - int64_t k = _nbCluster; // Sample size // - int64_t d = _pbDimension; // Sample dimension // - - int64_t alphaR = k*d; // alpha for for models with Restrainct proportions (Gaussian_p_...) - int64_t alphaF = (k*d) + k-1; // alpha for models with Free proportions (Gaussian_pk_...) - - switch (_modelType->_nameModel) { - case (Gaussian_p_L_I) : - nbParameter = alphaR + 1; - break; - case (Gaussian_p_Lk_I) : - nbParameter = alphaR + k; // correction 09/09/2009 (old version was alphaR + d) - break; - case (Gaussian_pk_L_I) : - nbParameter = alphaF + 1; - break; - case (Gaussian_pk_Lk_I) : - nbParameter = alphaF + k; // correction 09/09/2009 (old version was alphaR + d) - break; - default : - throw internalMixmodError; - break; - } - return nbParameter; -} - diff --git a/lib/src/mixmod/MIXMOD/XEMGaussianSphericalParameter.h b/lib/src/mixmod/MIXMOD/XEMGaussianSphericalParameter.h deleted file mode 100644 index 54c74fc..0000000 --- a/lib/src/mixmod/MIXMOD/XEMGaussianSphericalParameter.h +++ /dev/null @@ -1,75 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMGaussianSphericalParameter.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMGaussianSphericalParameter_H -#define XEMGaussianSphericalParameter_H - -#include "XEMGaussianEDDAParameter.h" - -/** - @brief Derived class of XEMGaussianParameter for Spherical Gaussian Model(s) - @author F Langrognet & A Echenim -*/ - -class XEMGaussianSphericalParameter : public XEMGaussianEDDAParameter{ - - public: - - /// Default constructor - XEMGaussianSphericalParameter(); - - /// Constructor - // called by XEMModel - XEMGaussianSphericalParameter(XEMModel * iModel, XEMModelType * iModelType); - - /// Constructor (copy) - XEMGaussianSphericalParameter(const XEMGaussianSphericalParameter * iParameter); - - - /// Destructor - virtual ~XEMGaussianSphericalParameter(); - - - /** @brief Selector - @return A copy of the model - */ - XEMParameter * clone() const; - - /// initialisation USER - void initUSER(XEMParameter * iParam); - - /// Compute table of sigmas of the samples of each cluster - // NB : compute also lambda, shpae, orientation, wk, w - void computeTabSigma(); - - double getLogLikelihoodOne() const; - - int64_t getFreeParameter() const; - -}; - - - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMGeneralMatrix.cpp b/lib/src/mixmod/MIXMOD/XEMGeneralMatrix.cpp deleted file mode 100644 index 42d7a74..0000000 --- a/lib/src/mixmod/MIXMOD/XEMGeneralMatrix.cpp +++ /dev/null @@ -1,337 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMGeneralMatrix.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMMatrix.h" -#include "XEMGeneralMatrix.h" -#include "XEMUtil.h" -#include "XEMDiagMatrix.h" -#include "XEMSymmetricMatrix.h" - -//------------ -// Constructor -//------------ -XEMGeneralMatrix::XEMGeneralMatrix(){ - _value = NULL; - _store = NULL; - throw wrongConstructorType; -} - -XEMGeneralMatrix::XEMGeneralMatrix(int64_t pbDimension, double d):XEMMatrix(pbDimension){ - _value = new Matrix(pbDimension, pbDimension); - _store = _value->Store(); - - _s_storeDim = pbDimension * pbDimension; - (*this)=1.0; -} - - - -// copy constructor -XEMGeneralMatrix::XEMGeneralMatrix(XEMGeneralMatrix * A):XEMMatrix(A){ - _value = new Matrix(_s_pbDimension, _s_pbDimension); - _store = _value->Store(); - - _s_storeDim = _s_pbDimension * _s_pbDimension; - - recopyTab(A->getStore(), _store, _s_storeDim); -} - - - -//---------- -//Destructor -//---------- -XEMGeneralMatrix::~XEMGeneralMatrix(){ - if(_value){ - delete _value; - } - _value = NULL; -} - - - -double XEMGeneralMatrix::determinant(XEMErrorType errorType){ - throw nonImplementedMethod; -} - - - - -void XEMGeneralMatrix::equalToMatrixMultiplyByDouble(XEMMatrix* D, double d){ - throw nonImplementedMethod; -} - - - -void XEMGeneralMatrix::multiply(double * V, int64_t nk, XEMGeneralMatrix * Q){ - int64_t indiceV, indiceQ, indice = 0; - double * storeQ = Q->getStore(); - - for (indiceV = 0; indiceV<_s_pbDimension; indiceV++){ - for (indiceQ = 0; indiceQputGeneralValueInStore(_store); -} - -//add M to this -void XEMGeneralMatrix::operator+=(XEMMatrix* M){ - M->addGeneralValueInStore(_store); -} - - -void XEMGeneralMatrix::edit(ostream& flux, string before, string sep,int64_t dim){ - - for (int64_t p=0;p<_s_pbDimension;p++){ - flux <> _store[r]; - } - } - -} - -void XEMGeneralMatrix::input(ifstream & fi, int64_t dim){ - int64_t i,j,r = 0; - - for (i=0; i<_s_pbDimension; i++){ - for (j=0; j> _store[r]; - } - for (j=dim;j<_s_pbDimension;j++,r++){ - _store[r] = 0.0; - } - } - -} - -// gives : det(diag(this)) -double XEMGeneralMatrix::detDiag(XEMErrorType errorType){ - throw nonImplementedMethod; -} - -// trace( this * O * S^{-1} * O' ) -double XEMGeneralMatrix::trace_this_O_Sm1_O(XEMGeneralMatrix* & O, XEMDiagMatrix* & S){ - throw nonImplementedMethod; -} - - -double** XEMGeneralMatrix::storeToArray() const{ - - int64_t i,j, k=0; - double** newStore = new double*[_s_pbDimension]; - for (i=0; i<_s_pbDimension ; ++i){ - newStore[i] = new double[_s_pbDimension]; - for (j=0; j<_s_pbDimension ; ++j){ - newStore[i][j] = _store[k]; - k++; - } - } - - return newStore; -} - diff --git a/lib/src/mixmod/MIXMOD/XEMGeneralMatrix.h b/lib/src/mixmod/MIXMOD/XEMGeneralMatrix.h deleted file mode 100644 index 0291bb5..0000000 --- a/lib/src/mixmod/MIXMOD/XEMGeneralMatrix.h +++ /dev/null @@ -1,234 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMGeneralMatrix.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMGENERALMATRIX_H -#define XEMGENERALMATRIX_H - - -#include "XEMUtil.h" -#include "XEMMatrix.h" - -/** - @brief class GeneralMatrix - @author F Langrognet & A Echenim -*/ - -class XEMDiagMatrix; - -class XEMGeneralMatrix : public XEMMatrix{ - - public: - - /// Default constructor - XEMGeneralMatrix(); - - /// cosntructor : d*Id - ///default value = Id - XEMGeneralMatrix(int64_t pbDimension, double d=1.0); - - XEMGeneralMatrix(XEMGeneralMatrix * A); - - - /// Desctructor - virtual ~XEMGeneralMatrix(); - - /// compute determinant of general matrix - double determinant(XEMErrorType errorType); - - /// return store of general matrix - double * getStore(); - - /// return newmat general matrix - Matrix * getValue(); - - /// return dimension of store - int64_t getStoreDim(); - - /// inverse general matrix - void inverse(XEMMatrix * & A); - - void compute_product_Lk_Wk(XEMMatrix* Wk, double L); - - /// compute (x - mean)' this (x - mean) - double norme(double * xMoinsMean); - - /// this = A / d - void equalToMatrixDividedByDouble(XEMMatrix * A, double d); - /// this = A * d - void equalToMatrixMultiplyByDouble(XEMMatrix*D, double d); - - - /// add : cik * xMoinsMean * xMoinsMean' to this - void add(double * xMoinsMean, double cik); - - // add : diag( cik * xMoinsMean * xMoinsMean' ) to this - //void addDiag(double * xMoinsMean, double cik); - - /// return store of a spherical matrix in a general one - double putSphericalValueInStore(double & store); - /// add store of a spherical matrix in a general one - double addSphericalValueInStore(double & store); - - double getSphericalStore(); - - /// Return store of a diagonal matrix - double* putDiagonalValueInStore(double * store); - /// Add store of a diagonal matrix in a diagonal one - double* addDiagonalValueInStore(double * store); - - double* getDiagonalStore(); - - /// Return store of a diagonal matrix - double* putSymmetricValueInStore(double * store); - /// Add store of a diagonal matrix in a diagonal one - double* addSymmetricValueInStore(double * store); - - double* getSymmetricStore(); - - /// Return store of a diagonal matrix - double* putGeneralValueInStore(double * store); - /// Add store of a diagonal matrix in a diagonal one - double* addGeneralValueInStore(double * store); - - double* getGeneralStore(); - - /// this = (d x Identity) - void operator=(const double& d); - - /// this = this / (d x Identity) - void operator/=(const double& d); - - /// this = this * (d x Identity) - void operator*=(const double& d); - - /// this = this + matrix - void operator+=(XEMMatrix* M); - - /// this = matrix - void operator=(XEMMatrix* M); - - - /// edit general matrix - void edit(ostream& flux, string before,string sep,int64_t dim); - - /// read general matrix from input file - void input(ifstream & fi); - /// read general matrix from input file - void input(ifstream & fi, int64_t dim); - - /// compute general matrix SVD decomposition - void computeSVD(XEMDiagMatrix* & S, XEMGeneralMatrix* & O); - - - - - /// compute Shape as diag(Ot . this . O ) / diviseur - void computeShape_as__diag_Ot_this_O(XEMDiagMatrix* & Shape, XEMGeneralMatrix* & Ori, double diviseur = 1.0); - - /// compute this as : multi * (O * S * O' ) - void compute_as__multi_O_S_O(double multi, XEMGeneralMatrix* & O, XEMDiagMatrix *& S); - - /// compute this as O * S *O' - void compute_as_O_S_O(XEMGeneralMatrix* & O, double* & S_store); - - /// compute trace of this - double computeTrace(); - - /// compute this as matrix * matrix' - void compute_as_M_tM(XEMGeneralMatrix* M,int64_t d); - - /// compute this as matrix * vector - void compute_as_M_V(XEMGeneralMatrix* M, double * V); - /// compute this as vector multiplied by matrix - void multiply(double * V, int64_t nk, XEMGeneralMatrix * Q); - - /// compute M as : M = ( O * S^{-1} * O' ) * this - void compute_M_as__O_Sinverse_Ot_this(XEMGeneralMatrix & M, XEMGeneralMatrix* & O, XEMDiagMatrix* & S); - double compute_trace_W_C(XEMMatrix * C); - // void computeShape_as__diag_Ot_this_O(XEMDiagMatrix* & Shape, XEMGeneralMatrix* & Ori, double diviseur = 1.0); - /// gives : det(diag(this)) - double detDiag(XEMErrorType errorType); - - /// trace( this * O * S^{-1} * O' ) - double trace_this_O_Sm1_O(XEMGeneralMatrix* & O, XEMDiagMatrix* & S); - - //void refreshStore(); - - void setSymmetricStore(double * store); - void setGeneralStore(double * store); - void setDiagonalStore(double * store); - void setSphericalStore(double store); - - double** storeToArray() const; - - - protected : - - Matrix * _value; - - double * _store; - - int64_t _s_storeDim; - -}; -// TODO static : -// int64_t XEMGeneralMatrix::_s_storeDim = 0; - -inline double * XEMGeneralMatrix::getStore(){ - return _store; -} - - -inline Matrix * XEMGeneralMatrix::getValue(){ - return _value; -} - -inline int64_t XEMGeneralMatrix::getStoreDim(){ - return _s_storeDim; -} - -inline void XEMGeneralMatrix::setSymmetricStore(double * store){ - throw wrongMatrixType; -} -inline void XEMGeneralMatrix::setSphericalStore(double store){ - throw wrongMatrixType; -} -inline void XEMGeneralMatrix::setGeneralStore(double * store){ - //_store = store; - recopyTab(store,_store,_s_storeDim); -} -inline void XEMGeneralMatrix::setDiagonalStore(double * store){ - throw wrongMatrixType; -} - - - -/* TODO static - inline void XEMGeneralMatrix::initiate(){ - _s_storeDim = _s_pbDimension * _s_pbDimension / 2; - } -*/ - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMICLCriterion.cpp b/lib/src/mixmod/MIXMOD/XEMICLCriterion.cpp deleted file mode 100644 index 6c19d33..0000000 --- a/lib/src/mixmod/MIXMOD/XEMICLCriterion.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMICLCriterion.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMICLCriterion.h" - - -//------------ -// Constructor -//------------ -XEMICLCriterion::XEMICLCriterion(){ -} - - - - -//----------- -// Destructor -//----------- -XEMICLCriterion::~XEMICLCriterion(){ -} - - -//--- -//run -//--- -void XEMICLCriterion::run(XEMModel * model, double & value, XEMErrorType & error, bool quiet){ - - /* Compute ICL (Integrated Completed Likelihood) Criterion */ - - double completedLoglikelihood; - //double loglikelihood; - int64_t freeParameter; - double logN; - - error = noError; - try{ - completedLoglikelihood = model->getCompletedLogLikelihood(); - freeParameter = model->getFreeParameter(); - logN = model->getLogN(); - - //_value = -2.0*loglikelihood -(2.0*completedLoglikelihood) + (freeParameter*logN); - value = -2.0*completedLoglikelihood + freeParameter*logN; - } - catch(XEMErrorType & e){ - error = e; - } -} - diff --git a/lib/src/mixmod/MIXMOD/XEMICLCriterion.h b/lib/src/mixmod/MIXMOD/XEMICLCriterion.h deleted file mode 100644 index 59a1c61..0000000 --- a/lib/src/mixmod/MIXMOD/XEMICLCriterion.h +++ /dev/null @@ -1,59 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMICLCriterion.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMICLCRITERION_H -#define XEMICLCRITERION_H - - -#include "XEMCriterion.h" -#include "XEMModel.h" - -/** - @brief Derived class of XEMCriterion for ICL Criterion - @author F Langrognet & A Echenim -*/ -class XEMICLCriterion : public XEMCriterion{ - - public: - - /// Default constructor - XEMICLCriterion(); - - /// Destructor - virtual ~XEMICLCriterion(); - - - XEMCriterionName getCriterionName() const; - - // Run method - void run(XEMModel * model, double & value, XEMErrorType & error, bool quiet=true); - - -}; - -inline XEMCriterionName XEMICLCriterion::getCriterionName() const{ - return ICL; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMIndividualColumnDescription.cpp b/lib/src/mixmod/MIXMOD/XEMIndividualColumnDescription.cpp deleted file mode 100644 index 19d21b6..0000000 --- a/lib/src/mixmod/MIXMOD/XEMIndividualColumnDescription.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMIndividualColumnDescription.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#include "XEMIndividualColumnDescription.h" - - -XEMIndividualColumnDescription::XEMIndividualColumnDescription():XEMColumnDescription(){ -} - -XEMIndividualColumnDescription::XEMIndividualColumnDescription(int64_t index):XEMColumnDescription(index){ - _index = index; - _individualDescription.resize(0); -} - -XEMIndividualColumnDescription::~XEMIndividualColumnDescription(){ -} - -string XEMIndividualColumnDescription::editType(){ - return "Individual"; -} - -XEMColumnDescription * XEMIndividualColumnDescription::clone()const{ - XEMIndividualColumnDescription * ICD = new XEMIndividualColumnDescription(); - ICD->_index = _index; - ICD->_name = _name; - - //filling of structure which describes individuals - ICD->_individualDescription.resize(_individualDescription.size()); - for (int64_t i = 0; i<_individualDescription.size() ; ++i){ - IndividualDescription indDescription; - indDescription.name = _individualDescription[i].name; - indDescription.num = _individualDescription[i].num; - ICD->_individualDescription[i] = indDescription; - } - return ICD; -} - -void XEMIndividualColumnDescription::setIndividualDescription(IndividualDescription & individualDescription, int64_t index){ - if (index>=0 && index<_individualDescription.size()){ - _individualDescription[index].name = individualDescription.name; - _individualDescription[index].num = individualDescription.num; - } -} - -void XEMIndividualColumnDescription::insertIndividualDescription(IndividualDescription individualDescription, int64_t index){ - if (index>=0 && index<=_individualDescription.size()){ - _individualDescription.insert(_individualDescription.begin()+index, individualDescription); - }else{ - throw; - } -} diff --git a/lib/src/mixmod/MIXMOD/XEMIndividualColumnDescription.h b/lib/src/mixmod/MIXMOD/XEMIndividualColumnDescription.h deleted file mode 100644 index c17d302..0000000 --- a/lib/src/mixmod/MIXMOD/XEMIndividualColumnDescription.h +++ /dev/null @@ -1,67 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMIndividualColumnDescription.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMINDIVIDUALCOLUMNDESCRIPTION_H -#define XEMINDIVIDUALCOLUMNDESCRIPTION_H - -#include "XEMColumnDescription.h" - -//Individual Description -struct IndividualDescription{ - int64_t num; - string name; -}; - -class XEMIndividualColumnDescription : public XEMColumnDescription -{ - public : - /// Default constructor - XEMIndividualColumnDescription(); - - /// initialization constructor - XEMIndividualColumnDescription(int64_t index); - - /// Destructor - virtual ~XEMIndividualColumnDescription(); - - string editType(); - - XEMColumnDescription * clone()const; - - const vector & getIndividualDescription()const; - - void setIndividualDescription(IndividualDescription & individualDescription, int64_t index); - - void insertIndividualDescription(IndividualDescription individualDescription, int64_t index); - - private : - vector _individualDescription; - -}; - -inline const vector & XEMIndividualColumnDescription::getIndividualDescription()const{ - return _individualDescription; -} - -#endif // XEMINDIVIDUALCOLUMNDESCRIPTION_H diff --git a/lib/src/mixmod/MIXMOD/XEMInput.cpp b/lib/src/mixmod/MIXMOD/XEMInput.cpp deleted file mode 100644 index d1391e8..0000000 --- a/lib/src/mixmod/MIXMOD/XEMInput.cpp +++ /dev/null @@ -1,378 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMInput.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMInput.h" -#include "XEMGaussianData.h" -#include "XEMBinaryData.h" -#include "XEMError.h" -#include "XEMLabelDescription.h" - -//-------------------- -// Default Constructor -//-------------------- -XEMInput::XEMInput(){ - _nbSample = 0; - _pbDimension = 0; - _nbCluster.clear(); - _knownPartition = NULL; - _labelDescription = NULL; - _finalized = false; - //_dataDescription will be created by default XEMDataDescription constructor -} - - -//----------------- -// Copy Constructor -//----------------- -XEMInput::XEMInput(const XEMInput & input){ - _finalized = input._finalized; - - _nbSample = input._nbSample; - _pbDimension = input._pbDimension; - _nbCluster = input._nbCluster; - - _dataDescription = (input._dataDescription); // op = - - - _knownPartition = NULL; - if (input._knownPartition != NULL){ - _knownPartition = new XEMPartition(input._knownPartition); - } - - if (!_labelDescription) - delete _labelDescription; - - _labelDescription = NULL; - if (input._labelDescription != NULL){ - _labelDescription = new XEMLabelDescription(*input._labelDescription); - } - - _criterionName = input._criterionName; - _modelType = input._modelType; - -} - - - -//--------------------------- -// Initialisation Constructor -//--------------------------- -XEMInput::XEMInput(const vector & iNbCluster, const XEMDataDescription & iDataDescription){ - cloneInitialisation(iNbCluster, iDataDescription); -} - -//--------------------- -// Clone Initialisation -//--------------------- -void XEMInput::cloneInitialisation(const vector & iNbCluster, const XEMDataDescription & iDataDescription){ - _finalized = false; - - _nbSample = iDataDescription.getNbSample(); - _pbDimension = iDataDescription.getPbDimension(); - _nbCluster = iNbCluster; // copy Constructor - - //_data - _dataDescription = iDataDescription; - - _knownPartition = NULL; - _labelDescription = NULL; - _criterionName.push_back(defaultCriterionName); - - if ( _dataDescription.isBinaryData()==false ){ - _modelType.push_back(new XEMModelType()); - } - else{ - _modelType.push_back(new XEMModelType(defaultBinaryModelName)); - } -} - - -//--------------------------------- -// Constructor used in DCV context -//-------------------------------- -XEMInput::XEMInput(XEMInput * originalInput, XEMCVBlock & learningBlock){ - throw internalMixmodError; -} - - - -//----------- -// Destructor -//----------- -XEMInput::~XEMInput(){ - if (!_knownPartition){ - delete _knownPartition; - } - if (!_labelDescription){ - delete _labelDescription; - } - -} - - - -//------------ -//------------ -// Modifiers -//------------ -//------------ - -//------ Criterion ----// - -//getCriterionName[i] -//------------------- -XEMCriterionName XEMInput::getCriterionName(int64_t index) const{ - if (index>=0 && index<_criterionName.size()){ - return _criterionName[index]; - } - else{ - throw wrongCriterionPositionInGet; - } -} - - -//setCriterionName -//---------------- -void XEMInput::setCriterionName(XEMCriterionName criterionName, int64_t index){ - if (index>=0 && index<_criterionName.size()){ - _criterionName[index] = criterionName; - } - else{ - throw wrongCriterionPositionInSet; - } - _finalized = false; -} - - -// insertCriterionName -//----------------- -void XEMInput::insertCriterionName(XEMCriterionName criterionName, int64_t index){ - if (index>=0 && index<=_criterionName.size()){ - _criterionName.insert (_criterionName.begin()+index , criterionName); - } - else{ - throw wrongCriterionPositionInInsert; - } - _finalized = false; -} - - -// removeCriterionName -//-------------------- -void XEMInput::removeCriterionName(int64_t index){ - if (index>=0 && index<_criterionName.size()){ - _criterionName.erase(_criterionName.begin()+index); - } - else{ - throw wrongCriterionPositionInRemove; - } - _finalized = false; -} - - - - - - -//------ modelType ----// - -//getModelType[i] -//------------------- -XEMModelType * XEMInput::getModelType(int64_t index) const{ - if (index>=0 && index<_modelType.size()){ - return _modelType[index]; - } - else{ - throw wrongModelPositionInGet; - } -} - - -//setModelType -//---------------- -void XEMInput::setModelType(const XEMModelType * modelType, int64_t index){ - if (index>=0 && index<_modelType.size()){ - _modelType[index] = new XEMModelType(*modelType); - } - else{ - throw wrongModelPositionInSet; - } - _finalized = false; -} - - -// insertModelType -//----------------- -void XEMInput::insertModelType(const XEMModelType * modelType, int64_t index){ - if (index>=0 && index<=_modelType.size()){ - _modelType.insert (_modelType.begin()+index , new XEMModelType(*modelType)); - } - else{ - throw wrongModelPositionInInsert; - } - _finalized = false; -} - - -// removeModelType -//-------------------- -void XEMInput::removeModelType(int64_t index){ - if (index>=0 && index<_modelType.size()){ - _modelType.erase(_modelType.begin()+index); - } - else{ - throw wrongModelPositionInRemove; - } - _finalized = false; -} - - - - - - -// ---- Weight ----// - -//setWeight() -//----------- -//TODO a enlever -void XEMInput::setWeight(string weightFileName){ - //_data->setWeight(weightFileName); - _finalized = false; -} - -//TODO a enlever -void XEMInput::insertWeight(string weightFileName){ - //_data->setWeight(weightFileName); - _finalized = false; -} - -//TODO a enlever -void XEMInput::removeWeight(){ - //_data->setWeightDefault(); - _finalized = false; -} - - - -// ----- KnownPartition ----// - -// setKnownPartition -//------------------ -void XEMInput::setKnownPartition(string iFileName){ - if (_nbCluster.size() != 1){ - throw badSetKnownPartition; - } - else{ - if (_knownPartition){ - delete _knownPartition; - } - XEMNumericPartitionFile partitionFile; - partitionFile._fileName = iFileName; - partitionFile._format = FormatNumeric::defaultFormatNumericFile; - partitionFile._type = TypePartition::defaultTypePartition; - _knownPartition = new XEMPartition(_nbSample, _nbCluster[0], partitionFile); - } - _finalized = false; -} - - - -// insertKnownPartition -//--------------------- -void XEMInput::insertKnownPartition(string iFileName){ - if (_nbCluster.size() != 1){ - throw badSetKnownPartition; - } - else{ - if (_knownPartition){ - delete _knownPartition; - } - XEMNumericPartitionFile partitionFile; - partitionFile._fileName = iFileName; - partitionFile._format = FormatNumeric::defaultFormatNumericFile; - partitionFile._type = TypePartition::defaultTypePartition; - _knownPartition = new XEMPartition(_nbSample, _nbCluster[0], partitionFile); - } - _finalized = false; -} - -// removeKnownPartition -//--------------------- -void XEMInput::removeKnownPartition(){ - if (_knownPartition){ - delete _knownPartition; - } - _finalized = false; -} - -void XEMInput::setLabel(XEMLabelDescription & labeldescription) -{ - removeLabel(); - - _labelDescription = new XEMLabelDescription(labeldescription); -} - -void XEMInput::removeLabel() -{ - if (!_labelDescription) - delete _labelDescription; - - _labelDescription = NULL; -} - -// -------- -// finalize -// -------- -void XEMInput::finalize(){ - if (!_finalized){ - _finalized = verif(); - } -} - - - - -// ---------------- -// Verif -//----------------- -bool XEMInput::verif(){ - bool res = true; - - // verif 1 : required inputs - if ( _nbSample == 0 - || _pbDimension == 0 - || _nbCluster.empty() ) { - res = false; - throw missingRequiredInputs; - } - - - // verif 2 : _data->verify - res = _dataDescription.verifyData(); - - return res; -} - - diff --git a/lib/src/mixmod/MIXMOD/XEMInput.h b/lib/src/mixmod/MIXMOD/XEMInput.h deleted file mode 100644 index 2d95003..0000000 --- a/lib/src/mixmod/MIXMOD/XEMInput.h +++ /dev/null @@ -1,368 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMInput.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMINPUT_H -#define XEMINPUT_H - - -#include "XEMUtil.h" -#include "XEMData.h" -#include "XEMPartition.h" -#include "XEMClusteringStrategy.h" - - -class XEMLabelDescription; - -using namespace std; - -class XEMInput{ - - public: - - /// Default Constructor - XEMInput(); - - /// Copy Constructor - XEMInput(const XEMInput & input); - - /// Initialisation constructor - XEMInput(const vector & iNbCluster, const XEMDataDescription & iDataDescription); - - /// clone initialisation - void cloneInitialisation(const vector & iNbCluster, const XEMDataDescription & iDataDescription); - - // Constructor used in DCV context - XEMInput(XEMInput * originalInput, XEMCVBlock & learningBlock); - - /// Destructor - virtual ~XEMInput(); - - - //---------------------------- - // Modifiers - //---------------------------- - - //------ Sample ----// - /// getNbSample - int64_t getNbSample() const; - - - //------ Dimension ----// - /// getPbDimension - int64_t getPbDimension() const; - - - //------ nbCluster ----// - /// get all NbCluster - vector getNbCluster() const; - - /// get ith NbCluster - int64_t getNbCluster(int64_t index) const; - - /// get NbCluster size - int64_t getNbClusterSize() const; - - - //------ Criterion ----// - /// get All Criterion Name - vector getCriterionName() const; - - ///getNbCriterionName - int64_t getNbCriterionName() const; - - ///getCriterionName[i] - XEMCriterionName getCriterionName(int64_t index) const; - - /// setCriterionName - void setCriterionName(XEMCriterionName criterionName, int64_t index); - - ///insertCriterionName[i] - void insertCriterionName(XEMCriterionName criterionName, int64_t index); - - /// removeCriterionName - void removeCriterionName(int64_t index); - - - // ----- ModelType ----// - /// getNbModelType - int64_t getNbModelType() const; - - /// getModelType[i] - XEMModelType * getModelType(int64_t index) const; - - /// setModelType - void setModelType(const XEMModelType * modelType, int64_t index); - - /// insertModelType - void insertModelType(const XEMModelType * modelType, int64_t index); - - /// removeModelType - void removeModelType(int64_t index); - - /// setSubDimensionEqual - // void setSubDimensionEqual(int64_t modelTypePosition, int64_t subDimensionValue); - - /// setSubDimensionFreel - // void setSubDimensionFree(int64_t modelTypePosition, int64_t subDimensionValue, int64_t dimensionPosition); - - ///setWeight(); - void setWeight(string weightFileName); - - ///removeWeight(); - void removeWeight(); - - ///insertWeight(); - void insertWeight(string weightFileName); - - - ///removeWeight(); - //void removeWeight(); - - - // ----- KnownPartition ----// - /// getKnownPartition - XEMPartition * getKnownPartition() const; - - /// setKnownPartition - void setKnownPartition(string iFileName); - - /// insertKnownPartition - void insertKnownPartition(string iFileName); - - /// removeKnownPartition - void removeKnownPartition(); - - //------- Label -----------// - ///getLabel - const XEMLabelDescription * getLabel() const; - - /// setLabel - void setLabel(XEMLabelDescription & labeldescription); - - /// removeLabel - void removeLabel(); - - // ----------------------------------------------------------------------------------------------- - // Other virtual Selector methods throw error (otherwise this method is write in inherited classes - // ----------------------------------------------------------------------------------------------- - virtual XEMClusteringStrategy * getStrategy() const; - - // setStrategy - virtual void setStrategy(XEMClusteringStrategy * strat); - - - - // - /// isBinaryData - const bool isBinaryData() const; - - - void finalize(); - - /// get Data Description - const XEMDataDescription & getDataDescription() const; - - /// get Data - XEMData * getData() const; - - bool isFinalized() const; - - protected : - //--------- - ///. verification of inputs validity - virtual bool verif(); - - - //------- - private : - //------- - - /// Data Description - XEMDataDescription _dataDescription; - - // Number of samples (no reduced data) - int64_t _nbSample; - - // Problem dimension - int64_t _pbDimension; - - // nbCluster - vector _nbCluster; - - // Known Partition - XEMPartition * _knownPartition; - XEMLabelDescription * _labelDescription; - - // CriterionName - vector _criterionName; - - // ModelType - vector _modelType; - - /** a input object must be finalized (verif, ...) - */ - bool _finalized; - -}; - -inline int64_t XEMInput::getNbSample() const{ - return _nbSample; -} - -inline int64_t XEMInput::getPbDimension() const{ - return _pbDimension; -} - - -inline vector XEMInput::getNbCluster() const{ - return _nbCluster; -} - -inline int64_t XEMInput::getNbCluster(int64_t index) const{ - return _nbCluster[index]; -} - -inline int64_t XEMInput::getNbClusterSize() const{ - return _nbCluster.size(); -} - -inline int64_t XEMInput::getNbCriterionName() const{ - return _criterionName.size(); -} - -inline int64_t XEMInput::getNbModelType() const{ - return _modelType.size(); -} - -inline XEMPartition * XEMInput::getKnownPartition() const{ - return _knownPartition; -} - -inline const XEMLabelDescription * XEMInput::getLabel() const{ - return _labelDescription; -} - -inline const bool XEMInput::isBinaryData() const{ - return _dataDescription.isBinaryData(); -} - -inline bool XEMInput::isFinalized() const{ - return _finalized; -} - - - -inline XEMClusteringStrategy * XEMInput::getStrategy()const{ - throw errorInXEMInputSelector; -} - - -inline void XEMInput::setStrategy(XEMClusteringStrategy * strat){ - throw errorInXEMInputSelector; -} - - -inline const XEMDataDescription & XEMInput::getDataDescription() const{ - return _dataDescription; -} - -inline XEMData * XEMInput::getData() const{ - return _dataDescription.getData(); -} - -inline vector XEMInput::getCriterionName() const{ - return _criterionName; -} - - -/* - - - inline const int64_t & XEMOldInput::getNbSample() const{ - return _nbSample; - } - - inline const int64_t & XEMOldInput::getPbDimension() const{ - return _pbDimension; - } - - inline void XEMOldInput::setWeight(string & fileNameWeight){ - if (fileNameWeight.compare("") == 0){ - return _data->setWeightDefault(); - }else{ - return _data->setWeight(fileNameWeight); - } - } - - inline const XEMPartition** XEMOldInput::getTabPartition() const{ - return const_cast(_tabKnownPartition); - } - - inline const XEMPartition* XEMOldInput::getTabPartitionI(int64_t index) const{ - return _tabKnownPartition[index]; - } - - inline const int64_t & XEMOldInput::getNbNbCluster() const{ - return _nbNbCluster; - } - - inline const int64_t* XEMOldInput::getTabNbCluster() const{ - return _tabNbCluster; - } - - inline const int64_t XEMOldInput::getTabNbClusterI(int64_t index) const{ - return _tabNbCluster[index]; - } - - inline const XEMCriterionName * XEMOldInput::getTabCriterionName() const{ - return _tabCriterionName; - } - - inline const XEMCriterionName & XEMOldInput::getCriterionName(int64_t index) const{ - return _tabCriterionName[index]; - } - - - inline const XEMModelType** XEMOldInput::getTabModelType() const{ - return const_cast(_tabModelType); - } - - - inline const XEMModelType* XEMOldInput::getTabModelTypeI(int64_t index) const{ - return _tabModelType[index]; - } -*/ -/* - inline int64_t XEMOldInput::getNbKnownPartition() const{ - int64_t nbPartition; - if (_tabKnownPartition){ - nbPartition = _nbNbCluster; - } - else{ - nbPartition = 0; - } - return nbPartition; - }*/ - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMInputControler.cpp b/lib/src/mixmod/MIXMOD/XEMInputControler.cpp deleted file mode 100644 index 1280517..0000000 --- a/lib/src/mixmod/MIXMOD/XEMInputControler.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMInputControler.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMInputControler.h" - - -//------------ -// Constructor -//------------ -XEMInputControler::XEMInputControler(){ - _input = NULL; -} - - - -//------------ -// Constructor -//------------ -XEMInputControler::XEMInputControler(XEMOldInput * input){ - _input = input; -} - - - -//----------- -// Destructor -//----------- -XEMInputControler::~XEMInputControler(){ -} - - - -//--- -//run -//--- -void XEMInputControler::run(const string iFileName){ - ifstream file(iFileName.c_str(), ios::in); - if (! file.is_open()) - throw wrongInputFileName; - file >> (*_input); - file.close(); -} - - diff --git a/lib/src/mixmod/MIXMOD/XEMInputControler.h b/lib/src/mixmod/MIXMOD/XEMInputControler.h deleted file mode 100644 index d5aceb7..0000000 --- a/lib/src/mixmod/MIXMOD/XEMInputControler.h +++ /dev/null @@ -1,59 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMInputControler.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMINPUTCONTROLER_H -#define XEMINPUTCONTROLER_H - -#include "XEMOldInput.h" - - - -/** @brief Base class for Input(s) Controler - @author F Langrognet & A Echenim -*/ - -class XEMInputControler{ - - public: - - /// Default constructor - XEMInputControler(); - - /// Constructor - XEMInputControler(XEMOldInput * input); - - /// Destructor - virtual ~XEMInputControler(); - - - /** @brief run method - @param fileName : the input file - */ - void run(const string iFileName ="geyser.xem"); - - /// Current Input - XEMOldInput * _input; -}; - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMLabel.cpp b/lib/src/mixmod/MIXMOD/XEMLabel.cpp deleted file mode 100644 index 4d585db..0000000 --- a/lib/src/mixmod/MIXMOD/XEMLabel.cpp +++ /dev/null @@ -1,220 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMLabel.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMLabel.h" -#include "XEMLabelDescription.h" - -//------------ -// Constructor -//------------ -XEMLabel::XEMLabel(){ - _nbSample = 0; -} - - -//------------ -// Constructor -//------------ -XEMLabel::XEMLabel(int64_t nbSample){ - _nbSample = nbSample; - _label.resize(_nbSample); -} - - - -//------------ -// Constructor -//------------ -XEMLabel::XEMLabel(XEMEstimation * estimation){ - - XEMModel * model = estimation->getModel(); - if (model == NULL){ - throw internalMixmodError; - } - - // compute tabLabel - //----------------- - int64_t * tabLabel = NULL; - int64_t nbCluster = estimation->getNbCluster(); - - XEMModelType * modelType = model->getParameter()->getModelType(); - bool binary = isBinary(modelType->_nameModel); - if (!binary){ - _nbSample = estimation->getNbSample(); - int64_t ** tabPartition = new int64_t*[_nbSample]; - for (int64_t i=0; i<_nbSample; i++){ - tabPartition[i] = new int64_t[nbCluster]; - } - tabLabel = new int64_t[_nbSample]; - estimation->getModel()->getLabelAndPartitionByMAPOrKnownPartition(tabLabel, tabPartition); - } - //// - else{ - //// - //binary case - const vector & correspondenceOriginDataToReduceData = estimation->getcorrespondenceOriginDataToReduceData(); - _nbSample = correspondenceOriginDataToReduceData.size(); - tabLabel = new int64_t[_nbSample]; - - //label et partition on reduceData - int64_t nbSampleOfDataReduce = estimation->getModel()->getNbSample(); - int64_t * tabLabelReduce = new int64_t[nbSampleOfDataReduce]; - int64_t ** tabPartitionReduce = new int64_t*[nbSampleOfDataReduce]; - for (int64_t i=0; igetModel()->getLabelAndPartitionByMAPOrKnownPartition(tabLabelReduce, tabPartitionReduce); - - double ** tabPostProbaReduce = NULL; - tabPostProbaReduce = copyTab(estimation->getModel()->getPostProba(), nbSampleOfDataReduce, nbCluster); // copy - - // convert labelReduce, partitionReduce, postProbaReduce to label, partition, postProba - for (int64_t i=0; i<_nbSample; i++){ - tabLabel[i] = tabLabelReduce[correspondenceOriginDataToReduceData[i]]; - } - - //delete - for (int64_t i=0; i>read; - if (read>=1 && read<=nbCluster){ - _label[i] = read; - } - else{ - throw badValueInLabelInput; - } - i++; - } - - if (!flux.eof() && i!=_nbSample){ - throw notEnoughValuesInLabelInput; - } - -} - -// ----------- -//input stream -// read labels between 1 and nbCluster -// ----------- -void XEMLabel::input(const XEMLabelDescription & labelDescription){ - int64_t i = 0; - int64_t readLabel; - - string labelFilename = labelDescription.getFileName(); - - _nbSample = labelDescription.getNbSample(); - - ifstream fi((labelFilename).c_str(), ios::in); - if (! fi.is_open()){ - throw wrongDataFileName; - } - - while (i<_nbSample && !fi.eof()){ - for (int64_t j =0; j>stringTmp; - //cout<>readLabel; - _label.push_back(readLabel); - } - } - ++i; - } - if (!fi.eof() && i!=_nbSample){ - throw notEnoughValuesInLabelInput; - } -} diff --git a/lib/src/mixmod/MIXMOD/XEMLabel.h b/lib/src/mixmod/MIXMOD/XEMLabel.h deleted file mode 100644 index 5d138c3..0000000 --- a/lib/src/mixmod/MIXMOD/XEMLabel.h +++ /dev/null @@ -1,96 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMLabel.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMLabel_H -#define XEMLabel_H -#include "XEMEstimation.h" -#include "XEMCVCriterion.h" - - - -/** @brief Base class for Label(s) - @author F Langrognet & A Echenim -*/ - -class XEMLabel{ - - public: - - /// Default constructor - XEMLabel(); - - /// Constructor - XEMLabel(int64_t nbSample); - - /// Constructor - XEMLabel(XEMEstimation * estimation); - - XEMLabel(const XEMLabel & iLabel); - - /// Destructor - virtual ~XEMLabel(); - - /// editProba - void edit(ostream & stream); - - /// getProba - int64_t * getTabLabel() const; - - /// getProba - vector getLabel() const; - - /// set Label - void setLabel(int64_t * label, int64_t nbSample); - void setLabel(vector label); - - /// Selector - int64_t getNbSample() const; - - ///input stream - void input(ifstream & flux, int64_t nbCluster); - void input(const XEMLabelDescription & labelDescription); - - private : - - /// Number of samples - int64_t _nbSample; - - /// dim : _nbSample *_nbCluster - vector _label; - -}; - - -inline vector XEMLabel::getLabel() const{ - return _label; -} - -inline int64_t XEMLabel::getNbSample() const{ - return _nbSample; -} - - - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMLabelDescription.cpp b/lib/src/mixmod/MIXMOD/XEMLabelDescription.cpp deleted file mode 100644 index 71b546f..0000000 --- a/lib/src/mixmod/MIXMOD/XEMLabelDescription.cpp +++ /dev/null @@ -1,159 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMLabelDescription.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#include "XEMLabelDescription.h" - -//------------ -// Constructor by default -//------------ -XEMLabelDescription::XEMLabelDescription() : XEMDescription(){ - _label = NULL; -} - - - -// --------------------------- -//constructor by initilization -// --------------------------- -XEMLabelDescription::XEMLabelDescription(int64_t nbSample, int64_t nbColumn, std::vector< XEMColumnDescription* > columnDescription, FormatNumeric::XEMFormatNumericFile format, string filename, string infoName):XEMDescription(nbSample, nbColumn, columnDescription, format, filename, infoName){ - _label = createLabel(); - // _infoName = "infoName"; - // _nbSample = nbSample; - // _nbColumn = 1; - // _fileName = filename; - // _format = format; - // _columnDescription.resize(1); - // _columnDescription[0] = new XEMQualitativeColumnDescription(0, nbCluster); - // string name("Label"); - // _columnDescription[0]->setName(name); - // _label = new XEMLabel(_nbSample); - // ifstream fi(filename.c_str(), ios::in); - // if (! fi.is_open()){ - // throw wrongLabelFileName; - // } - // _label->input(fi, nbCluster); -} - - -//------------------------------------- -// Constructor after an estimation->run -//-------------------------------------- -XEMLabelDescription::XEMLabelDescription(XEMEstimation * estimation) : XEMDescription(){ - if (estimation){ - _infoName = "Label"; - _nbSample = estimation->getNbSample(); - _nbColumn = 1; - _fileName = ""; - _format = FormatNumeric::txt; - _columnDescription.resize(1); - _columnDescription[0] = new XEMQualitativeColumnDescription(0, estimation->getNbCluster()); - string name("Label"); - _columnDescription[0]->setName(name); - _label = new XEMLabel(estimation); - } - else{ - throw nullPointerError; - } -} - - - - - - - - -//------------ -// Constructor by copy -//------------ -XEMLabelDescription::XEMLabelDescription(XEMLabelDescription & labelDescription){ - (*this) = labelDescription; -} - - -//------------ -// operator = -//------------ -XEMLabelDescription & XEMLabelDescription::operator=( XEMLabelDescription & labelDescription){ - _fileName = labelDescription._fileName; - _format = labelDescription._format; - _infoName = labelDescription._infoName; - _nbSample = labelDescription._nbSample; - _nbColumn = labelDescription._nbColumn; - _columnDescription.resize(_nbColumn); - _label = new XEMLabel(*(labelDescription.getLabel())); - return *this; -} - -//------------ -// Destructor -//------------ -XEMLabelDescription::~XEMLabelDescription(){ -} - - -//-------- -// ostream -//-------- -void XEMLabelDescription::saveNumericValues(string fileName){ - //if (_fileName==""){ - ofstream fo(fileName.c_str(), ios::out); - _label->edit(fo); - _fileName = fileName; - //} - /* else : if _fileName!="", labelDescription has been created by a XML file. - In this case, the numeric file already exists. - */ -} - - -XEMLabel* XEMLabelDescription::createLabel() -{ - XEMLabel * label = new XEMLabel(); - - int64_t nbQualitativeVariable = 0; - int64_t nbIndividualVariable = 0; - - for (int64_t i=0; i<_nbColumn; i++){ - if (typeid(*(_columnDescription[i])) == typeid(XEMQualitativeColumnDescription)){ - nbQualitativeVariable++; - } - if (typeid(*(_columnDescription[i]))==typeid(XEMQuantitativeColumnDescription)){ - throw badLabelDescription; - } - if (typeid(*(_columnDescription[i]))==typeid(XEMWeightColumnDescription)){ - throw tooManyWeightColumnDescription; - } - if (typeid(*(_columnDescription[i]))==typeid(XEMIndividualColumnDescription)){ - nbIndividualVariable++; - } - } - - if (nbQualitativeVariable != 1 || nbIndividualVariable>1){ - throw badLabelDescription; - } - label-> input(*this); - return label; -} diff --git a/lib/src/mixmod/MIXMOD/XEMLabelDescription.h b/lib/src/mixmod/MIXMOD/XEMLabelDescription.h deleted file mode 100644 index 16fea60..0000000 --- a/lib/src/mixmod/MIXMOD/XEMLabelDescription.h +++ /dev/null @@ -1,74 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMLabelDescription.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#ifndef XEMLABELDESCRIPTION_H -#define XEMLABELDESCRIPTION_H - -#include "XEMDescription.h" -#include "XEMEstimation.h" -#include "XEMLabel.h" - - -class XEMLabelDescription : public XEMDescription -{ - public: - /// Default constructor - XEMLabelDescription(); - - ///constructor by initilization - XEMLabelDescription(int64_t nbSample, int64_t nbColumn, std::vector< XEMColumnDescription* > columnDescription, FormatNumeric::XEMFormatNumericFile format, string filename, string infoName = ""); - - ///constructor after an estimation->run - XEMLabelDescription(XEMEstimation * estimation); - - - ///constructor by copy - XEMLabelDescription(XEMLabelDescription & labelDescription); - - /// Destructor - virtual ~XEMLabelDescription(); - - - ///operator= - XEMLabelDescription & operator=( XEMLabelDescription & labelDescription); - - const XEMLabel * getLabel() const; - - void saveNumericValues(string fileName=""); - - private : - - XEMLabel * _label; - XEMLabel* createLabel(); -}; - -inline const XEMLabel * XEMLabelDescription::getLabel() const{ - return _label; -} - - - - -#endif // XEMLABELDESCRIPTION_H diff --git a/lib/src/mixmod/MIXMOD/XEMLikelihoodOutput.cpp b/lib/src/mixmod/MIXMOD/XEMLikelihoodOutput.cpp deleted file mode 100644 index 50ec114..0000000 --- a/lib/src/mixmod/MIXMOD/XEMLikelihoodOutput.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMLikelihoodOutput.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMLikelihoodOutput.h" - - -//------------ -// Constructor -//------------ -XEMLikelihoodOutput::XEMLikelihoodOutput(){ -} - -XEMLikelihoodOutput::XEMLikelihoodOutput(double logLikelihood, double completeLogLikelihood, double entropy, int64_t nbFreeParam){ - _logLikelihood = logLikelihood; - _completeLogLikelihood = completeLogLikelihood; - _entropy = entropy; - _nbFreeParam = nbFreeParam; -} - - - -//------------ -// Constructor -//------------ -XEMLikelihoodOutput::XEMLikelihoodOutput(XEMModel * model){ - _logLikelihood = model->getLogLikelihood(false); // false : to not compute fik because already done - _completeLogLikelihood = model->getCompletedLogLikelihood(); - _entropy = model->getEntropy(); - _nbFreeParam = model->getFreeParameter(); -} - - - -//---------- -//Destructor -//---------- -XEMLikelihoodOutput::~XEMLikelihoodOutput(){ -} - - - -//---- -//edit -//---- -void XEMLikelihoodOutput::edit(ofstream & oFile, bool text){ - if(text){ - oFile<<"\t\t\tNumber of Free Parameters : "<<_nbFreeParam<. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMLikelihoodOutput_H -#define XEMLikelihoodOutput_H - -#include "XEMModel.h" - - - -/** @brief Base class for Label(s) - @author F Langrognet & A Echenim -*/ - -class XEMLikelihoodOutput{ - - public: - - /// Default constructor - XEMLikelihoodOutput(double logLikelihood, double completeLogLikelihood, double entropy, int64_t nbFreeParam); - - XEMLikelihoodOutput(); - /// Constructor - XEMLikelihoodOutput(XEMModel * model); - - /// Destructor - virtual ~XEMLikelihoodOutput(); - - /// Edit - void edit(ofstream & oFile, bool text=false); - - - ///Selector - double getLogLikelihood() const; - double getCompleteLogLikelihood() const; - - private : - - /// Value of logLikelihood - double _logLikelihood; - - /// Value of completed logLikelihood - double _completeLogLikelihood; - - /// Value of entropyd - double _entropy; - - /// Number of free parameter - int64_t _nbFreeParam; - -}; - -inline double XEMLikelihoodOutput::getLogLikelihood() const{ - return _logLikelihood; -} - -inline double XEMLikelihoodOutput::getCompleteLogLikelihood() const{ - return _completeLogLikelihood; -} - - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMMAPAlgo.cpp b/lib/src/mixmod/MIXMOD/XEMMAPAlgo.cpp deleted file mode 100644 index 45e988b..0000000 --- a/lib/src/mixmod/MIXMOD/XEMMAPAlgo.cpp +++ /dev/null @@ -1,85 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMMAPAlgo.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMMAPAlgo.h" - - -//------------ -// Constructor -//------------ -XEMMAPAlgo::XEMMAPAlgo(){ - _algoStopName = NBITERATION; - _nbIteration =1 ; -} - - - -/// Copy constructor -XEMMAPAlgo::XEMMAPAlgo(const XEMMAPAlgo & mapAlgo):XEMAlgo(mapAlgo){ -} - - -//------------ -// Constructor -//------------ -XEMMAPAlgo::XEMMAPAlgo(XEMAlgoStopName algoStopName, double epsilon, int64_t nbIteration) - :XEMAlgo(algoStopName, epsilon, nbIteration){ -} - - - -//----------- -// Destructor -//----------- -XEMMAPAlgo::~XEMMAPAlgo(){ -} - - - -// clone -//------ -XEMAlgo * XEMMAPAlgo::clone(){ - return (new XEMMAPAlgo(*this)); -} - - - -void XEMMAPAlgo::setAlgoStopName(XEMAlgoStopName * algoStopName){ - throw internalMixmodError; -} - - - -//--- -//run -//--- -void XEMMAPAlgo::run(XEMModel *& model){ - _indexIteration = 0; - model = model; - model->setAlgoName(MAP); - model->MAPstep(); // MAP Step - //cout << "\nMAP algorithm \n"; -} - - diff --git a/lib/src/mixmod/MIXMOD/XEMMAPAlgo.h b/lib/src/mixmod/MIXMOD/XEMMAPAlgo.h deleted file mode 100644 index 90aa114..0000000 --- a/lib/src/mixmod/MIXMOD/XEMMAPAlgo.h +++ /dev/null @@ -1,84 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMMAPAlgo.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMMAPALGO_H -#define XEMMAPALGO_H - -#include "XEMAlgo.h" - -/** - @brief Derived class of XEMAlgo for MAP Algorithm - @author F Langrognet & A Echenim -*/ - -class XEMMAPAlgo : public XEMAlgo{ - - public: - - /// Default constructor - XEMMAPAlgo(); - - // copy constructor - XEMMAPAlgo(const XEMMAPAlgo & mapAlgo); - /// Constructor - XEMMAPAlgo(XEMAlgoStopName algoStopName, double epsilon, int64_t nbIteration); - - /// Destructor - virtual ~XEMMAPAlgo(); - - - /// clone - XEMAlgo * clone(); - - /// Run method - virtual void run(XEMModel *& model); - - const XEMAlgoName getAlgoName() const; - - void setAlgoStopName(XEMAlgoStopName * algoStopName); - - void setEpsilon(double epsilon); - - const double getEpsilon() const; - - protected : - - /// Number of clusters - int64_t _nbCluster; - -}; - -inline const XEMAlgoName XEMMAPAlgo::getAlgoName() const{ - return MAP; -} - -inline const double XEMMAPAlgo::getEpsilon() const{ - throw internalMixmodError; -} - -inline void XEMMAPAlgo::setEpsilon(double eps){ - throw internalMixmodError; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMMAlgo.cpp b/lib/src/mixmod/MIXMOD/XEMMAlgo.cpp deleted file mode 100644 index e1016a4..0000000 --- a/lib/src/mixmod/MIXMOD/XEMMAlgo.cpp +++ /dev/null @@ -1,83 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMMAlgo.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMMAlgo.h" -//#include - - -//------------ -// Constructor -//------------ -XEMMAlgo::XEMMAlgo(){ - _algoStopName = NBITERATION; - _nbIteration =1 ; -} - - - - -/// Copy constructor -XEMMAlgo::XEMMAlgo(const XEMMAlgo & mAlgo):XEMAlgo(mAlgo){ -} - - -//------------ -// Constructor -//------------ -XEMMAlgo::XEMMAlgo(XEMAlgoStopName algoStopName, double epsilon, int64_t nbIteration) - :XEMAlgo(algoStopName, epsilon, nbIteration){ -} - - - -//----------- -// Destructor -//----------- -XEMMAlgo::~XEMMAlgo(){} - - - -// clone -//------ -XEMAlgo * XEMMAlgo::clone(){ - return (new XEMMAlgo(*this)); -} - - -void XEMMAlgo::setAlgoStopName(XEMAlgoStopName * algoStopName){ - throw internalMixmodError; -} - -//--- -//run -//--- -void XEMMAlgo::run(XEMModel *& model){ - _indexIteration = 0; - model = model; - model->setAlgoName(M); - model->Mstep(); // M Step - model->Estep(); // E step to update Tik - //cout << "\nMaximization algorithm \n"; -} - diff --git a/lib/src/mixmod/MIXMOD/XEMMAlgo.h b/lib/src/mixmod/MIXMOD/XEMMAlgo.h deleted file mode 100644 index 3f48fb8..0000000 --- a/lib/src/mixmod/MIXMOD/XEMMAlgo.h +++ /dev/null @@ -1,81 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMMAlgo.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMMALGO_H -#define XEMMALGO_H - -#include "XEMAlgo.h" - -/** - @brief Derived class of XEMAlgo for M Algorithm - @author F Langrognet & A Echenim -*/ - -class XEMMAlgo : public XEMAlgo{ - - public: - - /// Default constructor - XEMMAlgo(); - - /// copy constructor - XEMMAlgo(const XEMMAlgo & mAlgo); - - /// Constructor - XEMMAlgo(XEMAlgoStopName algoStopName, double epsilon, int64_t nbIteration); - - /// Destructor - virtual ~XEMMAlgo(); - - - /// clone - XEMAlgo * clone(); - - /// Run method - virtual void run(XEMModel *& model); - - const XEMAlgoName getAlgoName() const; - - - void setAlgoStopName(XEMAlgoStopName * algoStopName); - - void setEpsilon(double epsilon); - - const double getEpsilon() const; -}; - - -inline const XEMAlgoName XEMMAlgo::getAlgoName() const{ - return M; -} - -inline const double XEMMAlgo::getEpsilon() const{ - throw internalMixmodError; -} - -inline void XEMMAlgo::setEpsilon(double eps){ - throw internalMixmodError; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMMain.cpp b/lib/src/mixmod/MIXMOD/XEMMain.cpp deleted file mode 100644 index 909f7df..0000000 --- a/lib/src/mixmod/MIXMOD/XEMMain.cpp +++ /dev/null @@ -1,310 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMMain.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMError.h" -#include "XEMMain.h" -#include "XEMRandom.h" -#include "XEMOldInput.h" -#include "XEMBinaryData.h" -#include "XEMStrategy.h" - - -//------------ -// Constructor -//------------ -XEMMain::XEMMain(){ - _tabEstimation = NULL; - _tabSelection = NULL; -} - - - -//------------ -// Constructor -//------------ -XEMMain::XEMMain(XEMOldInput * input){ - if (! input->_finalized){ - throw inputNotFinalized; - } - _nbCriterion = input->_nbCriterionName; - _nbModelType = input->_nbModelType; - _nbNbCluster = input->_nbNbCluster; - _nbEstimation = _nbNbCluster * _nbModelType; - _nbSelection = _nbCriterion; - _tabEstimation = new XEMEstimation * [_nbEstimation]; - int64_t iNbCluster, iModelType, nbCluster; - XEMModelType * modelType; - - // data - XEMData * inputData = input->_data; - XEMData * workingData = inputData; - - //Strategy - XEMStrategy * inputStrategy = NULL; - XEMStrategy * workingStrategy = NULL; - - // knownPartition - XEMPartition * inputKnownPartition = NULL; - XEMPartition * workingKnownPartition = NULL; - - int64_t iEstimation = 0; // counting the estimations - // TODO nbStrategy - inputStrategy = input->_tabStrategy[0]; - workingStrategy = inputStrategy; - - - for (iNbCluster=0 ; iNbCluster<_nbNbCluster ; iNbCluster++){ - nbCluster = input->_tabNbCluster[iNbCluster]; - - //inputKnownPartition - if (input->_tabKnownPartition){ - inputKnownPartition = input->_tabKnownPartition[iNbCluster]; - }else{ - inputKnownPartition = NULL; - } - workingKnownPartition = inputKnownPartition ; - vector correspondenceOriginDataToReduceData; - - //Reduce Data - //------------ - if (input->_binaryDataType){ - XEMBinaryData * bData = (XEMBinaryData*)(inputData); - - // initPartition - XEMPartition * inputInitPartition = NULL; - XEMPartition * workingInitPartition = NULL; - const XEMStrategyInit * iit = inputStrategy->getStrategyInit(); - if (inputStrategy->getStrategyInit()->getStrategyInitName() == USER_PARTITION){ - inputInitPartition = inputStrategy->getStrategyInit()->getPartition(iNbCluster); - } - try{ - //TODO RD : data ne doit pas forcément etre recréé - workingData = bData->reduceData(correspondenceOriginDataToReduceData, inputKnownPartition, inputInitPartition, workingKnownPartition, workingInitPartition); - workingStrategy = new XEMStrategy(*inputStrategy); - if (workingInitPartition - ){ - workingStrategy->setInitPartition(workingInitPartition, iNbCluster); - } - /* TODO ?: - if inputKnownPartition : delete workingKnownPartition - if inputInitPartition : delete workingStrategy, workingInitPartition - - */ - } - catch(XEMErrorType errorType){ - workingData = NULL; - throw errorType; - } - } - // fin de ReduceData - - - // create tabEstmation[iEstimation] - //-------------------------------- - for (iModelType=0 ; iModelType<_nbModelType ; iModelType++){ - modelType = input->_tabModelType[iModelType]; - _tabEstimation[iEstimation] = new XEMEstimation(workingStrategy, modelType, nbCluster, workingData, workingKnownPartition, correspondenceOriginDataToReduceData); - iEstimation++; - } - } // end for iNbCluster - - - //create _tabSelection - _tabSelection = new XEMSelection * [_nbSelection]; - - int64_t iSelection ; - for (iSelection=0; iSelection<_nbSelection; iSelection++){ - XEMCriterionName criterionName = input->_tabCriterionName[iSelection]; - _tabSelection[iSelection] = new XEMSelection(criterionName, _tabEstimation, _nbEstimation, input); - } -} - - - -//----------- -// Destructor -//----------- -XEMMain::~XEMMain(){ - int64_t i; - - if (_tabEstimation){ - for (i=0; i<_nbEstimation ; i++){ - delete _tabEstimation[i]; - } - delete[] _tabEstimation; - _tabEstimation = NULL; - } - - if (_tabSelection){ - for (i=0; i<_nbSelection ; i++){ - delete _tabSelection[i]; - } - delete[] _tabSelection; - _tabSelection = NULL; - } - -} - - - -//---------------- -// getDCVCriterion -//---------------- -XEMDCVCriterion * XEMMain::getDCVCriterion(){ - XEMDCVCriterion * res = NULL; - int64_t iSelection=0; - while (iSelection<_nbSelection && res==NULL){ - if (_tabSelection[iSelection]->getCriterionName() == DCV){ - XEMCriterion * tmp = _tabSelection[iSelection]->getCriterion(); - res = dynamic_cast(tmp); - } - iSelection++; - } - return res; -} - - - - -//--- -//run -//--- -void XEMMain::run(XEMOutput * output, bool quiet){ - int64_t iEstimation, iSelection; - - // Estimation - //----------- - //_tabEstimation : run - int64_t todo = _nbEstimation-1; - int64_t j; - iEstimation = 0; - if(!quiet){ - cout << "...running" << endl; - } - - while (iEstimation<_nbEstimation){ - if(!quiet){ - - cout << " |"<< flush; - - j = iEstimation+1; - while(j){ - cout << "-" << flush; - j--; - } - j= todo; - while(j){ - cout << " " << flush; - j--; - } - - - cout << "| \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b" << flush; - printModelType(_tabEstimation[iEstimation]->getModelType()); - cout << " (k=" << _tabEstimation[iEstimation]->getNbCluster() << ")\r" << flush; - } - - - try{ - _tabEstimation[iEstimation]->run(); - } - - catch (XEMErrorType errorType){ - _tabEstimation[iEstimation]->setErrorType(errorType); - XEMError error(errorType); - if(!quiet) error.run(); - } - iEstimation++; - - if(!quiet){ - todo--; - } - - } - - - if(!quiet){ - j = _nbEstimation; - cout << " |"<< flush; - while(j){ - cout << "-" << flush; - j--; - } - cout << "| " << flush; - - cout << endl; - - //Selection - //--------- - cout << "... selecting"<< endl; - - } - int64_t bestIndexEstimation; - for (iSelection=0 ; iSelection<_nbSelection; iSelection++){ - - _tabSelection[iSelection]->run(quiet); - if(!quiet){ - cout << "| ---> "; - bestIndexEstimation = _tabSelection[iSelection]->getBestIndexEstimation(); - if (bestIndexEstimation != -1){ - printModelType(_tabEstimation[bestIndexEstimation]->getModelType()); - cout << " (k="<< _tabEstimation[bestIndexEstimation]->getNbCluster() << ") :: " << flush; - } - else{ - throw selectionErrorWithNoEstimation; - } - } - try{ - if(!quiet) - cout << _tabSelection[iSelection]->getBestCriterionValue() ; - } - catch(XEMErrorType errorType){ - if(!quiet) cout << "!" ; - } - - if(!quiet) cout << endl; - } - - - - bool allSelectionError = true; - for (iSelection=0 ; iSelection<_nbSelection; iSelection++){ - if (_tabSelection[iSelection]->getErrorType() != noSelectionError){ - allSelectionError = false; - } - } - if (allSelectionError){ - throw noSelectionError; - } - - - //output->update - if(output){ - output->update(_tabSelection, _nbSelection, _tabEstimation, _nbEstimation, _nbModelType); - } -} - - - - diff --git a/lib/src/mixmod/MIXMOD/XEMMain.h b/lib/src/mixmod/MIXMOD/XEMMain.h deleted file mode 100644 index d319dce..0000000 --- a/lib/src/mixmod/MIXMOD/XEMMain.h +++ /dev/null @@ -1,145 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMMain.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMMMAIN_H -#define XEMMMAIN_H - -/*#include */ - -#include "XEMOldInput.h" -#include "XEMOutput.h" -#include "XEMEstimation.h" -#include "XEMSelection.h" -#include "XEMError.h" -#include "XEMDCVCriterion.h" - -/** - @brief Main class for Mixmod - @author F Langrognet & A Echenim -*/ - -class XEMMain{ - - public: - - /// Default constructor - XEMMain(); - - /// Constructor - XEMMain(XEMOldInput * input); - - /// Destructor - virtual ~XEMMain(); - - - /** @brief Selector - @return The number of Selections - */ - int64_t getNbSelection(); - - /** @brief Selector - @return The table of Selections - */ - XEMSelection **& getTabSelection(); - - /** @brief Selector - @return The number of Estimations - */ - int64_t getNbEstimation(); - - /** @brief Selector - @return The table of estimations - */ - XEMEstimation **& getTabEstimation(); - - /** @brief Selector - @return The number of numbers of Clusters - */ - int64_t getNbNbCluster(); - - /** @brief Selector - @return The number of Models - */ - int64_t getNbModelType(); - - /// Run method - void run(XEMOutput * output = NULL, bool quiet=true); - - /// getDCVCriterion - XEMDCVCriterion * getDCVCriterion(); - - private : - - /// Number of criteria - int64_t _nbCriterion; - - /// Number of numbers of clusters - int64_t _nbNbCluster; - - /// Number of models - int64_t _nbModelType; - - /// Number of estimations - int64_t _nbEstimation; - - /// Table of estimations - XEMEstimation ** _tabEstimation; // aggregate - - /// Number of selections - int64_t _nbSelection; - - /// Table of selections - XEMSelection ** _tabSelection; // aggregate - - -}; - - - - -inline int64_t XEMMain::getNbSelection(){ - return _nbSelection; -} - -inline int64_t XEMMain::getNbEstimation(){ - return _nbEstimation; -} - -inline int64_t XEMMain::getNbNbCluster(){ - return _nbNbCluster; -} - -inline int64_t XEMMain::getNbModelType(){ - return _nbModelType; -} - -inline XEMSelection **& XEMMain::getTabSelection(){ - return _tabSelection; -} - -inline XEMEstimation **& XEMMain::getTabEstimation(){ - return _tabEstimation; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMMatrix.cpp b/lib/src/mixmod/MIXMOD/XEMMatrix.cpp deleted file mode 100644 index e1c00ce..0000000 --- a/lib/src/mixmod/MIXMOD/XEMMatrix.cpp +++ /dev/null @@ -1,81 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMMatrix.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMMatrix.h" - - -//------------ -// Constructor -//------------ -XEMMatrix::XEMMatrix(){ - _s_pbDimension = 0; -} - -XEMMatrix::XEMMatrix(int64_t pbDimension){ - _s_pbDimension = pbDimension; -} - -XEMMatrix::XEMMatrix(XEMMatrix * A){ - _s_pbDimension = A->getPbDimension(); -} - -//---------- -//Destructor -//---------- -XEMMatrix::~XEMMatrix(){ -} - -void XEMMatrix::edit(ostream& flux, string before){ - - int64_t i; - int64_t j; - double** store = storeToArray(); - for(i=0;i<_s_pbDimension;i++){ - flux<<'\t'<<'\t'<<'\t'<<'\t'; - for (j=0; j<_s_pbDimension; j++){ - flux <. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMMATRIX_H -#define XEMMATRIX_H - -#include "XEMUtil.h" -class XEMGeneralMatrix; -class XEMSymmetricMatrix; -class XEMDiagMatrix; -/** - @brief Base class for Matrix - @author F Langrognet & A Echenim -*/ - -class XEMMatrix{ - - public: - - /// Default constructor - XEMMatrix(); - - XEMMatrix(int64_t pbDimension); - - XEMMatrix(XEMMatrix * A); - - /// Desctructor - virtual ~XEMMatrix(); - - int64_t getPbDimension(); - - // TODO static - int64_t _s_pbDimension; - - - /// fill this with the inverse matrix of A - virtual void inverse(XEMMatrix * & A) = 0; - - virtual void compute_product_Lk_Wk(XEMMatrix* Wk, double L) = 0; - - /// compute (x - mean)' this (x - mean) - virtual double norme(double * xMoinsMean) = 0; - - /// compute determinant - virtual double determinant(XEMErrorType errorType) = 0; - - /// compute trace - virtual double computeTrace() = 0; - - /// this will be A / d - virtual void equalToMatrixDividedByDouble(XEMMatrix * A, double d) = 0; - - /// this will be A * d - virtual void equalToMatrixMultiplyByDouble(XEMMatrix*D, double d) = 0; - - - /// add : cik * xMoinsMean * xMoinsMean' to this - virtual void add(double * xMoinsMean, double cik) = 0; - - // add : diag( cik * xMoinsMean * xMoinsMean' ) to this - //virtual void addDiag(double * xMoinsMean, double cik) = 0; - - /// this = d * Identity - virtual void operator=(const double& d) = 0; - /// this = this / (d * Identity) - virtual void operator/=(const double& d) = 0; - /// this = this * (d * Identity) - virtual void operator*=(const double& d) = 0; - /// this = this + matrix - virtual void operator+=(XEMMatrix* M) = 0; - /// this = matrix - virtual void operator=(XEMMatrix* M)=0; - - - void edit(ostream& flux, string before); - /// read matrix from an input file - virtual void input(ifstream & fi) = 0; - - // pour ne plus faire de transtypages - - /// return store of a spherical matrix - virtual double putSphericalValueInStore(double & store) = 0; - /// add store of a spherical matrix - virtual double addSphericalValueInStore(double & store) = 0; - - virtual double getSphericalStore() = 0; - - /// Return store of a diagonal matrix - virtual double* putDiagonalValueInStore(double * store) = 0; - /// Add store of a diagonal matrix - virtual double* addDiagonalValueInStore(double * store) = 0; - - virtual double* getDiagonalStore() = 0; - - /// Return store of a diagonal matrix - virtual double* putSymmetricValueInStore(double * store) = 0; - /// Add store of a diagonal matrix in a diagonal one - virtual double* addSymmetricValueInStore(double * store) = 0; - - virtual double* getSymmetricStore() = 0; - - /// Return store of a diagonal matrix - virtual double* putGeneralValueInStore(double * store) = 0; - /// Add store of a diagonal matrix in a diagonal one - virtual double* addGeneralValueInStore(double * store) = 0; - - virtual double* getGeneralStore() = 0; - - virtual double** storeToArray() const = 0 ; - - /// gives : det(diag(this)) - virtual double detDiag(XEMErrorType errorType) = 0; - - ///compute singular vector decomposition - virtual void computeSVD(XEMDiagMatrix* & S, XEMGeneralMatrix* & O) = 0; - - virtual void compute_as__multi_O_S_O(double multi, XEMGeneralMatrix* & O, XEMDiagMatrix *& S) = 0; - virtual double trace_this_O_Sm1_O(XEMGeneralMatrix* & O, XEMDiagMatrix* & S) = 0; - virtual double compute_trace_W_C(XEMMatrix * C) = 0; - virtual void computeShape_as__diag_Ot_this_O(XEMDiagMatrix* & Shape, XEMGeneralMatrix* & Ori, double diviseur = 1.0) = 0; - // temporary table of Size pbDimension, comes from XEMGaussianData - // used in norme in the General case - double * _tmpTab ; - - ///set store - virtual void setSymmetricStore(double * store) = 0; - virtual void setGeneralStore(double * store) = 0; - virtual void setDiagonalStore(double * store) = 0; - virtual void setSphericalStore(double store) = 0; -}; - - -inline int64_t XEMMatrix::getPbDimension(){ - return _s_pbDimension; -} - -#endif - diff --git a/lib/src/mixmod/MIXMOD/XEMModel.cpp b/lib/src/mixmod/MIXMOD/XEMModel.cpp deleted file mode 100644 index c186b38..0000000 --- a/lib/src/mixmod/MIXMOD/XEMModel.cpp +++ /dev/null @@ -1,1705 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMModel.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMModel.h" -#include "XEMGaussianDiagParameter.h" -#include "XEMGaussianSphericalParameter.h" -#include "XEMGaussianGeneralParameter.h" -#include "XEMGaussianHDDAParameter.h" -#include "XEMBinaryEParameter.h" -#include "XEMBinaryEkParameter.h" -#include "XEMBinaryEjParameter.h" -#include "XEMBinaryEkjParameter.h" -#include "XEMBinaryEkjhParameter.h" -#include "XEMRandom.h" -#include "XEMGaussianData.h" -#include "XEMBinaryData.h" -#include - - - -//------------ -// Constructor -//------------ -XEMModel::XEMModel(){ - throw internalMixmodError; -} - - - -//------------ -// Constructor -//------------ -XEMModel::XEMModel(XEMModel * iModel){ - _deleteData = true; - _nbCluster = iModel->getNbCluster(); - _nbSample = iModel->getNbSample(); - _algoName = iModel->_algoName; - XEMModelType * iModelType = iModel->getParameter()->getModelType(); - XEMModelName iModelName = iModelType->_nameModel; - - if ( isBinary(iModelName )){ - XEMBinaryData * bD = (XEMBinaryData*)(iModel->getData()); - _data = new XEMBinaryData(*bD); - } - else{ - XEMGaussianData * gD = (XEMGaussianData*)(iModel->getData()); - _data = new XEMGaussianData(*gD); - } - - _tabFik = copyTab(iModel->getTabFik() , _nbSample, _nbCluster); - _tabSumF = copyTab(iModel->getTabSumF() , _nbSample); - _tabTik = copyTab(iModel->getTabTik() , _nbSample, _nbCluster); - _tabZikKnown = copyTab(iModel->getTabZikKnown(), _nbSample,_nbCluster); - _tabZiKnown = copyTab(iModel->getTabZiKnown(), _nbSample); - _tabCik = copyTab(iModel->getTabCik() , _nbSample, _nbCluster); - _tabNk = copyTab(iModel->getTabNk() , _nbCluster); - - _parameter = (iModel->getParameter())->clone(); - _parameter->setModel(this); - -} - - - -//------------ -// Constructor -//------------ -XEMModel::XEMModel(XEMModelType * modelType, int64_t nbCluster, XEMData *& data, XEMPartition *& knownPartition){ - int64_t k; - int64_t i; - _deleteData = false; - _nbCluster = nbCluster; - _data = data; - _nbSample = _data->_nbSample; - _algoName = UNKNOWN_ALGO_NAME; - - _tabFik = new double*[_nbSample]; - _tabCik = new double*[_nbSample]; - _tabSumF = new double[_nbSample]; - _tabTik = new double*[_nbSample]; - _tabZikKnown = new int64_t *[_nbSample]; - _tabZiKnown = new bool[_nbSample]; - _tabNk = new double[_nbCluster]; - - for (i=0; i<_nbSample; i++){ - _tabFik[i] = new double[_nbCluster]; - _tabTik[i] = new double[_nbCluster]; - _tabZikKnown[i] = new int64_t [_nbCluster]; - _tabCik[i] = new double[_nbCluster]; - for (k=0;k<_nbCluster;k++){ - _tabFik[i][k] = 0.0; - _tabTik[i][k] = 0.0; - _tabZikKnown[i][k] = 0; - _tabCik[i][k] = 0.0; - } - _tabZiKnown[i] = false; - _tabSumF[i] = 0.0; - } - - // _tabNk[k] = 0 even if knownPartition because this partition could be partial - for (k=0;k<_nbCluster;k++){ - _tabNk[k] = 0.0; - } - - FixKnownPartition(knownPartition); - XEMModelName modelName = modelType->_nameModel; - // create Param - if (isSpherical(modelName)){ - _parameter = new XEMGaussianSphericalParameter(this, modelType); - } - if (isDiagonal(modelName)){ - _parameter = new XEMGaussianDiagParameter(this, modelType); - } - if (isGeneral(modelName)){ - _parameter = new XEMGaussianGeneralParameter(this, modelType); - } - - - //HDDA models - if (isHD(modelName)){ - _parameter = new XEMGaussianHDDAParameter(this, modelType); - } - - - switch(modelName){ - // Binary models // - case (Binary_p_E): - _parameter = new XEMBinaryEParameter(this, modelType, ((XEMBinaryData*)data)->getTabNbModality()); - break; - case (Binary_p_Ek): - _parameter = new XEMBinaryEkParameter(this, modelType, ((XEMBinaryData*)data)->getTabNbModality()); - break; - case (Binary_p_Ej): - _parameter = new XEMBinaryEjParameter(this, modelType, ((XEMBinaryData*)data)->getTabNbModality()); - break; - case (Binary_p_Ekj): - _parameter = new XEMBinaryEkjParameter(this, modelType, ((XEMBinaryData*)data)->getTabNbModality()); - break; - case (Binary_p_Ekjh): - _parameter = new XEMBinaryEkjhParameter(this, modelType, ((XEMBinaryData*)data)->getTabNbModality()); - break; - case (Binary_pk_E): - _parameter = new XEMBinaryEParameter(this, modelType, ((XEMBinaryData*)data)->getTabNbModality()); - break; - case (Binary_pk_Ek): - _parameter = new XEMBinaryEkParameter(this, modelType, ((XEMBinaryData*)data)->getTabNbModality()); - break; - case (Binary_pk_Ej): - _parameter = new XEMBinaryEjParameter(this, modelType, ((XEMBinaryData*)data)->getTabNbModality()); - break; - case (Binary_pk_Ekj): - _parameter = new XEMBinaryEkjParameter(this, modelType, ((XEMBinaryData*)data)->getTabNbModality()); - break; - case (Binary_pk_Ekjh): - _parameter = new XEMBinaryEkjhParameter(this, modelType, ((XEMBinaryData*)data)->getTabNbModality()); - break; - } -} - - -//----------- -// Destructor -//----------- -XEMModel::~XEMModel(){ - int64_t i; - - if (_tabFik){ - for (i=0; i<_nbSample; i++){ - delete[] _tabFik[i]; - _tabFik[i] = NULL; - } - delete[] _tabFik; - _tabFik = NULL; - } - - - if (_tabCik){ - for (i=0; i<_nbSample; i++){ - delete[] _tabCik[i]; - _tabCik[i] = NULL; - } - delete[] _tabCik; - _tabCik = NULL; - } - - - if (_tabTik){ - for (i=0; i<_nbSample; i++){ - delete[] _tabTik[i]; - _tabTik[i] = NULL; - } - delete[] _tabTik; - _tabTik = NULL; - } - - if (_tabZikKnown){ - for (i=0; i<_nbSample; i++){ - delete[] _tabZikKnown[i]; - _tabZikKnown[i] = NULL; - } - delete[] _tabZikKnown; - _tabZikKnown = NULL; - } - - if (_tabZiKnown){ - delete[] _tabZiKnown; - _tabZiKnown = NULL; - } - - if (_tabNk){ - delete[] _tabNk; - _tabNk = NULL; - } - - if (_tabSumF){ - delete[] _tabSumF; - _tabSumF = NULL; - } - - - if (_parameter){ - delete _parameter; - _parameter = NULL; - } - - if (_deleteData){ - delete _data; - } - -} - - - -//------------ -// updateForCV -//------------ -void XEMModel::updateForCV(XEMModel * originalModel, XEMCVBlock & CVBlock){ - int64_t k,i; - - // _data - //------ - // _data=originalData but weight will be different - // _data has already been updated (copy constructor) - _data->_weightTotal = originalModel->_data->_weightTotal - CVBlock._weightTotal; - recopyTab(originalModel->_data->_weight, _data->_weight, _nbSample); - for (int64_t ii=0; ii_weight[i] -= CVBlock._tabWeightedIndividual[ii].weight; - } - - /* new version : Dec 2006*/ - /* recopy fik, tik and zik*/ - recopyTab(originalModel->_tabFik, _tabFik, _nbSample, _nbCluster); - recopyTab(originalModel->_tabSumF, _tabSumF, _nbSample); - recopyTab(originalModel->_tabTik, _tabTik, _nbSample, _nbCluster); - recopyTab(originalModel->_tabCik, _tabCik,_nbSample, _nbCluster); - - - // already done : (with the copy constructor - // recopyTab(originalModel->_tabZikKnown, _tabZik, _nbSample); - - //-------------- - // update _tabNk - //-------------- - recopyTab(originalModel->_tabNk, _tabNk, _nbCluster); - for (int64_t ii=0; iiupdateForCV(originalModel, CVBlock); -} - - - - - - -//-------------- -// getKnownLabel -//-------------- -// return a value in : 0, ..., K-1 -// i = 0 ... nbSample-1 -int64_t XEMModel::getKnownLabel(int64_t i){ - int64_t res=-1; - int64_t k; - if (_tabZiKnown[i]){ - for (k=0;k<_nbCluster;k++){ - if (_tabZikKnown[i][k]==1){ - res = k; - } - } - } - else{ - throw internalMixmodError; - } - return res; -} - - - -//------------------------------------------- -// getLabelAndPartitionByMAPOrKnownPartition -// label[i] = 1 ... nbSample -//------------------------------------------ -void XEMModel::getLabelAndPartitionByMAPOrKnownPartition(int64_t * label, int64_t ** partition){ - //if (!_isCikEqualToMapOrKnownPartition){ - if (_algoName == UNKNOWN_ALGO_NAME) - throw; - - if (_algoName==MAP || _algoName==CEM || _algoName==M ){ - // _tabCik contains the result - int64_t i; - int64_t k; - for (i=0; i<_nbSample; i++){ - for (k=0; k<_nbCluster; k++){ - partition[i][k] = (int64_t )_tabCik[i][k]; // cast double to int64_t (_tabCik[i][k] = 0.0 or 1.0) - if (partition[i][k] == 1){ - label[i] = k+1; - } - } - } - } - else{ - int64_t k, kMax; - int64_t i; - double tikMax = 0; - for (i=0; i<_nbSample; i++){ - if (_tabZiKnown[i]){ - //----------------- - for (k=0; k<_nbCluster; k++){ - partition[i][k] = _tabZikKnown[i][k]; - if (_tabZikKnown[i][k] == 1){ - label[i] = k+1; - } - } - } - else{ - // !ziKnown - //--------- - kMax = 0; - tikMax = _tabTik[i][0]; - for (k=1; k<_nbCluster; k++){ - if (_tabTik[i][k] > tikMax){ - tikMax = _tabTik[i][k]; - kMax = k; - } - } - for (k=0; k<_nbCluster; k++){ - partition[i][k] = 0; - partition[i][kMax] = 1; - label[i] = kMax+1; - } - } - } - } -} - - -//------------------------------ -// getLabelByMAPOrKnownPartition -//------------------------------ -// return a value in : 0, ..., K-1 -// i = 0 ... nbSample-1 -int64_t XEMModel::getLabelByMAPOrKnownPartition(int64_t i){ - - int64_t k, kMax; - double tikMax = 0; - int64_t res = -1; - - if (_algoName == UNKNOWN_ALGO_NAME) - throw; - // - if (_algoName==CEM || _algoName==MAP || _algoName==M){ - //_tabCik[i] gives to result - for (k=0; k<_nbCluster; k++){ - if (_tabCik[i][k]==1){ - res = k; - } - } - } - - else{ - // must be computed - // This method is called by getCompletedLogLikelihood - // In this case (!_isCikEqualToMapOrKnownPartition), it's called by XEMICLCriterion or XEMLikelihoodOutput, so an Estep have been done before to upadte fik and tik used in this section - if (_tabZiKnown[i]){ - for (k=0;k<_nbCluster;k++){ - if (_tabZikKnown[i][k]==1){ - res = k; - } - } - } - else { - tikMax = _tabTik[i][0]; - kMax = 0; - for (k=0;k<_nbCluster;k++){ - if (_tabTik[i][k] > tikMax){ - tikMax = _tabTik[i][k]; - kMax = k; - } - } - res = kMax; - } - } - - if (res == -1){ - // label couldn't be found - cout<<"internalMixmodError ds XEMModel::getLabelByMAPOrKnownPartition, i="<getLogLikelihoodOne(); -} - - - - - -//------------------- -// get log-likelihood -//------------------- -double XEMModel::getLogLikelihood(bool fikMustBeComputed){ - // Compute the log-likelihood (observed) // - - if (fikMustBeComputed){ - computeFik(); - } - - int64_t i; - double logLikelihood = 0.0 ; - double ** p_tabFik; - double * p_tabFik_i; - double * weight = _data->_weight; - p_tabFik = _tabFik; - for (i=0; i<_nbSample; i++){ - p_tabFik_i = *p_tabFik; - if (_tabZiKnown[i]){ - int64_t ki = getKnownLabel(i);// la classe de l'individu i - logLikelihood += log(p_tabFik_i[ki]) * weight[i]; - } - else{ - if (_tabSumF[i] > 0) - logLikelihood += log(_tabSumF[i]) * weight[i]; - } - //cout<<"compute LL, with ind "<edit(); - cout<<"LL : "<< bestLogLikelihood< bestLogLikelihood){ - bestLogLikelihood = logLikelihood; - bestParameter->recopy(_parameter); - } - /*cout<edit(); - cout<<"LL : "<< logLikelihood<setModel(this); - /*cout<edit(); - cout<<"LL : "<< bestLogLikelihood<recopy(_parameter); - /*cout<<"initRandom"<edit(); - cout<<"LL : "<< bestLogLikelihood< bestLogLikelihood){ - bestLogLikelihood = logLikelihood; - bestParameter->recopy(_parameter); - } - /*cout<edit(); - cout<<"LL : "<< logLikelihood<setModel(this); - /*cout<edit(); - cout<<"LL : "<< bestLogLikelihood<setModel(this); - // cout<<"fin de init SMALL_EM, nb d'essais effectues="<setModel(this); - // cout<<"fin de init SMALL_EM, nb d'essais effectues="< bestCLogLikelihood)){ - bestCLogLikelihood = cLogLikelihood; - bestParameter->recopy(_parameter); - } - //cout<<"nbIter : "<setModel(this); - throw CEM_INIT_error; - } - - //cout<<"fin de init CEM, nb d'essais effectues="<setModel(this); - -} - -void XEMModel::initCEM_INIT(XEMStrategyInit * strategyInit){ - //cout<<"init CEM, nbTryInInit="<getNbTry()<clone(); - int64_t nbRunOfCEMOk = 0; - bestCLogLikelihood = 0.0; - - for (i=0; igetNbTry(); i++){ - nbRunOfCEMOk++; - try{ - _parameter->reset(); // reset to default values - initRANDOM(1); - _algoName = CEM; - int64_t nbIter = 0; - bool fin = false; - while (!fin && nbIter<=maxNbIterationInCEM_INIT){ - Estep(); - Cstep(); - Mstep(); - nbIter++; - if (nbIter == 1){ - oldLogLikelihood = getCompletedLogLikelihood(); - } - else{ - cLogLikelihood = getCompletedLogLikelihood(); - if (cLogLikelihood == oldLogLikelihood){ - fin = true; - } - else{ - oldLogLikelihood = cLogLikelihood; - } - } - } - //cout<<"dans init CEM, nb d'iterations effectuées : "< bestCLogLikelihood)){ - bestCLogLikelihood = cLogLikelihood; - bestParameter->recopy(_parameter); - } - //cout<<"nbIter : "<setModel(this); - throw CEM_INIT_error; - } - - //cout<<"fin de init CEM, nb d'essais effectues="<setModel(this); - -} - - - - - -/*--------------------------------------------------------- - Initialization by SEM - --------------------- - - updated in this method : - - _parameter - - _tabFik, _tabSumF, _tabCik, _tabTik, _tabNk (because an Estep and a SStep are called to choose the bestParameter) - Note : _tabFik, _tabSumF, _tabCik, _tabTik, _tabNk wil be 're'computed in the following EStep - So, only _parameter have to be updated in this method - - -------------------------------------------------------*/ -void XEMModel::initSEM_MAX(XEMClusteringStrategyInit * clusteringStrategyInit){ - //cout<<"init SEM_MAX, nbTryInInit="<getNbIteration()<clone(); - int64_t nbRunOfSEMMAXOk = 0; - bestLogLikelihood = 0.0; - int64_t bestIndex=0; - - for (j=0; jgetNbIteration(); j++){ - nbRunOfSEMMAXOk++; - try{ - _parameter->reset(); - initRANDOM(1); - Estep(); - Sstep(); - Mstep(); - // Compute log-likelihood - logLikelihood = getLogLikelihood(true); // true : to compute fik - if ((nbRunOfSEMMAXOk==1) || (logLikelihood > bestLogLikelihood)){ - bestLogLikelihood = logLikelihood; - bestParameter->recopy(_parameter); - bestIndex = j; - } - } - catch (XEMErrorType errorType){ - nbRunOfSEMMAXOk--; - } - } - - if (nbRunOfSEMMAXOk==0){ - throw SEM_MAX_error; - } - - //cout<<"fin de init SEM_MAX, nb d'iterations effectuees="<setModel(this); -} - -void XEMModel::initSEM_MAX(XEMStrategyInit * strategyInit){ - //cout<<"init SEM_MAX, nbTryInInit="<getNbIteration()<clone(); - int64_t nbRunOfSEMMAXOk = 0; - bestLogLikelihood = 0.0; - int64_t bestIndex=0; - - for (j=0; jgetNbIteration(); j++){ - nbRunOfSEMMAXOk++; - try{ - _parameter->reset(); - initRANDOM(1); - Estep(); - Sstep(); - Mstep(); - // Compute log-likelihood - logLikelihood = getLogLikelihood(true); // true : to compute fik - - if ((nbRunOfSEMMAXOk==1) || (logLikelihood > bestLogLikelihood)){ - bestLogLikelihood = logLikelihood; - bestParameter->recopy(_parameter); - bestIndex = j; - } - } - catch (XEMErrorType errorType){ - nbRunOfSEMMAXOk--; - } - } - - if (nbRunOfSEMMAXOk==0){ - throw SEM_MAX_error; - } - - //cout<<"fin de init SEM_MAX, nb d'iterations effectuees="<setModel(this); -} - - - - - - - - - -//----------------------------------------------------------------------------------------------- -//----------------------------------------------------------------------------------------------- -// Algorithms -//----------------------------------------------------------------------------------------------- -//----------------------------------------------------------------------------------------------- - - - - -/*-------------------------------------------------------------------------------------------- - MAP step : Maximum a Posteriori procedure - --------- - MAP procedure consists in assigning a point to the group maximing this conditional probabiliy - - Note : MAP follows an USER initialisation - ---- - - already updated : - - _parameter (by USER initialisation) - - updated in this method : - - _tabFik, _tabCik, _tabTik, _tabNk (in Estep called in this method) - - _tabCik, _tabNk (called by Cstep in this method) - ----------------------------------------------------------------------------------------------*/ -void XEMModel::MAPstep(){ - Estep(); // to compute _tabFik, _tabTik, _tabCik, _tabNk - Cstep(); // to compute _tabCik (by MAP procedure) and _tabNk -} - - - - - -/*-------------------------------------------------------------------------------------------- - E step : Expectation - ------ - - Note : Estep follows a Mstep or an initialsation (so _parameter is updated) - ---- - - already updated : - - _parameter - - updated in this method : - - _tabFik, _tabCik, _tabTik, _tabNk - - --------------------------------------------------------------------------------------------*/ -void XEMModel::Estep(){ - - // 1. compute fik - //--------------- - computeFik(); - - //2. compute tik (conditional probabilities (posteriori probabilities)) - //--------------- - int64_t k; - int64_t i; - for (i=0; i<_nbSample; i++){ - if (_tabSumF[i]==0.0){ - _parameter->computeTikUnderflow(i, _tabTik); - } - else{ - for (k=0; k<_nbCluster; k++){ - _tabTik[i][k] = _tabFik[i][k] / _tabSumF[i] ; - } - } - - // 3. compute cik - //--------------- - if (!_tabZiKnown[i]){ - for (k=0;k<_nbCluster;k++){ - _tabCik[i][k] = _tabTik[i][k]; - } - } - } - //4. compute nk - //------------ - computeNk(); -} - - - - - -/*-------------------------------------------------------------------------------------------- - M step - ------ - - Note : Mstep follows an Estep, Cstep, Step, or USER_PARTITION initialisation - ---- - - already updated : - - _tabFik, _tabCik, _tabTik, _tabNk - - updated in this method : - - _parameter - --------------------------------------------------------------------------------------------*/ -void XEMModel::Mstep(){ - _parameter->MStep(); -} - - - - - -/*-------------------------------------------------------------------------------------------- - S step - ------ - // S Step : Stochastic Classification - - Note : Sstep follows an Estep - ---- - - already updated : - - _tabFik, _tabCik, _tabTik, _tabNk, _parameter - - updated in this method : - - _tabCik, _tabNk - --------------------------------------------------------------------------------------------*/ -void XEMModel::Sstep(){ - int64_t i; - int64_t k; - double ** cumTabT = new double*[_nbSample]; - - for (i=0; i<_nbSample; i++){ - cumTabT[i] = new double[_nbCluster]; - cumTabT[i][0] = _tabTik[i][0]; - } - for (k=1; k<_nbCluster; k++){ - for (i=0; i<_nbSample; i++){ - cumTabT[i][k] = _tabTik[i][k] + cumTabT[i][k-1]; - } - } - - double * tabRnd = new double[_nbSample]; - for (i=0; i<_nbSample; i++){ - tabRnd[i] = rnd(); - } - - for (i=0; i<_nbSample; i++){ - if (!_tabZiKnown[i]){ - for (k=0; k<_nbCluster; k++){ - _tabCik[i][k] = 0; - } - k=0; - while ((k<_nbCluster) && (tabRnd[i] > cumTabT[i][k])){ - k++; - } - if (tabRnd[i] <= cumTabT[i][k]){ - _tabCik[i][k] = 1; - } - else{ - throw internalMixmodError; - } - } - } - - for (i=0; i<_nbSample; i++){ - delete[] cumTabT[i]; - } - delete[] cumTabT; - delete[] tabRnd; - - //update _tabNk - computeNk(); -} - - - - - -/*-------------------------------------------------------------------------------------------- - C step - ------ - Classification Step - - Note : Cstep follows an Estep - ---- - - already updated : - - _tabFik, _tabCik, _tabTik, _tabNk, _parameter - - updated in this method : - - _tabCik, _tabNk - --------------------------------------------------------------------------------------------*/ -void XEMModel::Cstep(){ - int64_t k, kMax; - int64_t i; - double tikMax = 0; - for (i=0;i<_nbSample;i++){ - if (!_tabZiKnown[i]){ - kMax = 0; - tikMax = _tabTik[i][0]; - for (k=1; k<_nbCluster; k++){ - if (_tabTik[i][k] > tikMax){ - tikMax = _tabTik[i][k]; - kMax = k; - } - } - for (k=0;k<_nbCluster;k++){ - _tabCik[i][k] = 0; - } - _tabCik[i][kMax] = 1; - } - } - - - //update _tabNk - if(_algoName == UNKNOWN_ALGO_NAME) - throw; - - if(_algoName != MAP){ - computeNk(); - } -} - - - - - - -//----------------------- -// debug information -//----------------------- -void XEMModel::editDebugInformation(){ -#if DEBUG > 0 - _parameter->edit(); -#if DEBUG > 1 - editFik(); - editTik(); -#endif -#endif -} - - - -//--------- -// edit Fik -//--------- -void XEMModel::editFik(){ - int64_t i,k; - for (i=0; i<_nbSample; i++){ - for (k=0; k<_nbCluster; k++){ - cout<<"\tfik["<. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMMODEL_H -#define XEMMODEL_H - -#include "XEMData.h" -#include "XEMPartition.h" -#include "XEMParameter.h" -#include "XEMStrategyInit.h" -#include "XEMClusteringStrategyInit.h" -#include "XEMOldInput.h" - - -/** - @brief Base class for Model(s) - @author F Langrognet & A Echenim -*/ - -class XEMModel{ - - public: - - /// Default constructor - XEMModel(); - - /// Constructor - XEMModel(XEMModel * iModel); - - - /// Constructor - XEMModel(XEMModelType * modelType, int64_t nbCluster, XEMData *& data, XEMPartition *& knownPartition); - - /// Destructor - virtual ~XEMModel(); - - - void updateForCV(XEMModel * originalModel, XEMCVBlock & CVBlock) ; - //------- - // select - //------- - - /** @brief Selector - @return The parameters - */ - XEMParameter * getParameter(); - - /** @brief Selector - @return The current number for cluster - */ - int64_t getNbCluster(); - - /** @brief Selector - @return The current data - */ - XEMData * getData(); - - /** @brief Selector - @return The known partition - */ - - /** @brief Selector - @return The number of samples - */ - int64_t getNbSample(); - - /** @brief Selector - @return Table of Fik of each cluster : probabilitites: _fik = pk * f(xi,muk,Sk) - */ - double ** getTabFik(); - - /// return _tabSumF - double * getTabSumF(); - - /** @brief Selector - @return Table of Tik of each cluster : - conditionnal probabilities that xi arises from the k-th mixture component, 0 <= tik[i]k0] <= 1 - */ - double ** getTabTik(); - - /** @brief Selector - @return Table of Zik zik[i][k0] = 1 if xi arises from the k0-th mixture component, 0 else - */ - int64_t ** getTabZikKnown(); - - - double ** getTabCik(); - - /// getTabZikKnown - bool * getTabZiKnown(); - - /** @brief Selector - @return Table of number of elements in each cluster - */ - double * getTabNk(); - - bool getDeleteData(); - - //--------- - // compute - //-------- - - /// comute _fik - void computeFik(); - - /// Compute the number of points in each class - void computeNk(); - - /** @brief Compute the log-likelihood - @return The log-likelihood - */ - double getLogLikelihood(bool fikMustBeComputed); - - - /** @brief Compute the log-likelihood with one cluster - @return The log-likelihood - */ - double getLogLikelihoodOne(); - - /** @brief Compute the entropy - @return The entropy - */ - - double getEntropy(); - - /** @brief Compute the completed log-likelihood - @return The completed log-likelihood - */ - double getCompletedLogLikelihood(); - - /** get completed LL (if CEM) or LL (elseif)*/ - double getCompletedLogLikelihoodOrLogLikelihood() ; - - /// return the number of free parameters - int64_t getFreeParameter(); - - - /** @brief Selector - @return Log of the weight total - */ - double getLogN(); - - /// getLabel and partition - /// label=1...nbSample - void getLabelAndPartitionByMAPOrKnownPartition(int64_t * label, int64_t ** partition); - - /// get label of the ith individual (i=0 .... nbSample-1) by MAP (or known label) - /// return value in [0 nbCluster-1] - int64_t getLabelByMAPOrKnownPartition(int64_t i); - - - /// get knownLabel of the ith individual (i=0 .... nbSample-1) - /// return value in [0 nbCluster-1] - /// throw an error if the label is unkonwn - int64_t getKnownLabel(int64_t i); - - /// getPostProba - double ** getPostProba(); - - - - //-------- - // compute - //-------- - - - - /** @brief Compute the label of the i0-th point of the sample - @return The label of i0 (i0=0 -> _nBSample -1) - */ - int64_t computeLabel(int64_t i0); - - - /** @brief Compute the label of new point x - @return The label of x - */ - int64_t computeLabel(XEMSample * x); - - - - //------ - // algo - //------ - - /// Maximum a posteriori step method - void MAPstep(); - - /// Expectation step method - void Estep(); - - /// Maximization step method - void Mstep(); - - /// Stochastique classification step method - void Sstep(); - - /// Classification step method - void Cstep(); - - - - - //----- - // init - //----- - - /// Random center initialization of the parameters of the model - void initRANDOM(int64_t nbTry); - - - /// random step for init RANDOM or USER_PARTITION - void randomForInitRANDOMorUSER_PARTITION(bool * tabIndividualCanBeUsedForInitRandom, bool * tabClusterToInitialize); - - /// User initialization of the parameters of the model - void initUSER(XEMParameter * initParameter); - - /// User partition initialisation of the parameters of the model - void initUSER_PARTITION(XEMPartition * initPartition, int64_t nbTryInInit=defaultNbTryInInit); - - //TODO a enlever - /// Initialization by EM of the parameters of the model - void initSMALL_EM(XEMStrategyInit * strategyInit); - /// Initialization by EM of the parameters of the model - void initSMALL_EM(XEMClusteringStrategyInit * clustreringStrategyInit); - - //TODO a enlever - /// Initialization by CEM of the parameters of the model - void initCEM_INIT(XEMStrategyInit * strategyInit); - /// Initialization by CEM of the parameters of the model - void initCEM_INIT(XEMClusteringStrategyInit * clustreringStrategyInit); - - //TODO a enlever - /// Initialization by SEM of the parameters of the model - void initSEM_MAX(XEMStrategyInit * strategyInit); - /// Initialization by SEM of the parameters of the model - void initSEM_MAX(XEMClusteringStrategyInit * clustreringStrategyInit); - - void setAlgoName(XEMAlgoName algoName); - - - /// Fix label Known - void FixKnownPartition(XEMPartition *& y); - - - // edit debug information - void editDebugInformation(); - void editFik(); - void editCik(); - void editTik(); - void editNk(); - - protected : - - /// Number of clusters - int64_t _nbCluster; - - /// Number of samples - int64_t _nbSample; - - /// Current data - XEMData * _data; - bool _deleteData; - - /// parameter of model - XEMParameter * _parameter; - - /// Type of the model - - /// Probabilitites: _fik = pk * f(xi,muk,Sk) - /// dim : _nbSample * _nbCluster - double ** _tabFik; - - /// table of sum of _tabFik for all k (dim : _nbSample) - double * _tabSumF; - - /// Conditionnal probabilities that x(i) arises from the k-th mixture component, 0 <= tik[i][k0] <= 1 - /// dim : _nbSample * _nbCluster - double ** _tabTik; - - /// zikKnown : _tabZikKonwn[i][k0] = 1 if xi arises from the k0-th mixture component, 0 else* - /// dim : _nbSample * _nbCluster - int64_t ** _tabZikKnown; - - /** classification array for individual i and class k - // if zikKnown - // cik = zikKnown - // else : - // cik = tik if EM - // cik = zik by MAP rule if CEM or MAP - // cik = 'random' if SEM - */ - double ** _tabCik; - - - /// is the label zik known (fixed) - bool * _tabZiKnown; - - - /// Number of points in each class - double * _tabNk; - - XEMAlgoName _algoName; - - - private : - //------- - //TODO a enlever - void oneRunOfSmallEM(XEMStrategyInit * strategyInit, double & logLikelihood); - void oneRunOfSmallEM(XEMClusteringStrategyInit * clusteringStrategyInit, double & logLikelihood); - -}; - - -//-------------- -//inline methods -//-------------- -inline bool * XEMModel::getTabZiKnown(){ - return _tabZiKnown; -} - -inline int64_t ** XEMModel::getTabZikKnown(){ - return _tabZikKnown; -} - - -inline double ** XEMModel::getTabCik(){ - return _tabCik; -} - -inline double ** XEMModel::getTabTik(){ - return _tabTik; -} - -inline double ** XEMModel::getTabFik(){ - return _tabFik; -} - -inline double * XEMModel::getTabSumF(){ - return _tabSumF; -} - -inline double * XEMModel::getTabNk(){ - return _tabNk; -} - -inline int64_t XEMModel::getNbCluster(){ - return _nbCluster; -} - -inline XEMData * XEMModel::getData(){ - return _data; -} - - -inline XEMParameter * XEMModel::getParameter(){ - return _parameter; -} - - -inline int64_t XEMModel::getNbSample(){ - - return _nbSample; -} - - -inline double XEMModel::getLogN(){ - return log(_data->_weightTotal); -} - -inline double ** XEMModel::getPostProba(){ - return _tabTik; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMModelOutput.cpp b/lib/src/mixmod/MIXMOD/XEMModelOutput.cpp deleted file mode 100644 index bcbe8e8..0000000 --- a/lib/src/mixmod/MIXMOD/XEMModelOutput.cpp +++ /dev/null @@ -1,128 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMModelOutput.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMModelOutput.h" - - - -//-------------------- -// Default Constructor -//-------------------- -XEMModelOutput::XEMModelOutput(){ -} - - -//----------------- -// Copy constructor -//----------------- -XEMModelOutput::XEMModelOutput(const XEMModelOutput & modelOutput){ - throw internalMixmodError; -} - - - -//------------------------------ -// Initialization constructor 1 -//------------------------------ -XEMModelOutput::XEMModelOutput(XEMEstimation * estimation){ - if (!estimation){ - throw nullPointerError; - } - _estimation = estimation; - - _modelType = *(estimation->getModelType()); - _nbCluster = estimation->getNbCluster(); - _criterionOutput = estimation->getCriterionOutput(); - - - _strategyRunError = estimation->getErrorType(); - if (_strategyRunError == noError){ - _probaDescription = new XEMProbaDescription(estimation); - _labelDescription = new XEMLabelDescription(estimation); - _parameterDescription = new XEMParameterDescription(estimation); - } - else{ - _probaDescription = NULL; - _labelDescription = NULL; - _parameterDescription = NULL; - } - - _likelihood = estimation->getModel()->getLogLikelihood(false); -} - - - - -//------------------------------ -// Initialization constructor 2 -//------------------------------ -XEMModelOutput::XEMModelOutput(XEMModelType & modelType, int64_t nbCluster, vector & criterionOutput, double likelihood, XEMParameterDescription & parameterDescription, XEMLabelDescription & labelDescription, XEMProbaDescription & probaDescription){ - _estimation = NULL; - //TODO - - _modelType = modelType; - _nbCluster = nbCluster; - _criterionOutput = criterionOutput; - _strategyRunError = noError; // TODO ?? - if (_strategyRunError == noError){ - _probaDescription = &probaDescription; - _labelDescription = &labelDescription; - _parameterDescription = ¶meterDescription; - } - else{ - _probaDescription = NULL; - _labelDescription = NULL; - _parameterDescription = NULL; - } - - _likelihood = likelihood; -} - -//------------------------------ -// Initialization constructor 3 -//------------------------------ -XEMModelOutput::XEMModelOutput(XEMModelType & modelType, int64_t nbCluster, XEMErrorType error){ - _estimation = NULL; - - _modelType = modelType; - _nbCluster = nbCluster; - _strategyRunError = error; - _probaDescription = NULL; - _labelDescription = NULL; - _parameterDescription = NULL; - _criterionOutput.resize(0); - _likelihood = 0; -} - -//----------- -// Destructor -//----------- -XEMModelOutput::~XEMModelOutput(){ - -} - - - - - diff --git a/lib/src/mixmod/MIXMOD/XEMModelOutput.h b/lib/src/mixmod/MIXMOD/XEMModelOutput.h deleted file mode 100644 index b6100fe..0000000 --- a/lib/src/mixmod/MIXMOD/XEMModelOutput.h +++ /dev/null @@ -1,185 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMModelOutput.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMMODELOUTPUT_H -#define XEMMODELOUTPUT_H - - -#include "XEMUtil.h" -#include "XEMEstimation.h" -#include "XEMModel.h" -#include "XEMParameterDescription.h" -#include "XEMProbaDescription.h" -#include "XEMLabelDescription.h" - - -using namespace std; - -/* Note : - A XEMModelOutput object could be created : - - with an XEMEstimation (after calculation) - - or without XEMEstimation. In this case, XEMModelOutput is created from XML mixmod file which contains input and output information. -*/ - - -class XEMModelOutput{ - - public: - - /// Default Constructor - XEMModelOutput(); - - /// Copy Constructor - XEMModelOutput(const XEMModelOutput & modelOutput); - - /// Initialization Constructor 1 - XEMModelOutput(XEMEstimation * estimation); - - /// Initialization Constructor 2 - XEMModelOutput(XEMModelType & modelType, int64_t nbCluster, vector & criterionOutput, double likelihood, XEMParameterDescription & parameterDescription, XEMLabelDescription & labelDescription, XEMProbaDescription & probaDescription); - - ///Initialization Constructor 3 - XEMModelOutput(XEMModelType & modelType, int64_t nbCluster, XEMErrorType error); - - /// Destructor - virtual ~XEMModelOutput(); - - - // --- get --- /// - //-------------// - XEMModelType getModelType() const; - - int64_t getNbCluster() const; - - int64_t getCriterionSize() const; - - vector getCriterionOutput(); - - XEMParameterDescription * getParameterDescription() ; - - XEMLabelDescription * getLabelDescription() ; - - XEMProbaDescription * getProbaDescription() ; - - XEMErrorType getStrategyRunError() const; - - XEMEstimation * getEstimation(); - - double getLikelihood(); - - // TODO a enlever - friend class XEMOutput; - - friend class XEMClusteringOutput; - - - - - //------- - protected : - - XEMEstimation * _estimation; - - - XEMModelType _modelType; - - int64_t _nbCluster; - - vector _criterionOutput; - - XEMParameterDescription * _parameterDescription; - - XEMLabelDescription * _labelDescription; - - XEMProbaDescription * _probaDescription; - - double _likelihood; - - XEMErrorType _strategyRunError; -}; - - -inline XEMModelType XEMModelOutput::getModelType() const{ - return _modelType; -} - -inline int64_t XEMModelOutput::getNbCluster() const{ - return _nbCluster; -} - - - -inline int64_t XEMModelOutput::getCriterionSize() const{ - return _criterionOutput.size(); -} - - -inline vector XEMModelOutput::getCriterionOutput(){ - return _criterionOutput; -} - - -inline XEMParameterDescription * XEMModelOutput::getParameterDescription() { - return _parameterDescription; -} - -inline XEMLabelDescription * XEMModelOutput::getLabelDescription() { - return _labelDescription; -} - -inline XEMProbaDescription * XEMModelOutput::getProbaDescription() { - return _probaDescription; -} - -inline XEMErrorType XEMModelOutput::getStrategyRunError() const{ - return _strategyRunError; -} - -inline XEMEstimation * XEMModelOutput::getEstimation(){ - if (_estimation){ - return _estimation; - } - else{ - throw nullPointerError; - } -} - -inline double XEMModelOutput::getLikelihood() -{ - return _likelihood; -} - - -/* - - inline const XEMProbaOutput * const XEMModelOutput::getProbaOutput() const{ - if (_model){ - return _model->getProbaOutput(); - } - else{ - throw nullPointerEroor; - } - }*/ - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMModelType.cpp b/lib/src/mixmod/MIXMOD/XEMModelType.cpp deleted file mode 100644 index 6841f0c..0000000 --- a/lib/src/mixmod/MIXMOD/XEMModelType.cpp +++ /dev/null @@ -1,439 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMModelType.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMModelType.h" - -//------------ -// Constructor -//------------ -XEMModelType::XEMModelType(){ - _nameModel = defaultGaussianModelName; - _nbSubDimensionFree = 0; - _tabSubDimensionFree = NULL; - _subDimensionEqual = 0; - -} - - -XEMModelType::XEMModelType(XEMModelName name, int64_t nbSubDimensionFree){ - _nbSubDimensionFree = nbSubDimensionFree; - _tabSubDimensionFree = NULL; - _subDimensionEqual = 0; - - _nameModel = name; - -} - -XEMModelType::XEMModelType(const XEMModelType & iModelType){ - _nameModel = iModelType._nameModel; - _subDimensionEqual = iModelType._subDimensionEqual; - _nbSubDimensionFree = iModelType._nbSubDimensionFree; - if ((_nbSubDimensionFree!=0) && (iModelType._tabSubDimensionFree)){ - _tabSubDimensionFree = new int64_t[_nbSubDimensionFree]; - recopyTab(iModelType._tabSubDimensionFree,_tabSubDimensionFree,_nbSubDimensionFree); - } - else{ - _tabSubDimensionFree = NULL; - } -} - - -XEMModelType::~XEMModelType(){ - if (_tabSubDimensionFree){ - delete [] _tabSubDimensionFree; - _tabSubDimensionFree = NULL; - } -} - - - - - -void XEMModelType::input(ifstream & fi, int64_t nbCluster){ - - - _nbSubDimensionFree = nbCluster; - string keyWord = ""; - int64_t dim; - string a = ""; - - fi>>a; - if (a.compare("Gaussian_p_L_I") == 0){ - _nameModel = Gaussian_p_L_I; - } - else if (a.compare("Gaussian_p_Lk_I")==0){ - _nameModel = Gaussian_p_Lk_I; - } - else if (a.compare("Gaussian_p_L_B")==0){ - _nameModel = Gaussian_p_L_B; - } - else if (a.compare("Gaussian_p_Lk_B")==0){ - _nameModel = Gaussian_p_Lk_B; - } - else if (a.compare("Gaussian_p_L_Bk")==0){ - _nameModel = Gaussian_p_L_Bk; - } - else if (a.compare("Gaussian_p_Lk_Bk")==0){ - _nameModel = Gaussian_p_Lk_Bk; - } - else if (a.compare("Gaussian_p_L_C")==0){ - _nameModel = Gaussian_p_L_C; - } - else if (a.compare("Gaussian_p_Lk_C")==0){ - _nameModel = Gaussian_p_Lk_C; - } - else if (a.compare("Gaussian_p_L_D_Ak_D")==0){ - _nameModel = Gaussian_p_L_D_Ak_D; - } - else if (a.compare("Gaussian_p_Lk_D_Ak_D")==0){ - _nameModel = Gaussian_p_Lk_D_Ak_D; - } - else if (a.compare("Gaussian_p_L_Dk_A_Dk")==0){ - _nameModel = Gaussian_p_L_Dk_A_Dk; - } - else if (a.compare("Gaussian_p_Lk_Dk_A_Dk")==0){ - _nameModel = Gaussian_p_Lk_Dk_A_Dk; - } - else if (a.compare("Gaussian_p_L_Ck")==0){ - _nameModel = Gaussian_p_L_Ck; - } - else if (a.compare("Gaussian_p_Lk_Ck")==0){ - _nameModel = Gaussian_p_Lk_Ck; - } - else if (a.compare("Gaussian_pk_L_I")==0){ - _nameModel = Gaussian_pk_L_I; - } - else if (a.compare("Gaussian_pk_Lk_I")==0){ - _nameModel = Gaussian_pk_Lk_I; - } - else if (a.compare("Gaussian_pk_L_B")==0){ - _nameModel = Gaussian_pk_L_B; - } - else if (a.compare("Gaussian_pk_Lk_B")==0){ - _nameModel = Gaussian_pk_Lk_B; - } - else if (a.compare("Gaussian_pk_L_Bk")==0){ - _nameModel = Gaussian_pk_L_Bk; - } - else if (a.compare("Gaussian_pk_Lk_Bk")==0){ - _nameModel = Gaussian_pk_Lk_Bk; - } - else if (a.compare("Gaussian_pk_L_C")==0){ - _nameModel = Gaussian_pk_L_C; - } - else if (a.compare("Gaussian_pk_Lk_C")==0){ - _nameModel = Gaussian_pk_Lk_C; - } - else if (a.compare("Gaussian_pk_L_D_Ak_D")==0){ - _nameModel = Gaussian_pk_L_D_Ak_D; - } - else if (a.compare("Gaussian_pk_Lk_D_Ak_D")==0){ - _nameModel = Gaussian_pk_Lk_D_Ak_D; - } - else if (a.compare("Gaussian_pk_Lk_Dk_A_Dk")==0){ - _nameModel = Gaussian_pk_Lk_Dk_A_Dk; - } - else if (a.compare("Gaussian_pk_L_Dk_A_Dk")==0){ - _nameModel = Gaussian_pk_L_Dk_A_Dk; - } - else if (a.compare("Gaussian_pk_L_Ck")==0){ - _nameModel = Gaussian_pk_L_Ck; - } - else if (a.compare("Gaussian_pk_Lk_Ck")==0){ - _nameModel = Gaussian_pk_Lk_Ck; - } - - // Binary models // - else if (a.compare("Binary_p_E")==0){ - _nameModel = Binary_p_E; - } - else if (a.compare("Binary_p_Ek")==0){ - _nameModel = Binary_p_Ek; - } - else if (a.compare("Binary_p_Ej")==0){ - _nameModel = Binary_p_Ej; - } - else if (a.compare("Binary_p_Ekj")==0){ - _nameModel = Binary_p_Ekj; - } - else if (a.compare("Binary_p_Ekjh")==0){ - _nameModel = Binary_p_Ekjh; - } - else if (a.compare("Binary_pk_E")==0){ - _nameModel = Binary_pk_E; - } - else if (a.compare("Binary_pk_Ek")==0){ - _nameModel = Binary_pk_Ek; - } - else if (a.compare("Binary_pk_Ej")==0){ - _nameModel = Binary_pk_Ej; - } - else if (a.compare("Binary_pk_Ekj")==0){ - _nameModel = Binary_pk_Ekj; - } - else if (a.compare("Binary_pk_Ekjh")==0){ - _nameModel = Binary_pk_Ekjh; - } - - //HDDA models - - else if (a.compare("Gaussian_HD_pk_AkjBkQkD")==0){ - _nameModel = Gaussian_HD_pk_AkjBkQkD; - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if (keyWord.compare("subdimensionequal")==0){ - fi >> dim; - _subDimensionEqual = dim; - } - else{ - throw wrongSubDimension; - } - } - else if (a.compare("Gaussian_HD_pk_AkjBQkD")==0){ - _nameModel = Gaussian_HD_pk_AkjBQkD; - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if (keyWord.compare("subdimensionequal")==0){ - fi >> dim; - _subDimensionEqual = dim; - } - else{ - throw wrongSubDimension; - } - } - else if (a.compare("Gaussian_HD_pk_AjBkQkD")==0){ - _nameModel = Gaussian_HD_pk_AjBkQkD; - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if (keyWord.compare("subdimensionequal")==0){ - fi >> dim; - _subDimensionEqual = dim; - } - else{ - throw wrongSubDimension; - } - } - else if (a.compare("Gaussian_HD_pk_AjBQkD")==0){ - _nameModel = Gaussian_HD_pk_AjBQkD; - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if (keyWord.compare("subdimensionequal")==0){ - fi >> dim; - _subDimensionEqual = dim; - } - else{ - throw wrongSubDimension; - } - } - else if (a.compare("Gaussian_HD_pk_AkBkQkD")==0){ - _nameModel = Gaussian_HD_pk_AkBkQkD; - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if (keyWord.compare("subdimensionequal")==0){ - fi >> dim; - _subDimensionEqual = dim; - } - else{ - throw wrongSubDimension; - } - } - else if (a.compare("Gaussian_HD_pk_AkBQkD")==0){ - _nameModel = Gaussian_HD_pk_AkBQkD; - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if (keyWord.compare("subdimensionequal")==0){ - fi >> dim; - _subDimensionEqual = dim; - } - else{ - throw wrongSubDimension; - } - } - else if (a.compare("Gaussian_HD_pk_AkjBkQkDk")==0){ - _nameModel = Gaussian_HD_pk_AkjBkQkDk; - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if (keyWord.compare("subdimensionfree")==0){ - _tabSubDimensionFree = new int64_t[_nbSubDimensionFree]; - for (int64_t k=0; k<_nbSubDimensionFree; k++){ - fi >> dim; - _tabSubDimensionFree[k] = dim; - } - } - else{ - throw wrongSubDimension; - } - } - else if (a.compare("Gaussian_HD_pk_AkBkQkDk")==0){ - _nameModel = Gaussian_HD_pk_AkBkQkDk; - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if (keyWord.compare("subdimensionfree")==0){ - _tabSubDimensionFree = new int64_t[_nbSubDimensionFree]; - for (int64_t k=0; k<_nbSubDimensionFree; k++){ - fi >> dim; - _tabSubDimensionFree[k] = dim; - } - } - else{ - throw wrongSubDimension; - } - } - else if (a.compare("Gaussian_HD_p_AkjBkQkD")==0){ - _nameModel = Gaussian_HD_p_AkjBkQkD; - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if (keyWord.compare("subdimensionequal")==0){ - fi >> dim; - _subDimensionEqual = dim; - } - else{ - throw wrongSubDimension; - } - } - else if (a.compare("Gaussian_HD_p_AkjBQkD")==0){ - _nameModel = Gaussian_HD_p_AkjBQkD; - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if (keyWord.compare("subdimensionequal")==0){ - fi >> dim; - _subDimensionEqual = dim; - } - else{ - throw wrongSubDimension; - } - } - else if (a.compare("Gaussian_HD_p_AjBkQkD")==0){ - _nameModel = Gaussian_HD_p_AjBkQkD; - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if (keyWord.compare("subdimensionequal")==0){ - fi >> dim; - _subDimensionEqual = dim; - } - else{ - throw wrongSubDimension; - } - } - else if (a.compare("Gaussian_HD_p_AjBQkD")==0){ - _nameModel = Gaussian_HD_p_AjBQkD; - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if (keyWord.compare("subdimensionequal")==0){ - fi >> dim; - _subDimensionEqual = dim; - } - else{ - throw wrongSubDimension; - } - } - else if (a.compare("Gaussian_HD_p_AkBkQkD")==0){ - _nameModel = Gaussian_HD_p_AkBkQkD; - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if (keyWord.compare("subdimensionequal")==0){ - fi >> dim; - _subDimensionEqual = dim; - } - else{ - throw wrongSubDimension; - } - } - else if (a.compare("Gaussian_HD_p_AkBQkD")==0){ - _nameModel = Gaussian_HD_p_AkBQkD; - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if (keyWord.compare("subdimensionequal")==0){ - fi >> dim; - _subDimensionEqual = dim; - } - else{ - throw wrongSubDimension; - } - } - else if (a.compare("Gaussian_HD_p_AkjBkQkDk")==0){ - _nameModel = Gaussian_HD_p_AkjBkQkDk; - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if (keyWord.compare("subdimensionfree")==0){ - _tabSubDimensionFree = new int64_t[_nbSubDimensionFree]; - int64_t k; - for (k = 0; k < _nbSubDimensionFree ; k++){ - fi >>dim; - _tabSubDimensionFree[k] = dim; - } - } - else{ - throw wrongSubDimension; - } - } - else if (a.compare("Gaussian_HD_p_AkBkQkDk")==0){ - _nameModel = Gaussian_HD_p_AkBkQkDk; - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if (keyWord.compare("subdimensionfree")==0){ - _tabSubDimensionFree = new int64_t [_nbSubDimensionFree]; - for (int64_t k=0; k<_nbSubDimensionFree;k++){ - fi >>dim; - _tabSubDimensionFree[k] = dim; - } - } - else{ - throw wrongSubDimension; - } - } - - else{ - throw wrongModelType; - } - //delete[] a; - - - - - //delete[] keyWord; - - -} - - - -// << -ostream & operator<<(ostream & fo, XEMModelType & modelType){ - string name = XEMModelNameToString(modelType._nameModel); - fo<. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMMODELTYPE_H -#define XEMMODELTYPE_H - -#include "XEMUtil.h" - -/** - @brief Base class for ModelType(s) - @author F Langrognet & A Echenim -*/ - -class XEMModelType{ - - public: - - /// Default constructor - XEMModelType(); - - // constructor - XEMModelType(XEMModelName name,int64_t nbSubDimensionFree=0); - - XEMModelType(const XEMModelType & iModelType); - /// Destructor - virtual ~XEMModelType(); - - - - /// Input model type - void input(ifstream & fi, int64_t nbCluster); - - - /// name of the model - XEMModelName _nameModel; - - XEMModelType* clone(); - - //// list of number of subDimensionEqual - //int64_t _nbSubDimensionEqual; - //// list of number of subDimensionFree - //int64_t _nbSubDimensionFree; - - /// list of subDimensionEqual - int64_t _subDimensionEqual; - - /// _nbSubDimensionFree : size of array _tabSubDimensionFree - int64_t _nbSubDimensionFree; - - /// array of subDimensionFree - int64_t * _tabSubDimensionFree; - - /// getModelName - const XEMModelName & getModelName() const; - - /// getSubDimensionEqual - const int64_t & getSubDimensionEqual() const; - - /// getTabSubDimensionFree - const int64_t * getTabSubDimensionFree() const; - - ///getTabSubDimensionFreeI - const int64_t & getTabSubDimensionFreeI(int64_t index) const; - - /// setSubDimensionFree - void setTabSubDimensionFree(int64_t iTabSubDimensionFree, int64_t position) ; - - /// setSubDimensionEqual - void setSubDimensionEqual(int64_t iSubDimensionEqual) ; - - /// << - friend ostream & operator<<(ostream & fo, XEMModelType & modelType); - - -}; - -inline const XEMModelName & XEMModelType::getModelName() const{ - return _nameModel; -} - -inline const int64_t & XEMModelType::getSubDimensionEqual() const{ - return _subDimensionEqual; -} - -inline const int64_t * XEMModelType::getTabSubDimensionFree() const{ - return _tabSubDimensionFree; -} - -inline const int64_t & XEMModelType::getTabSubDimensionFreeI(int64_t index) const{ - return _tabSubDimensionFree[index]; -} - -inline void XEMModelType::setTabSubDimensionFree(int64_t iTabSubDimensionFree, int64_t position) { - if (_tabSubDimensionFree==NULL){ - _tabSubDimensionFree = new int64_t[_nbSubDimensionFree]; - } - _tabSubDimensionFree[position] = iTabSubDimensionFree; -} - -inline void XEMModelType::setSubDimensionEqual(int64_t iSubDimensionEqual) { - _subDimensionEqual = iSubDimensionEqual; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMNECCriterion.cpp b/lib/src/mixmod/MIXMOD/XEMNECCriterion.cpp deleted file mode 100644 index fc912a4..0000000 --- a/lib/src/mixmod/MIXMOD/XEMNECCriterion.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMNECCriterion.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMNECCriterion.h" - -//------------ -// Constructor -//------------ -XEMNECCriterion::XEMNECCriterion(){ -} - - - - -//----------- -// Destructor -//----------- -XEMNECCriterion::~XEMNECCriterion(){} - - - - -//--- -//run -//--- -void XEMNECCriterion::run(XEMModel * model, double & value, XEMErrorType & error, bool quiet){ - - error = noError; - - try{ - /* Compute NEC (An Entropy Criterion) */ - value = 0; - if (model->getNbCluster() == 1){ - value = 1; - } - else{ - double entropy = model->getEntropy(); - double loglikelihood = model->getLogLikelihood(false); // false : to not compute fik because already done - double loglikelihoodOne = model->getLogLikelihoodOne(); - if (fabs(loglikelihood-loglikelihoodOne) < minValueForLLandLLOne){ - throw pbNEC; - } - value = entropy / (loglikelihood-loglikelihoodOne); - } - } - catch(XEMErrorType & e){ - error = e; - } -} - diff --git a/lib/src/mixmod/MIXMOD/XEMNECCriterion.h b/lib/src/mixmod/MIXMOD/XEMNECCriterion.h deleted file mode 100644 index 9f91f95..0000000 --- a/lib/src/mixmod/MIXMOD/XEMNECCriterion.h +++ /dev/null @@ -1,62 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMNECCriterion.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMNECCRITERION_H -#define XEMNECCRITERION_H - -#include "XEMCriterion.h" -#include "XEMModel.h" - - -/** - @brief Derived class of XEMCriterion for NEC Criterion - @author F Langrognet & A Echenim -*/ - -class XEMNECCriterion : public XEMCriterion{ - - public: - - /// Default constructor - XEMNECCriterion(); - - - /// Destructor - virtual ~XEMNECCriterion(); - - XEMCriterionName getCriterionName() const; - - /// Run method - void run(XEMModel * model, double & value, XEMErrorType & error,bool quiet=true); - - - private : - -}; - -inline XEMCriterionName XEMNECCriterion::getCriterionName() const{ - return NEC; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMOldInput.cpp b/lib/src/mixmod/MIXMOD/XEMOldInput.cpp deleted file mode 100644 index 8f93bb0..0000000 --- a/lib/src/mixmod/MIXMOD/XEMOldInput.cpp +++ /dev/null @@ -1,1483 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMOldInput.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMOldInput.h" -#include "XEMStrategy.h" -#include "XEMGaussianData.h" -#include "XEMBinaryData.h" -#include "XEMError.h" - -//------------ -// Constructor -//------------ -XEMOldInput::XEMOldInput(){ - _finalized = false; - - _nbSample = 0; - _pbDimension = 0; - - _data = NULL; - _deleteData = false; - - - _tabKnownPartition = NULL; - _nbKnownPartition = 0; - _nbNbCluster = 0; - _tabNbCluster = NULL; - _deleteTabNbCluster = false; - - _nbCriterionName = 1; - _tabCriterionName = new XEMCriterionName[_nbCriterionName]; - _tabCriterionName[0] = defaultCriterionName; - _deleteTabCriterionName = true; - - _nbModelType = 1; - - _tabModelType = new XEMModelType*[_nbModelType]; - _tabModelType[0] = new XEMModelType(); - _deleteTabModelType = true; - - _nbStrategy = 1; - _tabStrategy = new XEMStrategy*[_nbStrategy]; - _tabStrategy[0] = new XEMStrategy(); - - _binaryDataType = false; - - _DCVinitBlocks = defaultDCVinitBlocks; - _numberOfDCVBlocks = defaultDCVnumberOfBlocks; - - _numberOfCVBlocks = defaultCVnumberOfBlocks; - _CVinitBlocks = defaultCVinitBlocks; -} - - - - -//------------ -// Constructor -//------------ -XEMOldInput::XEMOldInput(int64_t iNbSample, int64_t iPbDimension, int64_t iNbNbCluster, int64_t * iTabNbCluster, XEMData * iData, bool binaryDataType){ - - _finalized = false; - - _nbSample = iNbSample; - _pbDimension = iPbDimension; - - _nbNbCluster = iNbNbCluster; - //_tabNbCluster = iTabNbCluster; - - _tabNbCluster = new int64_t [ _nbNbCluster ]; - recopyTab( iTabNbCluster, _tabNbCluster, _nbNbCluster ); - - _deleteTabNbCluster = true; - - _tabKnownPartition = NULL; - _nbKnownPartition = _nbNbCluster; - _data = iData->clone(); - - //_deleteData = false; - _deleteData = true; - - _nbCriterionName = defaultNbCriterion; - _tabCriterionName = new XEMCriterionName[_nbCriterionName]; - _tabCriterionName[0] = defaultCriterionName; - _deleteTabCriterionName = true; - - _nbModelType = defaultNbModel; - - if (binaryDataType==false){ - _tabModelType = new XEMModelType * [_nbModelType]; - _tabModelType[0] = new XEMModelType(); - _deleteTabModelType = true; - _binaryDataType = false; - } - else{ - _tabModelType = new XEMModelType * [_nbModelType]; - _tabModelType[0] = new XEMModelType(defaultBinaryModelName); - _deleteTabModelType = true; - _binaryDataType = true; - } - _nbStrategy = defaultNbStrategy; - _tabStrategy = new XEMStrategy*[_nbStrategy]; - _tabStrategy[0] = new XEMStrategy(); - - _DCVinitBlocks = defaultDCVinitBlocks; - _numberOfDCVBlocks = defaultDCVnumberOfBlocks; - - _numberOfCVBlocks = defaultCVnumberOfBlocks; - _CVinitBlocks = defaultCVinitBlocks; - -} - - - -//--------------------------------- -// Constructor used in DCV context -//-------------------------------- -XEMOldInput::XEMOldInput(XEMOldInput * originalInput, XEMCVBlock & learningBlock){ - _nbSample = learningBlock._nbSample ; - _pbDimension = originalInput->_pbDimension; - - //---------------------- Nb cluster - _nbNbCluster = originalInput->_nbNbCluster ; - _tabNbCluster = originalInput->_tabNbCluster; - _deleteTabNbCluster = false; - - //---------------------- criterion type - _nbCriterionName = 1; - _tabCriterionName = new XEMCriterionName[1]; - _tabCriterionName[0] = CV; - _deleteTabCriterionName = true; - - - _nbStrategy = originalInput->_nbStrategy ; - - int64_t k,i ; - - //------------------------- Known labels - if(originalInput->_tabKnownPartition){ - _tabKnownPartition = new XEMPartition*[_nbNbCluster]; - for(k=0; k<_nbNbCluster; k++){ - _tabKnownPartition[k] = new XEMPartition(originalInput->_tabKnownPartition[k], learningBlock) ; - } - } - else{ - _tabKnownPartition = NULL; - } - - //------------------------- Model types - _nbModelType = originalInput->_nbModelType ; - _tabModelType = originalInput->_tabModelType ; - _deleteTabModelType = false; - - //------------------------- Strategy types - _tabStrategy = new XEMStrategy*[_nbStrategy] ; - for(k=0; k<_nbStrategy; k++){ - _tabStrategy[k] = new XEMStrategy(originalInput->_tabStrategy[k], learningBlock) ; - } - - _numberOfCVBlocks = originalInput->_numberOfCVBlocks; - _CVinitBlocks = originalInput->_CVinitBlocks; - - // will be not used but initalized - _numberOfDCVBlocks = originalInput->_numberOfDCVBlocks; - _DCVinitBlocks = originalInput->_DCVinitBlocks; - - - //---------------------- data - //---------------------------- - if (originalInput->_binaryDataType){ - // _data is not used by XEMMain... -> not updated - _deleteData = false; - _data = originalInput->_data; - _binaryDataType = true; - - } - else{ - // Gaussian case - _deleteData = true; - _data = new XEMGaussianData(_nbSample, _pbDimension, originalInput->_data , learningBlock); - _binaryDataType = false; - } - - _finalized = true; -} - - - -//----------- -// Destructor -//----------- -XEMOldInput::~XEMOldInput(){ - int64_t i,k; - - if (_tabCriterionName && _deleteTabCriterionName){ - delete[] _tabCriterionName; - _tabCriterionName = NULL; - } - if (_tabNbCluster && _deleteTabNbCluster){ - delete[] _tabNbCluster; - _tabNbCluster = NULL; - } - - if (_tabModelType && _deleteTabModelType){ - for (i=0; i<_nbModelType; i++){ - delete _tabModelType[i]; - _tabModelType[i] = NULL; - } - delete[] _tabModelType; - _tabModelType = NULL; - } - - if (_data && _deleteData){ - delete _data; - _data = NULL; - } - - - if (_tabKnownPartition){ - for(k=0; k<_nbNbCluster;k++){ - delete _tabKnownPartition[k]; - _tabKnownPartition[k] = NULL; - } - delete [] _tabKnownPartition; - _tabKnownPartition = NULL; - } - - if (_tabStrategy){ - for (i=0; i<_nbStrategy; i++){ - delete _tabStrategy[i]; - } - delete [] _tabStrategy; - } -} - - - -//----------------- -// setCriterionName -//----------------- -void XEMOldInput::setCriterionName(int64_t iNbCriterionName, XEMCriterionName * iTabCriterionName){ - if (_tabCriterionName && _deleteTabCriterionName){ - delete[] _tabCriterionName; - _tabCriterionName= NULL; - } - _nbCriterionName = iNbCriterionName; - _tabCriterionName = new XEMCriterionName[_nbCriterionName]; - recopyTab(iTabCriterionName, _tabCriterionName, iNbCriterionName); - _deleteTabCriterionName = true; - _finalized = false; -} - - - -void XEMOldInput::setCriterionName(XEMCriterionName criterionName, int64_t position){ - if ((position>(_nbCriterionName-1)) - ||(position<0) ){ - throw wrongCriterionPositionInSet; - } - else{ - _tabCriterionName[position] = criterionName; - _deleteTabCriterionName = true; - _finalized = false; - } -} - - - -// insertCriterionName -void XEMOldInput::insertCriterionName(XEMCriterionName criterionName, int64_t position){ - if ((position>_nbCriterionName) - || (position<0)){ - throw wrongCriterionPositionInInsert; - } - else{ - XEMCriterionName * tabCriterionName = new XEMCriterionName[_nbCriterionName+1]; - recopyTab(_tabCriterionName, tabCriterionName, position); - tabCriterionName[position] = criterionName; - for (int64_t i=position; i<_nbCriterionName;i++){ - tabCriterionName[i+1] = _tabCriterionName[i]; - } - delete [] _tabCriterionName; - _tabCriterionName = NULL; - _nbCriterionName++; - _tabCriterionName = tabCriterionName; - - _deleteTabCriterionName = true; - _finalized = false; - } -} - - - -// removeCriterionName -void XEMOldInput::removeCriterionName(int64_t position){ - if ((position>(_nbCriterionName-1)) - || ((position==0) && (_nbCriterionName==1)) - || (position<0)) { - throw wrongCriterionPositionInRemove; - } - else{ - XEMCriterionName * tabCriterionName = new XEMCriterionName[_nbCriterionName+1]; - recopyTab(_tabCriterionName, tabCriterionName, position); - for (int64_t i=position; i<(_nbCriterionName-1);++i){ - tabCriterionName[i] = _tabCriterionName[i+1]; - } - _nbCriterionName--; - delete [] _tabCriterionName; - _tabCriterionName = NULL; - _tabCriterionName = tabCriterionName; - - _deleteTabCriterionName = true; - _finalized = false; - - } -} - - - - -//------------- -// setModelType -//------------- -void XEMOldInput::setModelType(int64_t iNbModelType, XEMModelType ** iTabModelType){ - if (_tabModelType && _deleteTabModelType){ - delete[] _tabModelType; - _tabModelType= NULL; - } - _nbModelType = iNbModelType; - _tabModelType = new XEMModelType*[_nbModelType]; - for (int64_t i=0; i<_nbModelType; ++i){ - _tabModelType[i] = new XEMModelType(*(iTabModelType[i])); - } - _deleteTabModelType = true; - _finalized = false; -} - - -void XEMOldInput::setModelType(XEMModelName nameModel, int64_t position){ - if(position>(_nbModelType-1)){ - throw wrongModelPositionInSet; - } - else{ - XEMModelType * newModel; - if (isHD(nameModel)){ - newModel = new XEMModelType(nameModel,_tabNbCluster[0]); - } - else{ - newModel = new XEMModelType(nameModel); - } - delete _tabModelType[position]; - _tabModelType[position] = NULL; - _tabModelType[position] = new XEMModelType(*newModel); - - _deleteTabModelType = true; - _finalized = false; - - delete newModel; - } -} - -// insertModelType - - -void XEMOldInput::insertModelType(XEMModelName nameModel, int64_t position){ - if(position>(_nbModelType)){ - throw wrongModelPositionInInsert; - } - else{ - XEMModelType * newModel; - if (isHD(nameModel)){ - newModel = new XEMModelType(nameModel,_tabNbCluster[0]); - } - else{ - newModel = new XEMModelType(nameModel); - } - XEMModelType** tabModel = new XEMModelType*[_nbModelType+1]; - for (int64_t i=0;i(_nbModelType-1) || ((position==0) && (_nbModelType==1) )){ - throw wrongModelPositionInRemove; - } - else{ - XEMModelType** tabModel = new XEMModelType*[_nbModelType-1]; - - for (int64_t i=0 ; i(iTabStrategy,_tabStrategy,_nbStrategy); - _finalized = false; -} - - - -//-------------- -// setKnownPartition : copyTab in XEMPartition -//-------------- -void XEMOldInput::setKnownPartition(int64_t iNbKnownPartition, XEMPartition ** iTabKnownPartition){ - int64_t k; - if (_tabKnownPartition){ - for (k=0; k<_nbNbCluster; k++){ - delete _tabKnownPartition[k]; - } - delete[] _tabKnownPartition; - _tabKnownPartition = NULL; - } - - if (iNbKnownPartition != _nbNbCluster){ - throw wrongNbKnownPartition; - } - else{ - _tabKnownPartition = new XEMPartition *[_nbNbCluster]; - for (k=0; k<_nbNbCluster; k++){ - _tabKnownPartition[k] = new XEMPartition(iTabKnownPartition[k]); - } - } - _finalized = false; -} - - -void XEMOldInput::setKnownPartition(string & fileName, int64_t position){ - if(position>(_nbNbCluster-1)){ - throw wrongKnownPartitionPositionInSet; - } - else{ - // _nbKnownPartition = _nbNbCluster; - if (_tabKnownPartition){ - if (_tabKnownPartition[position]){ - delete _tabKnownPartition[position]; - _tabKnownPartition[position] = NULL; - } - } - else{ - _tabKnownPartition = new XEMPartition*[_nbNbCluster]; - } - try{ - XEMNumericPartitionFile partitionFile; - partitionFile._fileName = fileName; - partitionFile._format = FormatNumeric::defaultFormatNumericFile; - partitionFile._type = TypePartition::defaultTypePartition; - _tabKnownPartition[position] = new XEMPartition(_nbSample, _tabNbCluster[position], partitionFile); - } - catch (XEMError error){ - delete _tabKnownPartition[position]; - _tabKnownPartition[position] = NULL; - throw badKnownPartition; - } - _finalized = false; - } -} - - -// removeKnownPartition - -void XEMOldInput::removeKnownPartition(int64_t position, bool decrease){ - if (decrease){ - _nbKnownPartition--; - } - if(position>(_nbNbCluster-1)){ - throw wrongKnownPartitionPositionInRemove; - } - else{ - if (_tabKnownPartition){ - if (_tabKnownPartition[position]){ - delete _tabKnownPartition[position]; - _tabKnownPartition[position] = NULL; - } - } - if (_nbKnownPartition==0){ - if (_tabKnownPartition){ - delete [] _tabKnownPartition; - _tabKnownPartition = NULL; - } - } - _finalized = false; - } -} - -// insertKnownPartition -// void XEMOldInput::insertKnownPartition(string & fileName, int64_t position){ -// if( position > _nbNbCluster || position < 0 ){ -// throw wrongKnownPartitionPositionInInsert ; -// }else{ -// if( _tabKnownPartition ){ -// bool error = false; -// _tabKnownPartition[position] = new XEMPartition(_nbSample, _tabNbCluster[position],fileName, error); -// if (error){ -// delete _tabKnownPartition[position]; -// _tabKnownPartition[position] = NULL; -// throw badKnownPartition; -// } -// }else{ -// _tabKnownPartition = new XEMPartition*[_nbNbCluster]; -// _nbKnownPartition = _nbNbCluster; -// for( int64_t i = 0 ; i < _nbNbCluster ; i++ ){ -// _tabKnownPartition[i] = new XEMPartition(); -// } -// delete _tabKnownPartition[position] ; -// bool error = false; -// _tabKnownPartition[position] = new XEMPartition(_nbSample, _tabNbCluster[position],fileName, error); -// if (error){ -// delete _tabKnownPartition[position]; -// _tabKnownPartition[position] = NULL; -// throw badKnownPartition; -// } -// } -// _finalized = false; -// } -// } - - -//setNbTryInStrategy -void XEMOldInput::setNbTryInStrategy(int64_t strategyPosition, int64_t nbTry){ - if(strategyPosition>_nbStrategy){ - throw wrongStrategyPositionInSetOrGetMethod; - } - else{ - _tabStrategy[strategyPosition]->setNbTry(nbTry); - } -} - - -//--------------- -// getNbTryInStrategy -int64_t XEMOldInput::getNbTryInStrategy(int64_t strategyPosition){ - if(strategyPosition>_nbStrategy){ - throw wrongStrategyPositionInSetOrGetMethod; - } - else{ - return _tabStrategy[strategyPosition]->getNbTry(); - } -} - - -//-------------- -//setNbTryInInit -void XEMOldInput::setNbTryInInit(int64_t strategyPosition, int64_t nbTry){ - if(strategyPosition>_nbStrategy){ - throw wrongStrategyPositionInSetOrGetMethod; - } - else{ - _tabStrategy[strategyPosition]->setNbTryInInit(nbTry); - } -} - - -//--------------- -// getNbTryInInit -int64_t XEMOldInput::getNbTryInInit(int64_t strategyPosition){ - if(strategyPosition>_nbStrategy){ - throw wrongStrategyPositionInSetOrGetMethod; - } - else{ - return _tabStrategy[strategyPosition]->getNbTryInInit(); - } -} - - -//------------------ -// getStopNameInInit -//------------------ -const XEMAlgoStopName XEMOldInput::getStopNameInInit(int64_t strategyPosition) const{ - if(strategyPosition>_nbStrategy){ - throw wrongStrategyPositionInSetOrGetMethod; - } - else{ - return _tabStrategy[strategyPosition]->getStopNameInInit(); - } -} - - -//------------------ -// setStopNameInInit -//---------------- -void XEMOldInput::setStopNameInInit(int64_t strategyPosition, XEMAlgoStopName stopName){ - if(strategyPosition>_nbStrategy){ - throw wrongStrategyPositionInSetOrGetMethod; - } - else{ - _tabStrategy[strategyPosition]->setStopNameInInit(stopName); - } -} - - -//-------------------- -//setNbIterationInInit -void XEMOldInput::setNbIterationInInit(int64_t strategyPosition, int64_t nbIteration){ - if(strategyPosition>_nbStrategy){ - throw wrongStrategyPositionInSetOrGetMethod; - } - else{ - _tabStrategy[strategyPosition]->setNbIterationInInit(nbIteration); - } -} - -//--------------------- -// getNbIterationInInit -int64_t XEMOldInput::getNbIterationInInit(int64_t strategyPosition){ - if(strategyPosition>_nbStrategy){ - throw wrongStrategyPositionInSetOrGetMethod; - } - else{ - return _tabStrategy[strategyPosition]->getNbIterationInInit(); - } -} - - -//-------------- -//setEpsilonInInit -void XEMOldInput::setEpsilonInInit(int64_t strategyPosition, double epsilon){ - if(strategyPosition>_nbStrategy){ - throw wrongStrategyPositionInSetOrGetMethod; - } - else{ - _tabStrategy[strategyPosition]->setEpsilonInInit(epsilon); - } -} - - -//--------------- -// getEpsilonInInit -double XEMOldInput::getEpsilonInInit(int64_t strategyPosition){ - if(strategyPosition>_nbStrategy){ - throw wrongStrategyPositionInSetOrGetMethod; - } - else{ - return _tabStrategy[strategyPosition]->getEpsilonInInit(); - } -} - -// setStrategyInitType -void XEMOldInput::setStrategyInitName(XEMStrategyInitName initName, int64_t position){ - if(position>(_nbStrategy-1)){ - throw wrongStrategyPositionInSetOrGetMethod; - } - else{ - _tabStrategy[position]->setStrategyInit(initName,_data,_nbNbCluster,_tabNbCluster,_tabModelType); - _finalized = false; - } -} - -// set init parameter -void XEMOldInput::setInitParam(int64_t strategyPosition, string & paramFileName, int64_t position){ - if(strategyPosition>(_nbStrategy-1)){ - throw wrongStrategyPositionInSetOrGetMethod; - } - else{ - _tabStrategy[strategyPosition]->setInitParam(paramFileName, position); - _finalized = false; - } -} - -// set init partition -void XEMOldInput::setInitPartition(int64_t strategyPosition, string & partitionFileName, int64_t position){ - if(strategyPosition>(_nbStrategy-1)){ - throw wrongStrategyPositionInSetOrGetMethod; - } - else{ - _tabStrategy[strategyPosition]->setInitPartition(partitionFileName, position); - _finalized = false; - } -} - - -// set algo name -void XEMOldInput::setAlgoName(int64_t strategyPosition, XEMAlgoName algoName, int64_t position){ - if(strategyPosition>(_nbStrategy-1)){ - throw wrongStrategyPositionInSetOrGetMethod; - } - else{ - _tabStrategy[strategyPosition]->setAlgo(algoName, position); - _finalized = false; - } -} - -// remove algo type -void XEMOldInput::removeAlgo(int64_t strategyPosition, int64_t position){ - - if(strategyPosition>(_nbStrategy-1)){ - throw wrongStrategyPositionInSetOrGetMethod; - } - else{ - _tabStrategy[strategyPosition]->removeAlgo(position); - _finalized = false; - } -} - -/* -// insert algo type -void XEMOldInput::insertAlgoName(int64_t strategyPosition, XEMAlgoName algoName, int64_t position){ - -if(strategyPosition>_nbStrategy){ -throw wrongStrategyPositionInInsertAlgoType; -} -else{ -_tabStrategy[strategyPosition]->insertAlgo(algoName,position); -_finalized = false; -} -}*/ - -// insert default algo -void XEMOldInput::insertAlgo(int64_t strategyPosition, int64_t position){ - - if(strategyPosition>_nbStrategy){ - throw wrongStrategyPositionInSetOrGetMethod; - } - else{ - XEMAlgo * defaultAlgo = createDefaultAlgo(); - _tabStrategy[strategyPosition]->insertAlgo(defaultAlgo,position); - _finalized = false; - } -} - -// set algoStopRuleValue -void XEMOldInput::setAlgoStopRule(int64_t strategyPosition, int64_t position, XEMAlgoStopName stopName){ - if(strategyPosition>_nbStrategy){ - throw wrongStrategyPositionInSetOrGetMethod; - } - else{ - _tabStrategy[strategyPosition]->setAlgoStopRule(stopName,position); - } -} - -void XEMOldInput::setAlgoIteration(int64_t strategyPosition, int64_t position,int64_t nbIterationValue){ - if(strategyPosition>_nbStrategy){ - throw wrongStrategyPositionInSetOrGetMethod; - } - else{ - _tabStrategy[strategyPosition]->setAlgoIteration(position,nbIterationValue); - } -} - -void XEMOldInput::setAlgoEpsilon(int64_t strategyPosition, int64_t position, double epsilonValue){ - if(strategyPosition>_nbStrategy){ - throw wrongStrategyPositionInSetOrGetMethod; - } - else{ - _tabStrategy[strategyPosition]->setAlgoEpsilon(position,epsilonValue); - } -} - - -// set subDimensionEqual -void XEMOldInput::setSubDimensionEqual(int64_t position, int64_t subDimensionValue){ - if(position>_nbModelType){ - throw wrongModelPositionInSetSubDimensionEqual; - } - else{ - _tabModelType[position]->setSubDimensionEqual(subDimensionValue); - } -} - - -// set subDimensionFree -void XEMOldInput::setTabSubDimensionFree(int64_t positionModel, int64_t subDimensionValue, int64_t position){ - if(positionModel>_nbModelType){ - throw wrongModelPositionInSetSubDimensionFree; - } - else{ - _tabModelType[positionModel]->setTabSubDimensionFree(subDimensionValue, position); - } -} - - - - - -//--------------- -// Friend Methods -//--------------- - -ifstream & operator >> (ifstream & fi, XEMOldInput & input){ - int64_t i; - int64_t * tabNbModality = NULL; - bool nbFind = false; - - //////////////////////// - // // - // Compulsory Options // - // // - //////////////////////// - - // Number of sample(s) // - //---------------------// - moveUntilReach(fi,"nblines"); - if(!fi.eof()){ - fi >> input._nbSample; - if (input._nbSample > maxNbSample){ - throw nbLinesTooLarge; - } - else if (input._nbSample <= 0){ - throw nbLinesTooSmall; - } - } - else{ - throw errorNbLines; - } - - // Problem dimension // - //-------------------// - - - moveUntilReach(fi,"pbdimension"); - if(!fi.eof()){ - fi >> input._pbDimension; - if (input._pbDimension > maxPbDimension){ - throw pbDimensionTooLarge; - } - else if (input._pbDimension <= 0){ - throw pbDimensionTooSmall; - } - } - else{ - throw errorPbDimension; - } - - - - - - // Cluster(s) // - //------------// - - /* Number of number of cluster(s) */ - moveUntilReach(fi,"nbnbcluster"); - if(!fi.eof()){ - fi>>input._nbNbCluster; - if (input._nbNbCluster > maxNbNbCluster){ - throw nbNbClusterTooLarge; - } - else if (input._nbNbCluster <= 0){ - throw nbNbClusterTooSmall; - } - input._tabNbCluster = new int64_t[input._nbNbCluster]; - input._deleteTabNbCluster = true; - } - else{ - throw errorNbNbCluster; - } - - /* List of number of cluster(s) */ - moveUntilReach(fi,"listnbcluster"); - if(!fi.eof()){ - for (i=0; i>input._tabNbCluster[i]; - } - } - else{ - throw errorListNbCluster; - } - - // tab modality // - //--------------// - moveUntilReach(fi,"nbmodality"); - if(!fi.eof()){ - input._binaryDataType = true; - delete input._tabModelType[0]; - input._tabModelType[0] = new XEMModelType(defaultBinaryModelName); - tabNbModality = new int64_t[input._pbDimension]; - for (i=0; i> tabNbModality[i]; - if (tabNbModality[i]<2) - throw errorNbModality; - } - } - - - - - //------// - // Data // - //------// - - string dataFileName = ""; - moveUntilReach(fi); - if(fi.eof()){ - throw errorDataFile; - } - fi >> dataFileName; - /* XEMNumericDataFile dataFile; - dataFile._fileName = dataFileName; - dataFile._format = FormatNumeric::defaultFormatNumericFile;*/ - if (input._binaryDataType){ - input._data = new XEMBinaryData(input._nbSample, input._pbDimension, dataFileName, tabNbModality); - } - else{ - input._data = new XEMGaussianData(input._nbSample, input._pbDimension, dataFileName); - } - input._deleteData = true; - - if (tabNbModality){ - delete [] tabNbModality; - } - - //////////////////////// - // // - // Optional Options // - // // - //////////////////////// - - - //---------// - // Weight // - //---------// - string weightFileName = ""; - moveUntilReach(fi,"weightfile"); - if(!fi.eof()){ - fi >> weightFileName; - if(input._data){ - input._data->setWeight(weightFileName); - } - else{ - throw wrongWeightFileName; - } - } - - - // Model type(s) // - //---------------// - - /* Number of model(s) */ - moveUntilReach(fi,"nbmodel"); - if(!fi.eof()){ - nbFind = true; - fi >> input._nbModelType; - - // delete model data if necessary - if (input._tabModelType && input._deleteTabModelType){ - delete input._tabModelType[0]; - delete[] input._tabModelType; - input._tabModelType= NULL; - } - if (input._nbModelType > maxNbModel){ - throw nbModelTypeTooLarge; - } - else if (input._nbModelType <= 0){ - throw nbModelTypeTooSmall; - } - input._tabModelType = new XEMModelType*[input._nbModelType]; - input._deleteTabModelType = true; - - moveUntilReach(fi,"listmodel"); - if( (!fi.eof()) && (nbFind) ){ - for (i=0; iinput(fi, input._tabNbCluster[0]); - } - } - - } - - - // init reading at the beginning of file // - fi.clear(); - fi.seekg(0, ios::beg); - nbFind = false; - - - // tabKnownLabel // - //---------------// - string keyWord = ""; - moveUntilReach(fi,"partitionfile"); - if(!fi.eof()){ - input._tabKnownPartition = new XEMPartition*[input._nbNbCluster]; - string * tabFileName = new string[input._nbNbCluster]; - int64_t k; - for (k=0; k> input._nbCriterionName; - - // delete Criterion data if necessary - if (input._tabCriterionName && input._deleteTabCriterionName){ - delete[] input._tabCriterionName; - input._tabCriterionName= NULL; - } - if (input._nbCriterionName > maxNbCriterion){ - throw nbCriterionTooLarge; - } - else if (input._nbCriterionName <= 0){ - throw nbCriterionTooSmall; - } - moveUntilReach(fi,"listcriterion"); - if( (!fi.eof()) && (nbFind) ){ - delete[] input._tabCriterionName; - input._tabCriterionName = new XEMCriterionName[input._nbCriterionName]; - input._deleteTabCriterionName = true; - for (i=0; i>input._nbStrategy; - - // delete strategy Data - if (input._tabStrategy){ - delete input._tabStrategy[0]; - delete[] input._tabStrategy; - input._tabStrategy= NULL; - } - - if (input._nbStrategy > maxNbStrategy){ - throw nbStrategyTypeTooLarge; - } - else if (input._nbStrategy <= 0){ - throw nbStrategyTypeTooSmall; - } - - //delete[] input._tabStrategy; - input._tabStrategy = new XEMStrategy*[input._nbStrategy]; - - for (i=0; iinput(fi, input._data, input._nbNbCluster, input._tabNbCluster, input._tabModelType); - } - } - - - moveUntilReach(fi,"nbcvblocks"); - if(!fi.eof()){ - fi >> input._numberOfCVBlocks ; - } - moveUntilReach(fi,"cvinitblocks"); - if(!fi.eof()){ - inputCVinitBlocks( fi,input._CVinitBlocks); - } - - moveUntilReach(fi,"nbdcvblocks"); - if(!fi.eof()){ - fi >> input._numberOfDCVBlocks ; - } - - moveUntilReach(fi,"dcvinitblocks"); - if(!fi.eof()){ - inputDCVinitBlocks( fi,input._DCVinitBlocks); - } - - input.finalize(); - return fi; -} - - - - - - -//----------- -//----------- -// ostream << -//----------- -//----------- -ostream & operator << (ostream & fo, XEMOldInput & input){ - int64_t i,j; - - fo<<"nbSample : "<output(fo); - fo<_weightTotal; - int64_t iWeightTotal = (int64_t)weightTotal; - if (weightTotal - iWeightTotal != 0){ - res = false; - throw weightTotalIsNotAnInteger; - } - - - // verif 2 - //-------- - // DCV context : verify _nbDCVBlock - // each learning block must contains at least 10 individuals - int64_t iCriterion=0; - while (iCriterion<_nbCriterionName && res){ - if (_tabCriterionName[iCriterion] == DCV){ - if (_numberOfDCVBlocks *10 >= iWeightTotal){ - _numberOfDCVBlocks = iWeightTotal / 10; - } - // _nbDCVBlock must be > 1 - if (_numberOfDCVBlocks <= 1){ - res = false; - throw NbDCVBlocksTooSmall; - } - } - iCriterion++; - } - - - - //verif 3 HDDA models and MAP require given sub dimension - //------- - bool HDDA_context = false; - int64_t iModelType = 0; - while (iModelType<_nbModelType && HDDA_context==false){ - if (isHD(_tabModelType[iModelType]->_nameModel)){ - HDDA_context = true; - } - iModelType++; - } - - - // int64_t nbAlgoType = _tabStrategy[k]->_nbAlgoType; - int64_t inbAlgoType = 0; - bool MAPAlgo = false; - for (int64_t k=0;k<_nbStrategy;k++){ - int64_t nbAlgoType = _tabStrategy[k]->getNbAlgo(); - while (inbAlgoTypegetAlgo(inbAlgoType); - if (algo->getAlgoName() == MAP){ - MAPAlgo = true; - } - inbAlgoType++; - } - } - - /*if ((MAPAlgo==true) && (HDDA_context==true) && (_tabSubDimensionFree==NULL) &&(_subDimensionEqual==NULL) ){ - throw ungivenSubDimension; - res = false; - }*/ - - - if ((MAPAlgo==true) && (HDDA_context==true)) { - for (int64_t k=0;k<_nbModelType;k++){ - if ((_tabModelType[k]->_tabSubDimensionFree==NULL) && (_tabModelType[k]->_subDimensionEqual==0)){ - res = false; - throw ungivenSubDimension; - } - } - } - - //verif 4 if subDimensionFree only Gaussian_HDDA_AkjBkQkDk and Gaussian_HDDA_AkBkQkDk - for (int64_t k=0;k<_nbModelType;k++){ - - if (isHD(_tabModelType[k]->_nameModel)) - if (isFreeSubDimension(_tabModelType[k]->_nameModel) - && (_tabModelType[k]->_tabSubDimensionFree==NULL)){ - res = false; - throw wrongSubDimension; - } - else if (!isFreeSubDimension(_tabModelType[k]->_nameModel) - && (_tabModelType[k]->_subDimensionEqual==0)){ - res = false; - throw wrongSubDimension; - } - } - - - - //-------------------------------- - // verif : Verify all strategies - //------------------------------- - int64_t iStrategy; - for (iStrategy=0; iStrategy<_nbStrategy; iStrategy++){ - res = _tabStrategy[iStrategy]->verify(); - } - - //-------------------------------- - // verif : - // If one strategy is M or MAP, one only strategy is allowed - //------------------------------- - iStrategy = 0; - bool isOneStrategyUseMOrMAP = false; - while (iStrategy<_nbStrategy && !isOneStrategyUseMOrMAP){ - isOneStrategyUseMOrMAP = (_tabStrategy[iStrategy]->isMAlgo() || _tabStrategy[iStrategy]->isMAPAlgo()); - iStrategy++; - } - if (isOneStrategyUseMOrMAP){ - if (_nbStrategy > 1){ - res = false; - throw nbStrategyMustBe1; - } - } - - - //------- - // verif - // if HDDA model : only M or MAP could be choosen - //------ - if (HDDA_context && !isOneStrategyUseMOrMAP){ - res = false; - throw badAlgorithmInHDContext; - } - - - //-------- - // Verif - // if CV (or DCV) : - // - algo must be M - //-------- - iCriterion=0; - int64_t k; - bool CV_DCV_criterion = false; - while (iCriterion<_nbCriterionName && !CV_DCV_criterion){ - if ((_tabCriterionName[iCriterion] == CV) || (_tabCriterionName[iCriterion] == DCV)){ - CV_DCV_criterion = true; - } - iCriterion++; - } - - // CV or DCV - if (CV_DCV_criterion){ - // algo must be M - res = _tabStrategy[0]->isMAlgo(); // v�rifier sur le 1er suffit car on a d�j� v�rifi� que 'il y avait M, il n'y a qu'une strat�gie - if (!res){ - throw algorithmMustBeM; - } - } - - - - //--------------------------------------------------------------------- - // if M : - // knowLabel is required and knownLabel=initLabel (for each knonwLabel) - //--------------------------------------------------------------------- - if (_tabStrategy[0]->isMAlgo()){ // v�rifier sur le 1er suffit car on a d�j� v�rifi� que 'il y avait M, il n'y a qu'une strat�gie - // knwonLabel is required and initLabel=knownLabel - if (_tabKnownPartition == NULL){ - res = false; - throw knownPartitionNeeded; - } - else{ - if (_nbNbCluster != _tabStrategy[0]->getStrategyInit()->getNbPartition()){ - res = false; - throw wrongNbKnownPartitionOrInitPartition; - } - k = 0; - while (k<_nbNbCluster && res){ - res = *(_tabKnownPartition[k]) == *(_tabStrategy[0]->getStrategyInit()->getPartition(k)); - if (!res){ - throw knownPartitionAndInitPartitionMustBeEqual; - } - k++; - } - } - } - - - - - //verif MAP & CV or DCV impossible - if ((MAPAlgo==true) && (CV_DCV_criterion==true)){ - res=false; - throw wrongCriterionName; - } - - - return res; -} - - diff --git a/lib/src/mixmod/MIXMOD/XEMOldInput.h b/lib/src/mixmod/MIXMOD/XEMOldInput.h deleted file mode 100644 index 24801c9..0000000 --- a/lib/src/mixmod/MIXMOD/XEMOldInput.h +++ /dev/null @@ -1,496 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMOldInput.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMOLDINPUT_H -#define XEMOLDINPUT_H - -#include "XEMUtil.h" -#include "XEMData.h" -#include "XEMPartition.h" -//#include "XEMStrategy.h" -#include "XEMModelType.h" -class XEMStrategy; - -/** @brief Input Class for MIXMOD API - @author F Langrognet & A Echenim - - Mixmod inputs are stored in a XEMOldInput object.
- Required inputs :
- ----------------------- - \li nbSample (int64_t) : number of samples - \li pbDimension (int64_t) : problem dimension (number of variables) - \li nbCluster : nbCluster values -

    -
  • nbNbCluster (int64_t) : size of the following array
  • -
  • tabNbCluster (int64_t *) : Array of nbCluster values
  • -
- \li data : a XEMGaussianData or XEMBinaryData object - - - Optional inputs (inputs with default value) :
- ----------------------- - \li model : model type values -
    -
  • nbModelTye (int64_t) : size of the following array
  • -
  • tabModelType : array of XEMModelType value \see XEMModelType.h
  • -
- \li criterion : criterion types values -
    -
  • nbCriterionName (int64_t) : size of the following array
  • -
  • tabCriterionName : array of XEMCriterionName value \see XEMUtil.h
  • -
- \li knownPartition: fixed Partition (in Discriminant Analysis context) -
    -
  • nbTabKnownPartition (int64_t) : size of the following array = nbNbCluster
  • -
  • tabknownPartition (also called tabKnownPartition) : array of XEMPartition (a XEMPartition is a Partition !)
  • -
- \li strategy : strategies to apply (initialization method + algortihms) -
    -
  • nbStrategy (int64_t) : number of strategies (and size of the following array)
  • -
  • tabStrategy : array of XEMStrategy
  • -
- \li subDimensionFree : subDimension value if a High Dimension Model is choosen with free subdimension (....Dk....) : an array (size=nbNbCluster) of int64_t* value. subDimension[u] is NULL if subDimensions are unknown, or subDimension[u][k] = subDimension of the (k+1)th class if nbCluster=u+1 - \li subDimensionEqual : subDimension value if a High Dimension Model is choosen with equal subdimension (....D....) : an array (size=nbNbCluster) of int64_t * value. subDimension[u] is NULL if this subDimension is unknown or *(subDimension[u])=subDimension of all classes. - - -*/ - -class XEMOldInput{ - - public: - - /// Default Constructor - XEMOldInput(); - - /** @brief Constructor - @param iNbSample number of samples - @param iPbDimension problem dimension (or number of variables) - @param iNbNbCluster size of tabNbCluster array - @param iTabNbCluster array of number of clusters - @param iData data object (see XEMGaussianData and XEMBinary classes) - \see XEMGaussianData.h - \see XEMBinaryData.h - */ - XEMOldInput(int64_t iNbSample, int64_t iPbDimension, int64_t iNbNbCluster, int64_t * iTabNbCluster, XEMData * iData, bool binaryDataType=false); - - - // Constructor used in DCV context - XEMOldInput(XEMOldInput * originalInput, XEMCVBlock & learningBlock); - - - - /// Destructor - virtual ~XEMOldInput(); - - - /** @brief Criterion Selector : to set Criterion optional input - @param iNbCriterionName Number of criteria types - @param iTabCriterionName Array of criteria names (see XEMCriterionName) - \see XEMUtil.h - */ - void setCriterionName(int64_t iNbCriterionName, XEMCriterionName * iTabCriterionName); - - - /** @brief Model Selector : to set Model optional input - @param iNbModelType Number of model types - @param iTabModelType Array of model types - \see XEMModelType.h - */ - void setModelType(int64_t iNbModelType, XEMModelType ** iTabModelType); - - - /** @brief Strategy Selector : to set Strategy optional input - @param iNbStrategy Number of strategies - @param iTabStrategy Array of strategies (see XEMStrategy class) - \see XEMStrategy.h - */ - void setStrategy(int64_t iNbStrategy, XEMStrategy ** iTabStrategy); - - - /** @brief knownLabel Selector : to set Known partition (known partition) optional input - @param iNbKnownPartition Number of knownPartition - @param iTabKnownPartition Array of known partitions (see XEMPartition class) - \see XEMPartition.h - */ - void setKnownPartition(int64_t iNbKnownPartition, XEMPartition ** iTabKnownPartition); - - - /** finalize */ - void finalize(); - - /// getNbSample - const int64_t & getNbSample() const; - - /// getPbDimension - const int64_t & getPbDimension() const; - - /// getXEMData - const XEMData* getXEMData() const; - - ///getXEMPartition - const XEMPartition** getTabPartition() const; - - ///getXEMPartition[i] - const XEMPartition* getTabPartitionI(int64_t index) const; - - ///getNbNbCluster - const int64_t & getNbNbCluster() const; - - ///getTabNbCluster; - const int64_t* getTabNbCluster() const; - - /// getTabNbCluster[I] - const int64_t getTabNbClusterI(int64_t index) const; - ///getNbCriterionName - const int64_t & getNbCriterionName() const; - - ///getTabCriterionName - const XEMCriterionName * getTabCriterionName() const; - - ///getTabCriterionName[i] - const XEMCriterionName & getCriterionName(int64_t index) const; - - /// getNbModelType - const int64_t & getNbModelType() const; - - /// getTabModelType - const XEMModelType** getTabModelType() const; - - /// getTabModelType[i] - const XEMModelType* getTabModelTypeI(int64_t index) const; - - /// getNbStrategy - const int64_t & getNbStrategy() const; - - /// getTabStrategy - const XEMStrategy** getTabStrategy() const; - - /// getStrategy[i] - const XEMStrategy* getStrategy(int64_t index) const; - - ///getNbKnownPartition(); - int64_t getNbKnownPartition() const; - - ///setWeight(); - void setWeight(string & fileNameWeight); - - - /// setCriterionName - void setCriterionName(XEMCriterionName criterionName, int64_t position); - - ///insertCriterionName - void insertCriterionName(XEMCriterionName criterionName, int64_t position); - - /// removeCriterionName - void removeCriterionName(int64_t position); - - /// setModelType - void setModelType(XEMModelName nameModel, int64_t position); - - /// insertModelType - void insertModelType(XEMModelName nameModel, int64_t position); - - /// removeModelType - void removeModelType(int64_t position); - - /// setKnownPartition - void setKnownPartition(string & fileName, int64_t position); - - - /// removeKnownPartition - void removeKnownPartition(int64_t position, bool decrease); - - /// insertKnownPartition - //void insertKnownPartition(string & fileName, int64_t position); - - /// setNbTryInStrategy - void setNbTryInStrategy(int64_t strategyPosition, int64_t nbTry); - - /// getNbTryInStrategy - int64_t getNbTryInStrategy(int64_t strategyPosition); - - /// setNbTryInInit - void setNbTryInInit(int64_t strategyPosition, int64_t nbTry); - - /// getNbTryInInit - int64_t getNbTryInInit(int64_t strategyPosition); - - /// setNbIterationInInit - void setNbIterationInInit(int64_t strategyPosition, int64_t nbIteration); - - /// getNbIterationInInit - int64_t getNbIterationInInit(int64_t strategyPosition); - - /// setEpsilonInInit - void setEpsilonInInit(int64_t strategyPosition, double epsilon); - - /// getEpsilonInInit - double getEpsilonInInit(int64_t strategyPosition); - - /// setStrategyInitName - void setStrategyInitName(XEMStrategyInitName initName, int64_t position); - - /// getStopNameInInit - const XEMAlgoStopName getStopNameInInit(int64_t strategyPosition) const; - - /// setStopNameInInit - void setStopNameInInit(int64_t strategyPosition, XEMAlgoStopName stopName); - - /// setInitParam - void setInitParam(int64_t strategyPosition, string & paramFileName, int64_t position); - - /// setInitPartition - void setInitPartition(int64_t strategyPosition, string & partitionFileName, int64_t position); - - - /// setAlgoName - void setAlgoName(int64_t strategyPosition, XEMAlgoName algoName, int64_t position); - - /// removeAlgo - void removeAlgo(int64_t strategyPosition,int64_t position); - - // insertAlgoName - // void insertAlgoName(int64_t strategyPosition,XEMAlgoName algoName, int64_t position); - - /// insert default algo - void insertAlgo(int64_t strategyPosition, int64_t position); - - /// set algo stop rule - void setAlgoStopRule(int64_t strategyPosition, int64_t position, XEMAlgoStopName stopName); - - ///set nb iteration - void setAlgoIteration(int64_t strategyPosition, int64_t position,int64_t nbIterationValue); - - ///set nb epsilon - void setAlgoEpsilon(int64_t strategyPosition,int64_t position, double epsilonValue); - - - - /// setSubDimensionEqual - void setSubDimensionEqual(int64_t position, int64_t subDimensionValue); - - /// setSubDimensionFreel - void setTabSubDimensionFree(int64_t positionModel, int64_t subDimensionValue, int64_t position); - - //------- - private : - //------- - - // Number of samples (no reduced data) - int64_t _nbSample; - - // Problem dimension - int64_t _pbDimension; - - // Current data - XEMData * _data; // aggregate - - - // _data must be deleted in the desctructor ? - bool _deleteData; - - // Knwon label - XEMPartition ** _tabKnownPartition; // aggregate - - // Number of numbers of cluster - int64_t _nbNbCluster; - - // Table of numbers of cluster - int64_t * _tabNbCluster; // aggregate - - // _tabNbCluster must be deleted in the destructor ? - bool _deleteTabNbCluster; - - // Number of criteria - int64_t _nbCriterionName; - - // Table of criterion type - XEMCriterionName * _tabCriterionName; // aggregate - - // _tabCriterionName must be deleted in teh desctructor ? - bool _deleteTabCriterionName; - - // Number of models - int64_t _nbModelType; - - // Table of model type - XEMModelType ** _tabModelType; // aggregate - // _tabModelType must be deleted in teh desctructor ? - bool _deleteTabModelType; - - // Number of strategy - int64_t _nbStrategy; - - // Table of strategies - XEMStrategy ** _tabStrategy; // aggregate - - bool _binaryDataType; - - // number of Cv blocks - int64_t _numberOfCVBlocks ; // default 10 (see XEMUtil.h) - - // Initialisation method of CV blocks - XEMCVinitBlocks _CVinitBlocks; - - // Initialisation method of DCV blocks - XEMDCVinitBlocks _DCVinitBlocks; // how initialize the blocks (see XEMUtil.h) - // number of DCVBlock - int64_t _numberOfDCVBlocks; // number of DCV Blocks (default 10) - - int64_t _nbKnownPartition; - /** a input object must be finalized (verif, ...) - */ - bool _finalized; - - //. verification of inputs validity - bool verif(); - - - - - - - - - - - - - - - - /********************/ - /* FRIENDS */ - /********************/ - - friend class XEMCVCriterion; - friend class XEMDCVCriterion; - friend class XEMData; - friend class XEMMain; - friend class XEMCondExe; - friend class XEMOutput; - friend class XEMSelection; - - - /** @brief Friend method - @return Operator >> overloaded to read Input dat from input files - */ - friend ifstream & operator >> (ifstream & fi, XEMOldInput & input); - - /** @brief Friend method - @return Operator << overloaded to write Input data in output files - */ - friend ostream & operator << (ostream & fo, XEMOldInput & input); - - -}; - -inline const int64_t & XEMOldInput::getNbSample() const{ - return _nbSample; -} - -inline const int64_t & XEMOldInput::getPbDimension() const{ - return _pbDimension; -} - -inline const XEMData* XEMOldInput::getXEMData() const{ - return _data; -} - -inline void XEMOldInput::setWeight(string & fileNameWeight){ - if (fileNameWeight.compare("") == 0){ - return _data->setWeightDefault(); - }else{ - return _data->setWeight(fileNameWeight); - } -} - -inline const XEMPartition** XEMOldInput::getTabPartition() const{ - return const_cast(_tabKnownPartition); -} - -inline const XEMPartition* XEMOldInput::getTabPartitionI(int64_t index) const{ - return _tabKnownPartition[index]; -} - -inline const int64_t & XEMOldInput::getNbNbCluster() const{ - return _nbNbCluster; -} - -inline const int64_t* XEMOldInput::getTabNbCluster() const{ - return _tabNbCluster; -} - -inline const int64_t XEMOldInput::getTabNbClusterI(int64_t index) const{ - return _tabNbCluster[index]; -} -inline const int64_t & XEMOldInput::getNbCriterionName() const{ - return _nbCriterionName; -} - -inline const XEMCriterionName * XEMOldInput::getTabCriterionName() const{ - return _tabCriterionName; -} - -inline const XEMCriterionName & XEMOldInput::getCriterionName(int64_t index) const{ - return _tabCriterionName[index]; -} - -inline const int64_t & XEMOldInput::getNbModelType() const{ - return _nbModelType; -} - -inline const XEMModelType** XEMOldInput::getTabModelType() const{ - return const_cast(_tabModelType); -} - - -inline const XEMModelType* XEMOldInput::getTabModelTypeI(int64_t index) const{ - return _tabModelType[index]; -} - -inline const int64_t & XEMOldInput::getNbStrategy() const{ - return _nbStrategy; -} - -inline const XEMStrategy** XEMOldInput::getTabStrategy() const{ - return const_cast(_tabStrategy); -} - -inline const XEMStrategy* XEMOldInput::getStrategy(int64_t index) const{ - return _tabStrategy[index]; -} - -inline int64_t XEMOldInput::getNbKnownPartition() const{ - int64_t nbPartition; - if (_tabKnownPartition){ - nbPartition = _nbNbCluster; - } - else{ - nbPartition = 0; - } - return nbPartition; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMOldModelOutput.cpp b/lib/src/mixmod/MIXMOD/XEMOldModelOutput.cpp deleted file mode 100644 index a8b4bf4..0000000 --- a/lib/src/mixmod/MIXMOD/XEMOldModelOutput.cpp +++ /dev/null @@ -1,293 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMOldModelOutput.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMOldModelOutput.h" -#include "XEMGaussianParameter.h" - - - -//------------ -// Constructor -//------------ -// Default constructor -XEMOldModelOutput::XEMOldModelOutput(){ - _param = NULL; - _tabCriterionOutput = NULL; - _likelihoodOutput = NULL; - _probaOutput = NULL; - _errorType = internalMixmodError; // because the fields are not updated ! - _modelType = NULL; - _rankOfBestModelType = 0; -} - - - -//----------- -// Destructor -//----------- -XEMOldModelOutput::~XEMOldModelOutput(){ - int64_t i; - - if (_param){ - delete _param; - } - - if (_tabCriterionOutput){ - for (i=0; i<_nbCriterionOutput; i++){ - delete _tabCriterionOutput[i]; - } - delete [] _tabCriterionOutput; - _tabCriterionOutput = NULL; - } - - if (_likelihoodOutput){ - delete _likelihoodOutput; - } - - if (_probaOutput){ - delete _probaOutput; - } -} - - - -//----------------- -// setAllModelError -//----------------- -void XEMOldModelOutput::setErrorType(XEMErrorType error){ - _errorType = error; -} - - - -//--------- -// udpate 1 -//--------- -void XEMOldModelOutput::update(XEMSelection * selection, XEMEstimation ** tabEstimation, int64_t nbModelType){ - // this method must be called once time only : at the end of calculation - // If not, memory leaks appear (because of new in this method and delete in the destructor) - - if (_param != NULL) // 1rst called ? - throw internalMixmodError; - - _errorType = selection->getErrorType(); - if (_errorType == noError){ - int64_t bestIndexEstmimation = selection->getBestIndexEstimation(); - XEMEstimation * bestEstimation = tabEstimation[bestIndexEstmimation]; - - // Begin Bug 12464 - // old version : - //_rankOfBestModelType = bestIndexEstmimation+1; - // correction - _rankOfBestModelType = (bestIndexEstmimation%nbModelType)+1; - // End Bug 12464 - - XEMModel * bestModel = bestEstimation->getModel(); - XEMParameter * bestParam = bestModel->getParameter(); - - _modelType = bestEstimation->getModelType(); - _nbCluster = bestEstimation->getNbCluster(); - _strategy = bestEstimation->getStrategy(); - _cStrategy = bestEstimation->getClusteringStrategy(); - _param = bestParam->clone(); - // _param = new XEMGaussianParameter(bestEstimation->getLastModel()); - - _likelihoodOutput = new XEMLikelihoodOutput(bestModel); - - _probaOutput = new XEMProbaOutput(bestEstimation); - if (selection->getCriterionName() == CV){ - int64_t * tabCVLabel = selection->getCVLabelOfBestEstimation(); - int64_t * workingTabCVLabel = tabCVLabel; - const vector & correspondenceOriginDataToReduceData = bestEstimation->getcorrespondenceOriginDataToReduceData(); - int64_t nbSample = correspondenceOriginDataToReduceData.size(); - if (correspondenceOriginDataToReduceData.size() != 0){ // binary cas - workingTabCVLabel = new int64_t[nbSample]; - for (int64_t i=0; isetCVLabel(workingTabCVLabel); - } - - //_tabCriterionOutput - _nbCriterionOutput = 1; - _tabCriterionOutput = new XEMCriterionOutput*[_nbCriterionOutput]; - XEMCriterionName criterionName = selection->getCriterionName(); - double criterionValue = selection->getCriterionValue(bestEstimation); - XEMErrorType criterionErrorType = selection->getCriterionErrorType(bestEstimation); - // XEMCriterion * criterion = selection->getCriterion(bestEstimation); - _tabCriterionOutput[0] = new XEMCriterionOutput(criterionName, criterionValue, criterionErrorType); - } -} - - -//update1 //TODO : tmp -void XEMOldModelOutput::update1(XEMEstimation * bestEstimation, int64_t indexCriterion){ - // this method must be called once time only : at the end of calculation - // If not, memory leaks appear (because of new in this method and delete in the destructor) - - if (_param != NULL) // 1rst called ? - throw internalMixmodError; - - //_errorType = selection->getErrorType(); - _errorType = bestEstimation->getErrorType(); - if (_errorType == noError){ - - XEMModel * bestModel = bestEstimation->getModel(); - XEMParameter * bestParam = bestModel->getParameter(); - - _modelType = bestEstimation->getModelType(); - _nbCluster = bestEstimation->getNbCluster(); - _strategy = bestEstimation->getStrategy(); - _cStrategy = bestEstimation->getClusteringStrategy(); - _param = bestParam->clone(); - // _param = new XEMGaussianParameter(bestEstimation->getLastModel()); - - _likelihoodOutput = new XEMLikelihoodOutput(bestModel); - - _probaOutput = new XEMProbaOutput(bestEstimation); - //TODO - // if (bestEstimation->getCriterionName() == CV){ - // int64_t * tabCVLabel = selection->getCVLabelOfBestEstimation(); - // int64_t * workingTabCVLabel = tabCVLabel; - // const vector & correspondenceOriginDataToReduceData = bestEstimation->getcorrespondenceOriginDataToReduceData(); - // int64_t nbSample = correspondenceOriginDataToReduceData.size(); - // if (correspondenceOriginDataToReduceData.size() != 0){ // binary cas - // workingTabCVLabel = new int64_t[nbSample]; - // for (int64_t i=0; isetCVLabel(workingTabCVLabel); - // } - - //_tabCriterionOutput - _nbCriterionOutput = 1; - _tabCriterionOutput = new XEMCriterionOutput*[_nbCriterionOutput]; - vector criterionOutput = bestEstimation->getCriterionOutput(); - _tabCriterionOutput[0] = new XEMCriterionOutput(criterionOutput[indexCriterion].getCriterionName(), criterionOutput[indexCriterion].getValue(), criterionOutput[indexCriterion].getError()); - } -} - - - - - - -//--------- -// udpate 2 -//--------- -void XEMOldModelOutput::update(XEMEstimation * estimation, int64_t nbSelection, XEMSelection ** tabSelection){ - // this method must be called once only : at the end of calculation - // If not, memory leaks appear (because of new in this method and delete in the destructor) - - int64_t i; - - if (_param != NULL) // 1rst called ? - throw internalMixmodError; - - _errorType = estimation->getErrorType(); - if (_errorType == noError){ - XEMModel * bestModel = estimation->getModel(); - XEMParameter * bestParam = bestModel->getParameter(); - - _modelType = estimation->getModelType(); - _nbCluster = estimation->getNbCluster(); - _strategy = estimation->getStrategy(); - _cStrategy = estimation->getClusteringStrategy(); - _param = bestParam->clone(); - - // _param = new XEMGaussianParameter(estimation->getLastModel()); - - _likelihoodOutput = new XEMLikelihoodOutput(bestModel); - _probaOutput = new XEMProbaOutput(estimation); - - //_tabCriterionOutput - _nbCriterionOutput = nbSelection; - _tabCriterionOutput = new XEMCriterionOutput*[_nbCriterionOutput]; - for (i=0; i<_nbCriterionOutput; i++){ - XEMCriterionName criterionName = tabSelection[i]->getCriterionName(); - double criterionValue = tabSelection[i]->getCriterionValue(estimation); - XEMErrorType criterionErrorType = tabSelection[i]->getCriterionErrorType(estimation); - //XEMCriterion * criterion = tabSelection[i]->getCriterion(estimation); - _tabCriterionOutput[i] = new XEMCriterionOutput(criterionName, criterionValue, criterionErrorType); - } - } - else{ - _modelType = estimation->getModelType(); - _nbCluster = estimation->getNbCluster(); - _strategy = estimation->getStrategy(); - _cStrategy = estimation->getClusteringStrategy(); - } - -} - - - -////////////////////// -////////////////////// -/// update //TODO -// update 2 bis -void XEMOldModelOutput::update2(XEMEstimation * estimation){ - // this method must be called once only : at the end of calculation - // If not, memory leaks appear (because of new in this method and delete in the destructor) - - int64_t i; - - if (_param != NULL) // 1rst called ? - throw internalMixmodError; - - _errorType = estimation->getErrorType(); - if (_errorType == noError){ - XEMModel * bestModel = estimation->getModel(); - XEMParameter * bestParam = bestModel->getParameter(); - - _modelType = estimation->getModelType(); - _nbCluster = estimation->getNbCluster(); - _strategy = estimation->getStrategy(); - _cStrategy = estimation->getClusteringStrategy(); - _param = bestParam->clone(); - - // _param = new XEMGaussianParameter(estimation->getLastModel()); - - _likelihoodOutput = new XEMLikelihoodOutput(bestModel); - _probaOutput = new XEMProbaOutput(estimation); - - //_tabCriterionOutput - _nbCriterionOutput = estimation->getCriterionSize(); - _tabCriterionOutput = new XEMCriterionOutput*[_nbCriterionOutput]; - vector criterionOutput = estimation->getCriterionOutput(); - for (i=0; i<_nbCriterionOutput; i++){ - _tabCriterionOutput[i] = new XEMCriterionOutput(criterionOutput[i].getCriterionName(), criterionOutput[i].getValue(), criterionOutput[i].getError()); - } - } - else{ - _modelType = estimation->getModelType(); - _nbCluster = estimation->getNbCluster(); - _strategy = estimation->getStrategy(); - _cStrategy = estimation->getClusteringStrategy(); - } - -} - diff --git a/lib/src/mixmod/MIXMOD/XEMOldModelOutput.h b/lib/src/mixmod/MIXMOD/XEMOldModelOutput.h deleted file mode 100644 index df236a5..0000000 --- a/lib/src/mixmod/MIXMOD/XEMOldModelOutput.h +++ /dev/null @@ -1,151 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMOldModelOutput.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMOldModelOutput_H -#define XEMOldModelOutput_H - -#include "XEMSelection.h" -#include "XEMEstimation.h" -#include "XEMCriterionOutput.h" -#include "XEMUtil.h" -#include "XEMLikelihoodOutput.h" -#include "XEMProbaOutput.h" - -/** - @brief Base class for XEMOldModelOutput(s) - @author F Langrognet & A Echenim -*/ - -class XEMOldModelOutput{ - - public: - - /// Default constructor - XEMOldModelOutput(); - - /// Destructor - virtual ~XEMOldModelOutput(); - - - /// setErrorType - void setErrorType(XEMErrorType error); - - /// udpate - void update(XEMSelection * selection, XEMEstimation ** tabEstimation, int64_t nbModelType); - - /// update //TODO - void update1(XEMEstimation * bestEstimation, int64_t indexCriterion); - - /// update - void update(XEMEstimation * estimation, int64_t nbSelection, XEMSelection ** tabSelection); - - /// update //TODO - void update2(XEMEstimation * estimation); - - /// Model Type - XEMModelType * _modelType; - - /// rank of the best model type - int64_t _rankOfBestModelType; - - /// nb Cluster - int64_t _nbCluster; - - /// strategy - XEMStrategy * _strategy; - /// strategy - XEMClusteringStrategy * _cStrategy; - - - /// number of criterion (size of _tabCriterionOutput) - int64_t _nbCriterionOutput; - - /// Table of CriterionOutput - XEMCriterionOutput ** _tabCriterionOutput; - - /// parameter - XEMParameter * _param; - - /// probability - XEMProbaOutput * _probaOutput; - - /// Likelihood - XEMLikelihoodOutput * _likelihoodOutput; - - /// error code for this model, this number of class and this strategy - // (for table of all or best model) - XEMErrorType _errorType; - - - XEMModelType * getModelType() const; - int64_t getNbCluster() const; - XEMParameter* getParameter() const; - XEMProbaOutput * getProbaOutput() const; - XEMLikelihoodOutput * getLikelihoodOutput() const; - XEMCriterionOutput** getTabCriterionOutput() const; - XEMCriterionOutput* getTabCriterionOutput(int64_t index) const; - int64_t getNbCriterionOutput() const; - -}; - -inline XEMModelType * XEMOldModelOutput::getModelType() const{ - return _modelType; -} - -inline int64_t XEMOldModelOutput::getNbCluster() const{ - return _nbCluster; -} - -inline XEMParameter* XEMOldModelOutput:: getParameter() const{ - return _param; -} - -inline XEMProbaOutput * XEMOldModelOutput::getProbaOutput() const{ - return _probaOutput; -} - -inline XEMLikelihoodOutput * XEMOldModelOutput::getLikelihoodOutput() const{ - return _likelihoodOutput; -} - -inline int64_t XEMOldModelOutput::getNbCriterionOutput() const{ - return _nbCriterionOutput; -} - - -inline XEMCriterionOutput** XEMOldModelOutput::getTabCriterionOutput() const{ - return _tabCriterionOutput; -} - -inline XEMCriterionOutput* XEMOldModelOutput::getTabCriterionOutput(int64_t index) const{ - return _tabCriterionOutput[index]; -} - - - - - - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMOutput.cpp b/lib/src/mixmod/MIXMOD/XEMOutput.cpp deleted file mode 100644 index ed37fb9..0000000 --- a/lib/src/mixmod/MIXMOD/XEMOutput.cpp +++ /dev/null @@ -1,401 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMOutput.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMOutput.h" -#include "XEMMain.h" -#include "XEMClusteringMain.h" -#include "XEMEstimation.h" -#include "XEMClusteringModelOutput.h" -#include "XEMModelOutput.h" -#include "XEMClusteringOutput.h" - -//------------ -// Constructor -//------------ -XEMOutput::XEMOutput(){ - _condExe = NULL; - _tabAllModelOutput = NULL; - _tabBestModelOutput = NULL; - _DCVCriterion = NULL; -} - - - -//------------ -// Constructor -//------------ -XEMOutput::XEMOutput(XEMOldInput * cInput, XEMMain& xmain){ - int64_t i; - _nbEstimation = xmain.getNbEstimation(); - _nbBestModel = xmain.getNbSelection(); - _condExe = new XEMCondExe(cInput, xmain.getTabEstimation(), _nbEstimation); - _tabBestModelOutput = new XEMOldModelOutput*[_nbBestModel]; - for (i=0; i<_nbBestModel; i++){ - _tabBestModelOutput[i] = new XEMOldModelOutput(); - } - _tabAllModelOutput = new XEMOldModelOutput*[_nbEstimation]; - for (i=0; i<_nbEstimation; i++){ - _tabAllModelOutput[i] = new XEMOldModelOutput(); - } - _DCVCriterion = xmain.getDCVCriterion(); -} - - - -//------------ -// Constructor -//------------ -XEMOutput::XEMOutput(XEMClusteringMain & xmain){ - int64_t i; - //_nbEstimation = xmain.getNbEstimation(); - XEMClusteringInput * cInput = dynamic_cast (xmain.getInput()); - _nbEstimation = cInput->getNbClusterSize() * cInput->getNbModelType(); - //_nbBestModel = xmain.getNbSelection(); - XEMClusteringOutput * cOutput = xmain.getClusteringOutput(); - const XEMClusteringModelOutput * const cMOutput = cOutput->getClusteringModelOutput(0); - _nbBestModel = cMOutput->getCriterionSize(); - _condExe = new XEMCondExe(cInput, xmain.getClusteringOutput()); - _tabBestModelOutput = new XEMOldModelOutput*[_nbBestModel]; - for (i=0; i<_nbBestModel; i++){ - _tabBestModelOutput[i] = new XEMOldModelOutput(); - } - _tabAllModelOutput = new XEMOldModelOutput*[_nbEstimation]; - for (i=0; i<_nbEstimation; i++){ - _tabAllModelOutput[i] = new XEMOldModelOutput(); - } - // TODO ?? _DCVCriterion = xmain.getDCVCriterion(); - _DCVCriterion = NULL; - - - // TODO !! pour que les anciens Output fonctionnent : à enlever ASAP - XEMEstimation * estimation0 = cMOutput->_estimation; - vector criterionOutput = estimation0->getCriterionOutput(); - for (i=0; i<_nbEstimation; i++){ - const XEMClusteringModelOutput * const cMOutput = cOutput->getClusteringModelOutput(i); - _tabAllModelOutput[i]->update2(cMOutput->_estimation); - } - for (i=0; i<_nbBestModel; i++){ - //TODO _tabBestModelOutput[i]->update(tabSelection[i], tabEstimation); - XEMCriterionName cN = criterionOutput[i].getCriterionName(); - - cOutput->sort(cN); - XEMClusteringModelOutput * cMO2 = cOutput->getClusteringModelOutput(0); - _tabBestModelOutput[i]->update1(cMO2->_estimation, i); - } - - // for error update - //TODO _condExe->update(_nbEstimation, tabEstimation, _nbBestModel, tabSelection); -} - - - -//----------- -// Destructor -//----------- -XEMOutput::~XEMOutput(){ - int64_t i; - if (_condExe){ - delete _condExe; - } - - if (_tabAllModelOutput){ - for(i=0; i<_nbEstimation; i++){ - delete _tabAllModelOutput[i]; - } - delete [] _tabAllModelOutput; - _tabAllModelOutput = NULL; - } - - if (_tabBestModelOutput){ - for(i=0; i<_nbBestModel; i++){ - delete _tabBestModelOutput[i]; - } - delete [] _tabBestModelOutput; - //_tabBestModelOutput = NULL; - } -} - - - -//------------------- -// set a mixmod error -//------------------- -void XEMOutput::setErrorMixmod(XEMErrorType errorType){ - _condExe->_errorMixmod = errorType; -} - - - -//------- -// update -//------- -// after calculation, object must be updated -void XEMOutput::update(XEMSelection ** tabSelection, int64_t nbSelection, XEMEstimation ** tabEstimation, int64_t nbEstimation, int64_t nbModeltype){ - int64_t i; - for (i=0; iupdate(tabSelection[i], tabEstimation, nbModeltype); - } - for (i=0; iupdate(tabEstimation[i], nbSelection, tabSelection); - } - - // for error update - _condExe->update(nbEstimation, tabEstimation, nbSelection, tabSelection); -} - - - -//----- -// edit -//----- -void XEMOutput::editFile(ofstream ** oFile){ - int64_t i, iSel, iEst; - if (_condExe->_errorMixmod == noError){ - - int64_t nbOutputFileType = 9; - - XEMCriterionName criterionName ; - - ofstream * currentFile ; - - //standardOutput - for (iSel=0; iSel<_nbBestModel; iSel++){ - if (_tabBestModelOutput[iSel]->_errorType == noError){ - criterionName = _tabBestModelOutput[iSel]->_tabCriterionOutput[0]->getCriterionName(); - //if(criterionType == DCV) criterionType = CV; - - - i = nbOutputFileType*criterionName + 0; //index in table oFile - currentFile = oFile[i] ; - - *currentFile<<"---------------------------------\n"; - *currentFile<<" MIXMOD Standard Output \n"; - *currentFile<<"---------------------------------\n"; - *currentFile<<"\n"; - *currentFile<<"Number of samples : "<<_condExe->_weightTotal<_tabCriterionOutput[0]->editType(*currentFile); - if (_tabBestModelOutput[iSel]->_strategy){ - _tabBestModelOutput[iSel]->_strategy->edit(*currentFile); - } - else{ - _tabBestModelOutput[iSel]->_cStrategy->edit(*currentFile); - } - *currentFile<<"\n"; - *currentFile<<"\t\tNumber of Clusters : "<<_tabBestModelOutput[iSel]->_nbCluster<_modelType); - _tabBestModelOutput[iSel]->_tabCriterionOutput[0]->editValue(*currentFile, true); - _tabBestModelOutput[iSel]->_param->edit(*currentFile, true); - } - } - - - - //_rankOfBestModelTypetandardOutput - for (iSel=0; iSel<_nbBestModel; iSel++){ - if (_tabBestModelOutput[iSel]->_errorType == noError){ - criterionName = _tabBestModelOutput[iSel]->_tabCriterionOutput[0]->getCriterionName(); - - i = nbOutputFileType*criterionName + 1; //index in table oFile - currentFile = oFile[i] ; - - *currentFile<<_tabBestModelOutput[iSel]->_nbCluster<_rankOfBestModelType<_rankOfBestStrategy<_tabCriterionOutput[0]->editValue(*currentFile); - _tabBestModelOutput[iSel]->_param->edit(*currentFile); - } - } - - - // labelOutput - for (iSel=0; iSel<_nbBestModel; iSel++){ - if (_tabBestModelOutput[iSel]->_errorType == noError){ - criterionName = _tabBestModelOutput[iSel]->_tabCriterionOutput[0]->getCriterionName(); - //if(criterionType==DCV) criterionType = CV; - - i = nbOutputFileType*criterionName + 2; //index in table oFile - _tabBestModelOutput[iSel]->_probaOutput->editLabel(*(oFile[i])); - } - } - - // parameterOutput - for (iSel=0; iSel<_nbBestModel; iSel++){ - if (_tabBestModelOutput[iSel]->_errorType == noError){ - criterionName = _tabBestModelOutput[iSel]->_tabCriterionOutput[0]->getCriterionName(); - //if(criterionType==DCV) criterionType = CV; - i = nbOutputFileType*criterionName + 3; //index in table oFile - _tabBestModelOutput[iSel]->_param->edit(*(oFile[i])); - } - } - - // tikOutput - for (iSel=0; iSel<_nbBestModel; iSel++){ - if (_tabBestModelOutput[iSel]->_errorType == noError){ - criterionName = _tabBestModelOutput[iSel]->_tabCriterionOutput[0]->getCriterionName(); - //if(criterionType==DCV) criterionType = CV; - i = nbOutputFileType*criterionName + 4; //index in table oFile - _tabBestModelOutput[iSel]->_probaOutput->editPostProba(*(oFile[i])); - } - } - - // zikOutput - for (iSel=0; iSel<_nbBestModel; iSel++){ - if (_tabBestModelOutput[iSel]->_errorType == noError){ - criterionName = _tabBestModelOutput[iSel]->_tabCriterionOutput[0]->getCriterionName(); - //if(criterionType==DCV) criterionType = CV; - i = nbOutputFileType*criterionName + 5; //index in table oFile - _tabBestModelOutput[iSel]->_probaOutput->editPartition(*(oFile[i])); - } - } - - // likelihoodOutput - for (iSel=0; iSel<_nbBestModel; iSel++){ - if (_tabBestModelOutput[iSel]->_errorType == noError){ - criterionName = _tabBestModelOutput[iSel]->_tabCriterionOutput[0]->getCriterionName(); - //if(criterionType==DCV) criterionType = CV; - i = nbOutputFileType*criterionName + 6; //index in table oFile - currentFile = oFile[i]; - - *currentFile<<"---------------------------------\n"; - *currentFile<<" MIXMOD Likelihood Output \n"; - *currentFile<<"---------------------------------\n"; - *currentFile<<"\n"; - *currentFile<<"Number of samples : "<<_condExe->_weightTotal<_strategy){ - _tabBestModelOutput[iSel]->_strategy->edit(*currentFile); - } - else{ - _tabBestModelOutput[iSel]->_cStrategy->edit(*currentFile); - } - *currentFile<<"\n"; - *currentFile<<"\t\tNumber of Clusters : "<<_tabBestModelOutput[iSel]->_nbCluster<_modelType); - _tabBestModelOutput[iSel]->_likelihoodOutput->edit(*currentFile,true); - } - } - - // numericLikelihoodOutput - for (iSel=0; iSel<_nbBestModel; iSel++){ - if (_tabBestModelOutput[iSel]->_errorType == noError){ - criterionName = _tabBestModelOutput[iSel]->_tabCriterionOutput[0]->getCriterionName(); - //if(criterionType==DCV) criterionType = CV; - i = nbOutputFileType*criterionName + 8; //index in table oFile - //editModelType(*(oFile[i]), _tabBestModelOutput[iSel]->_modelType); - _tabBestModelOutput[iSel]->_likelihoodOutput->edit(*(oFile[i])); - } - } - - // ErrorOutput - for (iSel=0; iSel<_nbBestModel; iSel++){ - criterionName = _condExe->_tabCriterionName[iSel]; - //if(criterionType==DCV) criterionType = CV; - i = nbOutputFileType*criterionName + 7; //index in table oFile - _condExe->editTabCriterionError(*(oFile[i]), iSel); - } - - // completeOutput - i = (int64_t)completeOutput; - currentFile = oFile[i]; - *currentFile<<"---------------------------------\n"; - *currentFile<<" MIXMOD Complete Output \n"; - *currentFile<<"---------------------------------\n"; - *currentFile<<"\n"; - *currentFile<<"Number of samples : "<<_condExe->_weightTotal<_strategy){ - _tabAllModelOutput[iEst]->_strategy->edit(*currentFile); - } - else{ - _tabAllModelOutput[iEst]->_cStrategy->edit(*currentFile); - } - *currentFile<<"\n"; - *currentFile<<"\t\tNumber of Clusters : "<<_tabAllModelOutput[iEst]->_nbCluster<_modelType); - if (_tabAllModelOutput[iEst]->_errorType == noError){ - for (iSel=0; iSel<_nbBestModel; iSel++){ - _tabAllModelOutput[iEst]->_tabCriterionOutput[iSel]->editTypeAndValue(*currentFile); - } - _tabAllModelOutput[iEst]->_param->edit(*currentFile, true); - } - else{ - *currentFile<<"\t\t\tError"<_errorType == noError){ - for (iSel=0; iSel<_nbBestModel; iSel++){ - _tabAllModelOutput[iEst]->_tabCriterionOutput[iSel]->editValue(*currentFile); - } - _tabAllModelOutput[iEst]->_param->edit(*currentFile); - } - } - - // labelClassificationOutput - for (iSel=0; iSel<_nbBestModel; iSel++){ - if (_tabBestModelOutput[iSel]->_errorType == noError){ - criterionName = _tabBestModelOutput[iSel]->_tabCriterionOutput[0]->getCriterionName(); - //if(criterionType==DCV) criterionType = CV; - - if (criterionName == CV){ - i = (int64_t)CVlabelClassificationOutput; - _tabBestModelOutput[iSel]->_probaOutput->editCVLabel(*(oFile[i])); - } - } - } - - - // errorModelOutput - i = (int64_t)errorModelOutput; - _condExe->editTabEstimationError(*(oFile[i])); - - // DCV information - i = (int64_t)DCVinfo ; - if(_DCVCriterion){ - _DCVCriterion->edit(*(oFile[i])); - } - - i = (int64_t)DCVnumericInfo ; - if(_DCVCriterion){ - _DCVCriterion->editNumeric(*(oFile[i])); - } - - }// end if (condExe->_errorMixmod == noError) - - // Everytime errorMixmodOutputFile must be written - // errorMixmodOutput - i = (int64_t)errorMixmodOutput; - *(oFile[i])<<_condExe->_errorMixmod<. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMOUTPUT_H -#define XEMOUTPUT_H - - -#include "XEMCondExe.h" -#include "XEMOldModelOutput.h" -#include "XEMDCVCriterion.h" -#include "XEMStrategy.h" -#include "XEMClusteringStrategy.h" -#include - -class XEMClusteringMain; -/** - @brief Base class for Output(s) - @author F Langrognet & A Echenim -*/ -class XEMMain ; - -class XEMOutput{ - - public: - - /// Default constructor - XEMOutput(); - - /// Constructor - XEMOutput(XEMOldInput * input, XEMMain& xmain); - - /// Constructor - XEMOutput(XEMClusteringMain & xmain); - - /// Destructor - virtual ~XEMOutput(); - - - /// set error - void setErrorMixmod(XEMErrorType errorType); - - /// edit Method in files - void editFile(ofstream ** oFile); - - /// update - void update(XEMSelection ** tabSelection, int64_t nbSelection, XEMEstimation ** tabEstimation, int64_t nbEstimation, int64_t nbModeltype); - - - /// Number of estimation ( = nb of nbcluster * nb of models * nb of strategies) - int64_t _nbEstimation; - - /// Number of best model - int64_t _nbBestModel; - - /// condition of execution - XEMCondExe * _condExe; - - /// Table of best model output by criterion (size : nbCriterionType = _nbSelection) - XEMOldModelOutput ** _tabBestModelOutput; - - /// Table of XEMAllModelOuput (size : _nbEstimation) - XEMOldModelOutput ** _tabAllModelOutput; - - /// DCVCriterion for DCVinfo.txt - XEMDCVCriterion * _DCVCriterion; - - - XEMOldModelOutput ** getTabAllModelOutput() const; - int64_t getNbEstimation() const; - - private: - //void getCriterionSize(); -}; - -inline XEMOldModelOutput ** XEMOutput::getTabAllModelOutput() const{ - return _tabAllModelOutput; -} - -inline int64_t XEMOutput::getNbEstimation() const{ - return _nbEstimation; -} - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMOutputControler.cpp b/lib/src/mixmod/MIXMOD/XEMOutputControler.cpp deleted file mode 100644 index 9e33936..0000000 --- a/lib/src/mixmod/MIXMOD/XEMOutputControler.cpp +++ /dev/null @@ -1,209 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMOutputControler.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include -#include "XEMOutputControler.h" -#include "XEMUtil.h" - - - -//------------ -// Constructor -//------------ -XEMOutputControler::XEMOutputControler(){ - int64_t i; - - _output = NULL; - _nbOutputFiles = maxNbOutputFiles; - for (i=0; i<_nbOutputFiles; i++){ - _tabOutputTypes[i] = (XEMOutputType) i; - } - createEmptyFiles(); -} - - - -//------------ -// Constructor -//------------ -XEMOutputControler::XEMOutputControler(XEMOutput * output){ - int64_t i; - - _output = output; - _nbOutputFiles = maxNbOutputFiles; - for (i=0; i<_nbOutputFiles; i++){ - _tabOutputTypes[i] = (XEMOutputType) i; - } - createEmptyFiles(); -} - - - -//----------- -// Destructor -//----------- -XEMOutputControler::~XEMOutputControler(){ - int64_t i; - //cout<<"tabFileName"<editFile(_tabFiles); - for (i=0; i<_nbOutputFiles; i++){ - _tabFiles[i]->close(); - } - } -} - - - -//--------- -// editErroMixmodFile -//--------- -void XEMOutputControler::editErroMixmodFile(XEMErrorType error){ - // errorMixmodOutput - int64_t i = (int64_t)errorMixmodOutput; - *_tabFiles[i]<setf(ios::fixed, ios::floatfield); - } - } - - - // other files - //------------ - //char * completeFileName ="complete.txt"; - _tabFiles[(int64_t)completeOutput] = new ofstream("complete.txt", ios::out); - _tabFiles[(int64_t)completeOutput]->setf(ios::fixed, ios::floatfield); - - //char * numericCompleteFileName ="numericComplete.txt"; - _tabFiles[(int64_t)numericCompleteOutput] = new ofstream("numericComplete.txt", ios::out); - _tabFiles[(int64_t)numericCompleteOutput]->setf(ios::fixed, ios::floatfield); - - //char * CVlabelClassificationFileName = "CVlabelClassification.txt"; - _tabFiles[(int64_t)CVlabelClassificationOutput] = new ofstream("CVlabelClassification.txt", ios::out); - _tabFiles[(int64_t)CVlabelClassificationOutput]->setf(ios::fixed, ios::floatfield); - - //char * errorMixmodFileName = "errorMixmod.txt"; - _tabFiles[(int64_t)errorMixmodOutput] = new ofstream("errorMixmod.txt", ios::out); - _tabFiles[(int64_t)errorMixmodOutput]->setf(ios::fixed, ios::floatfield); - - //char * errorModelFileName = "errorModel.txt"; - _tabFiles[(int64_t)errorModelOutput] = new ofstream("errorModel.txt", ios::out); - _tabFiles[(int64_t)errorModelOutput]->setf(ios::fixed, ios::floatfield); - - - // DCV files - _tabFiles[(int64_t)DCVinfo] = new ofstream("DCVinfo.txt", ios::out); - _tabFiles[(int64_t)DCVinfo]->setf(ios::fixed, ios::floatfield); - _tabFiles[(int64_t)DCVnumericInfo] = new ofstream("DCVnumericInfo.txt", ios::out); - _tabFiles[(int64_t)DCVnumericInfo]->setf(ios::fixed, ios::floatfield); - - - - // verify if files are open - for (i=0 ;i<_nbOutputFiles; i++){ - if (! _tabFiles[i]->is_open()) - throw errorOpenFile; - } - - delete [] fileNameTmp; - /*delete completeFileName; - delete numericCompleteFileName; - delete CVlabelClassificationFileName; - delete errorMixmodFileName; - delete errorModelFileName; - */ - -} diff --git a/lib/src/mixmod/MIXMOD/XEMOutputControler.h b/lib/src/mixmod/MIXMOD/XEMOutputControler.h deleted file mode 100644 index 81dc98e..0000000 --- a/lib/src/mixmod/MIXMOD/XEMOutputControler.h +++ /dev/null @@ -1,81 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMOutputControler.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMOUTPUTCONTROLER_H -#define XEMOUTPUTCONTROLER_H - -#include "XEMOutput.h" -#include "XEMUtil.h" - -/** - @brief Base class for Output(s) Controler - @author F Langrognet & A Echenim -*/ - - -class XEMOutputControler { - - public: - - /// Default constructor - XEMOutputControler(); - - /// Constructor - XEMOutputControler(XEMOutput * output); - - /// Destructor - virtual ~XEMOutputControler(); - - - /** @brief Selector - @param output Output to control - */ - void setOutput(XEMOutput * output); - - /// editFile - void editFile(); - - void editErroMixmodFile(XEMErrorType error); - - - private : - - /// Number of output files - int64_t _nbOutputFiles; - - /// Create empty output files - void createEmptyFiles(); - - /// Current output - XEMOutput * _output; - - /// Table of output files - ofstream * _tabFiles[maxNbOutputFiles]; - - /// Table of output files types - XEMOutputType _tabOutputTypes[maxNbOutputFiles]; - -}; - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMParameter.cpp b/lib/src/mixmod/MIXMOD/XEMParameter.cpp deleted file mode 100644 index a55cdd6..0000000 --- a/lib/src/mixmod/MIXMOD/XEMParameter.cpp +++ /dev/null @@ -1,188 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMParameter.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMParameter.h" -#include "XEMRandom.h" -#include "XEMModel.h" - - -//------------ -// Constructor -//------------ -// Default constructor -XEMParameter::XEMParameter(){ - throw wrongConstructorType; -} - - - -//------------ -// Constructor -// called if USER initialisation -//------------ -XEMParameter::XEMParameter(int64_t iNbCluster, int64_t iPbDimension, XEMModelType * iModelType){ - _modelType = iModelType; - _nbCluster = iNbCluster; - _pbDimension = iPbDimension; - _tabProportion = new double[_nbCluster]; - for (int64_t k=0; k<_nbCluster; k++){ - _tabProportion[k] = 1.0/_nbCluster; - } - _model = NULL; - _filename = ""; - _format = FormatNumeric::defaultFormatNumericFile; -} - - - -//------------ -// Constructor -//------------ -// called by XEMModel::XEMModel -// ! iModel isn't updated (iModel._param is this) -XEMParameter::XEMParameter(XEMModel * iModel, XEMModelType * iModelType){ - _modelType = iModelType; - _model = iModel; - _nbCluster = _model->getNbCluster(); - _pbDimension = _model->getData()->_pbDimension ; - _tabProportion = new double[_nbCluster]; - - // _tabProportion isn't computed because model->_tabNk isn't updated (=0) - for (int64_t k=0; k<_nbCluster; k++){ - _tabProportion[k] = 1.0/_nbCluster; - } - _filename = ""; - _format = FormatNumeric::defaultFormatNumericFile; -} - - - - -//------------ -// Constructor -//------------ -XEMParameter::XEMParameter(const XEMParameter * iParameter){ - _nbCluster = iParameter->getNbCluster(); - _pbDimension = iParameter->getPbDimension(); - _tabProportion = copyTab(iParameter->getTabProportion(),_nbCluster); - _model = iParameter->getModel(); - _modelType = iParameter->getModelType(); - _freeProportion = iParameter->getFreeProportion(); - _filename = iParameter->getFilename(); - _format = iParameter->getFormat(); -} - - - -//----------- -// Destructor -//----------- -XEMParameter::~XEMParameter(){ - - if (_tabProportion){ - delete[] _tabProportion; - _tabProportion = NULL; - } -} - - - -//------------------------ -// reset to default values -//------------------------ -void XEMParameter::reset(){ - for (int64_t k=0; k<_nbCluster; k++){ - _tabProportion[k] = 1.0/_nbCluster; - } -} - - - - -//------------------- -//generateRandomIndex -//------------------- -int64_t XEMParameter::generateRandomIndex(bool * tabIndividualCanBeUsedForInitRandom, double * weight, double totalWeight){ - double rndWeight, sumWeight; - int64_t idxSample; - - /* Generate a random integer between 0 and _nbSample-1 */ - bool IdxSampleCanBeUsed = false; // idxSample can be used - while (!IdxSampleCanBeUsed){ - // get index of sample with weight // - rndWeight = (int64_t)(totalWeight*rnd()+1); - sumWeight = 0.0; - idxSample = -1; - while(sumWeight < rndWeight){ - idxSample++; - sumWeight += weight[idxSample]; - } - //cout<<"index tir� au hasard :"<getTabNk(); - double weightTotal = (_model->getData())->_weightTotal; - - if (_freeProportion){ - for (k=0; k<_nbCluster; k++) - _tabProportion[k] = tabNk[k] / weightTotal; - } - else{ - for (k=0; k<_nbCluster; k++) - _tabProportion[k] = 1.0 / _nbCluster; - } - -} - - - -//----------------------------------------- -// computeTik when underflow -// -model->_tabSumF[i] pour ith sample = 0 -// i : 0 ->_nbSample-1 -//----------------------------------------- -void XEMParameter::computeTikUnderflow(int64_t i, double ** tabTik){ - throw nonImplementedMethod; -} - diff --git a/lib/src/mixmod/MIXMOD/XEMParameter.h b/lib/src/mixmod/MIXMOD/XEMParameter.h deleted file mode 100644 index b0c9d21..0000000 --- a/lib/src/mixmod/MIXMOD/XEMParameter.h +++ /dev/null @@ -1,291 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMParameter.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMParameter_H -#define XEMParameter_H - -#include "XEMUtil.h" -#include "XEMModelType.h" -#include "XEMData.h" -#include "XEMMatrix.h" -#include "XEMPartition.h" - -class XEMModel; - -/** - @brief Base class for XEMParameter(s) - @author F Langrognet & A Echenim -*/ - -class XEMParameter{ - - public: - - - /// Default constructor - XEMParameter(); - - /// Constructor - // called by XEMGaussianParameter or XEMBinaryParameter (called by XENStrategyType) - // if USER initialisation - XEMParameter(int64_t iNbCluster, int64_t iPbDimension, XEMModelType * iModelType); - - /// Constructor - // called by XEMParameter (called by XEMModel) - XEMParameter(XEMModel * iModel, XEMModelType * iModelType); - - /// Constructor ccopy) - XEMParameter(const XEMParameter * iParameter); - - /// Destructor - virtual ~XEMParameter(); - - - /// reset to default values - virtual void reset()=0; - - //void initRandomForMeanOrCenter(); - - - /** @brief Selector - @return A copy of the model - */ - virtual XEMParameter * clone()const =0 ; - - - - - - //-------- - // compute - //-------- - - /** Compute normal probability density function - for iSample the sample and kCluster th cluster - */ - virtual double getPdf(int64_t iSample, int64_t kCluster) const = 0; - - - // compute normal probability density function - // for all i=1,..,n and k=1,..,K - virtual void getAllPdf(double ** tabFik, double * tabProportion) const = 0; - - - /** Compute normal probability density function - for x vector and kCluster th cluster - */ - virtual double getPdf(XEMSample * x, int64_t kCluster) const= 0; - - - // computeTabProportion - void computeTabProportion(); - - - /** @brief Selector - @return The number of free parameters - */ - virtual int64_t getFreeParameter() const = 0; - - /// get loglikelihood with one cluster - virtual double getLogLikelihoodOne() const = 0; - - /// compute Tik for xi (i=0 -> _nbSample-1) when underflow - virtual void computeTikUnderflow(int64_t i, double ** tabTik); - - - //--------------- - // initialization - //--------------- - - /// init user - virtual void initUSER(XEMParameter * iParam) = 0; - - - int64_t generateRandomIndex(bool * tabIndividualCanBeUsedForInitRandom, double * weight, double totalWeight); - - /// initialize attributes before an InitRandom - virtual void initForInitRANDOM() = 0; - - virtual void updateForInitRANDOMorUSER_PARTITION(XEMSample ** tabSampleForInit, bool * tabClusterToInitialze) = 0; - - - - /// initialize attributes for init USER_PARTITION - /// outputs : - /// - nbInitializedCluster - /// - tabNotInitializedCluster (array of size _nbCluster) - - virtual void initForInitUSER_PARTITION(int64_t & nbInitializedCluster, bool * tabNotInitializedCluster, XEMPartition * initPartition) = 0; - - - - //----------- - // Algorithms - //----------- - - /// Maximum a posteriori step method - //virtual void MAPStep() = 0; - - /// Maximization step method - virtual void MStep()= 0; - - - - //------- - // in/out - //------- - - // edit (for debug) - virtual void edit()=0; - - /// edit - virtual void edit(ofstream & oFile, bool text=false)=0; - - /// input - virtual void input(ifstream & fi)=0; - - - //------- - // select - //------- - - /// get TabProportion - double * getTabProportion() const ; - - /// get nbCluster - int64_t getNbCluster() const ; - - /// get pbDimension - int64_t getPbDimension() const ; - - /// getFreeProportion - bool getFreeProportion() const ; - - /// getModel - XEMModel * getModel() const ; - - /// getModelType - XEMModelType * getModelType() const ; - - /// setModel - void setModel(XEMModel * iModel); - - ///getFilename - const string & getFilename() const; - - ///setFilename - void setFilename(const string & filename); - - /// recopie sans faire construction / destruction - // utilisé par SMALL_EM, CEM_INIT - virtual void recopy(XEMParameter * otherParameter) = 0; - - - virtual void updateForCV(XEMModel * originalModel, XEMCVBlock & CVBlock) = 0; - - ///get Format - FormatNumeric::XEMFormatNumericFile getFormat()const; - - ///set FormatNumeric - void setFormat(const FormatNumeric::XEMFormatNumericFile format); - - protected : - - /// Number of classes - int64_t _nbCluster; - - /// problem dimension - int64_t _pbDimension; - - /// Table of proportion of each cluster - double * _tabProportion; - - /// free proportion ? - bool _freeProportion; - - /// model - XEMModel * _model; // not agregated - - ///modelType - XEMModelType * _modelType; - - private : - - ///filename - string _filename; - - FormatNumeric::XEMFormatNumericFile _format; -}; - -//--------------- -// inline methods -//--------------- - -inline int64_t XEMParameter::getNbCluster() const { - return _nbCluster; -} - -inline int64_t XEMParameter::getPbDimension() const { - return _pbDimension; -} - - -inline double * XEMParameter::getTabProportion() const { - return _tabProportion; -} - -inline bool XEMParameter::getFreeProportion() const { - return _freeProportion; -} - -inline XEMModel * XEMParameter::getModel() const { - return _model; -} - -inline void XEMParameter::setModel(XEMModel * iModel) { - _model = iModel; -} - -inline XEMModelType * XEMParameter::getModelType() const { - return _modelType; -} - -inline const string & XEMParameter::getFilename() const{ - return _filename; -} - -inline void XEMParameter::setFilename(const string & filename){ - _filename = filename; -} - -inline FormatNumeric::XEMFormatNumericFile XEMParameter::getFormat() const{ - return _format; -} - -inline void XEMParameter::setFormat(const FormatNumeric::XEMFormatNumericFile format){ - _format = format; -} - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMParameterDescription.cpp b/lib/src/mixmod/MIXMOD/XEMParameterDescription.cpp deleted file mode 100644 index 0760402..0000000 --- a/lib/src/mixmod/MIXMOD/XEMParameterDescription.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMParameterDescription.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#include "XEMParameterDescription.h" -#include "XEMBinaryParameter.h" -#include "XEMGaussianGeneralParameter.h" -#include "XEMBinaryEkjhParameter.h" - - -//------------ -// Constructor by default -//------------ -XEMParameterDescription::XEMParameterDescription(){ - _parameter = NULL; -} - - - -//------------------------------------- -// Constructor after an estimation->run -//-------------------------------------- -XEMParameterDescription::XEMParameterDescription(XEMEstimation* iEstimation){ - - if (iEstimation){ - _infoName = "Parameter"; - //_nbSample = iEstimation->getNbSample(); - _nbCluster = iEstimation->getNbCluster(); - _nbVariable = iEstimation->getData()->_pbDimension; - _format = FormatNumeric::defaultFormatNumericFile; - _filename = ""; - _modelType = iEstimation->getModelType(); - _parameter = iEstimation->getParameter(); - if (isBinary(_modelType->_nameModel)){ - XEMBinaryParameter * bParameter = dynamic_cast (iEstimation->getParameter()); - recopyTabToVector(bParameter->getTabNbModality(), _nbFactor, _nbCluster); - } - saveNumericValues(_filename); - } - else{ - throw nullPointerError; - } - -} - - -// --------------------------- -//constructor by initilization for Binary -// --------------------------- -XEMParameterDescription::XEMParameterDescription(int64_t nbCluster, int64_t nbVariable, vector< int64_t > nbFactor, FormatNumeric::XEMFormatNumericFile format, string filename, string infoName, XEMModelName& modelName){ - _infoName = "Parameter"; - _nbVariable = nbVariable; - _filename = filename; - _nbCluster = nbCluster; - _format = format; - _nbFactor = nbFactor; - _modelType = new XEMModelType(modelName); - ifstream fi(filename.c_str(), ios::in); - if (! fi.is_open()){ - throw wrongLabelFileName; - } - int64_t * tabNbFactor = new int64_t[_nbVariable]; - recopyVectorToTab(nbFactor, tabNbFactor); - // create _parameter : always a XEMBinaryEkjhParameter is created - _parameter = new XEMBinaryEkjhParameter(nbCluster, _nbVariable , _modelType, tabNbFactor, filename); -} - - -// ----------------------------------------- -//constructor by initilization for Gaussian -// ---------------------------------------- -XEMParameterDescription::XEMParameterDescription( int64_t nbCluster, int64_t nbVariable, FormatNumeric::XEMFormatNumericFile format, string filename, string infoName, XEMModelName& modelName){ - _infoName = "Parameter"; - _nbVariable = nbVariable; - _filename = filename; - _nbCluster = nbCluster; - _format = format; - //_nbFactor empty - _modelType = new XEMModelType(modelName); - ifstream fi(filename.c_str(), ios::in); - if (! fi.is_open()){ - throw wrongLabelFileName; - } - // create _parameter : always a XEMGaussianGeneralParameter is created - _parameter = new XEMGaussianGeneralParameter(nbCluster, _nbVariable , _modelType, filename); -} - - - -//------------ -// Desconstructor -//------------ -XEMParameterDescription::~XEMParameterDescription(){ -} - - - -//-------- -// ostream -//-------- -void XEMParameterDescription::saveNumericValues(string fileName){ - //if (_filename==""){ - ofstream fo(fileName.c_str(), ios::out); - _parameter->edit(fo); - _filename = fileName; - //} - /* else : if _fileName!="", paprameterDescription has been created by a XML file. - In this case, the numeric file already exists. - */ -} - - - diff --git a/lib/src/mixmod/MIXMOD/XEMParameterDescription.h b/lib/src/mixmod/MIXMOD/XEMParameterDescription.h deleted file mode 100644 index 580e559..0000000 --- a/lib/src/mixmod/MIXMOD/XEMParameterDescription.h +++ /dev/null @@ -1,143 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMParameterDescription.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#ifndef XEMPARAMETERDESCRIPTION_H -#define XEMPARAMETERDESCRIPTION_H - -#include "XEMUtil.h" -#include "XEMParameter.h" -#include "XEMEstimation.h" - -class XEMParameterDescription -{ - public: - /// Default constructor - XEMParameterDescription(); - - /// Constructor - XEMParameterDescription(XEMEstimation* iEstimation); - - // constructor for Binary - /// Constructor - XEMParameterDescription(int64_t nbCluster, int64_t nbVariable, vector< int64_t > nbFactor, FormatNumeric::XEMFormatNumericFile format, string filename, string infoName, XEMModelName & modelName); - - // constructor for Gaussian - /// Constructor - XEMParameterDescription(int64_t nbCluster, int64_t nbVariable, FormatNumeric::XEMFormatNumericFile format, string filename, string infoName, XEMModelName & modelName); - - /// Desconstructor - ~XEMParameterDescription(); - - /// getParameter - XEMParameter * getParameter(); - - ///getInfoName - string getInfoName(); - - ///getPbDimension - int64_t getNbVariable(); - - ///getNbCluster - int64_t getNbCluster(); - - ///getFormat - FormatNumeric::XEMFormatNumericFile getFormat(); - - ///getFilename - string getFilename(); - - ///getModelType - XEMModelType * getModelType(); - - ///getTabNbModality - vector & getTabNbFactor(); - - void saveNumericValues(string fileName=""); - - - private : - - string _infoName; - - int64_t _nbVariable; - - int64_t _nbCluster; - - FormatNumeric::XEMFormatNumericFile _format;//format of numeric file - - string _filename; - - vector _nbFactor; - - XEMModelType * _modelType; - - XEMParameter * _parameter; - -}; - -inline XEMParameter * XEMParameterDescription::getParameter(){ - if (_parameter){ - return _parameter; - } - else{ - throw nullPointerError; - } -} -inline int64_t XEMParameterDescription::getNbCluster() -{ - return _nbCluster; -} - - -inline string XEMParameterDescription::getInfoName(){ - return _infoName; -} - -inline int64_t XEMParameterDescription::getNbVariable() -{ - return _nbVariable; -} - -inline FormatNumeric::XEMFormatNumericFile XEMParameterDescription::getFormat(){ - return _format; -} - -inline string XEMParameterDescription::getFilename() -{ - return _filename; -} - -inline XEMModelType * XEMParameterDescription::getModelType() -{ - return _modelType; -} - -inline vector & XEMParameterDescription::getTabNbFactor() -{ - return _nbFactor; -} - - -#endif // XEMDATADESCRIPTION_H diff --git a/lib/src/mixmod/MIXMOD/XEMPartition.cpp b/lib/src/mixmod/MIXMOD/XEMPartition.cpp deleted file mode 100644 index 67489ee..0000000 --- a/lib/src/mixmod/MIXMOD/XEMPartition.cpp +++ /dev/null @@ -1,316 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMPartition.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMPartition.h" - - -//------------ -// Constructor -//------------ -XEMPartition::XEMPartition(){ - _nbSample = 0; - _nbCluster = 0; - _tabValue = NULL; - _deleteValues = false; - _partitionFile._fileName = ""; - _partitionFile._format = FormatNumeric::defaultFormatNumericFile; - _partitionFile._type = TypePartition::defaultTypePartition; -} - - - -//------------ -// Constructor -//------------ -XEMPartition::XEMPartition(XEMPartition * iPartition){ - _nbSample = iPartition->_nbSample; - _nbCluster = iPartition->_nbCluster; - if (iPartition->_tabValue) - _tabValue = copyTab((iPartition->_tabValue), iPartition->_nbSample, iPartition->_nbCluster); - else - _tabValue = NULL; - _partitionFile = iPartition->getPartitionFile(); - _deleteValues = true; -} - - -//----------- -//Constructor -//----------- -XEMPartition::XEMPartition(int64_t nbSample, int64_t nbCluster, const XEMNumericPartitionFile & partitionFile){ - _nbSample = nbSample; - _nbCluster = nbCluster; - _tabValue = NULL; - _partitionFile = partitionFile; - if ((_partitionFile._fileName).compare("") != 0){ - try{ - ifstream partitionFileStream((_partitionFile._fileName).c_str(), ios::in); - if (! partitionFileStream.is_open()){ - throw wrongPartitionFileName; - } - partitionFileStream>>(*this); - partitionFileStream.close(); - _deleteValues = true; - } - catch(XEMErrorType errorType){ - throw errorType; // knownPartiton catch this error - } - } -} - - - -//----------- -//Constructor -// used in DCV context -//----------- -XEMPartition::XEMPartition(XEMPartition * originalPartition, XEMCVBlock & block){ - - _nbSample = block._nbSample; - _nbCluster = originalPartition->_nbCluster; - - _tabValue = new int64_t*[_nbSample]; - int64_t ** originalTabValue= originalPartition->_tabValue ; - int64_t indexInOriginalTabValue; - for (int64_t i=0; i<_nbSample; i++){ - // _tabValue[i] = new int64_t[_nbCluster]; - indexInOriginalTabValue = block._tabWeightedIndividual[i].val; - _tabValue[i] = originalTabValue[indexInOriginalTabValue]; - // _tabValue[i] = copyTab(originalTabValue[indexInOriginalTabValue],_nbCluster); - - } - // TODO _partitionFile - _deleteValues = false ; - -} - - - -//---------- -//Destructor -//---------- -XEMPartition::~XEMPartition(){ - int64_t i; - if (_tabValue){ - - if(_deleteValues){ - for (i=0; i<_nbSample; i++){ - delete[] _tabValue[i]; - } - } - - delete[] _tabValue; - } - _tabValue = NULL; -} - - - -//-------------- -// Set attributs -//-------------- -void XEMPartition::setDimension(int64_t nbSample, int64_t nbCluster){ - _nbSample = nbSample; - _nbCluster = nbCluster; -} - - -/* return value between -1 and _nbCluster-1 - -1 : if unknown - 0.... _nbClustrer-1 else -*/ -int64_t XEMPartition::getGroupNumber(int64_t idxSample){ - int64_t res = -1; - int64_t k=0; - while (_tabValue[idxSample][k]==0 && k<_nbCluster){ - k++; - } - if (k==_nbCluster){ - res = -1; - } - else if (_tabValue[idxSample][k]==1){ - res = k; - }else throw internalMixmodError; - return res; -} - - - -//------------------------------------------- -// verify if partition is complete -// - each line has one (and only one) '1' -// - each cluster appears at least one time -//------------------------------------------- -bool XEMPartition::isComplete(){ - bool res = true; - int64_t i=0; - int64_t k; - - // each line has one (and only one '1' - int64_t compteurDe1=0; - while (i<_nbSample && res){ - compteurDe1 = 0; - for (k=0; k<_nbCluster; k++){ - if (_tabValue[i][k] == 1) - compteurDe1++; - } - if (compteurDe1 != 1){ - res = false; - } - i++; - } - - if (res){ - // each cluster appears at least one time - i=0; - int64_t nbClusterThatAppearAtLastOneTime = 0; - int64_t * tabNbOccurenceOfCluster = new int64_t[_nbCluster]; - for (k=0; k<_nbCluster; k++){ - tabNbOccurenceOfCluster[k] = 0; - for (i=0; i<_nbSample; i++){ - tabNbOccurenceOfCluster[k] += _tabValue[i][k]; - } - if (tabNbOccurenceOfCluster[k] > 0){ - nbClusterThatAppearAtLastOneTime ++; - } - } - delete [] tabNbOccurenceOfCluster; - if (nbClusterThatAppearAtLastOneTime != _nbCluster){ - res=false; - } - } - return res; - -} - - - -// ------------ -// operator == -//------------- -bool XEMPartition::operator==(XEMPartition & otherPartition){ - bool res = true; - if (_nbSample!=otherPartition._nbSample || _nbCluster!=otherPartition._nbCluster){ - cout<<_nbSample<> -//-------------------------- -ifstream & operator >> (ifstream & fi, XEMPartition & partition){ - int64_t j;/*, nbRows, indice*/; - int64_t i; - //int64_t compt = 0; - - partition._tabValue = new int64_t*[partition._nbSample]; - partition._deleteValues = true ; - for (i=0; i>partition._tabValue[i][j]; - // compt += label._tabValue[i][j]; - } - i++; - } - if (i != partition._nbSample){ - for (i=0; i(partition._tabValue, partition._nbSample, partition._nbCluster); - // End Debug - /* - if (compt == label._nbSample) - label._complete = true; - else - label._complete = false; - if (compt > label._nbSample) - throw errorInLabelInput; - */ - /* - fi>>nbRows; - - for (i=0; i>indice; - for (j=0; j>label._tabValue[indice-1][j]; - } - } - */ - - return fi; -} - - - -//------------------------- -// Friend method ostream << -//------------------------- -ostream & operator << (ostream & fo, const XEMPartition & partition){ - fo<<"\n Sample size: "<. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMPARTITION_H -#define XEMPARTITION_H - -#include "XEMUtil.h" - - -/** @brief Base class for Partition(s) - @author F Langrognet & A Echenim -*/ - -class XEMPartition{ - - public: - - /// Default constructor - XEMPartition(); - - /// Constructor - XEMPartition(XEMPartition * iPartition); - - /// Constructor - XEMPartition(int64_t nbSample, int64_t nbCluster, const XEMNumericPartitionFile & partitionFile); - - /// Constructor - // used in DCV context - XEMPartition(XEMPartition * originalPartition, XEMCVBlock & block); - - - /// Destructor - virtual ~XEMPartition(); - - - /** @brief Set the dimension of the Partition - @param nbSample The number of samples - @param nbCluster The number of clusters - */ - void setDimension(int64_t nbSample, int64_t nbCluster); - - int64_t getGroupNumber(int64_t idxSample); - - - /** verify if partition is complete - - each line has one (and only one) '1' - - each cluster appears at least one time - */ - bool isComplete(); - int64_t** getTabValue() const; - int64_t* getTabValueI(int64_t index) const; - - - ///get Format - const XEMNumericPartitionFile & getPartitionFile() const; - - /// get Number of samples - int64_t getNbSample()const; - - /// get Number of clusters - int64_t getNbCluster() const; - - bool operator==(XEMPartition & otherPartition); - - - /** @brief Friend method - @return Operator >> overloaded to read Partition from input files - */ - friend ifstream & operator >> (ifstream & fi, XEMPartition & partition); - - /** @brief Friend method - @return Operator << overloaded to write Partition - */ - friend ostream & operator << (ostream & fo, const XEMPartition & partition); - - /// Number of samples - int64_t _nbSample; - - /// Number of clusters - int64_t _nbCluster; - - int64_t ** _tabValue; // aggregate - - ///name of partition - XEMNumericPartitionFile _partitionFile; - - bool _deleteValues; - -}; - -inline int64_t ** XEMPartition::getTabValue() const{ - return _tabValue; -} - -inline int64_t * XEMPartition::getTabValueI(int64_t index) const{ - return _tabValue[index]; -} - -inline const XEMNumericPartitionFile & XEMPartition::getPartitionFile() const{ - return _partitionFile; -} - -inline int64_t XEMPartition::getNbSample()const{ - return _nbSample; -} - -inline int64_t XEMPartition::getNbCluster() const{ - return _nbCluster; -} -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMProba.cpp b/lib/src/mixmod/MIXMOD/XEMProba.cpp deleted file mode 100644 index 127fa8e..0000000 --- a/lib/src/mixmod/MIXMOD/XEMProba.cpp +++ /dev/null @@ -1,183 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMProba.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMProba.h" - - -//------------ -// Constructor -//------------ -XEMProba::XEMProba(){ - _nbCluster = 0; - _nbSample = 0; -} - - -//------------ -// Constructor -//------------ -XEMProba::XEMProba(int64_t nbSample, int64_t nbCluster){ - _nbCluster = nbCluster; - _nbSample = nbSample; - _proba.resize(_nbSample); - for (int64_t i = 0; i<_nbSample; i++){ - _proba[i].resize(_nbCluster); - } -} - - - -//------------ -// Constructor -//------------ -XEMProba::XEMProba(XEMEstimation * estimation){ - _nbCluster = estimation->getNbCluster(); - - XEMModel * model = estimation->getModel(); - if (model == NULL){ - throw internalMixmodError; - } - - // compute tabProba - //----------------- - double ** tabProba = NULL; - - XEMModelType * modelType = model->getParameter()->getModelType(); - bool binary = isBinary(modelType->_nameModel); - if (!binary){ - _nbSample = estimation->getNbSample(); - tabProba = copyTab(model->getPostProba(), _nbSample, _nbCluster); // copy - } - //// - else{ - //// - //binary case - - const vector & correspondenceOriginDataToReduceData = estimation->getcorrespondenceOriginDataToReduceData(); - _nbSample = correspondenceOriginDataToReduceData.size(); - tabProba = new double*[_nbSample]; - for (int64_t i=0; i<_nbSample; i++){ - tabProba[i] = new double[_nbCluster]; - } - int64_t nbSampleOfDataReduce = model->getNbSample(); - double ** tabPostProbaReduce = NULL; - tabPostProbaReduce = copyTab(model->getPostProba(), nbSampleOfDataReduce, _nbCluster); // copy - //editTab(tabPostProbaReduce,nbSampleOfDataReduce, _nbCluster); - // convert labelReduce, partitionReduce, postProbaReduce to label, partition, postProba - for (int64_t i=0; i<_nbSample; i++){ - for (int64_t k=0; k<_nbCluster ;k++){ - int64_t index = correspondenceOriginDataToReduceData[i]; - tabProba[i][k] = tabPostProbaReduce[index][k]; - } - } - - //delete - for (int64_t i=0; i>value; - _proba[i][k]=value; - k++; - } - if (!flux.eof() && k!=_nbCluster){ - throw notEnoughValuesInProbaInput; - } - i++; - } - if (!flux.eof() && i!=_nbSample){ - throw notEnoughValuesInProbaInput; - } -} - - diff --git a/lib/src/mixmod/MIXMOD/XEMProba.h b/lib/src/mixmod/MIXMOD/XEMProba.h deleted file mode 100644 index 8f8e51b..0000000 --- a/lib/src/mixmod/MIXMOD/XEMProba.h +++ /dev/null @@ -1,102 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMProba.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMProba_H -#define XEMProba_H -#include "XEMEstimation.h" -#include "XEMCVCriterion.h" - - - -/** @brief Base class for Label(s) - @author F Langrognet & A Echenim -*/ - -class XEMProba{ - - public: - - /// Default constructor - XEMProba(); - - /// Constructor - XEMProba(int64_t nbSample, int64_t nbCluster); - - /// Constructor - XEMProba(XEMEstimation * estimation); - - XEMProba(const XEMProba & iProba); - - /// Destructor - virtual ~XEMProba(); - - /// editProba - void edit(ostream & stream); - - /// getProba - double ** getTabProba() const; - - /// getProba - vector > getProba() const; - - /// set Proba - void setProba(double ** proba, int64_t nbSample, int64_t nbCluster); - void setProba(vector > proba); - - /// Selector - int64_t getNbSample() const; - int64_t getNbCluster() const; - - ///input stream - void input(ifstream & flux); - - private : - - /// Number of samples - int64_t _nbSample; - - /// Number of cluster - int64_t _nbCluster; - - /// dim : _nbSample *_nbCluster - vector > _proba; - -}; - - -inline vector > XEMProba::getProba() const{ - return _proba; -} - -inline int64_t XEMProba::getNbSample() const{ - return _nbSample; -} - -inline int64_t XEMProba::getNbCluster() const{ - return _nbCluster; -} - - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMProbaDescription.cpp b/lib/src/mixmod/MIXMOD/XEMProbaDescription.cpp deleted file mode 100644 index 569d3de..0000000 --- a/lib/src/mixmod/MIXMOD/XEMProbaDescription.cpp +++ /dev/null @@ -1,152 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMProbaDescription.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#include "XEMProbaDescription.h" -#include - -//------------ -// Constructor by default -//------------ -XEMProbaDescription::XEMProbaDescription() : XEMDescription(){ - _proba = NULL; -} - - -// --------------------------- -//constructor by initilization -// --------------------------- -XEMProbaDescription::XEMProbaDescription(int64_t nbSample, int64_t nbCluster, FormatNumeric::XEMFormatNumericFile format, string filename, string infoName){ - _infoName = "infoName"; - _nbSample = nbSample; - _nbColumn = nbCluster; - _fileName = filename; - _format = format; - _columnDescription.resize(nbCluster); - for (int64_t i=0; igetNbSample(); - _nbColumn = estimation->getNbCluster(); - _fileName = ""; - _format = FormatNumeric::txt; - _columnDescription.resize(_nbColumn); - for (int64_t iCol=0; iCol<_nbColumn; iCol++){ - _columnDescription[iCol] = new XEMQuantitativeColumnDescription(iCol); - string name("Probability for cluster "); - std::ostringstream sNum; - sNum << (iCol+1); - name.append(sNum.str()); - _columnDescription[iCol]->setName(name); - } - _proba = new XEMProba(estimation); - } - else{ - throw nullPointerError; - } -} - - - - - - - - -//------------ -// Constructor by copy -//------------ -XEMProbaDescription::XEMProbaDescription(XEMProbaDescription & probaDescription){ - (*this) = probaDescription; -} - - -//------------ -// operator = -//------------ -XEMProbaDescription & XEMProbaDescription::operator=( XEMProbaDescription & probaDescription){ - _fileName = probaDescription._fileName; - _format = probaDescription._format; - _infoName = probaDescription._infoName; - _nbSample = probaDescription._nbSample; - _nbColumn = probaDescription._nbColumn; - _columnDescription.resize(_nbColumn); - for (int64_t i = 0; i<_nbColumn; ++i){ - const XEMColumnDescription * cd = probaDescription.getColumnDescription(i); - _columnDescription[i] = cd->clone(); - } - _proba = new XEMProba(*(probaDescription.getProba())); - return *this; -} - - -//------------ -// Destructor -//------------ -XEMProbaDescription::~XEMProbaDescription(){ - if (_proba){ - delete _proba; - } -} - - - -//-------- -// ostream -//-------- -void XEMProbaDescription::saveNumericValues(string fileName){ - //if (_fileName==""){ - ofstream fo(fileName.c_str(), ios::out); - _proba->edit(fo); - _fileName = fileName; - //} - /* else : if _fileName!="", probaDescription has been created by a XML file. - In this case, the numeric file already exists. - */ -} - - - - - diff --git a/lib/src/mixmod/MIXMOD/XEMProbaDescription.h b/lib/src/mixmod/MIXMOD/XEMProbaDescription.h deleted file mode 100644 index 70a24ac..0000000 --- a/lib/src/mixmod/MIXMOD/XEMProbaDescription.h +++ /dev/null @@ -1,75 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMProbaDescription.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#ifndef XEMPROBADESCRIPTION_H -#define XEMPROBADESCRIPTION_H - -#include "XEMDescription.h" -#include "XEMEstimation.h" -#include "XEMProba.h" - - -class XEMProbaDescription : public XEMDescription -{ - public: - /// Default constructor - XEMProbaDescription(); - - ///constructor by initilization - XEMProbaDescription(int64_t nbSample, int64_t nbCluster, FormatNumeric::XEMFormatNumericFile format, string filename, string infoName=""); - - ///constructor after an estimation->run - XEMProbaDescription(XEMEstimation * estimation); - - - ///constructor by copy - XEMProbaDescription(XEMProbaDescription & probaDescription); - - /// Destructor - virtual ~XEMProbaDescription(); - - - ///operator= - XEMProbaDescription & operator=( XEMProbaDescription & probaDescription); - - XEMProba * getProba(); - - void saveNumericValues(string fileName=""); - - //void editProba(ostream & f) const; - - private : - - XEMProba * _proba; -}; - -inline XEMProba * XEMProbaDescription::getProba(){ - return _proba; -} - - - - -#endif // XEMPROBADESCRIPTION_H diff --git a/lib/src/mixmod/MIXMOD/XEMProbaOutput.cpp b/lib/src/mixmod/MIXMOD/XEMProbaOutput.cpp deleted file mode 100644 index 418a39e..0000000 --- a/lib/src/mixmod/MIXMOD/XEMProbaOutput.cpp +++ /dev/null @@ -1,264 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMProbaOutput.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMProbaOutput.h" - - -//------------ -// Constructor -//------------ -XEMProbaOutput::XEMProbaOutput(){ - _CVLabelAvailable = false; - _tabLabel = NULL; - _tabCVLabel = NULL; - _tabPartition = NULL; - _tabPostProba = NULL; -} - - - -//------------ -// Constructor -//------------ - -XEMProbaOutput::XEMProbaOutput(XEMEstimation * estimation){ - const vector & correspondenceOriginDataToReduceData = estimation->getcorrespondenceOriginDataToReduceData(); - - _CVLabelAvailable = false; - _tabCVLabel = NULL; - _nbCluster = estimation->getNbCluster(); - XEMModel * model = estimation->getModel(); - if (model == NULL){ - throw internalMixmodError; - } - - bool gaussian = correspondenceOriginDataToReduceData.empty(); - if (gaussian){ - // gaussian case - _nbSample = model->getNbSample(); - _tabLabel = new int64_t[_nbSample]; - _tabPartition = new int64_t *[_nbSample]; - for (int64_t i=0; i<_nbSample; i++){ - _tabPartition[i] = new int64_t[_nbCluster]; - } - model->getLabelAndPartitionByMAPOrKnownPartition(_tabLabel, _tabPartition); - _tabPostProba = copyTab(model->getPostProba(), _nbSample, _nbCluster); // copy - } - else{ - //binary case - _nbSample = correspondenceOriginDataToReduceData.size(); - _tabLabel = new int64_t[_nbSample]; - _tabPartition = new int64_t *[_nbSample]; - for (int64_t i=0; i<_nbSample; i++){ - _tabPartition[i] = new int64_t[_nbCluster]; - } - _tabPostProba = new double *[_nbSample]; - for (int64_t i=0; i<_nbSample; i++){ - _tabPostProba[i] = new double[_nbCluster]; - } - - //label et partition on reduceData - int64_t nbSampleOfDataReduce = model->getNbSample(); - int64_t ** tabPartitionReduce = new int64_t*[nbSampleOfDataReduce]; - for (int64_t i=0; igetLabelAndPartitionByMAPOrKnownPartition(tabLabelReduce, tabPartitionReduce); - - double ** tabPostProbaReduce = NULL; - tabPostProbaReduce = copyTab(model->getPostProba(), nbSampleOfDataReduce, _nbCluster); // copy - - // convert labelReduce, partitionReduce, postProbaReduce to label, partition, postProba - for (int64_t i=0; i<_nbSample; i++){ - _tabLabel[i] = tabLabelReduce[correspondenceOriginDataToReduceData[i]]; - for (int64_t k=0; k<_nbCluster ;k++){ - int64_t index = correspondenceOriginDataToReduceData[i]; - _tabPostProba[i][k] = tabPostProbaReduce[index][k]; - _tabPartition[i][k] = tabPartitionReduce[index][k]; - } - } - - //delete - for (int64_t i=0; igetNbSample(); - _nbCluster = iProbaOutput->getNbCluster(); - - _tabPostProba = copyTab(iProbaOutput->getTabPostProba(), _nbSample, _nbCluster); - _tabLabel = copyTab(iProbaOutput->getTabLabel(), _nbSample); - - _tabPartition = NULL; - _tabCVLabel = NULL; - _CVLabelAvailable = false; - -} - - - - -//----------- -// Destructor -//----------- -XEMProbaOutput::~XEMProbaOutput(){ - if (_tabLabel){ - delete[] _tabLabel; - _tabLabel = NULL; - } - - if (_tabCVLabel){ - delete[] _tabCVLabel; - _tabCVLabel = NULL; - } - - int64_t i; - if (_tabPartition){ - for (i=0; i<_nbSample; i++){ - delete[] _tabPartition[i]; - _tabPartition[i] = NULL; - } - delete [] _tabPartition; - _tabPartition = NULL; - } - - if (_tabPostProba){ - for (i=0; i<_nbSample; i++){ - delete[] _tabPostProba[i]; - _tabPostProba[i] = NULL; - } - delete [] _tabPostProba; - _tabPostProba = NULL; - } - -} - - -//----------- -// setCVLabel -//----------- -void XEMProbaOutput::setCVLabel(int64_t * CVLabel){ - _CVLabelAvailable = true; - _tabCVLabel = new int64_t[_nbSample]; - recopyTab(CVLabel,_tabCVLabel,_nbSample); -} - - - -//-------------- -// editPartition -//-------------- -void XEMProbaOutput::editPartition(ofstream & oFile){ - int64_t k, i; - - int64_t ** p_tabPartition; - int64_t * p_tabPartition_i; - - - p_tabPartition = _tabPartition; - for (i=0; i<_nbSample; i++){ - p_tabPartition_i = *p_tabPartition; - for (k=0; k<_nbCluster; k++){ - oFile << p_tabPartition_i[k] << "\t" ; - } - oFile<. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMProbaOutput_H -#define XEMProbaOutput_H -#include "XEMEstimation.h" -#include "XEMCVCriterion.h" - - - -/** @brief Base class for Label(s) - @author F Langrognet & A Echenim -*/ - -class XEMProbaOutput{ - - public: - - /// Default constructor - XEMProbaOutput(); - - /// Constructor - XEMProbaOutput(XEMEstimation * estimation); - - XEMProbaOutput(XEMProbaOutput * iProbaOutput); - - /// Destructor - virtual ~XEMProbaOutput(); - - /// setCVLabel - void setCVLabel(int64_t * CVLabel); - - /// editPartition - void editPartition(ofstream & oFile); - - /// editLabel - void editLabel(ofstream & oFile); - - /// editLabel - void editLabel(); - - /// editPostProba - void editPostProba(ofstream & oFile); - - /// editCVLabel - void editCVLabel(ofstream & oFile); - - /// Selector - int64_t * getTabLabel() const; - - /// Selector - int64_t * getTabCVLabel() const; - - /// Selector - int64_t ** getTabPartition() const; - - /// Selector - double ** getTabPostProba() const; - /// Selector - int64_t getNbSample() const; - int64_t getNbCluster() const; - ///clone - XEMProbaOutput * clone(); - - private : - - /// Number of samples - int64_t _nbSample; - - /// Number of cluster - int64_t _nbCluster; - - /// Vector of sample label (dim :_nbSample) - int64_t * _tabLabel; - - /// Yes if CV criterion - bool _CVLabelAvailable; - - /// Table of sample label from cross validation (dim :_nbSample) - int64_t * _tabCVLabel; - - /// Matrix of partition _partition(i,j)=1 if sample i in class j - /// dim : _nbSample * _nbCluster - - - //TODO RD : utiliser XEMPartition plutôt - int64_t ** _tabPartition; - - /// Matrix of posterior probabilities - /// dim : _nbSample *_nbCluster - double ** _tabPostProba; - -}; - - - - - - -//--------------- -// inline methods -//--------------- - -inline int64_t * XEMProbaOutput::getTabLabel() const{ - return _tabLabel; -} - -inline int64_t * XEMProbaOutput::getTabCVLabel() const{ - return _tabCVLabel; -} - -inline int64_t ** XEMProbaOutput::getTabPartition() const{ - return _tabPartition; -} - -inline double ** XEMProbaOutput::getTabPostProba() const{ - return _tabPostProba; -} - -inline int64_t XEMProbaOutput::getNbSample() const{ - return _nbSample; -} - -inline int64_t XEMProbaOutput::getNbCluster() const{ - return _nbCluster; -} - - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMQualitativeColumnDescription.cpp b/lib/src/mixmod/MIXMOD/XEMQualitativeColumnDescription.cpp deleted file mode 100644 index 2cca3cf..0000000 --- a/lib/src/mixmod/MIXMOD/XEMQualitativeColumnDescription.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMQualitativeColumnDescription.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#include "XEMQualitativeColumnDescription.h" - -XEMQualitativeColumnDescription::XEMQualitativeColumnDescription():XEMColumnDescription(){ -} - -XEMQualitativeColumnDescription::XEMQualitativeColumnDescription(int64_t index, int64_t nbFactor):XEMColumnDescription(index){ - _nbFactor = nbFactor; - _variableDescription.resize(nbFactor); - for (int64_t i = 0; i_index = _index; - QCD->_name = _name; - QCD->_nbFactor = _nbFactor; - - //filling of structure which describes variables - QCD->_variableDescription.resize(_variableDescription.size()); - for (int64_t i = 0; i<_variableDescription.size() ; ++i){ - VariableDescription varDescription; - varDescription.name = _variableDescription[i].name; - varDescription.num = _variableDescription[i].num; - QCD->_variableDescription[i] = varDescription; - } - return QCD; -} - -void XEMQualitativeColumnDescription::setVariableDescription(VariableDescription & variableDescription, int64_t index){ - if (index>=0 && index<_variableDescription.size()){ - _variableDescription[index].name = variableDescription.name; - _variableDescription[index].num = variableDescription.num; - } -} diff --git a/lib/src/mixmod/MIXMOD/XEMQualitativeColumnDescription.h b/lib/src/mixmod/MIXMOD/XEMQualitativeColumnDescription.h deleted file mode 100644 index bff92db..0000000 --- a/lib/src/mixmod/MIXMOD/XEMQualitativeColumnDescription.h +++ /dev/null @@ -1,73 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMQualitativeColumnDescription.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#ifndef XEMQUALITATIVECOLUMNDESCRIPTION_H -#define XEMQUALITATIVECOLUMNDESCRIPTION_H - -#include "XEMColumnDescription.h" - -//Variable Description -struct VariableDescription{ - int64_t num; - string name; -}; - - -class XEMQualitativeColumnDescription : public XEMColumnDescription -{ - public : - /// Default constructor - XEMQualitativeColumnDescription(); - - /// initialization constructor - XEMQualitativeColumnDescription(int64_t index, int64_t nbFactor); - - /// Destructor - virtual ~XEMQualitativeColumnDescription(); - - string editType(); - - XEMColumnDescription * clone()const; - - const int64_t & getNbFactor()const; - - const vector & getVariableDescription()const; - - void setVariableDescription(VariableDescription & variableDescription, int64_t index); - - private : - int64_t _nbFactor; - vector _variableDescription; -}; - -inline const int64_t & XEMQualitativeColumnDescription::getNbFactor()const{ - return _nbFactor; -} - -inline const vector & XEMQualitativeColumnDescription::getVariableDescription()const{ - return _variableDescription; -} - -#endif // XEMQUALITATIVECOLUMNDESCRIPTION_H diff --git a/lib/src/mixmod/MIXMOD/XEMQuantitativeColumnDescription.cpp b/lib/src/mixmod/MIXMOD/XEMQuantitativeColumnDescription.cpp deleted file mode 100644 index 3850601..0000000 --- a/lib/src/mixmod/MIXMOD/XEMQuantitativeColumnDescription.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMQuantitativeColumnDescription.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#include "XEMQuantitativeColumnDescription.h" - -XEMQuantitativeColumnDescription::XEMQuantitativeColumnDescription():XEMColumnDescription(){ -} - -XEMQuantitativeColumnDescription::XEMQuantitativeColumnDescription(int64_t index):XEMColumnDescription(index){ -} - -XEMQuantitativeColumnDescription::~XEMQuantitativeColumnDescription(){ - -} - -string XEMQuantitativeColumnDescription::editType(){ - return "Quantitative"; -} - -XEMColumnDescription * XEMQuantitativeColumnDescription::clone()const{ - XEMQuantitativeColumnDescription * QCD = new XEMQuantitativeColumnDescription(); - QCD->_index = _index; - QCD->_name = _name; - return QCD; -} diff --git a/lib/src/mixmod/MIXMOD/XEMQuantitativeColumnDescription.h b/lib/src/mixmod/MIXMOD/XEMQuantitativeColumnDescription.h deleted file mode 100644 index 8b4f89c..0000000 --- a/lib/src/mixmod/MIXMOD/XEMQuantitativeColumnDescription.h +++ /dev/null @@ -1,48 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMQuantitativeColumnDescription.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#ifndef XEMQUANTITATIVECOLUMNDESCRIPTION_H -#define XEMQUANTITATIVECOLUMNDESCRIPTION_H - -#include "XEMColumnDescription.h" - -class XEMQuantitativeColumnDescription : public XEMColumnDescription -{ - public : - /// Default constructor - XEMQuantitativeColumnDescription(); - - /// initialization constructor - XEMQuantitativeColumnDescription(int64_t index); - - /// Destructor - virtual ~XEMQuantitativeColumnDescription(); - - string editType(); - - XEMColumnDescription * clone()const; -}; - -#endif // XEMQUANTITATIVECOLUMNDESCRIPTION_H diff --git a/lib/src/mixmod/MIXMOD/XEMRandom.cpp b/lib/src/mixmod/MIXMOD/XEMRandom.cpp deleted file mode 100644 index 49b9ecc..0000000 --- a/lib/src/mixmod/MIXMOD/XEMRandom.cpp +++ /dev/null @@ -1,103 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMRandom.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -/* - Tiny Encryption Algorithm - ------------------------- -*/ - - -#include "XEMRandom.h" /* prototypes */ -#include /* time_t */ -#include - - - - - -/* Modification de l'implementation de l'algo pour être portable 32-64 bits, ...*/ - -const double m = 4294967296.0; -/*const uint32_t d = 2654435769U; - const uint32_t k0 = 3352799412U; - const uint32_t k1 = 2596254646U; - const uint32_t k2 = 1943803523U; - const uint32_t k3 = 397917763U; - - uint32_t y = 123456789U; - uint32_t z = 987654321U; -*/ -const uint32_t d = 0x09E3779B9L; -const uint32_t k0 = 0x0C7D7A8B4L; -const uint32_t k1 = 0x09ABFB3B6L; -const uint32_t k2 = 0x073DC1683L; -const uint32_t k3 = 0x017B7BE43L; - -uint32_t y = 123456789L; -uint32_t z = 987654321L; - - -// Return a value in [0...1[ // -double rnd() -{ - uint32_t s = 0; - uint32_t n = 8; - while (n-- > 0) { - s += d; - y += (z << 4) + k0 ^ z + s ^ (z >> 5) + k1; - z += (y << 4) + k2 ^ y + s ^ (y >> 5) + k3; - } - return (z + y / m) / m; -} - -int64_t flip(double x) -{ - return (rnd() <= x); -} - -void antiRandomise() -{ - z = 0; - y = 0; - rnd(); -} - -// Init random seed // -void randomise() -{ - timeb q; - ftime(&q); - z = (uint32_t) q.millitm; - y = (uint32_t) q.time; - rnd(); -} - -// User controlled initialization of the random state -void setSeed(const uint32_t yState, const uint32_t zState) -{ - y = yState; - z = zState; - rnd(); -} diff --git a/lib/src/mixmod/MIXMOD/XEMRandom.h b/lib/src/mixmod/MIXMOD/XEMRandom.h deleted file mode 100644 index 6aee3d8..0000000 --- a/lib/src/mixmod/MIXMOD/XEMRandom.h +++ /dev/null @@ -1,36 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMRandom.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef random_h -#define random_h - -#include - -extern double rnd(); -extern int64_t flip(double x); -extern void randomise(); -extern void antiRandomise(); -// ADDED BY OTMIXMOD -extern void setSeed(const uint32_t yState, const uint32_t zState); -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMSEMAlgo.cpp b/lib/src/mixmod/MIXMOD/XEMSEMAlgo.cpp deleted file mode 100644 index 68b1910..0000000 --- a/lib/src/mixmod/MIXMOD/XEMSEMAlgo.cpp +++ /dev/null @@ -1,140 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMSEMAlgo.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#include "XEMSEMAlgo.h" - - -//------------ -// Constructor -//------------ -XEMSEMAlgo::XEMSEMAlgo(){ - _algoStopName = NBITERATION; -} - - - -/// Copy constructor -XEMSEMAlgo::XEMSEMAlgo(const XEMSEMAlgo & semAlgo):XEMAlgo(semAlgo){ -} - - -//------------ -// Constructor -//------------ -XEMSEMAlgo::XEMSEMAlgo(XEMAlgoStopName algoStopName, int64_t nbIteration) - :XEMAlgo(algoStopName, defaultEpsilon, nbIteration){ -} - - - -//---------- -//Destructor -//---------- -XEMSEMAlgo::~XEMSEMAlgo(){ -} - - - -// clone -//------ -XEMAlgo * XEMSEMAlgo::clone(){ - return (new XEMSEMAlgo(*this)); -} - - -void XEMSEMAlgo::setAlgoStopName(XEMAlgoStopName * algoStopName){ - throw internalMixmodError; -} - - -//---------------- -// setNbIteration -//---------------- -void XEMSEMAlgo::setNbIteration(int64_t nbIteration){ - if (nbIterationmaxNbIteration){ - throw nbIterationTooLarge; - } - else{ - _nbIteration = nbIteration; - } -} - - - -//--- -//run -//--- -void XEMSEMAlgo::run(XEMModel *& model){ - model->setAlgoName(SEM); - -#if DEBUG > 0 - cout<<"Debut de l'Algo SEM :"<editDebugInformation(); -#endif - - - _indexIteration = 1 ; - // 1rst SEM : to initialize bestModel and bestLL - model->Estep(); // E Step - model->Sstep(); // S Step - model->Mstep(); // M Step -#if DEBUG > 0 - cout<<"Apres la 1ere iteration de SEM :"<editDebugInformation(); -#endif - XEMModel * bestModel = new XEMModel(model); - double bestLL = bestModel->getLogLikelihood(true); // true : to update fik - - // others iterations - _indexIteration++; - double lastLL; - while (_indexIteration <= _nbIteration){ - model->Estep(); // E Step - model->Sstep(); // S Step - model->Mstep(); // M Step -#if DEBUG > 0 - cout<<"Apres la "<<_indexIteration<<" eme iteration de SEM :"<editDebugInformation(); -#endif - // select Best Model - lastLL = model->getLogLikelihood(true); // true : to compute fik - if (lastLL > bestLL){ -#if DEBUG > 0 - cout<<"BestModel prend la valeur de LastModel"<Estep(); // E step to update Tik and fik - // update model (to output) - model = bestModel; -} diff --git a/lib/src/mixmod/MIXMOD/XEMSEMAlgo.h b/lib/src/mixmod/MIXMOD/XEMSEMAlgo.h deleted file mode 100644 index 3d2267f..0000000 --- a/lib/src/mixmod/MIXMOD/XEMSEMAlgo.h +++ /dev/null @@ -1,81 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMSEMAlgo.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMSEMALGO_H -#define XEMSEMALGO_H - -#include "XEMAlgo.h" - -/** - @brief Derived class of XEMAlgo for SEM Algorithm(s) - @author F Langrognet & A Echenim -*/ - -class XEMSEMAlgo : public XEMAlgo{ - - public: - - /// Default constructor - XEMSEMAlgo(); - - /// Copy constructor - XEMSEMAlgo(const XEMSEMAlgo & semAlgo); - - /// Constructor - XEMSEMAlgo(XEMAlgoStopName algoStopName, int64_t nbIteration); - - /// Destructor - virtual ~XEMSEMAlgo(); - - /// clone - XEMAlgo * clone(); - - /// Run method - void run(XEMModel *& model); - - const XEMAlgoName getAlgoName() const; - - - void setAlgoStopName(XEMAlgoStopName * algoStopName); - - void setNbIteration(int64_t nbIteration); - - void setEpsilon(double epsilon); - - const double getEpsilon() const; -}; - -inline const XEMAlgoName XEMSEMAlgo::getAlgoName() const{ - return SEM; -} - -inline const double XEMSEMAlgo::getEpsilon() const{ - throw internalMixmodError; -} - -inline void XEMSEMAlgo::setEpsilon(double eps){ - throw internalMixmodError; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMSample.cpp b/lib/src/mixmod/MIXMOD/XEMSample.cpp deleted file mode 100644 index 70cbb08..0000000 --- a/lib/src/mixmod/MIXMOD/XEMSample.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMSample.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#include "XEMSample.h" - - -//------------ -// Constructor -//------------ -XEMSample::XEMSample(){ - _pbDimension = 0; -} - - - -//------------ -// Constructor -//------------ -XEMSample::XEMSample(XEMSample * iSample){ - _pbDimension = iSample->getPbDimension(); -} - - - -//------------ -// Constructor -//------------ -XEMSample::XEMSample(int64_t pbDimension){ - _pbDimension = pbDimension; -} - - - -//----------- -// Destructor -//----------- -XEMSample::~XEMSample(){ -} - - diff --git a/lib/src/mixmod/MIXMOD/XEMSample.h b/lib/src/mixmod/MIXMOD/XEMSample.h deleted file mode 100644 index 4b1f1be..0000000 --- a/lib/src/mixmod/MIXMOD/XEMSample.h +++ /dev/null @@ -1,68 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMSample.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMSample_H -#define XEMSample_H - -#include "XEMUtil.h" - - -/** - @brief Base class for Sample - @author F Langrognet & A Echenim -*/ - -class XEMSample{ - - public : - - /// Constructor - XEMSample(); - - /// Constructor - XEMSample(XEMSample * iSample); - - /// Constructor - XEMSample(int64_t pbDimension); - - /// Destructor - virtual ~XEMSample(); - - /// Selector - int64_t getPbDimension(); - - protected : - - /// Problem dimension - int64_t _pbDimension; - -}; - -inline int64_t XEMSample::getPbDimension(){ - return _pbDimension; -} - - -#endif - diff --git a/lib/src/mixmod/MIXMOD/XEMSelection.cpp b/lib/src/mixmod/MIXMOD/XEMSelection.cpp deleted file mode 100644 index 2dbafc0..0000000 --- a/lib/src/mixmod/MIXMOD/XEMSelection.cpp +++ /dev/null @@ -1,422 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMSelection.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#include "XEMSelection.h" -#include "XEMBICCriterion.h" -#include "XEMCVCriterion.h" -#include "XEMICLCriterion.h" -#include "XEMNECCriterion.h" -#include "XEMDCVCriterion.h" -#include "XEMError.h" -#include "XEMUtil.h" - - -//------------ -// Constructor -//------------ -XEMSelection::XEMSelection(){ - _tabEstimation = NULL; - _criterion = NULL; - _criterionName = UNKNOWN_CRITERION_NAME; - _errorType = noError; - _tabCriterionValueForEachEstimation = NULL; - _tabCriterionErrorForEachEstimation = NULL; - _CVLabelOfEachEstimation = NULL; -} - - - -//------------ -// Constructor -//------------ -XEMSelection::XEMSelection(XEMCriterionName criterionName, XEMEstimation **& tabEstimation, - int64_t nbEstimation, XEMClusteringInput * input){ - - _tabEstimation = tabEstimation; - _nbEstimation = nbEstimation; - _criterionName = criterionName; - - _CVLabelOfEachEstimation = new int64_t*[_nbEstimation]; - _tabCriterionValueForEachEstimation = new double[_nbEstimation]; - _tabCriterionErrorForEachEstimation = new XEMErrorType[_nbEstimation]; - - if (_criterionName == DCV){ - throw XEMDAInput; - //TODO _nbCriterion = 1; - //TODO _criterion = new XEMDCVCriterion(tabEstimation, nbEstimation, input); - } - else{ - int64_t i; - switch (_criterionName) { - case BIC : _criterion = new XEMBICCriterion(); break; - case CV : - throw XEMDAInput; - //_tabCriterion[i] = new XEMCVCriterion(input); break; - case ICL : _criterion = new XEMICLCriterion(); break; - case NEC : _criterion = new XEMNECCriterion(); break; - case UNKNOWN_CRITERION_NAME : exit(1);break; - default : throw internalMixmodError; - } - } - - _errorType = noError; -} - -XEMSelection::XEMSelection(XEMCriterionName criterionName, XEMEstimation **& tabEstimation, - int64_t nbEstimation, XEMOldInput * input){ - - _tabEstimation = tabEstimation; - _nbEstimation = nbEstimation; - _criterionName = criterionName; - - _CVLabelOfEachEstimation = new int64_t*[_nbEstimation]; - _tabCriterionValueForEachEstimation = new double[_nbEstimation]; - _tabCriterionErrorForEachEstimation = new XEMErrorType[_nbEstimation]; - - if (_criterionName == DCV){ - _criterion = new XEMDCVCriterion(tabEstimation, nbEstimation, input); - } - else{ - int64_t i; - switch (_criterionName) { - case BIC : _criterion = new XEMBICCriterion(); break; - case CV :_criterion = new XEMCVCriterion(input); break; - case ICL : _criterion = new XEMICLCriterion(); break; - case NEC : _criterion = new XEMNECCriterion(); break; - case UNKNOWN_CRITERION_NAME : exit(1);break; - default : throw internalMixmodError; - } - } - - _errorType = noError; -} - - -//----------- -// Destructor -//----------- -XEMSelection::~XEMSelection(){ - int64_t i; - if (_criterion) { - delete _criterion; - _criterion = NULL; - } - - if (_tabCriterionValueForEachEstimation){ - delete [] _tabCriterionValueForEachEstimation; - } - if (_tabCriterionErrorForEachEstimation){ - delete [] _tabCriterionErrorForEachEstimation; - } -} - - - -//--------------------------- -// getCVLabelOfBestEstimation -//--------------------------- -int64_t * XEMSelection::getCVLabelOfBestEstimation(){ - if ((_criterionName == CV ) || (_criterionName == DCV)){ - return _CVLabelOfEachEstimation[_bestIndexEstimation];; - } - else{ - throw internalMixmodError; - } -} - - - - -//--------- -//set error -//--------- -void XEMSelection::setErrorType(XEMErrorType errorType){ - _errorType = errorType; -} - - - -//-------------------------------------- -// getCriterionErrorType for estimation -//------------------------------------- -XEMErrorType XEMSelection::getCriterionErrorType(XEMEstimation *& estimation){ - int64_t i = 0; - bool continu = true; - while (i<_nbEstimation && continu){ - if (estimation == _tabEstimation[i]){ - continu = false; - } - else{ - i++; - } - } - if (continu) - throw internalMixmodError; - - return _tabCriterionErrorForEachEstimation[i]; -} - - - -//-------------------------------------- -// getCriterionErrorType for jth estimation -//------------------------------------- -XEMErrorType XEMSelection::getCriterionErrorType(int64_t j){ - if (j<0 || j>=_nbEstimation){ - throw internalMixmodError; - } - else{ - return _tabCriterionErrorForEachEstimation[j]; - } - -} - - - -//--------------------------------- -// getCriterionValue for estimation -//---------------------------------- -double XEMSelection::getCriterionValue(XEMEstimation *& estimation){ - int64_t i = 0; - bool continu = true; - while (i<_nbEstimation && continu){ - if (estimation == _tabEstimation[i]){ - continu = false; - } - else{ - i++; - } - } - if (continu) - throw internalMixmodError; - - return _tabCriterionValueForEachEstimation[i]; -} - - -//---------------------- -// getBestCriterionValue -//----------------------- -double XEMSelection::getBestCriterionValue(){ - double res = 0.0; - - if (_bestIndexEstimation >=0 && _bestIndexEstimation <_nbEstimation){ - res = _tabCriterionValueForEachEstimation[_bestIndexEstimation]; - } - else - throw internalMixmodError; - - return res; -} - - - - -//--- -//run -//--- -void XEMSelection::run(bool quiet){ - - //verify that all estimation have error - int64_t nbEstimationError = 0; - int64_t i; - for (i=0; i<_nbEstimation; i++){ - if (_tabEstimation[i]->getErrorType() != noError){ - nbEstimationError++; - } - } - if (nbEstimationError == _nbEstimation){ - _errorType = errorAllEstimation; - throw errorAllEstimation; - } - - - //------------------ - // CV, NEC, BIC, ICL - //------------------ - if (_criterionName != DCV){ - int64_t todo; - - // printing ... - if(!quiet){ - - switch (_criterionName) { - case BIC : cout << "BIC |" << flush; break; - case CV : cout << "CV |" << flush; break; - case ICL : cout << "ICL |" << flush; break; - case NEC : cout << "NEC |" << flush; break; - case UNKNOWN_CRITERION_NAME : exit(1);break; - default : throw internalMixmodError; - } - todo = _nbEstimation; - while(todo){ - cout << " " << flush; - todo--; - } - cout << "|" << flush; - todo = _nbEstimation+1; - while(todo){ - cout << "\b" << flush; - todo--; - } - } - - XEMModel * model = NULL; - double value; - // update criteria - for (i=0; i<_nbEstimation; i++){ - if(!quiet) printShortcutModelType(_tabEstimation[i]->getModelType()); - - if (_tabEstimation[i]->getErrorType() == noError){ - model = _tabEstimation[i]->getModel(); // the best model - - // Criterion : run - try{ - if ((_criterionName==CV) & (_errorType != noSelectionError)) { - XEMCVCriterion * cvCriterion = dynamic_cast(_criterion); - cvCriterion->run(model, _tabCriterionValueForEachEstimation[i], _CVLabelOfEachEstimation[i], _tabCriterionErrorForEachEstimation[i], quiet); - } - else{ - _criterion->run(model, _tabCriterionValueForEachEstimation[i], _tabCriterionErrorForEachEstimation[i], quiet); - } - } - catch(XEMErrorType errorType){ - //_tabCriterion[i]->setErrorType(errorType); - _tabCriterionErrorForEachEstimation[i] = errorType; - } - catch (Exception){ - //_tabCriterion[i]->setErrorType(numericError); - _tabCriterionErrorForEachEstimation[i] = internalMixmodError; - } - } - else { - //_tabCriterion[i]->setErrorType(_tabEstimation[i]->getErrorType()); - _tabCriterionErrorForEachEstimation[i] = _tabEstimation[i]->getErrorType(); - _tabCriterionValueForEachEstimation[i] = 0; - } - if(!quiet) cout << "\b-" << flush; - } - // Select the best Estimation - selectBestEstimation(); - - } - - - else{ - //---- - //DCV - //---- - - if (!quiet){ - cout << "DCV " << flush<run - //try{ - - // todo : quiet en option du run - double value = 0; // TODO a enlever - XEMErrorType error = noError; // TODO a enlever - dcvCriterion->run(NULL, value, error, quiet); - - for (i=0; i<_nbEstimation; i++){ - _tabCriterionValueForEachEstimation[i] = (dcvCriterion->getTabCriterionValueForEachEstimation())[i]; - _tabCriterionErrorForEachEstimation[i] = (dcvCriterion->getTabCriterionErrorForEachEstimation())[i]; - } - _bestIndexEstimation = dcvCriterion->getBestIndexEstimation(); - - /*for (i=0; i<_nbEstimation; i++){ - cout<<"cv value for "<setErrorType(errorType); - } - catch (Exception){ - _tabCriterion[0]->setErrorType(numericError); - } - */ - //update _CVLabelOfBestEstimation : NON fait car on n'estime pas les labels de tous les individus pour la meilleur estimation (il faudrait relancer un CV si on voulait l'info) - /*if (_criterionType==DCV){ - copyTab(_CVLabelOfBestEstimation, _tabCriterion[0]->getCVLabelOfBestEstimation(), _nbSample); - }*/ - } - - -} - - - -//--------------------- -// selectBestEstimation -//--------------------- -void XEMSelection::selectBestEstimation(){ - - int64_t i = 0; - double valueMin, valueTmp; - _bestIndexEstimation = -1; - - valueMin = 0.0; - // is there an criterion with no error - while (i<_nbEstimation && _bestIndexEstimation==-1){ - if (_tabCriterionErrorForEachEstimation[i] == noError){ - _bestIndexEstimation = i; - valueMin = _tabCriterionValueForEachEstimation[i]; - } - i++; - } - - if (_bestIndexEstimation == -1){ - _errorType = noSelectionError; - } - else{ - for (i=_bestIndexEstimation+1; i<_nbEstimation; i++){ - if (_tabCriterionErrorForEachEstimation[i] == noError){ - valueTmp = _tabCriterionValueForEachEstimation[i]; - if (valueTmp < valueMin){ - // if this Estimation is better - valueMin = valueTmp; - _bestIndexEstimation= i; - } - else if (valueTmp == valueMin){ - // the model with less parameter is choosen - int64_t freeParameter = _tabEstimation[i]->getModel()->getFreeParameter(); - int64_t freeParameter2 = _tabEstimation[_bestIndexEstimation]->getModel()->getFreeParameter(); - if (freeParameter < freeParameter2){ - // if this Estimation is better - _bestIndexEstimation = i; - } - } - } - } - } -} - diff --git a/lib/src/mixmod/MIXMOD/XEMSelection.h b/lib/src/mixmod/MIXMOD/XEMSelection.h deleted file mode 100644 index cc90b50..0000000 --- a/lib/src/mixmod/MIXMOD/XEMSelection.h +++ /dev/null @@ -1,171 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMSelection.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMSELECTION_H -#define XEMSELECTION_H - - -#include "XEMUtil.h" -#include "XEMCriterion.h" -#include "XEMEstimation.h" -#include "XEMClusteringInput.h" - -/** - @brief Base class for Selection(s) - @author F Langrognet & A Echenim -*/ - -class XEMSelection{ - - public: - - /// Default Constructor - XEMSelection(); - - /// Constructor - XEMSelection(XEMCriterionName criterionName, XEMEstimation **& tabEstimation, int64_t nbEstimation, XEMClusteringInput * input); - - /// Constructor - XEMSelection(XEMCriterionName criterionName, XEMEstimation **& tabEstimation, int64_t nbEstimation, XEMOldInput * input); - - /// Destructor - virtual ~XEMSelection(); - - - /** @brief Selector - @return The type of the current criterion - */ - XEMCriterionName getCriterionName(); - - /** @brief Set the error type criterion - @param errorType Type of error to set - */ - void setErrorType(XEMErrorType errorType); - - /** @brief Selector - @return The type of the error - */ - XEMErrorType getErrorType(); - - /// getBestIndexEstimation - int64_t getBestIndexEstimation(); - - /// getCriterionErrorType for estimation - XEMErrorType getCriterionErrorType(XEMEstimation *& estimation); - - /// getCriterionErrorType for jth estimation - XEMErrorType getCriterionErrorType(int64_t j); - - /// getCriterionValue for estimation - double getCriterionValue(XEMEstimation *& estimation); - - /// getBestCriterionValue - double getBestCriterionValue(); - - /// getCriterion - XEMCriterion * getCriterion(); - - - /// getCVLabel of the best Estimation - int64_t * getCVLabelOfBestEstimation(); - - XEMErrorType * getTabCriterionErrorForEachEstimation(); - - double * getTabCriterionValueForEachEstimation(); - - /// Run method - void run(bool quiet=true); - - - - private : - - /// Select the best estimation - void selectBestEstimation(); - - - - /// Best index in _tabEstimation for best estimation - int64_t _bestIndexEstimation; - - /// Name of the current criterion - XEMCriterionName _criterionName; - - /// Number of estimation - int64_t _nbEstimation; - - /// Table of estimation - XEMEstimation ** _tabEstimation; - - - - /// XEMCriterion - XEMCriterion * _criterion; // aggregate - - - /// - double * _tabCriterionValueForEachEstimation; - /// - XEMErrorType * _tabCriterionErrorForEachEstimation; - - - /// Current error : if all criterion have error - XEMErrorType _errorType; - - - /// int64_t ** CV label of each estimation (only in cv or dcv configuration) - int64_t ** _CVLabelOfEachEstimation; - - /// int64_t * CV label of best estimation (only in cv or dcv configuration) - int64_t * _CVLabelOfBestEstimation; - -}; - - - -inline XEMCriterionName XEMSelection::getCriterionName(){ - return _criterionName; -} - -inline XEMErrorType XEMSelection::getErrorType(){ - return(_errorType); -} - -inline int64_t XEMSelection::getBestIndexEstimation(){ - return _bestIndexEstimation; -} - -inline XEMCriterion * XEMSelection::getCriterion(){ - return _criterion; -} - -inline XEMErrorType * XEMSelection::getTabCriterionErrorForEachEstimation(){ - return _tabCriterionErrorForEachEstimation; -} - -inline double * XEMSelection::getTabCriterionValueForEachEstimation(){ - return _tabCriterionValueForEachEstimation; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMSphericalMatrix.cpp b/lib/src/mixmod/MIXMOD/XEMSphericalMatrix.cpp deleted file mode 100644 index c7f1d38..0000000 --- a/lib/src/mixmod/MIXMOD/XEMSphericalMatrix.cpp +++ /dev/null @@ -1,327 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMSphericalMatrix.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#include "XEMSphericalMatrix.h" -#include "XEMGeneralMatrix.h" -#include "XEMSymmetricMatrix.h" -#include "XEMDiagMatrix.h" -#include "XEMUtil.h" - -//------------ -// Constructor -//------------ -XEMSphericalMatrix::XEMSphericalMatrix(){ - throw wrongConstructorType; -} - - -XEMSphericalMatrix::XEMSphericalMatrix(int64_t pbDimension, double initValue):XEMMatrix(pbDimension){ - _store = initValue; -} - -XEMSphericalMatrix::XEMSphericalMatrix(XEMSphericalMatrix * A):XEMMatrix(A){ - _store = A->getStore(); -} - - -//---------- -//Destructor -//---------- -XEMSphericalMatrix::~XEMSphericalMatrix(){ -} - - - - - - -double XEMSphericalMatrix::determinant(XEMErrorType errorType){ - double det; - det = pow(_store, (double)_s_pbDimension); - if(det < minDeterminantValue){ - throw errorType; - } - return det; -} - -double* XEMSphericalMatrix::getDiagonalStore(){ - throw wrongMatrixType; -} - - -double* XEMSphericalMatrix::getSymmetricStore(){ - throw wrongMatrixType; -} - -double* XEMSphericalMatrix::getGeneralStore(){ - throw wrongMatrixType; -} - -double XEMSphericalMatrix::getSphericalStore(){ - return(_store); -} - -void XEMSphericalMatrix::computeSVD(XEMDiagMatrix* & S, XEMGeneralMatrix* & O){ - throw nonImplementedMethod; -} - - -void XEMSphericalMatrix::equalToMatrixMultiplyByDouble(XEMMatrix* D, double d){ - //throw nonImplementedMethod; - double store_D = D->putSphericalValueInStore(_store); - _store= store_D*d; -} - - -void XEMSphericalMatrix::inverse(XEMMatrix * & Inv){ - - /*1. - if (Inv == NULL){ - Inv = new XEMSphericalMatrix(_s_pbDimension); - } - else{ - if (typeof(Inv) != XEMSphericalMatrix){ - delete Inv; - Inv = new XEMSphericalMatrix(_s_pbDimension); - } - } - */ - - if (Inv == NULL){ - Inv = new XEMSphericalMatrix(_s_pbDimension); - } - - // Inv = new XEMSphericalMatrix(_s_pbDimension); - double store_Inv = 1.0 / _store;// = A->getSphericalStore(); - Inv->setSphericalStore(store_Inv); // virtual -} - -void XEMSphericalMatrix::compute_product_Lk_Wk(XEMMatrix* Wk, double L){ - throw nonImplementedMethod; -} - -double XEMSphericalMatrix::computeTrace(){ - double trace = _s_pbDimension * _store; - return trace; -} - - - -void XEMSphericalMatrix::addToValue(double a){ - _store += a; -} - -double XEMSphericalMatrix::norme(double * xMoinsMean){ - int64_t p; - double termesDiag = 0.0; - double xMoinsMean_p; - - for(p=0 ; p<_s_pbDimension ; p++){ - xMoinsMean_p = xMoinsMean[p]; - termesDiag += xMoinsMean_p * xMoinsMean_p ; - } - termesDiag *= _store; - return termesDiag; - -} - - -// (this) will be A / d -void XEMSphericalMatrix::equalToMatrixDividedByDouble(XEMMatrix * A, double d){ - _store = (A->getSphericalStore()) / d; -} - - -void XEMSphericalMatrix::compute_as__multi_O_S_O(double multi, XEMGeneralMatrix* & O, XEMDiagMatrix *& S){ - throw nonImplementedMethod; -} -double XEMSphericalMatrix::trace_this_O_Sm1_O(XEMGeneralMatrix* & O, XEMDiagMatrix* & S){ - throw nonImplementedMethod; -} -double XEMSphericalMatrix::compute_trace_W_C(XEMMatrix * C){ - throw nonImplementedMethod; -} -void XEMSphericalMatrix::computeShape_as__diag_Ot_this_O(XEMDiagMatrix* & Shape, XEMGeneralMatrix* & Ori, double diviseur){ - throw nonImplementedMethod; -} - - - - - - - - - -// add : cik * xMoinsMean * xMoinsMean' to this -void XEMSphericalMatrix::add(double * xMoinsMean, double cik){ - - int64_t p; - double xMoinsMean_p, tmp; - - tmp = 0.0; - for(p=0; p<_s_pbDimension ; p++){ - xMoinsMean_p = xMoinsMean[p]; - tmp += xMoinsMean_p * xMoinsMean_p; - }//end for p - - _store += tmp / _s_pbDimension * cik; - -} - -// add : diag( cik * xMoinsMean * xMoinsMean' ) to this -void XEMSphericalMatrix::addDiag(double * xMoinsMean, double cik){ - - int64_t p; - double xMoinsMean_p, tmp; - - tmp = 0.0; - for(p=0; p<_s_pbDimension ; p++){ - xMoinsMean_p = xMoinsMean[p]; - tmp += xMoinsMean_p * xMoinsMean_p; - }//end for p - - _store += tmp / _s_pbDimension * cik; - -} - - -// set the value of (d x Identity) to this -void XEMSphericalMatrix::operator=(const double& d){ - _store = d; -} - -// divide each element by d -void XEMSphericalMatrix::operator/=(const double& d){ - _store /=d; -} - - -// multiply each element by d -void XEMSphericalMatrix::operator*=(const double& d){ - _store *=d; -} - - - -//add M to this -void XEMSphericalMatrix::operator+=(XEMMatrix* M){ - M->addSphericalValueInStore(_store); -} - -void XEMSphericalMatrix::operator=(XEMMatrix* M){ - M->putSphericalValueInStore(_store); -} - - -double XEMSphericalMatrix::putSphericalValueInStore(double & store){ - store = _store; - return(store); -} - -double XEMSphericalMatrix::addSphericalValueInStore(double & store){ - store += _store; - return(store); -} - -double* XEMSphericalMatrix::putDiagonalValueInStore(double * store){ - throw wrongMatrixType; -} - -double* XEMSphericalMatrix::addDiagonalValueInStore(double * store){ - throw wrongMatrixType; -} - -double* XEMSphericalMatrix::putSymmetricValueInStore(double * store){ - throw wrongMatrixType; -} - -double* XEMSphericalMatrix::addSymmetricValueInStore(double * store){ - throw wrongMatrixType; -} - - - -double* XEMSphericalMatrix::putGeneralValueInStore(double * store){ - throw wrongMatrixType; -} - -double* XEMSphericalMatrix::addGeneralValueInStore(double * store){ - throw wrongMatrixType; -} - - - -void XEMSphericalMatrix::input(ifstream & fi){ - int64_t p,q; - double garbage; - - for (p=0; p<_s_pbDimension; p++){ - // useless because all are 0 - for (q=0; q<_s_pbDimension; q++){ - if (p==0 && q==0){ - fi >> _store; - } - else{ - fi >> garbage; - } - } - } - -} - -double XEMSphericalMatrix::detDiag(XEMErrorType errorType){ - return determinant(errorType); -} - - - -double** XEMSphericalMatrix::storeToArray() const{ - - int64_t i,j; - double** newStore = new double*[_s_pbDimension]; - for (i=0; i<_s_pbDimension ; ++i){ - newStore[i] = new double[_s_pbDimension]; - - for (j=0; j<_s_pbDimension ; ++j){ - if (i == j){ - newStore[i][j] = _store; - } - else { - newStore[i][j] = 0; - } - } - } - - return newStore; - -} - - - - - - - diff --git a/lib/src/mixmod/MIXMOD/XEMSphericalMatrix.h b/lib/src/mixmod/MIXMOD/XEMSphericalMatrix.h deleted file mode 100644 index 8da2e5e..0000000 --- a/lib/src/mixmod/MIXMOD/XEMSphericalMatrix.h +++ /dev/null @@ -1,172 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMSphericalMatrix.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMSPHERICALMATRIX_H -#define XEMSPHERICALMATRIX_H - -#include "XEMUtil.h" -#include "XEMMatrix.h" -#include "XEMGeneralMatrix.h" - -/** - @brief class XEMSphericalMatrix - @author F Langrognet & A Echenim -*/ - -class XEMSphericalMatrix : public XEMMatrix{ - - public: - - /// Default constructor - XEMSphericalMatrix(); - - /// contructor - /// default initialisation : Id - XEMSphericalMatrix(int64_t pbDimension, double initValue=1.0); - - XEMSphericalMatrix(XEMSphericalMatrix * A); - - /// Desctructor - virtual ~XEMSphericalMatrix(); - - /// compute determinant of spherical matrix - double determinant(XEMErrorType errorType); - - /// return store of spherical matrix - double getStore(); - - - /// inverse spherical matrix - void inverse(XEMMatrix * & A); - - void compute_product_Lk_Wk(XEMMatrix* Wk, double L); - - /// add a to the value of this - void addToValue(double a); - - /// compute (x - mean)' this (x - mean) - double norme(double * xMoinsMean); - - /// (this) will be A / d - void equalToMatrixDividedByDouble(XEMMatrix * A, double d); - - /// (this) will be A * d - void equalToMatrixMultiplyByDouble(XEMMatrix*D, double d); - - /// compute trace of spherical matrix - double computeTrace(); - - - /// add : cik * xMoinsMean * xMoinsMean' to this - void add(double * xMoinsMean, double cik); - - /// add : diag( cik * xMoinsMean * xMoinsMean' ) to this - void addDiag(double * xMoinsMean, double cik); - - /// this = d * Identity - void operator=(const double& d); - - /// this = this / (d * Identity) - void operator/=(const double& d); - - /// this = this * (d * Identity) - void operator*=(const double& d); - /// this = this + matrix - void operator+=(XEMMatrix* M); - /// this = matrix - void operator=(XEMMatrix* M); - - - /// read spherical matrix store in file - void input(ifstream & fi); - - /// return store of a spherical matrix - double putSphericalValueInStore(double & store); - /// add store of a spherical matrix - double addSphericalValueInStore(double & store); - - double getSphericalStore(); - - /// Return store of a diagonal matrix - double* putDiagonalValueInStore(double * store); - /// Add store of a diagonal matrix in a diagonal one - double* addDiagonalValueInStore(double * store); - - double* getDiagonalStore(); - - /// Return store of a diagonal matrix - double* putSymmetricValueInStore(double * store); - /// Add store of a diagonal matrix in a diagonal one - double* addSymmetricValueInStore(double * store); - - double* getSymmetricStore(); - - /// Return store of a diagonal matrix - double* putGeneralValueInStore(double * store); - /// Add store of a diagonal matrix in a diagonal one - double* addGeneralValueInStore(double * store); - - double* getGeneralStore(); - - - /// compute general matrix SVD decomposition - void computeSVD(XEMDiagMatrix* & S, XEMGeneralMatrix* & O); - - void compute_as__multi_O_S_O(double multi, XEMGeneralMatrix* & O, XEMDiagMatrix *& S); - double trace_this_O_Sm1_O(XEMGeneralMatrix* & O, XEMDiagMatrix* & S); - double compute_trace_W_C(XEMMatrix * C); - void computeShape_as__diag_Ot_this_O(XEMDiagMatrix* & Shape, XEMGeneralMatrix* & Ori, double diviseur = 1.0); - /// gives : det(diag(this)) - double detDiag(XEMErrorType errorType); - - void setSymmetricStore(double * store); - void setGeneralStore(double * store); - void setDiagonalStore(double * store); - void setSphericalStore(double store); - double** storeToArray() const; - - protected : - - double _store; -}; - -inline double XEMSphericalMatrix::getStore(){ - return _store; -} - - -inline void XEMSphericalMatrix::setSymmetricStore(double * store){ - throw wrongMatrixType; -} -inline void XEMSphericalMatrix::setSphericalStore(double store){ - _store = store; -} -inline void XEMSphericalMatrix::setGeneralStore(double * store){ - throw wrongMatrixType; -} -inline void XEMSphericalMatrix::setDiagonalStore(double * store){ - throw wrongMatrixType; -} - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMStrategy.cpp b/lib/src/mixmod/MIXMOD/XEMStrategy.cpp deleted file mode 100644 index 3e5a32a..0000000 --- a/lib/src/mixmod/MIXMOD/XEMStrategy.cpp +++ /dev/null @@ -1,764 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMStrategy.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#include "XEMStrategy.h" -#include "XEMAlgo.h" -#include "XEMMAPAlgo.h" -#include "XEMEMAlgo.h" -#include "XEMCEMAlgo.h" -#include "XEMSEMAlgo.h" -#include "XEMMAlgo.h" -#include "XEMUtil.h" -#include "XEMGaussianParameter.h" -#include "XEMGaussianSphericalParameter.h" -#include "XEMGaussianDiagParameter.h" -#include "XEMGaussianGeneralParameter.h" -#include "XEMGaussianHDDAParameter.h" -#include "XEMBinaryEkjhParameter.h" -#include "XEMBinaryData.h" -#include "XEMUtil.h" - - -//----------- -//Constructor -//----------- -XEMStrategy::XEMStrategy(){ - _nbTry = defaultNbTryInStrategy; - _strategyInit = new XEMStrategyInit(); - _nbAlgo = defaultNbAlgo; - _tabAlgo = new XEMAlgo * [_nbAlgo]; - for (int64_t i=0; i<_nbAlgo; i++){ - _tabAlgo[i] = createDefaultAlgo(); - } -} - - -XEMStrategy::XEMStrategy(const XEMStrategy & strategy){ - _nbTry = strategy.getNbTry(); - _strategyInit = new XEMStrategyInit(*(strategy.getStrategyInit())); - _nbAlgo = strategy.getNbAlgo(); - _tabAlgo = new XEMAlgo * [_nbAlgo]; - XEMAlgo ** tabA = strategy.getTabAlgo(); - for (int64_t i=0; i<_nbAlgo; i++){ - _tabAlgo[i] = tabA[i]->clone(); - } - -} - - - -//------------ -// Constructor (used in DCV) -//------------ -XEMStrategy::XEMStrategy(XEMStrategy * originalStrategy, XEMCVBlock & block){ - _nbAlgo = originalStrategy->_nbAlgo ; - _nbTry = originalStrategy->_nbTry ; - _tabAlgo= new XEMAlgo*[_nbAlgo]; - XEMAlgo ** oTabAlgo = originalStrategy->_tabAlgo ; - for (int64_t i=0; i<_nbAlgo; i++){ - _tabAlgo[i] = oTabAlgo[i]->clone(); - } - _strategyInit = new XEMStrategyInit(originalStrategy->_strategyInit, block) ; -} - - - -//---------- -//Destructor -//---------- -XEMStrategy::~XEMStrategy(){ - - if (_tabAlgo){ - for (int64_t i=0; i<_nbAlgo ;i++){ - delete _tabAlgo[i]; - _tabAlgo[i] = NULL; - } - delete [] _tabAlgo; - _tabAlgo = NULL; - } -} - - - -void XEMStrategy::setAlgoEpsilon(int64_t position, double epsilonValue){ - _tabAlgo[position]->setEpsilon(epsilonValue); -} - -// setAlgoStopRuleTypeValue -void XEMStrategy::setAlgoStopRule(XEMAlgoStopName stopName, int64_t position){ - _tabAlgo[position]->setAlgoStopName(stopName); -} - -void XEMStrategy::setAlgoIteration( int64_t position, int64_t nbIterationValue){ - _tabAlgo[position]->setNbIteration(nbIterationValue); -} - - -// setAlgo -void XEMStrategy::setAlgo(XEMAlgoName algoName, int64_t position){ - if (_tabAlgo[position] != NULL){ - delete _tabAlgo[position]; - } - switch (algoName) { - case M : - _tabAlgo[position] = new XEMMAlgo(); - break; - case MAP : - _tabAlgo[position] = new XEMMAPAlgo(); - break; - case EM : - _tabAlgo[position] = new XEMEMAlgo(); - break; - case CEM : - _tabAlgo[position] = new XEMCEMAlgo(); - break; - case SEM : - _tabAlgo[position] = new XEMSEMAlgo(); - break; - default : - throw internalMixmodError; - } -} - - - -// set init parameter -void XEMStrategy::setInitParam(string & paramFileName, int64_t position){ - _strategyInit->setInitParam(paramFileName, position); -} - - - -// set init partition -void XEMStrategy::setInitPartition(string & partitionFileName, int64_t position){ - _strategyInit->setPartition(partitionFileName, position); -} - - -// set init partition -void XEMStrategy::setInitPartition(XEMPartition * part, int64_t position){ - _strategyInit->setPartition(part, position); -} - - -// removeAlgo -void XEMStrategy::removeAlgo(int64_t position){ - XEMAlgo ** tabAlgo = new XEMAlgo*[_nbAlgo-1]; - recopyTab(_tabAlgo, tabAlgo, position); - for (int64_t i=position ; i<(_nbAlgo-1);i++){ - tabAlgo[i] = _tabAlgo[i+1]; - } - _nbAlgo--; - - delete [] _tabAlgo; - _tabAlgo = NULL; - _tabAlgo = tabAlgo; - -} - -//-------------------- -// setStrategyInit -//-------------------- -void XEMStrategy::setStrategyInit(XEMStrategyInit * iStrategyInit){ - _strategyInit = iStrategyInit; //copy constructor -} - - -void XEMStrategy::setStrategyInit(XEMStrategyInitName initName, XEMData *& data, int64_t nbNbCluster, int64_t * tabNbCluster, XEMModelType ** tabModelType){ - int64_t nbSample = data->_nbSample; - int64_t pbDimension = data->_pbDimension; - string fileName = ""; - XEMParameter ** tabInitParameter = NULL; - XEMPartition ** tabInitPartition = NULL; - - switch (initName){ - case RANDOM : - case CEM_INIT : - case SEM_MAX : - case SMALL_EM : - _strategyInit->setStrategyInitName(initName); - break; - - case USER : - _strategyInit->setStrategyInitName(initName); - tabInitParameter = new XEMParameter * [nbNbCluster]; - - for (int64_t k=0; k_nameModel)){ - tabInitParameter[k] = new XEMGaussianGeneralParameter(tabNbCluster[k], pbDimension, tabModelType[0], fileName); - } - else if (isBinary(tabModelType[0]->_nameModel)){ - int64_t * tabNbModality = ((XEMBinaryData*)data)->getTabNbModality(); - tabInitParameter[k] = new XEMBinaryEkjhParameter(tabNbCluster[k], pbDimension, tabModelType[0], tabNbModality, fileName); - } - else if (isHD(tabModelType[0]->_nameModel)){ - tabInitParameter[k] = new XEMGaussianHDDAParameter(tabNbCluster[k], pbDimension, tabModelType[0], fileName); - } - else throw internalMixmodError; - } - _strategyInit->setTabInitParameter(tabInitParameter, nbNbCluster); - break; - - case USER_PARTITION : - _strategyInit->setStrategyInitName(initName); - tabInitPartition = new XEMPartition * [nbNbCluster]; - for (int64_t k=0; ksetTabPartition(tabInitPartition, nbNbCluster); - break; - } -} - -//------------- -// setNbTry -//------------- -void XEMStrategy::setNbTry(int64_t nbTry){ - if ((_strategyInit->getStrategyInitName() == USER) || - (_strategyInit->getStrategyInitName() == USER_PARTITION)){ - throw badSetNbTry; - } - if (nbTrymaxNbTryInStrategy){ - throw nbTryInStrategyTooLarge; - } - else{ - _nbTry = nbTry; - } -} - - - - - - -//--- -//run -//--- -void XEMStrategy::run(XEMModel *& model){ - //cout<<"XEMStrategy Init, nbTry="<<_nbTry<getCompletedLogLikelihoodOrLogLikelihood(); - // others tries - for (i=1; i<_nbTry; i++){ - delete currentModel; - currentModel = new XEMModel(model); - oneTry(currentModel); - double lastLLorCLL = currentModel->getCompletedLogLikelihoodOrLogLikelihood(); - if (lastLLorCLL > bestLLorCLL){ - delete bestModel; - bestModel = new XEMModel(currentModel); - bestLLorCLL = currentModel->getCompletedLogLikelihoodOrLogLikelihood(); - } - } - //cout<<"fin de XEMStrategy Init, nb d'essais effectues="<run(model); - } - else{ - //init model - switch (_strategyInit->getStrategyInitName()){ - case RANDOM : - model->initRANDOM(_strategyInit->getNbTry()); - break; - - case USER :{ // get initPartition - int64_t nbCluster = model->getNbCluster(); - int64_t index=0; - bool ok = false; - int64_t nbInitParameter = _strategyInit->getNbInitParameter(); - while (ok==false && indexgetInitParameter(index)->getNbCluster(); - if (nbCluster==nbClusterOfInitParameter){ - ok = true; - } - else{ - index++; - } - } - if (!ok) - throw internalMixmodError; - XEMParameter * initParameter =_strategyInit->getInitParameter(index); - model->initUSER(initParameter); - } - break; - - case USER_PARTITION :{ - // get initPartition - int64_t nbCluster = model->getNbCluster(); - int64_t index=0; - bool ok = false; - int64_t nbPartition = _strategyInit->getNbPartition(); - while (ok==false && indexgetPartition(index)->_nbCluster; - if (nbCluster == nbClusterOfInitPartition){ - ok = true; - } - else{ - index++; - } - } - if (!ok) - throw internalMixmodError; - XEMPartition * initPartition = _strategyInit->getPartition(index); - int64_t nbTyInInit = _strategyInit->getNbTry(); - model->initUSER_PARTITION(initPartition, nbTyInInit); - } - break; - - case SMALL_EM : - model->initSMALL_EM(_strategyInit); break; - - case CEM_INIT : - model->initCEM_INIT(_strategyInit); break; - - case SEM_MAX : - model->initSEM_MAX(_strategyInit); break; - - default : - cout << "XEMAlgo Error: Strategy Initialization Type Unknown";break; - } - - model->setAlgoName(UNKNOWN_ALGO_NAME); - - //model->getParameter()->edit(); - -#if DEBUG > 0 - cout<<"After initialization :"<editDebugInformation(); -#endif - - // runs algos - _tabAlgo[0]->run(model); - for (int64_t i=1; i<_nbAlgo ;i++){ - _tabAlgo[i]->run(model); - } - } -} - - - - -bool XEMStrategy::isMAlgo(){ - bool res = false; - if (_tabAlgo[0]->getAlgoName() == M){ - res = true; - } - return res; -} - - - -bool XEMStrategy::isMAPAlgo(){ - bool res = false; - if (_tabAlgo[0]->getAlgoName() == MAP){ - res = true; - } - return res; -} - - - -// insert algo -void XEMStrategy::insertAlgo(XEMAlgo * algo,int64_t position){ - XEMAlgo ** tabAlgo = new XEMAlgo*[_nbAlgo+1]; - recopyTab(_tabAlgo, tabAlgo, position); - tabAlgo[position] = algo; - - for (int64_t k=position; k<_nbAlgo;++k){ - tabAlgo[k+1] = _tabAlgo[k]; - } - - _nbAlgo++; - - delete [] _tabAlgo; - _tabAlgo = NULL; - _tabAlgo = tabAlgo; -} - - - - -//------- -// verify -//------- -bool XEMStrategy::verify(){ - - int64_t i; - bool res = true; - - // Test - //----- - // nbAlogType > 0 - if (_nbAlgo<1 || _tabAlgo==NULL){ - res = false; - throw nbAlgoTypeTooSmall; - } - if (_nbTrymaxNbTryInStrategy){ - res=false; - throw nbTryInStrategyTooLarge; - } - - - // Test - //------ - // If the 1rst algo is M or MAP, this algo must be the only one ! - if (((_tabAlgo[0]->getAlgoName() == M) || (_tabAlgo[0]->getAlgoName() == MAP)) - && _nbAlgo>1){ - res = false; - throw wrongNbAlgoWhenMorMAP; - } - - // Test - //------ - // If the algo is M or MAP, nbTry must be 1 - if (((_tabAlgo[0]->getAlgoName() == M) || (_tabAlgo[0]->getAlgoName() == - MAP)) && _nbTry != 1){ - res = false; - throw wrongNbStrategyTryValue; - } - - - // Test - //----- - // if algoType is M and MAP, the stopName must be nbIteration with nbIteration=1 - for (i=0; i<_nbAlgo; i++){ - if (_tabAlgo[i]->getAlgoName() == M || _tabAlgo[i]->getAlgoName() == MAP){ - if (_tabAlgo[i]->getAlgoStopName() == NBITERATION && _tabAlgo[i]->getNbIteration() == 1){ - // OK - } - else { - _tabAlgo[i]->setAlgoStopName(NBITERATION); - _tabAlgo[i]->setNbIteration(1); - cout<<" MIXMOD WARNING : if M or MAP is used, the stopName must be nbIteration and NbIteration must be 1"<getAlgoName() == SEM){ - if (_tabAlgo[i]->getAlgoStopName() != NBITERATION){ - throw badStopNameWithSEMAlgo; - } - } - } - - //if init is USER or PARTITION, nbTry must be 1 - if ((_strategyInit->getStrategyInitName() == USER_PARTITION || - _strategyInit->getStrategyInitName() == USER_PARTITION) && _nbTry != 1){ - throw wrongNbStrategyTryValue; - } - - - // Test - //----- - // if the algo is M, the initialization must be USER_PARTITION and the partion must be complete - if (_tabAlgo[0]->getAlgoName() == M){ - if (_strategyInit->getStrategyInitName() != USER_PARTITION){ - res = false; - throw BadInitialsationWhenM; - } - for (i=0; i<_strategyInit->getNbPartition(); i++){ - XEMPartition * partition = _strategyInit->getPartition(i); - if (! partition->isComplete()){ - res = false; - throw partitionMustBeComplete; - } - } - } - - - // test - //----- - // MAP => init USER - // and we suppose that the user has done a good param - if (_tabAlgo[0]->getAlgoName() == MAP){ - if (_strategyInit->getStrategyInitName() != USER){ - res = false; - throw BadInitialsationWhenMAP; - } - } - - return res; - -} - - - - - -//--------------- -// Input strategy -//--------------- -void XEMStrategy::input(ifstream & fi, XEMData *& data, int64_t nbNbCluster, int64_t * tabNbCluster, XEMModelType ** tabModelType){ - int64_t k, j; - string keyWord = ""; - int64_t nbSample = data->_nbSample; - int64_t pbDimension = data->_pbDimension; - bool alreadyRead = false; - string a =""; - - // nbTry - //------ - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if(keyWord.compare("nbtry")==0){ - int64_t nbTry; - fi>>nbTry; - setNbTry(nbTry); - } - - // StrategyInit - //----------------- - _strategyInit->input(fi, data, nbNbCluster, tabNbCluster, tabModelType, alreadyRead); - - - // Algos - //------- - /* Number of algorithms */ - moveUntilReach(fi,"nbAlgorithm"); - if(!fi.eof()){ - for (j=0; j<_nbAlgo; j++){ - delete _tabAlgo[j]; - } - delete[] _tabAlgo; - - fi>>_nbAlgo; - if (_nbAlgo > maxNbAlgo){ - throw nbAlgoTooLarge; - } - else if (_nbAlgo <= 0){ - throw nbAlgoTooSmall; - } - - _tabAlgo = new XEMAlgo * [_nbAlgo]; - - for (j=0; j<_nbAlgo; j++){ - fi>>keyWord; - ConvertBigtoLowString(keyWord); - - if(keyWord.compare("algorithm")==0){ - // tabAlgoType._type - fi>>a; - - if (a.compare("MAP")==0){ - _tabAlgo[j] = new XEMMAPAlgo(); - } - else if (a.compare("EM")==0){ - _tabAlgo[j] = new XEMEMAlgo(); - } - else if (a.compare("CEM")==0){ - _tabAlgo[j] = new XEMCEMAlgo(); - } - else if (a.compare("SEM")==0){ - _tabAlgo[j] = new XEMSEMAlgo(); - } - else if (a.compare("M")==0){ - _tabAlgo[j] = new XEMMAlgo(); - } - else{ - throw wrongAlgoType; - } - - if ((_tabAlgo[j]->getAlgoName() != MAP) && (_tabAlgo[j]->getAlgoName() != M)){ - fi>>keyWord; - ConvertBigtoLowString(keyWord); - - if(keyWord.compare("stoprule")==0){ - fi>>a; - - if (a.compare("NBITERATION")==0){ - _tabAlgo[j]->setAlgoStopName(NBITERATION); - } - - else if (a.compare("EPSILON")==0){ - _tabAlgo[j]->setAlgoStopName(EPSILON); - } - - else if (a.compare("NBITERATION_EPSILON")==0){ - _tabAlgo[j]->setAlgoStopName(NBITERATION_EPSILON); - } - else{ - throw wrongAlgoStopName; - } - // nbIteration && epsilon - fi>>keyWord; - ConvertBigtoLowString(keyWord); - - if(keyWord.compare("stoprulevalue")==0){ - if (_tabAlgo[j]->getAlgoStopName() == NBITERATION){ - int64_t nbIteration; - fi>>nbIteration; - _tabAlgo[j]->setNbIteration(nbIteration); - //_tabAlgo[j]->setEpsilon(minEpsilon); - } - else if (_tabAlgo[j]->getAlgoStopName() == EPSILON){ - double epsilon; - fi>>epsilon; - _tabAlgo[j]->setEpsilon(epsilon); - // _tabAlgo[j]->setNbIteration(maxNbIteration); - } - else if (_tabAlgo[j]->getAlgoStopName() == NBITERATION_EPSILON){ - int64_t nbIteration; - double epsilon; - fi>>nbIteration; - _tabAlgo[j]->setNbIteration(nbIteration); - fi>>epsilon; - _tabAlgo[j]->setEpsilon(epsilon); - } - - }// end if stopRuleValue - else{ - throw errorStopRuleValue; - } - - }// end if StopRule - else{ - throw errorStopRule; - } - - }// end if algo !=MAP ou != M - - }// end if algorithm - else{ - throw errorAlgo; - } - - }// end for jgetStrategyInitName()); - oFile<edit(oFile); - } - //oFile<<"\tNumber of strategy repetitions : "<<_nbStrategyTry<setNbTry(nbTryInDefaultClusteringStrategy); - - XEMAlgo * algo = createDefaultClusteringAlgo(); - strategy->insertAlgo(algo ,0); - - XEMStrategyInit * strategyInit = createDefaultClusteringStrategyInit(); - strategy->setStrategyInit(strategyInit); - - return strategy; -} - diff --git a/lib/src/mixmod/MIXMOD/XEMStrategy.h b/lib/src/mixmod/MIXMOD/XEMStrategy.h deleted file mode 100644 index 56ab2b5..0000000 --- a/lib/src/mixmod/MIXMOD/XEMStrategy.h +++ /dev/null @@ -1,222 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMStrategy.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMSTRATEGY_H -#define XEMSTRATEGY_H - -#include "XEMAlgo.h" -#include "XEMData.h" -#include "XEMPartition.h" -#include "XEMModel.h" - -/** - @brief Base class for Strategy(s) - @author F Langrognet -*/ - -class XEMStrategy{ - - public: - - /// Default constructor - XEMStrategy(); - - /// Constructor - XEMStrategy(const XEMStrategy & strategy); - - - - //------------ - // Constructor (used in DCV) - XEMStrategy(XEMStrategy * originalStrategy, XEMCVBlock & block); - - /// Destructor - virtual ~XEMStrategy(); - - ///getStrategyInit - const XEMStrategyInit * getStrategyInit() const; - - ///getAlgo[i] - const XEMAlgo * getAlgo(int64_t index) const; - - /// setStrategyInit - void setStrategyInit(XEMStrategyInit * iStrategyInit); - - /// setStrategyInit - void setStrategyInit(XEMStrategyInitName initName,XEMData *& data, int64_t nbNbCluster, int64_t * tabNbCluster, XEMModelType ** tabModelType); - - /// setInitParam - void setInitParam(string & paramFileName, int64_t position); - - /// setInitPartition - void setInitPartition(string & partitionFileName, int64_t position); - - /// setInitPartition - void setInitPartition(XEMPartition * part, int64_t position); - - /// getNbTryInInit - const int64_t getNbTryInInit() const; - - /// setNbTryInInit - void setNbTryInInit(int64_t nbTry); - - /// getNbIterationInInit - const int64_t getNbIterationInInit() const; - - /// set NbIterationInInit - void setNbIterationInInit(int64_t nbIteration); - - /// getEpsilonInInit - const double getEpsilonInInit() const; - - /// setEpsilonInInit - void setEpsilonInInit(double epsilon); - - /// getStopNameInInit - const XEMAlgoStopName getStopNameInInit() const; - - /// setStopNameInInit - void setStopNameInInit(XEMAlgoStopName stopName); - - - - - /// setAlgo - void setAlgo(XEMAlgoName algoName, int64_t position); - - /// removeAlgo - void removeAlgo(int64_t position); - - /// getTabAlgo - XEMAlgo ** getTabAlgo() const; - - /// insertAlgo - void insertAlgo(XEMAlgo * algo, int64_t position); - - - /// setAlgoStopRuleTypeValue - void setAlgoStopRule(XEMAlgoStopName stopName, int64_t position); - void setAlgoIteration( int64_t position, int64_t nbIterationValue); - void setAlgoEpsilon( int64_t position, double epsilonValue); - - ///nbTry - const int64_t getNbTry()const; - void setNbTry(int64_t nbTry); - - const int64_t getNbAlgo() const; - - - /// Input strategy - void input(ifstream & fi, XEMData *& data, int64_t nbNbCluster, int64_t * tabNbCluster, XEMModelType ** tabModelType); - - /// Run method - void run(XEMModel *& model); - - bool isMAPAlgo(); - - bool isMAlgo(); - - bool verify(); - - void edit(ofstream & oFile); - - - friend ostream & operator << (ostream & fo, XEMStrategy & strategy); - - - private : - - /// Number of try in the strategy - int64_t _nbTry; - - /// strategyInit - XEMStrategyInit * _strategyInit; - - /// Number of algorithm in the strategy - int64_t _nbAlgo; - - /// Table of algorithm - XEMAlgo ** _tabAlgo; // aggregate - - void oneTry(XEMModel *& model); - -}; - - -inline const XEMStrategyInit * XEMStrategy::getStrategyInit() const{ - return _strategyInit; -} - -inline const XEMAlgo * XEMStrategy::getAlgo(int64_t index) const{ - return _tabAlgo[index]; -} - -inline XEMAlgo ** XEMStrategy::getTabAlgo() const{ - return _tabAlgo; -} - -inline const int64_t XEMStrategy::getNbAlgo() const{ - return _nbAlgo; -} -inline const int64_t XEMStrategy::getNbTry()const{ - return _nbTry; -} - -inline const int64_t XEMStrategy::getNbTryInInit() const{ - return _strategyInit->getNbTry(); -} - -inline const int64_t XEMStrategy::getNbIterationInInit() const{ - return _strategyInit->getNbIteration(); -} - -inline const double XEMStrategy::getEpsilonInInit() const{ - return _strategyInit->getEpsilon(); -} - -inline void XEMStrategy::setNbTryInInit(int64_t nbTry){ - _strategyInit->setNbTry(nbTry); -} - -inline void XEMStrategy::setNbIterationInInit(int64_t nbIteration){ - _strategyInit->setNbIteration(nbIteration); -} - -inline void XEMStrategy::setEpsilonInInit(double epsilon){ - _strategyInit->setEpsilon(epsilon); -} - -inline const XEMAlgoStopName XEMStrategy::getStopNameInInit() const{ - return(_strategyInit->getStopName()); -} - -inline void XEMStrategy::setStopNameInInit(XEMAlgoStopName stopName){ - _strategyInit->setStopName(stopName); -} - -//others functions -XEMStrategy * buildDefaultClusteringStrategy(); - - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMStrategyInit.cpp b/lib/src/mixmod/MIXMOD/XEMStrategyInit.cpp deleted file mode 100644 index 157277a..0000000 --- a/lib/src/mixmod/MIXMOD/XEMStrategyInit.cpp +++ /dev/null @@ -1,632 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMStrategyInit.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#include "XEMStrategyInit.h" -#include "XEMGaussianParameter.h" -#include "XEMGaussianSphericalParameter.h" -#include "XEMGaussianDiagParameter.h" -#include "XEMGaussianGeneralParameter.h" -#include "XEMGaussianHDDAParameter.h" -#include "XEMBinaryEkjhParameter.h" -#include "XEMBinaryData.h" -//#include - -//------------ -// Constructor -//------------ -XEMStrategyInit::XEMStrategyInit(){ - _strategyInitName = defaultStrategyInitName; - _nbInitParameter = 0; - _tabInitParameter = NULL; - _nbPartition = 0; - _tabPartition = NULL; - _deleteTabParameter= false; - - _nbTry = defaultNbTryInInit; - _nbIteration = defaultNbIterationInInit; - _epsilon = defaultEpsilonInInit; - setStopName(NBITERATION_EPSILON); -} - - -//------------------ -// Copy constructor -//------------------ -XEMStrategyInit::XEMStrategyInit(const XEMStrategyInit & strategyInit){ - _strategyInitName = strategyInit.getStrategyInitName(); - _nbInitParameter = strategyInit.getNbInitParameter(); - - _nbPartition = strategyInit.getNbPartition(); - _tabPartition = NULL; - if (_nbPartition !=0){ - _tabPartition = new XEMPartition*[_nbPartition]; - const XEMPartition ** iPartition = strategyInit.getTabPartition(); - for (int64_t i=0; i<_nbPartition; i++){ - _tabPartition[i] = new XEMPartition(*(iPartition[i])); //copy constructor - } - } - - _nbInitParameter = strategyInit.getNbInitParameter(); - _tabInitParameter = NULL; - if (_nbInitParameter !=0){ - _tabInitParameter = new XEMParameter*[_nbInitParameter]; - const XEMParameter ** iParameter = strategyInit.getTabInitParameter(); - for (int64_t i=0; i<_nbInitParameter; i++){ - _tabInitParameter[i] = (iParameter[i])->clone(); - } - } - - _deleteTabParameter= false; // TODO ? - - _nbTry = strategyInit.getNbTry(); - _nbIteration = strategyInit.getNbIteration(); - _epsilon = strategyInit.getEpsilon(); - _stopName = strategyInit.getStopName(); - -} - - - - -//------------ -// Constructor (DCV context) -//------------ -XEMStrategyInit::XEMStrategyInit(XEMStrategyInit * originalSIT, XEMCVBlock & block){ - _strategyInitName = originalSIT->_strategyInitName ; - _nbInitParameter = originalSIT->_nbInitParameter ; - _tabInitParameter = originalSIT->_tabInitParameter ; - - _nbPartition = originalSIT->_nbPartition ; - if(_nbPartition >0){ - _tabPartition = new XEMPartition*[_nbPartition]; - int64_t k; - XEMPartition ** oPartition = originalSIT->_tabPartition; - - for(k=0; k<_nbPartition; k++){ - _tabPartition[k] = new XEMPartition(oPartition[k], block) ; - //editDoubleTab(oLabel[k]->_tabValue, _nbSample, 3) ; - } - } - else{ - _tabPartition = NULL; - } - - _deleteTabParameter = false ; - - _nbTry = originalSIT->getNbTry(); - _nbIteration = originalSIT->getNbIteration(); - _epsilon = originalSIT->getEpsilon(); - - _stopName = originalSIT->getStopName(); -} - - - -//----------- -// Destructor -//----------- -XEMStrategyInit::~XEMStrategyInit(){ - int64_t i; - if (_tabInitParameter && _deleteTabParameter){ - for (i=0; i<_nbInitParameter; i++){ - delete _tabInitParameter[i]; - } - delete [] _tabInitParameter; - _tabInitParameter = NULL; - } - - if (_tabPartition){ - for (i=0; i<_nbPartition; i++){ - delete _tabPartition[i]; - _tabPartition[i] = NULL; - } - delete [] _tabPartition; - _tabPartition = NULL; - } -} - - - -//--------------------- -// setStrategyInitName -//--------------------- -void XEMStrategyInit::setStrategyInitName(XEMStrategyInitName initName){ - - // delete ? - int64_t i; - if (_tabInitParameter && _deleteTabParameter){ - for (i=0; i<_nbInitParameter; i++){ - delete _tabInitParameter[i]; - } - delete [] _tabInitParameter; - _tabInitParameter = NULL; - } - - if (_tabPartition){ - for (i=0; i<_nbPartition; i++){ - delete _tabPartition[i]; - _tabPartition[i] = NULL; - } - delete [] _tabPartition; - _tabPartition = NULL; - } - - // - _strategyInitName = initName; - _nbInitParameter = 0; - _tabInitParameter = NULL; - _nbPartition = 0; - _tabPartition = NULL; - _deleteTabParameter= false; - - _nbTry = defaultNbTryInInit; - _nbIteration = defaultNbIterationInInit; - if (_strategyInitName == SEM_MAX){ - _nbIteration = defaultNbIterationInInitForSemMax; - setStopName(NBITERATION); - } - if (_strategyInitName == USER || _strategyInitName == USER_PARTITION){ - _nbTry = 1; - } - _epsilon = defaultEpsilonInInit; - -} - - - - -//------------------- -// set init parameter -//------------------- -void XEMStrategyInit::setInitParam(string & paramFileName, int64_t position){ - ifstream paramFile(paramFileName.c_str(), ios::in); - if (! paramFile.is_open()){ - throw wrongParamFileName; - } - if (_tabInitParameter != NULL){ - _tabInitParameter[position]->input(paramFile); - _tabInitParameter[position]->setFilename(paramFileName); - paramFile.close(); - } - else{ - throw internalMixmodError; - } -} - - - -//---------------- -// setTabInitParam -//---------------- -void XEMStrategyInit::setTabInitParameter(XEMParameter ** tabInitParameter, int64_t nbInitParameter){ - int64_t i; - if (_tabInitParameter && _deleteTabParameter){ - for (i=0; i<_nbInitParameter; i++){ - delete _tabInitParameter[i]; - } - delete [] _tabInitParameter; - _tabInitParameter = NULL; - } - - _tabInitParameter = tabInitParameter; - _nbInitParameter = nbInitParameter; -} - - - - -//------------------ -//set Init Partition -//------------------ -void XEMStrategyInit::setPartition(XEMPartition * part, int64_t position){ - if (part != NULL && _tabPartition!=NULL){ - _tabPartition[position] = part; - } - else{ - throw internalMixmodError; - } -} - - -//------------------ -//set Init Partition -//---------------- -void XEMStrategyInit::setPartition(string & partitionFileName, int64_t position){ - ifstream partitionFile(partitionFileName.c_str(), ios::in); - if (! partitionFile.is_open()){ - throw wrongPartitionFileName; - } - try{ - partitionFile>>(*_tabPartition[position]); - partitionFile.close(); - }catch(XEMErrorType errorType){ - throw badInitPart; - } -} - - - -//---------------- -// setTabPartition -//---------------- -void XEMStrategyInit::setTabPartition(XEMPartition ** tabPartition, int64_t nbPartition){ - int64_t i; - if (_tabPartition){ - for (i=0; i<_nbPartition; i++){ - delete _tabPartition[i]; - _tabPartition[i] = NULL; - } - delete [] _tabPartition; - _tabPartition = NULL; - } - - _tabPartition = tabPartition; - _nbPartition = nbPartition; -} - - -//------------ -// setStopName -//------------- -void XEMStrategyInit::setStopName(XEMAlgoStopName stopName){ - if (_strategyInitName == SMALL_EM){ - _stopName = stopName; - }else if (_strategyInitName == SEM_MAX && stopName==NBITERATION){ - _stopName = NBITERATION; - }else{ - throw badSetStopNameInInit; - } -} - - - -//--------- -// setNbTry -//--------- -void XEMStrategyInit::setNbTry(int64_t nbTry){ - if (_strategyInitName==SMALL_EM || _strategyInitName==CEM_INIT || _strategyInitName==RANDOM){ - if (nbTry > maxNbTryInInit){ - throw nbTryInInitTooLarge; - } - else if (nbTry < minNbTryInInit){ - throw nbTryInInitTooSmall; - } - else{ - _nbTry = nbTry; - } - } - else{ - throw badSetNbTryInInit; - } -} - - - -//---------------- -// set NbIteration -//---------------- -void XEMStrategyInit::setNbIteration(int64_t nbIteration){ - if (_strategyInitName==SMALL_EM || _strategyInitName==SEM_MAX){ - if (nbIteration > maxNbIterationInInit){ - throw nbIterationInInitTooLarge; - } - else if (nbIteration < minNbIterationInInit){ - throw nbIterationInInitTooSmall; - } - else{ - _nbIteration = nbIteration; - } - } - else{ - throw badSetNbIterationInInit; - } -} - - -//----------- -// setEpsilon -//----------- -void XEMStrategyInit::setEpsilon(double epsilon){ - if (_strategyInitName==SMALL_EM){ - if (epsilon > maxEpsilonInInit){ - throw epsilonInInitTooLarge; - } - else if (epsilon < minEpsilonInInit){ - throw epsilonInInitTooSmall; - } - else{ - _epsilon = epsilon; - } - } - else{ - throw badSetEpsilonInInit; - } -} - - - -//------- -// verify -//------- -bool XEMStrategyInit::verify() const{ - return false; -} - - - - -// input -void XEMStrategyInit::input(ifstream & fi, XEMData *& data, int64_t nbNbCluster, int64_t * tabNbCluster, XEMModelType ** tabModelType, bool & alreadyRead){ - string keyWord = ""; - string a =""; - int64_t k; - int64_t pbDimension = data->_pbDimension; - int64_t nbSample = data->_nbSample; - - moveUntilReach(fi,"inittype"); - if(!fi.eof()){ - - fi >> a; - if (a.compare("RANDOM")==0){ - setStrategyInitName(RANDOM); - // nbTryInInit - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if(keyWord.compare("nbtryininit")==0){ - int64_t nbTry; - fi>>nbTry; - setNbTry(nbTry); - } - else{ - alreadyRead = true; - } - } - - // USER init type // - else if (a.compare("USER")==0){ - setStrategyInitName(USER); - - // tabInitFileName - fi >> keyWord; - ConvertBigtoLowString(keyWord); - - if(keyWord.compare("initfile")==0){ - // _strategyInit->_nbInitParameter = nbNbCluster; - XEMParameter ** tabInitParameter = new XEMParameter * [nbNbCluster]; - string * tabFileName = new string[nbNbCluster]; - for (k=0; k_nameModel)){ - tabInitParameter[k] = new XEMGaussianGeneralParameter(tabNbCluster[k], pbDimension, tabModelType[0], tabFileName[k]); - } - else if (isBinary(tabModelType[0]->_nameModel)){ - int64_t * tabNbModality = ((XEMBinaryData*)data)->getTabNbModality(); - tabInitParameter[k] = new XEMBinaryEkjhParameter(tabNbCluster[k], pbDimension, tabModelType[0], tabNbModality, tabFileName[k]); - } - else if (isHD(tabModelType[0]->_nameModel)){ - tabInitParameter[k] = new XEMGaussianHDDAParameter(tabNbCluster[k], pbDimension, tabModelType[0], tabFileName[k]); - } - else throw internalMixmodError; - } - setTabInitParameter(tabInitParameter, nbNbCluster); - delete[] tabFileName; - } - else{ - throw errorInitFile; - } - } - - // USER_PARTITION init type // - - else if (a.compare("USER_PARTITION")==0){ - setStrategyInitName(USER_PARTITION); - - //label - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if(keyWord.compare("initfile")==0){ - //_strategyInit->_nbPartition = nbNbCluster; - XEMPartition ** tabPartition = new XEMPartition * [nbNbCluster]; - string * tabFileName = new string[nbNbCluster]; - for (k=0; k>keyWord; - ConvertBigtoLowString(keyWord); - if(keyWord.compare("nbtryininit")==0){ - int64_t nbTry; - fi>>nbTry; - setNbTry(nbTry); - } - else{ - alreadyRead = true; - } - - bool nbIteration = false; - bool epsilon = false; - //nbIterationInInit - if (!alreadyRead){ - fi>>keyWord; - } - ConvertBigtoLowString(keyWord); - if(keyWord.compare("nbiterationininit")==0){ - nbIteration = true; - int64_t nbIteration; - fi>>nbIteration; - setNbIteration(nbIteration); - alreadyRead = false; - } - else{ - alreadyRead = true; - } - - //epsilonInInit - if (!alreadyRead){ - fi>>keyWord; - alreadyRead = false; - } - ConvertBigtoLowString(keyWord); - if(keyWord.compare("epsilonininit")==0){ - epsilon = true; - double epsilon; - fi>>epsilon; - setEpsilon(epsilon); - alreadyRead = false; - } - else{ - alreadyRead = true; - } - if (nbIteration && epsilon){ - setStopName(NBITERATION_EPSILON); - } - if (nbIteration && !epsilon){ - setStopName(NBITERATION); - } - if (!nbIteration && epsilon){ - setStopName(EPSILON); - } - if (!nbIteration && !epsilon){ - setStopName(NBITERATION_EPSILON); - } - } - - else if (a.compare("CEM_INIT")==0){ - setStrategyInitName(CEM_INIT); - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if(keyWord.compare("nbtryininit")==0){ - int64_t nbTry; - fi>>nbTry; - setNbTry(nbTry); - } - else{ - alreadyRead = true; - } - } - - else if (a.compare("SEM_MAX")==0){ - setStrategyInitName(SEM_MAX); - fi>>keyWord; - ConvertBigtoLowString(keyWord); - if(keyWord.compare("nbiterationininit")==0){ - int64_t nbIteration; - fi>>nbIteration; - setNbIteration(nbIteration); - } - else{ - alreadyRead = true; - } - } - - else{ - throw wrongStrategyInitName; - } - } -} - - - - - - -// ostream << -//----------- -ostream & operator << (ostream & fo, XEMStrategyInit & strategyInit){ - //strategyInitType - string init = XEMStrategyInitNameToString(strategyInit._strategyInitName); - fo<<"\t strategyInitName : "<. - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMStrategyInit_H -#define XEMStrategyInit_H - -#include "XEMUtil.h" -#include "XEMParameter.h" -#include "XEMPartition.h" - -/** - @brief Base class for StrategyInitType(s) - @author F Langrognet -*/ - -class XEMStrategyInit{ - - public: - - /// Default constructor - XEMStrategyInit(); - - /// Copy constructor - XEMStrategyInit(const XEMStrategyInit & strategyInit); - - /// Constructor - // used in DCV - XEMStrategyInit(XEMStrategyInit * originalSIT, XEMCVBlock & block) ; - - /// Destructor - virtual ~XEMStrategyInit(); - - - /// getStrategyInitName - const XEMStrategyInitName & getStrategyInitName() const; - - /// setStrategyInitName - void setStrategyInitName(XEMStrategyInitName initName); - - - - /// getNbTry - const int64_t getNbTry() const; - - /// setNbTry - void setNbTry(int64_t nbTry); - - - - /// getNbIteration - const int64_t getNbIteration() const; - - /// set NbIteration - void setNbIteration(int64_t nbIteration); - - - - /// getEpsilon - const double getEpsilon() const; - - /// setEpsilon - void setEpsilon(double epsilon); - - - /// getStopName - const XEMAlgoStopName getStopName() const; - - /// setStopName - void setStopName(XEMAlgoStopName stopName); - - /* Parameter */ - //-----------// - /// getNbInitParameter - const int64_t & getNbInitParameter() const; - - /// getTabInitParameter - const XEMParameter ** getTabInitParameter() const; - - /// getTabInitParameter - XEMParameter * getInitParameter(int64_t index) const; - - /// setInitParam - void setInitParam(string & paramFileName, int64_t position); - - /// setTabInitParam - void setTabInitParameter(XEMParameter ** tabInitParameter, int64_t nbInitParameter); - - - /* Partition */ - //-----------// - /// getNbPartition - const int64_t & getNbPartition() const; - - /// getTabPartition - const XEMPartition ** getTabPartition() const; - - /// getTabPartition - XEMPartition * getPartition(int64_t index) const; - - ///set Init Partition - void setPartition(XEMPartition * part, int64_t position); - - ///set Init Partition - void setPartition(string & paramFileName, int64_t position); - - /// setTabPartition - void setTabPartition(XEMPartition ** tabPartition, int64_t nbPartition); - - - // input - void input(ifstream & fi,XEMData *& data, int64_t nbNbCluster, int64_t * tabNbCluster, XEMModelType ** tabModelTyper, bool & alreadyRead); - - - friend ostream & operator << (ostream & fo, XEMStrategyInit & strategyInit); - - //friend class XEMStrategy; - - - private : - - /// Initialization strategy type - XEMStrategyInitName _strategyInitName; - - /// nbTry - int64_t _nbTry; - - /// stopName (for smallEm) - XEMAlgoStopName _stopName; - - /// nbIteration - int64_t _nbIteration; - - /// epsilon - double _epsilon; - - - /* USER */ - /// number of InitParameter - int64_t _nbInitParameter; - - /// Init Parameters to initialize strategy - XEMParameter ** _tabInitParameter; - - - /* USER_PARTITION */ - /// number of Partition - int64_t _nbPartition; - - /// Labels to initialize strategy - XEMPartition ** _tabPartition; - - - bool _deleteTabParameter ; - - - bool verify() const; - -}; - -inline const XEMStrategyInitName & XEMStrategyInit::getStrategyInitName() const{ - return _strategyInitName; -} - -inline const XEMAlgoStopName XEMStrategyInit::getStopName() const{ - return _stopName; -} - -inline const int64_t & XEMStrategyInit::getNbInitParameter() const{ - return _nbInitParameter; -} - -inline const int64_t & XEMStrategyInit::getNbPartition() const{ - return _nbPartition; -} - -inline const XEMParameter ** XEMStrategyInit::getTabInitParameter() const{ - return const_cast(_tabInitParameter); -} - -inline XEMParameter * XEMStrategyInit::getInitParameter(int64_t index) const{ - return _tabInitParameter[index]; -} - -inline const XEMPartition** XEMStrategyInit::getTabPartition() const{ - return const_cast(_tabPartition); -} - -inline XEMPartition* XEMStrategyInit::getPartition(int64_t index) const{ - return _tabPartition[index]; -} - - -inline const int64_t XEMStrategyInit::getNbTry() const{ - return _nbTry; -} - -inline const int64_t XEMStrategyInit::getNbIteration() const{ - return _nbIteration; -} - -inline const double XEMStrategyInit::getEpsilon() const{ - return _epsilon; -} - - -// others functions -XEMStrategyInit * createDefaultClusteringStrategyInit(); - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMSymmetricMatrix.cpp b/lib/src/mixmod/MIXMOD/XEMSymmetricMatrix.cpp deleted file mode 100644 index e0d11f3..0000000 --- a/lib/src/mixmod/MIXMOD/XEMSymmetricMatrix.cpp +++ /dev/null @@ -1,705 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMSymmetricMatrix.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#include "XEMMatrix.h" -#include "XEMSymmetricMatrix.h" -#include "XEMUtil.h" -#include "XEMDiagMatrix.h" - -//------------ -// Constructor -//------------ -XEMSymmetricMatrix::XEMSymmetricMatrix(){ - _value = NULL; - _store = NULL; - throw wrongConstructorType; -} - -XEMSymmetricMatrix::XEMSymmetricMatrix(int64_t pbDimension, double d):XEMMatrix(pbDimension){ - _value = new SymmetricMatrix(_s_pbDimension); - _store = _value->Store(); - - _s_storeDim = _s_pbDimension * (_s_pbDimension + 1) / 2; - (*this)=d; -} - - - -// copy constructor -XEMSymmetricMatrix::XEMSymmetricMatrix(XEMSymmetricMatrix * A):XEMMatrix(A){ - _value = new SymmetricMatrix(_s_pbDimension); - _store = _value->Store(); - - _s_storeDim = _s_pbDimension * (_s_pbDimension + 1) / 2; - - recopyTab(A->getStore(), _store, _s_storeDim); -} - - - -//---------- -//Destructor -//---------- -XEMSymmetricMatrix::~XEMSymmetricMatrix(){ - if(_value){ - delete _value; - } - _value = NULL; -} - - - -double XEMSymmetricMatrix::determinant(XEMErrorType errorType){ - double det=0; - det = LogDeterminant(*_value).Value(); - if (det < minDeterminantValue){ - throw errorType; - } - return det; -} - - -void XEMSymmetricMatrix::equalToMatrixMultiplyByDouble(XEMMatrix* D, double d){ - throw nonImplementedMethod; -} - - -double* XEMSymmetricMatrix::getDiagonalStore(){ - throw wrongMatrixType; -} - - -double* XEMSymmetricMatrix::getSymmetricStore(){ - return(_store); -} - -double* XEMSymmetricMatrix::getGeneralStore(){ - return(_store); -} - -double XEMSymmetricMatrix::getSphericalStore(){ - throw wrongMatrixType; -} - - -void XEMSymmetricMatrix::compute_M_tM(double* V, int64_t l){ - int64_t indice1=l-1, indice2; - int64_t indiceStoreGammak = _s_storeDim-1; - int64_t dim = l / _s_pbDimension; - while (indice1 >0){ - for (int64_t j=0;j 0){ - for (int64_t j=0;jgetSymmetricStore(); - for(int64_t p=0; p<_s_storeDim ;p++){ - _store[p] += Wk_store[p] / L; - } -} - - - -double XEMSymmetricMatrix::compute_trace_W_C(XEMMatrix * C){ - double tabLambdak_k = 0.0; - double termesHorsDiag; - int64_t p,q,r; - double * C_store = C->getSymmetricStore(); - termesHorsDiag = 0.0; - for(p=0,r=0 ; p<_s_pbDimension ; p++,r++){ - for(q=0; q

i(); - - Inv->setSymmetricStore(value_Inv->Store()); - //cout<<"Inv Symm : "<putSymmetricValueInStore(_store); - - int64_t p; - for(p=0; p<_s_storeDim; p++){ - _store[p] /= d ; - } -} - - - -// add : cik * xMoinsMean * xMoinsMean' to this -void XEMSymmetricMatrix::add(double * xMoinsMean, double cik){ - - int64_t p,q,r; - double xMoinsMean_p; - - for(p=0,r=0 ; p<_s_pbDimension ; p++,r++){ - xMoinsMean_p = xMoinsMean[p]; - for(q=0 ; q

putSymmetricValueInStore(_store); -} - - -//add M to this -void XEMSymmetricMatrix::operator+=(XEMMatrix* M){ - - M->addSymmetricValueInStore(_store); -} - - - -// compute Shape as diag(Ot . this . O ) / diviseur -void XEMSymmetricMatrix::computeShape_as__diag_Ot_this_O(XEMDiagMatrix* & Shape, XEMGeneralMatrix* & Ori, double diviseur){ - - - int64_t i_index, j_index; - - int64_t p,q,r,j; - double * O_store = Ori->getStore(); - double * Shape_store = Shape->getStore(); - - double termesDiag, termesHorsDiag; - double tmp; - - for(j=0; j<_s_pbDimension; j++){ - // computation of the [j,j] term of the diagonal - - //-- reset - termesDiag = 0.0; - termesHorsDiag = 0.0; - - i_index = j; - for(p=0,r=0; p<_s_pbDimension; p++,r++,i_index+=_s_pbDimension){ - j_index = j; - for(q=0; qgetStore(); - double * S_store = S->getStore(); - double tmp; - - for(p=0,r=0; p<_s_pbDimension; p++,i_index+=_s_pbDimension){ - j_index = 0; - for(q=0; q<=p ; q++,r++,j_index+=_s_pbDimension){ - // compute this[i,j] = \multi * sum_{l} ( O[i,l] * 0[j,l] * S|l] ) - tmp = 0.0; - for(l=0; l<_s_pbDimension ;l++){ - tmp += O_store[i_index+l] * O_store[j_index+l] * S_store[l]; - } - tmp *= multi; - _store[r] = tmp; - - } - } - -} - - -// compute this as : (O * S * O' ) - -void XEMSymmetricMatrix::compute_as_O_S_O(XEMGeneralMatrix* & O, double* & S_store){ - - int64_t i_index = 0; - int64_t j_index; - int64_t p,q,r,l; - - for (int64_t i=0;i<_s_storeDim;i++){ - _store[i] = 0; - } - - double * O_store = O->getStore(); - double tmp; - for(p=0,r=0; p<_s_pbDimension; p++,i_index+=_s_pbDimension){ - j_index = 0; - for(q=0; q<=p ; q++,r++,j_index+=_s_pbDimension){ - tmp = 0.0; - for(l=0; l<_s_pbDimension ;l++){ - tmp += O_store[i_index+l] * O_store[j_index+l] * S_store[l]; - } - _store[r] = tmp; - } - } -} - -//compute trace of a symmetric matrix -double XEMSymmetricMatrix::computeTrace(){ - int64_t i; - int64_t indice = 0; - double trace = 0.0; - - - i = 0; - while(indice<_s_storeDim){ - trace += _store[indice]; - i++; - indice+=i+1; - } - return trace; -} - - - -void XEMSymmetricMatrix::computeSVD(XEMDiagMatrix* & S, XEMGeneralMatrix* & O){ - int64_t dim = O->getPbDimension(); - DiagonalMatrix * tabShape_k = new DiagonalMatrix(dim); - Matrix * tabOrientation_k = new Matrix(dim,dim); - SVD((*_value),(*tabShape_k),(*tabOrientation_k)); - - double * storeS = S->getStore(); - double * storeO = O->getStore(); - - - double * storeTabShape_k = (*tabShape_k).Store(); - double * storeTabOrientation_k = (*tabOrientation_k).Store(); - - recopyTab(storeTabShape_k, storeS, dim); - recopyTab(storeTabOrientation_k, storeO, dim*dim); - - delete tabShape_k; - delete tabOrientation_k; -} - - - -void XEMSymmetricMatrix::compute_as_M_tM(XEMGeneralMatrix* M, int64_t d){ - - int64_t indiceStoreM1=0, indiceStoreM2; - int64_t indice = 0; - int64_t k1 = 0, k2; - int64_t DimStoreM = _s_pbDimension*_s_pbDimension; - double * storeM = M->getStore(); - - for (int64_t i =0;i<_s_storeDim;i++){ - _store[i] = 0; - } - - while (indiceStoreM1 < DimStoreM){ - k2 = k1; - indiceStoreM2 = indiceStoreM1; - while (indiceStoreM2 < DimStoreM){ - - for (int64_t j=0;jgetStore(); - - while (indice < _s_pbDimension){ - for (int64_t i=0;i<(_s_pbDimension-k);i++){ - _store[indice] += V[indiceV+i]*storeM[indiceM + i]; - } - - for (int64_t j=1;j<(_s_pbDimension-k);j++){ - _store[indice+j] += V[indiceV]*storeM[indiceM+j]; - } - indiceM += (_s_pbDimension-k); - k += 1; - indiceV += 1; - indice += 1; - } -} - - - - - - -// compute M as : M = ( O * S^{-1} * O' ) * this -void XEMSymmetricMatrix::compute_M_as__O_Sinverse_Ot_this(XEMGeneralMatrix & M, XEMGeneralMatrix* & O, XEMDiagMatrix* & S){ - - double * M_store = M.getStore(); - double * O_store = O->getStore(); - double * S_store = S->getStore(); - - int64_t i,j,l, p,r; - int64_t O1_index = 0; - int64_t O2_index; - int64_t r_decalage ; - double tmp, omega; - int64_t fillindex = 0 ; - - - for(i=0; i<_s_pbDimension; i++){ - for(j=0; j<_s_pbDimension; j++, fillindex++){ - // filling tabMtmpk_store[i,j] - - tmp = 0.0; - r_decalage = _s_pbDimension - j + 1 ; - - r = j; - p = 0; - O2_index = 0; - - - while(p> _store[r]; - r++; - } - for (j=i+1; j<_s_pbDimension; j++){ - fi >> garbage; - } - } -} - - -// gives : det(diag(this)) -double XEMSymmetricMatrix::detDiag(XEMErrorType errorType){ - int64_t p,q,r; - double det = 1.0; - - for(p=0,r=0; p<_s_pbDimension; p++,r++){ - for(q=0;qgetStore(); - double * S_store = S->getStore(); - - double trace = 0.0; - double termesHorsDiag = 0.0; - double tmp,tmp2; - - int64_t i_index = 0; - int64_t j_index; - int64_t p,q,r,l; - - for(p=0,r=0; p<_s_pbDimension ;p++,r++,i_index+=_s_pbDimension){ - j_index = 0; - for(q=0; q-1 ; --i){ - newStore[i][i] = _store[k]; - k--; - for (j=(i-1); j>-1 ; --j){ - newStore[i][j] = _store[k]; - newStore[j][i] = _store[k]; - k--; - } - - } - - return newStore; - -} - - - - - - - - - - diff --git a/lib/src/mixmod/MIXMOD/XEMSymmetricMatrix.h b/lib/src/mixmod/MIXMOD/XEMSymmetricMatrix.h deleted file mode 100644 index 830e921..0000000 --- a/lib/src/mixmod/MIXMOD/XEMSymmetricMatrix.h +++ /dev/null @@ -1,229 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMSymmetricMatrix.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMSYMMETRICMATRIX_H -#define XEMSYMMETRICMATRIX_H - - -#include "XEMUtil.h" -#include "XEMMatrix.h" - -/** - @brief class GeneralMatrix - @author F Langrognet & A Echenim -*/ - -class XEMDiagMatrix; - -class XEMSymmetricMatrix : public XEMMatrix{ - - public: - - /// Default constructor - XEMSymmetricMatrix(); - - /// constructor : d*Id - /// default value : Id - XEMSymmetricMatrix(int64_t pbDimension, double d=1.0); - - XEMSymmetricMatrix(XEMSymmetricMatrix * A); - - - /// Desctructor - virtual ~XEMSymmetricMatrix(); - - /// Compute determinant of symmetric matrix - double determinant(XEMErrorType errorType); - - /// Return store of symmetric matrix - double * getStore(); - - /// Return newmat symmetric matrix - SymmetricMatrix * getValue(); - - /// Return dimension of store - int64_t getStoreDim(); - - /// Inverse symmetric matrix - void inverse(XEMMatrix * & A); - - - /// compute (x - mean)' this (x - mean) - double norme(double * xMoinsMean); - - /// compute : this = A / d - void equalToMatrixDividedByDouble(XEMMatrix * A, double d); - - /// compute : this = A * d - void equalToMatrixMultiplyByDouble(XEMMatrix*D, double d); - - /// add : cik * xMoinsMean * xMoinsMean' to this - void add(double * xMoinsMean, double cik); - - // add : diag( cik * xMoinsMean * xMoinsMean' ) to this - //void addDiag(double * xMoinsMean, double cik); - - /// Return store of a spherical matrix in a symmetric one - double putSphericalValueInStore(double & store); - /// Add store of a spherical matrix in a symmetric one - double addSphericalValueInStore(double & store); - - double getSphericalStore(); - - /// Return store of a diagonal matrix - double* putDiagonalValueInStore(double * store); - /// Add store of a diagonal matrix in a diagonal one - double* addDiagonalValueInStore(double * store); - - double* getDiagonalStore(); - - /// Return store of a diagonal matrix - double* putSymmetricValueInStore(double * store); - /// Add store of a diagonal matrix in a diagonal one - double* addSymmetricValueInStore(double * store); - - double* getSymmetricStore(); - - /// Return store of a diagonal matrix - double* putGeneralValueInStore(double * store); - /// Add store of a diagonal matrix in a diagonal one - double* addGeneralValueInStore(double * store); - - double* getGeneralStore(); - - /// compute general matrix SVD decomposition - void computeSVD(XEMDiagMatrix* & S, XEMGeneralMatrix* & O); - - - /// this = (d * Identity) - void operator=(const double& d); - /// this = this / (Identity * d) - void operator/=(const double& d); - /// this = this * ( Identity * d) - void operator*=(const double& d); - /// this = this + matrix - void operator+=(XEMMatrix* M); - /// this = matrix - void operator=(XEMMatrix* M); - - - /// read symmetric matrix store in file - void input(ifstream & fi); - - /* ///compute SVD decomposition for a symmetric matrix - void computeSVD(XEMDiagMatrix* & S, XEMGeneralMatrix* & O);*/ - - /// compute Shape as diag(Ot . this . O ) / diviseur - void computeShape_as__diag_Ot_this_O(XEMDiagMatrix* & Shape, XEMGeneralMatrix* & Ori, double diviseur = 1.0); - // double trace_this_O_Sm1_O(XEMGeneralMatrix* & O, XEMDiagMatrix* & S); - - - /// compute this as : multi * (O * S * O' ) - void compute_as__multi_O_S_O(double multi, XEMGeneralMatrix* & O, XEMDiagMatrix* & S); - - /// compute this as O*S*O' - void compute_as_O_S_O(XEMGeneralMatrix* & O, double* & S_store); - /// compute trace of this - double computeTrace(); - - /// compute this as M * M' - void compute_as_M_tM(XEMGeneralMatrix* M,int64_t d); - - /// compute this as matrix * vector - void compute_as_M_V(XEMSymmetricMatrix* M, double * V); - - /// compute this as double * matrix - void compute_product_Lk_Wk(XEMMatrix* Wk, double L); - - /// copute trace of W * C - double compute_trace_W_C(XEMMatrix * C); - - /// compute M as : M = ( O * S^{-1} * O' ) * this - void compute_M_as__O_Sinverse_Ot_this(XEMGeneralMatrix & M, XEMGeneralMatrix* & O, XEMDiagMatrix* & S); - - /// compute this as vector * vector' - void compute_M_tM(double* V, int64_t l); - - /// gives : det(diag(this)) - double detDiag(XEMErrorType errorType); - - /// trace( this * O * S^{-1} * O' ) - double trace_this_O_Sm1_O(XEMGeneralMatrix* & O, XEMDiagMatrix* & S); - - ///set store - - void setSymmetricStore(double * store); - void setGeneralStore(double * store); - void setDiagonalStore(double * store); - void setSphericalStore(double store); - double** storeToArray() const; - - protected : - - /// newmat symmetric matrix - SymmetricMatrix * _value; - - /// store of matrix - double * _store; - /// dimension of store - int64_t _s_storeDim; - -}; -// TODO static : -// int64_t XEMGeneralMatrix::_s_storeDim = 0; - -inline double * XEMSymmetricMatrix::getStore(){ - return _store; -} - - -inline SymmetricMatrix * XEMSymmetricMatrix::getValue(){ - return _value; -} - -inline int64_t XEMSymmetricMatrix::getStoreDim(){ - return _s_storeDim; -} - -inline void XEMSymmetricMatrix::setSymmetricStore(double * store){ - // _store = store; - recopyTab(store,_store,_s_storeDim); -} -inline void XEMSymmetricMatrix::setSphericalStore(double store){ - throw wrongMatrixType; -} -inline void XEMSymmetricMatrix::setGeneralStore(double * store){ - throw wrongMatrixType; -} -inline void XEMSymmetricMatrix::setDiagonalStore(double * store){ - throw wrongMatrixType; -} - -/* TODO static - inline void XEMGeneralMatrix::initiate(){ - _s_storeDim = _s_pbDimension * _s_pbDimension / 2; - } -*/ - -#endif diff --git a/lib/src/mixmod/MIXMOD/XEMUtil.cpp b/lib/src/mixmod/MIXMOD/XEMUtil.cpp deleted file mode 100644 index b7af8c0..0000000 --- a/lib/src/mixmod/MIXMOD/XEMUtil.cpp +++ /dev/null @@ -1,2480 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMUtil.cpp description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org - ***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#include "XEMUtil.h" -#include "XEMEMAlgo.h" -#include "XEMRandom.h" -#include "XEMModelType.h" -#include - - - -/*double determinant(const XEMMatrix& A,XEMErrorType errorType){ - XEMGeneralMatrix * A_bis; - A_bis = (XEMGeneralMatrix * A); - int64_t dim = A_bis.getStoreDim(); - Matrix * M = new Matrix(dim, dim); - double * storeM = M.Store(); - double * storeA = A_bis.getStore(); - - recopyTad(storeA, storeM, dim); - double det; - det = LogDeterminant(M).Value(); - if (det < minDeterminantValue) - throw errorType; - return det; -}*/ - -double powAndCheckIfNotNull(double a, double b, XEMErrorType errorType) { - double res; - res = pow(a,b); - if (res==0.0) throw errorType; - return res; -} - - -// compute the svd decomposition with eigenvalues in a decreasing order -void XEMSVD(const Matrix& A, DiagonalMatrix& Q, Matrix& U) { - - // call the SVD fucntion of Newmat - SVD(A,Q,U); - Real * storeQ = Q.Store(); - - // Sort - int64_t nbCols = A.Ncols(); - int64_t max; - for (int64_t i=1; i<=nbCols ;i++) { - //search the max eigenvalue - max = i; - for (int64_t j=i+1; j<=nbCols; j++) { - if (storeQ[j-1] > storeQ[max-1]) - max = j; - if (max != i) { - // switch - Real tmp = storeQ[max-1]; - storeQ[max-1] = storeQ[i-1]; - storeQ[i-1] = tmp; - - ColumnVector tmp2 = U.Column(max); - U.Column(max) = U.Column(i); - U.Column(i) = tmp2; - } - } - } -} - - - -//----------------------- -// return the nearest int64_t -//----------------------- -int64_t XEMRound(double d) { - int64_t res = (int64_t)(d+0.5); - return res; -} - - - -//------------------------------------ -// Convert big char of str in low char -//------------------------------------ -void ConvertBigtoLowString(string & str) { - for (int64_t i=0; i_nameModel) { - - // Gaussian models // - case (Gaussian_p_L_B) : - oFile<<"Gaussian Diagonal Model : "; - oFile<<"p_L_B"; - break; - case (Gaussian_p_Lk_B) : - oFile<<"p_Lk_B"; - break; - oFile<<"Gaussian Diagonal Model : "; - case (Gaussian_p_L_Bk) : - oFile<<"Gaussian Diagonal Model : "; - oFile<<"p_L_Bk"; - break; - case (Gaussian_p_Lk_Bk) : - oFile<<"Gaussian Diagonal Model : "; - oFile<<"p_Lk_Bk"; - break; - case (Gaussian_pk_L_B) : - oFile<<"Gaussian Diagonal Model : "; - oFile<<" pk_L_B"; - break; - case (Gaussian_pk_Lk_B) : - oFile<<"Gaussian Diagonal Model : "; - oFile<<" pk_Lk_B"; - break; - case (Gaussian_pk_L_Bk) : - oFile<<"Gaussian Diagonal Model : "; - oFile<<"pk_L_Bk"; - break; - case (Gaussian_pk_Lk_Bk) : - oFile<<"Gaussian Diagonal Model : "; - oFile<<"pk_Lk_Bk"; - break; - case (Gaussian_p_L_I) : - oFile<<"Gaussian Spherical Model : "; - oFile<<"p_L_I"; - break; - case (Gaussian_p_Lk_I) : - oFile<<"Gaussian Spherical Model : "; - oFile<<"p_Lk_I"; - break; - case (Gaussian_pk_L_I) : - oFile<<"Gaussian Spherical Model : "; - oFile<<"pk_L_I"; - break; - case (Gaussian_pk_Lk_I) : - oFile<<"Gaussian Spherical Model : "; - oFile<<"pk_Lk_I"; - break; - case (Gaussian_p_L_C): - oFile<<"Gaussian Ellipsoidal Model : "; - oFile<<"p_L_C"; - break; - case (Gaussian_p_Lk_C): - oFile<<"Gaussian Ellipsoidal Model : "; - oFile<<"p_Lk_C"; - break; - case (Gaussian_p_L_D_Ak_D): - oFile<<"Gaussian Ellipsoidal Model : "; - oFile<<"p_L_D_Ak_D"; - break; - case (Gaussian_p_Lk_D_Ak_D): - oFile<<"Gaussian Ellipsoidal Model : "; - oFile<<"p_Lk_D_Ak_D"; - break; - case (Gaussian_p_L_Dk_A_Dk): - oFile<<"Gaussian Ellipsoidal Model : "; - oFile<<"p_L_Dk_A_Dk"; - break; - case (Gaussian_p_Lk_Dk_A_Dk): - oFile<<"Gaussian Ellipsoidal Model : "; - oFile<<"p_Lk_Dk_A_Dk"; - break; - case (Gaussian_p_L_Ck): - oFile<<"Gaussian Ellipsoidal Model : "; - oFile<<"p_L_Ck"; - break; - case (Gaussian_p_Lk_Ck): - oFile<<"Gaussian Ellipsoidal Model : "; - oFile<<"p_Lk_Ck"; - break; - case (Gaussian_pk_L_C): - oFile<<"Gaussian Ellipsoidal Model : "; - oFile<<"pk_L_C"; - break; - case (Gaussian_pk_Lk_C): - oFile<<"Gaussian Ellipsoidal Model : "; - oFile<<"pk_Lk_C"; - break; - case (Gaussian_pk_L_D_Ak_D): - oFile<<"Gaussian Ellipsoidal Model : "; - oFile<<"pk_L_D_Ak_D"; - break; - case (Gaussian_pk_Lk_D_Ak_D): - oFile<<"Gaussian Ellipsoidal Model : "; - oFile<<"pk_Lk_D_Ak_D"; - break; - case (Gaussian_pk_L_Dk_A_Dk): - oFile<<"Gaussian Ellipsoidal Model : "; - oFile<<"pk_L_Dk_A_Dk"; - break; - case (Gaussian_pk_Lk_Dk_A_Dk): - oFile<<"Gaussian Ellipsoidal Model : "; - oFile<<"pk_Lk_Dk_A_Dk"; - break; - case (Gaussian_pk_L_Ck): - oFile<<"Gaussian Ellipsoidal Model : "; - oFile<<"pk_L_Ck"; - break; - case (Gaussian_pk_Lk_Ck): - oFile<<"Gaussian Ellipsoidal Model : "; - oFile<<"pk_Lk_Ck"; - break; - - // Binary models // - case (Binary_p_E): - oFile<<"Binary Model : "; - oFile<<"Binary_p_E"; - break; - case (Binary_p_Ek): - oFile<<"Binary Model : "; - oFile<<"Binary_p_Ek"; - break; - case (Binary_p_Ej): - oFile<<"Binary Model : "; - oFile<<"Binary_p_Ej"; - break; - case (Binary_p_Ekj): - oFile<<"Binary Model : "; - oFile<<"Binary_p_Ekj"; - break; - case (Binary_p_Ekjh): - oFile<<"Binary Model : "; - oFile<<"Binary_p_Ekjh"; - break; - case (Binary_pk_E): - oFile<<"Binary Model : "; - oFile<<"Binary_pk_E"; - break; - case (Binary_pk_Ek): - oFile<<"Binary Model : "; - oFile<<"Binary_pk_Ek"; - break; - case (Binary_pk_Ej): - oFile<<"Binary Model : "; - oFile<<"Binary_pk_Ej"; - break; - case (Binary_pk_Ekj): - oFile<<"Binary Model : "; - oFile<<"Binary_pk_Ekj"; - break; - case (Binary_pk_Ekjh): - oFile<<"Binary Model : "; - oFile<<"Binary_pk_Ekjh"; - break; - - case (Gaussian_HD_pk_AkjBkQkD) : - oFile<<"HD Model : "; - oFile<<"Gaussian_HD_pk_AkjBkQkD"; - break; - case (Gaussian_HD_pk_AkjBkQkDk) : - oFile<<"HD Model : "; - oFile<<"Gaussian_HD_pk_AkjBkQkDk"; - break; - case (Gaussian_HD_pk_AkjBQkD) : - oFile<<"HD Model : "; - oFile<<"Gaussian_HD_pk_AkjBQkD"; - break; - case (Gaussian_HD_pk_AjBkQkD) : - oFile<<"HD Model : "; - oFile<<"Gaussian_HD_pk_AjBkQkD"; - break; - case (Gaussian_HD_pk_AjBQkD) : - oFile<<"HD Model : "; - oFile<<"Gaussian_HD_pk_AjBQkD"; - break; - case (Gaussian_HD_pk_AkBkQkD) : - oFile<<"HD Model : "; - oFile<<"Gaussian_HD_pk_AkBkQkD"; - break; - case (Gaussian_HD_pk_AkBkQkDk) : - oFile<<"HD Model : "; - oFile<<"Gaussian_HD_pk_AkBkQkDk"; - break; - case (Gaussian_HD_pk_AkBQkD) : - oFile<<"HD Model : "; - oFile<<"Gaussian_HD_pk_AkBQkD"; - break; - case (Gaussian_HD_p_AkjBkQkD) : - oFile<<"HD Model : "; - oFile<<"Gaussian_HD_p_AkjBkQkD"; - break; - case (Gaussian_HD_p_AkjBkQkDk) : - oFile<<"HD Model : "; - oFile<<"Gaussian_HD_p_AkjBkQkDk"; - break; - case (Gaussian_HD_p_AkjBQkD) : - oFile<<"HD Model : "; - oFile<<"Gaussian_HD_p_AkjBQkD"; - break; - case (Gaussian_HD_p_AjBkQkD) : - oFile<<"HD Model : "; - oFile<<"Gaussian_HD_p_AjBkQkD"; - break; - case (Gaussian_HD_p_AjBQkD) : - oFile<<"HD Model : "; - oFile<<"Gaussian_HD_p_AjBQkD"; - break; - case (Gaussian_HD_p_AkBkQkD) : - oFile<<"HD Model : "; - oFile<<"Gaussian_HD_p_AkBkQkD"; - break; - case (Gaussian_HD_p_AkBkQkDk) : - oFile<<"HD Model : "; - oFile<<"Gaussian_HD_p_AkBkQkDk"; - break; - case (Gaussian_HD_p_AkBQkD) : - oFile<<"HD Model : "; - oFile<<"Gaussian_HD_p_AkBQkD"; - break; - - - - default : - oFile<<"Model Type Error"; - } - oFile<> keyWord ; - ConvertBigtoLowString(keyWord); - } - -// while( !fi.eof() && strcmp(keyWord,what)!=0 ) ; - while ( !fi.eof() && (keyWord.compare(what) !=0) ) ; -// delete[] keyWord; -} - - - - -//------------------- -// read nbNbCluster file names (ex : titi ; toto;tutu) - -void readTabFileName(ifstream & fi, int64_t nbNbCluster,string* tabFileName, string& keyWord) { - int64_t i, k=0; - - string c = ""; - string c1 = ""; - string tmp = ""; - string strBeforePv = ""; - string strAfterPv = ""; - - fi>>c; -// on ne converti pas tout le nom en minuscules sinon il y a des erreurs dans le nom des fichiers - - - while (!isKeyword(c) && (!fi.eof())) { - - if (c.compare(";")==0) { - k++; - fi>>c; - } - else { - if (c.find_first_of(';')==0) { // si c commence par ; - k++; - strAfterPv = c.substr(1,c.length()); - } - else { - strAfterPv = c; - } - while ((strAfterPv.find_first_of(';') != string::npos)) { // ; est dans la chaine de caracteres - tmp = strAfterPv; - strBeforePv = tmp.substr(0,tmp.find_first_of(';')); - strAfterPv = tmp.substr(tmp.find_first_of(';')+1,tmp.length()); - - - if (tabFileName[k].length() == 0) { - tabFileName[k] = strBeforePv; - } - else { - tabFileName[k].append(" "); - tabFileName[k].append(strBeforePv); - - } - k++; - } - - if (tabFileName[k].length() == 0) { - tabFileName[k] = strAfterPv; - } - else { - tabFileName[k].append(" "); - tabFileName[k].append(strBeforePv); - } - fi>>c; - } - } - - if ( (k != nbNbCluster-1) || (tabFileName[nbNbCluster-1].compare("")==0) || (tabFileName[nbNbCluster-1].compare(" ")==0)) - throw wrongPartitionFileName; - - keyWord = c; -} - - - - - - - - - - - - - - - - - - - - -void initToZero(double* tab, int64_t n) { - double * p_tab = tab; - int64_t i; - for (i=0 ; i_nameModel) { - case (Gaussian_p_L_B) : - case (Gaussian_p_Lk_B) : - case (Gaussian_p_L_Bk) : - case (Gaussian_p_Lk_Bk) : - case (Gaussian_pk_L_B) : - case (Gaussian_pk_Lk_B) : - case (Gaussian_pk_L_Bk) : - case (Gaussian_pk_Lk_Bk) : - flux << "D" << flush; - break; - - case (Gaussian_p_L_C): - case (Gaussian_p_Lk_C): - case (Gaussian_p_L_D_Ak_D): - case (Gaussian_p_Lk_D_Ak_D): - case (Gaussian_p_L_Dk_A_Dk): - case (Gaussian_p_Lk_Dk_A_Dk): - case (Gaussian_p_L_Ck): - case (Gaussian_p_Lk_Ck): - case (Gaussian_pk_L_C): - case (Gaussian_pk_Lk_C): - case (Gaussian_pk_L_D_Ak_D): - case (Gaussian_pk_Lk_D_Ak_D): - case (Gaussian_pk_L_Dk_A_Dk): - case (Gaussian_pk_Lk_Dk_A_Dk): - case (Gaussian_pk_L_Ck): - case (Gaussian_pk_Lk_Ck): - flux << "G" << flush; - break; - - case (Gaussian_p_L_I) : - case (Gaussian_p_Lk_I) : - case (Gaussian_pk_L_I) : - case (Gaussian_pk_Lk_I) : - flux << "S" << flush; - break; - - // Binary models // - case (Binary_p_E) : - case (Binary_p_Ek) : - case (Binary_p_Ej) : - case (Binary_p_Ekj) : - case (Binary_p_Ekjh) : - case (Binary_pk_E) : - case (Binary_pk_Ek) : - case (Binary_pk_Ej) : - case (Binary_pk_Ekj) : - case (Binary_pk_Ekjh) : - flux << "B" << flush; - break; - - case (Gaussian_HD_pk_AkjBkQkD) : - case (Gaussian_HD_pk_AkjBkQkDk) : - case (Gaussian_HD_pk_AkjBQkD) : - case (Gaussian_HD_pk_AjBkQkD) : - case (Gaussian_HD_pk_AjBQkD) : - case (Gaussian_HD_pk_AkBkQkD) : - case (Gaussian_HD_pk_AkBkQkDk) : - case (Gaussian_HD_pk_AkBQkD) : - case (Gaussian_HD_p_AkjBkQkD) : - case (Gaussian_HD_p_AkjBkQkDk) : - case (Gaussian_HD_p_AkjBQkD) : - case (Gaussian_HD_p_AjBkQkD) : - case (Gaussian_HD_p_AjBQkD) : - case (Gaussian_HD_p_AkBkQkD) : - case (Gaussian_HD_p_AkBkQkDk) : - case (Gaussian_HD_p_AkBQkD) : - flux<< "H" << flush; - break; - default : - throw internalMixmodError; - } -} - -void printModelType(const XEMModelType * const modelType,ostream & flux) { - switch (modelType->_nameModel) { - - // Gaussian models // - case (Gaussian_p_L_B) : - flux<<"p_L_B "; - break; - case (Gaussian_p_Lk_B) : - flux<<"p_Lk_B "; - break; - case (Gaussian_p_L_Bk) : - flux<<"p_L_Bk "; - break; - case (Gaussian_p_Lk_Bk) : - flux<<"p_Lk_Bk "; - break; - case (Gaussian_pk_L_B) : - flux<<"pk_L_B "; - break; - case (Gaussian_pk_Lk_B) : - flux<<"pk_Lk_B "; - break; - case (Gaussian_pk_L_Bk) : - flux<<"pk_L_Bk "; - break; - case (Gaussian_pk_Lk_Bk) : - flux<<"pk_Lk_Bk "; - break; - case (Gaussian_p_L_C): - flux<<"p_L_C "; - break; - case (Gaussian_p_Lk_C): - flux<<"p_Lk_C "; - break; - case (Gaussian_p_L_D_Ak_D): - flux<<"p_L_D_Ak_D "; - break; - case (Gaussian_p_Lk_D_Ak_D): - flux<<"p_Lk_D_Ak_D "; - break; - case (Gaussian_p_L_Dk_A_Dk): - flux<<"p_L_Dk_A_Dk "; - break; - case (Gaussian_p_Lk_Dk_A_Dk): - flux<<"p_Lk_Dk_A_Dk "; - break; - case (Gaussian_p_L_Ck): - flux<<"p_L_Ck "; - break; - case (Gaussian_p_Lk_Ck): - flux<<"p_Lk_Ck "; - break; - case (Gaussian_pk_L_C): - flux<<"pk_L_C "; - break; - case (Gaussian_pk_Lk_C): - flux<<"pk_Lk_C "; - break; - case (Gaussian_pk_L_D_Ak_D): - flux<<"pk_L_D_Ak_D "; - break; - case (Gaussian_pk_Lk_D_Ak_D): - flux<<"pk_Lk_D_Ak_D "; - break; - case (Gaussian_pk_L_Dk_A_Dk): - flux<<"pk_L_Dk_A_Dk "; - break; - case (Gaussian_pk_Lk_Dk_A_Dk): - flux<<"pk_Lk_Dk_A_Dk "; - break; - case (Gaussian_pk_L_Ck): - flux<<"pk_L_Ck "; - break; - case (Gaussian_pk_Lk_Ck): - flux<<"pk_Lk_Ck "; - break; - case (Gaussian_p_L_I) : - flux<<"p_L_I "; - break; - case (Gaussian_p_Lk_I) : - flux<<"p_Lk_I "; - break; - case (Gaussian_pk_L_I) : - flux<<"pk_L_I "; - break; - case (Gaussian_pk_Lk_I) : - flux<<"pk_Lk_I "; - break; - - // Binary models // - case (Binary_p_E) : - flux<<"Binary_p_E "; - break; - case (Binary_p_Ek) : - flux<<"Binary_p_Ek "; - break; - case (Binary_p_Ej) : - flux<<"Binary_p_Ej "; - break; - case (Binary_p_Ekj) : - flux<<"Binary_p_Ekj "; - break; - case (Binary_p_Ekjh) : - flux<<"Binary_p_Ekjh "; - break; - case (Binary_pk_E) : - flux<<"Binary_pk_E "; - break; - case (Binary_pk_Ek) : - flux<<"Binary_pk_Ek "; - break; - case (Binary_pk_Ej) : - flux<<"Binary_pk_Ej "; - break; - case (Binary_pk_Ekj) : - flux<<"Binary_pk_Ekj "; - break; - case (Binary_pk_Ekjh) : - flux<<"Binary_pk_Ekjh "; - break; - -//HDDA models - case (Gaussian_HD_pk_AkjBkQkD) : - flux<<"HD_pk_AkjBkQkD "; - break; - case (Gaussian_HD_pk_AkjBkQkDk) : - flux<<"HD_pk_AkjBkQkDk "; - break; - case (Gaussian_HD_pk_AkjBQkD) : - flux<<"HD_pk_AkjBQkD "; - break; - case (Gaussian_HD_pk_AjBkQkD) : - flux<<"HD_pk_AjBkQkD "; - break; - case (Gaussian_HD_pk_AjBQkD) : - flux<<"HD_pk_AjBQkD "; - break; - case (Gaussian_HD_pk_AkBkQkD) : - flux<<"HD_pk_AkBkQkD "; - break; - case (Gaussian_HD_pk_AkBkQkDk) : - flux<<"HD_pk_AkBkQkDk "; - break; - case (Gaussian_HD_pk_AkBQkD) : - flux<<"HD_pk_AkBQkD "; - break; - case (Gaussian_HD_p_AkjBkQkD) : - flux<<"HD_p_AkjBkQkD "; - break; - case (Gaussian_HD_p_AkjBkQkDk) : - flux<<"HD_p_AkjBkQkDk "; - break; - case (Gaussian_HD_p_AkjBQkD) : - flux<<"HD_p_AkjBQkD "; - break; - case (Gaussian_HD_p_AjBkQkD) : - flux<<"HD_p_AjBkQkD "; - break; - case (Gaussian_HD_p_AjBQkD) : - flux<<"HD_p_AjBQkD "; - break; - case (Gaussian_HD_p_AkBkQkD) : - flux<<"HD_p_AkBkQkD "; - break; - case (Gaussian_HD_p_AkBkQkDk) : - flux<<"HD_p_AkBkQkDk "; - break; - case (Gaussian_HD_p_AkBQkD) : - flux<<"HD_p_AkBQkD "; - break; - default : - throw internalMixmodError; - } - flux << flush; - -} - - -inline void echange(double * tab, int64_t i1, int64_t i2) { - double tmp_double = tab[i1]; - tab[i1] = tab[i2]; - tab[i2] = tmp_double ; -} -inline void echange(int64_t * tab, int64_t i1, int64_t i2) { - - int64_t tmp = tab[i1]; - tab[i1] = tab[i2]; - tab[i2] = tmp ; -} - -void selectionSortWithOrder(double * tabRandom, int64_t * tabOrder, int64_t left, int64_t right) { - int64_t i, j; - int64_t min; - - for (i = left; i < right; i++) { - min = i; - for (j=i+1; j <= right; j++) - if (tabRandom[j] < tabRandom[min]) - min = j; - echange(tabRandom, min, i); - echange(tabOrder, min, i); - } -} - -int64_t partition(double * tabRandom, int64_t * tabOrder, int64_t left, int64_t right) { - - double val = tabRandom[left]; - int64_t lm = left-1; - int64_t rm = right+1; - for (;;) { - do - rm--; - while (tabRandom[rm] > val); - - do - lm++; - while ( tabRandom[lm] < val); - - if (lm < rm) { - echange(tabRandom, rm, lm); - echange(tabOrder , rm, lm); - } - else - return rm; - } - -} - -void quickSortWithOrder(double * tabRandom, int64_t * tabOrder, int64_t left, int64_t right) { - if (left < (right - SMALL_ENOUGH_TO_USE_SELECTION_SORT)) { - int64_t split_pt = partition(tabRandom, tabOrder, left, right); - quickSortWithOrder(tabRandom, tabOrder, left , split_pt); - quickSortWithOrder(tabRandom, tabOrder, split_pt+1, right); - } - else selectionSortWithOrder(tabRandom, tabOrder, left, right); - - -} - - - -//------------------- -//generateRandomIndex -//------------------- -int64_t generateRandomIndex(bool * tabIndividualCanBeUsedForInitRandom, double * weight, double totalWeight) { - double rndWeight, sumWeight; - int64_t idxSample; - - /* Generate a random integer between 0 and _nbSample-1 */ - bool IdxSampleCanBeUsed = false; // idxSample can be used - while (!IdxSampleCanBeUsed) { - // get index of sample with weight // - rndWeight = (int64_t)(totalWeight*rnd()+1); - sumWeight = 0.0; - idxSample = -1; - while (sumWeight < rndWeight) { - idxSample++; - sumWeight += weight[idxSample]; - } - //cout<<"index tire au hasard :"<>a; - if (a.compare("BIC")==0) { - criterionName = BIC; - } - else if (a.compare("CV")==0) { - criterionName = CV; - } - else if (a.compare("ICL")==0) { - criterionName = ICL; - } - else if (a.compare("NEC")==0) { - criterionName = NEC; - } - else if (a.compare("DCV")==0) { - criterionName = DCV; - } - else { - throw wrongCriterionName; - } -} - - - - -void inputCVinitBlocks(ifstream & fi,XEMCVinitBlocks & CVinitBlocks) { - string a = ""; - fi>>a; - if (a.compare("CV_RANDOM")==0) { - CVinitBlocks = CV_RANDOM; - } - else if (a.compare("DIAG")==0) { - CVinitBlocks = CV_DIAG; - } - else { - throw wrongCVinitType; - } -} - -void inputDCVinitBlocks(ifstream & fi,XEMDCVinitBlocks & DCVinitBlocks) { - string a = ""; - fi>>a; - if (a.compare("DCV_RANDOM")==0) { - DCVinitBlocks = DCV_RANDOM; - } - else if (a.compare("DIAG")==0) { - DCVinitBlocks = DCV_DIAG; - } - else { - throw wrongDCVinitType; - } -} - - - -XEMAlgo * createDefaultAlgo() { - XEMAlgo * result = NULL; - if (defaultAlgoName == EM) { - result = new XEMEMAlgo(); - } - else { - throw internalMixmodError; - } - return result; -} - diff --git a/lib/src/mixmod/MIXMOD/XEMUtil.h b/lib/src/mixmod/MIXMOD/XEMUtil.h deleted file mode 100644 index 8891f84..0000000 --- a/lib/src/mixmod/MIXMOD/XEMUtil.h +++ /dev/null @@ -1,1066 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMUtil.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ -#ifndef XEMUTIL_H -#define XEMUTIL_H - -#ifndef WANT_STREAM -#define WANT_STREAM -#endif - -#ifndef WANT_MATH -#define WANT_MATH -#endif - -/* Need matrix applications */ -#include "../NEWMAT/newmatap.h" -#include "../NEWMAT/newmatio.h" - - - -/* Need matrix output routines */ -#include -#include -#include -#include -#include -#include -#include - -//#include -//#include -//#include "ctype.h" - -#include - -/* Preprocessor constants */ -#define CLOCK 0 /* 1 for execution time information */ -#define DEBUG 0 /* >0 for debug information */ -// 0 : no debug -// 1 : param debug -// 2 : param and fik, tik, zik debug - -#define DATA_REDUCE 1 // to activate DATA_REDUCE : 1 - -class XEMModelType; -class XEMMatrix; -class XEMAlgo; - -/* Constants definitions */ -/// Define PI -const double XEMPI = 3.14159265358979323846; /* Pi number */ -/// Define number of maximum samples -const int64_t maxNbSample = 1000000; /* Maximum sample size */ -const int64_t maxPbDimension = 10000; /* Maximum sample dimension */ -const int64_t minNbIteration = 1; /* Minimum number of iterations */ -const int64_t minNbIterationForSEM = 50; /* Minimum number of iterations for SEM */ -const int64_t maxNbIteration = 100000; /* Maximum number of iterations */ -const int64_t defaultNbIteration = 200; /* Default number of iteration*/ -const double minEpsilon = 0; /* Minimum value of eps */ -const double maxEpsilon = 1; /* Maximum value of eps */ - - -const double defaultEpsilon = 1.0E-3; /* Default value of eps*/ -const int64_t maxNbNbCluster = 10; /* Maximum size of cluster list */ -const int64_t maxNbAlgo = 5; /* Maximum number of algorithms */ -const int64_t defaultNbAlgo = 1; /* Default number of algorithms */ -const int64_t maxNbStrategy = 10; /* Maximum number of strategies */ -const int64_t defaultNbStrategy = 1; /* Default number of strategies */ -const int64_t maxNbModel = 100; /* Maximum number of models */ -const int64_t defaultNbModel = 1; /* Default number of models */ -const int64_t maxNbCriterion = 4; /* Maximum number of criteria */ -const int64_t defaultNbCriterion = 1; /* Default number of criteria */ - -const int64_t minNbTryInStrategy = 1; /* min of strategies repeats */ -const int64_t maxNbTryInStrategy = 100; /* max of strategies repeats */ -const int64_t defaultNbTryInStrategy=1; /* number of strategies repeats */ -const int64_t nbTryInDefaultClusteringStrategy=1; /* number of strategies repeats */ - -const int64_t minNbTryInInit = 1; /* min of repeats in init*/ -const int64_t maxNbTryInInit = 1000; /* max of repeats in init*/ -const int64_t defaultNbTryInInit = 10; /* number of repeats in init*/ - -const int64_t minNbIterationInInit = 1; /* min number of iterations in init*/ -const int64_t maxNbIterationInInit = 1000; /* max number of iterations in init*/ -const int64_t defaultNbIterationInInit = 5; /* default number of iterations in init*/ -const int64_t defaultNbIterationInInitForSemMax = 100; /* default number of iterations in init*/ - -const double minEpsilonInInit = 0; /* min number of iterations in init*/ -const double maxEpsilonInInit = 1; /* max number of iterations in init*/ -const double defaultEpsilonInInit = 0.001; /* default number of iterations in init*/ - -const int64_t maxNbIterationInCEM_INIT = 100; /* Maximum number of iterations of CEM in CEM_INIT */ - -const double minOverflow = 1.e-100; /* Minimum value for overflow */ -const double minUnderflow = 1.e-100; /* Minimum value for underflow */ -const int64_t nbMaxSelection = 5; /* Maximum number of selection */ -const int64_t maxNbOutputFiles = 52; /* Maximum number of output Files */ -const int64_t nbTestOutputFiles = 25; /* Number of output files to compare in test */ -const double defaultFluryEpsilon = 0.001; /* default value for espilon in flury algorthm */ -const int64_t maxFluryIter = 7; /* maximum of number of Flury iterations */ -const double minDeterminantValue = 1.e-100; /* minimum value of determinant of sigma */ -const double maxRelativeDiffValueTest = 1.0E-5; /* Maximum difference between 2 value in test */ -const double maxAbsoluteDiffValueTest = 1.0E-8; /* Maximum difference between 2 value in test */ - -const int64_t defaultDCVnumberOfBlocks = 10 ; // DCV -const int64_t defaultCVnumberOfBlocks = 10 ; // CV - -const double minValueForLLandLLOne = 1.e-10; // minimum value for LL - LLone - -const int64_t int64_t_max = +9223372036854775807LL; - -const int64_t nbQualitativeGraphics = 2; -const int64_t nbQuantitativeGraphics = 3; - -/* - Notes : - Enumeration types will be called ...Name - Ex : XEMStrategyInitName -*/ - - - -enum XEMCVinitBlocks{ - CV_RANDOM = 0, // initialize the CV blocks by random - - CV_DIAG = 1 // initialize the CV blocks by assiging - /* sample 1 : for w=1 to its weight : sample 1 in block w - sample 2 : for w=1 to its weight : sample w1+1 in block w1+w - - Ex : 1 - //----- - ind weight - 1 1 - 2 1 - 3 1 - ... - ind 1 -> block1 - ind 2 -> block2 - ... - ind V -> blockV - ind V+1->block1 - ... - - Ex 2 : - //----- - ind weight - 1 2 - 2 2 - 3 2 - 4 2 - 5 2 - if V=4 - ind 1 -> block1 - ind 1 -> block2 - ind 2 -> block3 - ind 2 -> block4 - ind 3 -> block1 - ind 3 -> block2 - ind 4 -> block3 - ind 4 -> block4 - ind 5 -> block1 - ind 5 -> block2 - - ->> block 1 : ind 1 - 3 - 5 - block 2 : ind 1 - 3 - 5 - block 3 : ind 2 - 4 - block 4 : ind 4 - 5 - - - */ - -}; -const XEMCVinitBlocks defaultCVinitBlocks = CV_RANDOM; - - -enum XEMDCVinitBlocks{ - DCV_RANDOM = 0, // initialize the DCV blocks by random - - DCV_DIAG = 1 // initialize the DCV blocks by the same way that CV_DIAG - /* - Ex : 1 - //----- - ind weight - 1 1 - 2 1 - 3 1 - ... - ind 1 -> blockTest1 - ind 2 -> blockTest2 - ... - ind V -> blockTestV - ind V+1->blockTest1 - ... - - Ex 2 : - //----- - ind weight - 1 10 - 2 10 - 3 10 - 4 10 - 5 10 - if V=4 - ind 1 -> blockTest1 - ind 1 -> blockTest2 - ind 1 -> blockTest3 - ind 1 -> blockTest4 - ind 1 -> blockTest1 - ind 1 -> blockTest2 - ind 1 -> blockTest3 - ind 1 -> blockTest4 - ind 1 -> blockTest1 - ind 1 -> blockTest2 - ind 2 -> blockTest3 - ind 2 -> blockTest4 - ind 2 -> blockTest1 - ind 2 -> blockTest2 - ind 2 -> blockTest3 - ind 2 -> blockTest4 - ind 2 -> blockTest1 - ind 2 -> blockTest2 - ind 2 -> blockTest3 - ind 2 -> blockTest4 - - ->> blockTest 1 : ind 1(x3) - 2(x2) - 3(x3) - 4(x2) - 5(x3) - 6(x2) - 7(x3) - 8(x2) - 9(x3) - 10(x2) - blockLearning 1 : ind 1(x7) - 2(x8) - 3(x7) - 4(x8) - 5(x7) - 6(x8) - 7(x7) - 8(x8) - 9(x7) - 10(x8) - ... - - */ -}; -const XEMDCVinitBlocks defaultDCVinitBlocks = DCV_RANDOM; - -/** @enum XEMStrategyInitName - @brief Enumeration of differents strategy initialization - - -*/ -enum XEMStrategyInitName { - RANDOM = 0, /* Random centers */ - USER = 1, /* Initial parameters specified by user */ - USER_PARTITION = 2, /* Partition specified by user */ - SMALL_EM = 3, /* em strategy for initial parameters */ - CEM_INIT = 4, /* initialization with cem */ - SEM_MAX = 5 /* initialization with sem max */ -}; -const XEMStrategyInitName defaultStrategyInitName = SMALL_EM; -const XEMStrategyInitName defaultClusteringStrategyInitName = SMALL_EM; - - -/* Type of convergence for each algorithm */ -/** @enum XEMAlgoStopName - @brief Enumeration of differents type of converge of algorithm (stop rule) -*/ -enum XEMAlgoStopName { - NO_STOP_NAME = -1, /* for MAP or M algo*/ - NBITERATION = 0, /* Number of iterations specified by user */ - EPSILON = 1, /* Stationarity of the xml criterion */ - NBITERATION_EPSILON = 2 /* Number of iterations & xml criterion */ -}; -const XEMAlgoStopName defaultAlgoStopName = NBITERATION_EPSILON; - - -/** @enum XEMCriterionName - @brief Enumeration of Criterion type -*/ -enum XEMCriterionName { - UNKNOWN_CRITERION_NAME = -1, /* Unknown criterion */ - - BIC = 0, /* Bayesian information criterion */ - CV = 1, /* Cross validation criterion */ - ICL = 2, /* Integrated completed likelihood */ - NEC = 3, /* Entropy criterion */ - DCV = 4 /* Double Cross validation criterion */ -}; -const XEMCriterionName defaultCriterionName = BIC; - -/** @enum XEMAlgoName - @brief Enumeration of Algo type -*/ -enum XEMAlgoName { - UNKNOWN_ALGO_NAME = -1, /* Unknown algorithm */ - MAP = 0, /* Maximum a posteriori */ - EM = 1, /* Expectation maximization */ - CEM = 2, /* Classification EM */ - SEM = 3, /* Stochastic EM */ - M = 4 /* Maximization */ -}; -const XEMAlgoName defaultAlgoName = EM; -const XEMAlgoName defaultClusteringAlgoName = EM; - -/** @enum XEMFormatFile - @brief Format of differents data file - - -*/ -const int64_t nbFormatNumeric = 3; -namespace FormatNumeric -{ - - enum XEMFormatNumericFile { - txt = 0, /* Format txt */ - hdf5 = 1, /* Format hdf5 */ - XML = 2, /* Format XML */ - }; - const XEMFormatNumericFile defaultFormatNumericFile = txt; -} - -/** @enum XEMTypePartition - @brief type of partition - - -*/ - -namespace TypePartition -{ - enum XEMTypePartition { - UNKNOWN_PARTITION = 0, - label = 1, - partition = 2, - }; - const XEMTypePartition defaultTypePartition = label; -} - -struct XEMNumericPartitionFile{ - string _fileName; - FormatNumeric::XEMFormatNumericFile _format; - TypePartition::XEMTypePartition _type; -}; - -enum XEMKeyword{ - NbLines, - PbDimension, - NbNbCluster, - ListNbCluster, - NbModality, - NbCriterion, - ListCriterion, - NbModel, - ListModel, - subDimensionEqual, - subDimensionFree=10, - NbStrategy, - InitType, - InitFile, - NbAlgorithm, - Algorithm, - PartitionFile, - DataFile, - WeightFile, - NbCVBlocks, - CVinitBlocks=20, - NbDCVBlocks, - DCVinitBlocks, - SizeKeyword -}; - -string XEMKeywordToString(const XEMKeyword & keyword); - -bool isKeyword(string name); - - -/** @struct TWeightedIndividual - @brief Structure for chain list of differents sample - -*/ -struct TWeightedIndividual{ - int64_t val; // index of individual - double weight; -}; - -/// XEMCVBlock -struct XEMCVBlock{ - int64_t _nbSample; // number of samples in this CV Block - double _weightTotal; // weight Total of this CV Block - TWeightedIndividual * _tabWeightedIndividual;// array (size=nbSample) of weighted individual -}; - - - -/** @enum XEMModelName - @brief Enumeration of model name -*/ -enum XEMModelName { - - /////////////////////// - // // - // Gaussian Models // - // // - - - /////////////////////// - - /* Unknown model type */ - UNKNOWN_MODEL_NAME = -1, - - /* 28 Gaussian 'Classical' models */ - - /* Spherical Gaussian model: proportion fixed */ - Gaussian_p_L_I = 0, - Gaussian_p_Lk_I , - - Gaussian_pk_L_I , - Gaussian_pk_Lk_I, - - /* Diagonal Gaussian model: proportion fixed */ - Gaussian_p_L_B, - Gaussian_p_Lk_B, - Gaussian_p_L_Bk, - Gaussian_p_Lk_Bk, - - Gaussian_pk_L_B, - Gaussian_pk_Lk_B, - Gaussian_pk_L_Bk, - Gaussian_pk_Lk_Bk, - - /* Ellipsoidal Gaussian model: proportion fixed */ - Gaussian_p_L_C, - Gaussian_p_Lk_C, - Gaussian_p_L_D_Ak_D, - Gaussian_p_Lk_D_Ak_D, - Gaussian_p_L_Dk_A_Dk, - Gaussian_p_Lk_Dk_A_Dk, - Gaussian_p_L_Ck, - Gaussian_p_Lk_Ck, - - Gaussian_pk_L_C, - Gaussian_pk_Lk_C, - Gaussian_pk_L_D_Ak_D, - Gaussian_pk_Lk_D_Ak_D, - Gaussian_pk_L_Dk_A_Dk, - Gaussian_pk_Lk_Dk_A_Dk, - Gaussian_pk_L_Ck, - Gaussian_pk_Lk_Ck, - - /*----------------*/ - /* 16 HD models*/ - /*----------------*/ - Gaussian_HD_p_AkjBkQkDk, - Gaussian_HD_p_AkBkQkDk, - Gaussian_HD_p_AkjBkQkD , - Gaussian_HD_p_AjBkQkD , - Gaussian_HD_p_AkjBQkD , - Gaussian_HD_p_AjBQkD , - Gaussian_HD_p_AkBkQkD , - Gaussian_HD_p_AkBQkD , - - Gaussian_HD_pk_AkjBkQkDk, - Gaussian_HD_pk_AkBkQkDk , - Gaussian_HD_pk_AkjBkQkD, - Gaussian_HD_pk_AjBkQkD, - Gaussian_HD_pk_AkjBQkD, - Gaussian_HD_pk_AjBQkD , - Gaussian_HD_pk_AkBkQkD, - Gaussian_HD_pk_AkBQkD , - - - ///////////////////// - // // - // 10 Binary Models // - // // - ///////////////////// - - /* : proportion fixed */ - Binary_p_E , - Binary_p_Ek, - Binary_p_Ej , - Binary_p_Ekj, - Binary_p_Ekjh , - /* : proportion free */ - Binary_pk_E , - Binary_pk_Ek, - Binary_pk_Ej , - Binary_pk_Ekj, - Binary_pk_Ekjh , - - nbXEMModelName = 54 - -}; - - -const XEMModelName defaultGaussianModelName = Gaussian_pk_Lk_C; -const XEMModelName defaultBinaryModelName = Binary_pk_Ekjh; -const XEMModelName defaultGaussianHDDAModelName = Gaussian_HD_pk_AkjBkQkD; - - -/* Output mode */ -enum XEMOutputType { - BICstandardOutput = 0, /* Standard output mode */ - BICnumericStandardOutput, /* Numerical standard output */ - BIClabelOutput, /* Label output */ - BICparameterOutput, /* Parameter output (nmerical) */ - BICtikOutput, /* Posterior probabilities output */ - BICzikOutput, /* Partition output (notation 1/0) */ - BIClikelihoodOutput, /* Log-likelihood, entropy & completed log-likelihood output */ - BICnumericLikelihoodOutput, - BICErrorOutput = 8, /* error code for BIC Criterion for each sestimation */ - - CVstandardOutput, /* CV Standard output mode */ - CVnumericStandardOutput, /* CV Numerical standard output */ - CVlabelOutput, /* CV Label output */ - CVparameterOutput, /* CV Parameter output (nmerical) */ - CVtikOutput, /* CV Posterior probabilities output */ - CVzikOutput, /* CV Partition output (notation 1/0) */ - CVlikelihoodOutput, /* CV Log-likelihood, entropy & completed log-likelihood output */ - CVnumericLikelihoodOutput, - CVErrorOutput = 17, /* error code for CV Criterion for each sestimation */ - - ICLstandardOutput, /* ICL Standard output mode */ - ICLnumericStandardOutput, /* ICL Numerical standard output */ - ICLlabelOutput, /* ICL Label output */ - ICLparameterOutput, /* ICL Parameter output (nmerical) */ - ICLtikOutput, /* ICL Posterior probabilities output */ - ICLzikOutput, /* ICL Partition output (notation 1/0) */ - ICLlikelihoodOutput, /* ICL Log-likelihood, entropy & completed log-likelihood output */ - ICLnumericLikelihoodOutput, - ICLErrorOutput = 26, /* error code for ICL Criterion for each sestimation */ - - NECstandardOutput, /* NEC Standard output mode */ - NECnumericStandardOutput, /* NEC Numerical standard output */ - NEClabelOutput, /* NEC Label output */ - NECparameterOutput, /* NEC Parameter output (nmerical) */ - NECtikOutput, /* NEC Posterior probabilities output */ - NECzikOutput, /* NEC Partition output (notation 1/0) */ - NEClikelihoodOutput, /* NEC Log-likelihood, entropy & completed log-likelihood output */ - NECnumericLikelihoodOutput, - NECErrorOutput = 35, /* error code for NEC Criterion for each sestimation */ - - DCVstandardOutput, /* DCV Standard output mode */ - DCVnumericStandardOutput, /* DCV Numerical standard output */ - DCVlabelOutput, /* DCV Label output */ - DCVparameterOutput, /* DCV Parameter output (nmerical) */ - DCVtikOutput, /* DCV Posterior probabilities output */ - DCVzikOutput, /* DCV Partition output (notation 1/0) */ - DCVlikelihoodOutput, /* DCV Log-likelihood, entropy & completed log-likelihood output */ - DCVnumericLikelihoodOutput, - DCVErrorOutput = 44, /* error code for DCV Criterion for each sestimation */ - - completeOutput , /* Complete output mode */ - numericCompleteOutput, /* Numerical complete output */ - - CVlabelClassificationOutput,/* label of classification CV method*/ - - errorMixmodOutput, /* error code for mixmod execution*/ - errorModelOutput, /* error code for NEC Criterion for each sestimation */ - - DCVinfo, // double cross validation information - DCVnumericInfo = 51 // numeric double cross validation information (for validation test) -}; - - -/** @enum ErrorError - @brief Enumeration of Error type -*/ -enum XEMErrorType { - /* Input errors */ - noError = 0, - nbLinesTooLarge, - nbLinesTooSmall, - pbDimensionTooLarge, - pbDimensionTooSmall, - nbCriterionTooLarge, - nbCriterionTooSmall, - wrongCriterionName, - nbNbClusterTooLarge, - nbNbClusterTooSmall, - nbModelTypeTooLarge, - nbModelTypeTooSmall, - wrongModelType, - wrongCVinitType, - wrongDCVinitType, - - nbStrategyTypeTooLarge, - - nbStrategyTypeTooSmall, - wrongStrategyInitName, - errorInitParameter, - nbAlgoTooLarge, - nbAlgoTooSmall, - wrongAlgoType, - nbIterationTooLarge, - nbIterationTooSmall, - - epsilonTooSmall, - epsilonTooLarge, - - wrongDataFileName, - wrongWeightFileName, - wrongParamFileName, - wrongLabelFileName, - wrongPartitionFileName, - wrongAlgoStopName, - wrongOutputType, - wrongInputFileName, - wrongXEMNbParam, - errorNbLines, - errorPbDimension, - errorNbCriterion, - errorListCriterion, - errorNbNbCluster, - errorListNbCluster, - errorNbModel, - errorListModel, - errorNbStrategy, - - errorInitType, - errorInitFile, - errorNbAlgo, - errorAlgo, - errorStopRule, - errorStopRuleValue, - - errorDataFile, - nbAlgoTypeTooSmall, - badStrategyInitName, - errorAllEstimation, - errorOpenFile, - noSelectionError, - errorInputSymmetricMatrix, - errorInputDiagonalMatrix, - - errorNbModality, - - knownPartitionNeeded, - badKnownPartition, - endDataFileReach, - - /* Numeric errors */ - nonPositiveDefiniteMatrix, - nullDeterminant, - randomProblem, - nullLikelihood, - noProbability, - pbNEC, - nullNk, - - numericError, - errorSigmaConditionNumber, - minDeterminantSigmaValueError, - minDeterminantWValueError, - minDeterminantDiagWkValueError, - - minDeterminantDiagWValueError, - minDeterminantBValueError, - minDeterminantRValueError, - minDeterminantWkValueError, - minDeterminantShapeValueError, - minDeterminantDiagQtmpValueError, - - - - /* Others errors */ - internalMixmodError, - errorComputationCriterion, - wrongValueInMultinomialCase, - errorPartitionSameSampleNotEqual, - - errorInPartitionInput, - notEnoughValuesInLabelInput, - notEnoughValuesInProbaInput, - badValueInLabelInput, - - - // DCV errors, - wrongDCVinitBlocks, - wrongDCVnumberOfBlocks, - DCVmustBeDIAG, - forbiddenCallToGetBestCVModel, - //DCVonlyInGaussianCase, - allCVCriterionErrorForAnEstimationInDCVContext, - NbDCVBlocksTooSmall, - - // Multinomial - sumFiNullAndfkTPrimNull, - sumFiNullInMultinomialCase, - badXEMBinaryParamterClass, - - - weightTotalIsNotAnInteger, - - wrongNbKnownPartition, - SubDimensionFreeTooLarge, - SubDimensionFreeTooSmall, - SubDimensionEqualTooLarge, - SubDimensionEqualTooSmall, - //errorSubDimension, - - wrongSymmetricMatrixDimension, - wrongGeneralMatrixDimension, - nonImplementedMethod, - tabNkNotInteger, - ungivenSubDimension, - wrongMatrixType, - wrongConstructorType, - wrongNbAlgoWhenMorMAP, - BadInitialsationWhenM, - BadInitialsationWhenMAP, - partitionMustBeComplete, - inputNotFinalized, - algorithmMustBeM, - knownPartitionAndInitPartitionMustBeEqual, - nbStrategyMustBe1, - wrongNbKnownPartitionOrInitPartition, - tooManySampleInInitPartitionAndTooManyClusterNotRepresented, - CEM_INIT_error, - SEM_MAX_error, - SMALL_EM_error, - badStopNameWithSEMAlgo, - badAlgorithmInHDContext, - differentSubDimensionsWithMAP, - selectionErrorWithNoEstimation, - wrongSubDimension, - functionShouldNotBeCalled, - missingRequiredInputs, - // the following errors should not be occur because they must have been see by MVCControler - wrongCriterionPositionInSet, - wrongCriterionPositionInGet, - wrongCriterionPositionInInsert, - wrongCriterionPositionInRemove, - wrongModelPositionInSet, - wrongModelPositionInGet, - wrongModelPositionInInsert, - wrongModelPositionInRemove, - wrongModelPositionInSetSubDimensionEqual, - wrongModelPositionInSetSubDimensionFree, - wrongKnownPartitionPositionInSet, - wrongKnownPartitionPositionInRemove, - badSetKnownPartition, - wrongStrategyPositionInSetOrGetMethod, - nbTryInStrategyTooSmall, - nbTryInStrategyTooLarge, - nbTryInInitTooSmall, - nbTryInInitTooLarge, - epsilonInInitTooSmall, - epsilonInInitTooLarge, - nbIterationInInitTooSmall, - nbIterationInInitTooLarge, - wrongNbStrategyTryValue, - badInitPart, - badSetNbTry, - badSetNbTryInInit, - badSetNbIterationInInit, - badSetEpsilonInInit, - int64_t_max_error, - badSetStopNameInInit, - badCriterion, - badAlgo, - badAlgoStop, - badInputType, - XEMDAInput, - wrongModelName, - knownPartitionNotAvailable, - tooManyWeightColumnDescription, - badDataDescription, - badLabelDescription, - errorInColumnDescription, - errorInXEMInputSelector, - wrongIndexInGetMethod, - nullPointerError, - errorEstimationStrategyRun, - wrongSortCallInXEMModelOutput, - badFormat, - ColumnTypeNotValid -}; - - -/// compute the determinant of a matrix and throw an exception if is is too small - -//double determinant(const XEMMatrix & A,XEMErrorType errorType); -/// compute a^b and throw an error if it's equal to zero -double powAndCheckIfNotNull(double a, double b, XEMErrorType errorType = nullDeterminant); - -/// compute the svd decomposition with eigenvalues in a decreasing order -void XEMSVD(const Matrix& A, DiagonalMatrix& Q, Matrix& U); - -/// return the nearest int64_t -int64_t XEMRound(double d); - -/// convert big char of a string in low char -void ConvertBigtoLowString(string & str); - - - -//XEMModelNameToString -string XEMModelNameToString(const XEMModelName & modelName); - -//StringToXEMModelName -XEMModelName StringToXEMModelName(const string & strModelName); - -//XEMErrorTypeToString -string XEMErrorTypeToString(const XEMErrorType & errorType); - -// edit modelName -void edit(const XEMModelName & modelName); - - -//criterionNameToString -string XEMCriterionNameToString(const XEMCriterionName & criterionName); - -//StringtoXEMCriterionName -XEMCriterionName StringtoXEMCriterionName(const string & str); - -// - -// edit XEMCriterionName -void edit(const XEMCriterionName & criterionName); - - - - -/// editModelType -void editModelType(ofstream & oFile, XEMModelType * modelType); - - - - - - -// XEMAlgoNameToString -string XEMAlgoNameToString(const XEMAlgoName & typeAlgo); - -//StringToAlgoName -XEMAlgoName StringToAlgoName(const string & str); - -// edit XEMAlgoName -void edit(const XEMAlgoName & typeAlgo); - - -//XEMFormatFileToString -string XEMFormatNumericFileToString(const FormatNumeric::XEMFormatNumericFile & formatNumericFile); - -//StringToXEMFormatFile -FormatNumeric::XEMFormatNumericFile StringToXEMFormatNumericFile(const string & strFormatNumericFile); - -//XEMTypePartitionToString -string XEMTypePartitionToString(const TypePartition::XEMTypePartition & typePartition); - -//StringToXEMTypePartition -TypePartition::XEMTypePartition StringToXEMTypePartition(const string & strTypePartition); - -//XEMStrategyInitNameToString -string XEMStrategyInitNameToString(const XEMStrategyInitName & strategyInitName); - -//StringToStrategyInitName -XEMStrategyInitName StringToStrategyInitName(const string & str); - -// edit XEMStrategyInitName -void edit(const XEMStrategyInitName & strategyInitName); - -// XEMAlgoStopNameToString -string XEMAlgoStopNameToString(const XEMAlgoStopName & algoStopName); - -// void XEMAlgoStopName -void edit(const XEMAlgoStopName & algoStopName); - - -// is modelName has free proportion -bool hasFreeProportion(XEMModelName modelName); - -// is modelName a diagonal Gaussian Model -bool isDiagonal(XEMModelName modelNamee); - -// is modelName a spherical Gaussian Model -bool isSpherical(XEMModelName modelName); - -// is modelName a general Gaussian Model -bool isGeneral(XEMModelName modelName); - -// is modelName a EDDA (Classical Gaussian) -bool isEDDA(XEMModelName modelName); - -// is modelName a HD (or HDk) -bool isHD(XEMModelName modelName); - -bool isFreeSubDimension(XEMModelName modelName); - - -bool isBinary(XEMModelName modelName); - -// is Matrix symmetric -bool isSymmetric(Matrix * mat, int64_t n); - - -// is Matrix Diagonal -bool isDiagonal(Matrix * mat, int64_t n); - - -// traitement sur les tableaux -//---------------------------- - -// T* copyTab(T * tab, int64_t dim) -template T * copyTab(T * tab, int64_t dim){ - T * res = new T[dim]; - int64_t i; - for (i=0; i T ** copyTab(T ** tab, int64_t dim1, int64_t dim2){ - T ** res = new T*[dim1]; - int64_t i,j; - for (i=0; i void recopyTab(T * source, T * destination, int64_t dim){ - int64_t i; - for(i=0; i > & destination, int64_t dim1, int64_t dim2){ - destination.resize(dim1); - int64_t i,j; - for(i=0; i & destination, int64_t dim1){ - destination.resize(dim1); - int64_t i; - for(i=0; i > source, double **& destination){ - int64_t dim1 = source.size(); - int64_t dim2 = source[0].size(); - destination = new double*[dim1]; - for (int64_t i=0; i source, int64_t *& destination){ - int64_t dim1 = source.size(); - destination = new int64_t[dim1]; - for (int64_t i=0; i void recopyTab(T ** source, T ** destination, int64_t dim1, int64_t dim2){ - int64_t i,j; - for (i=0; i void editTab(T ** tab, int64_t dim1, int64_t dim2, string sep=" ", string before="", ostream & flux=cout){ - T ** p_tab = tab; - T * p_tab_i; - int64_t i, j ; - for(i=0; i< dim1; i++){ - p_tab_i = *p_tab; - flux << before; - for(j=0; j. - - All informations available on : http://www.mixmod.org -***************************************************************************/ - -#include "XEMWeightColumnDescription.h" - -XEMWeightColumnDescription::XEMWeightColumnDescription():XEMColumnDescription(){ -} - -XEMWeightColumnDescription::XEMWeightColumnDescription(int64_t index):XEMColumnDescription(index){ - _index = index; -} - -XEMWeightColumnDescription::~XEMWeightColumnDescription(){ - -} - -string XEMWeightColumnDescription::editType(){ - return "Weight"; -} - -XEMColumnDescription * XEMWeightColumnDescription::clone()const{ - XEMWeightColumnDescription * WCD = new XEMWeightColumnDescription(); - WCD->_index = _index; - WCD->_name = _name; - return WCD; -} diff --git a/lib/src/mixmod/MIXMOD/XEMWeightColumnDescription.h b/lib/src/mixmod/MIXMOD/XEMWeightColumnDescription.h deleted file mode 100644 index 2f55998..0000000 --- a/lib/src/mixmod/MIXMOD/XEMWeightColumnDescription.h +++ /dev/null @@ -1,51 +0,0 @@ -/*************************************************************************** - SRC/MIXMOD/XEMWeightColumnDescription.h description - copyright : (C) MIXMOD Team - 2001-2011 - email : contact@mixmod.org -***************************************************************************/ - -/*************************************************************************** - This file is part of MIXMOD - - MIXMOD is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - MIXMOD 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with MIXMOD. If not, see . - - All informations available on : http://www.mixmod.org -***************************************************************************/ - - -#ifndef XEMWEIGHTCOLUMNDESCRIPTION_H -#define XEMWEIGHTCOLUMNDESCRIPTION_H - -#include "XEMColumnDescription.h" - -class XEMWeightColumnDescription : public XEMColumnDescription -{ - public : - /// Default constructor - XEMWeightColumnDescription(); - - /// initialization constructor - XEMWeightColumnDescription(int64_t index); - - /// Destructor - virtual ~XEMWeightColumnDescription(); - - string editType(); - - XEMColumnDescription * clone()const; - - -}; - -#endif // XEMWEIGHTCOLUMNDESCRIPTION_H diff --git a/lib/src/mixmod/NEWMAT/CMakeLists.txt b/lib/src/mixmod/NEWMAT/CMakeLists.txt deleted file mode 100644 index 7b065fc..0000000 --- a/lib/src/mixmod/NEWMAT/CMakeLists.txt +++ /dev/null @@ -1,26 +0,0 @@ - -ot_add_current_dir_to_include_dirs () -ot_add_source_file ( bandmat.cpp ) -ot_add_source_file ( cholesky.cpp ) -ot_add_source_file ( evalue.cpp ) -ot_add_source_file ( fft.cpp ) -ot_add_source_file ( hholder.cpp ) -ot_add_source_file ( jacobi.cpp ) -ot_add_source_file ( myexcept.cpp ) -ot_add_source_file ( newfft.cpp ) -ot_add_source_file ( newmat1.cpp ) -ot_add_source_file ( newmat2.cpp ) -ot_add_source_file ( newmat3.cpp ) -ot_add_source_file ( newmat4.cpp ) -ot_add_source_file ( newmat5.cpp ) -ot_add_source_file ( newmat6.cpp ) -ot_add_source_file ( newmat7.cpp ) -ot_add_source_file ( newmat8.cpp ) -ot_add_source_file ( newmat9.cpp ) -ot_add_source_file ( newmatex.cpp ) -ot_add_source_file ( newmatnl.cpp ) -ot_add_source_file ( newmatrm.cpp ) -ot_add_source_file ( solution.cpp ) -ot_add_source_file ( sort.cpp ) -ot_add_source_file ( submat.cpp ) -ot_add_source_file ( svd.cpp ) diff --git a/lib/src/mixmod/NEWMAT/add_time.png b/lib/src/mixmod/NEWMAT/add_time.png deleted file mode 100644 index 58731d4..0000000 Binary files a/lib/src/mixmod/NEWMAT/add_time.png and /dev/null differ diff --git a/lib/src/mixmod/NEWMAT/bandmat.cpp b/lib/src/mixmod/NEWMAT/bandmat.cpp deleted file mode 100644 index 226d9de..0000000 --- a/lib/src/mixmod/NEWMAT/bandmat.cpp +++ /dev/null @@ -1,569 +0,0 @@ -//$$ bandmat.cpp Band matrix definitions - -// Copyright (C) 1991,2,3,4,9: R B Davies - -#define WANT_MATH // include.h will get math fns - -//#define WANT_STREAM - -#include "include.h" - -#include "newmat.h" -#include "newmatrc.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - - - -#ifdef DO_REPORT -#define REPORT { static ExeCounter ExeCount(__LINE__,10); ++ExeCount; } -#else -#define REPORT {} -#endif - - static inline int my_min(int x, int y) { return x < y ? x : y; } - static inline int my_max(int x, int y) { return x > y ? x : y; } - - - BandMatrix::BandMatrix(const BaseMatrix& M) - { - REPORT // CheckConversion(M); - // MatrixConversionCheck mcc; - GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::BM); - GetMatrix(gmx); CornerClear(); - } - - void BandMatrix::SetParameters(const GeneralMatrix* gmx) - { - REPORT - MatrixBandWidth bw = gmx->BandWidth(); - lower = bw.lower; upper = bw.upper; - } - - void BandMatrix::ReSize(int n, int lb, int ub) - { - REPORT - Tracer tr("BandMatrix::ReSize"); - if (lb<0 || ub<0) Throw(ProgramException("Undefined bandwidth")); - lower = (lb<=n) ? lb : n-1; upper = (ub<=n) ? ub : n-1; - GeneralMatrix::ReSize(n,n,n*(lower+1+upper)); CornerClear(); - } - - // SimpleAddOK shows when we can add etc two matrices by a simple vector add - // and when we can add one matrix into another - // *gm must be the same type as *this - // return 0 if simple add is OK - // return 1 if we can add into *gm only - // return 2 if we can add into *this only - // return 3 if we can't add either way - // For SP this will still be valid if we swap 1 and 2 - - short BandMatrix::SimpleAddOK(const GeneralMatrix* gm) - { - const BandMatrix* bm = (const BandMatrix*)gm; - if (bm->lower == lower && bm->upper == upper) { REPORT return 0; } - else if (bm->lower >= lower && bm->upper >= upper) { REPORT return 1; } - else if (bm->lower <= lower && bm->upper <= upper) { REPORT return 2; } - else { REPORT return 3; } - } - - short SymmetricBandMatrix::SimpleAddOK(const GeneralMatrix* gm) - { - const SymmetricBandMatrix* bm = (const SymmetricBandMatrix*)gm; - if (bm->lower == lower) { REPORT return 0; } - else if (bm->lower > lower) { REPORT return 1; } - else { REPORT return 2; } - } - - void UpperBandMatrix::ReSize(int n, int lb, int ub) - { - REPORT - if (lb != 0) - { - Tracer tr("UpperBandMatrix::ReSize"); - Throw(ProgramException("UpperBandMatrix with non-zero lower band" )); - } - BandMatrix::ReSize(n, lb, ub); - } - - void LowerBandMatrix::ReSize(int n, int lb, int ub) - { - REPORT - if (ub != 0) - { - Tracer tr("LowerBandMatrix::ReSize"); - Throw(ProgramException("LowerBandMatrix with non-zero upper band" )); - } - BandMatrix::ReSize(n, lb, ub); - } - - void BandMatrix::ReSize(const GeneralMatrix& A) - { - REPORT - int n = A.Nrows(); - if (n != A.Ncols()) - { - Tracer tr("BandMatrix::ReSize(GM)"); - Throw(NotSquareException(*this)); - } - MatrixBandWidth mbw = A.BandWidth(); - ReSize(n, mbw.Lower(), mbw.Upper()); - } - - bool BandMatrix::SameStorageType(const GeneralMatrix& A) const - { - if (Type() != A.Type()) { REPORT return false; } - REPORT - return BandWidth() == A.BandWidth(); - } - - void BandMatrix::ReSizeForAdd(const GeneralMatrix& A, const GeneralMatrix& B) - { - REPORT - Tracer tr("BandMatrix::ReSizeForAdd"); - MatrixBandWidth A_BW = A.BandWidth(); MatrixBandWidth B_BW = B.BandWidth(); - if ((A_BW.Lower() < 0) | (A_BW.Upper() < 0) | (B_BW.Lower() < 0) - | (A_BW.Upper() < 0)) - Throw(ProgramException("Can't ReSize to BandMatrix" )); - // already know A and B are square - ReSize(A.Nrows(), my_max(A_BW.Lower(), B_BW.Lower()), - my_max(A_BW.Upper(), B_BW.Upper())); - } - - void BandMatrix::ReSizeForSP(const GeneralMatrix& A, const GeneralMatrix& B) - { - REPORT - Tracer tr("BandMatrix::ReSizeForSP"); - MatrixBandWidth A_BW = A.BandWidth(); MatrixBandWidth B_BW = B.BandWidth(); - if ((A_BW.Lower() < 0) | (A_BW.Upper() < 0) | (B_BW.Lower() < 0) - | (A_BW.Upper() < 0)) - Throw(ProgramException("Can't ReSize to BandMatrix" )); - // already know A and B are square - ReSize(A.Nrows(), my_min(A_BW.Lower(), B_BW.Lower()), - my_min(A_BW.Upper(), B_BW.Upper())); - } - - - void BandMatrix::operator=(const BaseMatrix& X) - { - REPORT // CheckConversion(X); - // MatrixConversionCheck mcc; - Eq(X,MatrixType::BM); CornerClear(); - } - - void BandMatrix::CornerClear() const - { - // set unused parts of BandMatrix to zero - REPORT - int i = lower; Real* s = store; int bw = lower + 1 + upper; - while (i) - { int j = i--; Real* sj = s; s += bw; while (j--) *sj++ = 0.0; } - i = upper; s = store + storage; - while (i) - { int j = i--; Real* sj = s; s -= bw; while (j--) *(--sj) = 0.0; } - } - - MatrixBandWidth MatrixBandWidth::operator+(const MatrixBandWidth& bw) const - { - REPORT - int l = bw.lower; int u = bw.upper; - l = (lower < 0 || l < 0) ? -1 : (lower > l) ? lower : l; - u = (upper < 0 || u < 0) ? -1 : (upper > u) ? upper : u; - return MatrixBandWidth(l,u); - } - - MatrixBandWidth MatrixBandWidth::operator*(const MatrixBandWidth& bw) const - { - REPORT - int l = bw.lower; int u = bw.upper; - l = (lower < 0 || l < 0) ? -1 : lower+l; - u = (upper < 0 || u < 0) ? -1 : upper+u; - return MatrixBandWidth(l,u); - } - - MatrixBandWidth MatrixBandWidth::minimum(const MatrixBandWidth& bw) const - { - REPORT - int l = bw.lower; int u = bw.upper; - if ((lower >= 0) && ( (l < 0) || (l > lower) )) l = lower; - if ((upper >= 0) && ( (u < 0) || (u > upper) )) u = upper; - return MatrixBandWidth(l,u); - } - - UpperBandMatrix::UpperBandMatrix(const BaseMatrix& M) - { - REPORT // CheckConversion(M); - // MatrixConversionCheck mcc; - GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::UB); - GetMatrix(gmx); CornerClear(); - } - - void UpperBandMatrix::operator=(const BaseMatrix& X) - { - REPORT // CheckConversion(X); - // MatrixConversionCheck mcc; - Eq(X,MatrixType::UB); CornerClear(); - } - - LowerBandMatrix::LowerBandMatrix(const BaseMatrix& M) - { - REPORT // CheckConversion(M); - // MatrixConversionCheck mcc; - GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::LB); - GetMatrix(gmx); CornerClear(); - } - - void LowerBandMatrix::operator=(const BaseMatrix& X) - { - REPORT // CheckConversion(X); - // MatrixConversionCheck mcc; - Eq(X,MatrixType::LB); CornerClear(); - } - - BandLUMatrix::BandLUMatrix(const BaseMatrix& m) - { - REPORT - Tracer tr("BandLUMatrix"); - storage2 = 0; store2 = 0; // in event of exception during build - GeneralMatrix* gm = ((BaseMatrix&)m).Evaluate(MatrixType::BM); - m1 = ((BandMatrix*)gm)->lower; m2 = ((BandMatrix*)gm)->upper; - GetMatrix(gm); - if (nrows!=ncols) Throw(NotSquareException(*this)); - d = true; sing = false; - indx = new int [nrows]; MatrixErrorNoSpace(indx); - MONITOR_INT_NEW("Index (BndLUMat)",nrows,indx) - storage2 = nrows * m1; - store2 = new Real [storage2]; MatrixErrorNoSpace(store2); - MONITOR_REAL_NEW("Make (BandLUMat)",storage2,store2) - ludcmp(); - } - - BandLUMatrix::~BandLUMatrix() - { - REPORT - MONITOR_INT_DELETE("Index (BndLUMat)",nrows,indx) - MONITOR_REAL_DELETE("Delete (BndLUMt)",storage2,store2) - delete [] indx; delete [] store2; - } - - MatrixType BandLUMatrix::Type() const { REPORT return MatrixType::BC; } - - - LogAndSign BandLUMatrix::LogDeterminant() const - { - REPORT - if (sing) return 0.0; - Real* a = store; int w = m1+1+m2; LogAndSign sum; int i = nrows; - // while (i--) { sum *= *a; a += w; } - if (i) for (;;) { sum *= *a; if (!(--i)) break; a += w; } - if (!d) sum.ChangeSign(); return sum; - } - - GeneralMatrix* BandMatrix::MakeSolver() - { - REPORT - GeneralMatrix* gm = new BandLUMatrix(*this); - MatrixErrorNoSpace(gm); gm->ReleaseAndDelete(); return gm; - } - - - void BandLUMatrix::ludcmp() - { - REPORT - Real* a = store2; int i = storage2; - // clear store2 - so unused locations are always zero - - // required by operator== - while (i--) *a++ = 0.0; - a = store; - i = m1; int j = m2; int k; int n = nrows; int w = m1 + 1 + m2; - while (i) - { - Real* ai = a + i; - k = ++j; while (k--) *a++ = *ai++; - k = i--; while (k--) *a++ = 0.0; - } - - a = store; int l = m1; - for (k=0; k=mini; i--) - { - Real* b = B + i; Real* bk = b; Real x = *bk; - Real* a = store + w*i; Real y = *a; - int k = l+m1; while (k--) x -= *(++a) * *(++bk); - *b = x / y; - if (l < m2) l++; - } - } - - void BandLUMatrix::Solver(MatrixColX& mcout, const MatrixColX& mcin) - { - REPORT - int i = mcin.skip; Real* el = mcin.data-i; Real* el1=el; - while (i--) *el++ = 0.0; - el += mcin.storage; i = nrows - mcin.skip - mcin.storage; - while (i--) *el++ = 0.0; - lubksb(el1, mcout.skip); - } - - // Do we need check for entirely zero output? - - - void UpperBandMatrix::Solver(MatrixColX& mcout, - const MatrixColX& mcin) - { - REPORT - int i = mcin.skip-mcout.skip; Real* elx = mcin.data-i; - while (i-- > 0) *elx++ = 0.0; - int nr = mcin.skip+mcin.storage; - elx = mcin.data+mcin.storage; Real* el = elx; - int j = mcout.skip+mcout.storage-nr; i = nr-mcout.skip; - while (j-- > 0) *elx++ = 0.0; - - Real* Ael = store + (upper+1)*(i-1)+1; j = 0; - if (i > 0) for(;;) - { - elx = el; Real sum = 0.0; int jx = j; - while (jx--) sum += *(--Ael) * *(--elx); - elx--; *elx = (*elx - sum) / *(--Ael); - if (--i <= 0) break; - if (j 0) *elx++ = 0.0; - int nc = mcin.skip; i = nc+mcin.storage; elx = mcin.data+mcin.storage; - int nr = mcout.skip+mcout.storage; int j = nr-i; i = nr-nc; - while (j-- > 0) *elx++ = 0.0; - - Real* el = mcin.data; Real* Ael = store + (lower+1)*nc + lower; j = 0; - if (i > 0) for(;;) - { - elx = el; Real sum = 0.0; int jx = j; - while (jx--) sum += *Ael++ * *elx++; - *elx = (*elx - sum) / *Ael++; - if (--i <= 0) break; - if (jReleaseAndDelete(); return gm; - } - - SymmetricBandMatrix::SymmetricBandMatrix(const BaseMatrix& M) - { - REPORT // CheckConversion(M); - // MatrixConversionCheck mcc; - GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::SB); - GetMatrix(gmx); - } - - GeneralMatrix* SymmetricBandMatrix::Transpose(TransposedMatrix*, MatrixType mt) - { REPORT return Evaluate(mt); } - - LogAndSign SymmetricBandMatrix::LogDeterminant() const - { - REPORT - BandLUMatrix C(*this); return C.LogDeterminant(); - } - - void SymmetricBandMatrix::SetParameters(const GeneralMatrix* gmx) - { REPORT lower = gmx->BandWidth().lower; } - - void SymmetricBandMatrix::ReSize(int n, int lb) - { - REPORT - Tracer tr("SymmetricBandMatrix::ReSize"); - if (lb<0) Throw(ProgramException("Undefined bandwidth")); - lower = (lb<=n) ? lb : n-1; - GeneralMatrix::ReSize(n,n,n*(lower+1)); - } - - void SymmetricBandMatrix::ReSize(const GeneralMatrix& A) - { - REPORT - int n = A.Nrows(); - if (n != A.Ncols()) - { - Tracer tr("SymmetricBandMatrix::ReSize(GM)"); - Throw(NotSquareException(*this)); - } - MatrixBandWidth mbw = A.BandWidth(); int b = mbw.Lower(); - if (b != mbw.Upper()) - { - Tracer tr("SymmetricBandMatrix::ReSize(GM)"); - Throw(ProgramException("Upper and lower band-widths not equal")); - } - ReSize(n, b); - } - - bool SymmetricBandMatrix::SameStorageType(const GeneralMatrix& A) const - { - if (Type() != A.Type()) { REPORT return false; } - REPORT - return BandWidth() == A.BandWidth(); - } - - void SymmetricBandMatrix::ReSizeForAdd(const GeneralMatrix& A, - const GeneralMatrix& B) - { - REPORT - Tracer tr("SymmetricBandMatrix::ReSizeForAdd"); - MatrixBandWidth A_BW = A.BandWidth(); MatrixBandWidth B_BW = B.BandWidth(); - if ((A_BW.Lower() < 0) | (B_BW.Lower() < 0)) - Throw(ProgramException("Can't ReSize to SymmetricBandMatrix" )); - // already know A and B are square - ReSize(A.Nrows(), my_max(A_BW.Lower(), B_BW.Lower())); - } - - void SymmetricBandMatrix::ReSizeForSP(const GeneralMatrix& A, - const GeneralMatrix& B) - { - REPORT - Tracer tr("SymmetricBandMatrix::ReSizeForSP"); - MatrixBandWidth A_BW = A.BandWidth(); MatrixBandWidth B_BW = B.BandWidth(); - if ((A_BW.Lower() < 0) | (B_BW.Lower() < 0)) - Throw(ProgramException("Can't ReSize to SymmetricBandMatrix" )); - // already know A and B are square - ReSize(A.Nrows(), my_min(A_BW.Lower(), B_BW.Lower())); - } - - - void SymmetricBandMatrix::operator=(const BaseMatrix& X) - { - REPORT // CheckConversion(X); - // MatrixConversionCheck mcc; - Eq(X,MatrixType::SB); - } - - void SymmetricBandMatrix::CornerClear() const - { - // set unused parts of BandMatrix to zero - REPORT - int i = lower; Real* s = store; int bw = lower + 1; - if (i) for(;;) - { - int j = i; - Real* sj = s; - while (j--) *sj++ = 0.0; - if (!(--i)) break; - s += bw; - } - } - - MatrixBandWidth SymmetricBandMatrix::BandWidth() const - { REPORT return MatrixBandWidth(lower,lower); } - - inline Real square(Real x) { return x*x; } - - - Real SymmetricBandMatrix::SumSquare() const - { - REPORT - CornerClear(); - Real sum1=0.0; Real sum2=0.0; Real* s=store; int i=nrows; int l=lower; - while (i--) - { int j = l; while (j--) sum2 += square(*s++); sum1 += square(*s++); } - ((GeneralMatrix&)*this).tDelete(); return sum1 + 2.0 * sum2; - } - - Real SymmetricBandMatrix::SumAbsoluteValue() const - { - REPORT - CornerClear(); - Real sum1=0.0; Real sum2=0.0; Real* s=store; int i=nrows; int l=lower; - while (i--) - { int j = l; while (j--) sum2 += fabs(*s++); sum1 += fabs(*s++); } - ((GeneralMatrix&)*this).tDelete(); return sum1 + 2.0 * sum2; - } - - Real SymmetricBandMatrix::Sum() const - { - REPORT - CornerClear(); - Real sum1=0.0; Real sum2=0.0; Real* s=store; int i=nrows; int l=lower; - while (i--) - { int j = l; while (j--) sum2 += *s++; sum1 += *s++; } - ((GeneralMatrix&)*this).tDelete(); return sum1 + 2.0 * sum2; - } - - -#ifdef use_namespace -} -#endif - diff --git a/lib/src/mixmod/NEWMAT/boolean.h b/lib/src/mixmod/NEWMAT/boolean.h deleted file mode 100644 index a601961..0000000 --- a/lib/src/mixmod/NEWMAT/boolean.h +++ /dev/null @@ -1,40 +0,0 @@ -//$$ boolean.h bool class - -// This is for compilers that do not have bool automatically defined - -#ifndef bool_LIB -#define bool_LIB 0 - -#ifdef use_namespace -namespace RBD_COMMON { -#endif - - - class bool - { - int value; - public: - bool(const int b) { value = b ? 1 : 0; } - bool(const void* b) { value = b ? 1 : 0; } - bool() {} - operator int() const { return value; } - int operator!() const { return !value; } - }; - - - const bool true = 1; - const bool false = 0; - - - - // version for some older versions of gnu g++ - //#define false 0 - //#define true 1 - -#ifdef use_namespace -} -#endif - - - -#endif diff --git a/lib/src/mixmod/NEWMAT/cholesky.cpp b/lib/src/mixmod/NEWMAT/cholesky.cpp deleted file mode 100644 index 83f689d..0000000 --- a/lib/src/mixmod/NEWMAT/cholesky.cpp +++ /dev/null @@ -1,88 +0,0 @@ -//$$ cholesky.cpp cholesky decomposition - -// Copyright (C) 1991,2,3,4: R B Davies - -#define WANT_MATH -//#define WANT_STREAM - -#include "include.h" - -#include "newmat.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - -#ifdef DO_REPORT -#define REPORT { static ExeCounter ExeCount(__LINE__,14); ++ExeCount; } -#else -#define REPORT {} -#endif - - /********* Cholesky decomposition of a positive definite matrix *************/ - - // Suppose S is symmetrix and positive definite. Then there exists a unique - // lower triangular matrix L such that L L.t() = S; - - inline Real square(Real x) { return x*x; } - - ReturnMatrix Cholesky(const SymmetricMatrix& S) - { - REPORT - Tracer trace("Cholesky"); - int nr = S.Nrows(); - LowerTriangularMatrix T(nr); - Real* s = S.Store(); Real* t = T.Store(); Real* ti = t; - for (int i=0; i=(ControlWord i) const { return (cw & i.cw) == i.cw; } - bool operator<=(ControlWord i) const { return (cw & i.cw) == cw; } - - // flip selected bits - ControlWord operator^(ControlWord i) const - { return ControlWord(cw ^ i.cw); } - ControlWord operator~() const { return ControlWord(~cw); } - - // convert to integer - int operator+() const { return cw; } - int operator!() const { return cw==0; } - FREE_CHECK(ControlWord) - }; - - -#endif diff --git a/lib/src/mixmod/NEWMAT/evalue.cpp b/lib/src/mixmod/NEWMAT/evalue.cpp deleted file mode 100644 index 7e1bb41..0000000 --- a/lib/src/mixmod/NEWMAT/evalue.cpp +++ /dev/null @@ -1,297 +0,0 @@ -//$$evalue.cpp eigen-value decomposition - -// Copyright (C) 1991,2,3,4: R B Davies - -#define WANT_MATH - -#include "include.h" -#include "newmatap.h" -#include "newmatrm.h" -#include "precisio.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - -#ifdef DO_REPORT -#define REPORT { static ExeCounter ExeCount(__LINE__,17); ++ExeCount; } -#else -#define REPORT {} -#endif - - - - static void tred2(const SymmetricMatrix& A, DiagonalMatrix& D, - DiagonalMatrix& E, Matrix& Z) - { - Tracer et("Evalue(tred2)"); - REPORT - Real tol = - FloatingPointPrecision::Minimum()/FloatingPointPrecision::Epsilon(); - int n = A.Nrows(); Z.ReSize(n,n); Z.Inject(A); - D.ReSize(n); E.ReSize(n); - Real* z = Z.Store(); int i; - - for (i=n-1; i > 0; i--) // i=0 is excluded - { - Real f = Z.element(i,i-1); Real g = 0.0; - int k = i-1; Real* zik = z + i*n; - while (k--) g += square(*zik++); - Real h = g + square(f); - if (g <= tol) { REPORT E.element(i) = f; h = 0.0; } - else - { - REPORT - g = sign(-sqrt(h), f); E.element(i) = g; h -= f*g; - Z.element(i,i-1) = f-g; f = 0.0; - Real* zji = z + i; Real* zij = z + i*n; Real* ej = E.Store(); - int j; - for (j=0; j=l; i--) - { - Real ei = E.element(i); Real di = D.element(i); - Real& ei1 = E.element(i+1); - g = c * ei; h = c * p; - if ( fabs(p) >= fabs(ei)) - { - REPORT - c = ei / p; r = sqrt(c*c + 1.0); - ei1 = s*p*r; s = c/r; c = 1.0/r; - } - else - { - REPORT - c = p / ei; r = sqrt(c*c + 1.0); - ei1 = s * ei * r; s = 1.0/r; c /= r; - } - p = c * di - s*g; D.element(i+1) = h + s * (c*g + s*di); - - Real* zki = z + i; Real* zki1 = zki + 1; int k = n; - if (k) for (;;) - { - REPORT - h = *zki1; *zki1 = s*(*zki) + c*h; *zki = c*(*zki) - s*h; - if (!(--k)) break; - zki += n; zki1 += n; - } - } - el = s*p; dl = c*p; - if (fabs(el) <= b) { REPORT; test = true; break; } - } - if (!test) Throw ( ConvergenceException(D) ); - dl += f; - } - /* - for (int i=0; i= 0; i--) - { - Real h = 0.0; Real f = - FloatingPointPrecision::Maximum(); - Real* d = D.Store(); Real* a = A.Store() + (i*(i+1))/2; int k = i; - while (k--) { f = *a++; *d++ = f; h += square(f); } - if (h <= tol) { REPORT *(--ei) = 0.0; h = 0.0; } - else - { - REPORT - Real g = sign(-sqrt(h), f); *(--ei) = g; h -= f*g; - f -= g; *(d-1) = f; *(a-1) = f; f = 0.0; - Real* dj = D.Store(); Real* ej = E.Store(); int j; - for (j = 0; j < i; j++) - { - Real* dk = D.Store(); Real* ak = A.Store()+(j*(j+1))/2; - Real g = 0.0; k = j; - while (k--) g += *ak++ * *dk++; - k = i-j; int l = j; - if (k) for (;;) { g += *ak * *dk++; if (!(--k)) break; ak += ++l; } - g /= h; *ej++ = g; f += g * *dj++; - } - Real hh = f / (2 * h); Real* ak = A.Store(); - dj = D.Store(); ej = E.Store(); - for (j = 0; j < i; j++) - { - f = *dj++; g = *ej - hh * f; *ej++ = g; - Real* dk = D.Store(); Real* ek = E.Store(); k = j+1; - while (k--) { *ak++ -= (f * *ek++ + g * *dk++); } - } - } - *d = *a; *a = h; - } - } - - static void tql1(DiagonalMatrix& D, DiagonalMatrix& E) - { - Tracer et("Evalue(tql1)"); - REPORT - Real eps = FloatingPointPrecision::Epsilon(); - int n = D.Nrows(); int l; - for (l=1; l=l; i--) - { - Real ei = E.element(i); Real di = D.element(i); - Real& ei1 = E.element(i+1); - g = c * ei; h = c * p; - if ( fabs(p) >= fabs(ei)) - { - REPORT - c = ei / p; r = sqrt(c*c + 1.0); - ei1 = s*p*r; s = c/r; c = 1.0/r; - } - else - { - REPORT - c = p / ei; r = sqrt(c*c + 1.0); - ei1 = s * ei * r; s = 1.0/r; c /= r; - } - p = c * di - s*g; D.element(i+1) = h + s * (c*g + s*di); - } - el = s*p; dl = c*p; - if (fabs(el) <= b) { REPORT test = true; break; } - } - if (!test) Throw ( ConvergenceException(D) ); - Real p = dl + f; - test = false; - for (i=l; i>0; i--) - { - if (p < D.element(i-1)) { REPORT D.element(i) = D.element(i-1); } - else { REPORT test = true; break; } - } - if (!test) i=0; - D.element(i) = p; - } - } - - void EigenValues(const SymmetricMatrix& A, DiagonalMatrix& D, Matrix& Z) - { REPORT DiagonalMatrix E; tred2(A, D, E, Z); tql2(D, E, Z); SortSV(D,Z,true); } - - void EigenValues(const SymmetricMatrix& X, DiagonalMatrix& D) - { REPORT DiagonalMatrix E; SymmetricMatrix A; tred3(X,D,E,A); tql1(D,E); } - - void EigenValues(const SymmetricMatrix& X, DiagonalMatrix& D, - SymmetricMatrix& A) - { REPORT DiagonalMatrix E; tred3(X,D,E,A); tql1(D,E); } - - -#ifdef use_namespace -} -#endif - diff --git a/lib/src/mixmod/NEWMAT/fft.cpp b/lib/src/mixmod/NEWMAT/fft.cpp deleted file mode 100644 index 3c21118..0000000 --- a/lib/src/mixmod/NEWMAT/fft.cpp +++ /dev/null @@ -1,450 +0,0 @@ -//$$ fft.cpp Fast fourier transform - -// Copyright (C) 1991,2,3,4,8: R B Davies - - -#define WANT_MATH -// #define WANT_STREAM - -#include "include.h" - -#include "newmatap.h" - -// #include "newmatio.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - -#ifdef DO_REPORT -#define REPORT { static ExeCounter ExeCount(__LINE__,19); ++ExeCount; } -#else -#define REPORT {} -#endif - - static void cossin(int n, int d, Real& c, Real& s) - // calculate cos(twopi*n/d) and sin(twopi*n/d) - // minimise roundoff error - { - REPORT - long n4 = n * 4; int sector = (int)floor( (Real)n4 / (Real)d + 0.5 ); - n4 -= sector * d; - if (sector < 0) { REPORT sector = 3 - (3 - sector) % 4; } - else { REPORT sector %= 4; } - Real ratio = 1.5707963267948966192 * (Real)n4 / (Real)d; - - switch (sector) - { - case 0: REPORT c = cos(ratio); s = sin(ratio); break; - case 1: REPORT c = -sin(ratio); s = cos(ratio); break; - case 2: REPORT c = -cos(ratio); s = -sin(ratio); break; - case 3: REPORT c = sin(ratio); s = -cos(ratio); break; - } - } - - static void fftstep(ColumnVector& A, ColumnVector& B, ColumnVector& X, - ColumnVector& Y, int after, int now, int before) - { - REPORT - Tracer trace("FFT(step)"); - // const Real twopi = 6.2831853071795864769; - const int gamma = after * before; const int delta = now * after; - // const Real angle = twopi / delta; Real temp; - // Real r_omega = cos(angle); Real i_omega = -sin(angle); - Real r_arg = 1.0; Real i_arg = 0.0; - Real* x = X.Store(); Real* y = Y.Store(); // pointers to array storage - const int m = A.Nrows() - gamma; - - for (int j = 0; j < now; j++) - { - Real* a = A.Store(); Real* b = B.Store(); // pointers to array storage - Real* x1 = x; Real* y1 = y; x += after; y += after; - for (int ia = 0; ia < after; ia++) - { - // generate sins & cosines explicitly rather than iteratively - // for more accuracy; but slower - cossin(-(j*after+ia), delta, r_arg, i_arg); - - Real* a1 = a++; Real* b1 = b++; Real* x2 = x1++; Real* y2 = y1++; - if (now==2) - { - REPORT int ib = before; - if (ib) for (;;) - { - REPORT - Real* a2 = m + a1; Real* b2 = m + b1; a1 += after; b1 += after; - Real r_value = *a2; Real i_value = *b2; - *x2 = r_value * r_arg - i_value * i_arg + *(a2-gamma); - *y2 = r_value * i_arg + i_value * r_arg + *(b2-gamma); - if (!(--ib)) break; - x2 += delta; y2 += delta; - } - } - else - { - REPORT int ib = before; - if (ib) for (;;) - { - REPORT - Real* a2 = m + a1; Real* b2 = m + b1; a1 += after; b1 += after; - Real r_value = *a2; Real i_value = *b2; - int in = now-1; while (in--) - { - // it should be possible to make this faster - // hand code for now = 2,3,4,5,8 - // use symmetry to halve number of operations - a2 -= gamma; b2 -= gamma; Real temp = r_value; - r_value = r_value * r_arg - i_value * i_arg + *a2; - i_value = temp * i_arg + i_value * r_arg + *b2; - } - *x2 = r_value; *y2 = i_value; - if (!(--ib)) break; - x2 += delta; y2 += delta; - } - } - - // temp = r_arg; - // r_arg = r_arg * r_omega - i_arg * i_omega; - // i_arg = temp * i_omega + i_arg * r_omega; - - } - } - } - - - void FFTI(const ColumnVector& U, const ColumnVector& V, - ColumnVector& X, ColumnVector& Y) - { - // Inverse transform - Tracer trace("FFTI"); - REPORT - FFT(U,-V,X,Y); - const Real n = X.Nrows(); X /= n; Y /= (-n); - } - - void RealFFT(const ColumnVector& U, ColumnVector& X, ColumnVector& Y) - { - // Fourier transform of a real series - Tracer trace("RealFFT"); - REPORT - const int n = U.Nrows(); // length of arrays - const int n2 = n / 2; - if (n != 2 * n2) - Throw(ProgramException("Vector length not multiple of 2", U)); - ColumnVector A(n2), B(n2); - Real* a = A.Store(); Real* b = B.Store(); Real* u = U.Store(); int i = n2; - while (i--) { *a++ = *u++; *b++ = *u++; } - FFT(A,B,A,B); - int n21 = n2 + 1; - X.ReSize(n21); Y.ReSize(n21); - i = n2 - 1; - a = A.Store(); b = B.Store(); // first els of A and B - Real* an = a + i; Real* bn = b + i; // last els of A and B - Real* x = X.Store(); Real* y = Y.Store(); // first els of X and Y - Real* xn = x + n2; Real* yn = y + n2; // last els of X and Y - - *x++ = *a + *b; *y++ = 0.0; // first complex element - *xn-- = *a++ - *b++; *yn-- = 0.0; // last complex element - - int j = -1; i = n2/2; - while (i--) - { - Real c,s; cossin(j--,n,c,s); - Real am = *a - *an; Real ap = *a++ + *an--; - Real bm = *b - *bn; Real bp = *b++ + *bn--; - Real samcbp = s * am + c * bp; Real sbpcam = s * bp - c * am; - *x++ = 0.5 * ( ap + samcbp); *y++ = 0.5 * ( bm + sbpcam); - *xn-- = 0.5 * ( ap - samcbp); *yn-- = 0.5 * (-bm + sbpcam); - } - } - - void RealFFTI(const ColumnVector& A, const ColumnVector& B, ColumnVector& U) - { - // inverse of a Fourier transform of a real series - Tracer trace("RealFFTI"); - REPORT - const int n21 = A.Nrows(); // length of arrays - if (n21 != B.Nrows() || n21 == 0) - Throw(ProgramException("Vector lengths unequal or zero", A, B)); - const int n2 = n21 - 1; const int n = 2 * n2; int i = n2 - 1; - - ColumnVector X(n2), Y(n2); - Real* a = A.Store(); Real* b = B.Store(); // first els of A and B - Real* an = a + n2; Real* bn = b + n2; // last els of A and B - Real* x = X.Store(); Real* y = Y.Store(); // first els of X and Y - Real* xn = x + i; Real* yn = y + i; // last els of X and Y - - Real hn = 0.5 / n2; - *x++ = hn * (*a + *an); *y++ = - hn * (*a - *an); - a++; an--; b++; bn--; - int j = -1; i = n2/2; - while (i--) - { - Real c,s; cossin(j--,n,c,s); - Real am = *a - *an; Real ap = *a++ + *an--; - Real bm = *b - *bn; Real bp = *b++ + *bn--; - Real samcbp = s * am - c * bp; Real sbpcam = s * bp + c * am; - *x++ = hn * ( ap + samcbp); *y++ = - hn * ( bm + sbpcam); - *xn-- = hn * ( ap - samcbp); *yn-- = - hn * (-bm + sbpcam); - } - FFT(X,Y,X,Y); // have done inverting elsewhere - U.ReSize(n); i = n2; - x = X.Store(); y = Y.Store(); Real* u = U.Store(); - while (i--) { *u++ = *x++; *u++ = - *y++; } - } - - void FFT(const ColumnVector& U, const ColumnVector& V, - ColumnVector& X, ColumnVector& Y) - { - // from Carl de Boor (1980), Siam J Sci Stat Comput, 1 173-8 - // but first try Sande and Gentleman - Tracer trace("FFT"); - REPORT - const int n = U.Nrows(); // length of arrays - if (n != V.Nrows() || n == 0) - Throw(ProgramException("Vector lengths unequal or zero", U, V)); - if (n == 1) { REPORT X = U; Y = V; return; } - - // see if we can use the newfft routine - if (!FFT_Controller::OnlyOldFFT && FFT_Controller::CanFactor(n)) - { - REPORT - X = U; Y = V; - if ( FFT_Controller::ar_1d_ft(n,X.Store(),Y.Store()) ) return; - } - - ColumnVector B = V; - ColumnVector A = U; - X.ReSize(n); Y.ReSize(n); - const int nextmx = 8; -#ifndef ATandT - int prime[8] = { 2,3,5,7,11,13,17,19 }; -#else - int prime[8]; - prime[0]=2; prime[1]=3; prime[2]=5; prime[3]=7; - prime[4]=11; prime[5]=13; prime[6]=17; prime[7]=19; -#endif - int after = 1; int before = n; int next = 0; bool inzee = true; - int now = 0; int b1; // initialised to keep gnu happy - - do - { - for (;;) - { - if (next < nextmx) { REPORT now = prime[next]; } - b1 = before / now; if (b1 * now == before) { REPORT break; } - next++; now += 2; - } - before = b1; - - if (inzee) { REPORT fftstep(A, B, X, Y, after, now, before); } - else { REPORT fftstep(X, Y, A, B, after, now, before); } - - inzee = !inzee; after *= now; - } - while (before != 1); - - if (inzee) { REPORT A.Release(); X = A; B.Release(); Y = B; } - } - - // Trigonometric transforms - // see Charles Van Loan (1992) "Computational frameworks for the fast - // Fourier transform" published by SIAM; section 4.4. - - void DCT_II(const ColumnVector& U, ColumnVector& V) - { - // Discrete cosine transform, type II, of a real series - Tracer trace("DCT_II"); - REPORT - const int n = U.Nrows(); // length of arrays - const int n2 = n / 2; const int n4 = n * 4; - if (n != 2 * n2) - Throw(ProgramException("Vector length not multiple of 2", U)); - ColumnVector A(n); - Real* a = A.Store(); Real* b = a + n; Real* u = U.Store(); - int i = n2; - while (i--) { *a++ = *u++; *(--b) = *u++; } - ColumnVector X, Y; - RealFFT(A, X, Y); A.CleanUp(); - V.ReSize(n); - Real* x = X.Store(); Real* y = Y.Store(); - Real* v = V.Store(); Real* w = v + n; - *v = *x; - int k = 0; i = n2; - while (i--) - { - Real c, s; cossin(++k, n4, c, s); - Real xi = *(++x); Real yi = *(++y); - *(++v) = xi * c + yi * s; *(--w) = xi * s - yi * c; - } - } - - void DCT_II_inverse(const ColumnVector& V, ColumnVector& U) - { - // Inverse of discrete cosine transform, type II - Tracer trace("DCT_II_inverse"); - REPORT - const int n = V.Nrows(); // length of array - const int n2 = n / 2; const int n4 = n * 4; const int n21 = n2 + 1; - if (n != 2 * n2) - Throw(ProgramException("Vector length not multiple of 2", V)); - ColumnVector X(n21), Y(n21); - Real* x = X.Store(); Real* y = Y.Store(); - Real* v = V.Store(); Real* w = v + n; - *x = *v; *y = 0.0; - int i = n2; int k = 0; - while (i--) - { - Real c, s; cossin(++k, n4, c, s); - Real vi = *(++v); Real wi = *(--w); - *(++x) = vi * c + wi * s; *(++y) = vi * s - wi * c; - } - ColumnVector A; RealFFTI(X, Y, A); - X.CleanUp(); Y.CleanUp(); U.ReSize(n); - Real* a = A.Store(); Real* b = a + n; Real* u = U.Store(); - i = n2; - while (i--) { *u++ = *a++; *u++ = *(--b); } - } - - void DST_II(const ColumnVector& U, ColumnVector& V) - { - // Discrete sine transform, type II, of a real series - Tracer trace("DST_II"); - REPORT - const int n = U.Nrows(); // length of arrays - const int n2 = n / 2; const int n4 = n * 4; - if (n != 2 * n2) - Throw(ProgramException("Vector length not multiple of 2", U)); - ColumnVector A(n); - Real* a = A.Store(); Real* b = a + n; Real* u = U.Store(); - int i = n2; - while (i--) { *a++ = *u++; *(--b) = -(*u++); } - ColumnVector X, Y; - RealFFT(A, X, Y); A.CleanUp(); - V.ReSize(n); - Real* x = X.Store(); Real* y = Y.Store(); - Real* v = V.Store(); Real* w = v + n; - *(--w) = *x; - int k = 0; i = n2; - while (i--) - { - Real c, s; cossin(++k, n4, c, s); - Real xi = *(++x); Real yi = *(++y); - *v++ = xi * s - yi * c; *(--w) = xi * c + yi * s; - } - } - - void DST_II_inverse(const ColumnVector& V, ColumnVector& U) - { - // Inverse of discrete sine transform, type II - Tracer trace("DST_II_inverse"); - REPORT - const int n = V.Nrows(); // length of array - const int n2 = n / 2; const int n4 = n * 4; const int n21 = n2 + 1; - if (n != 2 * n2) - Throw(ProgramException("Vector length not multiple of 2", V)); - ColumnVector X(n21), Y(n21); - Real* x = X.Store(); Real* y = Y.Store(); - Real* v = V.Store(); Real* w = v + n; - *x = *(--w); *y = 0.0; - int i = n2; int k = 0; - while (i--) - { - Real c, s; cossin(++k, n4, c, s); - Real vi = *v++; Real wi = *(--w); - *(++x) = vi * s + wi * c; *(++y) = - vi * c + wi * s; - } - ColumnVector A; RealFFTI(X, Y, A); - X.CleanUp(); Y.CleanUp(); U.ReSize(n); - Real* a = A.Store(); Real* b = a + n; Real* u = U.Store(); - i = n2; - while (i--) { *u++ = *a++; *u++ = -(*(--b)); } - } - - void DCT_inverse(const ColumnVector& V, ColumnVector& U) - { - // Inverse of discrete cosine transform, type I - Tracer trace("DCT_inverse"); - REPORT - const int n = V.Nrows()-1; // length of transform - const int n2 = n / 2; const int n21 = n2 + 1; - if (n != 2 * n2) - Throw(ProgramException("Vector length not multiple of 2", V)); - ColumnVector X(n21), Y(n21); - Real* x = X.Store(); Real* y = Y.Store(); Real* v = V.Store(); - Real vi = *v++; *x++ = vi; *y++ = 0.0; - Real sum1 = vi / 2.0; Real sum2 = sum1; vi = *v++; - int i = n2-1; - while (i--) - { - Real vi2 = *v++; sum1 += vi2 + vi; sum2 += vi2 - vi; - *x++ = vi2; vi2 = *v++; *y++ = vi - vi2; vi = vi2; - } - sum1 += vi; sum2 -= vi; - vi = *v; *x = vi; *y = 0.0; vi /= 2.0; sum1 += vi; sum2 += vi; - ColumnVector A; RealFFTI(X, Y, A); - X.CleanUp(); Y.CleanUp(); U.ReSize(n+1); - Real* a = A.Store(); Real* b = a + n; Real* u = U.Store(); v = u + n; - i = n2; int k = 0; *u++ = sum1 / n2; *v-- = sum2 / n2; - while (i--) - { - Real s = sin(1.5707963267948966192 * (++k) / n2); - Real ai = *(++a); Real bi = *(--b); - Real bz = (ai - bi) / 4 / s; Real az = (ai + bi) / 2; - *u++ = az - bz; *v-- = az + bz; - } - } - - void DCT(const ColumnVector& U, ColumnVector& V) - { - // Discrete cosine transform, type I - Tracer trace("DCT"); - REPORT - DCT_inverse(U, V); - V *= (V.Nrows()-1)/2; - } - - void DST_inverse(const ColumnVector& V, ColumnVector& U) - { - // Inverse of discrete sine transform, type I - Tracer trace("DST_inverse"); - REPORT - const int n = V.Nrows()-1; // length of transform - const int n2 = n / 2; const int n21 = n2 + 1; - if (n != 2 * n2) - Throw(ProgramException("Vector length not multiple of 2", V)); - ColumnVector X(n21), Y(n21); - Real* x = X.Store(); Real* y = Y.Store(); Real* v = V.Store(); - Real vi = *(++v); *x++ = 2 * vi; *y++ = 0.0; - int i = n2-1; - while (i--) { *y++ = *(++v); Real vi2 = *(++v); *x++ = vi2 - vi; vi = vi2; } - *x = -2 * vi; *y = 0.0; - ColumnVector A; RealFFTI(X, Y, A); - X.CleanUp(); Y.CleanUp(); U.ReSize(n+1); - Real* a = A.Store(); Real* b = a + n; Real* u = U.Store(); v = u + n; - i = n2; int k = 0; *u++ = 0.0; *v-- = 0.0; - while (i--) - { - Real s = sin(1.5707963267948966192 * (++k) / n2); - Real ai = *(++a); Real bi = *(--b); - Real az = (ai + bi) / 4 / s; Real bz = (ai - bi) / 2; - *u++ = az - bz; *v-- = az + bz; - } - } - - void DST(const ColumnVector& U, ColumnVector& V) - { - // Discrete sine transform, type I - Tracer trace("DST"); - REPORT - DST_inverse(U, V); - V *= (V.Nrows()-1)/2; - } - - - -#ifdef use_namespace -} -#endif - - diff --git a/lib/src/mixmod/NEWMAT/hholder.cpp b/lib/src/mixmod/NEWMAT/hholder.cpp deleted file mode 100644 index 3493812..0000000 --- a/lib/src/mixmod/NEWMAT/hholder.cpp +++ /dev/null @@ -1,199 +0,0 @@ -//$$ hholder.cpp QR decomposition - -// Copyright (C) 1991,2,3,4: R B Davies - -#define WANT_MATH - -#include "include.h" - -#include "newmatap.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - -#ifdef DO_REPORT -#define REPORT { static ExeCounter ExeCount(__LINE__,16); ++ExeCount; } -#else -#define REPORT {} -#endif - - - /*************************** QR decompositions ***************************/ - - inline Real square(Real x) { return x*x; } - - void QRZT(Matrix& X, LowerTriangularMatrix& L) - { - REPORT - Tracer et("QZT(1)"); - int n = X.Ncols(); int s = X.Nrows(); L.ReSize(s); - Real* xi = X.Store(); int k; - for (int i=0; i= 3 -#define _STANDARD_ // use standard library -#define ios_format_flags ios::fmtflags -#endif - -// for Intel C++ for Linux -#if defined __ICC -#define _STANDARD_ // use standard library -#define ios_format_flags ios::fmtflags -#endif - - -#ifdef _STANDARD_ // using standard library -#include -#ifdef _MSC_VER -#include // for VC++6 -#endif -#ifdef WANT_STREAM -#include -#include -#endif -#ifdef WANT_MATH -#include -#endif -#ifdef WANT_STRING -#include -#endif -#ifdef WANT_TIME -#include -#endif -#ifdef WANT_FSTREAM -#include -#endif -using namespace std; -#else - -#define DEFAULT_HEADER // use AT&T style header - // if no other compiler is recognised - -#ifdef _MSC_VER // Microsoft -#include - -// reactivate these statements to run under MSC version 7.0 -// typedef int jmp_buf[9]; -// extern "C" -// { -// int __cdecl setjmp(jmp_buf); -// void __cdecl longjmp(jmp_buf, int); -// } - -#ifdef WANT_STREAM -#include -#include -#endif -#ifdef WANT_MATH -#include -#include -#endif -#ifdef WANT_STRING -#include -#endif -#ifdef WANT_TIME -#include -#endif -#ifdef WANT_FSTREAM -#include -#endif -#undef DEFAULT_HEADER -#endif - -#ifdef __ZTC__ // Zortech -#include -#ifdef WANT_STREAM -#include -#include -#define flush "" // not defined in iomanip? -#endif -#ifdef WANT_MATH -#include -#include -#endif -#ifdef WANT_STRING -#include -#endif -#ifdef WANT_TIME -#include -#endif -#ifdef WANT_FSTREAM -#include -#endif -#undef DEFAULT_HEADER -#endif - -#if defined __BCPLUSPLUS__ || defined __TURBOC__ // Borland or Turbo -#include -#ifdef WANT_STREAM -#include -#include -#endif -#ifdef WANT_MATH -#include -#include // Borland has both float and values -// but values.h returns +INF for -// MAXDOUBLE in BC5 -#endif -#ifdef WANT_STRING -#include -#endif -#ifdef WANT_TIME -#include -#endif -#ifdef WANT_FSTREAM -#include -#endif -#undef DEFAULT_HEADER -#endif - -#ifdef __GNUG__ // Gnu C++ -#include -#ifdef WANT_STREAM -#include -#include -#endif -#ifdef WANT_MATH -#include -#include -#endif -#ifdef WANT_STRING -#include -#endif -#ifdef WANT_TIME -#include -#endif -#ifdef WANT_FSTREAM -#include -#endif -#undef DEFAULT_HEADER -#endif - -#ifdef __WATCOMC__ // Watcom C/C++ -#include -#ifdef WANT_STREAM -#include -#include -#endif -#ifdef WANT_MATH -#include -#include -#endif -#ifdef WANT_STRING -#include -#endif -#ifdef WANT_TIME -#include -#endif -#ifdef WANT_FSTREAM -#include -#endif -#undef DEFAULT_HEADER -#endif - - -#ifdef macintosh // MPW C++ on the Mac -#include -#ifdef WANT_STREAM -#include -#include -#endif -#ifdef WANT_MATH -#include -#include -#endif -#ifdef WANT_STRING -#include -#endif -#ifdef WANT_TIME -#include -#endif -#ifdef WANT_FSTREAM -#include -#endif -#undef DEFAULT_HEADER -#endif - -#ifdef use_float_h // use float.h for precision values -#include -#ifdef WANT_STREAM -#include -#include -#endif -#ifdef WANT_MATH -#include -#include -#endif -#ifdef WANT_STRING -#include -#endif -#ifdef WANT_TIME -#include -#endif -#ifdef WANT_FSTREAM -#include -#endif -#undef DEFAULT_HEADER -#endif - - -#ifdef DEFAULT_HEADER // for example AT&T -#define ATandT -#include -#ifdef WANT_STREAM -#include -#include -#endif -#ifdef WANT_MATH -#include -#define SystemV // use System V -#include -#endif -#ifdef WANT_STRING -#include -#endif -#ifdef WANT_TIME -#include -#endif -#ifdef WANT_FSTREAM -#include -#endif -#endif // DEFAULT_HEADER - -#endif // _STANDARD_ - -#ifdef use_namespace -namespace RBD_COMMON { -#endif - - -#ifdef USING_FLOAT // set precision type to float - typedef float Real; - typedef double long_Real; -#endif - -#ifdef USING_DOUBLE // set precision type to double - typedef double Real; - typedef long double long_Real; -#endif - - - // This is for (very old) compilers that do not have bool automatically defined - -#ifndef bool_LIB -#define bool_LIB 0 - - class bool - { - int value; - public: - bool(const int b) { value = b ? 1 : 0; } - bool(const void* b) { value = b ? 1 : 0; } - bool() {} - operator int() const { return value; } - int operator!() const { return !value; } - }; - - - const bool true = 1; - const bool false = 0; - -#endif - - - -#ifdef use_namespace -} -#endif - - -#ifdef use_namespace -namespace RBD_COMMON {} -namespace RBD_LIBRARIES // access all my libraries -{ - using namespace RBD_COMMON; -} -#endif - - -#endif diff --git a/lib/src/mixmod/NEWMAT/jacobi.cpp b/lib/src/mixmod/NEWMAT/jacobi.cpp deleted file mode 100644 index 655d71f..0000000 --- a/lib/src/mixmod/NEWMAT/jacobi.cpp +++ /dev/null @@ -1,123 +0,0 @@ -//$$jacobi.cpp jacobi eigenvalue analysis - -// Copyright (C) 1991,2,3,4: R B Davies - - -//#define WANT_STREAM - - -#define WANT_MATH - -#include "include.h" -#include "newmatap.h" -#include "precisio.h" -#include "newmatrm.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - -#ifdef DO_REPORT -#define REPORT { static ExeCounter ExeCount(__LINE__,18); ++ExeCount; } -#else -#define REPORT {} -#endif - - - void Jacobi(const SymmetricMatrix& X, DiagonalMatrix& D, SymmetricMatrix& A, - Matrix& V, bool eivec) - { - Real epsilon = FloatingPointPrecision::Epsilon(); - Tracer et("Jacobi"); - REPORT - int n = X.Nrows(); DiagonalMatrix B(n), Z(n); D.ReSize(n); A = X; - if (eivec) { REPORT V.ReSize(n,n); D = 1.0; V = D; } - B << A; D = B; Z = 0.0; A.Inject(Z); - bool converged = false; - for (int i=1; i<=50; i++) - { - Real sm=0.0; Real* a = A.Store(); int p = A.Storage(); - while (p--) sm += fabs(*a++); // have previously zeroed diags - if (sm==0.0) { REPORT converged = true; break; } - Real tresh = (i<4) ? 0.2 * sm / square(n) : 0.0; a = A.Store(); - for (p = 0; p < n; p++) - { - Real* ap1 = a + (p*(p+1))/2; - Real& zp = Z.element(p); Real& dp = D.element(p); - for (int q = p+1; q < n; q++) - { - Real* ap = ap1; Real* aq = a + (q*(q+1))/2; - Real& zq = Z.element(q); Real& dq = D.element(q); - Real& apq = A.element(q,p); - Real g = 100 * fabs(apq); Real adp = fabs(dp); Real adq = fabs(dq); - - if (i>4 && g < epsilon*adp && g < epsilon*adq) { REPORT apq = 0.0; } - else if (fabs(apq) > tresh) - { - REPORT - Real t; Real h = dq - dp; Real ah = fabs(h); - if (g < epsilon*ah) { REPORT t = apq / h; } - else - { - REPORT - Real theta = 0.5 * h / apq; - t = 1.0 / ( fabs(theta) + sqrt(1.0 + square(theta)) ); - if (theta<0.0) { REPORT t = -t; } - } - Real c = 1.0 / sqrt(1.0 + square(t)); Real s = t * c; - Real tau = s / (1.0 + c); h = t * apq; - zp -= h; zq += h; dp -= h; dq += h; apq = 0.0; - int j = p; - while (j--) - { - g = *ap; h = *aq; - *ap++ = g-s*(h+g*tau); *aq++ = h+s*(g-h*tau); - } - int ip = p+1; j = q-ip; ap += ip++; aq++; - while (j--) - { - g = *ap; h = *aq; - *ap = g-s*(h+g*tau); *aq++ = h+s*(g-h*tau); - ap += ip++; - } - if (q < n-1) // last loop is non-empty - { - int iq = q+1; j = n-iq; ap += ip++; aq += iq++; - for (;;) - { - g = *ap; h = *aq; - *ap = g-s*(h+g*tau); *aq = h+s*(g-h*tau); - if (!(--j)) break; - ap += ip++; aq += iq++; - } - } - if (eivec) - { - REPORT - RectMatrixCol VP(V,p); RectMatrixCol VQ(V,q); - Rotate(VP, VQ, tau, s); - } - } - } - } - B = B + Z; D = B; Z = 0.0; - } - if (!converged) Throw(ConvergenceException(X)); - if (eivec) SortSV(D, V, true); - else SortAscending(D); - } - - void Jacobi(const SymmetricMatrix& X, DiagonalMatrix& D) - { REPORT SymmetricMatrix A; Matrix V; Jacobi(X,D,A,V,false); } - - void Jacobi(const SymmetricMatrix& X, DiagonalMatrix& D, SymmetricMatrix& A) - { REPORT Matrix V; Jacobi(X,D,A,V,false); } - - void Jacobi(const SymmetricMatrix& X, DiagonalMatrix& D, Matrix& V) - { REPORT SymmetricMatrix A; Jacobi(X,D,A,V,true); } - - -#ifdef use_namespace -} -#endif - diff --git a/lib/src/mixmod/NEWMAT/myexcept.cpp b/lib/src/mixmod/NEWMAT/myexcept.cpp deleted file mode 100644 index 738af32..0000000 --- a/lib/src/mixmod/NEWMAT/myexcept.cpp +++ /dev/null @@ -1,485 +0,0 @@ -//$$myexcept.cpp Exception handler - -// Copyright (C) 1993,4,6: R B Davies - - -#define WANT_STREAM // include.h will get stream fns -#define WANT_STRING - -#include "include.h" // include standard files -#include "boolean.h" - - -#include "myexcept.h" // for exception handling - -#ifdef use_namespace -namespace RBD_COMMON { -#endif - - - //#define REG_DEREG // for print out uses of new/delete - //#define CLEAN_LIST // to print entries being added to - // or deleted from cleanup list - -#ifdef SimulateExceptions - - void Throw() - { - for (Janitor* jan = JumpBase::jl->janitor; jan; jan = jan->NextJanitor) - jan->CleanUp(); - JumpItem* jx = JumpBase::jl->ji; // previous jumpbase; - if ( !jx ) { Terminate(); } // jl was initial JumpItem - JumpBase::jl = jx; // drop down a level; cannot be in front - // of previous line - Tracer::last = JumpBase::jl->trace; - longjmp(JumpBase::jl->env, 1); - } - -#endif // end of simulate exceptions - - - unsigned long Exception::Select; - char* Exception::what_error; - int Exception::SoFar; - int Exception::LastOne; - - Exception::Exception(const char* a_what) - { - Select++; SoFar = 0; - if (!what_error) // make space for exception message - { - LastOne = 511; - what_error = new char[512]; - if (!what_error) // fail to make space - { - LastOne = 0; - what_error = (char *)"No heap space for exception message\n"; - } - } - AddMessage("\n\nAn exception has been thrown\n"); - AddMessage(a_what); - if (a_what) Tracer::AddTrace(); - } - - void Exception::AddMessage(const char* a_what) - { - if (a_what) - { - int l = strlen(a_what); int r = LastOne - SoFar; - if (l < r) { strcpy(what_error+SoFar, a_what); SoFar += l; } - else if (r > 0) - { - strncpy(what_error+SoFar, a_what, r); - what_error[LastOne] = 0; - SoFar = LastOne; - } - } - } - - void Exception::AddInt(int value) - { - bool negative; - if (value == 0) { AddMessage("0"); return; } - else if (value < 0) { value = -value; negative = true; } - else negative = false; - int n = 0; int v = value; // how many digits will we need? - while (v > 0) { v /= 10; n++; } - if (negative) n++; - if (LastOne-SoFar < n) { AddMessage("***"); return; } - - SoFar += n; n = SoFar; what_error[n] = 0; - while (value > 0) - { - int nv = value / 10; int rm = value - nv * 10; value = nv; - what_error[--n] = (char)(rm + '0'); - } - if (negative) what_error[--n] = '-'; - return; - } - - void Tracer::PrintTrace() - { - cout << "\n"; - for (Tracer* et = last; et; et=et->previous) - cout << " * " << et->entry << "\n"; - } - - void Tracer::AddTrace() - { - if (last) - { - Exception::AddMessage("Trace: "); - Exception::AddMessage(last->entry); - for (Tracer* et = last->previous; et; et=et->previous) - { - Exception::AddMessage("; "); - Exception::AddMessage(et->entry); - } - Exception::AddMessage(".\n"); - } - } - -#ifdef SimulateExceptions - - - Janitor::Janitor() - { - if (do_not_link) - { - do_not_link = false; NextJanitor = 0; OnStack = false; -#ifdef CLEAN_LIST - cout << "Not added to clean-list " << (unsigned long)this << "\n"; -#endif - } - else - { - OnStack = true; -#ifdef CLEAN_LIST - cout << "Add to clean-list " << (unsigned long)this << "\n"; -#endif - NextJanitor = JumpBase::jl->janitor; JumpBase::jl->janitor=this; - } - } - - Janitor::~Janitor() - { - // expect the item to be deleted to be first on list - // but must be prepared to search list - if (OnStack) - { -#ifdef CLEAN_LIST - cout << "Delete from clean-list " << (unsigned long)this << "\n"; -#endif - Janitor* lastjan = JumpBase::jl->janitor; - if (this == lastjan) JumpBase::jl->janitor = NextJanitor; - else - { - for (Janitor* jan = lastjan->NextJanitor; jan; - jan = lastjan->NextJanitor) - { - if (jan==this) - { lastjan->NextJanitor = jan->NextJanitor; return; } - lastjan=jan; - } - - Throw(Exception( - "Cannot resolve memory linked list\nSee notes in myexcept.cpp for details\n" - )); - - - // This message occurs when a call to ~Janitor() occurs, apparently - // without a corresponding call to Janitor(). This could happen if my - // way of deciding whether a constructor is being called by new - // fails. - - // It may happen if you are using my simulated exceptions and also have - // your compiler s exceptions turned on. - - // It can also happen if you have a class derived from Janitor - // which does not include a copy constructor [ eg X(const &X) ]. - // Possibly also if delete is applied an object on the stack (ie not - // called by new). Otherwise, it is a bug in myexcept or your compiler. - // If you do not #define TEMPS_DESTROYED_QUICKLY you will get this - // error with Microsoft C 7.0. There are probably situations where - // you will get this when you do define TEMPS_DESTROYED_QUICKLY. This - // is a bug in MSC. Beware of "operator" statements for defining - // conversions; particularly for converting from a Base class to a - // Derived class. - - // You may get away with simply deleting this error message and Throw - // statement if you can not find a better way of overcoming the - // problem. In any case please tell me if you get this error message, - // particularly for compilers apart from Microsoft C 7.0. - - - } - } - } - - JumpItem* JumpBase::jl; // will be set to zero - jmp_buf JumpBase::env; - bool Janitor::do_not_link; // will be set to false - - - int JanitorInitializer::ref_count; - - JanitorInitializer::JanitorInitializer() - { - if (ref_count++ == 0) new JumpItem; - // need JumpItem at head of list - } - -#endif // end of SimulateExceptions - - Tracer* Tracer::last; // will be set to zero - - - void Terminate() - { - cout << "\n\nThere has been an exception with no handler - exiting"; - const char* what = Exception::what(); - if (what) cout << what << "\n"; - exit(1); - } - - - -#ifdef DO_FREE_CHECK - // Routines for tracing whether new and delete calls are balanced - - FreeCheckLink::FreeCheckLink() : next(FreeCheck::next) - { FreeCheck::next = this; } - - FCLClass::FCLClass(void* t, char* name) : ClassName(name) { ClassStore=t; } - - FCLRealArray::FCLRealArray(void* t, char* o, int s) - : Operation(o), size(s) { ClassStore=t; } - - FCLIntArray::FCLIntArray(void* t, char* o, int s) - : Operation(o), size(s) { ClassStore=t; } - - FreeCheckLink* FreeCheck::next; - int FreeCheck::BadDelete; - - void FCLClass::Report() - { cout << " " << ClassName << " " << (unsigned long)ClassStore << "\n"; } - - void FCLRealArray::Report() - { - cout << " " << Operation << " " << (unsigned long)ClassStore << - " " << size << "\n"; - } - - void FCLIntArray::Report() - { - cout << " " << Operation << " " << (unsigned long)ClassStore << - " " << size << "\n"; - } - - void FreeCheck::Register(void* t, char* name) - { - FCLClass* f = new FCLClass(t,name); - if (!f) { cout << "Out of memory in FreeCheck\n"; exit(1); } -#ifdef REG_DEREG - cout << "Registering " << name << " " << (unsigned long)t << "\n"; -#endif - } - - void FreeCheck::RegisterR(void* t, char* o, int s) - { - FCLRealArray* f = new FCLRealArray(t,o,s); - if (!f) { cout << "Out of memory in FreeCheck\n"; exit(1); } -#ifdef REG_DEREG - cout << o << " " << s << " " << (unsigned long)t << "\n"; -#endif - } - - void FreeCheck::RegisterI(void* t, char* o, int s) - { - FCLIntArray* f = new FCLIntArray(t,o,s); - if (!f) { cout << "Out of memory in FreeCheck\n"; exit(1); } -#ifdef REG_DEREG - cout << o << " " << s << " " << (unsigned long)t << "\n"; -#endif - } - - void FreeCheck::DeRegister(void* t, char* name) - { - FreeCheckLink* last = 0; -#ifdef REG_DEREG - cout << "Deregistering " << name << " " << (unsigned long)t << "\n"; -#endif - for (FreeCheckLink* fcl = next; fcl; fcl = fcl->next) - { - if (fcl->ClassStore==t) - { - if (last) last->next = fcl->next; else next = fcl->next; - delete fcl; return; - } - last = fcl; - } - cout << "\nRequest to delete non-existent object of class and location:\n"; - cout << " " << name << " " << (unsigned long)t << "\n"; - BadDelete++; - Tracer::PrintTrace(); - cout << "\n"; - } - - void FreeCheck::DeRegisterR(void* t, char* o, int s) - { - FreeCheckLink* last = 0; -#ifdef REG_DEREG - cout << o << " " << s << " " << (unsigned long)t << "\n"; -#endif - for (FreeCheckLink* fcl = next; fcl; fcl = fcl->next) - { - if (fcl->ClassStore==t) - { - if (last) last->next = fcl->next; else next = fcl->next; - if (s >= 0 && ((FCLRealArray*)fcl)->size != s) - { - cout << "\nArray sizes do not agree:\n"; - cout << " " << o << " " << (unsigned long)t - << " " << ((FCLRealArray*)fcl)->size << " " << s << "\n"; - Tracer::PrintTrace(); - cout << "\n"; - } - delete fcl; return; - } - last = fcl; - } - cout << "\nRequest to delete non-existent real array:\n"; - cout << " " << o << " " << (unsigned long)t << " " << s << "\n"; - BadDelete++; - Tracer::PrintTrace(); - cout << "\n"; - } - - void FreeCheck::DeRegisterI(void* t, char* o, int s) - { - FreeCheckLink* last = 0; -#ifdef REG_DEREG - cout << o << " " << s << " " << (unsigned long)t << "\n"; -#endif - for (FreeCheckLink* fcl = next; fcl; fcl = fcl->next) - { - if (fcl->ClassStore==t) - { - if (last) last->next = fcl->next; else next = fcl->next; - if (s >= 0 && ((FCLIntArray*)fcl)->size != s) - { - cout << "\nArray sizes do not agree:\n"; - cout << " " << o << " " << (unsigned long)t - << " " << ((FCLIntArray*)fcl)->size << " " << s << "\n"; - Tracer::PrintTrace(); - cout << "\n"; - } - delete fcl; return; - } - last = fcl; - } - cout << "\nRequest to delete non-existent int array:\n"; - cout << " " << o << " " << (unsigned long)t << " " << s << "\n"; - BadDelete++; - Tracer::PrintTrace(); - cout << "\n"; - } - - void FreeCheck::Status() - { - if (next) - { - cout << "\nObjects of the following classes remain undeleted:\n"; - for (FreeCheckLink* fcl = next; fcl; fcl = fcl->next) fcl->Report(); - cout << "\n"; - } - else cout << "\nNo objects remain undeleted\n\n"; - if (BadDelete) - { - cout << "\nThere were " << BadDelete << - " requests to delete non-existent items\n\n"; - } - } - -#endif // end of DO_FREE_CHECK - - // derived exception bodies - - Logic_error::Logic_error(const char* a_what) : Exception() - { - Select = Exception::Select; - AddMessage("Logic error:- "); AddMessage(a_what); - if (a_what) Tracer::AddTrace(); - } - - Runtime_error::Runtime_error(const char* a_what) - : Exception() - { - Select = Exception::Select; - AddMessage("Runtime error:- "); AddMessage(a_what); - if (a_what) Tracer::AddTrace(); - } - - Domain_error::Domain_error(const char* a_what) : Logic_error() - { - Select = Exception::Select; - AddMessage("domain error\n"); AddMessage(a_what); - if (a_what) Tracer::AddTrace(); - } - - Invalid_argument::Invalid_argument(const char* a_what) : Logic_error() - { - Select = Exception::Select; - AddMessage("invalid argument\n"); AddMessage(a_what); - if (a_what) Tracer::AddTrace(); - } - - Length_error::Length_error(const char* a_what) : Logic_error() - { - Select = Exception::Select; - AddMessage("length error\n"); AddMessage(a_what); - if (a_what) Tracer::AddTrace(); - } - - Out_of_range::Out_of_range(const char* a_what) : Logic_error() - { - Select = Exception::Select; - AddMessage("out of range\n"); AddMessage(a_what); - if (a_what) Tracer::AddTrace(); - } - - //Bad_cast::Bad_cast(const char* a_what) : Logic_error() - //{ - // Select = Exception::Select; - // AddMessage("bad cast\n"); AddMessage(a_what); - // if (a_what) Tracer::AddTrace(); - //} - - //Bad_typeid::Bad_typeid(const char* a_what) : Logic_error() - //{ - // Select = Exception::Select; - // AddMessage("bad type id.\n"); AddMessage(a_what); - // if (a_what) Tracer::AddTrace(); - //} - - Range_error::Range_error(const char* a_what) : Runtime_error() - { - Select = Exception::Select; - AddMessage("range error\n"); AddMessage(a_what); - if (a_what) Tracer::AddTrace(); - } - - Overflow_error::Overflow_error(const char* a_what) : Runtime_error() - { - Select = Exception::Select; - AddMessage("overflow error\n"); AddMessage(a_what); - if (a_what) Tracer::AddTrace(); - } - - Bad_alloc::Bad_alloc(const char* a_what) : Exception() - { - Select = Exception::Select; - AddMessage("bad allocation\n"); AddMessage(a_what); - if (a_what) Tracer::AddTrace(); - } - - - - - unsigned long Logic_error::Select; - unsigned long Runtime_error::Select; - unsigned long Domain_error::Select; - unsigned long Invalid_argument::Select; - unsigned long Length_error::Select; - unsigned long Out_of_range::Select; - //unsigned long Bad_cast::Select; - //unsigned long Bad_typeid::Select; - unsigned long Range_error::Select; - unsigned long Overflow_error::Select; - unsigned long Bad_alloc::Select; - -#ifdef use_namespace -} -#endif - - diff --git a/lib/src/mixmod/NEWMAT/myexcept.h b/lib/src/mixmod/NEWMAT/myexcept.h deleted file mode 100644 index fbc223c..0000000 --- a/lib/src/mixmod/NEWMAT/myexcept.h +++ /dev/null @@ -1,430 +0,0 @@ -//$$ myexcept.h Exception handling classes - - -// A set of classes to simulate exceptions in C++ -// -// Partially copied from Carlos Vidal s article in the C users journal -// September 1992, pp 19-28 -// -// Operations defined -// Try { } -// Throw ( exception object ) -// ReThrow -// Catch ( exception class ) { } -// CatchAll { } -// CatchAndThrow -// -// All catch lists must end with a CatchAll or CatchAndThrow statement -// but not both. -// -// When exceptions are finally implemented replace Try, Throw(E), Rethrow, -// Catch, CatchAll, CatchAndThrow by try, throw E, throw, catch, -// catch(...), and {}. -// -// All exception classes must be derived from Exception, have no non-static -// variables and must include the statement -// -// static unsigned long Select; -// -// Any constructor in one of these exception classes must include -// -// Select = Exception::Select; -// -// For each exceptions class, EX_1, some .cpp file must include -// -// unsigned long EX_1::Select; -// - - -#ifndef EXCEPTION_LIB -#define EXCEPTION_LIB - -#ifdef use_namespace -namespace RBD_COMMON { -#endif - - - void Terminate(); - - - //********** classes for setting up exceptions and reporting ************// - - class Exception; - - class Tracer // linked list showing how - { // we got here - const char* entry; - Tracer* previous; - public: - Tracer(const char*); - ~Tracer(); - void ReName(const char*); - static void PrintTrace(); // for printing trace - static void AddTrace(); // insert trace in exception record - static Tracer* last; // points to Tracer list - friend class Exception; - }; - - - class Exception // The base exception class - { - protected: - static char* what_error; // error message - static int SoFar; // no. characters already entered - static int LastOne; // last location in error buffer - public: - static void AddMessage(const char* a_what); - // messages about exception - static void AddInt(int value); // integer to error message - static unsigned long Select; // for identifying exception - Exception(const char* a_what = 0); - static const char* what() { return what_error; } - // for getting error message - }; - - - inline Tracer::Tracer(const char* e) - : entry(e), previous(last) { last = this; } - - inline Tracer::~Tracer() { last = previous; } - - inline void Tracer::ReName(const char* e) { entry=e; } - -#ifdef SimulateExceptions // SimulateExceptions - -#include - - - //************* the definitions of Try, Throw and Catch *****************// - - - class JumpItem; - class Janitor; - - class JumpBase // pointer to a linked list of jmp_buf s - { - public: - static JumpItem *jl; - static jmp_buf env; - }; - - class JumpItem // an item in a linked list of jmp_buf s - { - public: - JumpItem *ji; - jmp_buf env; - Tracer* trace; // to keep check on Tracer items - Janitor* janitor; // list of items for cleanup - JumpItem() : ji(JumpBase::jl), trace(0), janitor(0) - { JumpBase::jl = this; } - ~JumpItem() { JumpBase::jl = ji; } - }; - - void Throw(); - - inline void Throw(const Exception&) { Throw(); } - -#define Try \ - if (!setjmp( JumpBase::jl->env )) { \ - JumpBase::jl->trace = Tracer::last; \ - JumpItem JI387256156; - -#define ReThrow Throw() - -#define Catch(EXCEPTION) \ - } else if (Exception::Select == EXCEPTION::Select) { - -#define CatchAll } else - -#define CatchAndThrow } else Throw(); - - - //****************** cleanup heap following Throw ***********************// - - class Janitor - { - protected: - static bool do_not_link; // set when new is called - bool OnStack; // false if created by new - public: - Janitor* NextJanitor; - virtual void CleanUp() {} - Janitor(); - virtual ~Janitor(); - }; - - - // The tiresome old trick for initializing the Janitor class - // this is needed for classes derived from Janitor which have objects - // declared globally - - class JanitorInitializer - { - public: - JanitorInitializer(); - private: - static int ref_count; - }; - - static JanitorInitializer JanInit; - -#endif // end of SimulateExceptions - -#ifdef UseExceptions - -#define Try try -#define Throw(E) throw E -#define ReThrow throw -#define Catch catch -#define CatchAll catch(...) -#define CatchAndThrow {} - -#endif // end of UseExceptions - - -#ifdef DisableExceptions // Disable exceptions - -#define Try { -#define ReThrow Throw() -#define Catch(EXCEPTION) } if (false) { -#define CatchAll } if (false) -#define CatchAndThrow } - - inline void Throw() { Terminate(); } - inline void Throw(const Exception&) { Terminate(); } - - -#endif // end of DisableExceptions - -#ifndef SimulateExceptions // ! SimulateExceptions - - class Janitor // a dummy version - { - public: - virtual void CleanUp() {} - Janitor() {} - virtual ~Janitor() {} - }; - -#endif // end of ! SimulateExceptions - - - //******************** FREE_CHECK and NEW_DELETE ***********************// - -#ifdef DO_FREE_CHECK // DO_FREE_CHECK - // Routines for tracing whether new and delete calls are balanced - - class FreeCheck; - - class FreeCheckLink - { - protected: - FreeCheckLink* next; - void* ClassStore; - FreeCheckLink(); - virtual void Report()=0; // print details of link - friend class FreeCheck; - }; - - class FCLClass : public FreeCheckLink // for registering objects - { - char* ClassName; - FCLClass(void* t, char* name); - void Report(); - friend class FreeCheck; - }; - - class FCLRealArray : public FreeCheckLink // for registering real arrays - { - char* Operation; - int size; - FCLRealArray(void* t, char* o, int s); - void Report(); - friend class FreeCheck; - }; - - class FCLIntArray : public FreeCheckLink // for registering int arrays - { - char* Operation; - int size; - FCLIntArray(void* t, char* o, int s); - void Report(); - friend class FreeCheck; - }; - - - class FreeCheck - { - static FreeCheckLink* next; - static int BadDelete; - public: - static void Register(void*, char*); - static void DeRegister(void*, char*); - static void RegisterR(void*, char*, int); - static void DeRegisterR(void*, char*, int); - static void RegisterI(void*, char*, int); - static void DeRegisterI(void*, char*, int); - static void Status(); - friend class FreeCheckLink; - friend class FCLClass; - friend class FCLRealArray; - friend class FCLIntArray; - }; - -#define FREE_CHECK(Class) \ - public: \ - void* operator new(size_t size) \ - { \ - void* t = ::operator new(size); FreeCheck::Register(t,#Class); \ - return t; \ - } \ - void operator delete(void* t) \ - { FreeCheck::DeRegister(t,#Class); ::operator delete(t); } - - -#ifdef SimulateExceptions // SimulateExceptions - -#define NEW_DELETE(Class) \ - public: \ - void* operator new(size_t size) \ - { \ - do_not_link=true; \ - void* t = ::operator new(size); FreeCheck::Register(t,#Class); \ - return t; \ - } \ - void operator delete(void* t) \ - { FreeCheck::DeRegister(t,#Class); ::operator delete(t); } - - -#endif // end of SimulateExceptions - - -#define MONITOR_REAL_NEW(Operation, Size, Pointer) \ - FreeCheck::RegisterR(Pointer, Operation, Size); -#define MONITOR_INT_NEW(Operation, Size, Pointer) \ - FreeCheck::RegisterI(Pointer, Operation, Size); -#define MONITOR_REAL_DELETE(Operation, Size, Pointer) \ - FreeCheck::DeRegisterR(Pointer, Operation, Size); -#define MONITOR_INT_DELETE(Operation, Size, Pointer) \ - FreeCheck::DeRegisterI(Pointer, Operation, Size); - -#else // DO_FREE_CHECK not defined - -#define FREE_CHECK(Class) public: -#define MONITOR_REAL_NEW(Operation, Size, Pointer) {} -#define MONITOR_INT_NEW(Operation, Size, Pointer) {} -#define MONITOR_REAL_DELETE(Operation, Size, Pointer) {} -#define MONITOR_INT_DELETE(Operation, Size, Pointer) {} - - -#ifdef SimulateExceptions // SimulateExceptions - - -#define NEW_DELETE(Class) \ - public: \ - void* operator new(size_t size) \ - { do_not_link=true; void* t = ::operator new(size); return t; } \ - void operator delete(void* t) { ::operator delete(t); } - -#endif // end of SimulateExceptions - -#endif // end of ! DO_FREE_CHECK - -#ifndef SimulateExceptions // ! SimulateExceptions - -#define NEW_DELETE(Class) FREE_CHECK(Class) - -#endif // end of ! SimulateExceptions - - - //********************* derived exceptions ******************************// - - class Logic_error : public Exception - { - public: - static unsigned long Select; - Logic_error(const char* a_what = 0); - }; - - class Runtime_error : public Exception - { - public: - static unsigned long Select; - Runtime_error(const char* a_what = 0); - }; - - class Domain_error : public Logic_error - { - public: - static unsigned long Select; - Domain_error(const char* a_what = 0); - }; - - class Invalid_argument : public Logic_error - { - public: - static unsigned long Select; - Invalid_argument(const char* a_what = 0); - }; - - class Length_error : public Logic_error - { - public: - static unsigned long Select; - Length_error(const char* a_what = 0); - }; - - class Out_of_range : public Logic_error - { - public: - static unsigned long Select; - Out_of_range(const char* a_what = 0); - }; - - //class Bad_cast : public Logic_error - //{ - //public: - // static unsigned long Select; - // Bad_cast(const char* a_what = 0); - //}; - - //class Bad_typeid : public Logic_error - //{ - //public: - // static unsigned long Select; - // Bad_typeid(const char* a_what = 0); - //}; - - class Range_error : public Runtime_error - { - public: - static unsigned long Select; - Range_error(const char* a_what = 0); - }; - - class Overflow_error : public Runtime_error - { - public: - static unsigned long Select; - Overflow_error(const char* a_what = 0); - }; - - class Bad_alloc : public Exception - { - public: - static unsigned long Select; - Bad_alloc(const char* a_what = 0); - }; - -#ifdef use_namespace -} -#endif - - -#endif // end of EXCEPTION_LIB - - -// body file: myexcept.cpp - - - diff --git a/lib/src/mixmod/NEWMAT/newfft.cpp b/lib/src/mixmod/NEWMAT/newfft.cpp deleted file mode 100644 index 460b030..0000000 --- a/lib/src/mixmod/NEWMAT/newfft.cpp +++ /dev/null @@ -1,1059 +0,0 @@ -//$ newfft.cpp - -// This is originally by Sande and Gentleman in 1967! I have translated from -// Fortran into C and a little bit of C++. - -// It takes about twice as long as fftw -// (http://theory.lcs.mit.edu/~fftw/homepage.html) -// but is much shorter than fftw and so despite its age -// might represent a reasonable -// compromise between speed and complexity. -// If you really need the speed get fftw. - - -// THIS SUBROUTINE WAS WRITTEN BY G.SANDE OF PRINCETON UNIVERSITY AND -// W.M.GENTLMAN OF THE BELL TELEPHONE LAB. IT WAS BROUGHT TO LONDON -// BY DR. M.D. GODFREY AT THE IMPERIAL COLLEGE AND WAS ADAPTED FOR -// BURROUGHS 6700 BY D. R. BRILLINGER AND J. PEMBERTON -// IT REPRESENTS THE STATE OF THE ART OF COMPUTING COMPLETE FINITE -// DISCRETE FOURIER TRANSFORMS AS OF NOV.1967. -// OTHER PROGRAMS REQUIRED. -// ONLY THOSE SUBROUTINES INCLUDED HERE. -// USAGE. -// CALL AR1DFT(N,X,Y) -// WHERE N IS THE NUMBER OF POINTS IN THE SEQUENCE . -// X - IS A ONE-DIMENSIONAL ARRAY CONTAINING THE REAL -// PART OF THE SEQUENCE. -// Y - IS A ONE-DIMENSIONAL ARRAY CONTAINING THE -// IMAGINARY PART OF THE SEQUENCE. -// THE TRANSFORM IS RETURNED IN X AND Y. -// METHOD -// FOR A GENERAL DISCUSSION OF THESE TRANSFORMS AND OF -// THE FAST METHOD FOR COMPUTING THEM, SEE GENTLEMAN AND SANDE, -// @FAST FOURIER TRANSFORMS - FOR FUN AND PROFIT,@ 1966 FALL JOINT -// COMPUTER CONFERENCE. -// THIS PROGRAM COMPUTES THIS FOR A COMPLEX SEQUENCE Z(T) OF LENGTH -// N WHOSE ELEMENTS ARE STORED AT(X(I) , Y(I)) AND RETURNS THE -// TRANSFORM COEFFICIENTS AT (X(I), Y(I)). -// DESCRIPTION -// AR1DFT IS A HIGHLY MODULAR ROUTINE CAPABLE OF COMPUTING IN PLACE -// THE COMPLETE FINITE DISCRETE FOURIER TRANSFORM OF A ONE- -// DIMENSIONAL SEQUENCE OF RATHER GENERAL LENGTH N. -// THE MAIN ROUTINE , AR1DFT ITSELF, FACTORS N. IT THEN CALLS ON -// ON GR 1D FT TO COMPUTE THE ACTUAL TRANSFORMS, USING THESE FACTORS. -// THIS GR 1D FT DOES, CALLING AT EACH STAGE ON THE APPROPRIATE KERN -// EL R2FTK, R4FTK, R8FTK, R16FTK, R3FTK, R5FTK, OR RPFTK TO PERFORM -// THE COMPUTATIONS FOR THIS PASS OVER THE SEQUENCE, DEPENDING ON -// WHETHER THE CORRESPONDING FACTOR IS 2, 4, 8, 16, 3, 5, OR SOME -// MORE GENERAL PRIME P. WHEN GR1DFT IS FINISHED THE TRANSFORM IS -// COMPUTED, HOWEVER, THE RESULTS ARE STORED IN "DIGITS REVERSED" -// ORDER. AR1DFT THEREFORE, CALLS UPON GR 1S FS TO SORT THEM OUT. -// TO RETURN TO THE FACTORIZATION, SINGLETON HAS POINTED OUT THAT -// THE TRANSFORMS ARE MORE EFFICIENT IF THE SAMPLE SIZE N, IS OF THE -// FORM B*A**2 AND B CONSISTS OF A SINGLE FACTOR. IN SUCH A CASE -// IF WE PROCESS THE FACTORS IN THE ORDER ABA THEN -// THE REORDERING CAN BE DONE AS FAST IN PLACE, AS WITH SCRATCH -// STORAGE. BUT AS B BECOMES MORE COMPLICATED, THE COST OF THE DIGIT -// REVERSING DUE TO B PART BECOMES VERY EXPENSIVE IF WE TRY TO DO IT -// IN PLACE. IN SUCH A CASE IT MIGHT BE BETTER TO USE EXTRA STORAGE -// A ROUTINE TO DO THIS IS, HOWEVER, NOT INCLUDED HERE. -// ANOTHER FEATURE INFLUENCING THE FACTORIZATION IS THAT FOR ANY FIXED -// FACTOR N WE CAN PREPARE A SPECIAL KERNEL WHICH WILL COMPUTE -// THAT STAGE OF THE TRANSFORM MORE EFFICIENTLY THAN WOULD A KERNEL -// FOR GENERAL FACTORS, ESPECIALLY IF THE GENERAL KERNEL HAD TO BE -// APPLIED SEVERAL TIMES. FOR EXAMPLE, FACTORS OF 4 ARE MORE -// EFFICIENT THAN FACTORS OF 2, FACTORS OF 8 MORE EFFICIENT THAN 4,ETC -// ON THE OTHER HAND DIMINISHING RETURNS RAPIDLY SET IN, ESPECIALLY -// SINCE THE LENGTH OF THE KERNEL FOR A SPECIAL CASE IS ROUGHLY -// PROPORTIONAL TO THE FACTOR IT DEALS WITH. HENCE THESE PROBABLY ARE -// ALL THE KERNELS WE WISH TO HAVE. -// RESTRICTIONS. -// AN UNFORTUNATE FEATURE OF THE SORTING PROBLEM IS THAT THE MOST -// EFFICIENT WAY TO DO IT IS WITH NESTED DO LOOPS, ONE FOR EACH -// FACTOR. THIS PUTS A RESTRICTION ON N AS TO HOW MANY FACTORS IT -// CAN HAVE. CURRENTLY THE LIMIT IS 16, BUT THE LIMIT CAN BE READILY -// RAISED IF NECESSARY. -// A SECOND RESTRICTION OF THE PROGRAM IS THAT LOCAL STORAGE OF THE -// THE ORDER P**2 IS REQUIRED BY THE GENERAL KERNEL RPFTK, SO SOME -// LIMIT MUST BE SET ON P. CURRENTLY THIS IS 19, BUT IT CAN BE INCRE -// INCREASED BY TRIVIAL CHANGES. -// OTHER COMMENTS. -//(1) THE ROUTINE IS ADAPTED TO CHECK WHETHER A GIVEN N WILL MEET THE -// ABOVE FACTORING REQUIREMENTS AN, IF NOT, TO RETURN THE NEXT HIGHER -// NUMBER, NX, SAY, WHICH WILL MEET THESE REQUIREMENTS. -// THIS CAN BE ACCHIEVED BY A STATEMENT OF THE FORM -// CALL FACTR(N,X,Y). -// IF A DIFFERENT N, SAY NX, IS RETURNED THEN THE TRANSFORMS COULD BE -// OBTAINED BY EXTENDING THE SIZE OF THE X-ARRAY AND Y-ARRAY TO NX, -// AND SETTING X(I) = Y(I) = 0., FOR I = N+1, NX. -//(2) IF THE SEQUENCE Z IS ONLY A REAL SEQUENCE, THEN THE IMAGINARY PART -// Y(I)=0., THIS WILL RETURN THE COSINE TRANSFORM OF THE REAL SEQUENCE -// IN X, AND THE SINE TRANSFORM IN Y. - - -#define WANT_STREAM - -#define WANT_MATH - -#include "newmatap.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - -#ifdef DO_REPORT -#define REPORT { static ExeCounter ExeCount(__LINE__,20); ++ExeCount; } -#else -#define REPORT {} -#endif - - inline Real square(Real x) { return x*x; } - inline int square(int x) { return x*x; } - - static void GR_1D_FS (int PTS, int N_SYM, int N_UN_SYM, - const SimpleIntArray& SYM, int P_SYM, const SimpleIntArray& UN_SYM, - Real* X, Real* Y); - static void GR_1D_FT (int N, int N_FACTOR, const SimpleIntArray& FACTOR, - Real* X, Real* Y); - static void R_P_FTK (int N, int M, int P, Real* X, Real* Y); - static void R_2_FTK (int N, int M, Real* X0, Real* Y0, Real* X1, Real* Y1); - static void R_3_FTK (int N, int M, Real* X0, Real* Y0, Real* X1, Real* Y1, - Real* X2, Real* Y2); - static void R_4_FTK (int N, int M, - Real* X0, Real* Y0, Real* X1, Real* Y1, - Real* X2, Real* Y2, Real* X3, Real* Y3); - static void R_5_FTK (int N, int M, - Real* X0, Real* Y0, Real* X1, Real* Y1, Real* X2, Real* Y2, - Real* X3, Real* Y3, Real* X4, Real* Y4); - static void R_8_FTK (int N, int M, - Real* X0, Real* Y0, Real* X1, Real* Y1, - Real* X2, Real* Y2, Real* X3, Real* Y3, - Real* X4, Real* Y4, Real* X5, Real* Y5, - Real* X6, Real* Y6, Real* X7, Real* Y7); - static void R_16_FTK (int N, int M, - Real* X0, Real* Y0, Real* X1, Real* Y1, - Real* X2, Real* Y2, Real* X3, Real* Y3, - Real* X4, Real* Y4, Real* X5, Real* Y5, - Real* X6, Real* Y6, Real* X7, Real* Y7, - Real* X8, Real* Y8, Real* X9, Real* Y9, - Real* X10, Real* Y10, Real* X11, Real* Y11, - Real* X12, Real* Y12, Real* X13, Real* Y13, - Real* X14, Real* Y14, Real* X15, Real* Y15); - static int BitReverse(int x, int prod, int n, const SimpleIntArray& f); - - - bool FFT_Controller::ar_1d_ft (int PTS, Real* X, Real *Y) - { - // ARBITRARY RADIX ONE DIMENSIONAL FOURIER TRANSFORM - - REPORT - - int F,J,N,NF,P,PMAX,P_SYM,P_TWO,Q,R,TWO_GRP; - - // NP is maximum number of squared factors allows PTS up to 2**32 at least - // NQ is number of not-squared factors - increase if we increase PMAX - const int NP = 16, NQ = 10; - SimpleIntArray PP(NP), QQ(NQ); - - TWO_GRP=16; PMAX=19; - - // PMAX is the maximum factor size - // TWO_GRP is the maximum power of 2 handled as a single factor - // Doesn't take advantage of combining powers of 2 when calculating - // number of factors - - if (PTS<=1) return true; - N=PTS; P_SYM=1; F=2; P=0; Q=0; - - // P counts the number of squared factors - // Q counts the number of the rest - // R = 0 for no non-squared factors; 1 otherwise - - // FACTOR holds all the factors - non-squared ones in the middle - // - length is 2*P+Q - // SYM also holds all the factors but with the non-squared ones - // multiplied together - length is 2*P+R - // PP holds the values of the squared factors - length is P - // QQ holds the values of the rest - length is Q - - // P_SYM holds the product of the squared factors - - // find the factors - load into PP and QQ - while (N > 1) - { - bool fail = true; - for (J=F; J<=PMAX; J++) - if (N % J == 0) { fail = false; F=J; break; } - if (fail || P >= NP || Q >= NQ) return false; // can't factor - N /= F; - if (N % F != 0) QQ[Q++] = F; - else { N /= F; PP[P++] = F; P_SYM *= F; } - } - - R = (Q == 0) ? 0 : 1; // R = 0 if no not-squared factors, 1 otherwise - - NF = 2*P + Q; - SimpleIntArray FACTOR(NF + 1), SYM(2*P + R); - FACTOR[NF] = 0; // we need this in the "combine powers of 2" - - // load into SYM and FACTOR - for (J=0; J0) - { - REPORT - for (J=0; J 0) - { - REPORT - SimpleIntArray U(N_SYM); - for(MultiRadixCounter MRC(N_SYM, SYM, U); !MRC.Finish(); ++MRC) - { - if (MRC.Swap()) - { - int P = MRC.Reverse(); int JJ = MRC.Counter(); Real T; - T=X[JJ]; X[JJ]=X[P]; X[P]=T; T=Y[JJ]; Y[JJ]=Y[P]; Y[P]=T; - } - } - } - - int J,JL,K,L,M,MS; - - // UN_SYM contains the non-squared factors - // I have replaced the Sande-Gentleman code as it runs into - // integer overflow problems - // My code (and theirs) would be improved by using a bit array - // as suggested by Van Loan - - if (N_UN_SYM==0) { REPORT return; } - P_UN_SYM=PTS/square(P_SYM); JL=(P_UN_SYM-3)*P_SYM; MS=P_UN_SYM*P_SYM; - - for (J = P_SYM; J<=JL; J+=P_SYM) - { - K=J; - do K = P_SYM * BitReverse(K / P_SYM, P_UN_SYM, N_UN_SYM, UN_SYM); - while (K 1) - { - bool fail = true; - for (int J = F; J <= PMAX; J++) - if (N % J == 0) { fail = false; F=J; break; } - if (fail || P >= NP || Q >= NQ) { REPORT return false; } - N /= F; - if (N % F != 0) Q++; else { N /= F; P++; } - } - - return true; // can factorise - - } - - bool FFT_Controller::OnlyOldFFT; // static variable - - // **************************** multi radix counter ********************** - - MultiRadixCounter::MultiRadixCounter(int nx, const SimpleIntArray& rx, - SimpleIntArray& vx) - : Radix(rx), Value(vx), n(nx), reverse(0), - product(1), counter(0), finish(false) - { - REPORT for (int k = 0; k < n; k++) { Value[k] = 0; product *= Radix[k]; } - } - - void MultiRadixCounter::operator++() - { - REPORT - counter++; int p = product; - for (int k = 0; k < n; k++) - { - Value[k]++; int p1 = p / Radix[k]; reverse += p1; - if (Value[k] == Radix[k]) { REPORT Value[k] = 0; reverse -= p; p = p1; } - else { REPORT return; } - } - finish = true; - } - - - static int BitReverse(int x, int prod, int n, const SimpleIntArray& f) - { - // x = c[0]+f[0]*(c[1]+f[1]*(c[2]+... - // return c[n-1]+f[n-1]*(c[n-2]+f[n-2]*(c[n-3]+... - // prod is the product of the f[i] - // n is the number of f[i] (don't assume f has the correct length) - - REPORT - const int* d = f.Data() + n; int sum = 0; int q = 1; - while (n--) - { - prod /= *(--d); - int c = x / prod; x-= c * prod; - sum += q * c; q *= *d; - } - return sum; - } - - -#ifdef use_namespace -} -#endif - - diff --git a/lib/src/mixmod/NEWMAT/newmat.h b/lib/src/mixmod/NEWMAT/newmat.h deleted file mode 100644 index d0a5c40..0000000 --- a/lib/src/mixmod/NEWMAT/newmat.h +++ /dev/null @@ -1,1797 +0,0 @@ -//$$ newmat.h definition file for new version of matrix package - -// Copyright (C) 1991,2,3,4,7,2000,2002: R B Davies - -#ifndef NEWMAT_LIB -#define NEWMAT_LIB 0 - -#include "include.h" - -#include "boolean.h" -#include "myexcept.h" - - -#ifdef use_namespace -namespace NEWMAT { using namespace RBD_COMMON; } -namespace RBD_LIBRARIES { using namespace NEWMAT; } -namespace NEWMAT { -#endif - - //#define DO_REPORT // to activate REPORT - -#ifdef NO_LONG_NAMES -#define UpperTriangularMatrix UTMatrix -#define LowerTriangularMatrix LTMatrix -#define SymmetricMatrix SMatrix -#define DiagonalMatrix DMatrix -#define BandMatrix BMatrix -#define UpperBandMatrix UBMatrix -#define LowerBandMatrix LBMatrix -#define SymmetricBandMatrix SBMatrix -#define BandLUMatrix BLUMatrix -#endif - -#ifndef TEMPS_DESTROYED_QUICKLY_R -#define ReturnMatrix ReturnMatrixX -#else -#define ReturnMatrix ReturnMatrixX& -#endif - - // ************************** general utilities ****************************/ - - class GeneralMatrix; - - void MatrixErrorNoSpace(void*); // no space handler - - class LogAndSign - // Return from LogDeterminant function - // - value of the log plus the sign (+, - or 0) - { - Real log_value; - int sign; - public: - LogAndSign() { log_value=0.0; sign=1; } - LogAndSign(Real); - void operator*=(Real); - void PowEq(int k); // raise to power of k - void ChangeSign() { sign = -sign; } - Real LogValue() const { return log_value; } - int Sign() const { return sign; } - Real Value() const; - FREE_CHECK(LogAndSign) - }; - - // the following class is for counting the number of times a piece of code - // is executed. It is used for locating any code not executed by test - // routines. Use turbo GREP locate all places this code is called and - // check which ones are not accessed. - // Somewhat implementation dependent as it relies on "cout" still being - // present when ExeCounter objects are destructed. - -#ifdef DO_REPORT - - class ExeCounter - { - int line; // code line number - int fileid; // file identifier - long nexe; // number of executions - static int nreports; // number of reports - public: - ExeCounter(int,int); - void operator++() { nexe++; } - ~ExeCounter(); // prints out reports - }; - -#endif - - - // ************************** class MatrixType *****************************/ - - // Is used for finding the type of a matrix resulting from the binary operations - // +, -, * and identifying what conversions are permissible. - // This class must be updated when new matrix types are added. - - class GeneralMatrix; // defined later - class BaseMatrix; // defined later - class MatrixInput; // defined later - - class MatrixType - { - public: - enum Attribute { Valid = 1, - Diagonal = 2, // order of these is important - Symmetric = 4, - Band = 8, - Lower = 16, - Upper = 32, - LUDeco = 64, - Ones = 128 }; - - enum { US = 0, - UT = Valid + Upper, - LT = Valid + Lower, - Rt = Valid, - Sm = Valid + Symmetric, - Dg = Valid + Diagonal + Band + Lower + Upper + Symmetric, - Id = Valid + Diagonal + Band + Lower + Upper + Symmetric - + Ones, - RV = Valid, // do not separate out - CV = Valid, // vectors - BM = Valid + Band, - UB = Valid + Band + Upper, - LB = Valid + Band + Lower, - SB = Valid + Band + Symmetric, - Ct = Valid + LUDeco, - BC = Valid + Band + LUDeco - }; - - - static int nTypes() { return 10; } // number of different types - // exclude Ct, US, BC - public: - int attribute; - bool DataLossOK; // true if data loss is OK when - // this represents a destination - public: - MatrixType () : DataLossOK(false) {} - MatrixType (int i) : attribute(i), DataLossOK(false) {} - MatrixType (int i, bool dlok) : attribute(i), DataLossOK(dlok) {} - MatrixType (const MatrixType& mt) - : attribute(mt.attribute), DataLossOK(mt.DataLossOK) {} - void operator=(const MatrixType& mt) - { attribute = mt.attribute; DataLossOK = mt.DataLossOK; } - void SetDataLossOK() { DataLossOK = true; } - int operator+() const { return attribute; } - MatrixType operator+(MatrixType mt) const - { return MatrixType(attribute & mt.attribute); } - MatrixType operator*(const MatrixType&) const; - MatrixType SP(const MatrixType&) const; - MatrixType KP(const MatrixType&) const; - MatrixType operator|(const MatrixType& mt) const - { return MatrixType(attribute & mt.attribute & Valid); } - MatrixType operator&(const MatrixType& mt) const - { return MatrixType(attribute & mt.attribute & Valid); } - bool operator>=(MatrixType mt) const - { return ( attribute & mt.attribute ) == attribute; } - bool operator<(MatrixType mt) const // for MS Visual C++ 4 - { return ( attribute & mt.attribute ) != attribute; } - bool operator==(MatrixType t) const - { return (attribute == t.attribute); } - bool operator!=(MatrixType t) const - { return (attribute != t.attribute); } - bool operator!() const { return (attribute & Valid) == 0; } - MatrixType i() const; // type of inverse - MatrixType t() const; // type of transpose - MatrixType AddEqualEl() const // Add constant to matrix - { return MatrixType(attribute & (Valid + Symmetric)); } - MatrixType MultRHS() const; // type for rhs of multiply - MatrixType sub() const // type of submatrix - { return MatrixType(attribute & Valid); } - MatrixType ssub() const // type of sym submatrix - { return MatrixType(attribute); } // not for selection matrix - GeneralMatrix* New() const; // new matrix of given type - GeneralMatrix* New(int,int,BaseMatrix*) const; - // new matrix of given type - const char* Value() const; // to print type - friend bool Rectangular(MatrixType a, MatrixType b, MatrixType c); - friend bool Compare(const MatrixType&, MatrixType&); - // compare and check conv. - bool IsBand() const { return (attribute & Band) != 0; } - bool IsDiagonal() const { return (attribute & Diagonal) != 0; } - bool IsSymmetric() const { return (attribute & Symmetric) != 0; } - bool CannotConvert() const { return (attribute & LUDeco) != 0; } - // used by operator== - FREE_CHECK(MatrixType) - }; - - - // *********************** class MatrixBandWidth ***********************/ - - class MatrixBandWidth - { - public: - int lower; - int upper; - MatrixBandWidth(const int l, const int u) : lower(l), upper (u) {} - MatrixBandWidth(const int i) : lower(i), upper(i) {} - MatrixBandWidth operator+(const MatrixBandWidth&) const; - MatrixBandWidth operator*(const MatrixBandWidth&) const; - MatrixBandWidth minimum(const MatrixBandWidth&) const; - MatrixBandWidth t() const { return MatrixBandWidth(upper,lower); } - bool operator==(const MatrixBandWidth& bw) const - { return (lower == bw.lower) && (upper == bw.upper); } - bool operator!=(const MatrixBandWidth& bw) const { return !operator==(bw); } - int Upper() const { return upper; } - int Lower() const { return lower; } - FREE_CHECK(MatrixBandWidth) - }; - - - // ********************* Array length specifier ************************/ - - // This class is introduced to avoid constructors such as - // ColumnVector(int) - // being used for conversions - - class ArrayLengthSpecifier - { - int value; - public: - int Value() const { return value; } - ArrayLengthSpecifier(int l) : value(l) {} - }; - - // ************************* Matrix routines ***************************/ - - - class MatrixRowCol; // defined later - class MatrixRow; - class MatrixCol; - class MatrixColX; - - class GeneralMatrix; // defined later - class AddedMatrix; - class MultipliedMatrix; - class SubtractedMatrix; - class SPMatrix; - class KPMatrix; - class ConcatenatedMatrix; - class StackedMatrix; - class SolvedMatrix; - class ShiftedMatrix; - class NegShiftedMatrix; - class ScaledMatrix; - class TransposedMatrix; - class ReversedMatrix; - class NegatedMatrix; - class InvertedMatrix; - class RowedMatrix; - class ColedMatrix; - class DiagedMatrix; - class MatedMatrix; - class GetSubMatrix; - class ReturnMatrixX; - class Matrix; - class nricMatrix; - class RowVector; - class ColumnVector; - class SymmetricMatrix; - class UpperTriangularMatrix; - class LowerTriangularMatrix; - class DiagonalMatrix; - class CroutMatrix; - class BandMatrix; - class LowerBandMatrix; - class UpperBandMatrix; - class SymmetricBandMatrix; - class LinearEquationSolver; - class GenericMatrix; - - -#define MatrixTypeUnSp 0 - //static MatrixType MatrixTypeUnSp(MatrixType::US); - // // AT&T needs this - - class BaseMatrix : public Janitor // base of all matrix classes - { - protected: - virtual int search(const BaseMatrix*) const = 0; - // count number of times matrix - // is referred to - - public: - virtual GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp) = 0; - // evaluate temporary - // for old version of G++ - // virtual GeneralMatrix* Evaluate(MatrixType mt) = 0; - // GeneralMatrix* Evaluate() { return Evaluate(MatrixTypeUnSp); } -#ifndef TEMPS_DESTROYED_QUICKLY - AddedMatrix operator+(const BaseMatrix&) const; // results of operations - MultipliedMatrix operator*(const BaseMatrix&) const; - SubtractedMatrix operator-(const BaseMatrix&) const; - ConcatenatedMatrix operator|(const BaseMatrix&) const; - StackedMatrix operator&(const BaseMatrix&) const; - ShiftedMatrix operator+(Real) const; - ScaledMatrix operator*(Real) const; - ScaledMatrix operator/(Real) const; - ShiftedMatrix operator-(Real) const; - TransposedMatrix t() const; - // TransposedMatrix t; - NegatedMatrix operator-() const; // change sign of elements - ReversedMatrix Reverse() const; - InvertedMatrix i() const; - // InvertedMatrix i; - RowedMatrix AsRow() const; - ColedMatrix AsColumn() const; - DiagedMatrix AsDiagonal() const; - MatedMatrix AsMatrix(int,int) const; - GetSubMatrix SubMatrix(int,int,int,int) const; - GetSubMatrix SymSubMatrix(int,int) const; - GetSubMatrix Row(int) const; - GetSubMatrix Rows(int,int) const; - GetSubMatrix Column(int) const; - GetSubMatrix Columns(int,int) const; -#else - AddedMatrix& operator+(const BaseMatrix&) const; // results of operations - MultipliedMatrix& operator*(const BaseMatrix&) const; - SubtractedMatrix& operator-(const BaseMatrix&) const; - ConcatenatedMatrix& operator|(const BaseMatrix&) const; - StackedMatrix& operator&(const BaseMatrix&) const; - ShiftedMatrix& operator+(Real) const; - ScaledMatrix& operator*(Real) const; - ScaledMatrix& operator/(Real) const; - ShiftedMatrix& operator-(Real) const; - TransposedMatrix& t() const; - // TransposedMatrix& t; - NegatedMatrix& operator-() const; // change sign of elements - ReversedMatrix& Reverse() const; - InvertedMatrix& i() const; - // InvertedMatrix& i; - RowedMatrix& AsRow() const; - ColedMatrix& AsColumn() const; - DiagedMatrix& AsDiagonal() const; - MatedMatrix& AsMatrix(int,int) const; - GetSubMatrix& SubMatrix(int,int,int,int) const; - GetSubMatrix& SymSubMatrix(int,int) const; - GetSubMatrix& Row(int) const; - GetSubMatrix& Rows(int,int) const; - GetSubMatrix& Column(int) const; - GetSubMatrix& Columns(int,int) const; -#endif - Real AsScalar() const; // conversion of 1 x 1 matrix - virtual LogAndSign LogDeterminant() const; - Real Determinant() const; - virtual Real SumSquare() const; - Real NormFrobenius() const; - virtual Real SumAbsoluteValue() const; - virtual Real Sum() const; - virtual Real MaximumAbsoluteValue() const; - virtual Real MaximumAbsoluteValue1(int& i) const; - virtual Real MaximumAbsoluteValue2(int& i, int& j) const; - virtual Real MinimumAbsoluteValue() const; - virtual Real MinimumAbsoluteValue1(int& i) const; - virtual Real MinimumAbsoluteValue2(int& i, int& j) const; - virtual Real Maximum() const; - virtual Real Maximum1(int& i) const; - virtual Real Maximum2(int& i, int& j) const; - virtual Real Minimum() const; - virtual Real Minimum1(int& i) const; - virtual Real Minimum2(int& i, int& j) const; - virtual Real Trace() const; - Real Norm1() const; - Real NormInfinity() const; - virtual MatrixBandWidth BandWidth() const; // bandwidths of band matrix - virtual void CleanUp() {} // to clear store - void IEQND() const; // called by ineq. ops - // virtual ReturnMatrix Reverse() const; // reverse order of elements - - - //protected: - // BaseMatrix() : t(this), i(this) {} - - friend class GeneralMatrix; - friend class Matrix; - friend class nricMatrix; - friend class RowVector; - friend class ColumnVector; - friend class SymmetricMatrix; - friend class UpperTriangularMatrix; - friend class LowerTriangularMatrix; - friend class DiagonalMatrix; - friend class CroutMatrix; - friend class BandMatrix; - friend class LowerBandMatrix; - friend class UpperBandMatrix; - friend class SymmetricBandMatrix; - friend class AddedMatrix; - friend class MultipliedMatrix; - friend class SubtractedMatrix; - friend class SPMatrix; - friend class KPMatrix; - friend class ConcatenatedMatrix; - friend class StackedMatrix; - friend class SolvedMatrix; - friend class ShiftedMatrix; - friend class NegShiftedMatrix; - friend class ScaledMatrix; - friend class TransposedMatrix; - friend class ReversedMatrix; - friend class NegatedMatrix; - friend class InvertedMatrix; - friend class RowedMatrix; - friend class ColedMatrix; - friend class DiagedMatrix; - friend class MatedMatrix; - friend class GetSubMatrix; - friend class ReturnMatrixX; - friend class LinearEquationSolver; - friend class GenericMatrix; - NEW_DELETE(BaseMatrix) - }; - - - // ***************************** working classes **************************/ - - class GeneralMatrix : public BaseMatrix // declarable matrix types - { - virtual GeneralMatrix* Image() const; // copy of matrix - protected: - int tag; // shows whether can reuse - int nrows, ncols; // dimensions - int storage; // total store required - Real* store; // point to store (0=not set) - GeneralMatrix(); // initialise with no store - GeneralMatrix(ArrayLengthSpecifier); // constructor getting store - void Add(GeneralMatrix*, Real); // sum of GM and Real - void Add(Real); // add Real to this - void NegAdd(GeneralMatrix*, Real); // Real - GM - void NegAdd(Real); // this = this - Real - void Multiply(GeneralMatrix*, Real); // product of GM and Real - void Multiply(Real); // multiply this by Real - void Negate(GeneralMatrix*); // change sign - void Negate(); // change sign - void ReverseElements(); // internal reverse of elements - void ReverseElements(GeneralMatrix*); // reverse order of elements - void operator=(Real); // set matrix to constant - Real* GetStore(); // get store or copy - GeneralMatrix* BorrowStore(GeneralMatrix*, MatrixType); - // temporarily access store - void GetMatrix(const GeneralMatrix*); // used by = and initialise - void Eq(const BaseMatrix&, MatrixType); // used by = - void Eq(const BaseMatrix&, MatrixType, bool);// used by << - void Eq2(const BaseMatrix&, MatrixType); // cut down version of Eq - int search(const BaseMatrix*) const; - virtual GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); - void CheckConversion(const BaseMatrix&); // check conversion OK - void ReSize(int, int, int); // change dimensions - virtual short SimpleAddOK(const GeneralMatrix* gm) { return 0; } - // see bandmat.cpp for explanation - public: - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); - virtual MatrixType Type() const = 0; // type of a matrix - int Nrows() const { return nrows; } // get dimensions - int Ncols() const { return ncols; } - int Storage() const { return storage; } - Real* Store() const { return store; } - virtual ~GeneralMatrix(); // delete store if set - void tDelete(); // delete if tag permits - bool reuse(); // true if tag allows reuse - void Protect() { tag=-1; } // cannot delete or reuse - int Tag() const { return tag; } - bool IsZero() const; // test matrix has all zeros - void Release() { tag=1; } // del store after next use - void Release(int t) { tag=t; } // del store after t accesses - void ReleaseAndDelete() { tag=0; } // delete matrix after use - void operator<<(const Real*); // assignment from an array - void operator<<(const BaseMatrix& X) - { Eq(X,this->Type(),true); } // = without checking type - void Inject(const GeneralMatrix&); // copy stored els only - void operator+=(const BaseMatrix&); - void operator-=(const BaseMatrix&); - void operator*=(const BaseMatrix&); - void operator|=(const BaseMatrix&); - void operator&=(const BaseMatrix&); - void operator+=(Real); - void operator-=(Real r) { operator+=(-r); } - void operator*=(Real); - void operator/=(Real r) { operator*=(1.0/r); } - virtual GeneralMatrix* MakeSolver(); // for solving - virtual void Solver(MatrixColX&, const MatrixColX&) {} - virtual void GetRow(MatrixRowCol&) = 0; // Get matrix row - virtual void RestoreRow(MatrixRowCol&) {} // Restore matrix row - virtual void NextRow(MatrixRowCol&); // Go to next row - virtual void GetCol(MatrixRowCol&) = 0; // Get matrix col - virtual void GetCol(MatrixColX&) = 0; // Get matrix col - virtual void RestoreCol(MatrixRowCol&) {} // Restore matrix col - virtual void RestoreCol(MatrixColX&) {} // Restore matrix col - virtual void NextCol(MatrixRowCol&); // Go to next col - virtual void NextCol(MatrixColX&); // Go to next col - Real SumSquare() const; - Real SumAbsoluteValue() const; - Real Sum() const; - Real MaximumAbsoluteValue1(int& i) const; - Real MinimumAbsoluteValue1(int& i) const; - Real Maximum1(int& i) const; - Real Minimum1(int& i) const; - Real MaximumAbsoluteValue() const; - Real MaximumAbsoluteValue2(int& i, int& j) const; - Real MinimumAbsoluteValue() const; - Real MinimumAbsoluteValue2(int& i, int& j) const; - Real Maximum() const; - Real Maximum2(int& i, int& j) const; - Real Minimum() const; - Real Minimum2(int& i, int& j) const; - LogAndSign LogDeterminant() const; - virtual bool IsEqual(const GeneralMatrix&) const; - // same type, same values - void CheckStore() const; // check store is non-zero - virtual void SetParameters(const GeneralMatrix*) {} - // set parameters in GetMatrix - operator ReturnMatrix() const; // for building a ReturnMatrix - ReturnMatrix ForReturn() const; - virtual bool SameStorageType(const GeneralMatrix& A) const; - virtual void ReSizeForAdd(const GeneralMatrix& A, const GeneralMatrix& B); - virtual void ReSizeForSP(const GeneralMatrix& A, const GeneralMatrix& B); - virtual void ReSize(const GeneralMatrix& A); - MatrixInput operator<<(Real); // for loading a list - MatrixInput operator<<(int f); - // ReturnMatrix Reverse() const; // reverse order of elements - void CleanUp(); // to clear store - - friend class Matrix; - friend class nricMatrix; - friend class SymmetricMatrix; - friend class UpperTriangularMatrix; - friend class LowerTriangularMatrix; - friend class DiagonalMatrix; - friend class CroutMatrix; - friend class RowVector; - friend class ColumnVector; - friend class BandMatrix; - friend class LowerBandMatrix; - friend class UpperBandMatrix; - friend class SymmetricBandMatrix; - friend class BaseMatrix; - friend class AddedMatrix; - friend class MultipliedMatrix; - friend class SubtractedMatrix; - friend class SPMatrix; - friend class KPMatrix; - friend class ConcatenatedMatrix; - friend class StackedMatrix; - friend class SolvedMatrix; - friend class ShiftedMatrix; - friend class NegShiftedMatrix; - friend class ScaledMatrix; - friend class TransposedMatrix; - friend class ReversedMatrix; - friend class NegatedMatrix; - friend class InvertedMatrix; - friend class RowedMatrix; - friend class ColedMatrix; - friend class DiagedMatrix; - friend class MatedMatrix; - friend class GetSubMatrix; - friend class ReturnMatrixX; - friend class LinearEquationSolver; - friend class GenericMatrix; - NEW_DELETE(GeneralMatrix) - }; - - - - class Matrix : public GeneralMatrix // usual rectangular matrix - { - GeneralMatrix* Image() const; // copy of matrix - public: - Matrix() {} - ~Matrix() {} - Matrix(int, int); // standard declaration - Matrix(const BaseMatrix&); // evaluate BaseMatrix - void operator=(const BaseMatrix&); - void operator=(Real f) { GeneralMatrix::operator=(f); } - void operator=(const Matrix& m) { operator=((const BaseMatrix&)m); } - MatrixType Type() const; - Real& operator()(int, int); // access element - Real& element(int, int); // access element - Real operator()(int, int) const; // access element - Real element(int, int) const; // access element -#ifdef SETUP_C_SUBSCRIPTS - Real* operator[](int m) { return store+m*ncols; } - const Real* operator[](int m) const { return store+m*ncols; } -#endif - Matrix(const Matrix& gm) { GetMatrix(&gm); } - GeneralMatrix* MakeSolver(); - Real Trace() const; - void GetRow(MatrixRowCol&); - void GetCol(MatrixRowCol&); - void GetCol(MatrixColX&); - void RestoreCol(MatrixRowCol&); - void RestoreCol(MatrixColX&); - void NextRow(MatrixRowCol&); - void NextCol(MatrixRowCol&); - void NextCol(MatrixColX&); - virtual void ReSize(int,int); // change dimensions - // virtual so we will catch it being used in a vector called as a matrix - void ReSize(const GeneralMatrix& A); - Real MaximumAbsoluteValue2(int& i, int& j) const; - Real MinimumAbsoluteValue2(int& i, int& j) const; - Real Maximum2(int& i, int& j) const; - Real Minimum2(int& i, int& j) const; - friend Real DotProduct(const Matrix& A, const Matrix& B); - NEW_DELETE(Matrix) - }; - - class nricMatrix : public Matrix // for use with Numerical - // Recipes in C - { - GeneralMatrix* Image() const; // copy of matrix - Real** row_pointer; // points to rows - void MakeRowPointer(); // build rowpointer - void DeleteRowPointer(); - public: - nricMatrix() {} - nricMatrix(int m, int n) // standard declaration - : Matrix(m,n) { MakeRowPointer(); } - nricMatrix(const BaseMatrix& bm) // evaluate BaseMatrix - : Matrix(bm) { MakeRowPointer(); } - void operator=(const BaseMatrix& bm) - { DeleteRowPointer(); Matrix::operator=(bm); MakeRowPointer(); } - void operator=(Real f) { GeneralMatrix::operator=(f); } - void operator=(const nricMatrix& m) { operator=((const BaseMatrix&)m); } - void operator<<(const BaseMatrix& X) - { DeleteRowPointer(); Eq(X,this->Type(),true); MakeRowPointer(); } - nricMatrix(const nricMatrix& gm) { GetMatrix(&gm); MakeRowPointer(); } - void ReSize(int m, int n) // change dimensions - { DeleteRowPointer(); Matrix::ReSize(m,n); MakeRowPointer(); } - void ReSize(const GeneralMatrix& A); - ~nricMatrix() { DeleteRowPointer(); } - Real** nric() const { CheckStore(); return row_pointer-1; } - void CleanUp(); // to clear store - NEW_DELETE(nricMatrix) - }; - - class SymmetricMatrix : public GeneralMatrix - { - GeneralMatrix* Image() const; // copy of matrix - public: - SymmetricMatrix() {} - ~SymmetricMatrix() {} - SymmetricMatrix(ArrayLengthSpecifier); - SymmetricMatrix(const BaseMatrix&); - void operator=(const BaseMatrix&); - void operator=(Real f) { GeneralMatrix::operator=(f); } - void operator=(const SymmetricMatrix& m) { operator=((const BaseMatrix&)m); } - Real& operator()(int, int); // access element - Real& element(int, int); // access element - Real operator()(int, int) const; // access element - Real element(int, int) const; // access element -#ifdef SETUP_C_SUBSCRIPTS - Real* operator[](int m) { return store+(m*(m+1))/2; } - const Real* operator[](int m) const { return store+(m*(m+1))/2; } -#endif - MatrixType Type() const; - SymmetricMatrix(const SymmetricMatrix& gm) { GetMatrix(&gm); } - Real SumSquare() const; - Real SumAbsoluteValue() const; - Real Sum() const; - Real Trace() const; - void GetRow(MatrixRowCol&); - void GetCol(MatrixRowCol&); - void GetCol(MatrixColX&); - void RestoreCol(MatrixRowCol&) {} - void RestoreCol(MatrixColX&); - GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); - void ReSize(int); // change dimensions - void ReSize(const GeneralMatrix& A); - NEW_DELETE(SymmetricMatrix) - }; - - class UpperTriangularMatrix : public GeneralMatrix - { - GeneralMatrix* Image() const; // copy of matrix - public: - UpperTriangularMatrix() {} - ~UpperTriangularMatrix() {} - UpperTriangularMatrix(ArrayLengthSpecifier); - void operator=(const BaseMatrix&); - void operator=(const UpperTriangularMatrix& m) - { operator=((const BaseMatrix&)m); } - UpperTriangularMatrix(const BaseMatrix&); - UpperTriangularMatrix(const UpperTriangularMatrix& gm) { GetMatrix(&gm); } - void operator=(Real f) { GeneralMatrix::operator=(f); } - Real& operator()(int, int); // access element - Real& element(int, int); // access element - Real operator()(int, int) const; // access element - Real element(int, int) const; // access element -#ifdef SETUP_C_SUBSCRIPTS - Real* operator[](int m) { return store+m*ncols-(m*(m+1))/2; } - const Real* operator[](int m) const { return store+m*ncols-(m*(m+1))/2; } -#endif - MatrixType Type() const; - GeneralMatrix* MakeSolver() { return this; } // for solving - void Solver(MatrixColX&, const MatrixColX&); - LogAndSign LogDeterminant() const; - Real Trace() const; - void GetRow(MatrixRowCol&); - void GetCol(MatrixRowCol&); - void GetCol(MatrixColX&); - void RestoreCol(MatrixRowCol&); - void RestoreCol(MatrixColX& c) { RestoreCol((MatrixRowCol&)c); } - void NextRow(MatrixRowCol&); - void ReSize(int); // change dimensions - void ReSize(const GeneralMatrix& A); - MatrixBandWidth BandWidth() const; - NEW_DELETE(UpperTriangularMatrix) - }; - - class LowerTriangularMatrix : public GeneralMatrix - { - GeneralMatrix* Image() const; // copy of matrix - public: - LowerTriangularMatrix() {} - ~LowerTriangularMatrix() {} - LowerTriangularMatrix(ArrayLengthSpecifier); - LowerTriangularMatrix(const LowerTriangularMatrix& gm) { GetMatrix(&gm); } - LowerTriangularMatrix(const BaseMatrix& M); - void operator=(const BaseMatrix&); - void operator=(Real f) { GeneralMatrix::operator=(f); } - void operator=(const LowerTriangularMatrix& m) - { operator=((const BaseMatrix&)m); } - Real& operator()(int, int); // access element - Real& element(int, int); // access element - Real operator()(int, int) const; // access element - Real element(int, int) const; // access element -#ifdef SETUP_C_SUBSCRIPTS - Real* operator[](int m) { return store+(m*(m+1))/2; } - const Real* operator[](int m) const { return store+(m*(m+1))/2; } -#endif - MatrixType Type() const; - GeneralMatrix* MakeSolver() { return this; } // for solving - void Solver(MatrixColX&, const MatrixColX&); - LogAndSign LogDeterminant() const; - Real Trace() const; - void GetRow(MatrixRowCol&); - void GetCol(MatrixRowCol&); - void GetCol(MatrixColX&); - void RestoreCol(MatrixRowCol&); - void RestoreCol(MatrixColX& c) { RestoreCol((MatrixRowCol&)c); } - void NextRow(MatrixRowCol&); - void ReSize(int); // change dimensions - void ReSize(const GeneralMatrix& A); - MatrixBandWidth BandWidth() const; - NEW_DELETE(LowerTriangularMatrix) - }; - - class DiagonalMatrix : public GeneralMatrix - { - GeneralMatrix* Image() const; // copy of matrix - public: - DiagonalMatrix() {} - ~DiagonalMatrix() {} - DiagonalMatrix(ArrayLengthSpecifier); - DiagonalMatrix(const BaseMatrix&); - DiagonalMatrix(const DiagonalMatrix& gm) { GetMatrix(&gm); } - void operator=(const BaseMatrix&); - void operator=(Real f) { GeneralMatrix::operator=(f); } - void operator=(const DiagonalMatrix& m) { operator=((const BaseMatrix&)m); } - Real& operator()(int, int); // access element - Real& operator()(int); // access element - Real operator()(int, int) const; // access element - Real operator()(int) const; - Real& element(int, int); // access element - Real& element(int); // access element - Real element(int, int) const; // access element - Real element(int) const; // access element -#ifdef SETUP_C_SUBSCRIPTS - Real& operator[](int m) { return store[m]; } - const Real& operator[](int m) const { return store[m]; } -#endif - MatrixType Type() const; - - LogAndSign LogDeterminant() const; - Real Trace() const; - void GetRow(MatrixRowCol&); - void GetCol(MatrixRowCol&); - void GetCol(MatrixColX&); - void NextRow(MatrixRowCol&); - void NextCol(MatrixRowCol&); - void NextCol(MatrixColX&); - GeneralMatrix* MakeSolver() { return this; } // for solving - void Solver(MatrixColX&, const MatrixColX&); - GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); - void ReSize(int); // change dimensions - void ReSize(const GeneralMatrix& A); - Real* nric() const - { CheckStore(); return store-1; } // for use by NRIC - MatrixBandWidth BandWidth() const; - // ReturnMatrix Reverse() const; // reverse order of elements - NEW_DELETE(DiagonalMatrix) - }; - - class RowVector : public Matrix - { - GeneralMatrix* Image() const; // copy of matrix - public: - RowVector() { nrows = 1; } - ~RowVector() {} - RowVector(ArrayLengthSpecifier n) : Matrix(1,n.Value()) {} - RowVector(const BaseMatrix&); - RowVector(const RowVector& gm) { GetMatrix(&gm); } - void operator=(const BaseMatrix&); - void operator=(Real f) { GeneralMatrix::operator=(f); } - void operator=(const RowVector& m) { operator=((const BaseMatrix&)m); } - Real& operator()(int); // access element - Real& element(int); // access element - Real operator()(int) const; // access element - Real element(int) const; // access element -#ifdef SETUP_C_SUBSCRIPTS - Real& operator[](int m) { return store[m]; } - const Real& operator[](int m) const { return store[m]; } -#endif - MatrixType Type() const; - void GetCol(MatrixRowCol&); - void GetCol(MatrixColX&); - void NextCol(MatrixRowCol&); - void NextCol(MatrixColX&); - void RestoreCol(MatrixRowCol&) {} - void RestoreCol(MatrixColX& c); - GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); - void ReSize(int); // change dimensions - void ReSize(int,int); // in case access is matrix - void ReSize(const GeneralMatrix& A); - Real* nric() const - { CheckStore(); return store-1; } // for use by NRIC - void CleanUp(); // to clear store - // friend ReturnMatrix GetMatrixRow(Matrix& A, int row); - NEW_DELETE(RowVector) - }; - - class ColumnVector : public Matrix - { - GeneralMatrix* Image() const; // copy of matrix - public: - ColumnVector() { ncols = 1; } - ~ColumnVector() {} - ColumnVector(ArrayLengthSpecifier n) : Matrix(n.Value(),1) {} - ColumnVector(const BaseMatrix&); - ColumnVector(const ColumnVector& gm) { GetMatrix(&gm); } - void operator=(const BaseMatrix&); - void operator=(Real f) { GeneralMatrix::operator=(f); } - void operator=(const ColumnVector& m) { operator=((const BaseMatrix&)m); } - Real& operator()(int); // access element - Real& element(int); // access element - Real operator()(int) const; // access element - Real element(int) const; // access element -#ifdef SETUP_C_SUBSCRIPTS - Real& operator[](int m) { return store[m]; } - const Real& operator[](int m) const { return store[m]; } -#endif - MatrixType Type() const; - GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); - void ReSize(int); // change dimensions - void ReSize(int,int); // in case access is matrix - void ReSize(const GeneralMatrix& A); - Real* nric() const - { CheckStore(); return store-1; } // for use by NRIC - void CleanUp(); // to clear store - // ReturnMatrix Reverse() const; // reverse order of elements - NEW_DELETE(ColumnVector) - }; - - class CroutMatrix : public GeneralMatrix // for LU decomposition - { - int* indx; - bool d; - bool sing; - void ludcmp(); - public: - CroutMatrix(const BaseMatrix&); - MatrixType Type() const; - void lubksb(Real*, int=0); - ~CroutMatrix(); - GeneralMatrix* MakeSolver() { return this; } // for solving - LogAndSign LogDeterminant() const; - void Solver(MatrixColX&, const MatrixColX&); - void GetRow(MatrixRowCol&); - void GetCol(MatrixRowCol&); - void GetCol(MatrixColX& c) { GetCol((MatrixRowCol&)c); } - void operator=(const BaseMatrix&); - void operator=(const CroutMatrix& m) { operator=((const BaseMatrix&)m); } - void CleanUp(); // to clear store - bool IsEqual(const GeneralMatrix&) const; - bool IsSingular() const { return sing; } - NEW_DELETE(CroutMatrix) - }; - - // ***************************** band matrices ***************************/ - - class BandMatrix : public GeneralMatrix // band matrix - { - GeneralMatrix* Image() const; // copy of matrix - protected: - void CornerClear() const; // set unused elements to zero - short SimpleAddOK(const GeneralMatrix* gm); - public: - int lower, upper; // band widths - BandMatrix() { lower=0; upper=0; CornerClear(); } - ~BandMatrix() {} - BandMatrix(int n,int lb,int ub) { ReSize(n,lb,ub); CornerClear(); } - // standard declaration - BandMatrix(const BaseMatrix&); // evaluate BaseMatrix - void operator=(const BaseMatrix&); - void operator=(Real f) { GeneralMatrix::operator=(f); } - void operator=(const BandMatrix& m) { operator=((const BaseMatrix&)m); } - MatrixType Type() const; - Real& operator()(int, int); // access element - Real& element(int, int); // access element - Real operator()(int, int) const; // access element - Real element(int, int) const; // access element -#ifdef SETUP_C_SUBSCRIPTS - Real* operator[](int m) { return store+(upper+lower)*m+lower; } - const Real* operator[](int m) const { return store+(upper+lower)*m+lower; } -#endif - BandMatrix(const BandMatrix& gm) { GetMatrix(&gm); } - LogAndSign LogDeterminant() const; - GeneralMatrix* MakeSolver(); - Real Trace() const; - Real SumSquare() const { CornerClear(); return GeneralMatrix::SumSquare(); } - Real SumAbsoluteValue() const - { CornerClear(); return GeneralMatrix::SumAbsoluteValue(); } - Real Sum() const - { CornerClear(); return GeneralMatrix::Sum(); } - Real MaximumAbsoluteValue() const - { CornerClear(); return GeneralMatrix::MaximumAbsoluteValue(); } - Real MinimumAbsoluteValue() const - { int i, j; return GeneralMatrix::MinimumAbsoluteValue2(i, j); } - Real Maximum() const { int i, j; return GeneralMatrix::Maximum2(i, j); } - Real Minimum() const { int i, j; return GeneralMatrix::Minimum2(i, j); } - void GetRow(MatrixRowCol&); - void GetCol(MatrixRowCol&); - void GetCol(MatrixColX&); - void RestoreCol(MatrixRowCol&); - void RestoreCol(MatrixColX& c) { RestoreCol((MatrixRowCol&)c); } - void NextRow(MatrixRowCol&); - virtual void ReSize(int, int, int); // change dimensions - void ReSize(const GeneralMatrix& A); - bool SameStorageType(const GeneralMatrix& A) const; - void ReSizeForAdd(const GeneralMatrix& A, const GeneralMatrix& B); - void ReSizeForSP(const GeneralMatrix& A, const GeneralMatrix& B); - MatrixBandWidth BandWidth() const; - void SetParameters(const GeneralMatrix*); - MatrixInput operator<<(Real); // will give error - MatrixInput operator<<(int f); - void operator<<(const Real* r); // will give error - // the next is included because Zortech and Borland - // cannot find the copy in GeneralMatrix - void operator<<(const BaseMatrix& X) { GeneralMatrix::operator<<(X); } - NEW_DELETE(BandMatrix) - }; - - class UpperBandMatrix : public BandMatrix // upper band matrix - { - GeneralMatrix* Image() const; // copy of matrix - public: - UpperBandMatrix() {} - ~UpperBandMatrix() {} - UpperBandMatrix(int n, int ubw) // standard declaration - : BandMatrix(n, 0, ubw) {} - UpperBandMatrix(const BaseMatrix&); // evaluate BaseMatrix - void operator=(const BaseMatrix&); - void operator=(Real f) { GeneralMatrix::operator=(f); } - void operator=(const UpperBandMatrix& m) - { operator=((const BaseMatrix&)m); } - MatrixType Type() const; - UpperBandMatrix(const UpperBandMatrix& gm) { GetMatrix(&gm); } - GeneralMatrix* MakeSolver() { return this; } - void Solver(MatrixColX&, const MatrixColX&); - LogAndSign LogDeterminant() const; - void ReSize(int, int, int); // change dimensions - void ReSize(int n,int ubw) // change dimensions - { BandMatrix::ReSize(n,0,ubw); } - void ReSize(const GeneralMatrix& A) { BandMatrix::ReSize(A); } - Real& operator()(int, int); - Real operator()(int, int) const; - Real& element(int, int); - Real element(int, int) const; -#ifdef SETUP_C_SUBSCRIPTS - Real* operator[](int m) { return store+upper*m; } - const Real* operator[](int m) const { return store+upper*m; } -#endif - NEW_DELETE(UpperBandMatrix) - }; - - class LowerBandMatrix : public BandMatrix // upper band matrix - { - GeneralMatrix* Image() const; // copy of matrix - public: - LowerBandMatrix() {} - ~LowerBandMatrix() {} - LowerBandMatrix(int n, int lbw) // standard declaration - : BandMatrix(n, lbw, 0) {} - LowerBandMatrix(const BaseMatrix&); // evaluate BaseMatrix - void operator=(const BaseMatrix&); - void operator=(Real f) { GeneralMatrix::operator=(f); } - void operator=(const LowerBandMatrix& m) - { operator=((const BaseMatrix&)m); } - MatrixType Type() const; - LowerBandMatrix(const LowerBandMatrix& gm) { GetMatrix(&gm); } - GeneralMatrix* MakeSolver() { return this; } - void Solver(MatrixColX&, const MatrixColX&); - LogAndSign LogDeterminant() const; - void ReSize(int, int, int); // change dimensions - void ReSize(int n,int lbw) // change dimensions - { BandMatrix::ReSize(n,lbw,0); } - void ReSize(const GeneralMatrix& A) { BandMatrix::ReSize(A); } - Real& operator()(int, int); - Real operator()(int, int) const; - Real& element(int, int); - Real element(int, int) const; -#ifdef SETUP_C_SUBSCRIPTS - Real* operator[](int m) { return store+lower*(m+1); } - const Real* operator[](int m) const { return store+lower*(m+1); } -#endif - NEW_DELETE(LowerBandMatrix) - }; - - class SymmetricBandMatrix : public GeneralMatrix - { - GeneralMatrix* Image() const; // copy of matrix - void CornerClear() const; // set unused elements to zero - short SimpleAddOK(const GeneralMatrix* gm); - public: - int lower; // lower band width - SymmetricBandMatrix() { lower=0; CornerClear(); } - ~SymmetricBandMatrix() {} - SymmetricBandMatrix(int n, int lb) { ReSize(n,lb); CornerClear(); } - SymmetricBandMatrix(const BaseMatrix&); - void operator=(const BaseMatrix&); - void operator=(Real f) { GeneralMatrix::operator=(f); } - void operator=(const SymmetricBandMatrix& m) - { operator=((const BaseMatrix&)m); } - Real& operator()(int, int); // access element - Real& element(int, int); // access element - Real operator()(int, int) const; // access element - Real element(int, int) const; // access element -#ifdef SETUP_C_SUBSCRIPTS - Real* operator[](int m) { return store+lower*(m+1); } - const Real* operator[](int m) const { return store+lower*(m+1); } -#endif - MatrixType Type() const; - SymmetricBandMatrix(const SymmetricBandMatrix& gm) { GetMatrix(&gm); } - GeneralMatrix* MakeSolver(); - Real SumSquare() const; - Real SumAbsoluteValue() const; - Real Sum() const; - Real MaximumAbsoluteValue() const - { CornerClear(); return GeneralMatrix::MaximumAbsoluteValue(); } - Real MinimumAbsoluteValue() const - { int i, j; return GeneralMatrix::MinimumAbsoluteValue2(i, j); } - Real Maximum() const { int i, j; return GeneralMatrix::Maximum2(i, j); } - Real Minimum() const { int i, j; return GeneralMatrix::Minimum2(i, j); } - Real Trace() const; - LogAndSign LogDeterminant() const; - void GetRow(MatrixRowCol&); - void GetCol(MatrixRowCol&); - void GetCol(MatrixColX&); - void RestoreCol(MatrixRowCol&) {} - void RestoreCol(MatrixColX&); - GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); - void ReSize(int,int); // change dimensions - void ReSize(const GeneralMatrix& A); - bool SameStorageType(const GeneralMatrix& A) const; - void ReSizeForAdd(const GeneralMatrix& A, const GeneralMatrix& B); - void ReSizeForSP(const GeneralMatrix& A, const GeneralMatrix& B); - MatrixBandWidth BandWidth() const; - void SetParameters(const GeneralMatrix*); - NEW_DELETE(SymmetricBandMatrix) - }; - - class BandLUMatrix : public GeneralMatrix - // for LU decomposition of band matrix - { - int* indx; - bool d; - bool sing; // true if singular - Real* store2; - int storage2; - void ludcmp(); - int m1,m2; // lower and upper - public: - BandLUMatrix(const BaseMatrix&); - MatrixType Type() const; - void lubksb(Real*, int=0); - ~BandLUMatrix(); - GeneralMatrix* MakeSolver() { return this; } // for solving - LogAndSign LogDeterminant() const; - void Solver(MatrixColX&, const MatrixColX&); - void GetRow(MatrixRowCol&); - void GetCol(MatrixRowCol&); - void GetCol(MatrixColX& c) { GetCol((MatrixRowCol&)c); } - void operator=(const BaseMatrix&); - void operator=(const BandLUMatrix& m) { operator=((const BaseMatrix&)m); } - void CleanUp(); // to clear store - bool IsEqual(const GeneralMatrix&) const; - bool IsSingular() const { return sing; } - NEW_DELETE(BandLUMatrix) - }; - - // ************************** special matrices **************************** - - class IdentityMatrix : public GeneralMatrix - { - GeneralMatrix* Image() const; // copy of matrix - public: - IdentityMatrix() {} - ~IdentityMatrix() {} - IdentityMatrix(ArrayLengthSpecifier n) : GeneralMatrix(1) - { nrows = ncols = n.Value(); *store = 1; } - IdentityMatrix(const IdentityMatrix& gm) { GetMatrix(&gm); } - IdentityMatrix(const BaseMatrix&); - void operator=(const BaseMatrix&); - void operator=(Real f) { GeneralMatrix::operator=(f); } - MatrixType Type() const; - - LogAndSign LogDeterminant() const; - Real Trace() const; - Real SumSquare() const; - Real SumAbsoluteValue() const; - Real Sum() const { return Trace(); } - void GetRow(MatrixRowCol&); - void GetCol(MatrixRowCol&); - void GetCol(MatrixColX&); - void NextRow(MatrixRowCol&); - void NextCol(MatrixRowCol&); - void NextCol(MatrixColX&); - GeneralMatrix* MakeSolver() { return this; } // for solving - void Solver(MatrixColX&, const MatrixColX&); - GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); - void ReSize(int n); - void ReSize(const GeneralMatrix& A); - MatrixBandWidth BandWidth() const; - // ReturnMatrix Reverse() const; // reverse order of elements - NEW_DELETE(IdentityMatrix) - }; - - - - - // ************************** GenericMatrix class ************************/ - - class GenericMatrix : public BaseMatrix - { - GeneralMatrix* gm; - int search(const BaseMatrix* bm) const; - friend class BaseMatrix; - public: - GenericMatrix() : gm(0) {} - GenericMatrix(const BaseMatrix& bm) - { gm = ((BaseMatrix&)bm).Evaluate(); gm = gm->Image(); } - GenericMatrix(const GenericMatrix& bm) - { gm = bm.gm->Image(); } - void operator=(const GenericMatrix&); - void operator=(const BaseMatrix&); - void operator+=(const BaseMatrix&); - void operator-=(const BaseMatrix&); - void operator*=(const BaseMatrix&); - void operator|=(const BaseMatrix&); - void operator&=(const BaseMatrix&); - void operator+=(Real); - void operator-=(Real r) { operator+=(-r); } - void operator*=(Real); - void operator/=(Real r) { operator*=(1.0/r); } - ~GenericMatrix() { delete gm; } - void CleanUp() { delete gm; gm = 0; } - void Release() { gm->Release(); } - GeneralMatrix* Evaluate(MatrixType = MatrixTypeUnSp); - MatrixBandWidth BandWidth() const; - NEW_DELETE(GenericMatrix) - }; - - // *************************** temporary classes *************************/ - - class MultipliedMatrix : public BaseMatrix - { - protected: - // if these union statements cause problems, simply remove them - // and declare the items individually - union { const BaseMatrix* bm1; GeneralMatrix* gm1; }; - // pointers to summands - union { const BaseMatrix* bm2; GeneralMatrix* gm2; }; - MultipliedMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) - : bm1(bm1x),bm2(bm2x) {} - int search(const BaseMatrix*) const; - friend class BaseMatrix; - friend class GeneralMatrix; - friend class GenericMatrix; - public: - ~MultipliedMatrix() {} - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); - MatrixBandWidth BandWidth() const; - NEW_DELETE(MultipliedMatrix) - }; - - class AddedMatrix : public MultipliedMatrix - { - protected: - AddedMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) - : MultipliedMatrix(bm1x,bm2x) {} - - friend class BaseMatrix; - friend class GeneralMatrix; - friend class GenericMatrix; - public: - ~AddedMatrix() {} - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); - MatrixBandWidth BandWidth() const; - NEW_DELETE(AddedMatrix) - }; - - class SPMatrix : public AddedMatrix - { - protected: - SPMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) - : AddedMatrix(bm1x,bm2x) {} - - friend class BaseMatrix; - friend class GeneralMatrix; - friend class GenericMatrix; - public: - ~SPMatrix() {} - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); - MatrixBandWidth BandWidth() const; - -#ifndef TEMPS_DESTROYED_QUICKLY - friend SPMatrix SP(const BaseMatrix&, const BaseMatrix&); -#else - friend SPMatrix& SP(const BaseMatrix&, const BaseMatrix&); -#endif - - NEW_DELETE(SPMatrix) - }; - - class KPMatrix : public MultipliedMatrix - { - protected: - KPMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) - : MultipliedMatrix(bm1x,bm2x) {} - - friend class BaseMatrix; - friend class GeneralMatrix; - friend class GenericMatrix; - public: - ~KPMatrix() {} - MatrixBandWidth BandWidth() const; - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); -#ifndef TEMPS_DESTROYED_QUICKLY - friend KPMatrix KP(const BaseMatrix&, const BaseMatrix&); -#else - friend KPMatrix& KP(const BaseMatrix&, const BaseMatrix&); -#endif - NEW_DELETE(KPMatrix) - }; - - class ConcatenatedMatrix : public MultipliedMatrix - { - protected: - ConcatenatedMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) - : MultipliedMatrix(bm1x,bm2x) {} - - friend class BaseMatrix; - friend class GeneralMatrix; - friend class GenericMatrix; - public: - ~ConcatenatedMatrix() {} - MatrixBandWidth BandWidth() const; - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); - NEW_DELETE(ConcatenatedMatrix) - }; - - class StackedMatrix : public ConcatenatedMatrix - { - protected: - StackedMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) - : ConcatenatedMatrix(bm1x,bm2x) {} - - friend class BaseMatrix; - friend class GeneralMatrix; - friend class GenericMatrix; - public: - ~StackedMatrix() {} - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); - NEW_DELETE(StackedMatrix) - }; - - class SolvedMatrix : public MultipliedMatrix - { - SolvedMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) - : MultipliedMatrix(bm1x,bm2x) {} - friend class BaseMatrix; - friend class InvertedMatrix; // for operator* - public: - ~SolvedMatrix() {} - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); - MatrixBandWidth BandWidth() const; - NEW_DELETE(SolvedMatrix) - }; - - class SubtractedMatrix : public AddedMatrix - { - SubtractedMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) - : AddedMatrix(bm1x,bm2x) {} - friend class BaseMatrix; - friend class GeneralMatrix; - friend class GenericMatrix; - public: - ~SubtractedMatrix() {} - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); - NEW_DELETE(SubtractedMatrix) - }; - - class ShiftedMatrix : public BaseMatrix - { - protected: - union { const BaseMatrix* bm; GeneralMatrix* gm; }; - Real f; - ShiftedMatrix(const BaseMatrix* bmx, Real fx) : bm(bmx),f(fx) {} - int search(const BaseMatrix*) const; - friend class BaseMatrix; - friend class GeneralMatrix; - friend class GenericMatrix; - public: - ~ShiftedMatrix() {} - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); -#ifndef TEMPS_DESTROYED_QUICKLY - friend ShiftedMatrix operator+(Real f, const BaseMatrix& BM); - // { return ShiftedMatrix(&BM, f); } -#endif - NEW_DELETE(ShiftedMatrix) - }; - - class NegShiftedMatrix : public ShiftedMatrix - { - protected: - NegShiftedMatrix(Real fx, const BaseMatrix* bmx) : ShiftedMatrix(bmx,fx) {} - friend class BaseMatrix; - friend class GeneralMatrix; - friend class GenericMatrix; - public: - ~NegShiftedMatrix() {} - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); -#ifndef TEMPS_DESTROYED_QUICKLY - friend NegShiftedMatrix operator-(Real, const BaseMatrix&); -#else - friend NegShiftedMatrix& operator-(Real, const BaseMatrix&); -#endif - NEW_DELETE(NegShiftedMatrix) - }; - - class ScaledMatrix : public ShiftedMatrix - { - ScaledMatrix(const BaseMatrix* bmx, Real fx) : ShiftedMatrix(bmx,fx) {} - friend class BaseMatrix; - friend class GeneralMatrix; - friend class GenericMatrix; - public: - ~ScaledMatrix() {} - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); - MatrixBandWidth BandWidth() const; -#ifndef TEMPS_DESTROYED_QUICKLY - friend ScaledMatrix operator*(Real f, const BaseMatrix& BM); - //{ return ScaledMatrix(&BM, f); } -#endif - NEW_DELETE(ScaledMatrix) - }; - - class NegatedMatrix : public BaseMatrix - { - protected: - union { const BaseMatrix* bm; GeneralMatrix* gm; }; - NegatedMatrix(const BaseMatrix* bmx) : bm(bmx) {} - int search(const BaseMatrix*) const; - private: - friend class BaseMatrix; - public: - ~NegatedMatrix() {} - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); - MatrixBandWidth BandWidth() const; - NEW_DELETE(NegatedMatrix) - }; - - class TransposedMatrix : public NegatedMatrix - { - TransposedMatrix(const BaseMatrix* bmx) : NegatedMatrix(bmx) {} - friend class BaseMatrix; - public: - ~TransposedMatrix() {} - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); - MatrixBandWidth BandWidth() const; - NEW_DELETE(TransposedMatrix) - }; - - class ReversedMatrix : public NegatedMatrix - { - ReversedMatrix(const BaseMatrix* bmx) : NegatedMatrix(bmx) {} - friend class BaseMatrix; - public: - ~ReversedMatrix() {} - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); - NEW_DELETE(ReversedMatrix) - }; - - class InvertedMatrix : public NegatedMatrix - { - InvertedMatrix(const BaseMatrix* bmx) : NegatedMatrix(bmx) {} - public: - ~InvertedMatrix() {} -#ifndef TEMPS_DESTROYED_QUICKLY - SolvedMatrix operator*(const BaseMatrix&) const; // inverse(A) * B - ScaledMatrix operator*(Real t) const { return BaseMatrix::operator*(t); } -#else - SolvedMatrix& operator*(const BaseMatrix&); // inverse(A) * B - ScaledMatrix& operator*(Real t) const { return BaseMatrix::operator*(t); } -#endif - friend class BaseMatrix; - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); - MatrixBandWidth BandWidth() const; - NEW_DELETE(InvertedMatrix) - }; - - class RowedMatrix : public NegatedMatrix - { - RowedMatrix(const BaseMatrix* bmx) : NegatedMatrix(bmx) {} - friend class BaseMatrix; - public: - ~RowedMatrix() {} - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); - MatrixBandWidth BandWidth() const; - NEW_DELETE(RowedMatrix) - }; - - class ColedMatrix : public NegatedMatrix - { - ColedMatrix(const BaseMatrix* bmx) : NegatedMatrix(bmx) {} - friend class BaseMatrix; - public: - ~ColedMatrix() {} - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); - MatrixBandWidth BandWidth() const; - NEW_DELETE(ColedMatrix) - }; - - class DiagedMatrix : public NegatedMatrix - { - DiagedMatrix(const BaseMatrix* bmx) : NegatedMatrix(bmx) {} - friend class BaseMatrix; - public: - ~DiagedMatrix() {} - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); - MatrixBandWidth BandWidth() const; - NEW_DELETE(DiagedMatrix) - }; - - class MatedMatrix : public NegatedMatrix - { - int nr, nc; - MatedMatrix(const BaseMatrix* bmx, int nrx, int ncx) - : NegatedMatrix(bmx), nr(nrx), nc(ncx) {} - friend class BaseMatrix; - public: - ~MatedMatrix() {} - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); - MatrixBandWidth BandWidth() const; - NEW_DELETE(MatedMatrix) - }; - - class ReturnMatrixX : public BaseMatrix // for matrix return - { - GeneralMatrix* gm; - int search(const BaseMatrix*) const; - public: - ~ReturnMatrixX() {} - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); - friend class BaseMatrix; -#ifdef TEMPS_DESTROYED_QUICKLY_R - ReturnMatrixX(const ReturnMatrixX& tm); -#else - ReturnMatrixX(const ReturnMatrixX& tm) : gm(tm.gm) {} -#endif - ReturnMatrixX(const GeneralMatrix* gmx) : gm((GeneralMatrix*&)gmx) {} - // ReturnMatrixX(GeneralMatrix&); - MatrixBandWidth BandWidth() const; - NEW_DELETE(ReturnMatrixX) - }; - - - // ************************** submatrices ******************************/ - - class GetSubMatrix : public NegatedMatrix - { - int row_skip; - int row_number; - int col_skip; - int col_number; - bool IsSym; - - GetSubMatrix - (const BaseMatrix* bmx, int rs, int rn, int cs, int cn, bool is) - : NegatedMatrix(bmx), - row_skip(rs), row_number(rn), col_skip(cs), col_number(cn), IsSym(is) {} - void SetUpLHS(); - friend class BaseMatrix; - public: - GetSubMatrix(const GetSubMatrix& g) - : NegatedMatrix(g.bm), row_skip(g.row_skip), row_number(g.row_number), - col_skip(g.col_skip), col_number(g.col_number), IsSym(g.IsSym) {} - ~GetSubMatrix() {} - GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); - void operator=(const BaseMatrix&); - void operator+=(const BaseMatrix&); - void operator-=(const BaseMatrix&); - void operator=(const GetSubMatrix& m) { operator=((const BaseMatrix&)m); } - void operator<<(const BaseMatrix&); - void operator<<(const Real*); // copy from array - MatrixInput operator<<(Real); // for loading a list - MatrixInput operator<<(int f); - void operator=(Real); // copy from constant - void operator+=(Real); // add constant - void operator-=(Real r) { operator+=(-r); } // subtract constant - void operator*=(Real); // multiply by constant - void operator/=(Real r) { operator*=(1.0/r); } // divide by constant - void Inject(const GeneralMatrix&); // copy stored els only - MatrixBandWidth BandWidth() const; - NEW_DELETE(GetSubMatrix) - }; - - // ******************** linear equation solving ****************************/ - - class LinearEquationSolver : public BaseMatrix - { - GeneralMatrix* gm; - int search(const BaseMatrix*) const { return 0; } - friend class BaseMatrix; - public: - LinearEquationSolver(const BaseMatrix& bm); - ~LinearEquationSolver() { delete gm; } - void CleanUp() { delete gm; } - GeneralMatrix* Evaluate(MatrixType) { return gm; } - // probably should have an error message if MatrixType != UnSp - NEW_DELETE(LinearEquationSolver) - }; - - // ************************** matrix input *******************************/ - - class MatrixInput // for reading a list of values into a matrix - // the difficult part is detecting a mismatch - // in the number of elements - { - int n; // number values still to be read - Real* r; // pointer to next location to be read to - public: - MatrixInput(const MatrixInput& mi) : n(mi.n), r(mi.r) {} - MatrixInput(int nx, Real* rx) : n(nx), r(rx) {} - ~MatrixInput(); - MatrixInput operator<<(Real); - MatrixInput operator<<(int f); - friend class GeneralMatrix; - }; - - - - // **************** a very simple integer array class ********************/ - - // A minimal array class to imitate a C style array but giving dynamic storage - // mostly intended for internal use by newmat - - class SimpleIntArray : public Janitor - { - protected: - int* a; // pointer to the array - int n; // length of the array - public: - SimpleIntArray(int xn); // build an array length xn - ~SimpleIntArray(); // return the space to memory - int& operator[](int i); // access element of the array - start at 0 - int operator[](int i) const; - // access element of constant array - void operator=(int ai); // set the array equal to a constant - void operator=(const SimpleIntArray& b); - // copy the elements of an array - SimpleIntArray(const SimpleIntArray& b); - // make a new array equal to an existing one - int Size() const { return n; } - // return the size of the array - int* Data() { return a; } // pointer to the data - const int* Data() const { return a; } - // pointer to the data - void ReSize(int i, bool keep = false); - // change length, keep data if keep = true - void CleanUp() { ReSize(0); } - NEW_DELETE(SimpleIntArray) - }; - - // *************************** exceptions ********************************/ - - class NPDException : public Runtime_error // Not positive definite - { - public: - static unsigned long Select; // for identifying exception - NPDException(const GeneralMatrix&); - }; - - class ConvergenceException : public Runtime_error - { - public: - static unsigned long Select; // for identifying exception - ConvergenceException(const GeneralMatrix& A); - ConvergenceException(const char* c); - }; - - class SingularException : public Runtime_error - { - public: - static unsigned long Select; // for identifying exception - SingularException(const GeneralMatrix& A); - }; - - class OverflowException : public Runtime_error - { - public: - static unsigned long Select; // for identifying exception - OverflowException(const char* c); - }; - - class ProgramException : public Logic_error - { - protected: - ProgramException(); - public: - static unsigned long Select; // for identifying exception - ProgramException(const char* c); - ProgramException(const char* c, const GeneralMatrix&); - ProgramException(const char* c, const GeneralMatrix&, const GeneralMatrix&); - ProgramException(const char* c, MatrixType, MatrixType); - }; - - class IndexException : public Logic_error - { - public: - static unsigned long Select; // for identifying exception - IndexException(int i, const GeneralMatrix& A); - IndexException(int i, int j, const GeneralMatrix& A); - // next two are for access via element function - IndexException(int i, const GeneralMatrix& A, bool); - IndexException(int i, int j, const GeneralMatrix& A, bool); - }; - - class VectorException : public Logic_error // cannot convert to vector - { - public: - static unsigned long Select; // for identifying exception - VectorException(); - VectorException(const GeneralMatrix& A); - }; - - class NotSquareException : public Logic_error - { - public: - static unsigned long Select; // for identifying exception - NotSquareException(const GeneralMatrix& A); - }; - - class SubMatrixDimensionException : public Logic_error - { - public: - static unsigned long Select; // for identifying exception - SubMatrixDimensionException(); - }; - - class IncompatibleDimensionsException : public Logic_error - { - public: - static unsigned long Select; // for identifying exception - IncompatibleDimensionsException(); - IncompatibleDimensionsException(const GeneralMatrix&, const GeneralMatrix&); - }; - - class NotDefinedException : public Logic_error - { - public: - static unsigned long Select; // for identifying exception - NotDefinedException(const char* op, const char* matrix); - }; - - class CannotBuildException : public Logic_error - { - public: - static unsigned long Select; // for identifying exception - CannotBuildException(const char* matrix); - }; - - - class InternalException : public Logic_error - { - public: - static unsigned long Select; // for identifying exception - InternalException(const char* c); - }; - - // ************************ functions ************************************ // - - bool operator==(const GeneralMatrix& A, const GeneralMatrix& B); - bool operator==(const BaseMatrix& A, const BaseMatrix& B); - inline bool operator!=(const GeneralMatrix& A, const GeneralMatrix& B) - { return ! (A==B); } - inline bool operator!=(const BaseMatrix& A, const BaseMatrix& B) - { return ! (A==B); } - - // inequality operators are dummies included for compatibility - // with STL. They throw an exception if actually called. - inline bool operator<=(const BaseMatrix& A, const BaseMatrix&) - { A.IEQND(); return true; } - inline bool operator>=(const BaseMatrix& A, const BaseMatrix&) - { A.IEQND(); return true; } - inline bool operator<(const BaseMatrix& A, const BaseMatrix&) - { A.IEQND(); return true; } - inline bool operator>(const BaseMatrix& A, const BaseMatrix&) - { A.IEQND(); return true; } - - bool IsZero(const BaseMatrix& A); - - - // ********************* inline functions ******************************** // - - - inline LogAndSign LogDeterminant(const BaseMatrix& B) - { return B.LogDeterminant(); } - inline Real Determinant(const BaseMatrix& B) - { return B.Determinant(); } - inline Real SumSquare(const BaseMatrix& B) { return B.SumSquare(); } - inline Real NormFrobenius(const BaseMatrix& B) { return B.NormFrobenius(); } - inline Real Trace(const BaseMatrix& B) { return B.Trace(); } - inline Real SumAbsoluteValue(const BaseMatrix& B) - { return B.SumAbsoluteValue(); } - inline Real Sum(const BaseMatrix& B) - { return B.Sum(); } - inline Real MaximumAbsoluteValue(const BaseMatrix& B) - { return B.MaximumAbsoluteValue(); } - inline Real MinimumAbsoluteValue(const BaseMatrix& B) - { return B.MinimumAbsoluteValue(); } - inline Real Maximum(const BaseMatrix& B) { return B.Maximum(); } - inline Real Minimum(const BaseMatrix& B) { return B.Minimum(); } - inline Real Norm1(const BaseMatrix& B) { return B.Norm1(); } - inline Real Norm1(RowVector& RV) { return RV.MaximumAbsoluteValue(); } - inline Real NormInfinity(const BaseMatrix& B) { return B.NormInfinity(); } - inline Real NormInfinity(ColumnVector& CV) - { return CV.MaximumAbsoluteValue(); } - inline bool IsZero(const GeneralMatrix& A) { return A.IsZero(); } - -#ifdef TEMPS_DESTROYED_QUICKLY - inline ShiftedMatrix& operator+(Real f, const BaseMatrix& BM) - { return BM + f; } - inline ScaledMatrix& operator*(Real f, const BaseMatrix& BM) - { return BM * f; } -#endif - - // these are moved out of the class definitions because of a problem - // with the Intel 8.1 compiler -#ifndef TEMPS_DESTROYED_QUICKLY - inline ShiftedMatrix operator+(Real f, const BaseMatrix& BM) - { return ShiftedMatrix(&BM, f); } - inline ScaledMatrix operator*(Real f, const BaseMatrix& BM) - { return ScaledMatrix(&BM, f); } -#endif - - - inline MatrixInput MatrixInput::operator<<(int f) { return *this << (Real)f; } - inline MatrixInput GeneralMatrix::operator<<(int f) { return *this << (Real)f; } - inline MatrixInput BandMatrix::operator<<(int f) { return *this << (Real)f; } - inline MatrixInput GetSubMatrix::operator<<(int f) { return *this << (Real)f; } - - - -#ifdef use_namespace -} -#endif - - -#endif - -// body file: newmat1.cpp -// body file: newmat2.cpp -// body file: newmat3.cpp -// body file: newmat4.cpp -// body file: newmat5.cpp -// body file: newmat6.cpp -// body file: newmat7.cpp -// body file: newmat8.cpp -// body file: newmatex.cpp -// body file: bandmat.cpp -// body file: submat.cpp - - - - - - - diff --git a/lib/src/mixmod/NEWMAT/newmat.lfl b/lib/src/mixmod/NEWMAT/newmat.lfl deleted file mode 100644 index dc884f5..0000000 --- a/lib/src/mixmod/NEWMAT/newmat.lfl +++ /dev/null @@ -1,4 +0,0 @@ -newmat.h -newmatap.h -newmatio.h -myexcept.cpp diff --git a/lib/src/mixmod/NEWMAT/newmat1.cpp b/lib/src/mixmod/NEWMAT/newmat1.cpp deleted file mode 100644 index 130a589..0000000 --- a/lib/src/mixmod/NEWMAT/newmat1.cpp +++ /dev/null @@ -1,177 +0,0 @@ -//$$ newmat1.cpp Matrix type functions - -// Copyright (C) 1991,2,3,4: R B Davies - -//#define WANT_STREAM - -#include "newmat.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - -#ifdef DO_REPORT -#define REPORT { static ExeCounter ExeCount(__LINE__,1); ++ExeCount; } -#else -#define REPORT {} -#endif - - - /************************* MatrixType functions *****************************/ - - - // all operations to return MatrixTypes which correspond to valid types - // of matrices. - // Eg: if it has the Diagonal attribute, then it must also have - // Upper, Lower, Band and Symmetric. - - - MatrixType MatrixType::operator*(const MatrixType& mt) const - { - REPORT - int a = attribute & mt.attribute & ~Symmetric; - a |= (a & Diagonal) * 31; // recognise diagonal - return MatrixType(a); - } - - MatrixType MatrixType::SP(const MatrixType& mt) const - // elementwise product - // Lower, Upper, Diag, Band if only one is - // Symmetric, Ones, Valid (and Real) if both are - // Need to include Lower & Upper => Diagonal - // Will need to include both Skew => Symmetric - { - REPORT - int a = ((attribute | mt.attribute) & ~(Symmetric + Valid + Ones)) - | (attribute & mt.attribute); - if ((a & Lower) != 0 && (a & Upper) != 0) a |= Diagonal; - a |= (a & Diagonal) * 31; // recognise diagonal - return MatrixType(a); - } - - MatrixType MatrixType::KP(const MatrixType& mt) const - // Kronecker product - // Lower, Upper, Diag, Symmetric, Band, Valid if both are - // Do not treat Band separately - // Ones is complicated so leave this out - { - REPORT - int a = (attribute & mt.attribute) & ~Ones; - return MatrixType(a); - } - - MatrixType MatrixType::i() const // type of inverse - { - REPORT - int a = attribute & ~(Band+LUDeco); - a |= (a & Diagonal) * 31; // recognise diagonal - return MatrixType(a); - } - - MatrixType MatrixType::t() const - // swap lower and upper attributes - // assume Upper is in bit above Lower - { - REPORT - int a = attribute; - a ^= (((a >> 1) ^ a) & Lower) * 3; - return MatrixType(a); - } - - MatrixType MatrixType::MultRHS() const - { - REPORT - // remove symmetric attribute unless diagonal - return (attribute >= Dg) ? attribute : (attribute & ~Symmetric); - } - - bool Rectangular(MatrixType a, MatrixType b, MatrixType c) - { - REPORT - return - ((a.attribute | b.attribute | c.attribute) & ~MatrixType::Valid) == 0; - } - - const char* MatrixType::Value() const - { - // make a string with the name of matrix with the given attributes - switch (attribute) - { - case Valid: REPORT return "Rect "; - case Valid+Symmetric: REPORT return "Sym "; - case Valid+Band: REPORT return "Band "; - case Valid+Symmetric+Band: REPORT return "SmBnd"; - case Valid+Upper: REPORT return "UT "; - case Valid+Diagonal+Symmetric+Band+Upper+Lower: - REPORT return "Diag "; - case Valid+Diagonal+Symmetric+Band+Upper+Lower+Ones: - REPORT return "Ident"; - case Valid+Band+Upper: REPORT return "UpBnd"; - case Valid+Lower: REPORT return "LT "; - case Valid+Band+Lower: REPORT return "LwBnd"; - default: - REPORT - if (!(attribute & Valid)) return "UnSp "; - if (attribute & LUDeco) - return (attribute & Band) ? "BndLU" : "Crout"; - return "?????"; - } - } - - - GeneralMatrix* MatrixType::New(int nr, int nc, BaseMatrix* bm) const - { - // make a new matrix with the given attributes - - Tracer tr("New"); GeneralMatrix* gm=0; // initialised to keep gnu happy - switch (attribute) - { - case Valid: - REPORT - if (nc==1) { gm = new ColumnVector(nr); break; } - if (nr==1) { gm = new RowVector(nc); break; } - gm = new Matrix(nr, nc); break; - - case Valid+Symmetric: - REPORT gm = new SymmetricMatrix(nr); break; - - case Valid+Band: - { - REPORT - MatrixBandWidth bw = bm->BandWidth(); - gm = new BandMatrix(nr,bw.lower,bw.upper); break; - } - - case Valid+Symmetric+Band: - REPORT gm = new SymmetricBandMatrix(nr,bm->BandWidth().lower); break; - - case Valid+Upper: - REPORT gm = new UpperTriangularMatrix(nr); break; - - case Valid+Diagonal+Symmetric+Band+Upper+Lower: - REPORT gm = new DiagonalMatrix(nr); break; - - case Valid+Band+Upper: - REPORT gm = new UpperBandMatrix(nr,bm->BandWidth().upper); break; - - case Valid+Lower: - REPORT gm = new LowerTriangularMatrix(nr); break; - - case Valid+Band+Lower: - REPORT gm = new LowerBandMatrix(nr,bm->BandWidth().lower); break; - - case Valid+Diagonal+Symmetric+Band+Upper+Lower+Ones: - REPORT gm = new IdentityMatrix(nr); break; - - default: - Throw(ProgramException("Invalid matrix type")); - } - - MatrixErrorNoSpace(gm); gm->Protect(); return gm; - } - - -#ifdef use_namespace -} -#endif - diff --git a/lib/src/mixmod/NEWMAT/newmat2.cpp b/lib/src/mixmod/NEWMAT/newmat2.cpp deleted file mode 100644 index 0ed5f2e..0000000 --- a/lib/src/mixmod/NEWMAT/newmat2.cpp +++ /dev/null @@ -1,633 +0,0 @@ -//$$ newmat2.cpp Matrix row and column operations - -// Copyright (C) 1991,2,3,4: R B Davies - -#define WANT_MATH - -#include "include.h" - -#include "newmat.h" -#include "newmatrc.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - - -#ifdef DO_REPORT -#define REPORT { static ExeCounter ExeCount(__LINE__,2); ++ExeCount; } -#else -#define REPORT {} -#endif - - //#define MONITOR(what,storage,store) { cout << what << " " << storage << " at " << (long)store << "\n"; } - -#define MONITOR(what,store,storage) {} - - /************************** Matrix Row/Col functions ************************/ - - void MatrixRowCol::Add(const MatrixRowCol& mrc) - { - // THIS += mrc - REPORT - int f = mrc.skip; int l = f + mrc.storage; int lx = skip + storage; - if (f < skip) f = skip; if (l > lx) l = lx; l -= f; - if (l<=0) return; - Real* elx=data+(f-skip); Real* el=mrc.data+(f-mrc.skip); - while (l--) *elx++ += *el++; - } - - void MatrixRowCol::AddScaled(const MatrixRowCol& mrc, Real x) - { - REPORT - // THIS += (mrc * x) - int f = mrc.skip; int l = f + mrc.storage; int lx = skip + storage; - if (f < skip) f = skip; if (l > lx) l = lx; l -= f; - if (l<=0) return; - Real* elx=data+(f-skip); Real* el=mrc.data+(f-mrc.skip); - while (l--) *elx++ += *el++ * x; - } - - void MatrixRowCol::Sub(const MatrixRowCol& mrc) - { - REPORT - // THIS -= mrc - int f = mrc.skip; int l = f + mrc.storage; int lx = skip + storage; - if (f < skip) f = skip; if (l > lx) l = lx; l -= f; - if (l<=0) return; - Real* elx=data+(f-skip); Real* el=mrc.data+(f-mrc.skip); - while (l--) *elx++ -= *el++; - } - - void MatrixRowCol::Inject(const MatrixRowCol& mrc) - // copy stored elements only - { - REPORT - int f = mrc.skip; int l = f + mrc.storage; int lx = skip + storage; - if (f < skip) f = skip; if (l > lx) l = lx; l -= f; - if (l<=0) return; - Real* elx=data+(f-skip); Real* ely=mrc.data+(f-mrc.skip); - while (l--) *elx++ = *ely++; - } - - Real DotProd(const MatrixRowCol& mrc1, const MatrixRowCol& mrc2) - { - REPORT // not accessed - int f = mrc1.skip; int f2 = mrc2.skip; - int l = f + mrc1.storage; int l2 = f2 + mrc2.storage; - if (f < f2) f = f2; if (l > l2) l = l2; l -= f; - if (l<=0) return 0.0; - - Real* el1=mrc1.data+(f-mrc1.skip); Real* el2=mrc2.data+(f-mrc2.skip); - Real sum = 0.0; - while (l--) sum += *el1++ * *el2++; - return sum; - } - - void MatrixRowCol::Add(const MatrixRowCol& mrc1, const MatrixRowCol& mrc2) - { - // THIS = mrc1 + mrc2 - int f = skip; int l = skip + storage; - int f1 = mrc1.skip; int l1 = f1 + mrc1.storage; - if (f1l) l1=l; - int f2 = mrc2.skip; int l2 = f2 + mrc2.storage; - if (f2l) l2=l; - Real* el = data + (f-skip); - Real* el1 = mrc1.data+(f1-mrc1.skip); Real* el2 = mrc2.data+(f2-mrc2.skip); - if (f1l) l1=l; - int f2 = mrc2.skip; int l2 = f2 + mrc2.storage; - if (f2l) l2=l; - Real* el = data + (f-skip); - Real* el1 = mrc1.data+(f1-mrc1.skip); Real* el2 = mrc2.data+(f2-mrc2.skip); - if (f1 lx) { l = lx; if (f > lx) f = lx; } - - Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); - - int l1 = f-skip; while (l1--) *elx++ = x; - l1 = l-f; while (l1--) *elx++ = *ely++ + x; - lx -= l; while (lx--) *elx++ = x; - } - - void MatrixRowCol::NegAdd(const MatrixRowCol& mrc1, Real x) - { - // THIS = x - mrc1 - REPORT - if (!storage) return; - int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; - if (f < skip) { f = skip; if (l < f) l = f; } - if (l > lx) { l = lx; if (f > lx) f = lx; } - - Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); - - int l1 = f-skip; while (l1--) *elx++ = x; - l1 = l-f; while (l1--) *elx++ = x - *ely++; - lx -= l; while (lx--) *elx++ = x; - } - - void MatrixRowCol::RevSub(const MatrixRowCol& mrc1) - { - // THIS = mrc - THIS - REPORT - if (!storage) return; - int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; - if (f < skip) { f = skip; if (l < f) l = f; } - if (l > lx) { l = lx; if (f > lx) f = lx; } - - Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); - - int l1 = f-skip; while (l1--) { *elx = - *elx; elx++; } - l1 = l-f; while (l1--) { *elx = *ely++ - *elx; elx++; } - lx -= l; while (lx--) { *elx = - *elx; elx++; } - } - - void MatrixRowCol::ConCat(const MatrixRowCol& mrc1, const MatrixRowCol& mrc2) - { - // THIS = mrc1 | mrc2 - REPORT - int f1 = mrc1.skip; int l1 = f1 + mrc1.storage; int lx = skip + storage; - if (f1 < skip) { f1 = skip; if (l1 < f1) l1 = f1; } - if (l1 > lx) { l1 = lx; if (f1 > lx) f1 = lx; } - - Real* elx = data; - - int i = f1-skip; while (i--) *elx++ =0.0; - i = l1-f1; - if (i) // in case f1 would take ely out of range - { Real* ely = mrc1.data+(f1-mrc1.skip); while (i--) *elx++ = *ely++; } - - int f2 = mrc2.skip; int l2 = f2 + mrc2.storage; i = mrc1.length; - int skipx = l1 - i; lx -= i; // addresses rel to second seg, maybe -ve - if (f2 < skipx) { f2 = skipx; if (l2 < f2) l2 = f2; } - if (l2 > lx) { l2 = lx; if (f2 > lx) f2 = lx; } - - i = f2-skipx; while (i--) *elx++ = 0.0; - i = l2-f2; - if (i) // in case f2 would take ely out of range - { Real* ely = mrc2.data+(f2-mrc2.skip); while (i--) *elx++ = *ely++; } - lx -= l2; while (lx--) *elx++ = 0.0; - } - - void MatrixRowCol::Multiply(const MatrixRowCol& mrc1) - // element by element multiply into - { - REPORT - if (!storage) return; - int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; - if (f < skip) { f = skip; if (l < f) l = f; } - if (l > lx) { l = lx; if (f > lx) f = lx; } - - Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); - - int l1 = f-skip; while (l1--) *elx++ = 0; - l1 = l-f; while (l1--) *elx++ *= *ely++; - lx -= l; while (lx--) *elx++ = 0; - } - - void MatrixRowCol::Multiply(const MatrixRowCol& mrc1, const MatrixRowCol& mrc2) - // element by element multiply - { - int f = skip; int l = skip + storage; - int f1 = mrc1.skip; int l1 = f1 + mrc1.storage; - if (f1l) l1=l; - int f2 = mrc2.skip; int l2 = f2 + mrc2.storage; - if (f2l) l2=l; - Real* el = data + (f-skip); int i; - if (f1l2) l1 = l2; - if (l1<=f1) { REPORT i = l-f; while (i--) *el++ = 0.0; } // disjoint - else - { - REPORT - Real* el1 = mrc1.data+(f1-mrc1.skip); - Real* el2 = mrc2.data+(f1-mrc2.skip); - i = f1-f ; while (i--) *el++ = 0.0; - i = l1-f1; while (i--) *el++ = *el1++ * *el2++; - i = l-l1; while (i--) *el++ = 0.0; - } - } - - void MatrixRowCol::KP(const MatrixRowCol& mrc1, const MatrixRowCol& mrc2) - // row for Kronecker product - { - int f = skip; int s = storage; Real* el = data; int i; - - i = mrc1.skip * mrc2.length; - if (i > f) - { - i -= f; f = 0; if (i > s) { i = s; s = 0; } else s -= i; - while (i--) *el++ = 0.0; - if (s == 0) return; - } - else f -= i; - - i = mrc1.storage; Real* el1 = mrc1.data; - int mrc2_skip = mrc2.skip; int mrc2_storage = mrc2.storage; - int mrc2_length = mrc2.length; - int mrc2_remain = mrc2_length - mrc2_skip - mrc2_storage; - while (i--) - { - int j; Real* el2 = mrc2.data; Real vel1 = *el1; - if (f == 0 && mrc2_length <= s) - { - j = mrc2_skip; s -= j; while (j--) *el++ = 0.0; - j = mrc2_storage; s -= j; while (j--) *el++ = vel1 * *el2++; - j = mrc2_remain; s -= j; while (j--) *el++ = 0.0; - } - else if (f >= mrc2_length) f -= mrc2_length; - else - { - j = mrc2_skip; - if (j > f) - { - j -= f; f = 0; if (j > s) { j = s; s = 0; } else s -= j; - while (j--) *el++ = 0.0; - } - else f -= j; - - j = mrc2_storage; - if (j > f) - { - j -= f; el2 += f; f = 0; if (j > s) { j = s; s = 0; } else s -= j; - while (j--) *el++ = vel1 * *el2++; - } - else f -= j; - - j = mrc2_remain; - if (j > f) - { - j -= f; f = 0; if (j > s) { j = s; s = 0; } else s -= j; - while (j--) *el++ = 0.0; - } - else f -= j; - } - if (s == 0) return; - ++el1; - } - - i = (mrc1.length - mrc1.skip - mrc1.storage) * mrc2.length; - if (i > f) - { - i -= f; if (i > s) i = s; - while (i--) *el++ = 0.0; - } - } - - - void MatrixRowCol::Copy(const MatrixRowCol& mrc1) - { - // THIS = mrc1 - REPORT - if (!storage) return; - int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; - if (f < skip) { f = skip; if (l < f) l = f; } - if (l > lx) { l = lx; if (f > lx) f = lx; } - - Real* elx = data; Real* ely = 0; - - if (l-f) ely = mrc1.data+(f-mrc1.skip); - - int l1 = f-skip; while (l1--) *elx++ = 0.0; - l1 = l-f; while (l1--) *elx++ = *ely++; - lx -= l; while (lx--) *elx++ = 0.0; - } - - void MatrixRowCol::CopyCheck(const MatrixRowCol& mrc1) - // Throw an exception if this would lead to a loss of data - { - REPORT - if (!storage) return; - int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; - if (f < skip || l > lx) Throw(ProgramException("Illegal Conversion")); - - Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); - - int l1 = f-skip; while (l1--) *elx++ = 0.0; - l1 = l-f; while (l1--) *elx++ = *ely++; - lx -= l; while (lx--) *elx++ = 0.0; - } - - void MatrixRowCol::Check(const MatrixRowCol& mrc1) - // Throw an exception if +=, -=, copy etc would lead to a loss of data - { - REPORT - int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; - if (f < skip || l > lx) Throw(ProgramException("Illegal Conversion")); - } - - void MatrixRowCol::Check() - // Throw an exception if +=, -= of constant would lead to a loss of data - // that is: check full row is present - // may not be appropriate for symmetric matrices - { - REPORT - if (skip!=0 || storage!=length) - Throw(ProgramException("Illegal Conversion")); - } - - void MatrixRowCol::Negate(const MatrixRowCol& mrc1) - { - // THIS = -mrc1 - REPORT - if (!storage) return; - int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; - if (f < skip) { f = skip; if (l < f) l = f; } - if (l > lx) { l = lx; if (f > lx) f = lx; } - - Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); - - int l1 = f-skip; while (l1--) *elx++ = 0.0; - l1 = l-f; while (l1--) *elx++ = - *ely++; - lx -= l; while (lx--) *elx++ = 0.0; - } - - void MatrixRowCol::Multiply(const MatrixRowCol& mrc1, Real s) - { - // THIS = mrc1 * s - REPORT - if (!storage) return; - int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; - if (f < skip) { f = skip; if (l < f) l = f; } - if (l > lx) { l = lx; if (f > lx) f = lx; } - - Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); - - int l1 = f-skip; while (l1--) *elx++ = 0.0; - l1 = l-f; while (l1--) *elx++ = *ely++ * s; - lx -= l; while (lx--) *elx++ = 0.0; - } - - void DiagonalMatrix::Solver(MatrixColX& mrc, const MatrixColX& mrc1) - { - // mrc = mrc / mrc1 (elementwise) - REPORT - int f = mrc1.skip; int f0 = mrc.skip; - int l = f + mrc1.storage; int lx = f0 + mrc.storage; - if (f < f0) { f = f0; if (l < f) l = f; } - if (l > lx) { l = lx; if (f > lx) f = lx; } - - Real* elx = mrc.data; Real* eld = store+f; - - int l1 = f-f0; while (l1--) *elx++ = 0.0; - l1 = l-f; while (l1--) *elx++ /= *eld++; - lx -= l; while (lx--) *elx++ = 0.0; - // Solver makes sure input and output point to same memory - } - - void IdentityMatrix::Solver(MatrixColX& mrc, const MatrixColX& mrc1) - { - // mrc = mrc / mrc1 (elementwise) - REPORT - int f = mrc1.skip; int f0 = mrc.skip; - int l = f + mrc1.storage; int lx = f0 + mrc.storage; - if (f < f0) { f = f0; if (l < f) l = f; } - if (l > lx) { l = lx; if (f > lx) f = lx; } - - Real* elx = mrc.data; Real eldv = *store; - - int l1 = f-f0; while (l1--) *elx++ = 0.0; - l1 = l-f; while (l1--) *elx++ /= eldv; - lx -= l; while (lx--) *elx++ = 0.0; - // Solver makes sure input and output point to same memory - } - - void MatrixRowCol::Copy(const Real*& r) - { - // THIS = *r - REPORT - Real* elx = data; const Real* ely = r+skip; r += length; - int l = storage; while (l--) *elx++ = *ely++; - } - - void MatrixRowCol::Copy(Real r) - { - // THIS = r - REPORT Real* elx = data; int l = storage; while (l--) *elx++ = r; - } - - void MatrixRowCol::Zero() - { - // THIS = 0 - REPORT Real* elx = data; int l = storage; while (l--) *elx++ = 0; - } - - void MatrixRowCol::Multiply(Real r) - { - // THIS *= r - REPORT Real* elx = data; int l = storage; while (l--) *elx++ *= r; - } - - void MatrixRowCol::Add(Real r) - { - // THIS += r - REPORT - Real* elx = data; int l = storage; while (l--) *elx++ += r; - } - - Real MatrixRowCol::SumAbsoluteValue() - { - REPORT - Real sum = 0.0; Real* elx = data; int l = storage; - while (l--) sum += fabs(*elx++); - return sum; - } - - // max absolute value of r and elements of row/col - // we use <= or >= in all of these so we are sure of getting - // r reset at least once. - Real MatrixRowCol::MaximumAbsoluteValue1(Real r, int& i) - { - REPORT - Real* elx = data; int l = storage; int li = -1; - while (l--) { Real f = fabs(*elx++); if (r <= f) { r = f; li = l; } } - i = (li >= 0) ? storage - li + skip : 0; - return r; - } - - // min absolute value of r and elements of row/col - Real MatrixRowCol::MinimumAbsoluteValue1(Real r, int& i) - { - REPORT - Real* elx = data; int l = storage; int li = -1; - while (l--) { Real f = fabs(*elx++); if (r >= f) { r = f; li = l; } } - i = (li >= 0) ? storage - li + skip : 0; - return r; - } - - // max value of r and elements of row/col - Real MatrixRowCol::Maximum1(Real r, int& i) - { - REPORT - Real* elx = data; int l = storage; int li = -1; - while (l--) { Real f = *elx++; if (r <= f) { r = f; li = l; } } - i = (li >= 0) ? storage - li + skip : 0; - return r; - } - - // min value of r and elements of row/col - Real MatrixRowCol::Minimum1(Real r, int& i) - { - REPORT - Real* elx = data; int l = storage; int li = -1; - while (l--) { Real f = *elx++; if (r >= f) { r = f; li = l; } } - i = (li >= 0) ? storage - li + skip : 0; - return r; - } - - Real MatrixRowCol::Sum() - { - REPORT - Real sum = 0.0; Real* elx = data; int l = storage; - while (l--) sum += *elx++; - return sum; - } - - void MatrixRowCol::SubRowCol(MatrixRowCol& mrc, int skip1, int l1) const - { - mrc.length = l1; int d = skip - skip1; - if (d<0) { mrc.skip = 0; mrc.data = data - d; } - else { mrc.skip = d; mrc.data = data; } - d = skip + storage - skip1; - d = ((l1 < d) ? l1 : d) - mrc.skip; mrc.storage = (d < 0) ? 0 : d; - mrc.cw = 0; - } - -#ifdef use_namespace -} -#endif - diff --git a/lib/src/mixmod/NEWMAT/newmat3.cpp b/lib/src/mixmod/NEWMAT/newmat3.cpp deleted file mode 100644 index d8f2bd1..0000000 --- a/lib/src/mixmod/NEWMAT/newmat3.cpp +++ /dev/null @@ -1,842 +0,0 @@ -//$$ newmat3.cpp Matrix get and restore rows and columns - -// Copyright (C) 1991,2,3,4: R B Davies - -//#define WANT_STREAM - -#include "include.h" - -#include "newmat.h" -#include "newmatrc.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - - -#ifdef DO_REPORT -#define REPORT { static ExeCounter ExeCount(__LINE__,3); ++ExeCount; } -#else -#define REPORT {} -#endif - - //#define MONITOR(what,storage,store) - // { cout << what << " " << storage << " at " << (long)store << "\n"; } - -#define MONITOR(what,store,storage) {} - - - // Control bits codes for GetRow, GetCol, RestoreRow, RestoreCol - // - // LoadOnEntry: - // Load data into MatrixRow or Col dummy array under GetRow or GetCol - // StoreOnExit: - // Restore data to original matrix under RestoreRow or RestoreCol - // DirectPart: - // Load or restore only part directly stored; must be set with StoreOnExit - // Still have decide how to handle this with symmetric - // StoreHere: - // used in columns only - store data at supplied storage address; - // used for GetCol, NextCol & RestoreCol. No need to fill out zeros - // HaveStore: - // dummy array has been assigned (internal use only). - - // For symmetric matrices, treat columns as rows unless StoreHere is set; - // then stick to columns as this will give better performance for doing - // inverses - - // How components are used: - - // Use rows wherever possible in preference to columns - - // Columns without StoreHere are used in in-exact transpose, sum column, - // multiply a column vector, and maybe in future access to column, - // additional multiply functions, add transpose - - // Columns with StoreHere are used in exact transpose (not symmetric matrices - // or vectors, load only) - - // Columns with MatrixColX (Store to full column) are used in inverse and solve - - // Functions required for each matrix class - - // GetRow(MatrixRowCol& mrc) - // GetCol(MatrixRowCol& mrc) - // GetCol(MatrixColX& mrc) - // RestoreRow(MatrixRowCol& mrc) - // RestoreCol(MatrixRowCol& mrc) - // RestoreCol(MatrixColX& mrc) - // NextRow(MatrixRowCol& mrc) - // NextCol(MatrixRowCol& mrc) - // NextCol(MatrixColX& mrc) - - // The Restore routines assume StoreOnExit has already been checked - // Defaults for the Next routines are given below - // Assume cannot have both !DirectPart && StoreHere for MatrixRowCol routines - - - // Default NextRow and NextCol: - // will work as a default but need to override NextRow for efficiency - - void GeneralMatrix::NextRow(MatrixRowCol& mrc) - { - REPORT - if (+(mrc.cw*StoreOnExit)) { REPORT this->RestoreRow(mrc); } - mrc.rowcol++; - if (mrc.rowcolGetRow(mrc); } - else { REPORT mrc.cw -= StoreOnExit; } - } - - void GeneralMatrix::NextCol(MatrixRowCol& mrc) - { - REPORT // 423 - if (+(mrc.cw*StoreOnExit)) { REPORT this->RestoreCol(mrc); } - mrc.rowcol++; - if (mrc.rowcolGetCol(mrc); } - else { REPORT mrc.cw -= StoreOnExit; } - } - - void GeneralMatrix::NextCol(MatrixColX& mrc) - { - REPORT // 423 - if (+(mrc.cw*StoreOnExit)) { REPORT this->RestoreCol(mrc); } - mrc.rowcol++; - if (mrc.rowcolGetCol(mrc); } - else { REPORT mrc.cw -= StoreOnExit; } - } - - - // routines for matrix - - void Matrix::GetRow(MatrixRowCol& mrc) - { - REPORT - mrc.skip=0; mrc.storage=mrc.length=ncols; mrc.data=store+mrc.rowcol*ncols; - } - - - void Matrix::GetCol(MatrixRowCol& mrc) - { - REPORT - mrc.skip=0; mrc.storage=mrc.length=nrows; - if ( ncols==1 && !(mrc.cw*StoreHere) ) // ColumnVector - { REPORT mrc.data=store; } - else - { - Real* ColCopy; - if ( !(mrc.cw*(HaveStore+StoreHere)) ) - { - REPORT - ColCopy = new Real [nrows]; MatrixErrorNoSpace(ColCopy); - MONITOR_REAL_NEW("Make (MatGetCol)",nrows,ColCopy) - mrc.data = ColCopy; mrc.cw += HaveStore; - } - else { REPORT ColCopy = mrc.data; } - if (+(mrc.cw*LoadOnEntry)) - { - REPORT - Real* Mstore = store+mrc.rowcol; int i=nrows; - //while (i--) { *ColCopy++ = *Mstore; Mstore+=ncols; } - if (i) for (;;) - { *ColCopy++ = *Mstore; if (!(--i)) break; Mstore+=ncols; } - } - } - } - - void Matrix::GetCol(MatrixColX& mrc) - { - REPORT - mrc.skip=0; mrc.storage=nrows; mrc.length=nrows; - if (+(mrc.cw*LoadOnEntry)) - { - REPORT Real* ColCopy = mrc.data; - Real* Mstore = store+mrc.rowcol; int i=nrows; - //while (i--) { *ColCopy++ = *Mstore; Mstore+=ncols; } - if (i) for (;;) - { *ColCopy++ = *Mstore; if (!(--i)) break; Mstore+=ncols; } - } - } - - void Matrix::RestoreCol(MatrixRowCol& mrc) - { - // always check StoreOnExit before calling RestoreCol - REPORT // 429 - if (+(mrc.cw*HaveStore)) - { - REPORT // 426 - Real* Mstore = store+mrc.rowcol; int i=nrows; - Real* Cstore = mrc.data; - // while (i--) { *Mstore = *Cstore++; Mstore+=ncols; } - if (i) for (;;) - { *Mstore = *Cstore++; if (!(--i)) break; Mstore+=ncols; } - } - } - - void Matrix::RestoreCol(MatrixColX& mrc) - { - REPORT - Real* Mstore = store+mrc.rowcol; int i=nrows; Real* Cstore = mrc.data; - // while (i--) { *Mstore = *Cstore++; Mstore+=ncols; } - if (i) for (;;) - { *Mstore = *Cstore++; if (!(--i)) break; Mstore+=ncols; } - } - - void Matrix::NextRow(MatrixRowCol& mrc) { REPORT mrc.IncrMat(); } // 1808 - - void Matrix::NextCol(MatrixRowCol& mrc) - { - REPORT // 632 - if (+(mrc.cw*StoreOnExit)) { REPORT RestoreCol(mrc); } - mrc.rowcol++; - if (mrc.rowcol= LoadOnEntry) - { REPORT *(mrc.data) = *(store+mrc.rowcol); } - - } - - void RowVector::NextCol(MatrixRowCol& mrc) - { REPORT mrc.rowcol++; mrc.data++; } - - void RowVector::NextCol(MatrixColX& mrc) - { - if (+(mrc.cw*StoreOnExit)) { REPORT *(store+mrc.rowcol)=*(mrc.data); } - - mrc.rowcol++; - if (mrc.rowcol < ncols) - { - if (+(mrc.cw*LoadOnEntry)) { REPORT *(mrc.data)=*(store+mrc.rowcol); } - } - else { REPORT mrc.cw -= StoreOnExit; } - } - - void RowVector::RestoreCol(MatrixColX& mrc) - { REPORT *(store+mrc.rowcol)=*(mrc.data); } // not accessed - - - // routines for band matrices - - void BandMatrix::GetRow(MatrixRowCol& mrc) - { - REPORT - int r = mrc.rowcol; int w = lower+1+upper; mrc.length=ncols; - int s = r-lower; - if (s<0) { mrc.data = store+(r*w-s); w += s; s = 0; } - else mrc.data = store+r*w; - mrc.skip = s; s += w-ncols; if (s>0) w -= s; mrc.storage = w; - } - - // should make special versions of this for upper and lower band matrices - - void BandMatrix::NextRow(MatrixRowCol& mrc) - { - REPORT - int r = ++mrc.rowcol; - if (r<=lower) { mrc.storage++; mrc.data += lower+upper; } - else { mrc.skip++; mrc.data += lower+upper+1; } - if (r>=ncols-upper) mrc.storage--; - } - - void BandMatrix::GetCol(MatrixRowCol& mrc) - { - REPORT - int c = mrc.rowcol; int n = lower+upper; int w = n+1; - mrc.length=nrows; Real* ColCopy; - int b; int s = c-upper; - if (s<=0) { w += s; s = 0; b = c+lower; } else b = s*w+n; - mrc.skip = s; s += w-nrows; if (s>0) w -= s; mrc.storage = w; - if ( +(mrc.cw*(StoreHere+HaveStore)) ) - { REPORT ColCopy = mrc.data; } - else - { - REPORT - ColCopy = new Real [n+1]; MatrixErrorNoSpace(ColCopy); - MONITOR_REAL_NEW("Make (BMGetCol)",n+1,ColCopy) - mrc.cw += HaveStore; mrc.data = ColCopy; - } - - if (+(mrc.cw*LoadOnEntry)) - { - REPORT - Real* Mstore = store+b; - // while (w--) { *ColCopy++ = *Mstore; Mstore+=n; } - if (w) for (;;) - { *ColCopy++ = *Mstore; if (!(--w)) break; Mstore+=n; } - } - } - - void BandMatrix::GetCol(MatrixColX& mrc) - { - REPORT - int c = mrc.rowcol; int n = lower+upper; int w = n+1; - mrc.length=nrows; int b; int s = c-upper; - if (s<=0) { w += s; s = 0; b = c+lower; } else b = s*w+n; - mrc.skip = s; s += w-nrows; if (s>0) w -= s; mrc.storage = w; - mrc.data = mrc.store+mrc.skip; - - if (+(mrc.cw*LoadOnEntry)) - { - REPORT - Real* ColCopy = mrc.data; Real* Mstore = store+b; - // while (w--) { *ColCopy++ = *Mstore; Mstore+=n; } - if (w) for (;;) - { *ColCopy++ = *Mstore; if (!(--w)) break; Mstore+=n; } - } - } - - void BandMatrix::RestoreCol(MatrixRowCol& mrc) - { - REPORT - int c = mrc.rowcol; int n = lower+upper; int s = c-upper; - Real* Mstore = store + ((s<=0) ? c+lower : s*n+s+n); - Real* Cstore = mrc.data; - int w = mrc.storage; - // while (w--) { *Mstore = *Cstore++; Mstore += n; } - if (w) for (;;) - { *Mstore = *Cstore++; if (!(--w)) break; Mstore += n; } - } - - // routines for symmetric band matrix - - void SymmetricBandMatrix::GetRow(MatrixRowCol& mrc) - { - REPORT - int r=mrc.rowcol; int s = r-lower; int w1 = lower+1; int o = r*w1; - mrc.length = ncols; - if (s<0) { w1 += s; o -= s; s = 0; } - mrc.skip = s; - - if (+(mrc.cw*DirectPart)) - { REPORT mrc.data = store+o; mrc.storage = w1; } - else - { - // do not allow StoreOnExit and !DirectPart - if (+(mrc.cw*StoreOnExit)) - Throw(InternalException("SymmetricBandMatrix::GetRow(MatrixRowCol&)")); - int w = w1+lower; s += w-ncols; Real* RowCopy; - if (s>0) w -= s; mrc.storage = w; int w2 = w-w1; - if (!(mrc.cw*HaveStore)) - { - REPORT - RowCopy = new Real [2*lower+1]; MatrixErrorNoSpace(RowCopy); - MONITOR_REAL_NEW("Make (SmBGetRow)",2*lower+1,RowCopy) - mrc.cw += HaveStore; mrc.data = RowCopy; - } - else { REPORT RowCopy = mrc.data; } - - if (+(mrc.cw*LoadOnEntry)) - { - REPORT - Real* Mstore = store+o; - while (w1--) *RowCopy++ = *Mstore++; - Mstore--; - while (w2--) { Mstore += lower; *RowCopy++ = *Mstore; } - } - } - } - - void SymmetricBandMatrix::GetCol(MatrixRowCol& mrc) - { - // do not allow StoreHere - if (+(mrc.cw*StoreHere)) - Throw(InternalException("SymmetricBandMatrix::GetCol(MatrixRowCol&)")); - - int c=mrc.rowcol; int w1 = lower+1; mrc.length=nrows; - REPORT - int s = c-lower; int o = c*w1; - if (s<0) { w1 += s; o -= s; s = 0; } - mrc.skip = s; - - if (+(mrc.cw*DirectPart)) - { REPORT mrc.data = store+o; mrc.storage = w1; } - else - { - // do not allow StoreOnExit and !DirectPart - if (+(mrc.cw*StoreOnExit)) - Throw(InternalException("SymmetricBandMatrix::GetCol(MatrixRowCol&)")); - int w = w1+lower; s += w-ncols; Real* ColCopy; - if (s>0) w -= s; mrc.storage = w; int w2 = w-w1; - - if ( +(mrc.cw*HaveStore) ) { REPORT ColCopy = mrc.data; } - else - { - REPORT ColCopy = new Real [2*lower+1]; MatrixErrorNoSpace(ColCopy); - MONITOR_REAL_NEW("Make (SmBGetCol)",2*lower+1,ColCopy) - mrc.cw += HaveStore; mrc.data = ColCopy; - } - - if (+(mrc.cw*LoadOnEntry)) - { - REPORT - Real* Mstore = store+o; - while (w1--) *ColCopy++ = *Mstore++; - Mstore--; - while (w2--) { Mstore += lower; *ColCopy++ = *Mstore; } - } - } - } - - void SymmetricBandMatrix::GetCol(MatrixColX& mrc) - { - int c=mrc.rowcol; int w1 = lower+1; mrc.length=nrows; - if (+(mrc.cw*DirectPart)) - { - REPORT - int b = c*w1+lower; - mrc.skip = c; c += w1-nrows; w1 -= c; mrc.storage = w1; - Real* ColCopy = mrc.data = mrc.store+mrc.skip; - if (+(mrc.cw*LoadOnEntry)) - { - REPORT - Real* Mstore = store+b; - // while (w1--) { *ColCopy++ = *Mstore; Mstore += lower; } - if (w1) for (;;) - { *ColCopy++ = *Mstore; if (!(--w1)) break; Mstore += lower; } - } - } - else - { - REPORT - // do not allow StoreOnExit and !DirectPart - if (+(mrc.cw*StoreOnExit)) - Throw(InternalException("SymmetricBandMatrix::GetCol(MatrixColX&)")); - int s = c-lower; int o = c*w1; - if (s<0) { w1 += s; o -= s; s = 0; } - mrc.skip = s; - - int w = w1+lower; s += w-ncols; - if (s>0) w -= s; mrc.storage = w; int w2 = w-w1; - - Real* ColCopy = mrc.data = mrc.store+mrc.skip; - - if (+(mrc.cw*LoadOnEntry)) - { - REPORT - Real* Mstore = store+o; - while (w1--) *ColCopy++ = *Mstore++; - Mstore--; - while (w2--) { Mstore += lower; *ColCopy++ = *Mstore; } - } - - } - } - - void SymmetricBandMatrix::RestoreCol(MatrixColX& mrc) - { - REPORT - int c = mrc.rowcol; - Real* Mstore = store + c*lower+c+lower; - Real* Cstore = mrc.data; int w = mrc.storage; - // while (w--) { *Mstore = *Cstore++; Mstore += lower; } - if (w) for (;;) - { *Mstore = *Cstore++; if (!(--w)) break; Mstore += lower; } - } - - // routines for identity matrix - - void IdentityMatrix::GetRow(MatrixRowCol& mrc) - { - REPORT - mrc.skip=mrc.rowcol; mrc.storage=1; mrc.data=store; mrc.length=ncols; - } - - void IdentityMatrix::GetCol(MatrixRowCol& mrc) - { - REPORT - mrc.skip=mrc.rowcol; mrc.storage=1; mrc.length=nrows; - if (+(mrc.cw*StoreHere)) // should not happen - Throw(InternalException("IdentityMatrix::GetCol(MatrixRowCol&)")); - else { REPORT mrc.data=store; } - } - - void IdentityMatrix::GetCol(MatrixColX& mrc) - { - REPORT - mrc.skip=mrc.rowcol; mrc.storage=1; mrc.length=nrows; - mrc.data = mrc.store+mrc.skip; *(mrc.data)=*store; - } - - void IdentityMatrix::NextRow(MatrixRowCol& mrc) { REPORT mrc.IncrId(); } - - void IdentityMatrix::NextCol(MatrixRowCol& mrc) { REPORT mrc.IncrId(); } - - void IdentityMatrix::NextCol(MatrixColX& mrc) - { - REPORT - if (+(mrc.cw*StoreOnExit)) { REPORT *store=*(mrc.data); } - mrc.IncrDiag(); // must increase mrc.data so need IncrDiag - int t1 = +(mrc.cw*LoadOnEntry); - if (t1 && mrc.rowcol < ncols) { REPORT *(mrc.data)=*store; } - } - - - - - // *************************** destructors ******************************* - - MatrixRowCol::~MatrixRowCol() - { - if (+(cw*HaveStore)) - { - MONITOR_REAL_DELETE("Free (RowCol)",-1,data) // do not know length - delete [] data; - } - } - - MatrixRow::~MatrixRow() { if (+(cw*StoreOnExit)) gm->RestoreRow(*this); } - - MatrixCol::~MatrixCol() { if (+(cw*StoreOnExit)) gm->RestoreCol(*this); } - - MatrixColX::~MatrixColX() { if (+(cw*StoreOnExit)) gm->RestoreCol(*this); } - -#ifdef use_namespace -} -#endif - diff --git a/lib/src/mixmod/NEWMAT/newmat4.cpp b/lib/src/mixmod/NEWMAT/newmat4.cpp deleted file mode 100644 index 95a3a06..0000000 --- a/lib/src/mixmod/NEWMAT/newmat4.cpp +++ /dev/null @@ -1,950 +0,0 @@ -//$$ newmat4.cpp Constructors, ReSize, basic utilities - -// Copyright (C) 1991,2,3,4,8,9: R B Davies - -#include "include.h" - -#include "newmat.h" -#include "newmatrc.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - - - -#ifdef DO_REPORT -#define REPORT { static ExeCounter ExeCount(__LINE__,4); ++ExeCount; } -#else -#define REPORT {} -#endif - - -#define DO_SEARCH // search for LHS of = in RHS - - // ************************* general utilities *************************/ - - static int tristore(int n) // elements in triangular matrix - { return (n*(n+1))/2; } - - - // **************************** constructors ***************************/ - - GeneralMatrix::GeneralMatrix() - { store=0; storage=0; nrows=0; ncols=0; tag=-1; } - - GeneralMatrix::GeneralMatrix(ArrayLengthSpecifier s) - { - REPORT - storage=s.Value(); tag=-1; - if (storage) - { - store = new Real [storage]; MatrixErrorNoSpace(store); - MONITOR_REAL_NEW("Make (GenMatrix)",storage,store) - } - else store = 0; - } - - Matrix::Matrix(int m, int n) : GeneralMatrix(m*n) - { REPORT nrows=m; ncols=n; } - - SymmetricMatrix::SymmetricMatrix(ArrayLengthSpecifier n) - : GeneralMatrix(tristore(n.Value())) - { REPORT nrows=n.Value(); ncols=n.Value(); } - - UpperTriangularMatrix::UpperTriangularMatrix(ArrayLengthSpecifier n) - : GeneralMatrix(tristore(n.Value())) - { REPORT nrows=n.Value(); ncols=n.Value(); } - - LowerTriangularMatrix::LowerTriangularMatrix(ArrayLengthSpecifier n) - : GeneralMatrix(tristore(n.Value())) - { REPORT nrows=n.Value(); ncols=n.Value(); } - - DiagonalMatrix::DiagonalMatrix(ArrayLengthSpecifier m) : GeneralMatrix(m) - { REPORT nrows=m.Value(); ncols=m.Value(); } - - Matrix::Matrix(const BaseMatrix& M) - { - REPORT // CheckConversion(M); - // MatrixConversionCheck mcc; - GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::Rt); - GetMatrix(gmx); - } - - RowVector::RowVector(const BaseMatrix& M) : Matrix(M) - { - if (nrows!=1) - { - Tracer tr("RowVector"); - Throw(VectorException(*this)); - } - } - - ColumnVector::ColumnVector(const BaseMatrix& M) : Matrix(M) - { - if (ncols!=1) - { - Tracer tr("ColumnVector"); - Throw(VectorException(*this)); - } - } - - SymmetricMatrix::SymmetricMatrix(const BaseMatrix& M) - { - REPORT // CheckConversion(M); - // MatrixConversionCheck mcc; - GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::Sm); - GetMatrix(gmx); - } - - UpperTriangularMatrix::UpperTriangularMatrix(const BaseMatrix& M) - { - REPORT // CheckConversion(M); - // MatrixConversionCheck mcc; - GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::UT); - GetMatrix(gmx); - } - - LowerTriangularMatrix::LowerTriangularMatrix(const BaseMatrix& M) - { - REPORT // CheckConversion(M); - // MatrixConversionCheck mcc; - GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::LT); - GetMatrix(gmx); - } - - DiagonalMatrix::DiagonalMatrix(const BaseMatrix& M) - { - REPORT //CheckConversion(M); - // MatrixConversionCheck mcc; - GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::Dg); - GetMatrix(gmx); - } - - IdentityMatrix::IdentityMatrix(const BaseMatrix& M) - { - REPORT //CheckConversion(M); - // MatrixConversionCheck mcc; - GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::Id); - GetMatrix(gmx); - } - - GeneralMatrix::~GeneralMatrix() - { - if (store) - { - MONITOR_REAL_DELETE("Free (GenMatrix)",storage,store) - delete [] store; - } - } - - CroutMatrix::CroutMatrix(const BaseMatrix& m) - { - REPORT - Tracer tr("CroutMatrix"); - indx = 0; // in case of exception at next line - GeneralMatrix* gm = ((BaseMatrix&)m).Evaluate(MatrixType::Rt); - GetMatrix(gm); - if (nrows!=ncols) { CleanUp(); Throw(NotSquareException(*gm)); } - d=true; sing=false; - indx=new int [nrows]; MatrixErrorNoSpace(indx); - MONITOR_INT_NEW("Index (CroutMat)",nrows,indx) - ludcmp(); - } - - CroutMatrix::~CroutMatrix() - { - MONITOR_INT_DELETE("Index (CroutMat)",nrows,indx) - delete [] indx; - } - - //ReturnMatrixX::ReturnMatrixX(GeneralMatrix& gmx) - //{ - // REPORT - // gm = gmx.Image(); gm->ReleaseAndDelete(); - //} - -#ifndef TEMPS_DESTROYED_QUICKLY_R - - GeneralMatrix::operator ReturnMatrixX() const - { - REPORT - GeneralMatrix* gm = Image(); gm->ReleaseAndDelete(); - return ReturnMatrixX(gm); - } - -#else - - GeneralMatrix::operator ReturnMatrixX&() const - { - REPORT - GeneralMatrix* gm = Image(); gm->ReleaseAndDelete(); - ReturnMatrixX* x = new ReturnMatrixX(gm); - MatrixErrorNoSpace(x); return *x; - } - -#endif - -#ifndef TEMPS_DESTROYED_QUICKLY_R - - ReturnMatrixX GeneralMatrix::ForReturn() const - { - REPORT - GeneralMatrix* gm = Image(); gm->ReleaseAndDelete(); - return ReturnMatrixX(gm); - } - -#else - - ReturnMatrixX& GeneralMatrix::ForReturn() const - { - REPORT - GeneralMatrix* gm = Image(); gm->ReleaseAndDelete(); - ReturnMatrixX* x = new ReturnMatrixX(gm); - MatrixErrorNoSpace(x); return *x; - } - -#endif - - // ************************** ReSize matrices ***************************/ - - void GeneralMatrix::ReSize(int nr, int nc, int s) - { - REPORT - if (store) - { - MONITOR_REAL_DELETE("Free (ReDimensi)",storage,store) - delete [] store; - } - storage=s; nrows=nr; ncols=nc; tag=-1; - if (s) - { - store = new Real [storage]; MatrixErrorNoSpace(store); - MONITOR_REAL_NEW("Make (ReDimensi)",storage,store) - } - else store = 0; - } - - void Matrix::ReSize(int nr, int nc) - { REPORT GeneralMatrix::ReSize(nr,nc,nr*nc); } - - void SymmetricMatrix::ReSize(int nr) - { REPORT GeneralMatrix::ReSize(nr,nr,tristore(nr)); } - - void UpperTriangularMatrix::ReSize(int nr) - { REPORT GeneralMatrix::ReSize(nr,nr,tristore(nr)); } - - void LowerTriangularMatrix::ReSize(int nr) - { REPORT GeneralMatrix::ReSize(nr,nr,tristore(nr)); } - - void DiagonalMatrix::ReSize(int nr) - { REPORT GeneralMatrix::ReSize(nr,nr,nr); } - - void RowVector::ReSize(int nc) - { REPORT GeneralMatrix::ReSize(1,nc,nc); } - - void ColumnVector::ReSize(int nr) - { REPORT GeneralMatrix::ReSize(nr,1,nr); } - - void RowVector::ReSize(int nr, int nc) - { - Tracer tr("RowVector::ReSize"); - if (nr != 1) Throw(VectorException(*this)); - REPORT GeneralMatrix::ReSize(1,nc,nc); - } - - void ColumnVector::ReSize(int nr, int nc) - { - Tracer tr("ColumnVector::ReSize"); - if (nc != 1) Throw(VectorException(*this)); - REPORT GeneralMatrix::ReSize(nr,1,nr); - } - - void IdentityMatrix::ReSize(int nr) - { REPORT GeneralMatrix::ReSize(nr,nr,1); *store = 1; } - - - void Matrix::ReSize(const GeneralMatrix& A) - { REPORT ReSize(A.Nrows(), A.Ncols()); } - - void nricMatrix::ReSize(const GeneralMatrix& A) - { REPORT ReSize(A.Nrows(), A.Ncols()); } - - void ColumnVector::ReSize(const GeneralMatrix& A) - { REPORT ReSize(A.Nrows(), A.Ncols()); } - - void RowVector::ReSize(const GeneralMatrix& A) - { REPORT ReSize(A.Nrows(), A.Ncols()); } - - void SymmetricMatrix::ReSize(const GeneralMatrix& A) - { - REPORT - int n = A.Nrows(); - if (n != A.Ncols()) - { - Tracer tr("SymmetricMatrix::ReSize(GM)"); - Throw(NotSquareException(*this)); - } - ReSize(n); - } - - void DiagonalMatrix::ReSize(const GeneralMatrix& A) - { - REPORT - int n = A.Nrows(); - if (n != A.Ncols()) - { - Tracer tr("DiagonalMatrix::ReSize(GM)"); - Throw(NotSquareException(*this)); - } - ReSize(n); - } - - void UpperTriangularMatrix::ReSize(const GeneralMatrix& A) - { - REPORT - int n = A.Nrows(); - if (n != A.Ncols()) - { - Tracer tr("UpperTriangularMatrix::ReSize(GM)"); - Throw(NotSquareException(*this)); - } - ReSize(n); - } - - void LowerTriangularMatrix::ReSize(const GeneralMatrix& A) - { - REPORT - int n = A.Nrows(); - if (n != A.Ncols()) - { - Tracer tr("LowerTriangularMatrix::ReSize(GM)"); - Throw(NotSquareException(*this)); - } - ReSize(n); - } - - void IdentityMatrix::ReSize(const GeneralMatrix& A) - { - REPORT - int n = A.Nrows(); - if (n != A.Ncols()) - { - Tracer tr("IdentityMatrix::ReSize(GM)"); - Throw(NotSquareException(*this)); - } - ReSize(n); - } - - void GeneralMatrix::ReSize(const GeneralMatrix&) - { - REPORT - Tracer tr("GeneralMatrix::ReSize(GM)"); - Throw(NotDefinedException("ReSize", "this type of matrix")); - } - - void GeneralMatrix::ReSizeForAdd(const GeneralMatrix& A, const GeneralMatrix&) - { REPORT ReSize(A); } - - void GeneralMatrix::ReSizeForSP(const GeneralMatrix& A, const GeneralMatrix&) - { REPORT ReSize(A); } - - - // ************************* SameStorageType ******************************/ - - // SameStorageType checks A and B have same storage type including bandwidth - // It does not check same dimensions since we assume this is already done - - bool GeneralMatrix::SameStorageType(const GeneralMatrix& A) const - { - REPORT - return Type() == A.Type(); - } - - - // ******************* manipulate types, storage **************************/ - - int GeneralMatrix::search(const BaseMatrix* s) const - { REPORT return (s==this) ? 1 : 0; } - - int GenericMatrix::search(const BaseMatrix* s) const - { REPORT return gm->search(s); } - - int MultipliedMatrix::search(const BaseMatrix* s) const - { REPORT return bm1->search(s) + bm2->search(s); } - - int ShiftedMatrix::search(const BaseMatrix* s) const - { REPORT return bm->search(s); } - - int NegatedMatrix::search(const BaseMatrix* s) const - { REPORT return bm->search(s); } - - int ReturnMatrixX::search(const BaseMatrix* s) const - { REPORT return (s==gm) ? 1 : 0; } - - MatrixType Matrix::Type() const { return MatrixType::Rt; } - MatrixType SymmetricMatrix::Type() const { return MatrixType::Sm; } - MatrixType UpperTriangularMatrix::Type() const { return MatrixType::UT; } - MatrixType LowerTriangularMatrix::Type() const { return MatrixType::LT; } - MatrixType DiagonalMatrix::Type() const { return MatrixType::Dg; } - MatrixType RowVector::Type() const { return MatrixType::RV; } - MatrixType ColumnVector::Type() const { return MatrixType::CV; } - MatrixType CroutMatrix::Type() const { return MatrixType::Ct; } - MatrixType BandMatrix::Type() const { return MatrixType::BM; } - MatrixType UpperBandMatrix::Type() const { return MatrixType::UB; } - MatrixType LowerBandMatrix::Type() const { return MatrixType::LB; } - MatrixType SymmetricBandMatrix::Type() const { return MatrixType::SB; } - - MatrixType IdentityMatrix::Type() const { return MatrixType::Id; } - - - - MatrixBandWidth BaseMatrix::BandWidth() const { REPORT return -1; } - MatrixBandWidth DiagonalMatrix::BandWidth() const { REPORT return 0; } - MatrixBandWidth IdentityMatrix::BandWidth() const { REPORT return 0; } - - MatrixBandWidth UpperTriangularMatrix::BandWidth() const - { REPORT return MatrixBandWidth(0,-1); } - - MatrixBandWidth LowerTriangularMatrix::BandWidth() const - { REPORT return MatrixBandWidth(-1,0); } - - MatrixBandWidth BandMatrix::BandWidth() const - { REPORT return MatrixBandWidth(lower,upper); } - - MatrixBandWidth GenericMatrix::BandWidth()const - { REPORT return gm->BandWidth(); } - - MatrixBandWidth AddedMatrix::BandWidth() const - { REPORT return gm1->BandWidth() + gm2->BandWidth(); } - - MatrixBandWidth SPMatrix::BandWidth() const - { REPORT return gm1->BandWidth().minimum(gm2->BandWidth()); } - - MatrixBandWidth KPMatrix::BandWidth() const - { - int lower, upper; - MatrixBandWidth bw1 = gm1->BandWidth(), bw2 = gm2->BandWidth(); - if (bw1.Lower() < 0) - { - if (bw2.Lower() < 0) { REPORT lower = -1; } - else { REPORT lower = bw2.Lower() + (gm1->Nrows() - 1) * gm2->Nrows(); } - } - else - { - if (bw2.Lower() < 0) - { REPORT lower = (1 + bw1.Lower()) * gm2->Nrows() - 1; } - else { REPORT lower = bw2.Lower() + bw1.Lower() * gm2->Nrows(); } - } - if (bw1.Upper() < 0) - { - if (bw2.Upper() < 0) { REPORT upper = -1; } - else { REPORT upper = bw2.Upper() + (gm1->Nrows() - 1) * gm2->Nrows(); } - } - else - { - if (bw2.Upper() < 0) - { REPORT upper = (1 + bw1.Upper()) * gm2->Nrows() - 1; } - else { REPORT upper = bw2.Upper() + bw1.Upper() * gm2->Nrows(); } - } - return MatrixBandWidth(lower, upper); - } - - MatrixBandWidth MultipliedMatrix::BandWidth() const - { REPORT return gm1->BandWidth() * gm2->BandWidth(); } - - MatrixBandWidth ConcatenatedMatrix::BandWidth() const { REPORT return -1; } - - MatrixBandWidth SolvedMatrix::BandWidth() const - { - if (+gm1->Type() & MatrixType::Diagonal) - { REPORT return gm2->BandWidth(); } - else { REPORT return -1; } - } - - MatrixBandWidth ScaledMatrix::BandWidth() const - { REPORT return gm->BandWidth(); } - - MatrixBandWidth NegatedMatrix::BandWidth() const - { REPORT return gm->BandWidth(); } - - MatrixBandWidth TransposedMatrix::BandWidth() const - { REPORT return gm->BandWidth().t(); } - - MatrixBandWidth InvertedMatrix::BandWidth() const - { - if (+gm->Type() & MatrixType::Diagonal) - { REPORT return MatrixBandWidth(0,0); } - else { REPORT return -1; } - } - - MatrixBandWidth RowedMatrix::BandWidth() const { REPORT return -1; } - MatrixBandWidth ColedMatrix::BandWidth() const { REPORT return -1; } - MatrixBandWidth DiagedMatrix::BandWidth() const { REPORT return 0; } - MatrixBandWidth MatedMatrix::BandWidth() const { REPORT return -1; } - MatrixBandWidth ReturnMatrixX::BandWidth() const - { REPORT return gm->BandWidth(); } - - MatrixBandWidth GetSubMatrix::BandWidth() const - { - - if (row_skip==col_skip && row_number==col_number) - { REPORT return gm->BandWidth(); } - else { REPORT return MatrixBandWidth(-1); } - } - - // ********************** the memory managment tools **********************/ - - // Rules regarding tDelete, reuse, GetStore - // All matrices processed during expression evaluation must be subject - // to exactly one of reuse(), tDelete(), GetStore() or BorrowStore(). - // If reuse returns true the matrix must be reused. - // GetMatrix(gm) always calls gm->GetStore() - // gm->Evaluate obeys rules - // bm->Evaluate obeys rules for matrices in bm structure - - void GeneralMatrix::tDelete() - { - if (tag<0) - { - if (tag<-1) { REPORT store=0; delete this; return; } // borrowed - else { REPORT return; } - } - if (tag==1) - { - if (store) - { - REPORT MONITOR_REAL_DELETE("Free (tDelete)",storage,store) - delete [] store; - } - store=0; CleanUp(); tag=-1; return; - } - if (tag==0) { REPORT delete this; return; } - REPORT tag--; return; - } - - static void BlockCopy(int n, Real* from, Real* to) - { - REPORT - int i = (n >> 3); - while (i--) - { - *to++ = *from++; *to++ = *from++; *to++ = *from++; *to++ = *from++; - *to++ = *from++; *to++ = *from++; *to++ = *from++; *to++ = *from++; - } - i = n & 7; while (i--) *to++ = *from++; - } - - bool GeneralMatrix::reuse() - { - if (tag<-1) - { - if (storage) - { - REPORT - Real* s = new Real [storage]; MatrixErrorNoSpace(s); - MONITOR_REAL_NEW("Make (reuse)",storage,s) - BlockCopy(storage, store, s); store=s; - } - else { REPORT store = 0; CleanUp(); } - tag=0; return true; - } - if (tag<0) { REPORT return false; } - if (tag<=1) { REPORT return true; } - REPORT tag--; return false; - } - - Real* GeneralMatrix::GetStore() - { - if (tag<0 || tag>1) - { - Real* s; - if (storage) - { - s = new Real [storage]; MatrixErrorNoSpace(s); - MONITOR_REAL_NEW("Make (GetStore)",storage,s) - BlockCopy(storage, store, s); - } - else s = 0; - if (tag>1) { REPORT tag--; } - else if (tag < -1) { REPORT store=0; delete this; } // borrowed store - else { REPORT } - return s; - } - Real* s=store; store=0; - if (tag==0) { REPORT delete this; } - else { REPORT CleanUp(); tag=-1; } - return s; - } - - void GeneralMatrix::GetMatrix(const GeneralMatrix* gmx) - { - REPORT tag=-1; nrows=gmx->Nrows(); ncols=gmx->Ncols(); - storage=gmx->storage; SetParameters(gmx); - store=((GeneralMatrix*)gmx)->GetStore(); - } - - GeneralMatrix* GeneralMatrix::BorrowStore(GeneralMatrix* gmx, MatrixType mt) - // Copy storage of *this to storage of *gmx. Then convert to type mt. - // If mt == 0 just let *gmx point to storage of *this if tag==-1. - { - if (!mt) - { - if (tag == -1) { REPORT gmx->tag = -2; gmx->store = store; } - else { REPORT gmx->tag = 0; gmx->store = GetStore(); } - } - else if (Compare(gmx->Type(),mt)) - { REPORT gmx->tag = 0; gmx->store = GetStore(); } - else - { - REPORT gmx->tag = -2; gmx->store = store; - gmx = gmx->Evaluate(mt); gmx->tag = 0; tDelete(); - } - - return gmx; - } - - void GeneralMatrix::Eq(const BaseMatrix& X, MatrixType mt) - // Count number of references to this in X. - // If zero delete storage in this; - // otherwise tag this to show when storage can be deleted - // evaluate X and copy to this - { -#ifdef DO_SEARCH - int counter=X.search(this); - if (counter==0) - { - REPORT - if (store) - { - MONITOR_REAL_DELETE("Free (operator=)",storage,store) - REPORT delete [] store; storage=0; store = 0; - } - } - else { REPORT Release(counter); } - GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(mt); - if (gmx!=this) { REPORT GetMatrix(gmx); } - else { REPORT } - Protect(); -#else - GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(mt); - if (gmx!=this) - { - REPORT - if (store) - { - MONITOR_REAL_DELETE("Free (operator=)",storage,store) - REPORT delete [] store; storage=0; store = 0; - } - GetMatrix(gmx); - } - else { REPORT } - Protect(); -#endif - } - - // version to work with operator<< - void GeneralMatrix::Eq(const BaseMatrix& X, MatrixType mt, bool ldok) - { - REPORT - if (ldok) mt.SetDataLossOK(); - Eq(X, mt); - } - - void GeneralMatrix::Eq2(const BaseMatrix& X, MatrixType mt) - // a cut down version of Eq for use with += etc. - // we know BaseMatrix points to two GeneralMatrix objects, - // the first being this (may be the same). - // we know tag has been set correctly in each. - { - GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(mt); - if (gmx!=this) { REPORT GetMatrix(gmx); } // simplify GetMatrix ? - else { REPORT } - Protect(); - } - - void GeneralMatrix::Inject(const GeneralMatrix& X) - // copy stored values of X; otherwise leave els of *this unchanged - { - REPORT - Tracer tr("Inject"); - if (nrows != X.nrows || ncols != X.ncols) - Throw(IncompatibleDimensionsException()); - MatrixRow mr((GeneralMatrix*)&X, LoadOnEntry); - MatrixRow mrx(this, LoadOnEntry+StoreOnExit+DirectPart); - int i=nrows; - while (i--) { mrx.Inject(mr); mrx.Next(); mr.Next(); } - } - - // ************* checking for data loss during conversion *******************/ - - bool Compare(const MatrixType& source, MatrixType& destination) - { - if (!destination) { destination=source; return true; } - if (destination==source) return true; - if (!destination.DataLossOK && !(destination>=source)) - Throw(ProgramException("Illegal Conversion", source, destination)); - return false; - } - - // ************* Make a copy of a matrix on the heap *********************/ - - GeneralMatrix* Matrix::Image() const - { - REPORT - GeneralMatrix* gm = new Matrix(*this); MatrixErrorNoSpace(gm); - return gm; - } - - GeneralMatrix* SymmetricMatrix::Image() const - { - REPORT - GeneralMatrix* gm = new SymmetricMatrix(*this); MatrixErrorNoSpace(gm); - return gm; - } - - GeneralMatrix* UpperTriangularMatrix::Image() const - { - REPORT - GeneralMatrix* gm = new UpperTriangularMatrix(*this); - MatrixErrorNoSpace(gm); return gm; - } - - GeneralMatrix* LowerTriangularMatrix::Image() const - { - REPORT - GeneralMatrix* gm = new LowerTriangularMatrix(*this); - MatrixErrorNoSpace(gm); return gm; - } - - GeneralMatrix* DiagonalMatrix::Image() const - { - REPORT - GeneralMatrix* gm = new DiagonalMatrix(*this); MatrixErrorNoSpace(gm); - return gm; - } - - GeneralMatrix* RowVector::Image() const - { - REPORT - GeneralMatrix* gm = new RowVector(*this); MatrixErrorNoSpace(gm); - return gm; - } - - GeneralMatrix* ColumnVector::Image() const - { - REPORT - GeneralMatrix* gm = new ColumnVector(*this); MatrixErrorNoSpace(gm); - return gm; - } - - GeneralMatrix* BandMatrix::Image() const - { - REPORT - GeneralMatrix* gm = new BandMatrix(*this); MatrixErrorNoSpace(gm); - return gm; - } - - GeneralMatrix* UpperBandMatrix::Image() const - { - REPORT - GeneralMatrix* gm = new UpperBandMatrix(*this); MatrixErrorNoSpace(gm); - return gm; - } - - GeneralMatrix* LowerBandMatrix::Image() const - { - REPORT - GeneralMatrix* gm = new LowerBandMatrix(*this); MatrixErrorNoSpace(gm); - return gm; - } - - GeneralMatrix* SymmetricBandMatrix::Image() const - { - REPORT - GeneralMatrix* gm = new SymmetricBandMatrix(*this); MatrixErrorNoSpace(gm); - return gm; - } - - GeneralMatrix* nricMatrix::Image() const - { - REPORT - GeneralMatrix* gm = new nricMatrix(*this); MatrixErrorNoSpace(gm); - return gm; - } - - GeneralMatrix* IdentityMatrix::Image() const - { - REPORT - GeneralMatrix* gm = new IdentityMatrix(*this); MatrixErrorNoSpace(gm); - return gm; - } - - GeneralMatrix* GeneralMatrix::Image() const - { - bool dummy = true; - if (dummy) // get rid of warning message - Throw(InternalException("Cannot apply Image to this matrix type")); - return 0; - } - - - // *********************** nricMatrix routines *****************************/ - - void nricMatrix::MakeRowPointer() - { - if (nrows > 0) - { - row_pointer = new Real* [nrows]; MatrixErrorNoSpace(row_pointer); - Real* s = Store() - 1; int i = nrows; Real** rp = row_pointer; - if (i) for (;;) { *rp++ = s; if (!(--i)) break; s+=ncols; } - } - else row_pointer = 0; - } - - void nricMatrix::DeleteRowPointer() - { if (nrows) delete [] row_pointer; } - - void GeneralMatrix::CheckStore() const - { - if (!store) - Throw(ProgramException("NRIC accessing matrix with unset dimensions")); - } - - - // *************************** CleanUp routines *****************************/ - - void GeneralMatrix::CleanUp() - { - // set matrix dimensions to zero, delete storage - REPORT - if (store && storage) - { - MONITOR_REAL_DELETE("Free (CleanUp) ",storage,store) - REPORT delete [] store; - } - store=0; storage=0; nrows=0; ncols=0; - } - - void nricMatrix::CleanUp() - { DeleteRowPointer(); GeneralMatrix::CleanUp(); } - - void RowVector::CleanUp() - { GeneralMatrix::CleanUp(); nrows=1; } - - void ColumnVector::CleanUp() - { GeneralMatrix::CleanUp(); ncols=1; } - - void CroutMatrix::CleanUp() - { - if (nrows) delete [] indx; - GeneralMatrix::CleanUp(); - } - - void BandLUMatrix::CleanUp() - { - if (nrows) delete [] indx; - if (storage2) delete [] store2; - GeneralMatrix::CleanUp(); - } - - // ************************ simple integer array class *********************** - - // construct a new array of length xn. Check that xn is non-negative and - // that space is available - - SimpleIntArray::SimpleIntArray(int xn) : n(xn) - { - if (n < 0) Throw(Logic_error("invalid array length")); - else if (n == 0) { REPORT a = 0; } - else { REPORT a = new int [n]; if (!a) Throw(Bad_alloc()); } - } - - // destroy an array - return its space to memory - - SimpleIntArray::~SimpleIntArray() { REPORT if (a) delete [] a; } - - // access an element of an array; return a "reference" so elements - // can be modified. - // check index is within range - // in this array class the index runs from 0 to n-1 - - int& SimpleIntArray::operator[](int i) - { - REPORT - if (i < 0 || i >= n) Throw(Logic_error("array index out of range")); - return a[i]; - } - - // same thing again but for arrays declared constant so we can't - // modify its elements - - int SimpleIntArray::operator[](int i) const - { - REPORT - if (i < 0 || i >= n) Throw(Logic_error("array index out of range")); - return a[i]; - } - - // set all the elements equal to a given value - - void SimpleIntArray::operator=(int ai) - { REPORT for (int i = 0; i < n; i++) a[i] = ai; } - - // set the elements equal to those of another array. - // check the arrays are of the same length - - void SimpleIntArray::operator=(const SimpleIntArray& b) - { - REPORT - if (b.n != n) Throw(Logic_error("array lengths differ in copy")); - for (int i = 0; i < n; i++) a[i] = b.a[i]; - } - - // construct a new array equal to an existing array - // check that space is available - - SimpleIntArray::SimpleIntArray(const SimpleIntArray& b) : n(b.n) - { - if (n == 0) { REPORT a = 0; } - else - { - REPORT - a = new int [n]; if (!a) Throw(Bad_alloc()); - for (int i = 0; i < n; i++) a[i] = b.a[i]; - } - } - - // change the size of an array; optionally copy data from old array to - // new array - - void SimpleIntArray::ReSize(int n1, bool keep) - { - if (n1 == n) { REPORT return; } - else if (n1 == 0) { REPORT n = 0; delete [] a; a = 0; } - else if (n == 0) - { REPORT a = new int [n1]; if (!a) Throw(Bad_alloc()); n = n1; } - else - { - int* a1 = a; - if (keep) - { - REPORT - a = new int [n1]; if (!a) Throw(Bad_alloc()); - if (n > n1) n = n1; - for (int i = 0; i < n; i++) a[i] = a1[i]; - n = n1; delete [] a1; - } - else - { - REPORT n = n1; delete [] a1; - a = new int [n]; if (!a) Throw(Bad_alloc()); - } - } - } - - -#ifdef use_namespace -} -#endif - diff --git a/lib/src/mixmod/NEWMAT/newmat5.cpp b/lib/src/mixmod/NEWMAT/newmat5.cpp deleted file mode 100644 index 43ad1e7..0000000 --- a/lib/src/mixmod/NEWMAT/newmat5.cpp +++ /dev/null @@ -1,563 +0,0 @@ -//$$ newmat5.cpp Transpose, evaluate etc - -// Copyright (C) 1991,2,3,4: R B Davies - -//#define WANT_STREAM - -#include "include.h" - -#include "newmat.h" -#include "newmatrc.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - - -#ifdef DO_REPORT -#define REPORT { static ExeCounter ExeCount(__LINE__,5); ++ExeCount; } -#else -#define REPORT {} -#endif - - - /************************ carry out operations ******************************/ - - - GeneralMatrix* GeneralMatrix::Transpose(TransposedMatrix* tm, MatrixType mt) - { - GeneralMatrix* gm1; - - if (Compare(Type().t(),mt)) - { - REPORT - gm1 = mt.New(ncols,nrows,tm); - for (int i=0; iReleaseAndDelete(); return gm1; - } - - GeneralMatrix* SymmetricMatrix::Transpose(TransposedMatrix*, MatrixType mt) - { REPORT return Evaluate(mt); } - - - GeneralMatrix* DiagonalMatrix::Transpose(TransposedMatrix*, MatrixType mt) - { REPORT return Evaluate(mt); } - - GeneralMatrix* ColumnVector::Transpose(TransposedMatrix*, MatrixType mt) - { - REPORT - GeneralMatrix* gmx = new RowVector; MatrixErrorNoSpace(gmx); - gmx->nrows = 1; gmx->ncols = gmx->storage = storage; - return BorrowStore(gmx,mt); - } - - GeneralMatrix* RowVector::Transpose(TransposedMatrix*, MatrixType mt) - { - REPORT - GeneralMatrix* gmx = new ColumnVector; MatrixErrorNoSpace(gmx); - gmx->ncols = 1; gmx->nrows = gmx->storage = storage; - return BorrowStore(gmx,mt); - } - - GeneralMatrix* IdentityMatrix::Transpose(TransposedMatrix*, MatrixType mt) - { REPORT return Evaluate(mt); } - - GeneralMatrix* GeneralMatrix::Evaluate(MatrixType mt) - { - if (Compare(this->Type(),mt)) { REPORT return this; } - REPORT - GeneralMatrix* gmx = mt.New(nrows,ncols,this); - MatrixRow mr(this, LoadOnEntry); - MatrixRow mrx(gmx, StoreOnExit+DirectPart); - int i=nrows; - while (i--) { mrx.Copy(mr); mrx.Next(); mr.Next(); } - tDelete(); gmx->ReleaseAndDelete(); return gmx; - } - - GeneralMatrix* GenericMatrix::Evaluate(MatrixType mt) - { REPORT return gm->Evaluate(mt); } - - GeneralMatrix* ShiftedMatrix::Evaluate(MatrixType mt) - { - gm=((BaseMatrix*&)bm)->Evaluate(); - int nr=gm->Nrows(); int nc=gm->Ncols(); - Compare(gm->Type().AddEqualEl(),mt); - if (!(mt==gm->Type())) - { - REPORT - GeneralMatrix* gmx = mt.New(nr,nc,this); - MatrixRow mr(gm, LoadOnEntry); - MatrixRow mrx(gmx, StoreOnExit+DirectPart); - while (nr--) { mrx.Add(mr,f); mrx.Next(); mr.Next(); } - gmx->ReleaseAndDelete(); gm->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - return gmx; - } - else if (gm->reuse()) - { - REPORT gm->Add(f); -#ifdef TEMPS_DESTROYED_QUICKLY - GeneralMatrix* gmx = gm; delete this; return gmx; -#else - return gm; -#endif - } - else - { - REPORT GeneralMatrix* gmy = gm->Type().New(nr,nc,this); - gmy->ReleaseAndDelete(); gmy->Add(gm,f); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - return gmy; - } - } - - GeneralMatrix* NegShiftedMatrix::Evaluate(MatrixType mt) - { - gm=((BaseMatrix*&)bm)->Evaluate(); - int nr=gm->Nrows(); int nc=gm->Ncols(); - Compare(gm->Type().AddEqualEl(),mt); - if (!(mt==gm->Type())) - { - REPORT - GeneralMatrix* gmx = mt.New(nr,nc,this); - MatrixRow mr(gm, LoadOnEntry); - MatrixRow mrx(gmx, StoreOnExit+DirectPart); - while (nr--) { mrx.NegAdd(mr,f); mrx.Next(); mr.Next(); } - gmx->ReleaseAndDelete(); gm->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - return gmx; - } - else if (gm->reuse()) - { - REPORT gm->NegAdd(f); -#ifdef TEMPS_DESTROYED_QUICKLY - GeneralMatrix* gmx = gm; delete this; return gmx; -#else - return gm; -#endif - } - else - { - REPORT GeneralMatrix* gmy = gm->Type().New(nr,nc,this); - gmy->ReleaseAndDelete(); gmy->NegAdd(gm,f); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - return gmy; - } - } - - GeneralMatrix* ScaledMatrix::Evaluate(MatrixType mt) - { - gm=((BaseMatrix*&)bm)->Evaluate(); - int nr=gm->Nrows(); int nc=gm->Ncols(); - if (Compare(gm->Type(),mt)) - { - if (gm->reuse()) - { - REPORT gm->Multiply(f); -#ifdef TEMPS_DESTROYED_QUICKLY - GeneralMatrix* gmx = gm; delete this; return gmx; -#else - return gm; -#endif - } - else - { - REPORT GeneralMatrix* gmx = gm->Type().New(nr,nc,this); - gmx->ReleaseAndDelete(); gmx->Multiply(gm,f); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - return gmx; - } - } - else - { - REPORT - GeneralMatrix* gmx = mt.New(nr,nc,this); - MatrixRow mr(gm, LoadOnEntry); - MatrixRow mrx(gmx, StoreOnExit+DirectPart); - while (nr--) { mrx.Multiply(mr,f); mrx.Next(); mr.Next(); } - gmx->ReleaseAndDelete(); gm->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - return gmx; - } - } - - GeneralMatrix* NegatedMatrix::Evaluate(MatrixType mt) - { - gm=((BaseMatrix*&)bm)->Evaluate(); - int nr=gm->Nrows(); int nc=gm->Ncols(); - if (Compare(gm->Type(),mt)) - { - if (gm->reuse()) - { - REPORT gm->Negate(); -#ifdef TEMPS_DESTROYED_QUICKLY - GeneralMatrix* gmx = gm; delete this; return gmx; -#else - return gm; -#endif - } - else - { - REPORT - GeneralMatrix* gmx = gm->Type().New(nr,nc,this); - gmx->ReleaseAndDelete(); gmx->Negate(gm); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - return gmx; - } - } - else - { - REPORT - GeneralMatrix* gmx = mt.New(nr,nc,this); - MatrixRow mr(gm, LoadOnEntry); - MatrixRow mrx(gmx, StoreOnExit+DirectPart); - while (nr--) { mrx.Negate(mr); mrx.Next(); mr.Next(); } - gmx->ReleaseAndDelete(); gm->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - return gmx; - } - } - - GeneralMatrix* ReversedMatrix::Evaluate(MatrixType mt) - { - gm=((BaseMatrix*&)bm)->Evaluate(); GeneralMatrix* gmx; - - if ((gm->Type()).IsBand() && ! (gm->Type()).IsDiagonal()) - { - gm->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - Throw(NotDefinedException("Reverse", "band matrices")); - } - - if (gm->reuse()) { REPORT gm->ReverseElements(); gmx = gm; } - else - { - REPORT - gmx = gm->Type().New(gm->Nrows(), gm->Ncols(), this); - gmx->ReverseElements(gm); gmx->ReleaseAndDelete(); - } -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - return gmx->Evaluate(mt); // target matrix is different type? - - } - - GeneralMatrix* TransposedMatrix::Evaluate(MatrixType mt) - { - REPORT - gm=((BaseMatrix*&)bm)->Evaluate(); - Compare(gm->Type().t(),mt); - GeneralMatrix* gmx=gm->Transpose(this, mt); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - return gmx; - } - - GeneralMatrix* RowedMatrix::Evaluate(MatrixType mt) - { - gm = ((BaseMatrix*&)bm)->Evaluate(); - GeneralMatrix* gmx = new RowVector; MatrixErrorNoSpace(gmx); - gmx->nrows = 1; gmx->ncols = gmx->storage = gm->storage; -#ifdef TEMPS_DESTROYED_QUICKLY - GeneralMatrix* gmy = gm; delete this; return gmy->BorrowStore(gmx,mt); -#else - return gm->BorrowStore(gmx,mt); -#endif - } - - GeneralMatrix* ColedMatrix::Evaluate(MatrixType mt) - { - gm = ((BaseMatrix*&)bm)->Evaluate(); - GeneralMatrix* gmx = new ColumnVector; MatrixErrorNoSpace(gmx); - gmx->ncols = 1; gmx->nrows = gmx->storage = gm->storage; -#ifdef TEMPS_DESTROYED_QUICKLY - GeneralMatrix* gmy = gm; delete this; return gmy->BorrowStore(gmx,mt); -#else - return gm->BorrowStore(gmx,mt); -#endif - } - - GeneralMatrix* DiagedMatrix::Evaluate(MatrixType mt) - { - gm = ((BaseMatrix*&)bm)->Evaluate(); - GeneralMatrix* gmx = new DiagonalMatrix; MatrixErrorNoSpace(gmx); - gmx->nrows = gmx->ncols = gmx->storage = gm->storage; -#ifdef TEMPS_DESTROYED_QUICKLY - GeneralMatrix* gmy = gm; delete this; return gmy->BorrowStore(gmx,mt); -#else - return gm->BorrowStore(gmx,mt); -#endif - } - - GeneralMatrix* MatedMatrix::Evaluate(MatrixType mt) - { - Tracer tr("MatedMatrix::Evaluate"); - gm = ((BaseMatrix*&)bm)->Evaluate(); - GeneralMatrix* gmx = new Matrix; MatrixErrorNoSpace(gmx); - gmx->nrows = nr; gmx->ncols = nc; gmx->storage = gm->storage; - if (nr*nc != gmx->storage) - Throw(IncompatibleDimensionsException()); -#ifdef TEMPS_DESTROYED_QUICKLY - GeneralMatrix* gmy = gm; delete this; return gmy->BorrowStore(gmx,mt); -#else - return gm->BorrowStore(gmx,mt); -#endif - } - - GeneralMatrix* GetSubMatrix::Evaluate(MatrixType mt) - { - REPORT - Tracer tr("SubMatrix(evaluate)"); - gm = ((BaseMatrix*&)bm)->Evaluate(); - if (row_number < 0) row_number = gm->Nrows(); - if (col_number < 0) col_number = gm->Ncols(); - if (row_skip+row_number > gm->Nrows() || col_skip+col_number > gm->Ncols()) - { - gm->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - Throw(SubMatrixDimensionException()); - } - if (IsSym) Compare(gm->Type().ssub(), mt); - else Compare(gm->Type().sub(), mt); - GeneralMatrix* gmx = mt.New(row_number, col_number, this); - int i = row_number; - MatrixRow mr(gm, LoadOnEntry, row_skip); - MatrixRow mrx(gmx, StoreOnExit+DirectPart); - MatrixRowCol sub; - while (i--) - { - mr.SubRowCol(sub, col_skip, col_number); // put values in sub - mrx.Copy(sub); mrx.Next(); mr.Next(); - } - gmx->ReleaseAndDelete(); gm->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - return gmx; - } - - - GeneralMatrix* ReturnMatrixX::Evaluate(MatrixType mt) - { -#ifdef TEMPS_DESTROYED_QUICKLY_R - GeneralMatrix* gmx = gm; delete this; return gmx->Evaluate(mt); -#else - return gm->Evaluate(mt); -#endif - } - - - void GeneralMatrix::Add(GeneralMatrix* gm1, Real f) - { - REPORT - Real* s1=gm1->store; Real* s=store; int i=(storage >> 2); - while (i--) - { *s++ = *s1++ + f; *s++ = *s1++ + f; *s++ = *s1++ + f; *s++ = *s1++ + f; } - i = storage & 3; while (i--) *s++ = *s1++ + f; - } - - void GeneralMatrix::Add(Real f) - { - REPORT - Real* s=store; int i=(storage >> 2); - while (i--) { *s++ += f; *s++ += f; *s++ += f; *s++ += f; } - i = storage & 3; while (i--) *s++ += f; - } - - void GeneralMatrix::NegAdd(GeneralMatrix* gm1, Real f) - { - REPORT - Real* s1=gm1->store; Real* s=store; int i=(storage >> 2); - while (i--) - { *s++ = f - *s1++; *s++ = f - *s1++; *s++ = f - *s1++; *s++ = f - *s1++; } - i = storage & 3; while (i--) *s++ = f - *s1++; - } - - void GeneralMatrix::NegAdd(Real f) - { - REPORT - Real* s=store; int i=(storage >> 2); - while (i--) - { - *s = f - *s; s++; *s = f - *s; s++; - *s = f - *s; s++; *s = f - *s; s++; - } - i = storage & 3; while (i--) { *s = f - *s; s++; } - } - - void GeneralMatrix::Negate(GeneralMatrix* gm1) - { - // change sign of elements - REPORT - Real* s1=gm1->store; Real* s=store; int i=(storage >> 2); - while (i--) - { *s++ = -(*s1++); *s++ = -(*s1++); *s++ = -(*s1++); *s++ = -(*s1++); } - i = storage & 3; while(i--) *s++ = -(*s1++); - } - - void GeneralMatrix::Negate() - { - REPORT - Real* s=store; int i=(storage >> 2); - while (i--) - { *s = -(*s); s++; *s = -(*s); s++; *s = -(*s); s++; *s = -(*s); s++; } - i = storage & 3; while(i--) { *s = -(*s); s++; } - } - - void GeneralMatrix::Multiply(GeneralMatrix* gm1, Real f) - { - REPORT - Real* s1=gm1->store; Real* s=store; int i=(storage >> 2); - while (i--) - { *s++ = *s1++ * f; *s++ = *s1++ * f; *s++ = *s1++ * f; *s++ = *s1++ * f; } - i = storage & 3; while (i--) *s++ = *s1++ * f; - } - - void GeneralMatrix::Multiply(Real f) - { - REPORT - Real* s=store; int i=(storage >> 2); - while (i--) { *s++ *= f; *s++ *= f; *s++ *= f; *s++ *= f; } - i = storage & 3; while (i--) *s++ *= f; - } - - - /************************ MatrixInput routines ****************************/ - - // int MatrixInput::n; // number values still to be read - // Real* MatrixInput::r; // pointer to next location to be read to - - MatrixInput MatrixInput::operator<<(Real f) - { - REPORT - Tracer et("MatrixInput"); - if (n<=0) Throw(ProgramException("List of values too long")); - *r = f; int n1 = n-1; n=0; // n=0 so we won't trigger exception - return MatrixInput(n1, r+1); - } - - - MatrixInput GeneralMatrix::operator<<(Real f) - { - REPORT - Tracer et("MatrixInput"); - int n = Storage(); - if (n<=0) Throw(ProgramException("Loading data to zero length matrix")); - Real* r; r = Store(); *r = f; n--; - return MatrixInput(n, r+1); - } - - MatrixInput GetSubMatrix::operator<<(Real f) - { - REPORT - Tracer et("MatrixInput (GetSubMatrix)"); - SetUpLHS(); - if (row_number != 1 || col_skip != 0 || col_number != gm->Ncols()) - { -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - Throw(ProgramException("MatrixInput requires complete rows")); - } - MatrixRow mr(gm, DirectPart, row_skip); // to pick up location and length - int n = mr.Storage(); - if (n<=0) - { -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - Throw(ProgramException("Loading data to zero length row")); - } - Real* r; r = mr.Data(); *r = f; n--; - if (+(mr.cw*HaveStore)) - { -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - Throw(ProgramException("Fails with this matrix type")); - } -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - return MatrixInput(n, r+1); - } - - MatrixInput::~MatrixInput() - { - REPORT - Tracer et("MatrixInput"); - if (n!=0) Throw(ProgramException("A list of values was too short")); - } - - MatrixInput BandMatrix::operator<<(Real) - { - Tracer et("MatrixInput"); - bool dummy = true; - if (dummy) // get rid of warning message - Throw(ProgramException("Cannot use list read with a BandMatrix")); - return MatrixInput(0, 0); - } - - void BandMatrix::operator<<(const Real*) - { Throw(ProgramException("Cannot use array read with a BandMatrix")); } - - // ************************* Reverse order of elements *********************** - - void GeneralMatrix::ReverseElements(GeneralMatrix* gm) - { - // reversing into a new matrix - REPORT - int n = Storage(); Real* rx = Store() + n; Real* x = gm->Store(); - while (n--) *(--rx) = *(x++); - } - - void GeneralMatrix::ReverseElements() - { - // reversing in place - REPORT - int n = Storage(); Real* x = Store(); Real* rx = x + n; - n /= 2; - while (n--) { Real t = *(--rx); *rx = *x; *(x++) = t; } - } - - -#ifdef use_namespace -} -#endif - diff --git a/lib/src/mixmod/NEWMAT/newmat6.cpp b/lib/src/mixmod/NEWMAT/newmat6.cpp deleted file mode 100644 index 99661ae..0000000 --- a/lib/src/mixmod/NEWMAT/newmat6.cpp +++ /dev/null @@ -1,1124 +0,0 @@ -//$$ newmat6.cpp Operators, element access, submatrices - -// Copyright (C) 1991,2,3,4: R B Davies - -#include "include.h" - -#include "newmat.h" -#include "newmatrc.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - - - -#ifdef DO_REPORT -#define REPORT { static ExeCounter ExeCount(__LINE__,6); ++ExeCount; } -#else -#define REPORT {} -#endif - - /*************************** general utilities *************************/ - - static int tristore(int n) // els in triangular matrix - { return (n*(n+1))/2; } - - - /****************************** operators *******************************/ - - Real& Matrix::operator()(int m, int n) - { - REPORT - if (m<=0 || m>nrows || n<=0 || n>ncols) - Throw(IndexException(m,n,*this)); - return store[(m-1)*ncols+n-1]; - } - - Real& SymmetricMatrix::operator()(int m, int n) - { - REPORT - if (m<=0 || n<=0 || m>nrows || n>ncols) - Throw(IndexException(m,n,*this)); - if (m>=n) return store[tristore(m-1)+n-1]; - else return store[tristore(n-1)+m-1]; - } - - Real& UpperTriangularMatrix::operator()(int m, int n) - { - REPORT - if (m<=0 || nncols) - Throw(IndexException(m,n,*this)); - return store[(m-1)*ncols+n-1-tristore(m-1)]; - } - - Real& LowerTriangularMatrix::operator()(int m, int n) - { - REPORT - if (n<=0 || mnrows) - Throw(IndexException(m,n,*this)); - return store[tristore(m-1)+n-1]; - } - - Real& DiagonalMatrix::operator()(int m, int n) - { - REPORT - if (n<=0 || m!=n || m>nrows || n>ncols) - Throw(IndexException(m,n,*this)); - return store[n-1]; - } - - Real& DiagonalMatrix::operator()(int m) - { - REPORT - if (m<=0 || m>nrows) Throw(IndexException(m,*this)); - return store[m-1]; - } - - Real& ColumnVector::operator()(int m) - { - REPORT - if (m<=0 || m> nrows) Throw(IndexException(m,*this)); - return store[m-1]; - } - - Real& RowVector::operator()(int n) - { - REPORT - if (n<=0 || n> ncols) Throw(IndexException(n,*this)); - return store[n-1]; - } - - Real& BandMatrix::operator()(int m, int n) - { - REPORT - int w = upper+lower+1; int i = lower+n-m; - if (m<=0 || m>nrows || n<=0 || n>ncols || i<0 || i>=w) - Throw(IndexException(m,n,*this)); - return store[w*(m-1)+i]; - } - - Real& UpperBandMatrix::operator()(int m, int n) - { - REPORT - int w = upper+1; int i = n-m; - if (m<=0 || m>nrows || n<=0 || n>ncols || i<0 || i>=w) - Throw(IndexException(m,n,*this)); - return store[w*(m-1)+i]; - } - - Real& LowerBandMatrix::operator()(int m, int n) - { - REPORT - int w = lower+1; int i = lower+n-m; - if (m<=0 || m>nrows || n<=0 || n>ncols || i<0 || i>=w) - Throw(IndexException(m,n,*this)); - return store[w*(m-1)+i]; - } - - Real& SymmetricBandMatrix::operator()(int m, int n) - { - REPORT - int w = lower+1; - if (m>=n) - { - REPORT - int i = lower+n-m; - if ( m>nrows || n<=0 || i<0 ) - Throw(IndexException(m,n,*this)); - return store[w*(m-1)+i]; - } - else - { - REPORT - int i = lower+m-n; - if ( n>nrows || m<=0 || i<0 ) - Throw(IndexException(m,n,*this)); - return store[w*(n-1)+i]; - } - } - - - Real Matrix::operator()(int m, int n) const - { - REPORT - if (m<=0 || m>nrows || n<=0 || n>ncols) - Throw(IndexException(m,n,*this)); - return store[(m-1)*ncols+n-1]; - } - - Real SymmetricMatrix::operator()(int m, int n) const - { - REPORT - if (m<=0 || n<=0 || m>nrows || n>ncols) - Throw(IndexException(m,n,*this)); - if (m>=n) return store[tristore(m-1)+n-1]; - else return store[tristore(n-1)+m-1]; - } - - Real UpperTriangularMatrix::operator()(int m, int n) const - { - REPORT - if (m<=0 || nncols) - Throw(IndexException(m,n,*this)); - return store[(m-1)*ncols+n-1-tristore(m-1)]; - } - - Real LowerTriangularMatrix::operator()(int m, int n) const - { - REPORT - if (n<=0 || mnrows) - Throw(IndexException(m,n,*this)); - return store[tristore(m-1)+n-1]; - } - - Real DiagonalMatrix::operator()(int m, int n) const - { - REPORT - if (n<=0 || m!=n || m>nrows || n>ncols) - Throw(IndexException(m,n,*this)); - return store[n-1]; - } - - Real DiagonalMatrix::operator()(int m) const - { - REPORT - if (m<=0 || m>nrows) Throw(IndexException(m,*this)); - return store[m-1]; - } - - Real ColumnVector::operator()(int m) const - { - REPORT - if (m<=0 || m> nrows) Throw(IndexException(m,*this)); - return store[m-1]; - } - - Real RowVector::operator()(int n) const - { - REPORT - if (n<=0 || n> ncols) Throw(IndexException(n,*this)); - return store[n-1]; - } - - Real BandMatrix::operator()(int m, int n) const - { - REPORT - int w = upper+lower+1; int i = lower+n-m; - if (m<=0 || m>nrows || n<=0 || n>ncols || i<0 || i>=w) - Throw(IndexException(m,n,*this)); - return store[w*(m-1)+i]; - } - - Real UpperBandMatrix::operator()(int m, int n) const - { - REPORT - int w = upper+1; int i = n-m; - if (m<=0 || m>nrows || n<=0 || n>ncols || i<0 || i>=w) - Throw(IndexException(m,n,*this)); - return store[w*(m-1)+i]; - } - - Real LowerBandMatrix::operator()(int m, int n) const - { - REPORT - int w = lower+1; int i = lower+n-m; - if (m<=0 || m>nrows || n<=0 || n>ncols || i<0 || i>=w) - Throw(IndexException(m,n,*this)); - return store[w*(m-1)+i]; - } - - Real SymmetricBandMatrix::operator()(int m, int n) const - { - REPORT - int w = lower+1; - if (m>=n) - { - REPORT - int i = lower+n-m; - if ( m>nrows || n<=0 || i<0 ) - Throw(IndexException(m,n,*this)); - return store[w*(m-1)+i]; - } - else - { - REPORT - int i = lower+m-n; - if ( n>nrows || m<=0 || i<0 ) - Throw(IndexException(m,n,*this)); - return store[w*(n-1)+i]; - } - } - - - Real BaseMatrix::AsScalar() const - { - REPORT - GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); - - if (gm->nrows!=1 || gm->ncols!=1) - { - Tracer tr("AsScalar"); - Try - { Throw(ProgramException("Cannot convert to scalar", *gm)); } - CatchAll { gm->tDelete(); ReThrow; } - } - - Real x = *(gm->store); gm->tDelete(); return x; - } - -#ifdef TEMPS_DESTROYED_QUICKLY - - AddedMatrix& BaseMatrix::operator+(const BaseMatrix& bm) const - { - REPORT - AddedMatrix* x = new AddedMatrix(this, &bm); - MatrixErrorNoSpace(x); - return *x; - } - - SPMatrix& SP(const BaseMatrix& bm1,const BaseMatrix& bm2) - { - REPORT - SPMatrix* x = new SPMatrix(&bm1, &bm2); - MatrixErrorNoSpace(x); - return *x; - } - - KPMatrix& KP(const BaseMatrix& bm1,const BaseMatrix& bm2) - { - REPORT - KPMatrix* x = new KPMatrix(&bm1, &bm2); - MatrixErrorNoSpace(x); - return *x; - } - - MultipliedMatrix& BaseMatrix::operator*(const BaseMatrix& bm) const - { - REPORT - MultipliedMatrix* x = new MultipliedMatrix(this, &bm); - MatrixErrorNoSpace(x); - return *x; - } - - ConcatenatedMatrix& BaseMatrix::operator|(const BaseMatrix& bm) const - { - REPORT - ConcatenatedMatrix* x = new ConcatenatedMatrix(this, &bm); - MatrixErrorNoSpace(x); - return *x; - } - - StackedMatrix& BaseMatrix::operator&(const BaseMatrix& bm) const - { - REPORT - StackedMatrix* x = new StackedMatrix(this, &bm); - MatrixErrorNoSpace(x); - return *x; - } - - //SolvedMatrix& InvertedMatrix::operator*(const BaseMatrix& bmx) const - SolvedMatrix& InvertedMatrix::operator*(const BaseMatrix& bmx) - { - REPORT - SolvedMatrix* x; - Try { x = new SolvedMatrix(bm, &bmx); MatrixErrorNoSpace(x); } - CatchAll { delete this; ReThrow; } - delete this; // since we are using bm rather than this - return *x; - } - - SubtractedMatrix& BaseMatrix::operator-(const BaseMatrix& bm) const - { - REPORT - SubtractedMatrix* x = new SubtractedMatrix(this, &bm); - MatrixErrorNoSpace(x); - return *x; - } - - ShiftedMatrix& BaseMatrix::operator+(Real f) const - { - REPORT - ShiftedMatrix* x = new ShiftedMatrix(this, f); - MatrixErrorNoSpace(x); - return *x; - } - - NegShiftedMatrix& operator-(Real f,const BaseMatrix& bm1) - { - REPORT - NegShiftedMatrix* x = new NegShiftedMatrix(f, &bm1); - MatrixErrorNoSpace(x); - return *x; - } - - ScaledMatrix& BaseMatrix::operator*(Real f) const - { - REPORT - ScaledMatrix* x = new ScaledMatrix(this, f); - MatrixErrorNoSpace(x); - return *x; - } - - ScaledMatrix& BaseMatrix::operator/(Real f) const - { - REPORT - ScaledMatrix* x = new ScaledMatrix(this, 1.0/f); - MatrixErrorNoSpace(x); - return *x; - } - - ShiftedMatrix& BaseMatrix::operator-(Real f) const - { - REPORT - ShiftedMatrix* x = new ShiftedMatrix(this, -f); - MatrixErrorNoSpace(x); - return *x; - } - - TransposedMatrix& BaseMatrix::t() const - { - REPORT - TransposedMatrix* x = new TransposedMatrix(this); - MatrixErrorNoSpace(x); - return *x; - } - - NegatedMatrix& BaseMatrix::operator-() const - { - REPORT - NegatedMatrix* x = new NegatedMatrix(this); - MatrixErrorNoSpace(x); - return *x; - } - - ReversedMatrix& BaseMatrix::Reverse() const - { - REPORT - ReversedMatrix* x = new ReversedMatrix(this); - MatrixErrorNoSpace(x); - return *x; - } - - InvertedMatrix& BaseMatrix::i() const - { - REPORT - InvertedMatrix* x = new InvertedMatrix(this); - MatrixErrorNoSpace(x); - return *x; - } - - RowedMatrix& BaseMatrix::AsRow() const - { - REPORT - RowedMatrix* x = new RowedMatrix(this); - MatrixErrorNoSpace(x); - return *x; - } - - ColedMatrix& BaseMatrix::AsColumn() const - { - REPORT - ColedMatrix* x = new ColedMatrix(this); - MatrixErrorNoSpace(x); - return *x; - } - - DiagedMatrix& BaseMatrix::AsDiagonal() const - { - REPORT - DiagedMatrix* x = new DiagedMatrix(this); - MatrixErrorNoSpace(x); - return *x; - } - - MatedMatrix& BaseMatrix::AsMatrix(int nrx, int ncx) const - { - REPORT - MatedMatrix* x = new MatedMatrix(this,nrx,ncx); - MatrixErrorNoSpace(x); - return *x; - } - -#else - - AddedMatrix BaseMatrix::operator+(const BaseMatrix& bm) const - { REPORT return AddedMatrix(this, &bm); } - - SPMatrix SP(const BaseMatrix& bm1,const BaseMatrix& bm2) - { REPORT return SPMatrix(&bm1, &bm2); } - - KPMatrix KP(const BaseMatrix& bm1,const BaseMatrix& bm2) - { REPORT return KPMatrix(&bm1, &bm2); } - - MultipliedMatrix BaseMatrix::operator*(const BaseMatrix& bm) const - { REPORT return MultipliedMatrix(this, &bm); } - - ConcatenatedMatrix BaseMatrix::operator|(const BaseMatrix& bm) const - { REPORT return ConcatenatedMatrix(this, &bm); } - - StackedMatrix BaseMatrix::operator&(const BaseMatrix& bm) const - { REPORT return StackedMatrix(this, &bm); } - - SolvedMatrix InvertedMatrix::operator*(const BaseMatrix& bmx) const - { REPORT return SolvedMatrix(bm, &bmx); } - - SubtractedMatrix BaseMatrix::operator-(const BaseMatrix& bm) const - { REPORT return SubtractedMatrix(this, &bm); } - - ShiftedMatrix BaseMatrix::operator+(Real f) const - { REPORT return ShiftedMatrix(this, f); } - - NegShiftedMatrix operator-(Real f, const BaseMatrix& bm) - { REPORT return NegShiftedMatrix(f, &bm); } - - ScaledMatrix BaseMatrix::operator*(Real f) const - { REPORT return ScaledMatrix(this, f); } - - ScaledMatrix BaseMatrix::operator/(Real f) const - { REPORT return ScaledMatrix(this, 1.0/f); } - - ShiftedMatrix BaseMatrix::operator-(Real f) const - { REPORT return ShiftedMatrix(this, -f); } - - TransposedMatrix BaseMatrix::t() const - { REPORT return TransposedMatrix(this); } - - NegatedMatrix BaseMatrix::operator-() const - { REPORT return NegatedMatrix(this); } - - ReversedMatrix BaseMatrix::Reverse() const - { REPORT return ReversedMatrix(this); } - - InvertedMatrix BaseMatrix::i() const - { REPORT return InvertedMatrix(this); } - - - RowedMatrix BaseMatrix::AsRow() const - { REPORT return RowedMatrix(this); } - - ColedMatrix BaseMatrix::AsColumn() const - { REPORT return ColedMatrix(this); } - - DiagedMatrix BaseMatrix::AsDiagonal() const - { REPORT return DiagedMatrix(this); } - - MatedMatrix BaseMatrix::AsMatrix(int nrx, int ncx) const - { REPORT return MatedMatrix(this,nrx,ncx); } - -#endif - - void GeneralMatrix::operator=(Real f) - { REPORT int i=storage; Real* s=store; while (i--) { *s++ = f; } } - - void Matrix::operator=(const BaseMatrix& X) - { - REPORT //CheckConversion(X); - // MatrixConversionCheck mcc; - Eq(X,MatrixType::Rt); - } - - void RowVector::operator=(const BaseMatrix& X) - { - REPORT // CheckConversion(X); - // MatrixConversionCheck mcc; - Eq(X,MatrixType::RV); - if (nrows!=1) - { Tracer tr("RowVector(=)"); Throw(VectorException(*this)); } - } - - void ColumnVector::operator=(const BaseMatrix& X) - { - REPORT //CheckConversion(X); - // MatrixConversionCheck mcc; - Eq(X,MatrixType::CV); - if (ncols!=1) - { Tracer tr("ColumnVector(=)"); Throw(VectorException(*this)); } - } - - void SymmetricMatrix::operator=(const BaseMatrix& X) - { - REPORT // CheckConversion(X); - // MatrixConversionCheck mcc; - Eq(X,MatrixType::Sm); - } - - void UpperTriangularMatrix::operator=(const BaseMatrix& X) - { - REPORT //CheckConversion(X); - // MatrixConversionCheck mcc; - Eq(X,MatrixType::UT); - } - - void LowerTriangularMatrix::operator=(const BaseMatrix& X) - { - REPORT //CheckConversion(X); - // MatrixConversionCheck mcc; - Eq(X,MatrixType::LT); - } - - void DiagonalMatrix::operator=(const BaseMatrix& X) - { - REPORT // CheckConversion(X); - // MatrixConversionCheck mcc; - Eq(X,MatrixType::Dg); - } - - void IdentityMatrix::operator=(const BaseMatrix& X) - { - REPORT // CheckConversion(X); - // MatrixConversionCheck mcc; - Eq(X,MatrixType::Id); - } - - void GeneralMatrix::operator<<(const Real* r) - { - REPORT - int i = storage; Real* s=store; - while(i--) *s++ = *r++; - } - - - void GenericMatrix::operator=(const GenericMatrix& bmx) - { - if (&bmx != this) { REPORT if (gm) delete gm; gm = bmx.gm->Image();} - else { REPORT } - gm->Protect(); - } - - void GenericMatrix::operator=(const BaseMatrix& bmx) - { - if (gm) - { - int counter=bmx.search(gm); - if (counter==0) { REPORT delete gm; gm=0; } - else { REPORT gm->Release(counter); } - } - else { REPORT } - GeneralMatrix* gmx = ((BaseMatrix&)bmx).Evaluate(); - if (gmx != gm) { REPORT if (gm) delete gm; gm = gmx->Image(); } - else { REPORT } - gm->Protect(); - } - - - /*************************** += etc ***************************************/ - - // will also need versions for SubMatrix - - - - // GeneralMatrix operators - - void GeneralMatrix::operator+=(const BaseMatrix& X) - { - REPORT - Tracer tr("GeneralMatrix::operator+="); - // MatrixConversionCheck mcc; - Protect(); // so it cannot get deleted - // during Evaluate - GeneralMatrix* gm = ((BaseMatrix&)X).Evaluate(); -#ifdef TEMPS_DESTROYED_QUICKLY - AddedMatrix* am = new AddedMatrix(this,gm); - MatrixErrorNoSpace(am); - if (gm==this) Release(2); else Release(); - Eq2(*am,Type()); -#else - AddedMatrix am(this,gm); - if (gm==this) Release(2); else Release(); - Eq2(am,Type()); -#endif - } - - void GeneralMatrix::operator-=(const BaseMatrix& X) - { - REPORT - Tracer tr("GeneralMatrix::operator-="); - // MatrixConversionCheck mcc; - Protect(); // so it cannot get deleted - // during Evaluate - GeneralMatrix* gm = ((BaseMatrix&)X).Evaluate(); -#ifdef TEMPS_DESTROYED_QUICKLY - SubtractedMatrix* am = new SubtractedMatrix(this,gm); - MatrixErrorNoSpace(am); - if (gm==this) Release(2); else Release(); - Eq2(*am,Type()); -#else - SubtractedMatrix am(this,gm); - if (gm==this) Release(2); else Release(); - Eq2(am,Type()); -#endif - } - - void GeneralMatrix::operator*=(const BaseMatrix& X) - { - REPORT - Tracer tr("GeneralMatrix::operator*="); - // MatrixConversionCheck mcc; - Protect(); // so it cannot get deleted - // during Evaluate - GeneralMatrix* gm = ((BaseMatrix&)X).Evaluate(); -#ifdef TEMPS_DESTROYED_QUICKLY - MultipliedMatrix* am = new MultipliedMatrix(this,gm); - MatrixErrorNoSpace(am); - if (gm==this) Release(2); else Release(); - Eq2(*am,Type()); -#else - MultipliedMatrix am(this,gm); - if (gm==this) Release(2); else Release(); - Eq2(am,Type()); -#endif - } - - void GeneralMatrix::operator|=(const BaseMatrix& X) - { - REPORT - Tracer tr("GeneralMatrix::operator|="); - // MatrixConversionCheck mcc; - Protect(); // so it cannot get deleted - // during Evaluate - GeneralMatrix* gm = ((BaseMatrix&)X).Evaluate(); -#ifdef TEMPS_DESTROYED_QUICKLY - ConcatenatedMatrix* am = new ConcatenatedMatrix(this,gm); - MatrixErrorNoSpace(am); - if (gm==this) Release(2); else Release(); - Eq2(*am,Type()); -#else - ConcatenatedMatrix am(this,gm); - if (gm==this) Release(2); else Release(); - Eq2(am,Type()); -#endif - } - - void GeneralMatrix::operator&=(const BaseMatrix& X) - { - REPORT - Tracer tr("GeneralMatrix::operator&="); - // MatrixConversionCheck mcc; - Protect(); // so it cannot get deleted - // during Evaluate - GeneralMatrix* gm = ((BaseMatrix&)X).Evaluate(); -#ifdef TEMPS_DESTROYED_QUICKLY - StackedMatrix* am = new StackedMatrix(this,gm); - MatrixErrorNoSpace(am); - if (gm==this) Release(2); else Release(); - Eq2(*am,Type()); -#else - StackedMatrix am(this,gm); - if (gm==this) Release(2); else Release(); - Eq2(am,Type()); -#endif - } - - void GeneralMatrix::operator+=(Real r) - { - REPORT - Tracer tr("GeneralMatrix::operator+=(Real)"); - // MatrixConversionCheck mcc; -#ifdef TEMPS_DESTROYED_QUICKLY - ShiftedMatrix* am = new ShiftedMatrix(this,r); - MatrixErrorNoSpace(am); - Release(); Eq2(*am,Type()); -#else - ShiftedMatrix am(this,r); - Release(); Eq2(am,Type()); -#endif - } - - void GeneralMatrix::operator*=(Real r) - { - REPORT - Tracer tr("GeneralMatrix::operator*=(Real)"); - // MatrixConversionCheck mcc; -#ifdef TEMPS_DESTROYED_QUICKLY - ScaledMatrix* am = new ScaledMatrix(this,r); - MatrixErrorNoSpace(am); - Release(); Eq2(*am,Type()); -#else - ScaledMatrix am(this,r); - Release(); Eq2(am,Type()); -#endif - } - - - // Generic matrix operators - - void GenericMatrix::operator+=(const BaseMatrix& X) - { - REPORT - Tracer tr("GenericMatrix::operator+="); - if (!gm) Throw(ProgramException("GenericMatrix is null")); - gm->Protect(); // so it cannot get deleted during Evaluate - GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(); -#ifdef TEMPS_DESTROYED_QUICKLY - AddedMatrix* am = new AddedMatrix(gm,gmx); - MatrixErrorNoSpace(am); - if (gmx==gm) gm->Release(2); else gm->Release(); - GeneralMatrix* gmy = am->Evaluate(); -#else - AddedMatrix am(gm,gmx); - if (gmx==gm) gm->Release(2); else gm->Release(); - GeneralMatrix* gmy = am.Evaluate(); -#endif - if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } - else { REPORT } - gm->Protect(); - } - - void GenericMatrix::operator-=(const BaseMatrix& X) - { - REPORT - Tracer tr("GenericMatrix::operator-="); - if (!gm) Throw(ProgramException("GenericMatrix is null")); - gm->Protect(); // so it cannot get deleted during Evaluate - GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(); -#ifdef TEMPS_DESTROYED_QUICKLY - SubtractedMatrix* am = new SubtractedMatrix(gm,gmx); - MatrixErrorNoSpace(am); - if (gmx==gm) gm->Release(2); else gm->Release(); - GeneralMatrix* gmy = am->Evaluate(); -#else - SubtractedMatrix am(gm,gmx); - if (gmx==gm) gm->Release(2); else gm->Release(); - GeneralMatrix* gmy = am.Evaluate(); -#endif - if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } - else { REPORT } - gm->Protect(); - } - - void GenericMatrix::operator*=(const BaseMatrix& X) - { - REPORT - Tracer tr("GenericMatrix::operator*="); - if (!gm) Throw(ProgramException("GenericMatrix is null")); - gm->Protect(); // so it cannot get deleted during Evaluate - GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(); -#ifdef TEMPS_DESTROYED_QUICKLY - MultipliedMatrix* am = new MultipliedMatrix(gm,gmx); - MatrixErrorNoSpace(am); - if (gmx==gm) gm->Release(2); else gm->Release(); - GeneralMatrix* gmy = am->Evaluate(); -#else - MultipliedMatrix am(gm,gmx); - if (gmx==gm) gm->Release(2); else gm->Release(); - GeneralMatrix* gmy = am.Evaluate(); -#endif - if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } - else { REPORT } - gm->Protect(); - } - - void GenericMatrix::operator|=(const BaseMatrix& X) - { - REPORT - Tracer tr("GenericMatrix::operator|="); - if (!gm) Throw(ProgramException("GenericMatrix is null")); - gm->Protect(); // so it cannot get deleted during Evaluate - GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(); -#ifdef TEMPS_DESTROYED_QUICKLY - ConcatenatedMatrix* am = new ConcatenatedMatrix(gm,gmx); - MatrixErrorNoSpace(am); - if (gmx==gm) gm->Release(2); else gm->Release(); - GeneralMatrix* gmy = am->Evaluate(); -#else - ConcatenatedMatrix am(gm,gmx); - if (gmx==gm) gm->Release(2); else gm->Release(); - GeneralMatrix* gmy = am.Evaluate(); -#endif - if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } - else { REPORT } - gm->Protect(); - } - - void GenericMatrix::operator&=(const BaseMatrix& X) - { - REPORT - Tracer tr("GenericMatrix::operator&="); - if (!gm) Throw(ProgramException("GenericMatrix is null")); - gm->Protect(); // so it cannot get deleted during Evaluate - GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(); -#ifdef TEMPS_DESTROYED_QUICKLY - StackedMatrix* am = new StackedMatrix(gm,gmx); - MatrixErrorNoSpace(am); - if (gmx==gm) gm->Release(2); else gm->Release(); - GeneralMatrix* gmy = am->Evaluate(); -#else - StackedMatrix am(gm,gmx); - if (gmx==gm) gm->Release(2); else gm->Release(); - GeneralMatrix* gmy = am.Evaluate(); -#endif - if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } - else { REPORT } - gm->Protect(); - } - - void GenericMatrix::operator+=(Real r) - { - REPORT - Tracer tr("GenericMatrix::operator+= (Real)"); - if (!gm) Throw(ProgramException("GenericMatrix is null")); -#ifdef TEMPS_DESTROYED_QUICKLY - ShiftedMatrix* am = new ShiftedMatrix(gm,r); - MatrixErrorNoSpace(am); - gm->Release(); - GeneralMatrix* gmy = am->Evaluate(); -#else - ShiftedMatrix am(gm,r); - gm->Release(); - GeneralMatrix* gmy = am.Evaluate(); -#endif - if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } - else { REPORT } - gm->Protect(); - } - - void GenericMatrix::operator*=(Real r) - { - REPORT - Tracer tr("GenericMatrix::operator*= (Real)"); - if (!gm) Throw(ProgramException("GenericMatrix is null")); -#ifdef TEMPS_DESTROYED_QUICKLY - ScaledMatrix* am = new ScaledMatrix(gm,r); - MatrixErrorNoSpace(am); - gm->Release(); - GeneralMatrix* gmy = am->Evaluate(); -#else - ScaledMatrix am(gm,r); - gm->Release(); - GeneralMatrix* gmy = am.Evaluate(); -#endif - if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } - else { REPORT } - gm->Protect(); - } - - - /************************* element access *********************************/ - - Real& Matrix::element(int m, int n) - { - REPORT - if (m<0 || m>= nrows || n<0 || n>= ncols) - Throw(IndexException(m,n,*this,true)); - return store[m*ncols+n]; - } - - Real Matrix::element(int m, int n) const - { - REPORT - if (m<0 || m>= nrows || n<0 || n>= ncols) - Throw(IndexException(m,n,*this,true)); - return store[m*ncols+n]; - } - - Real& SymmetricMatrix::element(int m, int n) - { - REPORT - if (m<0 || n<0 || m >= nrows || n>=ncols) - Throw(IndexException(m,n,*this,true)); - if (m>=n) return store[tristore(m)+n]; - else return store[tristore(n)+m]; - } - - Real SymmetricMatrix::element(int m, int n) const - { - REPORT - if (m<0 || n<0 || m >= nrows || n>=ncols) - Throw(IndexException(m,n,*this,true)); - if (m>=n) return store[tristore(m)+n]; - else return store[tristore(n)+m]; - } - - Real& UpperTriangularMatrix::element(int m, int n) - { - REPORT - if (m<0 || n=ncols) - Throw(IndexException(m,n,*this,true)); - return store[m*ncols+n-tristore(m)]; - } - - Real UpperTriangularMatrix::element(int m, int n) const - { - REPORT - if (m<0 || n=ncols) - Throw(IndexException(m,n,*this,true)); - return store[m*ncols+n-tristore(m)]; - } - - Real& LowerTriangularMatrix::element(int m, int n) - { - REPORT - if (n<0 || m=nrows) - Throw(IndexException(m,n,*this,true)); - return store[tristore(m)+n]; - } - - Real LowerTriangularMatrix::element(int m, int n) const - { - REPORT - if (n<0 || m=nrows) - Throw(IndexException(m,n,*this,true)); - return store[tristore(m)+n]; - } - - Real& DiagonalMatrix::element(int m, int n) - { - REPORT - if (n<0 || m!=n || m>=nrows || n>=ncols) - Throw(IndexException(m,n,*this,true)); - return store[n]; - } - - Real DiagonalMatrix::element(int m, int n) const - { - REPORT - if (n<0 || m!=n || m>=nrows || n>=ncols) - Throw(IndexException(m,n,*this,true)); - return store[n]; - } - - Real& DiagonalMatrix::element(int m) - { - REPORT - if (m<0 || m>=nrows) Throw(IndexException(m,*this,true)); - return store[m]; - } - - Real DiagonalMatrix::element(int m) const - { - REPORT - if (m<0 || m>=nrows) Throw(IndexException(m,*this,true)); - return store[m]; - } - - Real& ColumnVector::element(int m) - { - REPORT - if (m<0 || m>= nrows) Throw(IndexException(m,*this,true)); - return store[m]; - } - - Real ColumnVector::element(int m) const - { - REPORT - if (m<0 || m>= nrows) Throw(IndexException(m,*this,true)); - return store[m]; - } - - Real& RowVector::element(int n) - { - REPORT - if (n<0 || n>= ncols) Throw(IndexException(n,*this,true)); - return store[n]; - } - - Real RowVector::element(int n) const - { - REPORT - if (n<0 || n>= ncols) Throw(IndexException(n,*this,true)); - return store[n]; - } - - Real& BandMatrix::element(int m, int n) - { - REPORT - int w = upper+lower+1; int i = lower+n-m; - if (m<0 || m>= nrows || n<0 || n>= ncols || i<0 || i>=w) - Throw(IndexException(m,n,*this,true)); - return store[w*m+i]; - } - - Real BandMatrix::element(int m, int n) const - { - REPORT - int w = upper+lower+1; int i = lower+n-m; - if (m<0 || m>= nrows || n<0 || n>= ncols || i<0 || i>=w) - Throw(IndexException(m,n,*this,true)); - return store[w*m+i]; - } - - Real& UpperBandMatrix::element(int m, int n) - { - REPORT - int w = upper+1; int i = n-m; - if (m<0 || m>= nrows || n<0 || n>= ncols || i<0 || i>=w) - Throw(IndexException(m,n,*this,true)); - return store[w*m+i]; - } - - Real UpperBandMatrix::element(int m, int n) const - { - REPORT - int w = upper+1; int i = n-m; - if (m<0 || m>= nrows || n<0 || n>= ncols || i<0 || i>=w) - Throw(IndexException(m,n,*this,true)); - return store[w*m+i]; - } - - Real& LowerBandMatrix::element(int m, int n) - { - REPORT - int w = lower+1; int i = lower+n-m; - if (m<0 || m>= nrows || n<0 || n>= ncols || i<0 || i>=w) - Throw(IndexException(m,n,*this,true)); - return store[w*m+i]; - } - - Real LowerBandMatrix::element(int m, int n) const - { - REPORT - int w = lower+1; int i = lower+n-m; - if (m<0 || m>= nrows || n<0 || n>= ncols || i<0 || i>=w) - Throw(IndexException(m,n,*this,true)); - return store[w*m+i]; - } - - Real& SymmetricBandMatrix::element(int m, int n) - { - REPORT - int w = lower+1; - if (m>=n) - { - REPORT - int i = lower+n-m; - if ( m>=nrows || n<0 || i<0 ) - Throw(IndexException(m,n,*this,true)); - return store[w*m+i]; - } - else - { - REPORT - int i = lower+m-n; - if ( n>=nrows || m<0 || i<0 ) - Throw(IndexException(m,n,*this,true)); - return store[w*n+i]; - } - } - - Real SymmetricBandMatrix::element(int m, int n) const - { - REPORT - int w = lower+1; - if (m>=n) - { - REPORT - int i = lower+n-m; - if ( m>=nrows || n<0 || i<0 ) - Throw(IndexException(m,n,*this,true)); - return store[w*m+i]; - } - else - { - REPORT - int i = lower+m-n; - if ( n>=nrows || m<0 || i<0 ) - Throw(IndexException(m,n,*this,true)); - return store[w*n+i]; - } - } - -#ifdef use_namespace -} -#endif - diff --git a/lib/src/mixmod/NEWMAT/newmat7.cpp b/lib/src/mixmod/NEWMAT/newmat7.cpp deleted file mode 100644 index 2070973..0000000 --- a/lib/src/mixmod/NEWMAT/newmat7.cpp +++ /dev/null @@ -1,1052 +0,0 @@ -//$$ newmat7.cpp Invert, solve, binary operations - -// Copyright (C) 1991,2,3,4: R B Davies - -#include "include.h" - -#include "newmat.h" -#include "newmatrc.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - - -#ifdef DO_REPORT -#define REPORT { static ExeCounter ExeCount(__LINE__,7); ++ExeCount; } -#else -#define REPORT {} -#endif - - - //***************************** solve routines ******************************/ - - GeneralMatrix* GeneralMatrix::MakeSolver() - { - REPORT - GeneralMatrix* gm = new CroutMatrix(*this); - MatrixErrorNoSpace(gm); gm->ReleaseAndDelete(); return gm; - } - - GeneralMatrix* Matrix::MakeSolver() - { - REPORT - GeneralMatrix* gm = new CroutMatrix(*this); - MatrixErrorNoSpace(gm); gm->ReleaseAndDelete(); return gm; - } - - void CroutMatrix::Solver(MatrixColX& mcout, const MatrixColX& mcin) - { - REPORT - int i = mcin.skip; Real* el = mcin.data-i; Real* el1 = el; - while (i--) *el++ = 0.0; - el += mcin.storage; i = nrows - mcin.skip - mcin.storage; - while (i--) *el++ = 0.0; - lubksb(el1, mcout.skip); - } - - - // Do we need check for entirely zero output? - - void UpperTriangularMatrix::Solver(MatrixColX& mcout, - const MatrixColX& mcin) - { - REPORT - int i = mcin.skip-mcout.skip; Real* elx = mcin.data-i; - while (i-- > 0) *elx++ = 0.0; - int nr = mcin.skip+mcin.storage; - elx = mcin.data+mcin.storage; Real* el = elx; - int j = mcout.skip+mcout.storage-nr; int nc = ncols-nr; i = nr-mcout.skip; - while (j-- > 0) *elx++ = 0.0; - Real* Ael = store + (nr*(2*ncols-nr+1))/2; j = 0; - while (i-- > 0) - { - elx = el; Real sum = 0.0; int jx = j++; Ael -= nc; - while (jx--) sum += *(--Ael) * *(--elx); - elx--; *elx = (*elx - sum) / *(--Ael); - } - } - - void LowerTriangularMatrix::Solver(MatrixColX& mcout, - const MatrixColX& mcin) - { - REPORT - int i = mcin.skip-mcout.skip; Real* elx = mcin.data-i; - while (i-- > 0) *elx++ = 0.0; - int nc = mcin.skip; i = nc+mcin.storage; elx = mcin.data+mcin.storage; - int nr = mcout.skip+mcout.storage; int j = nr-i; i = nr-nc; - while (j-- > 0) *elx++ = 0.0; - Real* el = mcin.data; Real* Ael = store + (nc*(nc+1))/2; j = 0; - while (i-- > 0) - { - elx = el; Real sum = 0.0; int jx = j++; Ael += nc; - while (jx--) sum += *Ael++ * *elx++; - *elx = (*elx - sum) / *Ael++; - } - } - - //******************* carry out binary operations *************************/ - - static GeneralMatrix* - GeneralMult(GeneralMatrix*,GeneralMatrix*,MultipliedMatrix*,MatrixType); - static GeneralMatrix* - GeneralSolv(GeneralMatrix*,GeneralMatrix*,BaseMatrix*,MatrixType); - static GeneralMatrix* - GeneralSolvI(GeneralMatrix*,BaseMatrix*,MatrixType); - static GeneralMatrix* - GeneralKP(GeneralMatrix*,GeneralMatrix*,KPMatrix*,MatrixType); - - GeneralMatrix* MultipliedMatrix::Evaluate(MatrixType mt) - { - REPORT - gm2 = ((BaseMatrix*&)bm2)->Evaluate(); - gm2 = gm2->Evaluate(gm2->Type().MultRHS()); // no symmetric on RHS - gm1=((BaseMatrix*&)bm1)->Evaluate(); -#ifdef TEMPS_DESTROYED_QUICKLY - GeneralMatrix* gmx; - Try { gmx = GeneralMult(gm1, gm2, this, mt); } - CatchAll { delete this; ReThrow; } - delete this; return gmx; -#else - return GeneralMult(gm1, gm2, this, mt); -#endif - } - - GeneralMatrix* SolvedMatrix::Evaluate(MatrixType mt) - { - REPORT - gm1=((BaseMatrix*&)bm1)->Evaluate(); - gm2=((BaseMatrix*&)bm2)->Evaluate(); -#ifdef TEMPS_DESTROYED_QUICKLY - GeneralMatrix* gmx; - Try { gmx = GeneralSolv(gm1,gm2,this,mt); } - CatchAll { delete this; ReThrow; } - delete this; return gmx; -#else - return GeneralSolv(gm1,gm2,this,mt); -#endif - } - - GeneralMatrix* KPMatrix::Evaluate(MatrixType mt) - { - REPORT - gm1=((BaseMatrix*&)bm1)->Evaluate(); - gm2=((BaseMatrix*&)bm2)->Evaluate(); -#ifdef TEMPS_DESTROYED_QUICKLY - GeneralMatrix* gmx; - Try { gmx = GeneralKP(gm1,gm2,this,mt); } - CatchAll { delete this; ReThrow; } - delete this; return gmx; -#else - return GeneralKP(gm1,gm2,this,mt); -#endif - } - - // routines for adding or subtracting matrices of identical storage structure - - static void Add(GeneralMatrix* gm, GeneralMatrix* gm1, GeneralMatrix* gm2) - { - REPORT - Real* s1=gm1->Store(); Real* s2=gm2->Store(); - Real* s=gm->Store(); int i=gm->Storage() >> 2; - while (i--) - { - *s++ = *s1++ + *s2++; *s++ = *s1++ + *s2++; - *s++ = *s1++ + *s2++; *s++ = *s1++ + *s2++; - } - i=gm->Storage() & 3; while (i--) *s++ = *s1++ + *s2++; - } - - static void Add(GeneralMatrix* gm, GeneralMatrix* gm2) - { - REPORT - Real* s2=gm2->Store(); Real* s=gm->Store(); int i=gm->Storage() >> 2; - while (i--) - { *s++ += *s2++; *s++ += *s2++; *s++ += *s2++; *s++ += *s2++; } - i=gm->Storage() & 3; while (i--) *s++ += *s2++; - } - - static void Subtract(GeneralMatrix* gm, GeneralMatrix* gm1, GeneralMatrix* gm2) - { - REPORT - Real* s1=gm1->Store(); Real* s2=gm2->Store(); - Real* s=gm->Store(); int i=gm->Storage() >> 2; - while (i--) - { - *s++ = *s1++ - *s2++; *s++ = *s1++ - *s2++; - *s++ = *s1++ - *s2++; *s++ = *s1++ - *s2++; - } - i=gm->Storage() & 3; while (i--) *s++ = *s1++ - *s2++; - } - - static void Subtract(GeneralMatrix* gm, GeneralMatrix* gm2) - { - REPORT - Real* s2=gm2->Store(); Real* s=gm->Store(); int i=gm->Storage() >> 2; - while (i--) - { *s++ -= *s2++; *s++ -= *s2++; *s++ -= *s2++; *s++ -= *s2++; } - i=gm->Storage() & 3; while (i--) *s++ -= *s2++; - } - - static void ReverseSubtract(GeneralMatrix* gm, GeneralMatrix* gm2) - { - REPORT - Real* s2=gm2->Store(); Real* s=gm->Store(); int i=gm->Storage() >> 2; - while (i--) - { - *s = *s2++ - *s; s++; *s = *s2++ - *s; s++; - *s = *s2++ - *s; s++; *s = *s2++ - *s; s++; - } - i=gm->Storage() & 3; while (i--) { *s = *s2++ - *s; s++; } - } - - static void SP(GeneralMatrix* gm, GeneralMatrix* gm1, GeneralMatrix* gm2) - { - REPORT - Real* s1=gm1->Store(); Real* s2=gm2->Store(); - Real* s=gm->Store(); int i=gm->Storage() >> 2; - while (i--) - { - *s++ = *s1++ * *s2++; *s++ = *s1++ * *s2++; - *s++ = *s1++ * *s2++; *s++ = *s1++ * *s2++; - } - i=gm->Storage() & 3; while (i--) *s++ = *s1++ * *s2++; - } - - static void SP(GeneralMatrix* gm, GeneralMatrix* gm2) - { - REPORT - Real* s2=gm2->Store(); Real* s=gm->Store(); int i=gm->Storage() >> 2; - while (i--) - { *s++ *= *s2++; *s++ *= *s2++; *s++ *= *s2++; *s++ *= *s2++; } - i=gm->Storage() & 3; while (i--) *s++ *= *s2++; - } - - // routines for adding or subtracting matrices of different storage structure - - static void AddDS(GeneralMatrix* gm, GeneralMatrix* gm1, GeneralMatrix* gm2) - { - REPORT - int nr = gm->Nrows(); - MatrixRow mr1(gm1, LoadOnEntry); MatrixRow mr2(gm2, LoadOnEntry); - MatrixRow mr(gm, StoreOnExit+DirectPart); - while (nr--) { mr.Add(mr1,mr2); mr1.Next(); mr2.Next(); mr.Next(); } - } - - static void AddDS(GeneralMatrix* gm, GeneralMatrix* gm2) - // Add into first argument - { - REPORT - int nr = gm->Nrows(); - MatrixRow mr(gm, StoreOnExit+LoadOnEntry+DirectPart); - MatrixRow mr2(gm2, LoadOnEntry); - while (nr--) { mr.Add(mr2); mr.Next(); mr2.Next(); } - } - - static void SubtractDS - (GeneralMatrix* gm, GeneralMatrix* gm1, GeneralMatrix* gm2) - { - REPORT - int nr = gm->Nrows(); - MatrixRow mr1(gm1, LoadOnEntry); MatrixRow mr2(gm2, LoadOnEntry); - MatrixRow mr(gm, StoreOnExit+DirectPart); - while (nr--) { mr.Sub(mr1,mr2); mr1.Next(); mr2.Next(); mr.Next(); } - } - - static void SubtractDS(GeneralMatrix* gm, GeneralMatrix* gm2) - { - REPORT - int nr = gm->Nrows(); - MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart); - MatrixRow mr2(gm2, LoadOnEntry); - while (nr--) { mr.Sub(mr2); mr.Next(); mr2.Next(); } - } - - static void ReverseSubtractDS(GeneralMatrix* gm, GeneralMatrix* gm2) - { - REPORT - int nr = gm->Nrows(); - MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart); - MatrixRow mr2(gm2, LoadOnEntry); - while (nr--) { mr.RevSub(mr2); mr2.Next(); mr.Next(); } - } - - static void SPDS(GeneralMatrix* gm, GeneralMatrix* gm1, GeneralMatrix* gm2) - { - REPORT - int nr = gm->Nrows(); - MatrixRow mr1(gm1, LoadOnEntry); MatrixRow mr2(gm2, LoadOnEntry); - MatrixRow mr(gm, StoreOnExit+DirectPart); - while (nr--) { mr.Multiply(mr1,mr2); mr1.Next(); mr2.Next(); mr.Next(); } - } - - static void SPDS(GeneralMatrix* gm, GeneralMatrix* gm2) - // SP into first argument - { - REPORT - int nr = gm->Nrows(); - MatrixRow mr(gm, StoreOnExit+LoadOnEntry+DirectPart); - MatrixRow mr2(gm2, LoadOnEntry); - while (nr--) { mr.Multiply(mr2); mr.Next(); mr2.Next(); } - } - - static GeneralMatrix* GeneralMult1(GeneralMatrix* gm1, GeneralMatrix* gm2, - MultipliedMatrix* mm, MatrixType mtx) - { - REPORT - Tracer tr("GeneralMult1"); - int nr=gm1->Nrows(); int nc=gm2->Ncols(); - if (gm1->Ncols() !=gm2->Nrows()) - Throw(IncompatibleDimensionsException(*gm1, *gm2)); - GeneralMatrix* gmx = mtx.New(nr,nc,mm); - - MatrixCol mcx(gmx, StoreOnExit+DirectPart); - MatrixCol mc2(gm2, LoadOnEntry); - while (nc--) - { - MatrixRow mr1(gm1, LoadOnEntry, mcx.Skip()); - Real* el = mcx.Data(); // pointer to an element - int n = mcx.Storage(); - while (n--) { *(el++) = DotProd(mr1,mc2); mr1.Next(); } - mc2.Next(); mcx.Next(); - } - gmx->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); return gmx; - } - - static GeneralMatrix* GeneralMult2(GeneralMatrix* gm1, GeneralMatrix* gm2, - MultipliedMatrix* mm, MatrixType mtx) - { - // version that accesses by row only - not good for thin matrices - // or column vectors in right hand term. - REPORT - Tracer tr("GeneralMult2"); - int nr=gm1->Nrows(); int nc=gm2->Ncols(); - if (gm1->Ncols() !=gm2->Nrows()) - Throw(IncompatibleDimensionsException(*gm1, *gm2)); - GeneralMatrix* gmx = mtx.New(nr,nc,mm); - - MatrixRow mrx(gmx, LoadOnEntry+StoreOnExit+DirectPart); - MatrixRow mr1(gm1, LoadOnEntry); - while (nr--) - { - MatrixRow mr2(gm2, LoadOnEntry, mr1.Skip()); - Real* el = mr1.Data(); // pointer to an element - int n = mr1.Storage(); - mrx.Zero(); - while (n--) { mrx.AddScaled(mr2, *el++); mr2.Next(); } - mr1.Next(); mrx.Next(); - } - gmx->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); return gmx; - } - - static GeneralMatrix* mmMult(GeneralMatrix* gm1, GeneralMatrix* gm2) - { - // matrix multiplication for type Matrix only - REPORT - Tracer tr("MatrixMult"); - - int nr=gm1->Nrows(); int ncr=gm1->Ncols(); int nc=gm2->Ncols(); - if (ncr != gm2->Nrows()) Throw(IncompatibleDimensionsException(*gm1,*gm2)); - - Matrix* gm = new Matrix(nr,nc); MatrixErrorNoSpace(gm); - - Real* s1=gm1->Store(); Real* s2=gm2->Store(); Real* s=gm->Store(); - - if (ncr) - { - while (nr--) - { - Real* s2x = s2; int j = ncr; - Real* sx = s; Real f = *s1++; int k = nc; - while (k--) *sx++ = f * *s2x++; - while (--j) - { sx = s; f = *s1++; k = nc; while (k--) *sx++ += f * *s2x++; } - s = sx; - } - } - else *gm = 0.0; - - gm->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); return gm; - } - - static GeneralMatrix* GeneralMult(GeneralMatrix* gm1, GeneralMatrix* gm2, - MultipliedMatrix* mm, MatrixType mtx) - { - if ( Rectangular(gm1->Type(), gm2->Type(), mtx)) - { - REPORT - return mmMult(gm1, gm2); - } - else - { - REPORT - Compare(gm1->Type() * gm2->Type(),mtx); - int nr = gm2->Nrows(); int nc = gm2->Ncols(); - if (nc <= 5 && nr > nc) { REPORT return GeneralMult1(gm1, gm2, mm, mtx); } - else { REPORT return GeneralMult2(gm1, gm2, mm, mtx); } - } - } - - static GeneralMatrix* GeneralKP(GeneralMatrix* gm1, GeneralMatrix* gm2, - KPMatrix* kp, MatrixType mtx) - { - REPORT - Tracer tr("GeneralKP"); - int nr1 = gm1->Nrows(); int nc1 = gm1->Ncols(); - int nr2 = gm2->Nrows(); int nc2 = gm2->Ncols(); - Compare((gm1->Type()).KP(gm2->Type()),mtx); - GeneralMatrix* gmx = mtx.New(nr1*nr2, nc1*nc2, kp); - MatrixRow mrx(gmx, LoadOnEntry+StoreOnExit+DirectPart); - MatrixRow mr1(gm1, LoadOnEntry); - for (int i = 1; i <= nr1; ++i) - { - MatrixRow mr2(gm2, LoadOnEntry); - for (int j = 1; j <= nr2; ++j) - { mrx.KP(mr1,mr2); mr2.Next(); mrx.Next(); } - mr1.Next(); - } - gmx->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); return gmx; - } - - static GeneralMatrix* GeneralSolv(GeneralMatrix* gm1, GeneralMatrix* gm2, - BaseMatrix* sm, MatrixType mtx) - { - REPORT - Tracer tr("GeneralSolv"); - Compare(gm1->Type().i() * gm2->Type(),mtx); - int nr = gm1->Nrows(); - if (nr != gm1->Ncols()) Throw(NotSquareException(*gm1)); - int nc = gm2->Ncols(); - if (gm1->Ncols() != gm2->Nrows()) - Throw(IncompatibleDimensionsException(*gm1, *gm2)); - GeneralMatrix* gmx = mtx.New(nr,nc,sm); MatrixErrorNoSpace(gmx); - Real* r = new Real [nr]; MatrixErrorNoSpace(r); - MONITOR_REAL_NEW("Make (GenSolv)",nr,r) - GeneralMatrix* gms = gm1->MakeSolver(); - Try - { - - MatrixColX mcx(gmx, r, StoreOnExit+DirectPart); // copy to and from r - // this must be inside Try so mcx is destroyed before gmx - MatrixColX mc2(gm2, r, LoadOnEntry); - while (nc--) { gms->Solver(mcx, mc2); mcx.Next(); mc2.Next(); } - } - CatchAll - { - if (gms) gms->tDelete(); - delete gmx; // <-------------------- - gm2->tDelete(); - MONITOR_REAL_DELETE("Delete (GenSolv)",nr,r) - // ATandT version 2.1 gives an internal error - delete [] r; - ReThrow; - } - gms->tDelete(); gmx->ReleaseAndDelete(); gm2->tDelete(); - MONITOR_REAL_DELETE("Delete (GenSolv)",nr,r) - // ATandT version 2.1 gives an internal error - delete [] r; - return gmx; - } - - // version for inverses - gm2 is identity - static GeneralMatrix* GeneralSolvI(GeneralMatrix* gm1, BaseMatrix* sm, - MatrixType mtx) - { - REPORT - Tracer tr("GeneralSolvI"); - Compare(gm1->Type().i(),mtx); - int nr = gm1->Nrows(); - if (nr != gm1->Ncols()) Throw(NotSquareException(*gm1)); - int nc = nr; - // DiagonalMatrix I(nr); I = 1; - IdentityMatrix I(nr); - GeneralMatrix* gmx = mtx.New(nr,nc,sm); MatrixErrorNoSpace(gmx); - Real* r = new Real [nr]; MatrixErrorNoSpace(r); - MONITOR_REAL_NEW("Make (GenSolvI)",nr,r) - GeneralMatrix* gms = gm1->MakeSolver(); - Try - { - - MatrixColX mcx(gmx, r, StoreOnExit+DirectPart); // copy to and from r - // this must be inside Try so mcx is destroyed before gmx - MatrixColX mc2(&I, r, LoadOnEntry); - while (nc--) { gms->Solver(mcx, mc2); mcx.Next(); mc2.Next(); } - } - CatchAll - { - if (gms) gms->tDelete(); - delete gmx; - MONITOR_REAL_DELETE("Delete (GenSolvI)",nr,r) - // ATandT version 2.1 gives an internal error - delete [] r; - ReThrow; - } - gms->tDelete(); gmx->ReleaseAndDelete(); - MONITOR_REAL_DELETE("Delete (GenSolvI)",nr,r) - // ATandT version 2.1 gives an internal error - delete [] r; - return gmx; - } - - GeneralMatrix* InvertedMatrix::Evaluate(MatrixType mtx) - { - // Matrix Inversion - use solve routines - Tracer tr("InvertedMatrix::Evaluate"); - REPORT - gm=((BaseMatrix*&)bm)->Evaluate(); -#ifdef TEMPS_DESTROYED_QUICKLY - GeneralMatrix* gmx; - Try { gmx = GeneralSolvI(gm,this,mtx); } - CatchAll { delete this; ReThrow; } - delete this; return gmx; -#else - return GeneralSolvI(gm,this,mtx); -#endif - } - - //*************************** New versions ************************ - - GeneralMatrix* AddedMatrix::Evaluate(MatrixType mtd) - { - REPORT - Tracer tr("AddedMatrix::Evaluate"); - gm1=((BaseMatrix*&)bm1)->Evaluate(); gm2=((BaseMatrix*&)bm2)->Evaluate(); - int nr=gm1->Nrows(); int nc=gm1->Ncols(); - if (nr!=gm2->Nrows() || nc!=gm2->Ncols()) - { - Try { Throw(IncompatibleDimensionsException(*gm1, *gm2)); } - CatchAll - { - gm1->tDelete(); gm2->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - ReThrow; - } - } - MatrixType mt1 = gm1->Type(), mt2 = gm2->Type(); MatrixType mts = mt1 + mt2; - if (!mtd) { REPORT mtd = mts; } - else if (!(mtd.DataLossOK || mtd >= mts)) - { - REPORT - gm1->tDelete(); gm2->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - Throw(ProgramException("Illegal Conversion", mts, mtd)); - } - GeneralMatrix* gmx; - bool c1 = (mtd == mt1), c2 = (mtd == mt2); - if ( c1 && c2 && (gm1->SimpleAddOK(gm2) == 0) ) - { - if (gm1->reuse()) { REPORT Add(gm1,gm2); gm2->tDelete(); gmx = gm1; } - else if (gm2->reuse()) { REPORT Add(gm2,gm1); gmx = gm2; } - else - { - REPORT - // what if new throws an exception - Try { gmx = mt1.New(nr,nc,this); } - CatchAll - { -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - ReThrow; - } - gmx->ReleaseAndDelete(); Add(gmx,gm1,gm2); - } - } - else - { - if (c1 && c2) - { - short SAO = gm1->SimpleAddOK(gm2); - if (SAO & 1) { REPORT c1 = false; } - if (SAO & 2) { REPORT c2 = false; } - } - if (c1 && gm1->reuse() ) // must have type test first - { REPORT AddDS(gm1,gm2); gm2->tDelete(); gmx = gm1; } - else if (c2 && gm2->reuse() ) - { REPORT AddDS(gm2,gm1); if (!c1) gm1->tDelete(); gmx = gm2; } - else - { - REPORT - Try { gmx = mtd.New(nr,nc,this); } - CatchAll - { - if (!c1) gm1->tDelete(); if (!c2) gm2->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - ReThrow; - } - AddDS(gmx,gm1,gm2); - if (!c1) gm1->tDelete(); if (!c2) gm2->tDelete(); - gmx->ReleaseAndDelete(); - } - } -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - return gmx; - } - - GeneralMatrix* SubtractedMatrix::Evaluate(MatrixType mtd) - { - REPORT - Tracer tr("SubtractedMatrix::Evaluate"); - gm1=((BaseMatrix*&)bm1)->Evaluate(); gm2=((BaseMatrix*&)bm2)->Evaluate(); - int nr=gm1->Nrows(); int nc=gm1->Ncols(); - if (nr!=gm2->Nrows() || nc!=gm2->Ncols()) - { - Try { Throw(IncompatibleDimensionsException(*gm1, *gm2)); } - CatchAll - { - gm1->tDelete(); gm2->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - ReThrow; - } - } - MatrixType mt1 = gm1->Type(), mt2 = gm2->Type(); MatrixType mts = mt1 + mt2; - if (!mtd) { REPORT mtd = mts; } - else if (!(mtd.DataLossOK || mtd >= mts)) - { - gm1->tDelete(); gm2->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - Throw(ProgramException("Illegal Conversion", mts, mtd)); - } - GeneralMatrix* gmx; - bool c1 = (mtd == mt1), c2 = (mtd == mt2); - if ( c1 && c2 && (gm1->SimpleAddOK(gm2) == 0) ) - { - if (gm1->reuse()) { REPORT Subtract(gm1,gm2); gm2->tDelete(); gmx = gm1; } - else if (gm2->reuse()) { REPORT ReverseSubtract(gm2,gm1); gmx = gm2; } - else - { - REPORT - Try { gmx = mt1.New(nr,nc,this); } - CatchAll - { -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - ReThrow; - } - gmx->ReleaseAndDelete(); Subtract(gmx,gm1,gm2); - } - } - else - { - if (c1 && c2) - { - short SAO = gm1->SimpleAddOK(gm2); - if (SAO & 1) { REPORT c1 = false; } - if (SAO & 2) { REPORT c2 = false; } - } - if (c1 && gm1->reuse() ) // must have type test first - { REPORT SubtractDS(gm1,gm2); gm2->tDelete(); gmx = gm1; } - else if (c2 && gm2->reuse() ) - { - REPORT ReverseSubtractDS(gm2,gm1); - if (!c1) gm1->tDelete(); gmx = gm2; - } - else - { - REPORT - // what if New throws and exception - Try { gmx = mtd.New(nr,nc,this); } - CatchAll - { - if (!c1) gm1->tDelete(); if (!c2) gm2->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - ReThrow; - } - SubtractDS(gmx,gm1,gm2); - if (!c1) gm1->tDelete(); if (!c2) gm2->tDelete(); - gmx->ReleaseAndDelete(); - } - } -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - return gmx; - } - - GeneralMatrix* SPMatrix::Evaluate(MatrixType mtd) - { - REPORT - Tracer tr("SPMatrix::Evaluate"); - gm1=((BaseMatrix*&)bm1)->Evaluate(); gm2=((BaseMatrix*&)bm2)->Evaluate(); - int nr=gm1->Nrows(); int nc=gm1->Ncols(); - if (nr!=gm2->Nrows() || nc!=gm2->Ncols()) - { - Try { Throw(IncompatibleDimensionsException(*gm1, *gm2)); } - CatchAll - { - gm1->tDelete(); gm2->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - ReThrow; - } - } - MatrixType mt1 = gm1->Type(), mt2 = gm2->Type(); - MatrixType mts = mt1.SP(mt2); - if (!mtd) { REPORT mtd = mts; } - else if (!(mtd.DataLossOK || mtd >= mts)) - { - gm1->tDelete(); gm2->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - Throw(ProgramException("Illegal Conversion", mts, mtd)); - } - GeneralMatrix* gmx; - bool c1 = (mtd == mt1), c2 = (mtd == mt2); - if ( c1 && c2 && (gm1->SimpleAddOK(gm2) == 0) ) - { - if (gm1->reuse()) { REPORT SP(gm1,gm2); gm2->tDelete(); gmx = gm1; } - else if (gm2->reuse()) { REPORT SP(gm2,gm1); gmx = gm2; } - else - { - REPORT - Try { gmx = mt1.New(nr,nc,this); } - CatchAll - { -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - ReThrow; - } - gmx->ReleaseAndDelete(); SP(gmx,gm1,gm2); - } - } - else - { - if (c1 && c2) - { - short SAO = gm1->SimpleAddOK(gm2); - if (SAO & 1) { REPORT c2 = false; } // c1 and c2 swapped - if (SAO & 2) { REPORT c1 = false; } - } - if (c1 && gm1->reuse() ) // must have type test first - { REPORT SPDS(gm1,gm2); gm2->tDelete(); gmx = gm1; } - else if (c2 && gm2->reuse() ) - { REPORT SPDS(gm2,gm1); if (!c1) gm1->tDelete(); gmx = gm2; } - else - { - REPORT - // what if New throws and exception - Try { gmx = mtd.New(nr,nc,this); } - CatchAll - { - if (!c1) gm1->tDelete(); if (!c2) gm2->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - ReThrow; - } - SPDS(gmx,gm1,gm2); - if (!c1) gm1->tDelete(); if (!c2) gm2->tDelete(); - gmx->ReleaseAndDelete(); - } - } -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - return gmx; - } - - - - //*************************** norm functions ****************************/ - - Real BaseMatrix::Norm1() const - { - // maximum of sum of absolute values of a column - REPORT - GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); - int nc = gm->Ncols(); Real value = 0.0; - MatrixCol mc(gm, LoadOnEntry); - while (nc--) - { Real v = mc.SumAbsoluteValue(); if (value < v) value = v; mc.Next(); } - gm->tDelete(); return value; - } - - Real BaseMatrix::NormInfinity() const - { - // maximum of sum of absolute values of a row - REPORT - GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); - int nr = gm->Nrows(); Real value = 0.0; - MatrixRow mr(gm, LoadOnEntry); - while (nr--) - { Real v = mr.SumAbsoluteValue(); if (value < v) value = v; mr.Next(); } - gm->tDelete(); return value; - } - - //********************** Concatenation and stacking *************************/ - - GeneralMatrix* ConcatenatedMatrix::Evaluate(MatrixType mtx) - { - REPORT - Tracer tr("Concatenate"); -#ifdef TEMPS_DESTROYED_QUICKLY - Try - { - gm2 = ((BaseMatrix*&)bm2)->Evaluate(); - gm1 = ((BaseMatrix*&)bm1)->Evaluate(); - Compare(gm1->Type() | gm2->Type(),mtx); - int nr=gm1->Nrows(); int nc = gm1->Ncols() + gm2->Ncols(); - if (nr != gm2->Nrows()) - Throw(IncompatibleDimensionsException(*gm1, *gm2)); - GeneralMatrix* gmx = mtx.New(nr,nc,this); - MatrixRow mr1(gm1, LoadOnEntry); MatrixRow mr2(gm2, LoadOnEntry); - MatrixRow mr(gmx, StoreOnExit+DirectPart); - while (nr--) { mr.ConCat(mr1,mr2); mr1.Next(); mr2.Next(); mr.Next(); } - gmx->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); delete this; - return gmx; - } - CatchAll { delete this; ReThrow; } -#ifndef UseExceptions - return 0; -#endif -#else - gm2 = ((BaseMatrix*&)bm2)->Evaluate(); - gm1 = ((BaseMatrix*&)bm1)->Evaluate(); - Compare(gm1->Type() | gm2->Type(),mtx); - int nr=gm1->Nrows(); int nc = gm1->Ncols() + gm2->Ncols(); - if (nr != gm2->Nrows()) - Throw(IncompatibleDimensionsException(*gm1, *gm2)); - GeneralMatrix* gmx = mtx.New(nr,nc,this); - MatrixRow mr1(gm1, LoadOnEntry); MatrixRow mr2(gm2, LoadOnEntry); - MatrixRow mr(gmx, StoreOnExit+DirectPart); - while (nr--) { mr.ConCat(mr1,mr2); mr1.Next(); mr2.Next(); mr.Next(); } - gmx->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); return gmx; -#endif - } - - GeneralMatrix* StackedMatrix::Evaluate(MatrixType mtx) - { - REPORT - Tracer tr("Stack"); -#ifdef TEMPS_DESTROYED_QUICKLY - Try - { - gm2 = ((BaseMatrix*&)bm2)->Evaluate(); - gm1 = ((BaseMatrix*&)bm1)->Evaluate(); - Compare(gm1->Type() & gm2->Type(),mtx); - int nc=gm1->Ncols(); - int nr1 = gm1->Nrows(); int nr2 = gm2->Nrows(); - if (nc != gm2->Ncols()) - Throw(IncompatibleDimensionsException(*gm1, *gm2)); - GeneralMatrix* gmx = mtx.New(nr1+nr2,nc,this); - MatrixRow mr1(gm1, LoadOnEntry); MatrixRow mr2(gm2, LoadOnEntry); - MatrixRow mr(gmx, StoreOnExit+DirectPart); - while (nr1--) { mr.Copy(mr1); mr1.Next(); mr.Next(); } - while (nr2--) { mr.Copy(mr2); mr2.Next(); mr.Next(); } - gmx->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); delete this; - return gmx; - } - CatchAll { delete this; ReThrow; } -#ifndef UseExceptions - return 0; -#endif -#else - gm2 = ((BaseMatrix*&)bm2)->Evaluate(); - gm1 = ((BaseMatrix*&)bm1)->Evaluate(); - Compare(gm1->Type() & gm2->Type(),mtx); - int nc=gm1->Ncols(); - int nr1 = gm1->Nrows(); int nr2 = gm2->Nrows(); - if (nc != gm2->Ncols()) - Throw(IncompatibleDimensionsException(*gm1, *gm2)); - GeneralMatrix* gmx = mtx.New(nr1+nr2,nc,this); - MatrixRow mr1(gm1, LoadOnEntry); MatrixRow mr2(gm2, LoadOnEntry); - MatrixRow mr(gmx, StoreOnExit+DirectPart); - while (nr1--) { mr.Copy(mr1); mr1.Next(); mr.Next(); } - while (nr2--) { mr.Copy(mr2); mr2.Next(); mr.Next(); } - gmx->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); return gmx; -#endif - } - - // ************************* equality of matrices ******************** // - - static bool RealEqual(Real* s1, Real* s2, int n) - { - int i = n >> 2; - while (i--) - { - if (*s1++ != *s2++) return false; if (*s1++ != *s2++) return false; - if (*s1++ != *s2++) return false; if (*s1++ != *s2++) return false; - } - i = n & 3; while (i--) if (*s1++ != *s2++) return false; - return true; - } - - static bool intEqual(int* s1, int* s2, int n) - { - int i = n >> 2; - while (i--) - { - if (*s1++ != *s2++) return false; if (*s1++ != *s2++) return false; - if (*s1++ != *s2++) return false; if (*s1++ != *s2++) return false; - } - i = n & 3; while (i--) if (*s1++ != *s2++) return false; - return true; - } - - - bool operator==(const BaseMatrix& A, const BaseMatrix& B) - { - Tracer tr("BaseMatrix =="); - REPORT - GeneralMatrix* gmA = ((BaseMatrix&)A).Evaluate(); - GeneralMatrix* gmB = ((BaseMatrix&)B).Evaluate(); - - if (gmA == gmB) // same matrix - { REPORT gmA->tDelete(); return true; } - - if ( gmA->Nrows() != gmB->Nrows() || gmA->Ncols() != gmB->Ncols() ) - // different dimensions - { REPORT gmA->tDelete(); gmB->tDelete(); return false; } - - // check for CroutMatrix or BandLUMatrix - MatrixType AType = gmA->Type(); MatrixType BType = gmB->Type(); - if (AType.CannotConvert() || BType.CannotConvert() ) - { - REPORT - bool bx = gmA->IsEqual(*gmB); - gmA->tDelete(); gmB->tDelete(); - return bx; - } - - // is matrix storage the same - // will need to modify if further matrix structures are introduced - if (AType == BType && gmA->BandWidth() == gmB->BandWidth()) - { // compare store - REPORT - bool bx = RealEqual(gmA->Store(),gmB->Store(),gmA->Storage()); - gmA->tDelete(); gmB->tDelete(); - return bx; - } - - // matrix storage different - just subtract - REPORT return IsZero(*gmA-*gmB); - } - - bool operator==(const GeneralMatrix& A, const GeneralMatrix& B) - { - Tracer tr("GeneralMatrix =="); - // May or may not call tDeletes - REPORT - - if (&A == &B) // same matrix - { REPORT return true; } - - if ( A.Nrows() != B.Nrows() || A.Ncols() != B.Ncols() ) - { REPORT return false; } // different dimensions - - // check for CroutMatrix or BandLUMatrix - MatrixType AType = A.Type(); MatrixType BType = B.Type(); - if (AType.CannotConvert() || BType.CannotConvert() ) - { REPORT return A.IsEqual(B); } - - // is matrix storage the same - // will need to modify if further matrix structures are introduced - if (AType == BType && A.BandWidth() == B.BandWidth()) - { REPORT return RealEqual(A.Store(),B.Store(),A.Storage()); } - - // matrix storage different - just subtract - REPORT return IsZero(A-B); - } - - bool GeneralMatrix::IsZero() const - { - REPORT - Real* s=store; int i = storage >> 2; - while (i--) - { - if (*s++) return false; if (*s++) return false; - if (*s++) return false; if (*s++) return false; - } - i = storage & 3; while (i--) if (*s++) return false; - return true; - } - - bool IsZero(const BaseMatrix& A) - { - Tracer tr("BaseMatrix::IsZero"); - REPORT - GeneralMatrix* gm1 = 0; bool bx; - Try { gm1=((BaseMatrix&)A).Evaluate(); bx = gm1->IsZero(); } - CatchAll { if (gm1) gm1->tDelete(); ReThrow; } - gm1->tDelete(); - return bx; - } - - // IsEqual functions - insist matrices are of same type - // as well as equal values to be equal - - bool GeneralMatrix::IsEqual(const GeneralMatrix& A) const - { - Tracer tr("GeneralMatrix IsEqual"); - if (A.Type() != Type()) // not same types - { REPORT return false; } - if (&A == this) // same matrix - { REPORT return true; } - if (A.nrows != nrows || A.ncols != ncols) - // different dimensions - { REPORT return false; } - // is matrix storage the same - compare store - REPORT - return RealEqual(A.store,store,storage); - } - - bool CroutMatrix::IsEqual(const GeneralMatrix& A) const - { - Tracer tr("CroutMatrix IsEqual"); - if (A.Type() != Type()) // not same types - { REPORT return false; } - if (&A == this) // same matrix - { REPORT return true; } - if (A.nrows != nrows || A.ncols != ncols) - // different dimensions - { REPORT return false; } - // is matrix storage the same - compare store - REPORT - return RealEqual(A.store,store,storage) - && intEqual(((CroutMatrix&)A).indx, indx, nrows); - } - - - bool BandLUMatrix::IsEqual(const GeneralMatrix& A) const - { - Tracer tr("BandLUMatrix IsEqual"); - if (A.Type() != Type()) // not same types - { REPORT return false; } - if (&A == this) // same matrix - { REPORT return true; } - if ( A.Nrows() != nrows || A.Ncols() != ncols - || ((BandLUMatrix&)A).m1 != m1 || ((BandLUMatrix&)A).m2 != m2 ) - // different dimensions - { REPORT return false; } - - // matrix storage the same - compare store - REPORT - return RealEqual(A.Store(),store,storage) - && RealEqual(((BandLUMatrix&)A).store2,store2,storage2) - && intEqual(((BandLUMatrix&)A).indx, indx, nrows); - } - - -#ifdef use_namespace -} -#endif - - diff --git a/lib/src/mixmod/NEWMAT/newmat8.cpp b/lib/src/mixmod/NEWMAT/newmat8.cpp deleted file mode 100644 index e9ea28b..0000000 --- a/lib/src/mixmod/NEWMAT/newmat8.cpp +++ /dev/null @@ -1,734 +0,0 @@ -//$$ newmat8.cpp Advanced LU transform, scalar functions - -// Copyright (C) 1991,2,3,4,8: R B Davies - -#define WANT_MATH - -#include "include.h" - -#include "newmat.h" -#include "newmatrc.h" -#include "precisio.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - - -#ifdef DO_REPORT -#define REPORT { static ExeCounter ExeCount(__LINE__,8); ++ExeCount; } -#else -#define REPORT {} -#endif - - - /************************** LU transformation ****************************/ - - void CroutMatrix::ludcmp() - // LU decomposition from Golub & Van Loan, algorithm 3.4.1, (the "outer - // product" version). - // This replaces the code derived from Numerical Recipes in C in previous - // versions of newmat and being row oriented runs much faster with large - // matrices. - { - REPORT - Tracer trace( "Crout(ludcmp)" ); sing = false; - Real* akk = store; // runs down diagonal - - Real big = fabs(*akk); int mu = 0; Real* ai = akk; int k; - - for (k = 1; k < nrows; k++) - { - ai += nrows; const Real trybig = fabs(*ai); - if (big < trybig) { big = trybig; mu = k; } - } - - - if (nrows) for (k = 0;;) - { - /* - int mu1; - { - Real big = fabs(*akk); mu1 = k; Real* ai = akk; int i; - - for (i = k+1; i < nrows; i++) - { - ai += nrows; const Real trybig = fabs(*ai); - if (big < trybig) { big = trybig; mu1 = i; } - } - } - if (mu1 != mu) cout << k << " " << mu << " " << mu1 << endl; - */ - - indx[k] = mu; - - if (mu != k) //row swap - { - Real* a1 = store + nrows * k; Real* a2 = store + nrows * mu; d = !d; - int j = nrows; - while (j--) { const Real temp = *a1; *a1++ = *a2; *a2++ = temp; } - } - - Real diag = *akk; big = 0; mu = k + 1; - if (diag != 0) - { - ai = akk; int i = nrows - k - 1; - while (i--) - { - ai += nrows; Real* al = ai; Real mult = *al / diag; *al = mult; - int l = nrows - k - 1; Real* aj = akk; - // work out the next pivot as part of this loop - // this saves a column operation - if (l-- != 0) - { - *(++al) -= (mult * *(++aj)); - const Real trybig = fabs(*al); - if (big < trybig) { big = trybig; mu = nrows - i - 1; } - while (l--) *(++al) -= (mult * *(++aj)); - } - } - } - else sing = true; - if (++k == nrows) break; // so next line won't overflow - akk += nrows + 1; - } - } - - void CroutMatrix::lubksb(Real* B, int mini) - { - REPORT - // this has been adapted from Numerical Recipes in C. The code has been - // substantially streamlined, so I do not think much of the original - // copyright remains. However there is not much opportunity for - // variation in the code, so it is still similar to the NR code. - // I follow the NR code in skipping over initial zeros in the B vector. - - Tracer trace("Crout(lubksb)"); - if (sing) Throw(SingularException(*this)); - int i, j, ii = nrows; // ii initialised : B might be all zeros - - - // scan for first non-zero in B - for (i = 0; i < nrows; i++) - { - int ip = indx[i]; Real temp = B[ip]; B[ip] = B[i]; B[i] = temp; - if (temp != 0.0) { ii = i; break; } - } - - Real* bi; Real* ai; - i = ii + 1; - - if (i < nrows) - { - bi = B + ii; ai = store + ii + i * nrows; - for (;;) - { - int ip = indx[i]; Real sum = B[ip]; B[ip] = B[i]; - Real* aij = ai; Real* bj = bi; j = i - ii; - while (j--) sum -= *aij++ * *bj++; - B[i] = sum; - if (++i == nrows) break; - ai += nrows; - } - } - - ai = store + nrows * nrows; - - for (i = nrows - 1; i >= mini; i--) - { - Real* bj = B+i; ai -= nrows; Real* ajx = ai+i; - Real sum = *bj; Real diag = *ajx; - j = nrows - i; while(--j) sum -= *(++ajx) * *(++bj); - B[i] = sum / diag; - } - } - - /****************************** scalar functions ****************************/ - - inline Real square(Real x) { return x*x; } - - Real GeneralMatrix::SumSquare() const - { - REPORT - Real sum = 0.0; int i = storage; Real* s = store; - while (i--) sum += square(*s++); - ((GeneralMatrix&)*this).tDelete(); return sum; - } - - Real GeneralMatrix::SumAbsoluteValue() const - { - REPORT - Real sum = 0.0; int i = storage; Real* s = store; - while (i--) sum += fabs(*s++); - ((GeneralMatrix&)*this).tDelete(); return sum; - } - - Real GeneralMatrix::Sum() const - { - REPORT - Real sum = 0.0; int i = storage; Real* s = store; - while (i--) sum += *s++; - ((GeneralMatrix&)*this).tDelete(); return sum; - } - - // maxima and minima - - // There are three sets of routines - // MaximumAbsoluteValue, MinimumAbsoluteValue, Maximum, Minimum - // ... these find just the maxima and minima - // MaximumAbsoluteValue1, MinimumAbsoluteValue1, Maximum1, Minimum1 - // ... these find the maxima and minima and their locations in a - // one dimensional object - // MaximumAbsoluteValue2, MinimumAbsoluteValue2, Maximum2, Minimum2 - // ... these find the maxima and minima and their locations in a - // two dimensional object - - // If the matrix has no values throw an exception - - // If we do not want the location find the maximum or minimum on the - // array stored by GeneralMatrix - // This won't work for BandMatrices. We call ClearCorner for - // MaximumAbsoluteValue but for the others use the AbsoluteMinimumValue2 - // version and discard the location. - - // For one dimensional objects, when we want the location of the - // maximum or minimum, work with the array stored by GeneralMatrix - - // For two dimensional objects where we want the location of the maximum or - // minimum proceed as follows: - - // For rectangular matrices use the array stored by GeneralMatrix and - // deduce the location from the location in the GeneralMatrix - - // For other two dimensional matrices use the Matrix Row routine to find the - // maximum or minimum for each row. - - static void NullMatrixError(const GeneralMatrix* gm) - { - ((GeneralMatrix&)*gm).tDelete(); - Throw(ProgramException("Maximum or minimum of null matrix")); - } - - Real GeneralMatrix::MaximumAbsoluteValue() const - { - REPORT - if (storage == 0) NullMatrixError(this); - Real maxval = 0.0; int l = storage; Real* s = store; - while (l--) { Real a = fabs(*s++); if (maxval < a) maxval = a; } - ((GeneralMatrix&)*this).tDelete(); return maxval; - } - - Real GeneralMatrix::MaximumAbsoluteValue1(int& i) const - { - REPORT - if (storage == 0) NullMatrixError(this); - Real maxval = 0.0; int l = storage; Real* s = store; int li = storage; - while (l--) - { Real a = fabs(*s++); if (maxval <= a) { maxval = a; li = l; } } - i = storage - li; - ((GeneralMatrix&)*this).tDelete(); return maxval; - } - - Real GeneralMatrix::MinimumAbsoluteValue() const - { - REPORT - if (storage == 0) NullMatrixError(this); - int l = storage - 1; Real* s = store; Real minval = fabs(*s++); - while (l--) { Real a = fabs(*s++); if (minval > a) minval = a; } - ((GeneralMatrix&)*this).tDelete(); return minval; - } - - Real GeneralMatrix::MinimumAbsoluteValue1(int& i) const - { - REPORT - if (storage == 0) NullMatrixError(this); - int l = storage - 1; Real* s = store; Real minval = fabs(*s++); int li = l; - while (l--) - { Real a = fabs(*s++); if (minval >= a) { minval = a; li = l; } } - i = storage - li; - ((GeneralMatrix&)*this).tDelete(); return minval; - } - - Real GeneralMatrix::Maximum() const - { - REPORT - if (storage == 0) NullMatrixError(this); - int l = storage - 1; Real* s = store; Real maxval = *s++; - while (l--) { Real a = *s++; if (maxval < a) maxval = a; } - ((GeneralMatrix&)*this).tDelete(); return maxval; - } - - Real GeneralMatrix::Maximum1(int& i) const - { - REPORT - if (storage == 0) NullMatrixError(this); - int l = storage - 1; Real* s = store; Real maxval = *s++; int li = l; - while (l--) { Real a = *s++; if (maxval <= a) { maxval = a; li = l; } } - i = storage - li; - ((GeneralMatrix&)*this).tDelete(); return maxval; - } - - Real GeneralMatrix::Minimum() const - { - REPORT - if (storage == 0) NullMatrixError(this); - int l = storage - 1; Real* s = store; Real minval = *s++; - while (l--) { Real a = *s++; if (minval > a) minval = a; } - ((GeneralMatrix&)*this).tDelete(); return minval; - } - - Real GeneralMatrix::Minimum1(int& i) const - { - REPORT - if (storage == 0) NullMatrixError(this); - int l = storage - 1; Real* s = store; Real minval = *s++; int li = l; - while (l--) { Real a = *s++; if (minval >= a) { minval = a; li = l; } } - i = storage - li; - ((GeneralMatrix&)*this).tDelete(); return minval; - } - - Real GeneralMatrix::MaximumAbsoluteValue2(int& i, int& j) const - { - REPORT - if (storage == 0) NullMatrixError(this); - Real maxval = 0.0; int nr = Nrows(); - MatrixRow mr((GeneralMatrix*)this, LoadOnEntry+DirectPart); - for (int r = 1; r <= nr; r++) - { - int c; maxval = mr.MaximumAbsoluteValue1(maxval, c); - if (c > 0) { i = r; j = c; } - mr.Next(); - } - ((GeneralMatrix&)*this).tDelete(); return maxval; - } - - Real GeneralMatrix::MinimumAbsoluteValue2(int& i, int& j) const - { - REPORT - if (storage == 0) NullMatrixError(this); - Real minval = FloatingPointPrecision::Maximum(); int nr = Nrows(); - MatrixRow mr((GeneralMatrix*)this, LoadOnEntry+DirectPart); - for (int r = 1; r <= nr; r++) - { - int c; minval = mr.MinimumAbsoluteValue1(minval, c); - if (c > 0) { i = r; j = c; } - mr.Next(); - } - ((GeneralMatrix&)*this).tDelete(); return minval; - } - - Real GeneralMatrix::Maximum2(int& i, int& j) const - { - REPORT - if (storage == 0) NullMatrixError(this); - Real maxval = -FloatingPointPrecision::Maximum(); int nr = Nrows(); - MatrixRow mr((GeneralMatrix*)this, LoadOnEntry+DirectPart); - for (int r = 1; r <= nr; r++) - { - int c; maxval = mr.Maximum1(maxval, c); - if (c > 0) { i = r; j = c; } - mr.Next(); - } - ((GeneralMatrix&)*this).tDelete(); return maxval; - } - - Real GeneralMatrix::Minimum2(int& i, int& j) const - { - REPORT - if (storage == 0) NullMatrixError(this); - Real minval = FloatingPointPrecision::Maximum(); int nr = Nrows(); - MatrixRow mr((GeneralMatrix*)this, LoadOnEntry+DirectPart); - for (int r = 1; r <= nr; r++) - { - int c; minval = mr.Minimum1(minval, c); - if (c > 0) { i = r; j = c; } - mr.Next(); - } - ((GeneralMatrix&)*this).tDelete(); return minval; - } - - Real Matrix::MaximumAbsoluteValue2(int& i, int& j) const - { - REPORT - int k; Real m = GeneralMatrix::MaximumAbsoluteValue1(k); k--; - i = k / Ncols(); j = k - i * Ncols(); i++; j++; - return m; - } - - Real Matrix::MinimumAbsoluteValue2(int& i, int& j) const - { - REPORT - int k; Real m = GeneralMatrix::MinimumAbsoluteValue1(k); k--; - i = k / Ncols(); j = k - i * Ncols(); i++; j++; - return m; - } - - Real Matrix::Maximum2(int& i, int& j) const - { - REPORT - int k; Real m = GeneralMatrix::Maximum1(k); k--; - i = k / Ncols(); j = k - i * Ncols(); i++; j++; - return m; - } - - Real Matrix::Minimum2(int& i, int& j) const - { - REPORT - int k; Real m = GeneralMatrix::Minimum1(k); k--; - i = k / Ncols(); j = k - i * Ncols(); i++; j++; - return m; - } - - Real SymmetricMatrix::SumSquare() const - { - REPORT - Real sum1 = 0.0; Real sum2 = 0.0; Real* s = store; int nr = nrows; - for (int i = 0; iSumSquare(); return s; - } - - Real BaseMatrix::NormFrobenius() const - { REPORT return sqrt(SumSquare()); } - - Real BaseMatrix::SumAbsoluteValue() const - { - REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); - Real s = gm->SumAbsoluteValue(); return s; - } - - Real BaseMatrix::Sum() const - { - REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); - Real s = gm->Sum(); return s; - } - - Real BaseMatrix::MaximumAbsoluteValue() const - { - REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); - Real s = gm->MaximumAbsoluteValue(); return s; - } - - Real BaseMatrix::MaximumAbsoluteValue1(int& i) const - { - REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); - Real s = gm->MaximumAbsoluteValue1(i); return s; - } - - Real BaseMatrix::MaximumAbsoluteValue2(int& i, int& j) const - { - REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); - Real s = gm->MaximumAbsoluteValue2(i, j); return s; - } - - Real BaseMatrix::MinimumAbsoluteValue() const - { - REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); - Real s = gm->MinimumAbsoluteValue(); return s; - } - - Real BaseMatrix::MinimumAbsoluteValue1(int& i) const - { - REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); - Real s = gm->MinimumAbsoluteValue1(i); return s; - } - - Real BaseMatrix::MinimumAbsoluteValue2(int& i, int& j) const - { - REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); - Real s = gm->MinimumAbsoluteValue2(i, j); return s; - } - - Real BaseMatrix::Maximum() const - { - REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); - Real s = gm->Maximum(); return s; - } - - Real BaseMatrix::Maximum1(int& i) const - { - REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); - Real s = gm->Maximum1(i); return s; - } - - Real BaseMatrix::Maximum2(int& i, int& j) const - { - REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); - Real s = gm->Maximum2(i, j); return s; - } - - Real BaseMatrix::Minimum() const - { - REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); - Real s = gm->Minimum(); return s; - } - - Real BaseMatrix::Minimum1(int& i) const - { - REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); - Real s = gm->Minimum1(i); return s; - } - - Real BaseMatrix::Minimum2(int& i, int& j) const - { - REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); - Real s = gm->Minimum2(i, j); return s; - } - - Real DotProduct(const Matrix& A, const Matrix& B) - { - REPORT - int n = A.storage; - if (n != B.storage) Throw(IncompatibleDimensionsException(A,B)); - Real sum = 0.0; Real* a = A.store; Real* b = B.store; - while (n--) sum += *a++ * *b++; - return sum; - } - - Real Matrix::Trace() const - { - REPORT - Tracer trace("Trace"); - int i = nrows; int d = i+1; - if (i != ncols) Throw(NotSquareException(*this)); - Real sum = 0.0; Real* s = store; - // while (i--) { sum += *s; s += d; } - if (i) for (;;) { sum += *s; if (!(--i)) break; s += d; } - ((GeneralMatrix&)*this).tDelete(); return sum; - } - - Real DiagonalMatrix::Trace() const - { - REPORT - int i = nrows; Real sum = 0.0; Real* s = store; - while (i--) sum += *s++; - ((GeneralMatrix&)*this).tDelete(); return sum; - } - - Real SymmetricMatrix::Trace() const - { - REPORT - int i = nrows; Real sum = 0.0; Real* s = store; int j = 2; - // while (i--) { sum += *s; s += j++; } - if (i) for (;;) { sum += *s; if (!(--i)) break; s += j++; } - ((GeneralMatrix&)*this).tDelete(); return sum; - } - - Real LowerTriangularMatrix::Trace() const - { - REPORT - int i = nrows; Real sum = 0.0; Real* s = store; int j = 2; - // while (i--) { sum += *s; s += j++; } - if (i) for (;;) { sum += *s; if (!(--i)) break; s += j++; } - ((GeneralMatrix&)*this).tDelete(); return sum; - } - - Real UpperTriangularMatrix::Trace() const - { - REPORT - int i = nrows; Real sum = 0.0; Real* s = store; - while (i) { sum += *s; s += i--; } // won t cause a problem - ((GeneralMatrix&)*this).tDelete(); return sum; - } - - Real BandMatrix::Trace() const - { - REPORT - int i = nrows; int w = lower+upper+1; - Real sum = 0.0; Real* s = store+lower; - // while (i--) { sum += *s; s += w; } - if (i) for (;;) { sum += *s; if (!(--i)) break; s += w; } - ((GeneralMatrix&)*this).tDelete(); return sum; - } - - Real SymmetricBandMatrix::Trace() const - { - REPORT - int i = nrows; int w = lower+1; - Real sum = 0.0; Real* s = store+lower; - // while (i--) { sum += *s; s += w; } - if (i) for (;;) { sum += *s; if (!(--i)) break; s += w; } - ((GeneralMatrix&)*this).tDelete(); return sum; - } - - Real IdentityMatrix::Trace() const - { - Real sum = *store * nrows; - ((GeneralMatrix&)*this).tDelete(); return sum; - } - - - Real BaseMatrix::Trace() const - { - REPORT - MatrixType Diag = MatrixType::Dg; Diag.SetDataLossOK(); - GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(Diag); - Real sum = gm->Trace(); return sum; - } - - void LogAndSign::operator*=(Real x) - { - if (x > 0.0) { log_value += log(x); } - else if (x < 0.0) { log_value += log(-x); sign = -sign; } - else sign = 0; - } - - void LogAndSign::PowEq(int k) - { - if (sign) - { - log_value *= k; - if ( (k & 1) == 0 ) sign = 1; - } - } - - Real LogAndSign::Value() const - { - Tracer et("LogAndSign::Value"); - if (log_value >= FloatingPointPrecision::LnMaximum()) - Throw(OverflowException("Overflow in exponential")); - return sign * exp(log_value); - } - - LogAndSign::LogAndSign(Real f) - { - if (f == 0.0) { log_value = 0.0; sign = 0; return; } - else if (f < 0.0) { sign = -1; f = -f; } - else sign = 1; - log_value = log(f); - } - - LogAndSign DiagonalMatrix::LogDeterminant() const - { - REPORT - int i = nrows; LogAndSign sum; Real* s = store; - while (i--) sum *= *s++; - ((GeneralMatrix&)*this).tDelete(); return sum; - } - - LogAndSign LowerTriangularMatrix::LogDeterminant() const - { - REPORT - int i = nrows; LogAndSign sum; Real* s = store; int j = 2; - // while (i--) { sum *= *s; s += j++; } - if (i) for(;;) { sum *= *s; if (!(--i)) break; s += j++; } - ((GeneralMatrix&)*this).tDelete(); return sum; - } - - LogAndSign UpperTriangularMatrix::LogDeterminant() const - { - REPORT - int i = nrows; LogAndSign sum; Real* s = store; - while (i) { sum *= *s; s += i--; } - ((GeneralMatrix&)*this).tDelete(); return sum; - } - - LogAndSign IdentityMatrix::LogDeterminant() const - { - REPORT - int i = nrows; LogAndSign sum; - if (i > 0) { sum = *store; sum.PowEq(i); } - ((GeneralMatrix&)*this).tDelete(); return sum; - } - - LogAndSign BaseMatrix::LogDeterminant() const - { - REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); - LogAndSign sum = gm->LogDeterminant(); return sum; - } - - LogAndSign GeneralMatrix::LogDeterminant() const - { - REPORT - Tracer tr("LogDeterminant"); - if (nrows != ncols) Throw(NotSquareException(*this)); - CroutMatrix C(*this); return C.LogDeterminant(); - } - - LogAndSign CroutMatrix::LogDeterminant() const - { - REPORT - if (sing) return 0.0; - int i = nrows; int dd = i+1; LogAndSign sum; Real* s = store; - if (i) for(;;) - { - sum *= *s; - if (!(--i)) break; - s += dd; - } - if (!d) sum.ChangeSign(); return sum; - - } - - Real BaseMatrix::Determinant() const - { - REPORT - Tracer tr("Determinant"); - REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); - LogAndSign ld = gm->LogDeterminant(); - return ld.Value(); - } - - - - - - LinearEquationSolver::LinearEquationSolver(const BaseMatrix& bm) - : gm( ( ((BaseMatrix&)bm).Evaluate() )->MakeSolver() ) - { - if (gm==&bm) { REPORT gm = gm->Image(); } - // want a copy if *gm is actually bm - else { REPORT gm->Protect(); } - } - - -#ifdef use_namespace -} -#endif - diff --git a/lib/src/mixmod/NEWMAT/newmat9.cpp b/lib/src/mixmod/NEWMAT/newmat9.cpp deleted file mode 100644 index fe1c4f7..0000000 --- a/lib/src/mixmod/NEWMAT/newmat9.cpp +++ /dev/null @@ -1,76 +0,0 @@ -//$$ newmat9.cpp Input and output - -// Copyright (C) 1991,2,3,4: R B Davies - - -#define WANT_STREAM - -#include "include.h" - -#include "newmat.h" -#include "newmatio.h" -#include "newmatrc.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - - - -#ifdef DO_REPORT -#define REPORT { static ExeCounter ExeCount(__LINE__,9); ++ExeCount; } -#else -#define REPORT {} -#endif - - // for G++ 3.01 -#ifndef ios_format_flags -#define ios_format_flags long -#endif - - ostream& operator<<(ostream& s, const BaseMatrix& X) - { - GeneralMatrix* gm = ((BaseMatrix&)X).Evaluate(); operator<<(s, *gm); - gm->tDelete(); return s; - } - - - ostream& operator<<(ostream& s, const GeneralMatrix& X) - { - MatrixRow mr((GeneralMatrix*)&X, LoadOnEntry); - int w = s.width(); int nr = X.Nrows(); ios_format_flags f = s.flags(); - s.setf(ios::fixed, ios::floatfield); - for (int i=1; i<=nr; i++) - { - int skip = mr.skip; int storage = mr.storage; - Real* store = mr.data; skip *= w+1; - while (skip--) s << " "; - while (storage--) { s.width(w); s << *store++ << " "; } - // while (storage--) s << setw(w) << *store++ << " "; - mr.Next(); s << "\n"; - } - s << flush; s.flags(f); return s; - } - - // include this stuff if you are using an old version of G++ - // with an incomplete io library - - /* - - ostream& operator<<(ostream& os, Omanip_precision i) - { os.precision(i.x); return os; } - - Omanip_precision setprecision(int i) { return Omanip_precision(i); } - - ostream& operator<<(ostream& os, Omanip_width i) - { os.width(i.x); return os; } - - Omanip_width setw(int i) { return Omanip_width(i); } - - */ - -#ifdef use_namespace -} -#endif - - diff --git a/lib/src/mixmod/NEWMAT/newmatap.h b/lib/src/mixmod/NEWMAT/newmatap.h deleted file mode 100644 index 830b642..0000000 --- a/lib/src/mixmod/NEWMAT/newmatap.h +++ /dev/null @@ -1,171 +0,0 @@ -//$$ newmatap.h definition file for matrix package applications - -// Copyright (C) 1991,2,3,4,8: R B Davies - -#ifndef NEWMATAP_LIB -#define NEWMATAP_LIB 0 - -#include "newmat.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - - - // ************************** applications *****************************/ - - - void QRZT(Matrix&, LowerTriangularMatrix&); - - void QRZT(const Matrix&, Matrix&, Matrix&); - - void QRZ(Matrix&, UpperTriangularMatrix&); - - void QRZ(const Matrix&, Matrix&, Matrix&); - - inline void HHDecompose(Matrix& X, LowerTriangularMatrix& L) - { QRZT(X,L); } - - inline void HHDecompose(const Matrix& X, Matrix& Y, Matrix& M) - { QRZT(X, Y, M); } - - ReturnMatrix Cholesky(const SymmetricMatrix&); - - ReturnMatrix Cholesky(const SymmetricBandMatrix&); - - void SVD(const Matrix&, DiagonalMatrix&, Matrix&, Matrix&, - bool=true, bool=true); - - void SVD(const Matrix&, DiagonalMatrix&); - - inline void SVD(const Matrix& A, DiagonalMatrix& D, Matrix& U, - bool withU = true) { SVD(A, D, U, U, withU, false); } - - void SortSV(DiagonalMatrix& D, Matrix& U, bool ascending = false); - - void SortSV(DiagonalMatrix& D, Matrix& U, Matrix& V, bool ascending = false); - - void Jacobi(const SymmetricMatrix&, DiagonalMatrix&); - - void Jacobi(const SymmetricMatrix&, DiagonalMatrix&, SymmetricMatrix&); - - void Jacobi(const SymmetricMatrix&, DiagonalMatrix&, Matrix&); - - void Jacobi(const SymmetricMatrix&, DiagonalMatrix&, SymmetricMatrix&, - Matrix&, bool=true); - - void EigenValues(const SymmetricMatrix&, DiagonalMatrix&); - - void EigenValues(const SymmetricMatrix&, DiagonalMatrix&, SymmetricMatrix&); - - void EigenValues(const SymmetricMatrix&, DiagonalMatrix&, Matrix&); - - class SymmetricEigenAnalysis - // not implemented yet - { - public: - SymmetricEigenAnalysis(const SymmetricMatrix&); - private: - DiagonalMatrix diag; - DiagonalMatrix offdiag; - SymmetricMatrix backtransform; - FREE_CHECK(SymmetricEigenAnalysis) - }; - - void SortAscending(GeneralMatrix&); - - void SortDescending(GeneralMatrix&); - - - // class for deciding which fft to use and containing new fft function - class FFT_Controller - { - public: - static bool OnlyOldFFT; - static bool ar_1d_ft (int PTS, Real* X, Real *Y); - static bool CanFactor(int PTS); - }; - - void FFT(const ColumnVector&, const ColumnVector&, - ColumnVector&, ColumnVector&); - - void FFTI(const ColumnVector&, const ColumnVector&, - ColumnVector&, ColumnVector&); - - void RealFFT(const ColumnVector&, ColumnVector&, ColumnVector&); - - void RealFFTI(const ColumnVector&, const ColumnVector&, ColumnVector&); - - void DCT_II(const ColumnVector&, ColumnVector&); - - void DCT_II_inverse(const ColumnVector&, ColumnVector&); - - void DST_II(const ColumnVector&, ColumnVector&); - - void DST_II_inverse(const ColumnVector&, ColumnVector&); - - void DCT(const ColumnVector&, ColumnVector&); - - void DCT_inverse(const ColumnVector&, ColumnVector&); - - void DST(const ColumnVector&, ColumnVector&); - - void DST_inverse(const ColumnVector&, ColumnVector&); - - // This class is used by the new FFT program - - // Suppose an integer is expressed as a sequence of digits with each - // digit having a different radix. - // This class supposes we are counting with this multi-radix number - // but also keeps track of the number with the digits (and radices) - // reversed. - // The integer starts at zero - // operator++() increases it by 1 - // Counter gives the number of increments - // Reverse() gives the value with the digits in reverse order - // Swap is true if reverse is less than counter - // Finish is true when we have done a complete cycle and are back at zero - - class MultiRadixCounter - { - const SimpleIntArray& Radix; - // radix of each digit - // n-1 highest order, 0 lowest order - SimpleIntArray& Value; // value of each digit - const int n; // number of digits - int reverse; // value when order of digits is reversed - int product; // product of radices - int counter; // counter - bool finish; // true when we have gone over whole range - public: - MultiRadixCounter(int nx, const SimpleIntArray& rx, - SimpleIntArray& vx); - void operator++(); // increment the multi-radix counter - bool Swap() const { return reverse < counter; } - bool Finish() const { return finish; } - int Reverse() const { return reverse; } - int Counter() const { return counter; } - }; - - -#ifdef use_namespace -} -#endif - - - -#endif - -// body file: cholesky.cpp -// body file: evalue.cpp -// body file: fft.cpp -// body file: hholder.cpp -// body file: jacobi.cpp -// body file: newfft.cpp -// body file: sort.cpp -// body file: svd.cpp - - - - - diff --git a/lib/src/mixmod/NEWMAT/newmatex.cpp b/lib/src/mixmod/NEWMAT/newmatex.cpp deleted file mode 100644 index c1b179c..0000000 --- a/lib/src/mixmod/NEWMAT/newmatex.cpp +++ /dev/null @@ -1,307 +0,0 @@ -//$$ newmatex.cpp Exception handler - -// Copyright (C) 1992,3,4,7: R B Davies - -#define WANT_STREAM // include.h will get stream fns - -#include "include.h" // include standard files -#include "newmat.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - - unsigned long OverflowException::Select; - unsigned long SingularException::Select; - unsigned long NPDException::Select; - unsigned long ConvergenceException::Select; - unsigned long ProgramException::Select; - unsigned long IndexException::Select; - unsigned long VectorException::Select; - unsigned long NotSquareException::Select; - unsigned long SubMatrixDimensionException::Select; - unsigned long IncompatibleDimensionsException::Select; - unsigned long NotDefinedException::Select; - unsigned long CannotBuildException::Select; - unsigned long InternalException::Select; - - - - static void MatrixDetails(const GeneralMatrix& A) - // write matrix details to Exception buffer - { - MatrixBandWidth bw = A.BandWidth(); int ubw = bw.upper; int lbw = bw.lower; - Exception::AddMessage("MatrixType = "); - Exception::AddMessage(A.Type().Value()); - Exception::AddMessage(" # Rows = "); Exception::AddInt(A.Nrows()); - Exception::AddMessage("; # Cols = "); Exception::AddInt(A.Ncols()); - if (lbw >=0) - { Exception::AddMessage("; lower BW = "); Exception::AddInt(lbw); } - if (ubw >=0) - { Exception::AddMessage("; upper BW = "); Exception::AddInt(ubw); } - Exception::AddMessage("\n"); - } - - NPDException::NPDException(const GeneralMatrix& A) - : Runtime_error() - { - Select = Exception::Select; - AddMessage("detected by Newmat: matrix not positive definite\n\n"); - MatrixDetails(A); - Tracer::AddTrace(); - } - - SingularException::SingularException(const GeneralMatrix& A) - : Runtime_error() - { - Select = Exception::Select; - AddMessage("detected by Newmat: matrix is singular\n\n"); - MatrixDetails(A); - Tracer::AddTrace(); - } - - ConvergenceException::ConvergenceException(const GeneralMatrix& A) - : Runtime_error() - { - Select = Exception::Select; - AddMessage("detected by Newmat: process fails to converge\n\n"); - MatrixDetails(A); - Tracer::AddTrace(); - } - - ConvergenceException::ConvergenceException(const char* c) : Runtime_error() - { - Select = Exception::Select; - AddMessage("detected by Newmat: "); - AddMessage(c); AddMessage("\n\n"); - if (c) Tracer::AddTrace(); - } - - OverflowException::OverflowException(const char* c) : Runtime_error() - { - Select = Exception::Select; - AddMessage("detected by Newmat: "); - AddMessage(c); AddMessage("\n\n"); - if (c) Tracer::AddTrace(); - } - - ProgramException::ProgramException(const char* c) : Logic_error() - { - Select = Exception::Select; - AddMessage("detected by Newmat: "); - AddMessage(c); AddMessage("\n\n"); - if (c) Tracer::AddTrace(); - } - - ProgramException::ProgramException(const char* c, const GeneralMatrix& A) - : Logic_error() - { - Select = Exception::Select; - AddMessage("detected by Newmat: "); - AddMessage(c); AddMessage("\n\n"); - MatrixDetails(A); - if (c) Tracer::AddTrace(); - } - - ProgramException::ProgramException(const char* c, const GeneralMatrix& A, - const GeneralMatrix& B) : Logic_error() - { - Select = Exception::Select; - AddMessage("detected by Newmat: "); - AddMessage(c); AddMessage("\n\n"); - MatrixDetails(A); MatrixDetails(B); - if (c) Tracer::AddTrace(); - } - - ProgramException::ProgramException(const char* c, MatrixType a, MatrixType b) - : Logic_error() - { - Select = Exception::Select; - AddMessage("detected by Newmat: "); - AddMessage(c); AddMessage("\nMatrixTypes = "); - AddMessage(a.Value()); AddMessage("; "); - AddMessage(b.Value()); AddMessage("\n\n"); - if (c) Tracer::AddTrace(); - } - - VectorException::VectorException() : Logic_error() - { - Select = Exception::Select; - AddMessage("detected by Newmat: cannot convert matrix to vector\n\n"); - Tracer::AddTrace(); - } - - VectorException::VectorException(const GeneralMatrix& A) - : Logic_error() - { - Select = Exception::Select; - AddMessage("detected by Newmat: cannot convert matrix to vector\n\n"); - MatrixDetails(A); - Tracer::AddTrace(); - } - - NotSquareException::NotSquareException(const GeneralMatrix& A) - : Logic_error() - { - Select = Exception::Select; - AddMessage("detected by Newmat: matrix is not square\n\n"); - MatrixDetails(A); - Tracer::AddTrace(); - } - - SubMatrixDimensionException::SubMatrixDimensionException() - : Logic_error() - { - Select = Exception::Select; - AddMessage("detected by Newmat: incompatible submatrix dimension\n\n"); - Tracer::AddTrace(); - } - - IncompatibleDimensionsException::IncompatibleDimensionsException() - : Logic_error() - { - Select = Exception::Select; - AddMessage("detected by Newmat: incompatible dimensions\n\n"); - Tracer::AddTrace(); - } - - IncompatibleDimensionsException::IncompatibleDimensionsException - (const GeneralMatrix& A, const GeneralMatrix& B) - : Logic_error() - { - Select = Exception::Select; - AddMessage("detected by Newmat: incompatible dimensions\n\n"); - MatrixDetails(A); MatrixDetails(B); - Tracer::AddTrace(); - } - - NotDefinedException::NotDefinedException(const char* op, const char* matrix) - : Logic_error() - { - Select = Exception::Select; - AddMessage("detected by Newmat: "); - AddMessage(op); - AddMessage(" not defined for "); - AddMessage(matrix); - AddMessage("\n\n"); - Tracer::AddTrace(); - } - - CannotBuildException::CannotBuildException(const char* matrix) - : Logic_error() - { - Select = Exception::Select; - AddMessage("detected by Newmat: cannot build matrix type "); - AddMessage(matrix); AddMessage("\n\n"); - Tracer::AddTrace(); - } - - IndexException::IndexException(int i, const GeneralMatrix& A) - : Logic_error() - { - Select = Exception::Select; - AddMessage("detected by Newmat: index error: requested index = "); - AddInt(i); AddMessage("\n\n"); - MatrixDetails(A); - Tracer::AddTrace(); - } - - IndexException::IndexException(int i, int j, const GeneralMatrix& A) - : Logic_error() - { - Select = Exception::Select; - AddMessage("detected by Newmat: index error: requested indices = "); - AddInt(i); AddMessage(", "); AddInt(j); - AddMessage("\n\n"); - MatrixDetails(A); - Tracer::AddTrace(); - } - - - IndexException::IndexException(int i, const GeneralMatrix& A, bool) - : Logic_error() - { - Select = Exception::Select; - AddMessage("detected by Newmat: element error: requested index (wrt 0) = "); - AddInt(i); - AddMessage("\n\n"); - MatrixDetails(A); - Tracer::AddTrace(); - } - - IndexException::IndexException(int i, int j, const GeneralMatrix& A, bool) - : Logic_error() - { - Select = Exception::Select; - AddMessage( - "detected by Newmat: element error: requested indices (wrt 0) = "); - AddInt(i); AddMessage(", "); AddInt(j); - AddMessage("\n\n"); - MatrixDetails(A); - Tracer::AddTrace(); - } - - InternalException::InternalException(const char* c) : Logic_error() - { - Select = Exception::Select; - AddMessage("internal error detected by Newmat: please inform author\n"); - AddMessage(c); AddMessage("\n\n"); - Tracer::AddTrace(); - } - - - - - /************************* ExeCounter functions *****************************/ - -#ifdef DO_REPORT - - int ExeCounter::nreports; // will be set to zero - - ExeCounter::ExeCounter(int xl, int xf) : line(xl), fileid(xf), nexe(0) {} - - ExeCounter::~ExeCounter() - { - nreports++; - cout << "REPORT " << setw(6) << nreports << " " - << setw(6) << fileid << " " << setw(6) << line - << " " << setw(6) << nexe << "\n"; - } - -#endif - - /**************************** error handler *******************************/ - - void MatrixErrorNoSpace(void* v) { if (!v) Throw(Bad_alloc()); } - // throw exception if v is null - - - - - /************************* miscellanous errors ***************************/ - - - void CroutMatrix::GetRow(MatrixRowCol&) - { Throw(NotDefinedException("GetRow","Crout")); } - void CroutMatrix::GetCol(MatrixRowCol&) - { Throw(NotDefinedException("GetCol","Crout")); } - void CroutMatrix::operator=(const BaseMatrix&) - { Throw(NotDefinedException("=","Crout")); } - void BandLUMatrix::GetRow(MatrixRowCol&) - { Throw(NotDefinedException("GetRow","BandLUMatrix")); } - void BandLUMatrix::GetCol(MatrixRowCol&) - { Throw(NotDefinedException("GetCol","BandLUMatrix")); } - void BandLUMatrix::operator=(const BaseMatrix&) - { Throw(NotDefinedException("=","BandLUMatrix")); } - void BaseMatrix::IEQND() const - { Throw(NotDefinedException("inequalities", "matrices")); } -#ifdef TEMPS_DESTROYED_QUICKLY_R - ReturnMatrixX::ReturnMatrixX(const ReturnMatrixX& tm) - : gm(tm.gm) { Throw(ProgramException("ReturnMatrixX error")); } -#endif - - -#ifdef use_namespace -} -#endif - diff --git a/lib/src/mixmod/NEWMAT/newmatio.h b/lib/src/mixmod/NEWMAT/newmatio.h deleted file mode 100644 index 1d76f63..0000000 --- a/lib/src/mixmod/NEWMAT/newmatio.h +++ /dev/null @@ -1,61 +0,0 @@ -//$$ newmatio.h definition file for matrix package input/output - -// Copyright (C) 1991,2,3,4: R B Davies - -#ifndef NEWMATIO_LIB -#define NEWMATIO_LIB 0 - -#ifndef WANT_STREAM -#define WANT_STREAM -#endif - -#include "newmat.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - - - - /**************************** input/output *****************************/ - - ostream& operator<<(ostream&, const BaseMatrix&); - - ostream& operator<<(ostream&, const GeneralMatrix&); - - - /* Use in some old versions of G++ without complete iomanipulators - - class Omanip_precision - { - int x; - public: - Omanip_precision(int i) : x(i) {} - friend ostream& operator<<(ostream& os, Omanip_precision i); - }; - - - Omanip_precision setprecision(int i); - - class Omanip_width - { - int x; - public: - Omanip_width(int i) : x(i) {} - friend ostream& operator<<(ostream& os, Omanip_width i); - }; - - Omanip_width setw(int i); - - */ - -#ifdef use_namespace -} -#endif - - - -#endif - -// body file: newmat9.cpp - diff --git a/lib/src/mixmod/NEWMAT/newmatnl.cpp b/lib/src/mixmod/NEWMAT/newmatnl.cpp deleted file mode 100644 index 0c8680c..0000000 --- a/lib/src/mixmod/NEWMAT/newmatnl.cpp +++ /dev/null @@ -1,258 +0,0 @@ -//$$ newmatnl.cpp Non-linear optimisation - -// Copyright (C) 1993,4,5,6: R B Davies - - -#define WANT_MATH -#define WANT_STREAM - -#include "newmatap.h" -#include "newmatnl.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - - - - void FindMaximum2::Fit(ColumnVector& Theta, int n_it) - { - Tracer tr("FindMaximum2::Fit"); - enum State {Start, Restart, Continue, Interpolate, Extrapolate, - Fail, Convergence}; - State TheState = Start; - Real z,w,x,x2,g,l1,l2,l3,d1,d2=0,d3; - ColumnVector Theta1, Theta2, Theta3; - int np = Theta.Nrows(); - ColumnVector H1(np), H3, HP(np), K, K1(np); - bool oorg, conv; - int counter = 0; - Theta1 = Theta; HP = 0.0; g = 0.0; - - // This is really a set of gotos and labels, but they do not work - // correctly in AT&T C++ and Sun 4.01 C++. - - for(;;) - { - switch (TheState) - { - case Start: - tr.ReName("FindMaximum2::Fit/Start"); - Value(Theta1, true, l1, oorg); - if (oorg) Throw(ProgramException("invalid starting value\n")); - - case Restart: - tr.ReName("FindMaximum2::Fit/ReStart"); - conv = NextPoint(H1, d1); - if (conv) { TheState = Convergence; break; } - if (counter++ > n_it) { TheState = Fail; break; } - - z = 1.0 / sqrt(d1); - H3 = H1 * z; K = (H3 - HP) * g; HP = H3; - g = 0.0; // de-activate to use curved projection - if (g==0.0) K1 = 0.0; else K1 = K * 0.2 + K1 * 0.6; - // (K - K1) * alpha + K1 * (1 - alpha) - // = K * alpha + K1 * (1 - 2 * alpha) - K = K1 * d1; g = z; - - case Continue: - tr.ReName("FindMaximum2::Fit/Continue"); - Theta2 = Theta1 + H1 + K; - Value(Theta2, false, l2, oorg); - if (counter++ > n_it) { TheState = Fail; break; } - if (oorg) - { - H1 *= 0.5; K *= 0.25; d1 *= 0.5; g *= 2.0; - TheState = Continue; break; - } - d2 = LastDerivative(H1 + K * 2.0); - - case Interpolate: - tr.ReName("FindMaximum2::Fit/Interpolate"); - z = d1 + d2 - 3.0 * (l2 - l1); - w = z * z - d1 * d2; - if (w < 0.0) { TheState = Extrapolate; break; } - w = z + sqrt(w); - if (1.5 * w + d1 < 0.0) - { TheState = Extrapolate; break; } - if (d2 > 0.0 && l2 > l1 && w > 0.0) - { TheState = Extrapolate; break; } - x = d1 / (w + d1); x2 = x * x; g /= x; - Theta3 = Theta1 + H1 * x + K * x2; - Value(Theta3, true, l3, oorg); - if (counter++ > n_it) { TheState = Fail; break; } - if (oorg) - { - if (x <= 1.0) - { x *= 0.5; x2 = x*x; g *= 2.0; d1 *= x; H1 *= x; K *= x2; } - else - { - x = 0.5 * (x-1.0); x2 = x*x; Theta1 = Theta2; - H1 = (H1 + K * 2.0) * x; - K *= x2; g = 0.0; d1 = x * d2; l1 = l2; - } - TheState = Continue; break; - } - - if (l3 >= l1 && l3 >= l2) - { Theta1 = Theta3; l1 = l3; TheState = Restart; break; } - - d3 = LastDerivative(H1 + K * 2.0); - if (l1 > l2) - { H1 *= x; K *= x2; Theta2 = Theta3; d1 *= x; d2 = d3*x; } - else - { - Theta1 = Theta2; Theta2 = Theta3; - x -= 1.0; x2 = x*x; g = 0.0; H1 = (H1 + K * 2.0) * x; - K *= x2; l1 = l2; l2 = l3; d1 = x*d2; d2 = x*d3; - if (d1 <= 0.0) { TheState = Start; break; } - } - TheState = Interpolate; break; - - case Extrapolate: - tr.ReName("FindMaximum2::Fit/Extrapolate"); - Theta1 = Theta2; g = 0.0; K *= 4.0; H1 = (H1 * 2.0 + K); - d1 = 2.0 * d2; l1 = l2; - TheState = Continue; break; - - case Fail: - Throw(ConvergenceException(Theta)); - - case Convergence: - Theta = Theta1; return; - } - } - } - - - - void NonLinearLeastSquares::Value - (const ColumnVector& Parameters, bool, Real& v, bool& oorg) - { - Tracer tr("NonLinearLeastSquares::Value"); - Y.ReSize(n_obs); X.ReSize(n_obs,n_param); - // put the fitted values in Y, the derivatives in X. - Pred.Set(Parameters); - if (!Pred.IsValid()) { oorg=true; return; } - for (int i=1; i<=n_obs; i++) - { - Y(i) = Pred(i); - X.Row(i) = Pred.Derivatives(); - } - if (!Pred.IsValid()) { oorg=true; return; } // check afterwards as well - Y = *DataPointer - Y; Real ssq = Y.SumSquare(); - errorvar = ssq / (n_obs - n_param); - cout << "\n" << setw(15) << setprecision(10) << " " << errorvar; - Derivs = Y.t() * X; // get the derivative and stash it - oorg = false; v = -0.5 * ssq; - } - - bool NonLinearLeastSquares::NextPoint(ColumnVector& Adj, Real& test) - { - Tracer tr("NonLinearLeastSquares::NextPoint"); - QRZ(X, U); QRZ(X, Y, M); // do the QR decomposition - test = M.SumSquare(); - cout << " " << setw(15) << setprecision(10) - << test << " " << Y.SumSquare() / (n_obs - n_param); - Adj = U.i() * M; - if (test < errorvar * criterion) return true; - else return false; - } - - Real NonLinearLeastSquares::LastDerivative(const ColumnVector& H) - { return (Derivs * H).AsScalar(); } - - void NonLinearLeastSquares::Fit(const ColumnVector& Data, - ColumnVector& Parameters) - { - Tracer tr("NonLinearLeastSquares::Fit"); - n_param = Parameters.Nrows(); n_obs = Data.Nrows(); - DataPointer = &Data; - FindMaximum2::Fit(Parameters, Lim); - cout << "\nConverged\n"; - } - - void NonLinearLeastSquares::MakeCovariance() - { - if (Covariance.Nrows()==0) - { - UpperTriangularMatrix UI = U.i(); - Covariance << UI * UI.t() * errorvar; - SE << Covariance; // get diagonals - for (int i = 1; i<=n_param; i++) SE(i) = sqrt(SE(i)); - } - } - - void NonLinearLeastSquares::GetStandardErrors(ColumnVector& SEX) - { MakeCovariance(); SEX = SE.AsColumn(); } - - void NonLinearLeastSquares::GetCorrelations(SymmetricMatrix& Corr) - { MakeCovariance(); Corr << SE.i() * Covariance * SE.i(); } - - void NonLinearLeastSquares::GetHatDiagonal(DiagonalMatrix& Hat) const - { - Hat.ReSize(n_obs); - for (int i = 1; i<=n_obs; i++) Hat(i) = X.Row(i).SumSquare(); - } - - - // the MLE_D_FI routines - - void MLE_D_FI::Value - (const ColumnVector& Parameters, bool wg, Real& v, bool& oorg) - { - Tracer tr("MLE_D_FI::Value"); - if (!LL.IsValid(Parameters,wg)) { oorg=true; return; } - v = LL.LogLikelihood(); - if (!LL.IsValid()) { oorg=true; return; } // check validity again - cout << "\n" << setw(20) << setprecision(10) << v; - oorg = false; - Derivs = LL.Derivatives(); // Get derivatives - } - - bool MLE_D_FI::NextPoint(ColumnVector& Adj, Real& test) - { - Tracer tr("MLE_D_FI::NextPoint"); - SymmetricMatrix FI = LL.FI(); - LT = Cholesky(FI); - ColumnVector Adj1 = LT.i() * Derivs; - Adj = LT.t().i() * Adj1; - test = SumSquare(Adj1); - cout << " " << setw(20) << setprecision(10) << test; - return (test < Criterion); - } - - Real MLE_D_FI::LastDerivative(const ColumnVector& H) - { return (Derivs.t() * H).AsScalar(); } - - void MLE_D_FI::Fit(ColumnVector& Parameters) - { - Tracer tr("MLE_D_FI::Fit"); - FindMaximum2::Fit(Parameters,Lim); - cout << "\nConverged\n"; - } - - void MLE_D_FI::MakeCovariance() - { - if (Covariance.Nrows()==0) - { - LowerTriangularMatrix LTI = LT.i(); - Covariance << LTI.t() * LTI; - SE << Covariance; // get diagonal - int n = Covariance.Nrows(); - for (int i=1; i <= n; i++) SE(i) = sqrt(SE(i)); - } - } - - void MLE_D_FI::GetStandardErrors(ColumnVector& SEX) - { MakeCovariance(); SEX = SE.AsColumn(); } - - void MLE_D_FI::GetCorrelations(SymmetricMatrix& Corr) - { MakeCovariance(); Corr << SE.i() * Covariance * SE.i(); } - - - -#ifdef use_namespace -} -#endif - diff --git a/lib/src/mixmod/NEWMAT/newmatnl.h b/lib/src/mixmod/NEWMAT/newmatnl.h deleted file mode 100644 index 556aae2..0000000 --- a/lib/src/mixmod/NEWMAT/newmatnl.h +++ /dev/null @@ -1,322 +0,0 @@ -//$$ newmatnl.h definition file for non-linear optimisation - -// Copyright (C) 1993,4,5: R B Davies - -#ifndef NEWMATNL_LIB -#define NEWMATNL_LIB 0 - -#include "newmat.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - - - - /* - - This is a beginning of a series of classes for non-linear optimisation. - - At present there are two classes. FindMaximum2 is the basic optimisation - strategy when one is doing an optimisation where one has first - derivatives and estimates of the second derivatives. Class - NonLinearLeastSquares is derived from FindMaximum2. This provides the - functions that calculate function values and derivatives. - - A third class is now added. This is for doing maximum-likelihood when - you have first derviatives and something like the Fisher Information - matrix (eg the variance covariance matrix of the first derivatives or - minus the second derivatives - this matrix is assumed to be positive - definite). - - - - class FindMaximum2 - - Suppose T is the ColumnVector of parameters, F(T) the function we want - to maximise, D(T) the ColumnVector of derivatives of F with respect to - T, and S(T) the matrix of second derivatives. - - Then the basic iteration is given a value of T, update it to - - T - S.i() * D - - where .i() denotes inverse. - - If F was quadratic this would give exactly the right answer (except it - might get a minimum rather than a maximum). Since F is not usually - quadratic, the simple procedure would be to recalculate S and D with the - new value of T and keep iterating until the process converges. This is - known as the method of conjugate gradients. - - In practice, this method may not converge. FindMaximum2 considers an - iteration of the form - - T - x * S.i() * D - - where x is a number. It tries x = 1 and uses the values of F and its - slope with respect to x at x = 0 and x = 1 to fit a cubic in x. It then - choses x to maximise the resulting function. This gives our new value of - T. The program checks that the value of F is getting better and carries - out a variety of strategies if it is not. - - The program also has a second strategy. If the successive values of T - seem to be lying along a curve - eg we are following along a curved - ridge, the program will try to fit this ridge and project along it. This - does not work at present and is commented out. - - FindMaximum2 has three virtual functions which need to be over-ridden by - a derived class. - - void Value(const ColumnVector& T, bool wg, Real& f, bool& oorg); - - T is the column vector of parameters. The function returns the value of - the function to f, but may instead set oorg to true if the parameter - values are not valid. If wg is true it may also calculate and store the - second derivative information. - - bool NextPoint(ColumnVector& H, Real& d); - - Using the value of T provided in the previous call of Value, find the - conjugate gradients adjustment to T, that is - S.i() * D. Also return - - d = D.t() * S.i() * D. - - NextPoint should return true if it considers that the process has - converged (d very small) and false otherwise. The previous call of Value - will have set wg to true, so that S will be available. - - Real LastDerivative(const ColumnVector& H); - - Return the scalar product of H and the vector of derivatives at the last - value of T. - - The function Fit is the function that calls the iteration. - - void Fit(ColumnVector&, int); - - The arguments are the trial parameter values as a ColumnVector and the - maximum number of iterations. The program calls a DataException if the - initial parameters are not valid and a ConvergenceException if the - process fails to converge. - - - class NonLinearLeastSquares - - This class is derived from FindMaximum2 and carries out a non-linear - least squares fit. It uses a QR decomposition to carry out the - operations required by FindMaximum2. - - A prototype class R1_Col_I_D is provided. The user needs to derive a - class from this which includes functions the predicted value of each - observation its derivatives. An object from this class has to be - provided to class NonLinearLeastSquares. - - Suppose we observe n normal random variables with the same unknown - variance and such the i-th one has expected value given by f(i,P) - where P is a column vector of unknown parameters and f is a known - function. We wish to estimate P. - - First derive a class from R1_Col_I_D and override Real operator()(int i) - to give the value of the function f in terms of i and the ColumnVector - para defined in class R1_CoL_I_D. Also override ReturnMatrix - Derivatives() to give the derivates of f at para and the value of i - used in the preceeding call to operator(). Return the result as a - RowVector. Construct an object from this class. Suppose in what follows - it is called pred. - - Now constuct a NonLinearLeastSquaresObject accessing pred and optionally - an iteration limit and an accuracy critierion. - - NonLinearLeastSquares NLLS(pred, 1000, 0.0001); - - The accuracy critierion should be somewhat less than one and 0.0001 is - about the smallest sensible value. - - Define a ColumnVector P containing a guess at the value of the unknown - parameter, and a ColumnVector Y containing the unknown data. Call - - NLLS.Fit(Y,P); - - If the process converges, P will contain the estimates of the unknown - parameters. If it does not converge an exception will be generated. - - The following member functions can be called after you have done a fit. - - Real ResidualVariance() const; - - The estimate of the variance of the observations. - - void GetResiduals(ColumnVector& Z) const; - - The residuals of the individual observations. - - void GetStandardErrors(ColumnVector&); - - The standard errors of the observations. - - void GetCorrelations(SymmetricMatrix&); - - The correlations of the observations. - - void GetHatDiagonal(DiagonalMatrix&) const; - - Forms a diagonal matrix of values between 0 and 1. If the i-th value is - larger than, say 0.2, then the i-th data value could have an undue - influence on your estimates. - - - */ - - class FindMaximum2 - { - virtual void Value(const ColumnVector&, bool, Real&, bool&) = 0; - virtual bool NextPoint(ColumnVector&, Real&) = 0; - virtual Real LastDerivative(const ColumnVector&) = 0; - public: - void Fit(ColumnVector&, int); - virtual ~FindMaximum2() {} // to keep gnu happy - }; - - class R1_Col_I_D - { - // The prototype for a Real function of a ColumnVector and an - // integer. - // You need to derive your function from this one and put in your - // function for operator() and Derivatives() at least. - // You may also want to set up a constructor to enter in additional - // parameter values (that will not vary during the solve). - - protected: - ColumnVector para; // Current x value - - public: - virtual bool IsValid() { return true; } - // is the current x value OK - virtual Real operator()(int i) = 0; // i-th function value at current para - virtual void Set(const ColumnVector& X) { para = X; } - // set current para - bool IsValid(const ColumnVector& X) - { Set(X); return IsValid(); } - // set para, check OK - Real operator()(int i, const ColumnVector& X) - { Set(X); return operator()(i); } - // set para, return value - virtual ReturnMatrix Derivatives() = 0; - // return derivatives as RowVector - virtual ~R1_Col_I_D() {} // to keep gnu happy - }; - - - class NonLinearLeastSquares : public FindMaximum2 - { - // these replace the corresponding functions in FindMaximum2 - void Value(const ColumnVector&, bool, Real&, bool&); - bool NextPoint(ColumnVector&, Real&); - Real LastDerivative(const ColumnVector&); - - Matrix X; // the things we need to do the - ColumnVector Y; // QR triangularisation - UpperTriangularMatrix U; // see the write-up in newmata.txt - ColumnVector M; - Real errorvar, criterion; - int n_obs, n_param; - const ColumnVector* DataPointer; - RowVector Derivs; - SymmetricMatrix Covariance; - DiagonalMatrix SE; - R1_Col_I_D& Pred; // Reference to predictor object - int Lim; // maximum number of iterations - - public: - NonLinearLeastSquares(R1_Col_I_D& pred, int lim=1000, Real crit=0.0001) - : criterion(crit), Pred(pred), Lim(lim) {} - void Fit(const ColumnVector&, ColumnVector&); - Real ResidualVariance() const { return errorvar; } - void GetResiduals(ColumnVector& Z) const { Z = Y; } - void GetStandardErrors(ColumnVector&); - void GetCorrelations(SymmetricMatrix&); - void GetHatDiagonal(DiagonalMatrix&) const; - - private: - void MakeCovariance(); - }; - - - // The next class is the prototype class for calculating the - // log-likelihood. - // I assume first derivatives are available and something like the - // Fisher Information or variance/covariance matrix of the first - // derivatives or minus the matrix of second derivatives is - // available. This matrix must be positive definite. - - class LL_D_FI - { - protected: - ColumnVector para; // current parameter values - bool wg; // true if FI matrix wanted - - public: - virtual void Set(const ColumnVector& X) { para = X; } - // set parameter values - virtual void WG(bool wgx) { wg = wgx; } - // set wg - - virtual bool IsValid() { return true; } - // return true is para is OK - bool IsValid(const ColumnVector& X, bool wgx=true) - { Set(X); WG(wgx); return IsValid(); } - - virtual Real LogLikelihood() = 0; // return the loglikelihhod - Real LogLikelihood(const ColumnVector& X, bool wgx=true) - { Set(X); WG(wgx); return LogLikelihood(); } - - virtual ReturnMatrix Derivatives() = 0; - // column vector of derivatives - virtual ReturnMatrix FI() = 0; // Fisher Information matrix - virtual ~LL_D_FI() {} // to keep gnu happy - }; - - // This is the class for doing the maximum likelihood estimation - - class MLE_D_FI : public FindMaximum2 - { - // these replace the corresponding functions in FindMaximum2 - void Value(const ColumnVector&, bool, Real&, bool&); - bool NextPoint(ColumnVector&, Real&); - Real LastDerivative(const ColumnVector&); - - // the things we need for the analysis - LL_D_FI& LL; // reference to log-likelihood - int Lim; // maximum number of iterations - Real Criterion; // convergence criterion - ColumnVector Derivs; // for the derivatives - LowerTriangularMatrix LT; // Cholesky decomposition of FI - SymmetricMatrix Covariance; - DiagonalMatrix SE; - - public: - MLE_D_FI(LL_D_FI& ll, int lim=1000, Real criterion=0.0001) - : LL(ll), Lim(lim), Criterion(criterion) {} - void Fit(ColumnVector& Parameters); - void GetStandardErrors(ColumnVector&); - void GetCorrelations(SymmetricMatrix&); - - private: - void MakeCovariance(); - }; - - -#ifdef use_namespace -} -#endif - - - -#endif - -// body file: newmatnl.cpp - - - - diff --git a/lib/src/mixmod/NEWMAT/newmatrc.h b/lib/src/mixmod/NEWMAT/newmatrc.h deleted file mode 100644 index 6694742..0000000 --- a/lib/src/mixmod/NEWMAT/newmatrc.h +++ /dev/null @@ -1,170 +0,0 @@ -//$$ newmatrc.h definition file for row/column classes - -// Copyright (C) 1991,2,3,4,7: R B Davies - -#ifndef NEWMATRC_LIB -#define NEWMATRC_LIB 0 - -#ifdef use_namespace -namespace NEWMAT { -#endif - -#include "controlw.h" - - - /************** classes MatrixRowCol, MatrixRow, MatrixCol *****************/ - - // Used for accessing the rows and columns of matrices - // All matrix classes must provide routines for calculating matrix rows and - // columns. Assume rows can be found very efficiently. - - enum LSF { LoadOnEntry=1,StoreOnExit=2,DirectPart=4,StoreHere=8,HaveStore=16 }; - - - class LoadAndStoreFlag : public ControlWord - { - public: - LoadAndStoreFlag() {} - LoadAndStoreFlag(int i) : ControlWord(i) {} - LoadAndStoreFlag(LSF lsf) : ControlWord(lsf) {} - LoadAndStoreFlag(const ControlWord& cwx) : ControlWord(cwx) {} - }; - - class MatrixRowCol - // the row or column of a matrix - { - public: // these are public to avoid - // numerous friend statements - int length; // row or column length - int skip; // initial number of zeros - int storage; // number of stored elements - int rowcol; // row or column number - GeneralMatrix* gm; // pointer to parent matrix - Real* data; // pointer to local storage - LoadAndStoreFlag cw; // Load? Store? Is a Copy? - void IncrMat() { rowcol++; data += storage; } // used by NextRow - void IncrDiag() { rowcol++; skip++; data++; } - void IncrId() { rowcol++; skip++; } - void IncrUT() { rowcol++; data += storage; storage--; skip++; } - void IncrLT() { rowcol++; data += storage; storage++; } - - public: - void Zero(); // set elements to zero - void Add(const MatrixRowCol&); // add a row/col - void AddScaled(const MatrixRowCol&, Real); // add a multiple of a row/col - void Add(const MatrixRowCol&, const MatrixRowCol&); - // add two rows/cols - void Add(const MatrixRowCol&, Real); // add a row/col - void NegAdd(const MatrixRowCol&, Real); // Real - a row/col - void Sub(const MatrixRowCol&); // subtract a row/col - void Sub(const MatrixRowCol&, const MatrixRowCol&); - // sub a row/col from another - void RevSub(const MatrixRowCol&); // subtract from a row/col - void ConCat(const MatrixRowCol&, const MatrixRowCol&); - // concatenate two row/cols - void Multiply(const MatrixRowCol&); // multiply a row/col - void Multiply(const MatrixRowCol&, const MatrixRowCol&); - // multiply two row/cols - void KP(const MatrixRowCol&, const MatrixRowCol&); - // Kronecker Product two row/cols - void Copy(const MatrixRowCol&); // copy a row/col - void CopyCheck(const MatrixRowCol&); // ... check for data loss - void Check(const MatrixRowCol&); // just check for data loss - void Check(); // check full row/col present - void Copy(const Real*&); // copy from an array - void Copy(Real); // copy from constant - void Add(Real); // add a constant - void Multiply(Real); // multiply by constant - Real SumAbsoluteValue(); // sum of absolute values - Real MaximumAbsoluteValue1(Real r, int& i); // maximum of absolute values - Real MinimumAbsoluteValue1(Real r, int& i); // minimum of absolute values - Real Maximum1(Real r, int& i); // maximum - Real Minimum1(Real r, int& i); // minimum - Real Sum(); // sum of values - void Inject(const MatrixRowCol&); // copy stored els of a row/col - void Negate(const MatrixRowCol&); // change sign of a row/col - void Multiply(const MatrixRowCol&, Real); // scale a row/col - friend Real DotProd(const MatrixRowCol&, const MatrixRowCol&); - // sum of pairwise product - Real* Data() { return data; } - int Skip() { return skip; } // number of elements skipped - int Storage() { return storage; } // number of elements stored - int Length() { return length; } // length of row or column - void Skip(int i) { skip=i; } - void Storage(int i) { storage=i; } - void Length(int i) { length=i; } - void SubRowCol(MatrixRowCol&, int, int) const; - // get part of a row or column - MatrixRowCol() {} // to stop warning messages - ~MatrixRowCol(); - FREE_CHECK(MatrixRowCol) - }; - - class MatrixRow : public MatrixRowCol - { - public: - // bodies for these are inline at the end of this .h file - MatrixRow(GeneralMatrix*, LoadAndStoreFlag, int=0); - // extract a row - ~MatrixRow(); - void Next(); // get next row - FREE_CHECK(MatrixRow) - }; - - class MatrixCol : public MatrixRowCol - { - public: - // bodies for these are inline at the end of this .h file - MatrixCol(GeneralMatrix*, LoadAndStoreFlag, int=0); - // extract a col - MatrixCol(GeneralMatrix*, Real*, LoadAndStoreFlag, int=0); - // store/retrieve a col - ~MatrixCol(); - void Next(); // get next row - FREE_CHECK(MatrixCol) - }; - - // MatrixColX is an alternative to MatrixCol where the complete - // column is stored externally - - class MatrixColX : public MatrixRowCol - { - public: - // bodies for these are inline at the end of this .h file - MatrixColX(GeneralMatrix*, Real*, LoadAndStoreFlag, int=0); - // store/retrieve a col - ~MatrixColX(); - void Next(); // get next row - Real* store; // pointer to local storage - // less skip - FREE_CHECK(MatrixColX) - }; - - /**************************** inline bodies ****************************/ - - inline MatrixRow::MatrixRow(GeneralMatrix* gmx, LoadAndStoreFlag cwx, int row) - { gm=gmx; cw=cwx; rowcol=row; gm->GetRow(*this); } - - inline void MatrixRow::Next() { gm->NextRow(*this); } - - inline MatrixCol::MatrixCol(GeneralMatrix* gmx, LoadAndStoreFlag cwx, int col) - { gm=gmx; cw=cwx; rowcol=col; gm->GetCol(*this); } - - inline MatrixCol::MatrixCol(GeneralMatrix* gmx, Real* r, - LoadAndStoreFlag cwx, int col) - { gm=gmx; data=r; cw=cwx+StoreHere; rowcol=col; gm->GetCol(*this); } - - inline MatrixColX::MatrixColX(GeneralMatrix* gmx, Real* r, - LoadAndStoreFlag cwx, int col) - { gm=gmx; store=data=r; cw=cwx+StoreHere; rowcol=col; gm->GetCol(*this); } - - - inline void MatrixCol::Next() { gm->NextCol(*this); } - - inline void MatrixColX::Next() { gm->NextCol(*this); } - -#ifdef use_namespace -} -#endif - -#endif diff --git a/lib/src/mixmod/NEWMAT/newmatrm.cpp b/lib/src/mixmod/NEWMAT/newmatrm.cpp deleted file mode 100644 index 1524af1..0000000 --- a/lib/src/mixmod/NEWMAT/newmatrm.cpp +++ /dev/null @@ -1,189 +0,0 @@ -//$$newmatrm.cpp rectangular matrix operations - -// Copyright (C) 1991,2,3,4: R B Davies - - - -#include "newmat.h" -#include "newmatrm.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - -#ifdef DO_REPORT -#define REPORT { static ExeCounter ExeCount(__LINE__,12); ++ExeCount; } -#else -#define REPORT {} -#endif - - - // operations on rectangular matrices - - - void RectMatrixRow::Reset (const Matrix& M, int row, int skip, int length) - { - REPORT - RectMatrixRowCol::Reset - ( M.Store()+row*M.Ncols()+skip, length, 1, M.Ncols() ); - } - - void RectMatrixRow::Reset (const Matrix& M, int row) - { - REPORT - RectMatrixRowCol::Reset( M.Store()+row*M.Ncols(), M.Ncols(), 1, M.Ncols() ); - } - - void RectMatrixCol::Reset (const Matrix& M, int skip, int col, int length) - { - REPORT - RectMatrixRowCol::Reset - ( M.Store()+col+skip*M.Ncols(), length, M.Ncols(), 1 ); - } - - void RectMatrixCol::Reset (const Matrix& M, int col) - { - REPORT - RectMatrixRowCol::Reset( M.Store()+col, M.Nrows(), M.Ncols(), 1 ); - } - - - Real RectMatrixRowCol::SumSquare() const - { - REPORT - long_Real sum = 0.0; int i = n; Real* s = store; int d = spacing; - // while (i--) { sum += (long_Real)*s * *s; s += d; } - if (i) for(;;) - { sum += (long_Real)*s * *s; if (!(--i)) break; s += d; } - return (Real)sum; - } - - Real RectMatrixRowCol::operator*(const RectMatrixRowCol& rmrc) const - { - REPORT - long_Real sum = 0.0; int i = n; - Real* s = store; int d = spacing; - Real* s1 = rmrc.store; int d1 = rmrc.spacing; - if (i!=rmrc.n) - { - Tracer tr("newmatrm"); - Throw(InternalException("Dimensions differ in *")); - } - // while (i--) { sum += (long_Real)*s * *s1; s += d; s1 += d1; } - if (i) for(;;) - { sum += (long_Real)*s * *s1; if (!(--i)) break; s += d; s1 += d1; } - return (Real)sum; - } - - void RectMatrixRowCol::AddScaled(const RectMatrixRowCol& rmrc, Real r) - { - REPORT - int i = n; Real* s = store; int d = spacing; - Real* s1 = rmrc.store; int d1 = rmrc.spacing; - if (i!=rmrc.n) - { - Tracer tr("newmatrm"); - Throw(InternalException("Dimensions differ in AddScaled")); - } - // while (i--) { *s += *s1 * r; s += d; s1 += d1; } - if (i) for (;;) - { *s += *s1 * r; if (!(--i)) break; s += d; s1 += d1; } - } - - void RectMatrixRowCol::Divide(const RectMatrixRowCol& rmrc, Real r) - { - REPORT - int i = n; Real* s = store; int d = spacing; - Real* s1 = rmrc.store; int d1 = rmrc.spacing; - if (i!=rmrc.n) - { - Tracer tr("newmatrm"); - Throw(InternalException("Dimensions differ in Divide")); - } - // while (i--) { *s = *s1 / r; s += d; s1 += d1; } - if (i) for (;;) { *s = *s1 / r; if (!(--i)) break; s += d; s1 += d1; } - } - - void RectMatrixRowCol::Divide(Real r) - { - REPORT - int i = n; Real* s = store; int d = spacing; - // while (i--) { *s /= r; s += d; } - if (i) for (;;) { *s /= r; if (!(--i)) break; s += d; } - } - - void RectMatrixRowCol::Negate() - { - REPORT - int i = n; Real* s = store; int d = spacing; - // while (i--) { *s = - *s; s += d; } - if (i) for (;;) { *s = - *s; if (!(--i)) break; s += d; } - } - - void RectMatrixRowCol::Zero() - { - REPORT - int i = n; Real* s = store; int d = spacing; - // while (i--) { *s = 0.0; s += d; } - if (i) for (;;) { *s = 0.0; if (!(--i)) break; s += d; } - } - - void ComplexScale(RectMatrixCol& U, RectMatrixCol& V, Real x, Real y) - { - REPORT - int n = U.n; - if (n != V.n) - { - Tracer tr("newmatrm"); - Throw(InternalException("Dimensions differ in ComplexScale")); - } - Real* u = U.store; Real* v = V.store; - int su = U.spacing; int sv = V.spacing; - //while (n--) - //{ - // Real z = *u * x - *v * y; *v = *u * y + *v * x; *u = z; - // u += su; v += sv; - //} - if (n) for (;;) - { - Real z = *u * x - *v * y; *v = *u * y + *v * x; *u = z; - if (!(--n)) break; - u += su; v += sv; - } - } - - void Rotate(RectMatrixCol& U, RectMatrixCol& V, Real tau, Real s) - { - REPORT - // (U, V) = (U, V) * (c, s) where tau = s/(1+c), c^2 + s^2 = 1 - int n = U.n; - if (n != V.n) - { - Tracer tr("newmatrm"); - Throw(InternalException("Dimensions differ in Rotate")); - } - Real* u = U.store; Real* v = V.store; - int su = U.spacing; int sv = V.spacing; - //while (n--) - //{ - // Real zu = *u; Real zv = *v; - // *u -= s * (zv + zu * tau); *v += s * (zu - zv * tau); - // u += su; v += sv; - //} - if (n) for(;;) - { - Real zu = *u; Real zv = *v; - *u -= s * (zv + zu * tau); *v += s * (zu - zv * tau); - if (!(--n)) break; - u += su; v += sv; - } - } - - - - -#ifdef use_namespace -} -#endif - - diff --git a/lib/src/mixmod/NEWMAT/newmatrm.h b/lib/src/mixmod/NEWMAT/newmatrm.h deleted file mode 100644 index 4d16a32..0000000 --- a/lib/src/mixmod/NEWMAT/newmatrm.h +++ /dev/null @@ -1,122 +0,0 @@ -//$$newmatrm.h rectangular matrix operations - -// Copyright (C) 1991,2,3,4: R B Davies - -#ifndef NEWMATRM_LIB -#define NEWMATRM_LIB 0 - -#ifdef use_namespace -namespace NEWMAT { -#endif - - // operations on rectangular matrices - - class RectMatrixCol; - - class RectMatrixRowCol - // a class for accessing rows and columns of rectangular matrices - { - protected: -#ifdef use_namespace // to make namespace work - public: -#endif - Real* store; // pointer to storage - int n; // number of elements - int spacing; // space between elements - int shift; // space between cols or rows - RectMatrixRowCol(Real* st, int nx, int sp, int sh) - : store(st), n(nx), spacing(sp), shift(sh) {} - void Reset(Real* st, int nx, int sp, int sh) - { store=st; n=nx; spacing=sp; shift=sh; } - public: - Real operator*(const RectMatrixRowCol&) const; // dot product - void AddScaled(const RectMatrixRowCol&, Real); // add scaled - void Divide(const RectMatrixRowCol&, Real); // scaling - void Divide(Real); // scaling - void Negate(); // change sign - void Zero(); // zero row col - Real& operator[](int i) { return *(store+i*spacing); } // element - Real SumSquare() const; // sum of squares - Real& First() { return *store; } // get first element - void DownDiag() { store += (shift+spacing); n--; } - void UpDiag() { store -= (shift+spacing); n++; } - friend void ComplexScale(RectMatrixCol&, RectMatrixCol&, Real, Real); - friend void Rotate(RectMatrixCol&, RectMatrixCol&, Real, Real); - FREE_CHECK(RectMatrixRowCol) - }; - - class RectMatrixRow : public RectMatrixRowCol - { - public: - RectMatrixRow(const Matrix&, int, int, int); - RectMatrixRow(const Matrix&, int); - void Reset(const Matrix&, int, int, int); - void Reset(const Matrix&, int); - Real& operator[](int i) { return *(store+i); } - void Down() { store += shift; } - void Right() { store++; n--; } - void Up() { store -= shift; } - void Left() { store--; n++; } - FREE_CHECK(RectMatrixRow) - }; - - class RectMatrixCol : public RectMatrixRowCol - { - public: - RectMatrixCol(const Matrix&, int, int, int); - RectMatrixCol(const Matrix&, int); - void Reset(const Matrix&, int, int, int); - void Reset(const Matrix&, int); - void Down() { store += spacing; n--; } - void Right() { store++; } - void Up() { store -= spacing; n++; } - void Left() { store--; } - friend void ComplexScale(RectMatrixCol&, RectMatrixCol&, Real, Real); - friend void Rotate(RectMatrixCol&, RectMatrixCol&, Real, Real); - FREE_CHECK(RectMatrixCol) - }; - - class RectMatrixDiag : public RectMatrixRowCol - { - public: - RectMatrixDiag(const DiagonalMatrix& D) - : RectMatrixRowCol(D.Store(), D.Nrows(), 1, 1) {} - Real& operator[](int i) { return *(store+i); } - void DownDiag() { store++; n--; } - void UpDiag() { store--; n++; } - FREE_CHECK(RectMatrixDiag) - }; - - - inline RectMatrixRow::RectMatrixRow - (const Matrix& M, int row, int skip, int length) - : RectMatrixRowCol( M.Store()+row*M.Ncols()+skip, length, 1, M.Ncols() ) {} - - inline RectMatrixRow::RectMatrixRow (const Matrix& M, int row) - : RectMatrixRowCol( M.Store()+row*M.Ncols(), M.Ncols(), 1, M.Ncols() ) {} - - inline RectMatrixCol::RectMatrixCol - (const Matrix& M, int skip, int col, int length) - : RectMatrixRowCol( M.Store()+col+skip*M.Ncols(), length, M.Ncols(), 1 ) {} - - inline RectMatrixCol::RectMatrixCol (const Matrix& M, int col) - : RectMatrixRowCol( M.Store()+col, M.Nrows(), M.Ncols(), 1 ) {} - - inline Real square(Real x) { return x*x; } - inline Real sign(Real x, Real y) - { return (y>=0) ? x : -x; } // assume x >=0 - - - - - - -#ifdef use_namespace -} -#endif - -#endif - -// body file: newmatrm.cpp - - diff --git a/lib/src/mixmod/NEWMAT/nm10.htm b/lib/src/mixmod/NEWMAT/nm10.htm deleted file mode 100644 index 2c06807..0000000 --- a/lib/src/mixmod/NEWMAT/nm10.htm +++ /dev/null @@ -1,3512 +0,0 @@ - - - - - - - - - -Newmat10 documentation - - - - -

Documentation for newmat10A, a matrix library in C++

-

next - skip - -up - start
-return to online documentation page

-

Copyright (C) 1991,2,3,4,5,6,7,8,9,2000,1,2: R B Davies

-

8 October, 2002.

- - - - - -
1. -Introduction
-2. Getting started
-3. Reference manual
4. -Error messages
-5. Design of the library
-

This is the how to use documentation for newmat plus some -background information on its design.

-

There is additional support material on my web site. -

-

Navigation:  This page is arranged in sections, -sub-sections and sub-sub-sections; four cross-references are given at the top -of these. Next takes you through the sections, sub-sections and -sub-sub-sections in order. Skip goes to the next section, sub-section or -sub-sub-section at the same level in the hierarchy as the section, sub-section -or sub-sub-section that you are currently reading. Up takes you up one -level in the hierarchy and start gets you back here.

-

Please read the sections on customising and -compilers before -attempting to compile newmat.

-

1. Introduction

-

next - skip - -up - start

- - - - - -
1.1 -Conditions of use
-1.2 Description
-1.3 Is this the library for you?
-1.4 Other matrix libraries
1.5 -Where to find this library
-1.6 How to contact the author
-1.7 Change history
-1.8 References
-

1.1 Conditions of use

-

next - skip - -up - start

-

There are no restrictions on the use of newmat except that I take no -liability for any problems that may arise from this use.

-

I welcome its distribution as part of low cost CD-ROM collections.

-

You can use it in your commercial projects. However, if you distribute the -source, please make it clear which parts are mine and that they are available -essentially for free over the Internet.

-
-

Please understand that there may still be bugs and errors. Use at -your own risk. I take no responsibility for any errors or omissions in this -package or for any misfortune that may befall you or others as a result of its -use.

-
-

Please report bugs to me at robert (at) statsresearch.co.nz

-

When reporting a bug please tell me which C++ compiler you are using, and -what version. Also give me details of your computer. And tell me which version -of newmat (e.g. newmat03 or newmat04) you are using. Note any changes -you have made to my code. If at all possible give me a piece of code -illustrating the bug. See the problem report form.

-

Please do report bugs to me.

-

1.2 General description -

-

next - skip - -up - start

-

The package is intended for scientists and engineers who need to manipulate -a variety of types of matrices using standard matrix operations. Emphasis is on -the kind of operations needed in statistical calculations such as least -squares, linear equation solve and eigenvalues.

-

It supports matrix types

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Matrixrectangular matrix
nricMatrixfor use with Numerical Recipes in C programs
UpperTriangularMatrix 
LowerTriangularMatrix 
DiagonalMatrix 
SymmetricMatrix 
BandMatrix 
UpperBandMatrixupper triangular band matrix
LowerBandMatrixlower triangular band matrix
SymmetricBandMatrix 
RowVectorderived from Matrix
ColumnVectorderived from Matrix
IdentityMatrixdiagonal matrix, elements have same value
-
-

Only one element type (float or double) is supported.

-

The package includes the operations *, +, -, -Kronecker product, Schur product, concatenation, inverse, transpose, conversion between types, submatrix, -determinant, Cholesky decomposition, QR triangularisation, singular value -decomposition, eigenvalues of a symmetric matrix, sorting, fast Fourier -transform, printing and an interface with Numerical Recipes in C.

-

It is intended for matrices in the range 10 x 10 to the maximum size your -machine will accommodate in a single array. The number of elements in an array -cannot exceed the maximum size of an int. The package will work for very -small matrices but becomes rather inefficient. Some of the factorisation -functions are not (yet) optimised for paged memory and so become inefficient -when used with very large matrices.

-

A lazy evaluation approach to evaluating matrix expressions is used -to improve efficiency and reduce the use of temporary storage.

-

I have tested versions of the package on variety of compilers and platforms -including Borland, Gnu, Microsoft, Sun and Watcom. For more details -see the section on compilers.

-

1.3 Is this the library for -you?

-

next - skip - -up - start

-

Do you

-
    -
  • understand * to mean matrix multiply and not element by element -multiply
  • -
  • need matrix operators such as * and + defined as -operators so you can write things like X = A * (B + C);
  • -
  • need a variety of types of matrices (but not sparse)
  • -
  • need only one element type (float or double)
  • -
  • work with matrices in the range 10 x 10 up to what can be stored in memory -
  • -
  • tolerate a moderately large but not huge package
  • -
  • need high quality but not necessarily the latest numerical methods.
  • -
-

Then newmat may be the right matrix library for you.

-

1.4 Other matrix libraries -

-

next - skip - -up - start

-

For details of other C++ matrix libraries look at -http://www.robertnz.net/cpp_site.html. -Look at the section lists of libraries which gives the locations of -several very comprehensive lists of matrix and other C++ libraries and at the -section source code.

-

1.5 Where to find this -library

-

next - skip - -up - start

- -

1.6 How to contact the -author

-

next - skip - -up - start

-
   Robert Davies
-   16 Gloucester Street
-   Wilton
-   Wellington
-   New Zealand
-
-   email: robert(at)statsresearch.co.nz
-
- -

1.7 Change history

-

next - skip - -up - start

-

Newmat10A - October, 2002:

-

Fix error in Kronecker product; fixes for Intel and GCC3 -compilers.

-

Newmat10 - January, 2002:

-

Improve compatibility with GCC, fix errors in FFT and -GenericMatrix, update simulated exceptions, maxima, minima, determinant, dot -product and Frobenius norm functions, update make files for CC and GCC, faster -FFT, A.ReSize(B), fix pointer arithmetic, << for loading -data into rows, IdentityMatrix, Kronecker product, sort singular values.

-

Newmat09 - September, 1997:

-

Operator ==, !=, +=, -=, -*=, /=, |=, &=. Follow new rules for -for (int i; ... ) construct. Change Boolean, TRUE, FALSE to bool, true, -false. Change ReDimension to ReSize. SubMatrix allows zero rows and columns. -Scalar +, - or * matrix is OK. Simplify simulated -exceptions. Fix non-linear programs for AT&T compilers. Dummy inequality -operators. Improve internal row/column operations. Improve matrix LU -decomposition. Improve sort. Reverse function. IsSingular function. Fast trig -transforms. Namespace definitions.

-

Newmat08A - July, 1995:

-

Fix error in SVD.

-

Newmat08 - January, 1995:

-

Corrections to improve compatibility with Gnu, Watcom. -Concatenation of matrices. Elementwise products. Option to use compilers -supporting exceptions. Correction to exception module to allow global -declarations of matrices. Fix problem with inverse of symmetric matrices. Fix -divide-by-zero problem in SVD. Include new QR routines. Sum function. -Non-linear optimisation. GenericMatrices.

-

Newmat07 - January, 1993

-

Minor corrections to improve compatibility with Zortech, -Microsoft and Gnu. Correction to exception module. Additional FFT functions. -Some minor increases in efficiency. Submatrices can now be used on RHS of =. -Option for allowing C type subscripts. Method for loading short lists of -numbers.

-

Newmat06 - December 1992:

-

Added band matrices; 'real' changed to 'Real' (to avoid -potential conflict in complex class); Inject doesn't check for no loss of -information; fixes for AT&T C++ version 3.0; real(A) becomes A.AsScalar(); -CopyToMatrix becomes AsMatrix, etc; .c() is no longer required (to be deleted -in next version); option for version 2.1 or later. Suffix for include files -changed to .h; BOOL changed to Boolean (BOOL doesn't work in g++ v 2.0); -modifications to allow for compilers that destroy temporaries very quickly; -(Gnu users - see the section of compilers). Added CleanUp, -LinearEquationSolver, primitive version of exceptions.

-

Newmat05 - June 1992:

-

For private release only

-

Newmat04 - December 1991:

-

Fix problem with G++1.40, some extra documentation -

-

Newmat03 - November 1991:

-

Col and Cols become Column and Columns. Added Sort, SVD, -Jacobi, Eigenvalues, FFT, real conversion of 1x1 matrix, Numerical Recipes -in C interface, output operations, various scalar functions. Improved -return from functions. Reorganised setting options in "include.hxx". -

-

Newmat02 - July 1991:

-

Version with matrix row/column operations and numerous -additional functions.

-

Matrix - October 1990:

-

Early version of package.

-

1.8 References

-

next - skip - -up - start

-
    -
  • The matrix LU decomposition is from Golub, G.H. & Van Loan, C.F. -(1996), Matrix Computations, published by Johns Hopkins University -Press.
  • -
  • Part of the matrix inverse/solve routine is adapted from Press, Flannery, -Teukolsky, Vetterling (1988), Numerical Recipes in C, published by the -Cambridge University Press.
  • -
  • Many of the advanced matrix routines are adapted from routines in Wilkinson -and Reinsch (1971), Handbook for Automatic Computation, Vol II, Linear -Algebra published by Springer Verlag.
  • -
  • The fast Fourier transform is adapted from Carl de Boor (1980), Siam J -Sci Stat Comput, pp173-8 and the fast trigonometric transforms from Charles -Van Loan (1992) in Computational frameworks for the fast Fourier -transform published by SIAM.
  • -
  • The sort function is derived from Sedgewick, Robert (1992), Algorithms -in C++ published by Addison Wesley.
  • -
-

For references about Newmat see

-
    -
  • Davies, R.B. (1994) Writing a matrix package in C++. In OON-SKI'94: The -second annual object-oriented numerics conference, pp 207-213. Rogue Wave -Software, Corvallis.
  • -
  • Eddelbuttel, Dirk (1996) Object-oriented econometrics: matrix programming -in C++ using GCC and Newmat. Journal of Applied Econometrics, Vol 11, No 2, pp -199-209.
  • -
-

2. Getting started

-

next - skip - -up - start

- - - - - -
2.1 Overview
-2.2 Make files
-2.3 Customising
-2.4 Compilers
-2.5 Updating from previous versions
-2.6 Catching exceptions
2.7 Example
-2.8 Testing
-2.9 Bugs
-2.10 Files in newmat10
-2.11 Problem report form
-

2.1 Overview

-

next - skip - -up - start

-

I use .h as the suffix of definition files and .cpp as the suffix of C++ -source files.

-

You will need to compile all the *.cpp files listed as program files in the -files section to get the complete package. Ideally you -should store the resulting object files as a library. The tmt*.cpp files are -used for testing, example.cpp is an example and sl_ex.cpp, nl_ex.cpp and garch.cpp are examples -of the non-linear solve and optimisation routines. A -demonstration and test of the exception mechanism is in test_exc.cpp.

-

I include a number of make files for compiling the example and the -test package. See the section on make files for details. -But with the PC compilers, its pretty quick just to load all the files in the -interactive environments by pointing and clicking.

-

Use the large or win32 console model when you are using a PC. Do not -outline inline functions. You may need to increase the stack size.

-

Your source files that access the newmat will need to #include one or more -of the following files.

- - - - - - - - - - - - - - - - - - - - - -
include.hto access just the compiler options
newmat.hto access just the main matrix library (includes include.h)
newmatap.hto access the advanced matrix routines such as Cholesky decomposition, QR -triangularisation etc (includes newmat.h)
newmatio.hto access the output routines (includes newmat.h) You -can use this only with compilers that support the standard input/output -routines including manipulators
newmatnl.hto access the non-linear optimisation routines (includes newmat.h)
-

See the section on customising to see how to edit -include.h for your environment and the section on compilers for any special problems with the compiler you -are using.

-

2.2 Make files

-

next - skip - -up - start

-

I have included make files for CC, Borland 5.5 and Gnu compilers. You -can generate make files for a number of other files with my -genmake utility. Make files provide -a way of compiling your programs without using the IDE that comes with -PC compilers. See the files section for details. See the -example for how to use them. Leave out the target name -to compile and link all my examples and test files.

-

PC

-

I include a make file for Borland 5.5. You will need to edit it to show where -you have stored your Borland compiler. For make files for other compilers use my -genmake utility.

-

Unix

-

The make file for the Unix CC compilers link a .cxx file to each .cpp -file since some of these compilers do not recognise .cpp as a legitimate -extension for a C++ file. I suggest you delete this part of the make -file and, if necessary, rename the .cpp files to something your compiler -recognises.

-

My make file for Gnu GCC on Unix systems is for use with -gmake rather than make. I assume your compiler recognises the -.cpp extension. Ordinary make works with it on the Sun but not the -Silicon Graphics or HP machines. On Linux use make.

-

My make file for the CC compilers works with the ordinary make.

-

To compile everything with the CC compiler use

-
   make -f nm_cc.mak
-
- -

or for the gnu compiler use

-
   gmake -f nm_gnu.mak
-
- -

There is a line in the make file for CC rm -f $*.cxx. Some systems -won't accept this line and you will need to delete it. In this case, if you -have a bad compile and you are using my scheme for linking .cxx files, you will -need to delete the .cxx file link generated by that compile before you can do -the next one.

-

2.3 Customising

-

next - skip - -up - start

-

The file include.h sets a variety of options including several -compiler dependent options. You may need to edit include.h to get the options -you require. If you are using a compiler different from one I have worked with -you may have to set up a new section in include.h appropriate for your -compiler.

-

Borland, Turbo, Gnu, Microsoft and Watcom are recognised automatically. If -none of these are recognised a default set of options is used. These are fine -for AT&T, HPUX and Sun C++. If you using a compiler I don't know about you -may have to write a new set of options.

-

There is an option in include.h for selecting whether you use compiler -supported exceptions, simulated exceptions, or disable exceptions. I now set - compiler supported exceptions as the default. Use the option for -compiler supported exceptions if and only if you have set the option on -your compiler to recognise exceptions. Disabling exceptions sometimes helps -with compilers that are incompatible with my exception simulation scheme.

-

If you are using an older compiler that does not recognises -bool as required by the standard then de-activate the statement -#define bool_LIB. This will turn on my Boolean class.

-

Activate the appropriate statement to make the element type float or double. -

-

I suggest you leave the options TEMPS_DESTROYED_QUICKLY, -TEMPS_DESTROYED_QUICKLY_R de-activated, unless you are using a very old -version of Gnu compiler (<2.6). This stores the trees describing -matrix expressions on the stack rather than the heap. See the discussion on -destruction of temporaries for more explanation.

-

The option DO_FREE_CHECK is used for tracking memory -leaks and normally should not be activated.

-

Activate SETUP_C_SUBSCRIPTS if you want to use traditional C style -element access. Note that this does not change -the starting point for indices when you are using round brackets for accessing -elements or selecting submatrices. It does enable you to use C style square -brackets.

-

Activate #define use_namespace if you want to use namespaces. Do this only if you are sure your compiler -supports namespaces. If you do turn this option on, be prepared to turn it off -again if the compiler reports inaccessible variables or the linker reports -missing links.

-

Activate #define _STANDARD_ to use the standard names for the -included files and to find the floating point precision data using the floating -point standard. This will work only with the most recent compilers. This is -automatically turned on for the Gnu compiler version 3 and the Intel compiler -for Linux.

-

If you haven't defined _STANDARD_ and are using a compiler that -include.h does not recognise and you want to pick up the floating point -precision data from float.h then activate #define use_float_h. -Otherwise the floating point precision data will be accessed from -values.h. You may need to do this with computers from Digital, in -particular.

-

2.4 Compilers

-

next - skip - -up - start

- - - - - -
-2.4.1 AT&T
-2.4.2 Borland
-2.4.3 Gnu G++
-2.4.4 HPUX
-2.4.5 Intel
-2.4.6 Microsoft
-2.4.7 Sun
-2.4.8 Watcom
-

I have tested this library on a number of compilers. Here are the levels of -success and any special considerations. In most cases I have chosen code that -works under all the compilers I have access to, but I have had to include some -specific work-arounds for some compilers. For the PC versions, I use a Pentium III computer running windows 2000 or Linux -(Red Hat 7.1). The older compilers are tested on older computers. The Unix versions are on a Sun Sparc -station. Thanks to Victoria University for access to the Sparc.

-

I have set up a block of code for each of the compilers in include.h. Turbo, -Borland, Gnu, Microsoft and Watcom are recognised automatically. There is a -default option that works for AT&T, Sun C++ and HPUX. So you don't -have to make any changes for these compilers. Otherwise you may have to build -your own set of options in include.h.

-

2.4.1 AT&T

-

next - skip - -up - start

-

The AT&T compiler used to be available on a wide variety of Unix -workstations. I don't know if anyone still uses it. However the AT&T options are -the default if your compiler is not recognised.

-

AT&T C++ 2.1; 3.0.1 on a Sun: Previous versions worked on these -compilers, which I no longer have access to.

-

In AT&T 2.1 you may get an error when you use an expression for the -single argument when constructing a Vector or DiagonalMatrix or one of the -Triangular Matrices. You need to evaluate the expression separately.

-

2.4.2 Borland

-

next - skip - -up - start

-

Newer compilers

-

Borland Builder version 6: This is not compatible with -newmat10. Use newmat11 instead.

-

Borland Builder version 5: This works fine in console mode and no -special editing of the source codes is required. I haven't tested it in GUI -mode. You can set the newmat10 options to use namespace and the standard -library. You -should turn off the Borland option to use pre-compiled headers. There -are notes on compiling with the IDE on my website. -Alternatively you can use the nm_b55.mak make file.

-

Borland Builder version 4: I have successfully used this on older -versions of newmat using the -console wizard (menu item file/new - select new tab). Use compiler -exceptions. Suppose you are compiling my test program tmt. Rename my -main() function in tmt.cpp to my_main(). Rename -tmt.cpp to tmt_main.cpp. Borland will generate a new file -tmt.cpp containing their main() function. Put the line int -my_main(); above this function and put return my_main(); into the -body of main().

-

Borland compiler version 5.5: this is the free C++ compiler available -from Borland's web site. I suggest you use -the compiler supported exceptions and turn on standard in include.h. You -can use the make file nm_b55.mak after editing to correct the file locations for -your system.

-

Older compilers

-

Borland C++ 3.1, 5.02: Version 5.02 is still one of my development -platforms, so naturally everything works with this compiler. You will need to use -the large or 32 bit flat model. If you are not debugging, turn off the options -that collect debugging information. Use my -simulated exceptions. I haven't tested the most recent version with version 3.1.

-

If you are using versions earlier than 5 remember to edit include.h to -activate my Boolean class.

-

When running my test program under ms-dos you may run out of memory. Either -compile the test routine to run under easywin or use simulated exceptions -rather than the built in exceptions.

-

If you can, upgrade to windows 9X or window NT and use the 32 bit console -model.

-

If you are using the 16 bit large model, don't forget to keep all matrices -less than 64K bytes in length (90x90 for a rectangular matrix if you are using -double as your element type). Otherwise your program will crash -without warning or explanation. You will need to break the tmt set of test files into several parts to get the program -to fit into your computer and run without stack overflow.

-

One version of Borland had DBL_MIN incorrectly defined. If you are using an -older version of Borland and are getting strange numerical errors in the test -programs reinstate the commented out statements in precision.h.

-

You can generate make files for versions 5 or 3.1 with my -genmake utility.

-

2.4.3 Gnu G++

-

next - skip - -up - start

-

Gnu G++ 2.95, 2.96, 3.1: This works OK. If you are using a much -earlier version see if you can upgrade. You can't use namespace or standard with -the 2.9X versions. Standard is automatically turned on with 3.X.

-

If you are using 2.6 or earlier remember to edit include.h to activate my -Boolean class.

-

For versions earlier than 2.6.0 you must enable the options -TEMPS_DESTROYED_QUICKLY and TEMPS_DESTROYED_QUICKLY_R. You can't use -expressions like Matrix(X*Y) in the middle of an expression and -(Matrix)(X*Y) is unreliable. If you write a function returning a -matrix, you MUST use the ReturnMatrix method described in -this documentation. This is because g++ destroys temporaries occurring in an -expression too soon for the two stage way of evaluating expressions that newmat -uses. You will have problems with versions of Gnu earlier than 2.3.1.

-

Linux: It works fine on my copy of G++ (2.96) that came with RedHat -7.3. Use -compiler supported exceptions. You can use namespace but not the -standard option.

-

In 2.6.?, fabs(*X++) causes a problem. You may need to write you -own non-inlined version.

-

2.4.4 HP-UX

-

next - skip - -up - start

-

HP 9000 series HP-UX. I no longer have access to this compiler. Newmat09 -worked without problems with the simulated exceptions; haven't tried the -built-in exceptions.

-

With recent versions of the compiler you may get warning messages like -Unsafe cast between pointers/references to incomplete classes. At -present, I think these can be ignored.

-

Here are comments I made in 1997.

-

I have tried the library on two versions of HP-UX. (I don't know the version -numbers, the older is a clone of AT&T 3, the newer is HP's version with -exceptions). Both worked after the modifications described in this section. -

-

With the older version of the compiler I needed to edit the math.h library -file to remove a duplicate definition of abs.

-

With the newer version you can set the +eh option to enable exceptions and -activate the UseExceptions option in include.h. If you are using my make file, -you will need to replace CC with CC +eh where ever CC occurs. I recommend that -you do not do this and either disable exceptions or use my simulated -exceptions. I get core dumps when I use the built-in exceptions and suspect -they are not sufficiently debugged as yet.

-

If you are using my simulated exceptions you may get a mass of error -messages from the linker about __EH_JMPBUF_TEMP. In this case get file setjmp.h -(in directory /usr/include/CC ?) and put extern in front of the line

-
   jmp_buf * __EH_JMPBUF_TEMP;
-
- -

The file setjmp.h is accessed in my file myexcept.h. You may want to change -the #include statement to access your edited copy of setjmp.h.

- -

2.4.5 Intel

-

next - skip - -up - start

- -

Newmat works correctly with the Intel 5 C++ compiler for Windows and the free -versions 5 and 6 for Linux. Standard is automatically switched on for the Linux -versions.

- -

2.4.6 Microsoft

-

next - skip - -up - start

-

Newer versions

-

See my web site for instructions how to work -Microsoft's IDE.

-

Microsoft Visual C++ 7: This works OK. Note that all my tests have -been in console mode. You can turn on my standard option but I am still a bit -wary about the namespace option.

-

Microsoft Visual C++ 6: Get the latest service pack. I have tried this -in console mode and it seems to work satisfactorily. Use the compiler supported exceptions. You -may be able to -use the namespace and standard options but I suggest not using namespace. If you want to work under MFC -you may need to #include "stdafx.h" at the beginning of each .cpp file.

-

Microsoft Visual C++ 5: I have tried this in console mode and it -seems to work satisfactorily. There may be a problem with namespace (fixed by Service Pack 3?). Turn optimisation -off. Use the compiler supported exceptions. If -you want to work under MFC  -you may need to #include "stdafx.h" at the -beginning of each .cpp file.

-

Older versions

-

Microsoft Visual C++ 2.0: This used to work OK. I haven't tried it with -recent versions of newmat.

-

You must #define TEMPS_DESTROYED_QUICKLY owing to a bug in version -7 (at least) of MSC. There are some notes in the file include.h on -changes to run under version 7. I haven't tried newmat10 on version 7.

-

Microsoft Visual C++ 1.51. Disable exceptions, comment out the line in -include.h #define TEMPS_DESTROYED_QUICKLY_R. In tmt.cpp, -comment out the Try and CatchAll lines at the beginning of -main() and the line trymati(). You can use the makefile -ms.mak. You will probably need to break the tmt -test files into two parts to get the program to link.

-

If you can, upgrade to windows 95, 98 or window NT and use the 32 bit -console model.

-

If you are using the 16 bit large model, don't forget to keep all matrices -less than 64K bytes in length (90x90 for a rectangular matrix if you are using -double as your element type). Otherwise your program will crash -without warning or explanation. You may need to break the tmt set of test files into two parts to get the program to -fit into your computer.

-

Microsoft Visual C++ 4: I haven't tried this - a correspondent reports: I -use Microsoft Visual C++ Version 4. there is only one minor problem. In all -files you must include #include "stdafx.h" (presumably if -you are using MFC). This file contains essential information for VC++. Leave it -out and you get Unexpected end of file.

-

2.4.7 Sun

-

next - skip - -up - start

-

Sun C++ (version 4.2, version 6): These seem to work fine with -compiler supported exceptions. Sun C++ (version -5): There seems to be a problem with exceptions. If you use my simulated -exceptions the non-linear optimisation programs hang. If you use the compiler -supported exceptions my tmt and test_exc programs crash. You should -disable exceptions.

-

2.4.8 Watcom

-

next - skip - -up - start

-

Watcom C++ (version 10a): this works fine. You may need to increase -the stack size to 16384. With this elderly compiler, use my simulated exceptions -and simulated bool class (comment out the line #define bool_LIB 0 in -include.h).  I haven't tried more recent versions of Watcom. (I can -compile with the downloadable version of Watcom 11c but haven't found out -how to link the files).

-

2.5 Updating from previous -versions

-

next - skip - -up - start

-

Newmat10 includes new maxima, minima, -determinant, dot product and Frobenius norm functions, a -faster FFT, revised make files for GCC -and CC compilers, several corrections, new ReSize function, IdentityMatrix -and Kronecker Product. Singular values from -SVD are sorted. The program files include a new file, newfft.cpp, so you -will need to include this in the list of files in your IDE and make files. There -is also a new test file tmtm.cpp. -Pointer arithmetic now mostly meets requirements of -standard. You can use << to load data into rows -of a matrix. The default options in include.h have been -changed. If you are updating from a beta version of newmat09 look through the -next section as there were some late changes to newmat09.

-

If you are upgrading from newmat08 note the following: -

-
    -
  • Boolean, TRUE, FALSE are now bool, true, false. See -customising if your compiler supports the bool class. -
  • -
  • ReDimension is now ReSize. -
  • -
  • The simulated exception package has -been updated.
  • -
  • Operators ==, !=, +=, --=, *=, |=, &= are now supported as -binary matrix operators.
  • -
  • A+=f, A-=f, A*=f, A/=f, -f+A, f-A, f*A are supported for A -matrix, f scalar.
  • -
  • Fast trigonometric transforms. -
  • -
  • Reverse function for reversing order of -elements in a vector or matrix.
  • -
  • IsSingular function.
  • -
  • An option is included for defining namespaces.
  • -
  • Dummy inequality operators are defined for compatibility -with the STL.
  • -
  • The row/column classes in newmat3.cpp have been modified to -improve efficiency and correct an invalid use of pointer arithmetic. Most users -won't be using these classes explicitly; if you are, please contact me for -details of the changes.
  • -
  • Matrix LU decomposition rewritten (faster for large arrays). -
  • -
  • The sort function rewritten (faster).
  • -
  • The documentation files newmata.txt and newmatb.txt have -been amalgamated and both are included in the hypertext version.
  • -
  • Some of the make files reorganised -again.
  • -
-

If you are upgrading from newmat07 note the following: -

-
    -
  • .cxx files are now .cpp files. Some versions of won't accept -.cpp. The make files for Gnu and AT&T link the .cpp files to .cxx -files before compilation and delete the links after compilation.
  • -
  • An option in include.h allows you to -use compiler supported exceptions, simulated exceptions or disable exceptions. -Edit the file include.h to select one of these three options. Don't simulate -exceptions if you have set your compiler's option to implement exceptions. -
  • -
  • New QR decomposition functions. -
  • -
  • A non-linear least squares class. -
  • -
  • No need to explicitly set the AT&T option in include.h. -
  • -
  • Concatenation and elementwise -multiplication.
  • -
  • A new GenericMatrix class. -
  • -
  • Sum function.
  • -
  • Some of the make files reorganised. -
  • -
-

If you are upgrading from newmat06 note the following: -

-
    -
  • If you are using << to load a Real into a submatrix -change this to =.
  • -
-

If you are upgrading from newmat03 or newmat04 -note the following

-
    -
  • .hxx files are now .h files
  • -
  • real changed to Real
  • -
  • BOOL changed to Boolean
  • -
  • CopyToMatrix changed to AsMatrix, etc
  • -
  • real(A) changed to A.AsScalar()
  • -
-

The current version is quite a bit longer that newmat04, so -if you are almost out of space with newmat04, don't throw newmat04 away until -you have checked your program will work under this version.

-

See the change history for other changes.

-

2.6 Catching exceptions

-

This section applies particularly to people using compiler supported -exceptions rather than my simulated exceptions.

-

If newmat detects an error it will throw an exception. It is important that -you catch this exception and print the error message. Otherwise you will get an -unhelpful message like abnormal termination. I suggest you set up your -main program like 

-
#define WANT_STREAM             // or #include <iostream>
-#include "include.h"            // or #include "newmat.h"
-#include "myexcept.h"
-
-main()
-{
-   try
-   {
-      ... your program here
-   }
-   // catch exceptions thrown by my programs
-   catch(Exception) { cout << Exception::what() << endl; }
-   // catch exceptions thrown by other people's programs
-   catch(...) { cout << "exception caught in main program" << endl; }
-   return 0;
-}
-

If you are using a GUI version rather a console version of the program you -will need to replace the cout statements by windows pop-up messages.

-

If you are using my simulated exceptions or have set the disable exceptions -option in include.h then uncaught exceptions automatically print the -error message generated by the exception so you can ignore this section. -Alternatively use Try, Catch and CatchAll in place of try, catch -and catch(...) in the preceding code. It is probably a good idea to do -this if you are using a GUI version of the program as opposed to a console -version as the cout statement used in newmat's Terminate function -may be ignored in a GUI version.

-

See the section on exceptions for more information on -the exception structure.

-

2.7 Example

-

next - skip - -up - start

-

An example is given in example.cpp. This gives a simple linear -regression example using five different algorithms. The correct output is given -in example.txt. The program carries out a rough check that no memory -is left allocated on the heap when it terminates. See the section on -testing for a comment on the reliability of this check -(generally it doesn't work with the newer compilers) and the use of the -DO_FREE_CHECK option.

-

I include a variety of make files. To compile the example use a command like -

-
   gmake -f nm_gnu.mak example              (Gnu G++)
-   gmake -f nm_cc.mak example               (AT&T, HPUX, Sun)
-   make -f nm_b55.mak example.exe           (Borland C++ 5.5)
-

You can generate make make files for a number of other compilers with my -genmake utility.

- -

To compile all the example and test files use a command like

-
   gmake -f nm_gnu.mak                      (Gnu G++)
-
- -

The example uses io manipulators. It will not work with a -compiler that does not support the standard io manipulators.

-

Other example files are nl_ex.cpp and garch.cpp for -demonstrating the non-linear fitting routines, sl_ex for demonstrating -the solve function and test_exc for demonstrating the exceptions.

-

2.8 Testing

-

next - skip - -up - start

-

The library package contains a comprehensive test program in the form of a -series of files with names of the form tmt?.cxx. The files consist of a large -number of matrix formulae all of which evaluate to zero (except the first one -which is used to check that we are detecting non-zero matrices). The printout -should state that it has found just one non-zero matrix.

-

The test program should be run with Real typedefed to double -rather than float in include.h.

-

Make sure the C subscripts are enabled if you want -to test these.

-

If you are carrying out some form of bounds checking, for example, with -Borland's CodeGuard, then disable the testing of the Numerical Recipes in C interface. Activate the statement -#define DONT_DO_NRIC in tmt.h.

-

Various versions of the make file (extension .mak) are included with the -package. See the section on make files.

-

The program also allocates and deletes a large block and small block of -memory before it starts the main testing and then at the end of the test. It -then checks that the blocks of memory were allocated in the same place. If not, -then one suspects that there has been a memory leak. i.e. a piece of memory has -been allocated and not deleted.

-

This is not completely foolproof. Programs may allocate extra print buffers -while the program is running. I have tried to overcome this by doing a print -before I allocate the first memory block. Programs may allocate memory for -different sized items in different places, or might not allocate items -consecutively. Or they might mix the items with memory blocks from other -programs. Nevertheless, I seem to get consistent answers from some of the -compilers I work with, so I think this is a worthwhile test. The compilers that -the test seems to work for include the Borland compilers, Microsoft VC++ 6 , -Watcom 10a, and Gnu 2.96 for Linux.

-

If the DO_FREE_CHECK option in include.h is activated, -the program checks that each new is balanced with exactly one -delete. This provides a more definitive test of no memory leaks. There -are additional statements in myexcept.cpp which can be activated to print out -details of the memory being allocated and released.

-

I have included a facility for checking that each piece of code in the -library is really exercised by the test routines. Each block of code in the -main part of the library contains a word REPORT. newmat.h has -a line defining REPORT that can be activated (deactivate the dummy -version). This gives a printout of the number of times each of the -REPORT statements in the .cpp files is accessed. Use a grep -with line numbers to locate the lines on which REPORT occurs and -compare these with the lines that the printout shows were actually accessed. -One can then see which lines of code were not accessed.

-

2.9 Bugs

-

next - skip - -up - start

-
    -
  • Small memory leaks may occur when an exception is thrown and caught.
  • -
  • My exception scheme may not be not properly linked in with the standard -library exceptions. In particular, my scheme may fail to catch out-of-memory -exceptions.
  • -
-

2.10 List of files

-

next - skip - -up - start

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Documentationreadmereadme file
 nm10.htmdocumentation file
 add_time.pgnimage used by nm10.htm - move to subdirectory "images"
 rbd.cssstyle sheet for nm10.htm
Definition filesboolean.hboolean class definition
 controlw.hcontrol word definition file
 include.hdetails of include files and options
 myexcept.hgeneral exception handler definitions
 newmat.hmain matrix class definition file
 newmatap.happlications definition file
 newmatio.hinput/output definition file
 newmatnl.hnon-linear optimisation definition file
 newmatrc.hrow/column functions definition files
 newmatrm.hrectangular matrix access definition files
 precisio.hnumerical precision constants
 solution.hone dimensional solve definition file
Program filesbandmat.cppband matrix routines
 cholesky.cppCholesky decomposition
 evalue.cppeigenvalues and eigenvector calculation
 fft.cppfast Fourier, trig. transforms
 hholder.cppQR routines
 jacobi.cppeigenvalues by the Jacobi method
 myexcept.cppgeneral error and exception handler
 newfft.cppnew fast Fourier transform
 newmat1.cpptype manipulation routines
 newmat2.cpprow and column manipulation functions
 newmat3.cpprow and column access functions
 newmat4.cppconstructors, resize, utilities
 newmat5.cpptranspose, evaluate, matrix functions
 newmat6.cppoperators, element access
 newmat7.cppinvert, solve, binary operations
 newmat8.cppLU decomposition, scalar functions
 newmat9.cppoutput routines
 newmatex.cppmatrix exception handler
 newmatnl.cppnon-linear optimisation
 newmatrm.cpprectangular matrix access functions
 sort.cppsorting functions
 solution.cppone dimensional solve
 submat.cppsubmatrix functions
 svd.cppsingular value decomposition
Example filesexample.cppexample of use of package
 example.txtoutput from example
 sl_ex.cppexample of OneDimSolve routine
 sl_ex.txtoutput from example
 nl_ex.cppexample of non-linear least squares
 nl_ex.txtoutput from example
 garch.cppexample of maximum-likelihood fit
 garch.datdata file for garch.cpp
 garch.txtoutput from example
 test_exc.cppdemonstration exceptions
 test_exc.txtoutput from test_exc.cpp
Test filestmt.hheader file for test files
 tmt*.cpptest files (see the section on testing)
 tmt.txtoutput from test files
Make filesnm_gnu.makmake file for Gnu G++
 nm_cc.makmake file for AT&T, Sun and HPUX
 nm_b55.makmake file for Borland C++ 5.5
 newmat.lfllibrary file list for use with genmake
 nm_targ.txttarget file list for use with genmake
-

2.11 Problem report form -

-

next - skip - -up - start

-

Copy and paste this to your editor; fill it out and email to -robert (at) statsresearch.co.nz

-

But first look in my web page http://www.robertnz.net/bugs.htm to see if the bug has -already been reported.

-
 Version: ............... newmat10A (8 October 2002)
- Your email address: ....
- Today's date: ..........
- Your machine: ..........
- Operating system: ......
- Compiler & version: ....
- Compiler options
-   (eg GUI or console)...
- Describe the problem - attach examples if possible:
-
-
-
-
-
------------------------------------------------------------
-
- -

3. Reference manual

-

next - skip - -up - start

- - - - - -
3.1 -Constructors
-3.2 Accessing elements
-3.3 Assignment and copying
-3.4 Entering values
-3.5 Unary operations
-3.6 Binary operations
-3.7 Matrix and scalar ops
-3.8 Scalar functions - size & shape
-3.9 Scalar functions - maximum & minimum
-3.10 Scalar functions - numerical
-3.11 Submatrices
-3.12 Change dimension
-3.13 Change type
-3.14 Multiple matrix solve
-3.15 Memory management
-3.16 Efficiency
3.17 Output
-3.18 Accessing unspecified type
-3.19 Cholesky decomposition
-3.20 QR decomposition
-3.21 Singular value decomposition
-3.22 Eigenvalue decomposition
-3.23 Sorting
-3.24 Fast Fourier transform
-3.25 Fast trigonometric transforms
-3.26 Numerical recipes in C
-3.27 Exceptions
-3.28 Cleanup following exception
-3.29 Non-linear applications
-3.30 Standard template library
-3.31 Namespace
-

3.1 Constructors

-

next - skip - -up - start

-

To construct an m x n matrix, A, (m and -n are integers) use

-
    Matrix A(m,n);
-
- -

The UpperTriangularMatrix, LowerTriangularMatrix, SymmetricMatrix and -DiagonalMatrix types are square. To construct an n x n matrix -use, for example

-
    UpperTriangularMatrix UT(n);
-    LowerTriangularMatrix LT(n);
-    SymmetricMatrix S(n);
-    DiagonalMatrix D(n);
-
- -

Band matrices need to include bandwidth information in their constructors. -

-
    BandMatrix BM(n, lower, upper);
-    UpperBandMatrix UB(n, upper);
-    LowerBandMatrix LB(n, lower);
-    SymmetricBandMatrix SB(n, lower);
-
- -

The integers upper and lower are the number of non-zero -diagonals above and below the diagonal (excluding the diagonal) -respectively.

-

The RowVector and ColumnVector types take just one argument in their -constructors:

-
    RowVector RV(n);
-    ColumnVector CV(n);
-
- -

These constructors do not initialise the elements of the matrices. - -To set all the elements to zero use, for example,

-
    Matrix A(m, n); A = 0.0;
-
- -

The IdentityMatrix takes one argument in its constructor specifying its -dimension.

-
    IdentityMatrix I(n);
-

The value of the diagonal elements is set to 1 by default, but you can -change this value as with other matrix types.

- -

You can also construct vectors and matrices without specifying the -dimension. For example

-
    Matrix A;
-
- -

In this case the dimension must be set by an assignment -statement or a re-size statement.

-

You can also use a constructor to set a matrix equal to another matrix or -matrix expression.

-
    Matrix A = UT;
-    Matrix A = UT * LT;
-
- -

Only conversions that don't lose information are supported - eg you cannot -convert an upper triangular matrix into a diagonal matrix using =.

-

3.2 Accessing elements -

-

next - skip - -up - start

-

Elements are accessed by expressions of the form A(i,j) where -i and j run from 1 to the appropriate dimension. Access elements -of vectors with just one argument. Diagonal matrices can accept one or two -subscripts.

-

This is different from the earliest version of the package in which the -subscripts ran from 0 to one less than the appropriate dimension. Use -A.element(i,j) if you want this earlier convention.

-

A(i,j) and A.element(i,j) can appear on either side of an -= sign.

-

If you activate the #define SETUP_C_SUBSCRIPTS in -include.h you can also access elements using the traditional C style -notation. That is A[i][j] for matrices (except diagonal) and -V[i] for vectors and diagonal matrices. The subscripts start at zero -(i.e. like element) and there is no range checking. Because of the -possibility of confusing V(i) and V[i], I suggest you do -not activate this option unless you really want to use it.

-

Symmetric matrices are stored as lower triangular matrices. It is important -to remember this if you are using the A[i][j] method of accessing -elements. Make sure the first subscript is greater than or equal to the second -subscript. However, if you are using the A(i,j) method the program -will swap i and j if necessary; so it doesn't matter if you -think of the storage as being in the upper triangle (but it does matter -in some other situations such as when entering data).

-

The IdentityMatrix type does not support element access. -

-

3.3 Assignment and copying

-

next - skip - -up - start

-

The operator = is used for copying matrices, converting matrices, -or evaluating expressions. For example

-
    A = B;  A = L;  A = L * U;
-
- -

Only conversions that don't lose information are supported. The dimensions -of the matrix on the left hand side are adjusted to those of the matrix or -expression on the right hand side. Elements on the right hand side which are -not present on the left hand side are set to zero.

-

The operator << can be used in place of = where it -is permissible for information to be lost.

-

For example

-
    SymmetricMatrix S; Matrix A;
-    ......
-    S << A.t() * A;
-
- -

is acceptable whereas

-
    S = A.t() * A;                            // error
-
- -

will cause a runtime error since the package does not (yet?) recognise -A.t()*A as symmetric.

-

Note that you can not use << with constructors. For -example

-
    SymmetricMatrix S << A.t() * A;           // error
-
- -

does not work.

-

Also note that << cannot be used to load values from a full -matrix into a band matrix, since it will be unable to determine the bandwidth -of the band matrix.

-

A third copy routine is used in a similar role to =. Use

-
    A.Inject(D);
-
- -

to copy the elements of D to the corresponding elements of -A but leave the elements of A unchanged if there is no -corresponding element of D (the = operator would set them to -0). This is useful, for example, for setting the diagonal elements of a matrix -without disturbing the rest of the matrix. Unlike = and -<<, Inject does not reset the dimensions of A, which -must match those of D. Inject does not test for no loss of -information.

-

You cannot replace D by a matrix expression. The effect of -Inject(D) depends on the type of D. If D is an -expression it might not be obvious to the user what type it would have. So I -thought it best to disallow expressions.

-

Inject can be used for loading values from a regular matrix into a band -matrix. (Don't forget to zero any elements of the left hand side that will not -be set by the loading operation).

-

Both << and Inject can be used with submatrix expressions on -the left hand side. See the section on submatrices.

-

To set the elements of a matrix to a scalar use operator =

-
    Real r; int m,n;
-    ......
-    Matrix A(m,n); A = r;
- -

Notes:

- -
    -
  • When you do a matrix assignment to another matrix or matrix expression with -either = or << the original data array associated with the matrix - being assigned to is destroyed -even if there is no change in length. See the section on storage. -This means, in particular, that pointers to matrix elements - e.g. -Real* a; a = &(A(1,1)); become invalid. If you want avoid this you - can use -Inject rather than =. But remember that you may need to zero - the matrix first.
    -
  • -
- -

3.4 Entering values

-

next - skip - -up - start

-

You can load the elements of a matrix from an array:

-
    Matrix A(3,2);
-    Real a[] = { 11,12,21,22,31,33 };
-    A << a;
-
- -

This construction does not check that the numbers of elements match -correctly. This version of << can be used with submatrices on -the left hand side. It is not defined for band matrices.

-

Alternatively you can enter short lists using a sequence of numbers -separated by << .

-
    Matrix A(3,2);
-    A << 11 << 12
-      << 21 << 22
-      << 31 << 32;
-
- -

This does check for the correct total number of entries, although the -message for there being insufficient numbers in the list may be delayed until -the end of the block or the next use of this construction. This does not -work for band matrices or for long lists. It does work for submatrices if the -submatrix is a single complete row. For example

-
    Matrix A(3,2);
-    A.Row(1) << 11 << 12;
-    A.Row(2) << 21 << 22;
-    A.Row(3) << 31 << 32;
-
- -

Load only values that are actually stored in the matrix. For example

-
    SymmetricMatrix S(2);
-    S.Row(1) << 11;
-    S.Row(2) << 21 << 22;
-
- -

Try to restrict this way of loading data to numbers. You can include -expressions, but these must not call a function which includes the same -construction.

- -

Remember that matrices are stored by rows and that symmetric matrices are -stored as lower triangular matrices when using these methods to enter -data.

-

3.5 Unary operators

-

next - skip - -up - start

-

The package supports unary operations

-
    X = -A;           // change sign of elements
-    X = A.t();        // transpose
-    X = A.i();        // inverse (of square matrix A)
-    X = A.Reverse();  // reverse order of elements of vector
-                      // or matrix (not band matrix)
-
- -

3.6 Binary operators

-

next - skip - -up - start

-

The package supports binary operations

-
    X = A + B;       // matrix addition
-    X = A - B;       // matrix subtraction
-    X = A * B;       // matrix multiplication
-    X = A.i() * B;   // equation solve (square matrix A)
-    X = A | B;       // concatenate horizontally (concatenate the rows)
-    X = A & B;       // concatenate vertically (concatenate the columns)
-    X = SP(A, B);    // elementwise product of A and B (Schur product)
-    X = KP(A, B);    // Kronecker product of A and B
-    bool b = A == B; // test whether A and B are equal
-    bool b = A != B; // ! (A == B)
-    A += B;          // A = A + B;
-    A -= B;          // A = A - B;
-    A *= B;          // A = A * B;
-    A |= B;          // A = A | B;
-    A &= B;          // A = A & B;
-    <, >, <=, >=     // included for compatibility with STL - see notes
-
- -

Notes:

-
    -
  • If you are doing repeated multiplication. For example A*B*C, use -brackets to force the order of evaluation to minimise the number of operations. -If C is a column vector and A is not a vector, then it will -usually reduce the number of operations to use A*(B*C).
  • -
  • In the equation solve example case the inverse is not explicitly -calculated. An LU decomposition of A is performed and this is applied -to B. This is more efficient than calculating the inverse and then -multiplying. See also multiple matrix solving.
  • -
  • The package does not (yet?) recognise B*A.i() as an equation solve -and the inverse of A would be calculated. It is probably better to use -(A.t().i()*B.t()).t().
  • -
  • Horizontal or vertical concatenation returns a result of type Matrix, -RowVector or ColumnVector.
  • -
  • If A is m x p, B is m x q, -then A | B is m x (p+q) with the k-th row -being the elements of the k-th row of A followed by the -elements of the k-th row of B.
  • -
  • If A is p x n, B is q x n, -then A & B is (p+q) x n with the k-th -column being the elements of the k-th column of A followed by -the elements of the k-th column of B.
  • -
  • For complicated concatenations of matrices, consider instead using -submatrices.
  • -
  • See the section on submatrices on using a submatrix -on the RHS of an expression.
  • -
  • Two matrices are equal if their difference is zero. They may be of -different types. For the CroutMatrix or BandLUMatrix they must be of the same -type and have all their elements equal. This is not a very useful operator and -is included for compatibility with some container templates.
  • -
  • The inequality operators are included for compatibility with the -standard template library. If actually called, they will -throw an exception. So don't try to sort a list of matrices.
  • -
  • A row vector multiplied by a column vector yields a 1x1 matrix, not -a Real. To get a Real result use either AsScalar or -DotProduct.
  • -
  • The result from Kronecker product, KP(A, B), possesses an attribute such as -upper triangular, lower triangular, band, symmetric, diagonal if both of the -matrices A and B have the attribute. (This differs slightly from the way the -January 2002 version of newmat10 worked).
  • -
-

Remember that the product of symmetric matrices is not -necessarily symmetric so the following code will not run:

-
   SymmetricMatrix A, B;
-   .... put values in A, B ....
-   SymmetricMatrix C = A * B;   // run time error
- -

Use instead

-
   Matrix C = A * B;
- -

or, if you know the product will be symmetric, -use

-
   SymmetricMatrix C; C << A * B;
-
- -

3.7 Matrix and scalar

-

next - skip - -up - start

-

The following expressions multiply the elements of a matrix A by a -scalar f: A * f or f * A . Likewise one can divide -the elements of a matrix A by a scalar f: A / f . -

-

The expressions A + f and A - f add or subtract a -rectangular matrix of the same dimension as A with elements equal to -f to or from the matrix A .

-

The expression f + A is an alternative to A + f. The -expression f - A subtracts matrix A from a rectangular matrix -of the same dimension as A and with elements equal to f . -

-

The expression A += f replaces A by A + f. -Operators -=, *=, /= are similarly defined.

-

3.8 Scalar functions of a -matrix - size & shape

-

next - skip - -up - start

-

This page describes functions returning the values associated with the size -and shape of matrices. The following pages describe other scalar matrix -functions.

-
    int m = A.Nrows();                     // number of rows
-    int n = A.Ncols();                     // number of columns
-    MatrixType mt = A.Type();              // type of matrix
-    Real* s = A.Store();                   // pointer to array of elements
-    int l = A.Storage();                   // length of array of elements
-    MatrixBandWidth mbw = A.BandWidth();   // upper and lower bandwidths
-
- -

MatrixType mt = A.Type() returns the type of a matrix. Use -(char*)mt to get a string (UT, LT, Rect, Sym, Diag, Band, UB, LB, -Crout, BndLU) showing the type (Vector types are returned as Rect).

-

MatrixBandWidth has member functions Upper() and -Lower() for finding the upper and lower bandwidths (number of -diagonals above and below the diagonal, both zero for a diagonal matrix). For -non-band matrices -1 is returned for both these values.

-

3.9 Scalar functions of a -matrix - maximum & minimum

-

next - skip - -up - start

-

This page describes functions for finding the maximum and minimum elements -of a matrix.

-
    int i, j;
-    Real mv = A.MaximumAbsoluteValue();    // maximum of absolute values
-    Real mv = A.MinimumAbsoluteValue();    // minimum of absolute values
-    Real mv = A.Maximum();                 // maximum value
-    Real mv = A.Minimum();                 // minimum value
-    Real mv = A.MaximumAbsoluteValue1(i);  // maximum of absolute values
-    Real mv = A.MinimumAbsoluteValue1(i);  // minimum of absolute values
-    Real mv = A.Maximum1(i);               // maximum value
-    Real mv = A.Minimum1(i);               // minimum value
-    Real mv = A.MaximumAbsoluteValue2(i,j);// maximum of absolute values
-    Real mv = A.MinimumAbsoluteValue2(i,j);// minimum of absolute values
-    Real mv = A.Maximum2(i,j);             // maximum value
-    Real mv = A.Minimum2(i,j);             // minimum value
-
- -

All these functions throw an exception if A has no rows or no -columns.

-

The versions A.MaximumAbsoluteValue1(i), etc return the location of -the extreme element in a RowVector, ColumnVector or DiagonalMatrix. The -versions A.MaximumAbsoluteValue2(i,j), etc return the row and column -numbers of the extreme element. If the extreme value occurs more than once the -location of the last one is given.

-

The versions MaximumAbsoluteValue(A), MinimumAbsoluteValue(A), Maximum(A), -Minimum(A) can be used in place of A.MaximumAbsoluteValue(), -A.MinimumAbsoluteValue(), A.Maximum(), A.Minimum().

-

3.10 Scalar functions of a -matrix - numerical

-

next - skip - -up - start

-
    Real r = A.AsScalar();                 // value of 1x1 matrix
-    Real ssq = A.SumSquare();              // sum of squares of elements
-    Real sav = A.SumAbsoluteValue();       // sum of absolute values
-    Real s = A.Sum();                      // sum of values
-    Real norm = A.Norm1();                 // maximum of sum of absolute
-                                              values of elements of a column
-    Real norm = A.NormInfinity();          // maximum of sum of absolute
-                                              values of elements of a row
-    Real norm = A.NormFrobenius();         // square root of sum of squares
-                                           // of the elements
-    Real t = A.Trace();                    // trace
-    Real d = A.Determinant();              // determinant
-    LogAndSign ld = A.LogDeterminant();    // log of determinant
-    bool z = A.IsZero();                   // test all elements zero
-    bool s = A.IsSingular();               // A is a CroutMatrix or
-                                              BandLUMatrix
-    Real s = DotProduct(A, B);             // dot product of A and B
-                                           // interpreted as vectors
-
- -

A.LogDeterminant() returns a value of type LogAndSign. If ld is of -type LogAndSign use

-
    ld.Value()    to get the value of the determinant
-    ld.Sign()     to get the sign of the determinant (values 1, 0, -1)
-    ld.LogValue() to get the log of the absolute value.
-
- -

Note that the direct use of the function Determinant() will often -cause a floating point overflow exception.

-

A.IsZero() returns Boolean value true if the matrix -A has all elements equal to 0.0.

-

IsSingular is defined only for CroutMatrix and BandLUMatrix. It -returns true if one of the diagonal elements of the LU decomposition -is exactly zero.

-

DotProduct(const Matrix& A,const Matrix& B) converts both -of the arguments to rectangular matrices, checks that they have the same number -of elements and then calculates the first element of A * first element -of B + second element of A * second element of B + -... ignoring the row/column structure of A and B. It is -primarily intended for the situation where A and B are row or -column vectors.

-

The versions Sum(A), SumSquare(A), SumAbsoluteValue(A), Trace(A), -LogDeterminant(A), Determinant(A), Norm1(A), NormInfinity(A), NormFrobenius(A) -can be used in place of A.Sum(), A.SumSquare(), A.SumAbsoluteValue(), -A.Trace(), A.LogDeterminant(), A.Norm1(), A.NormInfinity(), A.NormFrobenius(). -

-

3.11 Submatrices

-

next - skip - -up - start

-
    A.SubMatrix(fr,lr,fc,lc)
-
- -

This selects a submatrix from A. The arguments -fr,lr,fc,lc are the first row, last row, -first column, last column of the submatrix with the numbering beginning at 1. -

-

I allow lr = fr-1 or lc = fc-1 or to indicate that a -matrix of zero rows or columns is to be returned.

-

A submatrix command may be used in any matrix expression or on the left hand -side of =, << or Inject. Inject does not check -no information loss. You can also use the construction

-
    Real c; .... A.SubMatrix(fr,lr,fc,lc) = c;
-
- -

to set a submatrix equal to a constant.

-

The following are variants of SubMatrix:

-
    A.SymSubMatrix(f,l)             //   This assumes fr=fc and lr=lc.
-    A.Rows(f,l)                     //   select rows
-    A.Row(f)                        //   select single row
-    A.Columns(f,l)                  //   select columns
-    A.Column(f)                     //   select single column
-
- -

In each case f and l mean the first and last row or column -to be selected (starting at 1).

-

I allow l = f-1 to indicate that a matrix of zero rows or columns -is to be returned.

-

If SubMatrix or its variant occurs on the right hand side of an = -or << or within an expression think of its type as follows

-
    A.SubMatrix(fr,lr,fc,lc)           If A is RowVector or
-                                       ColumnVector then same type
-                                       otherwise type Matrix
-    A.SymSubMatrix(f,l)                Same type as A
-    A.Rows(f,l)                        Type Matrix
-    A.Row(f)                           Type RowVector
-    A.Columns(f,l)                     Type Matrix
-    A.Column(f)                        Type ColumnVector
-
- -

If SubMatrix or its variant appears on the left hand side of = or -<< , think of its type being Matrix. Thus L.Row(1) -where L is LowerTriangularMatrix expects L.Ncols() elements -even though it will use only one of them. If you are using = the -program will check for no loss of data.

- -

A SubMatrix can appear on the left-hand side of += or -= -with a matrix expression on the right-hand side. It can also appear on the -left-hand side of +=, -=, *= or /= with a -Real on the right-hand side. In each case there must be no loss of information. -

-

The Row version can appear on the left hand side of -<< for loading literal data into a row. -Load only the number of elements that are actually going to be stored in -memory.

-

Do not use the += and -= operations with a submatrix of a -SymmetricMatrix or BandSymmetricMatrix on the LHS and a Real on the RHS.

-

You can't pass a submatrix (or any of its variants) as a reference -non-constant matrix in a function argument. For example, the following will not -work:

-
   void YourFunction(Matrix& A);
-   ...
-   Matrix B(10,10);
-   YourFunction(B.SubMatrix(1,5,1,5))    // won't compile
-

If you are are using the submatrix facility to build a matrix from a small -number of components, consider instead using the concatenation operators.

-

3.12 Change dimensions

-

next - skip - -up - start

-

The following operations change the dimensions of a matrix. The values of -the elements are lost.

-
    A.ReSize(nrows,ncols);        // for type Matrix or nricMatrix
-    A.ReSize(n);                  // for all other types, except Band
-    A.ReSize(n,lower,upper);      // for BandMatrix
-    A.ReSize(n,lower);            // for LowerBandMatrix
-    A.ReSize(n,upper);            // for UpperBandMatrix
-    A.ReSize(n,lower);            // for SymmetricBandMatrix
-    A.ReSize(B);                  // set dims to those of B 
-
- -

Use A.CleanUp() to set the dimensions of A to zero and -release all the heap memory.

-

A.ReSize(B) sets the dimensions of A to those of a matrix -B. This includes the band-width in the case of a band matrix. It is an -error for A to be a band matrix and B not a band matrix (or -diagonal matrix).

-

Remember that ReSize destroys values. If you want to -ReSize, but keep the values in the bit that is left use something like -

-
   ColumnVector V(100);
-   ...                            // load values
-   V = V.Rows(1,50);              // to get first 50 values.
-
- -

If you want to extend a matrix or vector use something like

-
   ColumnVector V(50);
-   ...                            // load values
-   { V.Release(); ColumnVector X=V; V.ReSize(100); V.Rows(1,50)=X; }
-                                  // V now length 100
-
- -

3.13 Change type

-

next - skip - -up - start

-

The following functions interpret the elements of a matrix (stored row by -row) to be a vector or matrix of a different type. Actual copying is usually -avoided where these occur as part of a more complicated expression.

-
    A.AsRow()
-    A.AsColumn()
-    A.AsDiagonal()
-    A.AsMatrix(nrows,ncols)
-    A.AsScalar()
-
- -

The expression A.AsScalar() is used to convert a 1 x 1 matrix to a -scalar.

-

3.14 Multiple matrix solve

-

next - skip - -up - start

-

To solve the matrix equation Ay = b where A is a square -matrix of equation coefficients, y is a column vector of values to be -solved for, and b is a column vector, use the code

-
    int n = something
-    Matrix A(n,n); ColumnVector b(n);
-    ... put values in A and b
-    ColumnVector y = A.i() * b;       // solves matrix equation
-
- -

The following notes are for the case where you want to solve more than one -matrix equation with different values of b but the same A. Or -where you want to solve a matrix equation and also find the determinant of -A. In these cases you probably want to avoid repeating the LU -decomposition of A for each solve or determinant calculation.

-

If A is a square or symmetric matrix use

-
    CroutMatrix X = A;                // carries out LU decomposition
-    Matrix AP = X.i()*P; Matrix AQ = X.i()*Q;
-    LogAndSign ld = X.LogDeterminant();
-
- -

rather than

-
    Matrix AP = A.i()*P; Matrix AQ = A.i()*Q;
-    LogAndSign ld = A.LogDeterminant();
-
- -

since each operation will repeat the LU decomposition.

-

If A is a BandMatrix or a SymmetricBandMatrix begin with

-
    BandLUMatrix X = A;               // carries out LU decomposition
-
- -

A CroutMatrix or a BandLUMatrix can't be manipulated or copied. Use -references as an alternative to copying.

-

Alternatively use

-
    LinearEquationSolver X = A;
-
- -

This will choose the most appropriate decomposition of A. That is, -the band form if A is banded; the Crout decomposition if A is -square or symmetric and no decomposition if A is triangular or -diagonal.

-

3.15 Memory management

-

next - skip - -up - start

-

The package does not support delayed copy. Several strategies are required -to prevent unnecessary matrix copies.

-

Where a matrix is called as a function argument use a constant reference. -For example

-
    YourFunction(const Matrix& A)
-
- -

rather than

-
    YourFunction(Matrix A)
-
- -

Skip the rest of this section on your first reading.

-

Gnu g++ (< 2.6) users please read on: if you are returning -matrix values from a function, then you must use the ReturnMatrix -construct.

-

A second place where it is desirable to avoid unnecessary copies is when a -function is returning a matrix. Matrices can be returned from a function with -the return command as you would expect. However these may incur one and -possibly two copyings of the matrix. To avoid this use the following -instructions.

-

Make your function of type ReturnMatrix . Then precede the return statement -with a Release statement (or a ReleaseAndDelete statement if the matrix was -created with new). For example

-
    ReturnMatrix MakeAMatrix()
-    {
-       Matrix A;                // or any other matrix type
-       ......
-       A.Release(); return A;
-    }
-
- -

or

-
    ReturnMatrix MakeAMatrix()
-    {
-       Matrix* m = new Matrix;
-       ......
-       m->ReleaseAndDelete(); return *m;
-    }
-
- -

If your compiler objects to this code, replace the return statements with -

-
    return A.ForReturn();
-
- -

or

-
    return m->ForReturn();
-
- -

If you are using AT&T C++ you may wish to replace return A; by -return (ReturnMatrix)A; to avoid a warning message; but this will give -a runtime error with Gnu. (You can't please everyone.)

-
-

Do not forget to make the function of type ReturnMatrix; otherwise you -may get incomprehensible run-time errors.

-
-

You can also use .Release() or ->ReleaseAndDelete() to -allow a matrix expression to recycle space. Suppose you call

-
    A.Release();
-
- -

just before A is used just once in an expression. Then the memory -used by A is either returned to the system or reused in the -expression. In either case, A's memory is destroyed. This procedure -can be used to improve efficiency and reduce the use of memory.

-

Use ->ReleaseAndDelete for matrices created by new if you want -to completely delete the matrix after it is accessed.

-

3.16 Efficiency

-

next - skip - -up - start

-

The package tends to be not very efficient for dealing with matrices with -short rows. This is because some administration is required for accessing rows -for a variety of types of matrices. To reduce the administration a special -multiply routine is used for rectangular matrices in place of the generic one. -Where operations can be done without reference to the individual rows (such as -adding matrices of the same type) appropriate routines are used.

-

When you are using small matrices (say smaller than 10 x 10) you may find it -faster to use rectangular matrices rather than the triangular or symmetric -ones.

-

3.17 Output

-

next - skip - -up - start

-

To print a matrix use an expression like

-
   Matrix A;
-   ......
-   cout << setw(10) << setprecision(5) << A;
-
- -

This will work only with systems that support the standard input/output -routines including manipulators. You need to #include the files iostream.h, -iomanip.h, newmatio.h in your C++ source files that use this facility. The -files iostream.h, iomanip.h will be included automatically if you include the -statement #define WANT_STREAM at the beginning of your source file. So -you can begin your file with either

-
   #define WANT_STREAM
-   #include "newmatio.h"
-
- -

or

-
   #include <iostream.h>
-   #include <iomanip.h>
-   #include "newmatio.h"
-
- -

The present version of this routine is useful only for matrices small enough -to fit within a page or screen width.

-

To print several vectors or matrices in columns use a concatenation operator:

-
   ColumnVector A, B;
-   .....
-   cout << setw(10) << setprecision(5) << (A | B);
-
- -

3.18 Unspecified type

-

next - skip - -up - start

-

Skip this section on your first reading.

-

If you want to work with a matrix of unknown type, say in a function. You -can construct a matrix of type GenericMatrix. Eg

-
   Matrix A;
-   .....                                  // put some values in A
-   GenericMatrix GM = A;
-
- -

A GenericMatrix matrix can be used anywhere where a matrix expression can be -used and also on the left hand side of an =. You can pass any type of -matrix (excluding the Crout and BandLUMatrix types) to a const -GenericMatrix& argument in a function. However most scalar functions -including Nrows(), Ncols(), Type() and element access do not work with it. Nor -does the ReturnMatrix construct. See also the paragraph on LinearEquationSolver.

-

An alternative and less flexible approach is to use BaseMatrix or -GeneralMatrix.

-

Suppose you wish to write a function which accesses a matrix of unknown type -including expressions (eg A*B). Then use a layout similar to the -following:

-
   void YourFunction(BaseMatrix& X)
-   {
-      GeneralMatrix* gm = X.Evaluate();   // evaluate an expression
-                                          // if necessary
-      ........                            // operations on *gm
-      gm->tDelete();                      // delete *gm if a temporary
-   }
-
- -

See, as an example, the definitions of operator<< in -newmat9.cpp.

-

Under certain circumstances; particularly where X is to be used -just once in an expression you can leave out the Evaluate() statement -and the corresponding tDelete(). Just use X in the -expression.

-

If you know YourFunction will never have to handle a formula as its argument -you could also use

-
   void YourFunction(const GeneralMatrix& X)
-   {
-      ........                            // operations on X
-   }
-
- -

Do not try to construct a GeneralMatrix or BaseMatrix.

-

3.19 Cholesky -decomposition

-

next - skip - -up - start

-

Suppose S is symmetric and positive definite. Then there exists a -unique lower triangular matrix L such that L * L.t() = S. To -calculate this use

-
    SymmetricMatrix S;
-    ......
-    LowerTriangularMatrix L = Cholesky(S);
-
- -

If S is a symmetric band matrix then L is a band matrix -and an alternative procedure is provided for carrying out the decomposition: -

-
    SymmetricBandMatrix S;
-    ......
-    LowerBandMatrix L = Cholesky(S);
-
- -

3.20 QR decomposition

-

next - skip - -up - start

-

This is a variant on the usual QR transformation.

-

Start with matrix (dimensions shown to left and below the matrix)

-
       / 0    0 \      s
-       \ X    Y /      n
-
-         s    t
-
- -

Our version of the QR decomposition multiplies this matrix by an orthogonal -matrix Q to get

-
       / U    M \      s
-       \ 0    Z /      n
-
-         s    t
-
- -

where U is upper triangular (the R of the QR transform). That is -

-
      Q  / 0   0 \  =  / U   M \
-         \ X   Y /     \ 0   Z / 
- -

This is good for solving least squares problems: choose b (matrix or column -vector) to minimise the sum of the squares of the elements of

-
         Y - X*b
-
- -

Then choose b = U.i()*M; The residuals Y - X*b are in -Z.

-

This is the usual QR transformation applied to the matrix X with -the square zero matrix concatenated on top of it. It gives the same triangular -matrix as the QR transform applied directly to X and generally seems -to work in the same way as the usual QR transform. However it fits into the -matrix package better and also gives us the residuals directly. It turns out to -be essentially a modified Gram-Schmidt decomposition.

-

Two routines are provided in newmat:

-
    QRZ(X, U);
-
- -

replaces X by orthogonal columns and forms U.

-
    QRZ(X, Y, M);
-
- -

uses X from the first routine, replaces Y by Z -and forms M.

-

The are also two routines QRZT(X, L) and QRZT(X, Y, M) -which do the same decomposition on the transposes of all these matrices. QRZT -replaces the routines HHDecompose in earlier versions of newmat. HHDecompose is -still defined but just calls QRZT.

-

For an example of the use of this decomposition see the file -example.cpp.

-

3.21 Singular value -decomposition

-

next - skip - -up - start

-

The singular value decomposition of an m x n Matrix -A (where m >= n) is a decomposition

-
    A  = U * D * V.t()
-
- -

where U is m x n with U.t() * U equalling -the identity, D is an n x n DiagonalMatrix and -V is an n x n orthogonal matrix (type Matrix in -Newmat).

-

Singular value decompositions are useful for understanding the structure of -ill-conditioned matrices, solving least squares problems, and for finding the -eigenvalues of A.t() * A.

-

To calculate the singular value decomposition of A (with m ->= n) use one of

-
    SVD(A, D, U, V);                  // U = A is OK
-    SVD(A, D);
-    SVD(A, D, U);                     // U = A is OK
-    SVD(A, D, U, false);              // U (can = A) for workspace only
-    SVD(A, D, U, V, false);           // U (can = A) for workspace only
-
- -

where A, U and V are of type Matrix and -D is a DiagonalMatrix. The values of A are not -changed unless A is also inserted as the third argument.

- -

The elements of D are sorted in descending order.

-

Remember that the SVD decomposition is not completely unique. The signs of the elements in a column of U may be reversed -if the signs in the corresponding column in V are reversed. If a -number of the singular values are identical one can apply an orthogonal -transformation to the corresponding columns of U and the corresponding -columns of V.

-

3.22 Eigenvalue -decomposition

-

next - skip - -up - start

-

An eigenvalue decomposition of a SymmetricMatrix A is a -decomposition

-
    A  = V * D * V.t()
-
- -

where V is an orthogonal matrix (type Matrix in -Newmat) and D is a DiagonalMatrix.

-

Eigenvalue analyses are used in a wide variety of engineering, statistical -and other mathematical analyses.

-

The package includes two algorithms: Jacobi and Householder. The first is -extremely reliable but much slower than the second.

-

The code is adapted from routines in Handbook for Automatic Computation, -Vol II, Linear Algebra by Wilkinson and Reinsch, published by Springer -Verlag.

-
    Jacobi(A,D,S,V);                  // A, S symmetric; S is workspace,
-                                      //    S = A is OK; V is a matrix
-    Jacobi(A,D);                      // A symmetric
-    Jacobi(A,D,S);                    // A, S symmetric; S is workspace,
-                                      //    S = A is OK
-    Jacobi(A,D,V);                    // A symmetric; V is a matrix
-
-    EigenValues(A,D);                 // A symmetric
-    EigenValues(A,D,S);               // A, S symmetric; S is for back
-                                      //    transforming, S = A is OK
-    EigenValues(A,D,V);               // A symmetric; V is a matrix
-
- -

where A, S are of type SymmetricMatrix, -D is of type DiagonalMatrix and V is of type -Matrix. The values of A are not changed unless A is -also inserted as the third argument. If you need eigenvectors use one of the -forms with matrix V. The eigenvectors are returned as the columns of -V.

- -

The elements of D are sorted in ascending order.

-

Remember that an eigenvalue decomposition is not completely -unique - see the comments about the SVD -decomposition.

-

3.23 Sorting

-

next - skip - -up - start

-

To sort the values in a matrix or vector, A, (in general this -operation makes sense only for vectors and diagonal matrices) use one of

-
    SortAscending(A);
-
-    SortDescending(A);
-
- -

I use the quicksort algorithm. The algorithm is similar to that in -Sedgewick's algorithms in C++. If the sort seems to be failing (as quicksort -can do) an exception is thrown.

-

You will get incorrect results if you try to sort a band matrix - but why -would you want to sort a band matrix?

-

3.24 Fast Fourier transform -

-

next - skip - -up - start

-
   FFT(X, Y, F, G);                         // F=X and G=Y are OK
-
- -

where X, Y, F, G are column vectors. -X and Y are the real and imaginary input vectors; F -and G are the real and imaginary output vectors. The lengths of -X and Y must be equal and should be the product of numbers -less than about 10 for fast execution.

-

The formula is

-
          n-1
-   h[k] = SUM  z[j] exp (-2 pi i jk/n)
-          j=0
-
- -

where z[j] is stored complex and stored in X(j+1) and -Y(j+1). Likewise h[k] is complex and stored in -F(k+1) and G(k+1). The fast Fourier algorithm takes order -n log(n) operations (for good values of n) rather than -n**2 that straight evaluation (see the file tmtf.cpp) takes. -

-

I use one of two methods:

-
    -
  • A program originally written by Sande and Gentleman. This requires that -n can be expressed as a product of small numbers.
  • -
  • A method of Carl de Boor (1980), Siam J Sci Stat Comput, pp 173-8. -The sines and cosines are calculated explicitly. This gives better accuracy, at -an expense of being a little slower than is otherwise possible. This is slower -than the Sande-Gentleman program but will work for all n --- although it -will be very slow for bad values of n.
  • -
-

Related functions

-
   FFTI(F, G, X, Y);                        // X=F and Y=G are OK
-   RealFFT(X, F, G);
-   RealFFTI(F, G, X);
-
- -

FFTI is the inverse transform for FFT. RealFFT is -for the case when the input vector is real, that is Y = 0. I assume -the length of X, denoted by n, is even. That is, -n must be divisible by 2. The program sets the lengths of F and -G to n/2 + 1. RealFFTI is the inverse of -RealFFT.

-

See also the section on fast trigonometric -transforms.

-

3.25 Fast trigonometric -transforms

-

next - skip - -up - start

-

These are the sin and cosine transforms as defined by Charles Van Loan -(1992) in Computational frameworks for the fast Fourier transform -published by SIAM. See page 229. Some other authors use slightly different -conventions. All the functions call the fast Fourier -transforms and require an even transform length, denoted by -m in these notes. That is, m must be divisible by 2. As with the -FFT m should be the product of numbers less than about 10 for fast -execution.

-

The functions I define are

-
   DCT(U,V);                // U, V are ColumnVectors, length m+1
-   DCT_inverse(V,U);        // inverse of DCT
-   DST(U,V);                // U, V are ColumnVectors, length m+1
-   DST_inverse(V,U);        // inverse of DST
-   DCT_II(U,V);             // U, V are ColumnVectors, length m
-   DCT_II_inverse(V,U);     // inverse of DCT_II
-   DST_II(U,V);             // U, V are ColumnVectors, length m
-   DST_II_inverse(V,U);     // inverse of DST_II
-
- -

where the first argument is the input and the second argument is the output. -V = U is OK. The length of the output ColumnVector is set by the -functions.

-

Here are the formulae:

-

DCT

-
                   m-1                             k
-   v[k] = u[0]/2 + SUM { u[j] cos (pi jk/m) } + (-) u[m]/2
-                   j=1
-
- -

for k = 0...m, where u[j] and v[k] are stored in -U(j+1) and V(k+1).

-

DST

-
          m-1
-   v[k] = SUM { u[j] sin (pi jk/m) }
-          j=1
-
- -

for k = 1...(m-1), where u[j] and v[k] are stored -in U(j+1) and V(k+1)and where u[0] and u[m] -are ignored and v[0] and v[m] are set to zero. For the -inverse function v[0] and v[m] are ignored and u[0] -and u[m] are set to zero.

-

DCT_II

-
          m-1
-   v[k] = SUM { u[j] cos (pi (j+1/2)k/m) }
-          j=0
-
- -

for k = 0...(m-1), where u[j] and v[k] are stored -in U(j+1) and V(k+1).

-

DST_II

-
           m
-   v[k] = SUM { u[j] sin (pi (j-1/2)k/m) }
-          j=1
-
- -

for k = 1...m, where u[j] and v[k] are stored in -U(j) and V(k).

-

Note that the relationship between the subscripts in the formulae and those -used in newmat is different for DST_II (and DST_II_inverse).

-

3.26 Interface to Numerical -Recipes in C

-

next - skip - -up - start

-

This package can be used with the vectors and matrices defined in -Numerical Recipes in C. You need to edit the routines in Numerical -Recipes so that the elements are of the same type as used in this package. Eg -replace float by double, vector by dvector and matrix by dmatrix, etc. You may -need to edit the function definitions to use the version acceptable to your -compiler (if you are using the first edition of NRIC). You may need to enclose -the code from Numerical Recipes in extern "C" { ... }. You -will also need to include the matrix and vector utility routines.

-

Then any vector in Numerical Recipes with subscripts starting from 1 in a -function call can be accessed by a RowVector, ColumnVector or DiagonalMatrix in -the present package. Similarly any matrix with subscripts starting from 1 can -be accessed by an nricMatrix in the present package. The class nricMatrix is -derived from Matrix and can be used in place of Matrix. In each case, if you -wish to refer to a RowVector, ColumnVector, DiagonalMatrix or nricMatrix -X in an function from Numerical Recipes, use X.nric() in the -function call.

-

Numerical Recipes cannot change the dimensions of a matrix or vector. So -matrices or vectors must be correctly dimensioned before a Numerical Recipes -routine is called.

-

For example

-
   SymmetricMatrix B(44);
-   .....                             // load values into B
-   nricMatrix BX = B;                // copy values to an nricMatrix
-   DiagonalMatrix D(44);             // Matrices for output
-   nricMatrix V(44,44);              //    correctly dimensioned
-   int nrot;
-   jacobi(BX.nric(),44,D.nric(),V.nric(),&nrot);
-                                     // jacobi from NRIC
-   cout << D;                        // print eigenvalues
-
- -

3.27 Exceptions

-

next - skip - -up - start

-

Here is the class structure for exceptions:

-
Exception
-  Logic_error
-    ProgramException                 miscellaneous matrix error
-    IndexException                   index out of bounds
-    VectorException                  unable to convert matrix to vector
-    NotSquareException               matrix is not square (invert, solve)
-    SubMatrixDimensionException      out of bounds index of submatrix
-    IncompatibleDimensionsException  (multiply, add etc)
-    NotDefinedException              operation not defined (eg <)
-    CannotBuildException             copying a matrix where copy is undefined
-    InternalException                probably an error in newmat
-  Runtime_error
-    NPDException                     matrix not positive definite (Cholesky)
-    ConvergenceException             no convergence (e-values, non-linear, sort)
-    SingularException                matrix is singular (invert, solve)
-    SolutionException                no convergence in solution routine
-    OverflowException                floating point overflow
-  Bad_alloc                          out of space (new fails)
-
- -

I have attempted to mimic the exception class structure in the C++ standard -library, by defining the Logic_error and Runtime_error classes.

-

Suppose you have edited include.h to use my simulated -exceptions or to disable exceptions. If there is no catch statement or exceptions are disabled then my -Terminate() function in myexcept.h is called when you throw an -exception. This prints out -an error message, the dimensions and types of the matrices involved, the name -of the routine detecting the exception, and any other information set by the -Tracer class. Also see the section on error messages for additional notes on the messages generated -by the exceptions.

-

You can also print this information in a catch clause by printing Exception::what(). -

-

If you are using compiler supported exceptions then see the section -on catching exceptions.  -

-

See the file test_exc.cpp as an example of catching an exception -and printing the error message.

-

The 08 version of newmat defined a member function void -SetAction(int) to help customise the action when an exception is called. -This has been deleted in the 09 and 10 versions. Now include an instruction -such as cout << Exception::what() << endl; in the -Catch or CatchAll block to determine the action.

-

The library includes the alternatives of using the inbuilt exceptions -provided by a compiler, simulating exceptions, or disabling exceptions. See -customising for selecting the correct exception option. -

-

The rest of this section describes my partial simulation of exceptions for -compilers which do not support C++ exceptions. I use Carlos Vidal's article in -the September 1992 C Users Journal as a starting point.

-

Newmat does a partial clean up of memory following throwing an exception - -see the next section. However, the present version will leave a little heap -memory unrecovered under some circumstances. I would not expect this to be a -major problem, but it is something that needs to be sorted out.

-

The functions/macros I define are Try, Throw, Catch, CatchAll and -CatchAndThrow. Try, Throw, Catch and CatchAll correspond to try, throw, catch -and catch(...) in the C++ standard. A list of Catch clauses must be terminated -by either CatchAll or CatchAndThrow but not both. Throw takes an Exception as -an argument or takes no argument (for passing on an exception). I do not have a -version of Throw for specifying which exceptions a function might throw. Catch -takes an exception class name as an argument; CatchAll and CatchAndThrow don't -have any arguments. Try, Catch and CatchAll must be followed by blocks enclosed -in curly brackets.

-

I have added another macro ReThrow to mean a rethrow, Throw(). This was -necessary to enable the package to be compatible with both my exception package -and C++ exceptions.

-

If you want to throw an exception, use a statement like

-
   Throw(Exception("Error message\n"));
-
- -

It is important to have the exception declaration in the Throw statement, -rather than as a separate statement.

-

All exception classes must be derived from the class, Exception, defined in -newmat and can contain only static variables. See the examples in newmat if you -want to define additional exceptions.

-

Note that the simulation exception mechanism does not work if you define -arrays of matrices.

-

3.28 Cleanup after an -exception

-

next - skip - -up - start

-

This section is about the simulated exceptions used in newmat. It is -irrelevant if you are using the exceptions built into a compiler or have set -the disable-exceptions option.

-

The simulated exception mechanisms in newmat are based on the C functions -setjmp and longjmp. These functions do not call destructors so can lead to -garbage being left on the heap. (I refer to memory allocated by new as -heap memory). For example, when you call

-
   Matrix A(20,30);
-
- -

a small amount of space is used on the stack containing the row and column -dimensions of the matrix and 600 doubles are allocated on the heap for the -actual values of the matrix. At the end of the block in which A is declared, -the destructor for A is called and the 600 doubles are freed. The locations on -the stack are freed as part of the normal operations of the stack. If you leave -the block using a longjmp command those 600 doubles will not be freed and will -occupy space until the program terminates.

-

To overcome this problem newmat keeps a list of all the currently declared -matrices and its exception mechanism will return heap memory when you do a -Throw and Catch.

-

However it will not return heap memory from objects from other packages. -

-

If you want the mechanism to work with another class you will have to do -four things:

-
    -
  1. derive your class from class Janitor defined in except.h;
  2. -
  3. define a function void CleanUp() in that class to return all heap -memory;
  4. -
  5. include the following lines in the class definition
          public:
    -         void* operator new(size_t size)
    -         { do_not_link=true; void* t = ::operator new(size); return t; }
    -         void operator delete(void* t) { ::operator delete(t); }
    -
    - -
  6. -
  7. be sure to include a copy constructor in you class definition, that is, -something like
          X(const X&);
    -
    - -
  8. -
-

Note that the function CleanUp() does somewhat the same duties as -the destructor. However CleanUp() has to do the cleaning for -the class you are working with and also the classes it is derived from. So it -will often be wrong to use exactly the same code for both CleanUp() -and the destructor or to define your destructor as a call to -CleanUp().

-

3.29 Non-linear -applications

-

next - skip - -up - start

-

Files solution.h, solution.cpp contain a class for solving for x in -y = f(x) where x is a one-dimensional continuous -monotonic function. This is not a matrix thing at all but is included because -it is a useful thing and because it is a simpler version of the technique used -in the non-linear least squares.

-

Files newmatnl.h, newmatnl.cpp contain a series of classes for non-linear -least squares and maximum likelihood. These classes work on very well-behaved -functions but need upgrading for less well-behaved functions.

-

Documentation for both of these is in the definition files. Simple examples -are in sl_ex.cpp, nl_ex.cpp and garch.cpp.

-

3.30 Standard template -library

-

next - skip - -up - start

-

The standard template library (STL) is the set of container templates -(vector, deque, list etc) defined by the C++ standards committee. Newmat is -intended to be compatible with the STL in the sense that you can store matrices -in the standard containers. I have defined == and -inequality operators which seem to be required by some versions of the STL. Probably there will have -to be some other changes. My experiments with the Rogue Wave STL that comes -with Borland C++ 5.0 showed that some things worked and some things -unexpectedly didn't work.

-

If you want to use the container classes with Newmat please note

-
    -
  • Don't use simulated exceptions.
  • -
  • Make sure the option DO_FREE_CHECK is not -turned on.
  • -
  • You can store only one type of matrix in a container. If you want to use a -variety of types use the GenericMatrix type or store pointers to the matrices. -
  • -
  • The vector and deque container templates like to copy their elements. For -the vector container this happens when you insert an element anywhere except at -the end or when you append an element and the current vector storage overflows. -Since Newmat does not have copy-on-write this could get very -inefficient. (Later versions may have copy-on-write for the -GenericMatrix type).
  • -
  • You won't be able to sort the container or do anything that would call an -inequality operator.
  • -
-

I doubt whether the STL container will be used often for matrices. So I -don't think these limitations are very critical. If you think otherwise, please -tell me.

-

3.31 Namespace

-

next - skip - -up - start

-

Namespace is a new facility in C++. Its purpose is to avoid name -clashes between different libraries. I have included the namespace capability. -Activate the line #define use_namespace in include.h. Then -include either the statement

-
   using namespace NEWMAT;
-
- -

at the beginning of any file that needs to access the newmat library or

-
   using namespace RBD_LIBRARIES;
-
- -

at the beginning of any file that needs to access all my libraries.

-

This works correctly with Borland C++ version 5.

-

Microsoft Visual C++ version 5 works in my example -and test files, but fails with apparently insignificant changes (it may be more -reliable if you have applied service pack 3). If you #include -"newmatap.h", but no other newmat include file, then also #include -"newmatio.h". It seems to work with Microsoft -Visual C++ version 6 if you have applied at least service pack 2.

-

My use of namespace does not work with Gnu g++ version -2.8.1 but does work with the egs version that comes with Red Hat 6.2.

-

I have defined the following namespaces:

-
    -
  • RBD_COMMON for functions and classes used by most of my libraries
  • -
  • NEWMAT for the newmat library
  • -
  • RBD_LIBRARIES for all my libraries
  • -
-

4. Error messages

-

next - skip - -up - start

-

Most error messages are self-explanatory. The message gives the size of the -matrices involved. Matrix types are referred to by the following codes:

-
   Matrix or vector                   Rect
-   Symmetric matrix                   Sym
-   Band matrix                        Band
-   Symmetric band matrix              SmBnd
-   Lower triangular matrix            LT
-   Lower triangular band matrix       LwBnd
-   Upper triangular matrix            UT
-   Upper triangular band matrix       UpBnd
-   Diagonal matrix                    Diag
-   Crout matrix (LU matrix)           Crout
-   Band LU matrix                     BndLU
-
- -

Other codes should not occur.

-

See the section on exceptions for more details on the -structure of the exception classes.

-

I have defined a class Tracer that is intended to help locate the place -where an error has occurred. At the beginning of a function I suggest you -include a statement like

-
   Tracer tr("name");
-
- -

where name is the name of the function. This name will be printed as part of -the error message, if an exception occurs in that function, or in a function -called from that function. You can change the name as you proceed through a -function with the ReName function

-
   tr.ReName("new name");
-
- -

if, for example, you want to track progress through the function.

-

5. Notes on the design of the -library

-

next - skip - -up - start

- - - - - -
5.1 -Safety, usability, efficiency
-5.2 Matrix vs array library
-5.3 Design questions
-5.4 Data storage
-5.5 Memory management - 1
-5.6 Memory management - 2
-5.7 Evaluation of expressions
5.8 Explosion in the number of operations
-5.9 Destruction of temporaries
-5.10 A calculus of matrix types
-5.11 Pointer arithmetic
-5.12 Error handling
-5.13 Sparse matrices
-5.14 Complex matrices
-

I describe some of the ideas behind this package, some of the decisions that -I needed to make and give some details about the way it works. You don't need -to read this part of the documentation in order to use the package.

-

It isn't obvious what is the best way of going about structuring a matrix -package. I don't think you can figure this out with thought experiments. -Different people have to try out different approaches. And someone else may -have to figure out which is best. Or, more likely, the ultimate packages will -lift some ideas from each of a variety of trial packages. So, I don't claim my -package is an ultimate package, but simply a trial of a number of ideas. -The following pages give some background on these ideas.

-

5.1 Safety, usability, -efficiency

-

next - skip - -up - start

-

Some general comments

-

A library like newmat needs to balance safety, -usability and efficiency.

-

By safety, I mean getting the right answer, and not causing crashes -or damage to the computer system.

-

By usability, I mean being easy to learn and use, including not being -too complicated, being intuitive, saving the users' time, being nice to use. -

-

Efficiency means minimising the use of computer memory and time.

-

In the early days of computers the emphasis was on efficiency. But computer -power gets cheaper and cheaper, halving in price every 18 months. On the other -hand the unaided human brain is probably not a lot better than it was 100,000 -years ago! So we should expect the balance to shift to put more emphasis on -safety and usability and a little less on efficiency. So I don't mind if my -programs are a little less efficient than programs written in pure C (or -Fortran) if I gain substantially in safety and usability. But I would mind if -they were a lot less efficient.

-

Type of use

-

Second reason for putting extra emphasis on safety and usability is the way -I and, I suspect, most other users actually use newmat. Most completed -programs are used only a few times. Some result is required for a client, paper -or thesis. The program is developed and tested, the result is obtained, and the -program archived. Of course bits of the program will be recycled for the next -project. But it may be less usual for the same program to be run over and over -again. So the cost, computer time + people time, is in the development time and -often, much less in the actual time to run the final program. So good use of -people time, especially during development is really important. This means you -need highly usable libraries.

-

So if you are dealing with matrices, you want the good interface that I have -tried to provide in newmat, and, of course, reliable methods underneath -it.

-

Of course, efficiency is still important. We often want to run the biggest -problem our computer will handle and often a little bigger. The C++ language -almost lets us have both worlds. We can define a reasonably good interface, and -get good efficiency in the use of the computer.

-

Levels of access

-

We can imagine the black box model of a newmat. Suppose the -inside is hidden but can be accessed by the methods described in the -reference section. Then the interface is reasonably -consistent and intuitive. Matrices can be accessed and manipulated in much the -same way as doubles or ints in regular C. All accesses are checked. It is most -unlikely that an incorrect index will crash the system. In general, users do -not need to use pointers, so one shouldn't get pointers pointing into space. -And, hopefully, you will get simpler code and so less errors.

-

There are some exceptions to this. In particular, the C-like subscripts are not checked for validity. They give -faster access but with a lower level of safety.

-

Then there is the Store() function which takes you to -the data array within a matrix. This takes you right inside the black -box. But this is what you have to use if you are writing, for example, a -new matrix factorisation, and require fast access to the data array. I have -tried to write code to simplify access to the interior of a rectangular matrix, -see file newmatrm.cpp, but I don't regard this as very successful, as yet, and -have not included it in the documentation. Ideally we should have improved -versions of this code for each of the major types of matrix. But, in reality, -most of my matrix factorisations are written in what is basically the C -language with very little C++.

-

So our box is not very black. You have a choice of how far you -penetrate. On the outside you have a good level of safety, but in some cases -efficiency is compromised a little. If you penetrate inside the box -safety is reduced but you can get better efficiency.

-

Some performance data

-

This section looks at the performance on newmat for simple sums, -comparing it with C code and with a simple array program. -

-

The following table lists the time (in seconds) for carrying out the -operations X=A+B;, X=A+B+C;, X=A+B+C+D;, X=A+B+C+D+E; where -X,A,B,C,D,E are of type ColumnVector, with a variety of programs. I am -using Microsoft VC++, version 6 in console mode under windows 2000 on a PC with -a 1 ghz Pentium III and 512 mbytes of memory.

-
    length    iters. newmat      C C-res.  subs.  array
-X = A + B
-         2   5000000   27.8    0.3    8.8    1.9    9.5 
-        20    500000    3.0    0.3    1.1    1.9    1.2 
-       200     50000    0.5    0.3    0.4    1.9    0.3 
-      2000      5000    0.4    0.3    0.4    2.0    1.0 
-     20000       500    4.5    4.5    4.5    6.7    4.4 
-    200000        50    5.2    4.7    5.5    5.8    5.2 
-
-X = A + B + C
-         2   5000000   36.6    0.4    8.9    2.5   12.2 
-        20    500000    4.0    0.4    1.2    2.5    1.6 
-       200     50000    0.8    0.3    0.5    2.5    0.5 
-      2000      5000    3.6    4.4    4.6    9.0    4.4 
-     20000       500    6.8    5.4    5.4    9.6    6.8 
-    200000        50    8.6    6.0    6.7    7.1    8.6 
-
-X = A + B + C + D
-         2   5000000   44.0    0.7    9.3    3.1   14.6 
-        20    500000    4.9    0.6    1.5    3.1    1.9 
-       200     50000    1.0    0.6    0.8    3.2    0.8 
-      2000      5000    5.6    6.6    6.8   11.5    5.9 
-     20000       500    9.0    6.7    6.8   11.0    8.5 
-    200000        50   11.9    7.1    7.9    9.5   12.0 
-
-X = A + B + C + D + E
-         2   5000000   50.6    1.0    9.5    3.8   17.1 
-        20    500000    5.7    0.8    1.7    3.9    2.4 
-       200     50000    1.3    0.9    1.0    3.9    1.0 
-      2000      5000    7.0    8.3    8.2   13.8    7.1 
-     20000       500   11.5    8.1    8.4   13.2   11.0 
-    200000        50   15.2    8.7    9.5   12.4   15.4 
-
-

I have graphed the results -and included rather more array lengths.

- -

You may need to move file add_time.png to subdirectory -images to see this -graph.

- -

The first column gives the lengths of the arrays, the second the number of -iterations and the remaining columns the total time required in seconds. If the -only thing that consumed time was the double precision addition then the -numbers within each block of the table would be the same. The summation is -repeated 5 times within each loop, for example:

-
   for (i=1; i<=m; ++i)
-   {
-      X1 = A1+B1+C1; X2 = A2+B2+C2; X3 = A3+B3+C3;
-      X4 = A4+B4+C4; X5 = A5+B5+C5;
-   }
-

The column labelled newmat is using the standard newmat add. The column labelled C uses the usual C method: while -(j1--) *x1++ = *a1++ + *b1++; . The following column also includes an -X.ReSize() in the outer loop to correspond to the reassignment of -memory that newmat would do. In the next column the calculation is using -the usual C style for loop -and accessing the elements using newmat subscripts such as -A(i). The final column is the time taken by a -simple array package. This uses an alternative method for avoiding temporaries -and unnecessary copies that does not involve runtime tests. It does its sums in blocks of 4 and copies in blocks of -8 in the same way that newmat does.

-

Here are my conclusions.

-
    -
  • Newmat does very badly for length 2 and doesn't do well for -length 20. There is a lot of code in newmat for -determining which sum algorithm to use and it is not surprising that this -impacts on performance for small lengths. -However the array program is also having difficulty with length 2 so it -is unlikely that the problem could be completely eliminated.
  • -
  • For arrays of length 2000 or longer newmat is doing about as well as -C and slightly better than C with resize in the X=A+B table. For the -other two tables it tends to be slower, but not dramatically so.
  • -
  • It is really important for fast processing with the Pentium III to stay -within the Pentium cache.
  • -
  • Addition using the newmat subscripts, while considerably slower than -the others, is still surprisingly good for the longer arrays.
  • -
  • The array program and newmat are similar for -lengths 2000 or higher (the longer times for the array program for the longest -arrays shown on the graph are probably a quirk of the timing program).
  • -
-

In summary: for the situation considered here, newmat is doing very -well for large ColumnVectors, even for sums with several terms, but not so well -for shorter ColumnVectors.

-

5.2 Matrix vs array -library

-

next - skip - -up - start

-

The newmat library is for the manipulation of matrices, including the -standard operations such as multiplication as understood by numerical analysts, -engineers and mathematicians.

-

A matrix is a two dimensional array of numbers. However, very special -operations such as matrix multiplication are defined specifically for matrices. -This means that a matrix library, as I understand the term, is different -from a general array library. Here are some contrasting properties.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureMatrix -libraryArray -library
ExpressionsMatrix expressions; -* means matrix multiply; inverse functionArithmetic operations, if -supported, mean elementwise combination of arrays
Element accessAccess to the elements of a -matrixHigh speed access to elements -directly and perhaps with iterators
Elementary functionsFor example: determinant, -traceMatrix multiplication as a -function
Advanced functionsFor example: eigenvalue -analysis 
Element typesReal and possibly -complexWide range - real, integer, string -etc
TypesRectangular, symmetric, diagonal, -etcOne, two and three dimensional -arrays, at least
-

Both types of library need to support access to sub-matrices or sub-arrays, -have good efficiency and storage management, and graceful exit for errors. In -both cases, we probably need two versions, one optimised for large matrices or -arrays and one for small matrices or arrays.

-

It may be possible to amalgamate the two sets of requirements to some -extent. However newmat is definitely oriented towards the matrix library -set.

-

5.3 Design questions

-

next - skip - -up - start

-

Even within the bounds set by the requirements of a matrix library there is -a substantial opportunity for variation between what different matrix packages -might provide. It is not possible to build a matrix package that will meet -everyone's requirements. In many cases if you put in one facility, you impose -overheads on everyone using the package. This both in storage required for the -program and in efficiency. Likewise a package that is optimised towards -handling large matrices is likely to become less efficient for very small -matrices where the administration time for the matrix may become significant -compared with the time to carry out the operations. It is better to provide a -variety of packages (hopefully compatible) so that most users can find one that -meets their requirements. This package is intended to be one of these packages; -but not all of them.

-

Since my background is in statistical methods, this package is oriented -towards the kinds things you need for statistical analyses.

-

Now looking at some specific questions.

-

What size of matrices?

-

A matrix library may target small matrices (say 3 x 3), or medium sized -matrices, or very large matrices.

-

A library targeting very small matrices will seek to minimise -administration. A library for medium sized or very large matrices can spend -more time on administration in order to conserve space or optimise the -evaluation of expressions. A library for very large matrices will need to pay -special attention to storage and numerical properties. This library is designed -for medium sized matrices. This means it is worth introducing some -optimisations, but I don't have to worry about setting up some form of virtual -memory.

-

Which matrix types?

-

As well as the usual rectangular matrices, matrices occurring repeatedly in -numerical calculations are upper and lower triangular matrices, symmetric -matrices and diagonal matrices. This is particularly the case in calculations -involving least squares and eigenvalue calculations. So as a first stage these -were the types I decided to include.

-

It is also necessary to have types row vector and column vector. In a -matrix package, in contrast to an array package, it is necessary -to have both these types since they behave differently in matrix expressions. -The vector types can be derived for the rectangular matrix type, so having them -does not greatly increase the complexity of the package.

-

The problem with having several matrix types is the number of versions of -the binary operators one needs. If one has 5 distinct matrix types then a -simple library will need 25 versions of each of the binary operators. In fact, -we can evade this problem, but at the cost of some complexity.

-

What element types?

-

Ideally we would allow element types double, float, complex and int, at -least. It might be reasonably easy, using templates or equivalent, to provide a -library which could handle a variety of element types. However, as soon as one -starts implementing the binary operators between matrices with different -element types, again one gets an explosion in the number of operations one -needs to consider. At the present time the compilers I deal with are not up to -handling this problem with templates. (Of course, when I started writing -newmat there were no templates). But even when the compilers do meet the -specifications of the draft standard, writing a matrix package that allows for -a variety of element types using the template mechanism is going to be very -difficult. I am inclined to use templates in an array library but not in -a matrix library.

-

Hence I decided to implement only one element type. But the user can decide -whether this is float or double. The package assumes elements are of type Real. -The user typedefs Real to float or double.

-

It might also be worth including symmetric and triangular matrices with -extra precision elements (double or long double) to be used for storage only -and with a minimum of operations defined. These would be used for accumulating -the results of sums of squares and product matrices or multi-stage QR -triangularisations.

-

Allow matrix expressions

-

I want to be able to write matrix expressions the way I would on paper. So -if I want to multiply two matrices and then add the transpose of a third one I -can write something like X = A * B + C.t();. I want this expression to -be evaluated with close to the same efficiency as a hand-coded version. This is -not so much of a problem with expressions including a multiply since the -multiply will dominate the time. However, it is not so easy to achieve with -expressions with just + and -.

-

A second requirement is that temporary matrices generated during the -evaluation of an expression are destroyed as quickly as possible.

-

A desirable feature is that a certain amount of intelligence be -displayed in the evaluation of an expression. For example, in the expression -X = A.i() * B; where i() denotes inverse, it would be -desirable if the inverse wasn't explicitly calculated.

-

Naming convention

-

How are classes and public member functions to be named? As a general rule I -have spelt identifiers out in full with individual words being capitalised. For -example UpperTriangularMatrix. If you don't like this you can #define or -typedef shorter names. This convention means you can select an abbreviation -scheme that makes sense to you.

-

Exceptions to the general rule are the functions for transpose and inverse. -To make matrix expressions more like the corresponding mathematical formulae, I -have used the single letter abbreviations, t() and i().

-

Row and column index ranges

-

In mathematical work matrix subscripts usually start at one. In C, array -subscripts start at zero. In Fortran, they start at one. Possibilities for this -package were to make them start at 0 or 1 or be arbitrary.

-

Alternatively one could specify an index set for indexing the rows -and columns of a matrix. One would be able to add or multiply matrices only if -the appropriate row and column index sets were identical.

-

In fact, I adopted the simpler convention of making the rows and columns of -a matrix be indexed by an integer starting at one, following the traditional -convention. In an earlier version of the package I had them starting at zero, -but even I was getting mixed up when trying to use this earlier package. So I -reverted to the more usual notation and started at 1.

-

Element access - method and checking

-

We want to be able to use the notation A(i,j) to specify the -(i,j)-th element of a matrix. This is the way mathematicians expect to -address the elements of matrices. I consider the notation A[i][j] -totally alien. However I include this as an option to help people converting -from C.

-

There are two ways of working out the address of A(i,j). One is -using a dope vector which contains the first address of each row. -Alternatively you can calculate the address using the formula appropriate for -the structure of A. I use this second approach. It is probably slower, -but saves worrying about an extra bit of storage.

-

The other question is whether to check for i and j being -in range. I do carry out this check following years of experience with both -systems that do and systems that don't do this check. I would hope that the -routines I supply with this package will reduce your need to access elements of -matrices so speed of access is not a high priority.

-

Use iterators

-

Iterators are an alternative way of providing fast access to the elements of -an array or matrix when they are to be accessed sequentially. They need to be -customised for each type of matrix. I have not implemented iterators in this -package, although some iterator like functions are used internally for some row -and column functions.

-

5.4 Data storage

-

next - skip - -up - start

-

The stack and heap

-

To understand how newmat stores matrices you need to know a little bit -about the heap and stack.

-

The data values of variables or objects in a C++ program are stored in either -of two sections of memory called the stack and the heap. Sometimes -there is more than one heap to cater for different sized variables.

-

If you declare an automatic variable

-
   int x;
-

then the value of x is stored on the stack. As you declare more -variables the stack gets bigger. When you exit a block (i.e a section of code -delimited by curly brackets {...}) the memory used by the automatic -variables declared in the block is released and the stack shrinks.

-

When you declare a variable with new, for example,

-
   int* y = new int;
-

the pointer y is stored on the stack but the value it is -pointing to is stored on the heap. Memory on the heap is not -released until the program explicitly does this with a delete statement

-
   delete *y;
-

or the program exits.

-

On the stack, variables and objects are is always added to the end of -the stack and are removed in the reverse order to that in which they are -added - that is the last on will be the first off. This is not the case with the -heap, where the variables and objects can be removed in any order. So one -can get alternating pieces of used and unused memory. When a new variable or -object is declared on the heap the system needs to search for piece of -unused memory large enough to hold it. This means that storing on the heap -will usually be a slower process than storing on the stack. There is also -likely to be waste space on the heap because of gaps between the used -blocks of memory that are too small for the next object you want to store on the -heap. There is also the possibility of wasting space if you forget to -remove a variable or object on the heap even though you have finished -using it. However, the stack is usually limited to holding small objects -with size known at compile time. Large objects, objects whose size you don't -know at compile time, and objects that you want to persist after the end of the -block need to be stored on the heap.

-

In C++, the constructor/destructor system enables one to build -complicated objects such as matrices that behave as automatic variables stored -on the stack, so the programmer doesn't have to worry about deleting them -at the end of the block, but which really utilise the heap for storing -their data.

-

Structure of matrix objects

-

Each matrix object contains the basic information such as the number of rows -and columns, the amount of memory used, a status variable and a pointer to the data array which is on -the heap. So if you declare a matrix

-
   Matrix A(1000,1000);
-

there is an small amount of memory used on the stack for storing the numbers -of rows and columns, the amount of  memory used, the status variable and -the pointer together with 1,000,000 Real locations stored on the heap. -When you exit the block in which A is declared, the heap memory used by -A is automatically returned to the system, as well as the memory used on -the stack.

-

Of course, if you use new to declare a matrix

-
   Matrix* B = new Matrix(1000,1000);
-

both the information about the size and the actual data are stored on heap -and not deleted until the program exits or you do an explicit delete:

-
   delete *B;
-

If you carry out an assignment with = or << or do a -resize() the data array currently associated with a matrix is destroyed and -a new array generated. For example

-
   Matrix A(1000,1000);
-   Matrix B(50, 50);
-   ... put some values in B
-   A = B;
-

At the last step the heap memory associated with A is returned to the -system and a new block of heap memory is assigned to contain the new values. -This happens even if there is no change in the amount of memory required.

-

One block or several

-

The elements of the matrix are stored as a single array. Alternatives would -have been to store each row as a separate array or a set of adjacent rows as a -separate array. The present solution simplifies the program but limits the size -of matrices in 16 bit PCs that have a 64k byte limit on the size of arrays (I -don't use the huge keyword). The large arrays may also cause problems -for memory management in smaller machines. [The 16 bit PC problem has largely -gone away but it was a problem when much of newmat was written. Now, -occasionally I run into the 32 bit PC problem.]

-

By row or by column or other

-

In Fortran two dimensional arrays are stored by column. In most other -systems they are stored by row. I have followed this later convention. This -makes it easier to interface with other packages written in C but harder to -interface with those written in Fortran. This may have been a wrong decision. -Most work on the efficient manipulation of large matrices is being done in -Fortran. It would have been easier to use this work if I had adopted the -Fortran convention.

-

An alternative would be to store the elements by mid-sized rectangular -blocks. This might impose less strain on memory management when one needs to -access both rows and columns.

-

Storage of symmetric matrices

-

Symmetric matrices are stored as lower triangular matrices. The decision was -pretty arbitrary, but it does slightly simplify the Cholesky decomposition -program.

-

5.5 Memory management - -reference counting or status variable?

-

next - skip - -up - start

-

Consider the instruction

-
   X = A + B + C;
-
- -

To evaluate this a simple program will add A to B putting -the total in a temporary T1. Then it will add T1 to -C creating another temporary T2 which will be copied into -X. T1 and T2 will sit around till the end of the -execution of the statement and perhaps of the block. It would be faster if the -program recognised that T1 was temporary and stored the sum of -T1 and C back into T1 instead of creating -T2 and then avoided the final copy by just assigning the contents of -T1 to X rather than copying. In this case there will be no -temporaries requiring deletion. (More precisely there will be a header to be -deleted but no contents).

-

For an instruction like

-
   X = (A * B) + (C * D);
-
- -

we can't easily avoid one temporary being left over, so we would like this -temporary deleted as quickly as possible.

-

I provide the functionality for doing all this by attaching a status -variable to each matrix. This indicates if the matrix is temporary so that its -memory is available for recycling or deleting. Any matrix operation checks the -status variables of the matrices it is working with and recycles or deletes any -temporary memory.

-

An alternative or additional approach would be to use reference counting -and delayed copying - also known as copy on write. If a program -requests a matrix to be copied, the copy is delayed until an instruction is -executed which modifies the memory of either the original matrix or the copy. -If the original matrix is deleted before either matrix is modified, in effect, -the values of the original matrix are transferred to the copy without any -actual copying taking place. This solves the difficult problem of returning an -object from a function without copying and saves the unnecessary copying in the -previous examples.

-

There are downsides to the delayed copying approach. Typically, for delayed -copying one uses a structure like the following:

-
   Matrix
-     |
-     +------> Array Object
-     |          |
-     |          +------> Data array
-     |          |
-     |          +------- Counter
-     |
-     +------ Dimension information
-
-
- -

where the arrows denote a pointer to a data structure. If one wants to -access the Data array one will need to track through two pointers. If -one is going to write, one will have to check whether one needs to copy first. -This is not important when one is going to access the whole array, say, for a -add operation. But if one wants to access just a single element, then it -imposes a significant additional overhead on that operation. Any subscript -operation would need to check whether an update was required - even read since -it is hard for the compiler to tell whether a subscript access is a read or -write.

-

Some matrix libraries don't bother to do this. So if you write A = -B; and then modify an element of one of A or B, then the -same element of the other is also modified. I don't think this is acceptable -behaviour.

-

Delayed copy does not provide the additional functionality of my approach -but I suppose it would be possible to have both delayed copy and tagging -temporaries.

-

My approach does not automatically avoid all copying. In particular, you -need use a special technique to return a matrix from a function without -copying.

-

5.6 Memory management - -accessing contiguous locations

-

next - skip - -up - start

-

Modern computers work faster if one accesses memory by running through -contiguous locations rather than by jumping around all over the place. Newmat -stores matrices by rows so that algorithms that access -memory by running along rows will tend to work faster than one that runs down -columns. A number of the algorithms used in Newmat were developed before this -was an issue and so are not as efficient as possible.

-

I have gradually upgrading the algorithms to access memory by rows. The -following table shows the current status of this process.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FunctionContiguous memory accessComment
Add, subtractYes 
MultiplyYes 
ConcatenateYes 
TransposeNo 
Invert and solveYesMostly
CholeskyYes 
QRZ, QRZTYes 
SVDNo 
JacobiNoNot an issue; used only for smaller matrices
EigenvaluesNo 
SortYesQuick-sort is naturally good
FFT?Could be improved?
-

5.7 Evaluation of expressions - -lazy evaluation

-

next - skip - -up - start

-

Consider the instruction

-
   X = B - X;
-
- -

A simple program will subtract X from B, store the result -in a temporary T1 and copy T1 into X. It would be -faster if the program recognised that the result could be stored directly into -X. This would happen automatically if the program could look at the -instruction first and mark X as temporary.

-

C programmers would expect to avoid the same problem with

-
   X = X - B;
-
- -

by using an operator -=

-
   X -= B;
-
- -

However this is an unnatural notation for non C users and it may be nicer to -write X = X - B; and know that the program will carry out the -simplification.

-

Another example where this intelligent analysis of an instruction is helpful -is in

-
   X = A.i() * B;
-
- -

where i() denotes inverse. Numerical analysts know it is -inefficient to evaluate this expression by carrying out the inverse operation -and then the multiply. Yet it is a convenient way of writing the instruction. -It would be helpful if the program recognised this expression and carried out -the more appropriate approach.

-

I regard this interpretation of A.i() * B as just providing a -convenient notation. The objective is not primarily to correct the errors of -people who are unaware of the inefficiency of A.i() * B if interpreted -literally.

-

There is a third reason for the two-stage evaluation of expressions and this -is probably the most important one. In C++ it is quite hard to return an -expression from a function such as (*, + etc) without a copy. -This is particularly the case when an assignment (=) is involved. The -mechanism described here provides one way for avoiding this in matrix -expressions.

-

The C++ standard (section 12.8/15) allows the compiler to optimise away the -copy when returning an object from a function (but there will still be one copy -is an assignment (=) is involved). This means special handling of returns from a -function is less important when a modern optimising compiler is being -used. 

-

To carry out this intelligent analysis of an instruction matrix -expressions are evaluated in two stages. In the the first stage a tree -representation of the expression is formed. For example (A+B)*C is -represented by a tree

-

-       *
-      / \
-     +   C
-    / \
-   A   B
-
- -

Rather than adding A and B the + operator yields -an object of a class AddedMatrix which is just a pair of pointers to -A and B. Then the * operator yields a -MultipliedMatrix which is a pair of pointers to the AddedMatrix -and C. The tree is examined for any simplifications and then evaluated -recursively.

-

Further possibilities not yet included are to recognise A.t()*A and -A.t()+A as symmetric or to improve the efficiency of evaluation of -expressions like A+B+C, A*B*C, A*B.t() (t() -denotes transpose).

-

One of the disadvantages of the two-stage approach is that the types of -matrix expressions are determined at run-time. So the compiler will not detect -errors of the type

-
   Matrix M;
-   DiagonalMatrix D;
-   ....;
-   D = M;
-
- -

We don't allow conversions using = when information would be lost. -Such errors will be detected when the statement is executed.

-

5.8 How to overcome an -explosion in number of operations

-

next - skip - -up - start

-

The package attempts to solve the problem of the large number of versions of -the binary operations required when one has a variety of types.

-

With n types of matrices the binary operations will each require -n-squared separate algorithms. Some reduction in the number may be -possible by carrying out conversions. However, the situation rapidly becomes -impossible with more than 4 or 5 types. Doug Lea told me that it was possible -to avoid this problem. I don't know what his solution is. Here's mine.

-

Each matrix type includes routines for extracting individual rows or -columns. I assume a row or column consists of a sequence of zeros, a sequence -of stored values and then another sequence of zeros. Only a single algorithm is -then required for each binary operation. The rows can be located very quickly -since most of the matrices are stored row by row. Columns must be copied and so -the access is somewhat slower. As far as possible my algorithms access the -matrices by row.

-

There is another approach. Each of the matrix types defined in this package -can be set up so both rows and columns have their elements at equal intervals -provided we are prepared to store the rows and columns in up to three chunks. -With such an approach one could write a single "generic" algorithm -for each of multiply and add. This would be a reasonable alternative to my -approach.

-

I provide several algorithms for operations like + . If one is adding two -matrices of the same type then there is no need to access the individual rows -or columns and a faster general algorithm is appropriate.

-

Generally the method works well. However symmetric matrices are not always -handled very efficiently (yet) since complete rows are not stored explicitly. -

-

The original version of the package did not use this access by row or column -method and provided the multitude of algorithms for the combination of -different matrix types. The code file length turned out to be just a little -longer than the present one when providing the same facilities with 5 distinct -types of matrices. It would have been very difficult to increase the number of -matrix types in the original version. Apparently 4 to 5 types is about the -break even point for switching to the approach adopted in the present package. -

-

However it must also be admitted that there is a substantial overhead in the -approach adopted in the present package for small matrices. The test program -developed for the original version of the package takes 30 to 50% longer to run -with the current version (though there may be some other reasons for this). -This is for matrices in the range 6x6 to 10x10.

-

To try to improve the situation a little I do provide an ordinary matrix -multiplication routine for the case when all the matrices involved are -rectangular.

-

5.9 Destruction of -temporaries

-

next - skip - -up - start

-

Versions before version 5 of newmat did not work correctly with Gnu C++ -(version 5 or earlier). This was because the tree structure used to represent a -matrix expression was set up on the stack. This was fine for AT&T, Borland -and Zortech C++.

-

However early version Gnu C++ destroys temporary structures as soon as the -function that accesses them finishes. The other compilers wait until the end of -the current expression or current block. To overcome this problem, there is now -an option to store the temporaries forming the tree structure on the heap -(created with new) and to delete them explicitly. Activate the definition of -TEMPS_DESTROYED_QUICKLY to set this option.

-

Now that the C++ standards committee has said that temporary structures -should not be destroyed before a statement finishes, I suggest using the stack, -because of the difficulty of managing exceptions with the heap version.

-

5.10 A calculus of matrix -types

-

next - skip - -up - start

-

The program needs to be able to work out the class of the result of a matrix -expression. This is to check that a conversion is legal or to determine the -class of an intermediate result. To assist with this, a class MatrixType is -defined. Operators +, -, *, >= are -defined to calculate the types of the results of expressions or to check that -conversions are legal.

-

Early versions of newmat stored the types of the results of -operations in a table. So, for example, if you multiplied an -UpperTriangularMatrix by a LowerTriangularMatrix, newmat would look up -the table and see that the result was of type Matrix. With this approach the -exploding number of operations problem recurred although -not as seriously as when code had to be written for each pair of types. But -there was always the suspicion that somewhere, there was an error in one of -those 9x9 tables, that would be very hard to find. And the problem would get -worse as additional matrix types or operators were included.

-

The present version of newmat solves the problem by assigning -attributes such as diagonal or band or upper -triangular to each matrix type. Which attributes a matrix type has, is -stored as bits in an integer. As an example, the DiagonalMatrix type has the -bits corresponding to diagonal, symmetric and band equal -to 1. By looking at the attributes of each of the operands of a binary -operator, the program can work out the attributes of the result of the -operation with simple bitwise operations. Hence it can deduce an appropriate -type. The symmetric attribute is a minor problem because -symmetric * symmetric does not yield symmetric unless both -operands are diagonal. But otherwise very simple code can be used to -deduce the attributes of the result of a binary operation.

-

Tables of the types resulting from the binary operators are output at the -beginning of the test program.

-

5.11 Pointer arithmetic

-

next - skip - -up - start

-

Suppose you do something like

-
   int* y = new int[100];
-   y += 200;          // y points to something outside the array
-   // y is never accessed
-
- -

Then the standard says that the behaviour of the program is undefined -even if y is never accessed. (You are allowed to calculate a pointer -value one location beyond the end of the array). In practice, a program like -this does not cause any problems with any compiler I have come across and -no-one has reported any such problems to me.

-

However, this error is detected by Borland's Code Guard -bound's checker and this makes it very difficult to use this to use Code -Guard to detect other problems since the output is swamped by reports of -this error.

-

Now consider

-
   int* y = new int[100];
-   y += 200;          // y points to something outside the array
-   y -= 150;          // y points to something inside the array
-   // y is accessed
-
- -

Again this is not strictly correct but does not seem to cause a problem. But -it is much more doubtful than the previous example.

-

I removed most instances of the second version of the problem from Newmat09. -Hopefully the remainder of these instances were removed from the current -version of Newmat10. In addition, most instances of the first version of the -problem have also been fixed.

-

There is one exception. The interface to the Numerical -Recipes in C does still contain the second version of the problem. This is -inevitable because of the way Numerical Recipes in C stores vectors and -matrices. If you are running the test program with a -bounds checking program, edit tmt.h to disable the testing of the NRIC -interface.

-

The rule does does cause a problem for authors of matrix and -multidimensional array packages. If we want to run down a column of a matrix we -would like to do something like

-
   // set values of column 1
-   Matrix A;
-   ... set dimensions and put values in A
-   Real* a = A.Store();               // points to first element
-   int nr = A.Nrows();                // number of rows
-   int nc = A.Ncols();                // number of columns
-   while (nr--)
-   {
-      *a = something to put in first element of row
-      a += nc;                        // jump to next element of column
-   }
-
- -

If the matrix has more than one column the last execution of a += -nc; will run off the end of the space allocated to the matrix and we'll -get a bounds error report.

-

Instead we have to use a program like

-
   // set values of column 1
-   Matrix A;
-   ... set dimensions and put values in A
-   Real* a = A.Store();               // points to first element
-   int nr = A.Nrows();                // number of rows
-   int nc = A.Ncols();                // number of columns
-   if (nr != 0)
-   {
-      for(;;)
-      {
-         *a = something to put in first element of row
-         if (!(--nr)) break;
-         a += nc;                     // jump to next element of column
-      }
-   }
-
- -

which is more complicated and consequently introduces more chance of error. -

-

5.12 Error handling -

-

next - skip - -up - start

-

The library now does have a moderately graceful exit from errors. One can -use either the simulated exceptions or the compiler supported exceptions. When -newmat08 was released (in 1995), compiler exception handling in the compilers I -had access to was unreliable. I recommended you used my simulated exceptions. -In 1997 compiler supported exceptions seemed to work on a variety of -compilers - but not all compilers. This is still true in 2001. Try using the -compiler supported exceptions if you have a recent compiler, but if you are -getting strange crashes or errors try going back to my simulated exceptions. -

-

The approach in the present library, attempting to simulate C++ exceptions, -is not completely satisfactory, but seems a good interim solution for those who -cannot use compiler supported exceptions. People who don't want exceptions in -any shape or form, can set the option to exit the program if an exception is -thrown.

-

The exception mechanism cannot clean-up objects explicitly created by new. -This must be explicitly carried out by the package writer or the package user. -I have not yet done this completely with the present package so occasionally a -little garbage may be left behind after an exception. I don't think this is a -big problem, but it is one that needs fixing.

-

5.13 Sparse matrices

-

next - skip - -up - start

-

The library does not support sparse matrices.

-

For sparse matrices there is going to be some kind of structure vector. It -is going to have to be calculated for the results of expressions in much the -same way that types are calculated. In addition, a whole new set of row and -column operations would have to be written.

-

Sparse matrices are important for people solving large sets of differential -equations as well as being important for statistical and operational research -applications.

-

But there are packages being developed specifically for sparse matrices and -these might present the best approach, at least where sparse matrices are the -main interest.

-

5.14 Complex matrices

-

next - skip - -up - start

-

The package does not yet support matrices with complex elements. There are -at least two approaches to including these. One is to have matrices with -complex elements.

-

This probably means making new versions of the basic row and column -operations for Real*Complex, Complex*Complex, Complex*Real and similarly for -+ and -. This would be OK, except that if I also want to do -this for sparse matrices, then when you put these together, the whole thing -will get out of hand.

-

The alternative is to represent a Complex matrix by a pair of Real matrices. -One probably needs another level of decoding expressions but I think it might -still be simpler than the first approach. But there is going to be a problem -with accessing elements and it does not seem possible to solve this in an -entirely satisfactory way.

-

Complex matrices are used extensively by electrical engineers and physicists -and really should be fully supported in a comprehensive package.

-

You can simulate most complex operations by representing Z = X + iY -by

-
    /  X   Y \
-    \ -Y   X / 
-
- -

Most matrix operations will simulate the corresponding complex operation, -when applied to this matrix. But, of course, this matrix is essentially twice as big as you -would need with a genuine complex matrix library.

-

return to top
-return to online documentation page

-

 

-

 

-

 

-

 

-

 

-

 

-

 

- - \ No newline at end of file diff --git a/lib/src/mixmod/NEWMAT/precisio.h b/lib/src/mixmod/NEWMAT/precisio.h deleted file mode 100644 index ee8b3a8..0000000 --- a/lib/src/mixmod/NEWMAT/precisio.h +++ /dev/null @@ -1,241 +0,0 @@ -//$$ precisio.h floating point constants - -#ifndef PRECISION_LIB -#define PRECISION_LIB 0 - -#ifdef _STANDARD_ // standard library available -#include -#endif - -#ifdef use_namespace -namespace NEWMAT { -#endif - -#ifdef _STANDARD_ // standard library available - - using namespace std; - - class FloatingPointPrecision - { - public: - static int Dig() // number of decimal digits or precision - { return numeric_limits::digits10 ; } - - static Real Epsilon() // smallest number such that 1+Eps!=Eps - { return numeric_limits::epsilon(); } - - static int Mantissa() // bits in mantisa - { return numeric_limits::digits; } - - static Real Maximum() // maximum value - { return numeric_limits::max(); } - - static int MaximumDecimalExponent() // maximum decimal exponent - { return numeric_limits::max_exponent10; } - - static int MaximumExponent() // maximum binary exponent - { return numeric_limits::max_exponent; } - - static Real LnMaximum() // natural log of maximum - { return (Real)log(Maximum()); } - - static Real Minimum() // minimum positive value - { return numeric_limits::min(); } - - static int MinimumDecimalExponent() // minimum decimal exponent - { return numeric_limits::min_exponent10; } - - static int MinimumExponent() // minimum binary exponent - { return numeric_limits::min_exponent; } - - static Real LnMinimum() // natural log of minimum - { return (Real)log(Minimum()); } - - static int Radix() // exponent radix - { return numeric_limits::radix; } - - static int Rounds() // addition rounding (1 = does round) - { - return numeric_limits::round_style == - round_to_nearest ? 1 : 0; - } - - }; - - -#else // _STANDARD_ not defined - -#ifndef SystemV // if there is float.h - - -#ifdef USING_FLOAT - - - class FloatingPointPrecision - { - public: - static int Dig() - { return FLT_DIG; } // number of decimal digits or precision - - static Real Epsilon() - { return FLT_EPSILON; } // smallest number such that 1+Eps!=Eps - - static int Mantissa() - { return FLT_MANT_DIG; } // bits in mantisa - - static Real Maximum() - { return FLT_MAX; } // maximum value - - static int MaximumDecimalExponent() - { return FLT_MAX_10_EXP; } // maximum decimal exponent - - static int MaximumExponent() - { return FLT_MAX_EXP; } // maximum binary exponent - - static Real LnMaximum() - { return (Real)log(Maximum()); } // natural log of maximum - - static Real Minimum() - { return FLT_MIN; } // minimum positive value - - static int MinimumDecimalExponent() - { return FLT_MIN_10_EXP; } // minimum decimal exponent - - static int MinimumExponent() - { return FLT_MIN_EXP; } // minimum binary exponent - - static Real LnMinimum() - { return (Real)log(Minimum()); } // natural log of minimum - - static int Radix() - { return FLT_RADIX; } // exponent radix - - static int Rounds() - { return FLT_ROUNDS; } // addition rounding (1 = does round) - - }; - -#endif // USING_FLOAT - - -#ifdef USING_DOUBLE - - class FloatingPointPrecision - { - public: - - static int Dig() - { return DBL_DIG; } // number of decimal digits or precision - - static Real Epsilon() - { return DBL_EPSILON; } // smallest number such that 1+Eps!=Eps - - static int Mantissa() - { return DBL_MANT_DIG; } // bits in mantisa - - static Real Maximum() - { return DBL_MAX; } // maximum value - - static int MaximumDecimalExponent() - { return DBL_MAX_10_EXP; } // maximum decimal exponent - - static int MaximumExponent() - { return DBL_MAX_EXP; } // maximum binary exponent - - static Real LnMaximum() - { return (Real)log(Maximum()); } // natural log of maximum - - static Real Minimum() - { - //#ifdef __BCPLUSPLUS__ - // return 2.225074e-308; // minimum positive value - //#else - return DBL_MIN; - //#endif - } - - static int MinimumDecimalExponent() - { return DBL_MIN_10_EXP; } // minimum decimal exponent - - static int MinimumExponent() - { return DBL_MIN_EXP; } // minimum binary exponent - - static Real LnMinimum() - { return (Real)log(Minimum()); } // natural log of minimum - - - static int Radix() - { return FLT_RADIX; } // exponent radix - - static int Rounds() - { return FLT_ROUNDS; } // addition rounding (1 = does round) - - }; - -#endif // USING_DOUBLE - -#else // if there is no float.h - -#ifdef USING_FLOAT - - class FloatingPointPrecision - { - public: - - static Real Epsilon() - { return pow(2.0,(int)(1-FSIGNIF)); } - // smallest number such that 1+Eps!=Eps - - static Real Maximum() - { return MAXFLOAT; } // maximum value - - static Real LnMaximum() - { return (Real)log(Maximum()); } // natural log of maximum - - static Real Minimum() - { return MINFLOAT; } // minimum positive value - - static Real LnMinimum() - { return (Real)log(Minimum()); } // natural log of minimum - - }; - -#endif // USING_FLOAT - - -#ifdef USING_DOUBLE - - class FloatingPointPrecision - { - public: - - static Real Epsilon() - { return pow(2.0,(int)(1-DSIGNIF)); } - // smallest number such that 1+Eps!=Eps - - static Real Maximum() - { return MAXDOUBLE; } // maximum value - - static Real LnMaximum() - { return LN_MAXDOUBLE; } // natural log of maximum - - static Real Minimum() - { return MINDOUBLE; } - - static Real LnMinimum() - { return LN_MINDOUBLE; } // natural log of minimum - }; - -#endif // USING_DOUBLE - -#endif // SystemV - -#endif // _STANDARD_ - -#ifdef use_namespace -} -#endif // use_namespace - - - -#endif // PRECISION_LIB diff --git a/lib/src/mixmod/NEWMAT/rbd.css b/lib/src/mixmod/NEWMAT/rbd.css deleted file mode 100644 index 97f61ca..0000000 --- a/lib/src/mixmod/NEWMAT/rbd.css +++ /dev/null @@ -1,19 +0,0 @@ -/* Style sheet - if you are saving my files, please also save this file as rbd.css */ -h1 { font-family: Arial, Helvetica, sans-serif; font-size: 20pt; color: maroon } -h2 { font-family: Arial, Helvetica, sans-serif; font-size: 16pt; color: maroon } -h3 { font-family: Arial, Helvetica, sans-serif; font-size: 14pt; color: maroon } -h4 { font-family: Arial, Helvetica, sans-serif; font-size: 12pt; color: maroon } -body { font-family: "Times New Roman", Times, serif; background-color: white } -body.gray { font-family: "Times New Roman", Times, serif; background-color: #CCCCCC } -p { font-family: "Times New Roman", Times, serif; margin-top: 8; margin-bottom: 8 } -p.small { font-family: "Times New Roman", Times, serif; font-size: 10pt; margin-top: 8; margin-bottom: 8 } -ul { line-height: 100%; margin-top: 2; margin-bottom: 2 } -li { margin-top: 2; margin-bottom: 2; font-size: 10pt } -tt { font-family: "Courier New", Courier, monospaced; font-size: 10pt } -pre { font-family: "Courier New", Courier, monospaced; font-size: 10pt } -hr { color: maroon } -a:link { color: blue } -a:visited { color: green } -a:active { color: red } -table { font-size: 10pt } -.question { color: navy; } \ No newline at end of file diff --git a/lib/src/mixmod/NEWMAT/readme b/lib/src/mixmod/NEWMAT/readme deleted file mode 100644 index 379e3b7..0000000 --- a/lib/src/mixmod/NEWMAT/readme +++ /dev/null @@ -1,17 +0,0 @@ -ReadMe file for newmat10A - release version - 8 October, 2002 -------------------------------------------------------------- - -This is the release version of newmat10A. - -Documentation is in nm10.htm. - -This library is freeware and may be freely used and distributed. - -To contact the author please email robert@statsresearch.co.nz - - -Version 10A corrects an error on the Kronecker production function and -you can now run Gnu G++ version 3 and Intel for Linux without making -any modifications. - - diff --git a/lib/src/mixmod/NEWMAT/solution.cpp b/lib/src/mixmod/NEWMAT/solution.cpp deleted file mode 100644 index 58164a6..0000000 --- a/lib/src/mixmod/NEWMAT/solution.cpp +++ /dev/null @@ -1,200 +0,0 @@ -//$$ solution.cpp // solve routines - -// Copyright (C) 1994: R B Davies - - -#define WANT_STREAM // include.h will get stream fns -#define WANT_MATH // include.h will get math fns - -#include "include.h" -#include "boolean.h" -#include "myexcept.h" - -#include "solution.h" - -#ifdef use_namespace -namespace RBD_COMMON { -#endif - - - void R1_R1::Set(Real X) - { - if ((!minXinf && X <= minX) || (!maxXinf && X >= maxX)) - Throw(SolutionException("X value out of range")); - x = X; xSet = true; - } - - R1_R1::operator Real() - { - if (!xSet) Throw(SolutionException("Value of X not set")); - Real y = operator()(); - return y; - } - - unsigned long SolutionException::Select; - - SolutionException::SolutionException(const char* a_what) : Exception() - { - Select = Exception::Select; - AddMessage("Error detected by solution package\n"); - AddMessage(a_what); AddMessage("\n"); - if (a_what) Tracer::AddTrace(); - }; - - inline Real square(Real x) { return x*x; } - - void OneDimSolve::LookAt(int V) - { - lim--; - if (!lim) Throw(SolutionException("Does not converge")); - Last = V; - Real yy = function(x[V]) - YY; - Finish = (fabs(yy) <= accY) || (Captured && fabs(x[L]-x[U]) <= accX ); - y[V] = vpol*yy; - } - - void OneDimSolve::HFlip() { hpol=-hpol; State(U,C,L); } - - void OneDimSolve::VFlip() - { vpol = -vpol; y[0] = -y[0]; y[1] = -y[1]; y[2] = -y[2]; } - - void OneDimSolve::Flip() - { - hpol=-hpol; vpol=-vpol; State(U,C,L); - y[0] = -y[0]; y[1] = -y[1]; y[2] = -y[2]; - } - - void OneDimSolve::State(int I, int J, int K) { L=I; C=J; U=K; } - - void OneDimSolve::Linear(int I, int J, int K) - { - x[J] = (x[I]*y[K] - x[K]*y[I])/(y[K] - y[I]); - // cout << "Linear\n"; - } - - void OneDimSolve::Quadratic(int I, int J, int K) - { - // result to overwrite I - Real YJK, YIK, YIJ, XKI, XKJ; - YJK = y[J] - y[K]; YIK = y[I] - y[K]; YIJ = y[I] - y[J]; - XKI = (x[K] - x[I]); - XKJ = (x[K]*y[J] - x[J]*y[K])/YJK; - if ( square(YJK/YIK)>(x[K] - x[J])/XKI || - square(YIJ/YIK)>(x[J] - x[I])/XKI ) - { - x[I] = XKJ; - // cout << "Quadratic - exceptional\n"; - } - else - { - XKI = (x[K]*y[I] - x[I]*y[K])/YIK; - x[I] = (XKJ*y[I] - XKI*y[J])/YIJ; - // cout << "Quadratic - normal\n"; - } - } - - Real OneDimSolve::Solve(Real Y, Real X, Real Dev, int Lim) - { - enum Loop { start, captured1, captured2, binary, finish }; - Tracer et("OneDimSolve::Solve"); - lim=Lim; Captured = false; - if (Dev==0.0) Throw(SolutionException("Dev is zero")); - L=0; C=1; U=2; vpol=1; hpol=1; y[C]=0.0; y[U]=0.0; - if (Dev<0.0) { hpol=-1; Dev = -Dev; } - YY=Y; // target value - x[L] = X; // initial trial value - if (!function.IsValid(X)) - Throw(SolutionException("Starting value is invalid")); - Loop TheLoop = start; - for (;;) - { - switch (TheLoop) - { - case start: - LookAt(L); if (Finish) { TheLoop = finish; break; } - if (y[L]>0.0) VFlip(); // so Y[L] < 0 - - x[U] = X + Dev * hpol; - if (!function.maxXinf && x[U] > function.maxX) - x[U] = (function.maxX + X) / 2.0; - if (!function.minXinf && x[U] < function.minX) - x[U] = (function.minX + X) / 2.0; - - LookAt(U); if (Finish) { TheLoop = finish; break; } - if (y[U] > 0.0) { TheLoop = captured1; Captured = true; break; } - if (y[U] == y[L]) - Throw(SolutionException("Function is flat")); - if (y[U] < y[L]) HFlip(); // Change direction - State(L,U,C); - for (i=0; i<20; i++) - { - // cout << "Searching for crossing point\n"; - // Have L C then crossing point, Y[L] function.maxX) - x[U] = (function.maxX + x[C]) / 2.0; - if (!function.minXinf && x[U] < function.minX) - x[U] = (function.minX + x[C]) / 2.0; - - LookAt(U); if (Finish) { TheLoop = finish; break; } - if (y[U] > 0) { TheLoop = captured2; Captured = true; break; } - if (y[U] < y[C]) - Throw(SolutionException("Function is not monotone")); - Dev *= 2.0; - State(C,U,L); - } - if (TheLoop != start ) break; - Throw(SolutionException("Cannot locate a crossing point")); - - case captured1: - // cout << "Captured - 1\n"; - // We have 2 points L and U with crossing between them - Linear(L,C,U); // linear interpolation - // - result to C - LookAt(C); if (Finish) { TheLoop = finish; break; } - if (y[C] > 0.0) Flip(); // Want y[C] < 0 - if (y[C] < 0.5*y[L]) { State(C,L,U); TheLoop = binary; break; } - - case captured2: - // cout << "Captured - 2\n"; - // We have L,C before crossing, U after crossing - Quadratic(L,C,U); // quad interpolation - // - result to L - State(C,L,U); - if ((x[C] - x[L])*hpol <= 0.0 || (x[C] - x[U])*hpol >= 0.0) - { TheLoop = captured1; break; } - LookAt(C); if (Finish) { TheLoop = finish; break; } - // cout << "Through first stage\n"; - if (y[C] > 0.0) Flip(); - if (y[C] > 0.5*y[L]) { TheLoop = captured2; break; } - else { State(C,L,U); TheLoop = captured1; break; } - - case binary: - // We have L, U around crossing - do binary search - // cout << "Binary\n"; - for (i=3; i; i--) - { - x[C] = 0.5*(x[L]+x[U]); - LookAt(C); if (Finish) { TheLoop = finish; break; } - if (y[C]>0.0) State(L,U,C); else State(C,L,U); - } - if (TheLoop != binary) break; - TheLoop = captured1; break; - - case finish: - return x[Last]; - - } - } - } - - bool R1_R1::IsValid(Real X) - { - Set(X); - return (minXinf || x > minX) && (maxXinf || x < maxX); - } - -#ifdef use_namespace -} -#endif - diff --git a/lib/src/mixmod/NEWMAT/solution.h b/lib/src/mixmod/NEWMAT/solution.h deleted file mode 100644 index db377c2..0000000 --- a/lib/src/mixmod/NEWMAT/solution.h +++ /dev/null @@ -1,94 +0,0 @@ -//$$ solution.h // solve routines - -#include "boolean.h" -#include "myexcept.h" - -#ifdef use_namespace -namespace RBD_COMMON { -#endif - - - // Solve the equation f(x)=y for x where f is a monotone continuous - // function of x - // Essentially Brent s method - - // You need to derive a class from R1_R1 and override "operator()" - // with the function you want to solve. - // Use an object from this class in OneDimSolve - - class R1_R1 - { - // the prototype for a Real function of a Real variable - // you need to derive your function from this one and put in your - // function for operator() at least. You probably also want to set up a - // constructor to put in additional parameter values (e.g. that will not - // vary during a solve) - - protected: - Real x; // Current x value - bool xSet; // true if a value assigned to x - - public: - Real minX, maxX; // range of value x - bool minXinf, maxXinf; // true if these are infinite - R1_R1() : xSet(false), minXinf(true), maxXinf(true) {} - virtual Real operator()() = 0; // function value at current x - // set current x - virtual void Set(Real X); // set x, check OK - Real operator()(Real X) { Set(X); return operator()(); } - // set x, return value - virtual bool IsValid(Real X); - operator Real(); // implicit conversion - }; - - class SolutionException : public Exception - { - public: - static unsigned long Select; - SolutionException(const char* a_what = 0); - }; - - class OneDimSolve - { - R1_R1& function; // reference to the function - Real accX; // accuracy in X direction - Real accY; // accuracy in Y direction - int lim; // maximum number of iterations - - public: - OneDimSolve(R1_R1& f, Real AccY = 0.0001, Real AccX = 0.0) - : function(f), accX(AccX), accY(AccY) {} - // f is an R1_R1 function - Real Solve(Real Y, Real X, Real Dev, int Lim=100); - // Solve for x in Y=f(x) - // X is the initial trial value of x - // X+Dev is the second trial value - // program returns a value of x such that - // |Y-f(x)| <= accY or |f.inv(Y)-x| <= accX - - private: - Real x[3], y[3]; // Trial values of X and Y - int L,C,U,Last; // Locations of trial values - int vpol, hpol; // polarities - Real YY; // target value - int i; - void LookAt(int); // get new value of function - bool Finish; // true if LookAt finds conv. - bool Captured; // true when target surrounded - void VFlip(); - void HFlip(); - void Flip(); - void State(int I, int J, int K); - void Linear(int, int, int); - void Quadratic(int, int, int); - }; - - -#ifdef use_namespace -} -#endif - -// body file: solution.cpp - - - diff --git a/lib/src/mixmod/NEWMAT/sort.cpp b/lib/src/mixmod/NEWMAT/sort.cpp deleted file mode 100644 index b4f1d01..0000000 --- a/lib/src/mixmod/NEWMAT/sort.cpp +++ /dev/null @@ -1,272 +0,0 @@ -//$$ sort.cpp Sorting - -// Copyright (C) 1991,2,3,4: R B Davies - -#define WANT_MATH - -#include "include.h" - -#include "newmatap.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - -#ifdef DO_REPORT -#define REPORT { static ExeCounter ExeCount(__LINE__,13); ++ExeCount; } -#else -#define REPORT {} -#endif - - /******************************** Quick sort ********************************/ - - // Quicksort. - // Essentially the method described in Sedgewick s algorithms in C++ - // My version is still partially recursive, unlike Segewick s, but the - // smallest segment of each split is used in the recursion, so it should - // not overlead the stack. - - // If the process does not seems to be converging an exception is thrown. - - -#define DoSimpleSort 17 // when to switch to insert sort -#define MaxDepth 50 // maximum recursion depth - - static void MyQuickSortDescending(Real* first, Real* last, int depth); - static void InsertionSortDescending(Real* first, const int length, - int guard); - static Real SortThreeDescending(Real* a, Real* b, Real* c); - - static void MyQuickSortAscending(Real* first, Real* last, int depth); - static void InsertionSortAscending(Real* first, const int length, - int guard); - - - void SortDescending(GeneralMatrix& GM) - { - REPORT - Tracer et("QuickSortDescending"); - - Real* data = GM.Store(); int max = GM.Storage(); - - if (max > DoSimpleSort) MyQuickSortDescending(data, data + max - 1, 0); - InsertionSortDescending(data, max, DoSimpleSort); - - } - - static Real SortThreeDescending(Real* a, Real* b, Real* c) - { - // sort *a, *b, *c; return *b; optimise for already sorted - if (*a >= *b) - { - if (*b >= *c) { REPORT return *b; } - else if (*a >= *c) { REPORT Real x = *c; *c = *b; *b = x; return x; } - else { REPORT Real x = *a; *a = *c; *c = *b; *b = x; return x; } - } - else if (*c >= *b) { REPORT Real x = *c; *c = *a; *a = x; return *b; } - else if (*a >= *c) { REPORT Real x = *a; *a = *b; *b = x; return x; } - else { REPORT Real x = *c; *c = *a; *a = *b; *b = x; return x; } - } - - static void InsertionSortDescending(Real* first, const int length, - int guard) - // guard gives the length of the sequence to scan to find first - // element (eg = length) - { - REPORT - if (length <= 1) return; - - // scan for first element - Real* f = first; Real v = *f; Real* h = f; - if (guard > length) { REPORT guard = length; } - int i = guard - 1; - while (i--) if (v < *(++f)) { v = *f; h = f; } - *h = *first; *first = v; - - // do the sort - i = length - 1; f = first; - while (i--) - { - Real* g = f++; h = f; v = *h; - while (*g < v) *h-- = *g--; - *h = v; - } - } - - static void MyQuickSortDescending(Real* first, Real* last, int depth) - { - REPORT - for (;;) - { - const int length = last - first + 1; - if (length < DoSimpleSort) { REPORT return; } - if (depth++ > MaxDepth) - Throw(ConvergenceException("QuickSortDescending fails: ")); - Real* centre = first + length/2; - const Real test = SortThreeDescending(first, centre, last); - Real* f = first; Real* l = last; - for (;;) - { - while (*(++f) > test) {} - while (*(--l) < test) {} - if (l <= f) break; - const Real temp = *f; *f = *l; *l = temp; - } - if (f > centre) - { REPORT MyQuickSortDescending(l+1, last, depth); last = f-1; } - else { REPORT MyQuickSortDescending(first, f-1, depth); first = l+1; } - } - } - - void SortAscending(GeneralMatrix& GM) - { - REPORT - Tracer et("QuickSortAscending"); - - Real* data = GM.Store(); int max = GM.Storage(); - - if (max > DoSimpleSort) MyQuickSortAscending(data, data + max - 1, 0); - InsertionSortAscending(data, max, DoSimpleSort); - - } - - static void InsertionSortAscending(Real* first, const int length, - int guard) - // guard gives the length of the sequence to scan to find first - // element (eg guard = length) - { - REPORT - if (length <= 1) return; - - // scan for first element - Real* f = first; Real v = *f; Real* h = f; - if (guard > length) { REPORT guard = length; } - int i = guard - 1; - while (i--) if (v > *(++f)) { v = *f; h = f; } - *h = *first; *first = v; - - // do the sort - i = length - 1; f = first; - while (i--) - { - Real* g = f++; h = f; v = *h; - while (*g > v) *h-- = *g--; - *h = v; - } - } - static void MyQuickSortAscending(Real* first, Real* last, int depth) - { - REPORT - for (;;) - { - const int length = last - first + 1; - if (length < DoSimpleSort) { REPORT return; } - if (depth++ > MaxDepth) - Throw(ConvergenceException("QuickSortAscending fails: ")); - Real* centre = first + length/2; - const Real test = SortThreeDescending(last, centre, first); - Real* f = first; Real* l = last; - for (;;) - { - while (*(++f) < test) {} - while (*(--l) > test) {} - if (l <= f) break; - const Real temp = *f; *f = *l; *l = temp; - } - if (f > centre) - { REPORT MyQuickSortAscending(l+1, last, depth); last = f-1; } - else { REPORT MyQuickSortAscending(first, f-1, depth); first = l+1; } - } - } - - //********* sort diagonal matrix & rearrange matrix columns **************** - - // used by SVD - - // these are for sorting singular values - should be updated with faster - // sorts that handle exchange of columns better - // however time is probably not significant compared with SVD time - - void SortSV(DiagonalMatrix& D, Matrix& U, bool ascending) - { - REPORT - Tracer trace("SortSV_DU"); - int m = U.Nrows(); int n = U.Ncols(); - if (n != D.Nrows()) Throw(IncompatibleDimensionsException(D,U)); - Real* u = U.Store(); - for (int i=0; i p) { k = j; p = D.element(j); } } - } - if (k != i) - { - D.element(k) = D.element(i); D.element(i) = p; int j = m; - Real* uji = u + i; Real* ujk = u + k; - if (j) for(;;) - { - p = *uji; *uji = *ujk; *ujk = p; - if (!(--j)) break; - uji += n; ujk += n; - } - } - } - } - - void SortSV(DiagonalMatrix& D, Matrix& U, Matrix& V, bool ascending) - { - REPORT - Tracer trace("SortSV_DUV"); - int mu = U.Nrows(); int mv = V.Nrows(); int n = D.Nrows(); - if (n != U.Ncols()) Throw(IncompatibleDimensionsException(D,U)); - if (n != V.Ncols()) Throw(IncompatibleDimensionsException(D,V)); - Real* u = U.Store(); Real* v = V.Store(); - for (int i=0; i p) { k = j; p = D.element(j); } } - } - if (k != i) - { - D.element(k) = D.element(i); D.element(i) = p; - Real* uji = u + i; Real* ujk = u + k; - Real* vji = v + i; Real* vjk = v + k; - int j = mu; - if (j) for(;;) - { - p = *uji; *uji = *ujk; *ujk = p; if (!(--j)) break; - uji += n; ujk += n; - } - j = mv; - if (j) for(;;) - { - p = *vji; *vji = *vjk; *vjk = p; if (!(--j)) break; - vji += n; vjk += n; - } - } - } - } - - - - -#ifdef use_namespace -} -#endif - diff --git a/lib/src/mixmod/NEWMAT/submat.cpp b/lib/src/mixmod/NEWMAT/submat.cpp deleted file mode 100644 index 89c01c2..0000000 --- a/lib/src/mixmod/NEWMAT/submat.cpp +++ /dev/null @@ -1,429 +0,0 @@ -//$$ submat.cpp submatrices - -// Copyright (C) 1991,2,3,4: R B Davies - -#include "include.h" - -#include "newmat.h" -#include "newmatrc.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - -#ifdef DO_REPORT -#define REPORT { static ExeCounter ExeCount(__LINE__,11); ++ExeCount; } -#else -#define REPORT {} -#endif - - - /****************************** submatrices *********************************/ - -#ifdef TEMPS_DESTROYED_QUICKLY - GetSubMatrix& BaseMatrix::SubMatrix(int first_row, int last_row, int first_col, - int last_col) const -#else - GetSubMatrix BaseMatrix::SubMatrix(int first_row, int last_row, int first_col, - int last_col) const -#endif - { - REPORT - Tracer tr("SubMatrix"); - int a = first_row - 1; int b = last_row - first_row + 1; - int c = first_col - 1; int d = last_col - first_col + 1; - if (a<0 || b<0 || c<0 || d<0) Throw(SubMatrixDimensionException()); - // allow zero rows or columns -#ifdef TEMPS_DESTROYED_QUICKLY - GetSubMatrix* x = new GetSubMatrix(this, a, b, c, d, false); - MatrixErrorNoSpace(x); - return *x; -#else - return GetSubMatrix(this, a, b, c, d, false); -#endif - } - -#ifdef TEMPS_DESTROYED_QUICKLY - GetSubMatrix& BaseMatrix::SymSubMatrix(int first_row, int last_row) const -#else - GetSubMatrix BaseMatrix::SymSubMatrix(int first_row, int last_row) const -#endif - { - REPORT - Tracer tr("SubMatrix(symmetric)"); - int a = first_row - 1; int b = last_row - first_row + 1; - if (a<0 || b<0) Throw(SubMatrixDimensionException()); - // allow zero rows or columns -#ifdef TEMPS_DESTROYED_QUICKLY - GetSubMatrix* x = new GetSubMatrix(this, a, b, a, b, true); - MatrixErrorNoSpace(x); - return *x; -#else - return GetSubMatrix( this, a, b, a, b, true); -#endif - } - -#ifdef TEMPS_DESTROYED_QUICKLY - GetSubMatrix& BaseMatrix::Row(int first_row) const -#else - GetSubMatrix BaseMatrix::Row(int first_row) const -#endif - { - REPORT - Tracer tr("SubMatrix(row)"); - int a = first_row - 1; - if (a<0) Throw(SubMatrixDimensionException()); -#ifdef TEMPS_DESTROYED_QUICKLY - GetSubMatrix* x = new GetSubMatrix(this, a, 1, 0, -1, false); - MatrixErrorNoSpace(x); - return *x; -#else - return GetSubMatrix(this, a, 1, 0, -1, false); -#endif - } - -#ifdef TEMPS_DESTROYED_QUICKLY - GetSubMatrix& BaseMatrix::Rows(int first_row, int last_row) const -#else - GetSubMatrix BaseMatrix::Rows(int first_row, int last_row) const -#endif - { - REPORT - Tracer tr("SubMatrix(rows)"); - int a = first_row - 1; int b = last_row - first_row + 1; - if (a<0 || b<0) Throw(SubMatrixDimensionException()); - // allow zero rows or columns -#ifdef TEMPS_DESTROYED_QUICKLY - GetSubMatrix* x = new GetSubMatrix(this, a, b, 0, -1, false); - MatrixErrorNoSpace(x); - return *x; -#else - return GetSubMatrix(this, a, b, 0, -1, false); -#endif - } - -#ifdef TEMPS_DESTROYED_QUICKLY - GetSubMatrix& BaseMatrix::Column(int first_col) const -#else - GetSubMatrix BaseMatrix::Column(int first_col) const -#endif - { - REPORT - Tracer tr("SubMatrix(column)"); - int c = first_col - 1; - if (c<0) Throw(SubMatrixDimensionException()); -#ifdef TEMPS_DESTROYED_QUICKLY - GetSubMatrix* x = new GetSubMatrix(this, 0, -1, c, 1, false); - MatrixErrorNoSpace(x); - return *x; -#else - return GetSubMatrix(this, 0, -1, c, 1, false); -#endif - } - -#ifdef TEMPS_DESTROYED_QUICKLY - GetSubMatrix& BaseMatrix::Columns(int first_col, int last_col) const -#else - GetSubMatrix BaseMatrix::Columns(int first_col, int last_col) const -#endif - { - REPORT - Tracer tr("SubMatrix(columns)"); - int c = first_col - 1; int d = last_col - first_col + 1; - if (c<0 || d<0) Throw(SubMatrixDimensionException()); - // allow zero rows or columns -#ifdef TEMPS_DESTROYED_QUICKLY - GetSubMatrix* x = new GetSubMatrix(this, 0, -1, c, d, false); - MatrixErrorNoSpace(x); - return *x; -#else - return GetSubMatrix(this, 0, -1, c, d, false); -#endif - } - - void GetSubMatrix::SetUpLHS() - { - REPORT - Tracer tr("SubMatrix(LHS)"); - const BaseMatrix* bm1 = bm; - GeneralMatrix* gm1 = ((BaseMatrix*&)bm)->Evaluate(); - if ((BaseMatrix*)gm1!=bm1) - Throw(ProgramException("Invalid LHS")); - if (row_number < 0) row_number = gm1->Nrows(); - if (col_number < 0) col_number = gm1->Ncols(); - if (row_skip+row_number > gm1->Nrows() - || col_skip+col_number > gm1->Ncols()) - Throw(SubMatrixDimensionException()); - } - - void GetSubMatrix::operator<<(const BaseMatrix& bmx) - { - REPORT - Tracer tr("SubMatrix(<<)"); GeneralMatrix* gmx = 0; - Try - { - SetUpLHS(); gmx = ((BaseMatrix&)bmx).Evaluate(); - if (row_number != gmx->Nrows() || col_number != gmx->Ncols()) - Throw(IncompatibleDimensionsException()); - MatrixRow mrx(gmx, LoadOnEntry); - MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); - // do need LoadOnEntry - MatrixRowCol sub; int i = row_number; - while (i--) - { - mr.SubRowCol(sub, col_skip, col_number); // put values in sub - sub.Copy(mrx); mr.Next(); mrx.Next(); - } - gmx->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - } - - CatchAll - { - if (gmx) gmx->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - ReThrow; - } - } - - void GetSubMatrix::operator=(const BaseMatrix& bmx) - { - REPORT - Tracer tr("SubMatrix(=)"); GeneralMatrix* gmx = 0; - // MatrixConversionCheck mcc; // Check for loss of info - Try - { - SetUpLHS(); gmx = ((BaseMatrix&)bmx).Evaluate(); - if (row_number != gmx->Nrows() || col_number != gmx->Ncols()) - Throw(IncompatibleDimensionsException()); - LoadAndStoreFlag lasf = - ( row_skip == col_skip - && gm->Type().IsSymmetric() - && gmx->Type().IsSymmetric() ) - ? LoadOnEntry+DirectPart - : LoadOnEntry; - MatrixRow mrx(gmx, lasf); - MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); - // do need LoadOnEntry - MatrixRowCol sub; int i = row_number; - while (i--) - { - mr.SubRowCol(sub, col_skip, col_number); // put values in sub - sub.CopyCheck(mrx); mr.Next(); mrx.Next(); - } - gmx->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - } - - CatchAll - { - if (gmx) gmx->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - ReThrow; - } - } - - void GetSubMatrix::operator<<(const Real* r) - { - REPORT - Tracer tr("SubMatrix(< gm->Nrows() || col_skip+col_number > gm->Ncols()) - Throw(SubMatrixDimensionException()); - MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); - // do need LoadOnEntry - MatrixRowCol sub; int i = row_number; - while (i--) - { - mr.SubRowCol(sub, col_skip, col_number); // put values in sub - sub.Copy(r); mr.Next(); - } -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - } - - void GetSubMatrix::operator=(Real r) - { - REPORT - Tracer tr("SubMatrix(=Real)"); - SetUpLHS(); - MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); - // do need LoadOnEntry - MatrixRowCol sub; int i = row_number; - while (i--) - { - mr.SubRowCol(sub, col_skip, col_number); // put values in sub - sub.Copy(r); mr.Next(); - } -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - } - - void GetSubMatrix::Inject(const GeneralMatrix& gmx) - { - REPORT - Tracer tr("SubMatrix(inject)"); - SetUpLHS(); - if (row_number != gmx.Nrows() || col_number != gmx.Ncols()) - Throw(IncompatibleDimensionsException()); - MatrixRow mrx((GeneralMatrix*)(&gmx), LoadOnEntry); - MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); - // do need LoadOnEntry - MatrixRowCol sub; int i = row_number; - while (i--) - { - mr.SubRowCol(sub, col_skip, col_number); // put values in sub - sub.Inject(mrx); mr.Next(); mrx.Next(); - } -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - } - - void GetSubMatrix::operator+=(const BaseMatrix& bmx) - { - REPORT - Tracer tr("SubMatrix(+=)"); GeneralMatrix* gmx = 0; - // MatrixConversionCheck mcc; // Check for loss of info - Try - { - SetUpLHS(); gmx = ((BaseMatrix&)bmx).Evaluate(); - if (row_number != gmx->Nrows() || col_number != gmx->Ncols()) - Throw(IncompatibleDimensionsException()); - MatrixRow mrx(gmx, LoadOnEntry); - MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); - // do need LoadOnEntry - MatrixRowCol sub; int i = row_number; - while (i--) - { - mr.SubRowCol(sub, col_skip, col_number); // put values in sub - sub.Check(mrx); // check for loss of info - sub.Add(mrx); mr.Next(); mrx.Next(); - } - gmx->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - } - - CatchAll - { - if (gmx) gmx->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - ReThrow; - } - } - - void GetSubMatrix::operator-=(const BaseMatrix& bmx) - { - REPORT - Tracer tr("SubMatrix(-=)"); GeneralMatrix* gmx = 0; - // MatrixConversionCheck mcc; // Check for loss of info - Try - { - SetUpLHS(); gmx = ((BaseMatrix&)bmx).Evaluate(); - if (row_number != gmx->Nrows() || col_number != gmx->Ncols()) - Throw(IncompatibleDimensionsException()); - MatrixRow mrx(gmx, LoadOnEntry); - MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); - // do need LoadOnEntry - MatrixRowCol sub; int i = row_number; - while (i--) - { - mr.SubRowCol(sub, col_skip, col_number); // put values in sub - sub.Check(mrx); // check for loss of info - sub.Sub(mrx); mr.Next(); mrx.Next(); - } - gmx->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - } - - CatchAll - { - if (gmx) gmx->tDelete(); -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - ReThrow; - } - } - - void GetSubMatrix::operator+=(Real r) - { - REPORT - Tracer tr("SubMatrix(+= or -= Real)"); - // MatrixConversionCheck mcc; // Check for loss of info - Try - { - SetUpLHS(); - MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); - // do need LoadOnEntry - MatrixRowCol sub; int i = row_number; - while (i--) - { - mr.SubRowCol(sub, col_skip, col_number); // put values in sub - sub.Check(); // check for loss of info - sub.Add(r); mr.Next(); - } -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - } - - CatchAll - { -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - ReThrow; - } - } - - void GetSubMatrix::operator*=(Real r) - { - REPORT - Tracer tr("SubMatrix(*= or /= Real)"); - // MatrixConversionCheck mcc; // Check for loss of info - Try - { - SetUpLHS(); - MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); - // do need LoadOnEntry - MatrixRowCol sub; int i = row_number; - while (i--) - { - mr.SubRowCol(sub, col_skip, col_number); // put values in sub - sub.Multiply(r); mr.Next(); - } -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - } - - CatchAll - { -#ifdef TEMPS_DESTROYED_QUICKLY - delete this; -#endif - ReThrow; - } - } - -#ifdef use_namespace -} -#endif - diff --git a/lib/src/mixmod/NEWMAT/svd.cpp b/lib/src/mixmod/NEWMAT/svd.cpp deleted file mode 100644 index 0af4897..0000000 --- a/lib/src/mixmod/NEWMAT/svd.cpp +++ /dev/null @@ -1,227 +0,0 @@ -//$$svd.cpp singular value decomposition - -// Copyright (C) 1991,2,3,4,5: R B Davies -// Updated 17 July, 1995 - -#define WANT_MATH - -#include "include.h" -#include "newmatap.h" -#include "newmatrm.h" -#include "precisio.h" - -#ifdef use_namespace -namespace NEWMAT { -#endif - -#ifdef DO_REPORT -#define REPORT { static ExeCounter ExeCount(__LINE__,15); ++ExeCount; } -#else -#define REPORT {} -#endif - - - static Real pythag(Real f, Real g, Real& c, Real& s) - // return z=sqrt(f*f+g*g), c=f/z, s=g/z - // set c=1,s=0 if z==0 - // avoid floating point overflow or divide by zero - { - if (f==0 && g==0) { c=1.0; s=0.0; return 0.0; } - Real af = f>=0 ? f : -f; - Real ag = g>=0 ? g : -g; - if (ag= no. Cols", A)); - if (withV && &U == &V) - Throw(ProgramException("Need different matrices for U and V", U, V)); - U = A; Real g = 0.0; Real f,h; Real x = 0.0; int i; - RowVector E(n); RectMatrixRow EI(E,0); Q.ReSize(n); - RectMatrixCol UCI(U,0); RectMatrixRow URI(U,0,1,n-1); - - if (n) for (i=0;;) - { - EI.First() = g; Real ei = g; EI.Right(); Real s = UCI.SumSquare(); - if (s=0; i--) - { - VCI.Left(); - if (g!=0.0) - { - VCI.Divide(URI, URI.First()*g); int j = n-i; - RectMatrixCol VCJ = VCI; - while (--j) { VCJ.Right(); VCJ.AddScaled( VCI, (URI*VCJ) ); } - } - VCI.Zero(); VCI.Up(); VCI.First() = 1.0; g=E.element(i); - if (i==0) break; - URI.UpDiag(); - } - } - - if (withU) - { - REPORT - for (i=n-1; i>=0; i--) - { - g = Q.element(i); URI.Reset(U,i,i+1,n-i-1); URI.Zero(); - if (g!=0.0) - { - h=UCI.First()*g; int j=n-i; RectMatrixCol UCJ = UCI; - while (--j) - { - UCJ.Right(); UCI.Down(); UCJ.Down(); Real s = UCI*UCJ; - UCI.Up(); UCJ.Up(); UCJ.AddScaled(UCI,s/h); - } - UCI.Divide(g); - } - else UCI.Zero(); - UCI.First() += 1.0; - if (i==0) break; - UCI.UpDiag(); - } - } - - eps *= x; - for (int k=n-1; k>=0; k--) - { - Real z = -FloatingPointPrecision::Maximum(); // to keep Gnu happy - Real y; int limit = 50; int l = 0; - while (limit--) - { - Real c, s; int i; int l1=k; bool tfc=false; - for (l=k; l>=0; l--) - { - // if (fabs(E.element(l))<=eps) goto test_f_convergence; - if (fabs(E.element(l))<=eps) { REPORT tfc=true; break; } - if (fabs(Q.element(l-1))<=eps) { REPORT l1=l; break; } - REPORT - } - if (!tfc) - { - REPORT - l=l1; l1=l-1; s = -1.0; c = 0.0; - for (i=l; i<=k; i++) - { - f = - s * E.element(i); E.element(i) *= c; - // if (fabs(f)<=eps) goto test_f_convergence; - if (fabs(f)<=eps) { REPORT break; } - g = Q.element(i); h = pythag(g,f,c,s); Q.element(i) = h; - if (withU) - { - REPORT - RectMatrixCol UCI(U,i); RectMatrixCol UCJ(U,l1); - ComplexScale(UCJ, UCI, c, s); - } - } - } - // test_f_convergence: z = Q.element(k); if (l==k) goto convergence; - z = Q.element(k); if (l==k) { REPORT break; } - - x = Q.element(l); y = Q.element(k-1); - g = E.element(k-1); h = E.element(k); - f = ((y-z)*(y+z) + (g-h)*(g+h)) / (2*h*y); - if (f>1) { REPORT g = f * sqrt(1 + square(1/f)); } - else if (f<-1) { REPORT g = -f * sqrt(1 + square(1/f)); } - else { REPORT g = sqrt(f*f + 1); } - { REPORT f = ((x-z)*(x+z) + h*(y / ((f<0.0) ? f-g : f+g)-h)) / x; } - - c = 1.0; s = 1.0; - for (i=l+1; i<=k; i++) - { - g = E.element(i); y = Q.element(i); h = s*g; g *= c; - z = pythag(f,h,c,s); E.element(i-1) = z; - f = x*c + g*s; g = -x*s + g*c; h = y*s; y *= c; - if (withV) - { - REPORT - RectMatrixCol VCI(V,i); RectMatrixCol VCJ(V,i-1); - ComplexScale(VCI, VCJ, c, s); - } - z = pythag(f,h,c,s); Q.element(i-1) = z; - f = c*g + s*y; x = -s*g + c*y; - if (withU) - { - REPORT - RectMatrixCol UCI(U,i); RectMatrixCol UCJ(U,i-1); - ComplexScale(UCI, UCJ, c, s); - } - } - E.element(l) = 0.0; E.element(k) = f; Q.element(k) = x; - } - if (l!=k) { Throw(ConvergenceException(A)); } - // convergence: - if (z < 0.0) - { - REPORT - Q.element(k) = -z; - if (withV) { RectMatrixCol VCI(V,k); VCI.Negate(); } - } - } - if (withU & withV) SortSV(Q, U, V); - else if (withU) SortSV(Q, U); - else if (withV) SortSV(Q, V); - else SortDescending(Q); - } - - void SVD(const Matrix& A, DiagonalMatrix& D) - { REPORT Matrix U; SVD(A, D, U, U, false, false); } - - - -#ifdef use_namespace -} -#endif - diff --git a/lib/src/otmixmod/MixtureClassifierFactory.hxx b/lib/src/otmixmod/MixtureClassifierFactory.hxx deleted file mode 100644 index 3dc95a0..0000000 --- a/lib/src/otmixmod/MixtureClassifierFactory.hxx +++ /dev/null @@ -1,67 +0,0 @@ -/** - * @brief Top-level class for mixture factory using MixMod. - * - * - * Copyright 2005-2018 Airbus-EDF-IMACS-Phimeca - * - * OTMixmod is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OTMixmod 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OTMixmod. If not, see . - * - */ -#ifndef OTMIXMOD_MIXTURECLASSIFIERFACTORY_HXX -#define OTMIXMOD_MIXTURECLASSIFIERFACTORY_HXX - -#include -#include - -#include "MixtureFactory.hxx" - -namespace OTMIXMOD -{ - -/** - * @class MixtureClassifierFactory - */ -class MixtureClassifierFactory : public OT::Object -{ - CLASSNAME -public: - - /** Default constructor */ - MixtureClassifierFactory(); - - /** Parameters constructor */ - MixtureClassifierFactory(const MixtureFactory & mixtureFactory); - - /** Virtual constructor */ - virtual MixtureClassifierFactory * clone() const; - - /** Build a classifier from a sample using the mixture factory */ - OT::MixtureClassifier build(const OT::Sample & sample) const; - - /** Mixture Factory accessors */ - MixtureFactory getMixtureFactory() const; - void setMixtureFactory(const MixtureFactory & mixtureFactory); - -private: - - /** The underlying mixture factory */ - MixtureFactory mixtureFactory_; - -}; /* class MixtureClassifierFactory */ - - -} // namespace OTMIXMOD - -#endif /* OTMIXMOD_MIXTURECLASSIFIERFACTORY_HXX */ - diff --git a/lib/src/otmixmod/MixtureFactory.hxx b/lib/src/otmixmod/MixtureFactory.hxx index c097782..e1a91b7 100644 --- a/lib/src/otmixmod/MixtureFactory.hxx +++ b/lib/src/otmixmod/MixtureFactory.hxx @@ -78,14 +78,15 @@ public: const OT::UnsignedInteger nbClusters); /** Mixmod PRNG state accessor */ - void setState(const OT::UnsignedInteger yState, - const OT::UnsignedInteger zState); + void setSeed(const OT::SignedInteger seed); private: /** The main parameter set of the factory */ - OT::UnsignedInteger atomsNumber_; + OT::UnsignedInteger atomsNumber_ = 0; OT::String covarianceModel_; + OT::SignedInteger seed_ = 0; + /** \todo Later : * MixModAlgorithm mixmodAlgorithm_; */ diff --git a/lib/test/t_MixtureFactory_expert.expout b/lib/test/t_MixtureFactory_expert.expout index c630e67..55057fa 100644 --- a/lib/test/t_MixtureFactory_expert.expout +++ b/lib/test/t_MixtureFactory_expert.expout @@ -39,70 +39,70 @@ Build the clusters Build the local experts Build the expert mixture Value at -1=-1.81904 -Value at 0=2.00012 -Value at 1=1.08026 +Value at 0=2.00064 +Value at 1=1.07945 Validation expert input dimension=1 validation dimension=1 -k=5 error=0.000114676 -5 cluster(s) done, best=5 error=0.000114676 +k=5 error=3.8492e-05 +5 cluster(s) done, best=5 error=3.8492e-05 Try with 6 cluster(s) Build the clusters Build the local experts Build the expert mixture Value at -1=-1.81904 -Value at 0=2.00011 -Value at 1=1.08026 +Value at 0=2.00006 +Value at 1=1.07945 Validation expert input dimension=1 validation dimension=1 -k=6 error=3.47744e-05 -6 cluster(s) done, best=6 error=3.47744e-05 +k=6 error=3.60806e-05 +6 cluster(s) done, best=6 error=3.60806e-05 Try with 7 cluster(s) Build the clusters Build the local experts Build the expert mixture -Value at -1=-1.81798 +Value at -1=-1.81904 Value at 0=2.00012 Value at 1=1.08026 Validation expert input dimension=1 validation dimension=1 -k=7 error=8.2664e-06 -7 cluster(s) done, best=7 error=8.2664e-06 +k=7 error=3.23765e-05 +7 cluster(s) done, best=7 error=3.23765e-05 Try with 8 cluster(s) Build the clusters Build the local experts Build the expert mixture Value at -1=-1.81798 -Value at 0=2.00011 +Value at 0=2.00012 Value at 1=1.08026 Validation expert input dimension=1 validation dimension=1 -k=8 error=1.89644e-06 -8 cluster(s) done, best=8 error=1.89644e-06 +k=8 error=9.66844e-06 +8 cluster(s) done, best=8 error=9.66844e-06 Try with 9 cluster(s) Build the clusters Build the local experts Build the expert mixture Value at -1=-1.81798 -Value at 0=2.00008 -Value at 1=1.08031 +Value at 0=2.00005 +Value at 1=1.08047 Validation expert input dimension=1 validation dimension=1 -k=9 error=8.89406e-06 -9 cluster(s) done, best=8 error=1.89644e-06 +k=9 error=8.1529e-06 +9 cluster(s) done, best=9 error=8.1529e-06 Try with 10 cluster(s) Build the clusters Build the local experts Build the expert mixture Value at -1=-1.81798 -Value at 0=2.00006 -Value at 1=1.08047 +Value at 0=2.00012 +Value at 1=1.08026 Validation expert input dimension=1 validation dimension=1 -k=10 error=9.54857e-06 -10 cluster(s) done, best=8 error=1.89644e-06 +k=10 error=6.74044e-07 +10 cluster(s) done, best=10 error=6.74044e-07 diff --git a/lib/test/t_MixtureFactory_std.expout b/lib/test/t_MixtureFactory_std.expout index 10d0dae..4e564c9 100644 --- a/lib/test/t_MixtureFactory_std.expout +++ b/lib/test/t_MixtureFactory_std.expout @@ -1,9 +1,9 @@ -nb clusters=3 +nb clusters=1 point=class=Point name=Unnamed dimension=2 values=[-1.66667,-1.66667] reference pdf=0.0345418 reference cdf=0.456312 reference quantile(0.75)=class=Point name=Unnamed dimension=2 values=[2.06331,2.06331] -estimated pdf=0.0348634 -estimated cdf=0.448425 -estimated quantile(0.75)=class=Point name=Unnamed dimension=2 values=[2.03074,2.1049] +estimated pdf=0.0314941 +estimated cdf=0.412686 +estimated quantile(0.75)=class=Point name=Unnamed dimension=2 values=[1.03894,1.10747] done diff --git a/python/src/CMakeLists.txt b/python/src/CMakeLists.txt index 3837aca..dfe6364 100644 --- a/python/src/CMakeLists.txt +++ b/python/src/CMakeLists.txt @@ -77,8 +77,7 @@ endmacro () ot_add_python_module ( ${PACKAGE_NAME} ${PACKAGE_NAME}_module.i - MixtureFactory.i - MixtureClassifierFactory.i + MixtureFactory.i MixtureFactory_doc.i.in ) diff --git a/python/src/MixtureClassifierFactory.i b/python/src/MixtureClassifierFactory.i deleted file mode 100644 index 365d6fc..0000000 --- a/python/src/MixtureClassifierFactory.i +++ /dev/null @@ -1,9 +0,0 @@ -// SWIG file MixtureClassifierFactory.i - -%{ -#include "otmixmod/MixtureClassifierFactory.hxx" -%} - -%include otmixmod/MixtureClassifierFactory.hxx -namespace OTMIXMOD { %extend MixtureClassifierFactory { MixtureClassifierFactory(const MixtureClassifierFactory & other) { return new OTMIXMOD::MixtureClassifierFactory(other); } }} - diff --git a/python/src/MixtureFactory.i b/python/src/MixtureFactory.i index 8025dd2..5ee5d6d 100644 --- a/python/src/MixtureFactory.i +++ b/python/src/MixtureFactory.i @@ -13,8 +13,9 @@ OT::Implementation OTMIXMOD::MixtureFactory::build(const OT::Sample & sample, OT #include "otmixmod/MixtureFactory.hxx" %} -%template(SampleCollection) OT::Collection; +%include MixtureFactory_doc.i + +%copyctor OTMIXMOD::MixtureFactory; %include otmixmod/MixtureFactory.hxx -namespace OTMIXMOD { %extend MixtureFactory { MixtureFactory(const MixtureFactory & other) { return new OTMIXMOD::MixtureFactory(other); } }} diff --git a/python/src/MixtureFactory_doc.i.in b/python/src/MixtureFactory_doc.i.in new file mode 100644 index 0000000..73a0f69 --- /dev/null +++ b/python/src/MixtureFactory_doc.i.in @@ -0,0 +1,20 @@ +%feature("docstring") OTMIXMOD::MixtureFactory +"Mixture inference." + +// ---------------------------------------------------------------------------- + +%feature("docstring") OTMIXMOD::MixtureFactory::buildAsMixture +"Mixture inference." + +// ---------------------------------------------------------------------------- + +%feature("docstring") OTMIXMOD::MixtureFactory::setSeed +"Mixmod RNG seed accessor + +Parameters +---------- +seed : int + Seed used to initialize the Mixmod RNG seed before the learning step. + A negative seed will randomly initialize the RNG. + The default value is 0. +" \ No newline at end of file diff --git a/python/src/otmixmod_module.i b/python/src/otmixmod_module.i index 26197e8..a817625 100644 --- a/python/src/otmixmod_module.i +++ b/python/src/otmixmod_module.i @@ -19,4 +19,3 @@ // The new classes %include MixtureFactory.i -%include MixtureClassifierFactory.i diff --git a/python/test/t_MixtureFactory_expert.expout b/python/test/t_MixtureFactory_expert.expout index f774aa9..15be314 100755 --- a/python/test/t_MixtureFactory_expert.expout +++ b/python/test/t_MixtureFactory_expert.expout @@ -254,13 +254,13 @@ Expert 3 Expert 4 Build the expert mixture Value at -1=-1.819036 -Value at 0=2.000122 -Value at 1=1.080262 +Value at 0=2.000642 +Value at 1=1.079446 Validation expert input dimension= 1 validation dimension= 1 -k= 5 error=1.1468e-04 -5 cluster(s) done, best= 5 error=1.1468e-04 +k= 5 error=3.8492e-05 +5 cluster(s) done, best= 5 error=3.8492e-05 Try with 6 cluster(s) Build the clusters Build the local experts @@ -272,13 +272,13 @@ Expert 4 Expert 5 Build the expert mixture Value at -1=-1.819036 -Value at 0=2.000109 -Value at 1=1.080262 +Value at 0=2.000058 +Value at 1=1.079446 Validation expert input dimension= 1 validation dimension= 1 -k= 6 error=3.4774e-05 -6 cluster(s) done, best= 6 error=3.4774e-05 +k= 6 error=3.6081e-05 +6 cluster(s) done, best= 6 error=3.6081e-05 Try with 7 cluster(s) Build the clusters Build the local experts @@ -290,14 +290,14 @@ Expert 4 Expert 5 Expert 6 Build the expert mixture -Value at -1=-1.817981 +Value at -1=-1.819036 Value at 0=2.000122 Value at 1=1.080262 Validation expert input dimension= 1 validation dimension= 1 -k= 7 error=8.2664e-06 -7 cluster(s) done, best= 7 error=8.2664e-06 +k= 7 error=3.2377e-05 +7 cluster(s) done, best= 7 error=3.2377e-05 Try with 8 cluster(s) Build the clusters Build the local experts @@ -311,13 +311,13 @@ Expert 6 Expert 7 Build the expert mixture Value at -1=-1.817981 -Value at 0=2.000109 +Value at 0=2.000122 Value at 1=1.080262 Validation expert input dimension= 1 validation dimension= 1 -k= 8 error=1.8964e-06 -8 cluster(s) done, best= 8 error=1.8964e-06 +k= 8 error=9.6684e-06 +8 cluster(s) done, best= 8 error=9.6684e-06 Try with 9 cluster(s) Build the clusters Build the local experts @@ -332,13 +332,13 @@ Expert 7 Expert 8 Build the expert mixture Value at -1=-1.817981 -Value at 0=2.000076 -Value at 1=1.080305 +Value at 0=2.000047 +Value at 1=1.080466 Validation expert input dimension= 1 validation dimension= 1 -k= 9 error=8.8941e-06 -9 cluster(s) done, best= 8 error=1.8964e-06 +k= 9 error=8.1529e-06 +9 cluster(s) done, best= 9 error=8.1529e-06 Try with 10 cluster(s) Build the clusters Build the local experts @@ -354,10 +354,10 @@ Expert 8 Expert 9 Build the expert mixture Value at -1=-1.817981 -Value at 0=2.000058 -Value at 1=1.080466 +Value at 0=2.000122 +Value at 1=1.080262 Validation expert input dimension= 1 validation dimension= 1 -k= 10 error=9.5486e-06 -10 cluster(s) done, best= 8 error=1.8964e-06 +k= 10 error=6.7404e-07 +10 cluster(s) done, best= 10 error=6.7404e-07