ClassifierMAPStrategy.cpp
Go to the documentation of this file.
1 /* Copyright (C) 2008 National Institute For Space Research (INPE) - Brazil.
2 
3  This file is part of the TerraLib - a Framework for building GIS enabled applications.
4 
5  TerraLib is free software: you can redistribute it and/or modify
6  it under the terms of the GNU Lesser General Public License as published by
7  the Free Software Foundation, either version 3 of the License,
8  or (at your option) any later version.
9 
10  TerraLib is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  GNU Lesser General Public License for more details.
14 
15  You should have received a copy of the GNU Lesser General Public License
16  along with TerraLib. See COPYING. If not, write to
17  TerraLib Team at <terralib-team@terralib.org>.
18  */
19 
20 /*!
21  \file terralib/rp/ClassifierMAPStrategy.cpp
22 
23  \brief Maximum a posteriori probability strategy.
24 */
25 
26 // TerraLib
27 
28 #include "ClassifierMAPStrategy.h"
29 #include "Macros.h"
30 #include "../raster/Band.h"
31 // #include "../common/MatrixUtils.h"
32 #include "ClassifierAdaptors.h"
33 
34 #include <cfloat>
35 
36 namespace
37 {
38  static te::rp::ClassifierMAPStrategyFactory classifierMAPStrategyFactoryInstance;
39 }
40 
41 //-----------------------------------------------------------------------------
42 
44 {
45  reset();
46 }
47 
49 
51 {
52  reset();
53 
57 
58  return *this;
59 }
60 
62 {
63  m_trainSamplesPtr.reset();
64  m_prioriProbs.clear();
66 }
67 
69 {
71 }
72 
73 //-----------------------------------------------------------------------------
74 
76 {
77  m_isInitialized = false;
79 }
80 
82 
84  te::rp::ClassifierStrategyParameters const* const strategyParams) throw(te::rp::Exception)
85 {
86  m_isInitialized = false;
88 
89  ClassifierMAPStrategy::Parameters const * const castParamsPtr =
90  dynamic_cast< ClassifierMAPStrategy::Parameters const * >( strategyParams );
91  TERP_INSTANCE_TRUE_OR_RETURN_FALSE( castParamsPtr, "Invalid parameters" );
92 
93  // Checking the input parameters
94 
96  "Invalid classes samples pointer" )
97  TERP_INSTANCE_TRUE_OR_RETURN_FALSE( castParamsPtr->m_trainSamplesPtr->size() > 0,
98  "Invalid classes samples number" )
99  TERP_INSTANCE_TRUE_OR_RETURN_FALSE( castParamsPtr->m_trainSamplesPtr->begin()->second.size() > 0,
100  "Invalid classes samples number" )
101 
102  m_initParams = (*castParamsPtr);
103 
104  // Groupping samples
105 
106  std::vector< std::vector< double > > samples;
107  std::vector<unsigned int> samplesLabels;
108  std::vector<unsigned int> samplesAttributesIndices;
109 
110  {
111  Parameters::MClassesSamplesCT::const_iterator classesSamplesIt = castParamsPtr->m_trainSamplesPtr->begin();
112  const Parameters::MClassesSamplesCT::const_iterator classesSamplesItEnd = castParamsPtr->m_trainSamplesPtr->end();
113  Parameters::ClassSamplesContainerT::const_iterator classSamplesIt;
114  Parameters::ClassSamplesContainerT::const_iterator classSamplesItEnd;
115 
117 
118  while( classesSamplesIt != classesSamplesItEnd )
119  {
120  classSamplesIt = classesSamplesIt->second.begin();
121  classSamplesItEnd = classesSamplesIt->second.end();
122 
124  classesSamplesIt->first );
125 
126  while( classSamplesIt != classSamplesItEnd )
127  {
128  samples.push_back( *classSamplesIt);
129  samplesLabels.push_back( classesSamplesIt->first );
130 
131  ++classSamplesIt;
132  }
133 
134  ++classesSamplesIt;
135  }
136 
137  if( !samples.empty() )
138  {
139  const std::size_t featuresNmb = samples[ 0 ].size();
140 
141  for( std::size_t featureIdx = 0 ; featureIdx < featuresNmb ; ++featureIdx )
142  {
143  samplesAttributesIndices.push_back(static_cast<unsigned int>(featureIdx));
144  }
145  }
146  }
147 
148  // Initializing the generic classifier
149 
150  te::cl::MAP::Parameters genPars;
153 
155  "Invalid parameters" )
156 
157  // Training the generic classifier
158 
160  samples );
161 
162  TERP_INSTANCE_TRUE_OR_RETURN_FALSE( m_genClassInstance.train( samplesAdaptor, samplesAttributesIndices,
163  samplesLabels, false ), "Classifier trainning error" );
164 
165  // Finalizing
166 
167  m_isInitialized = true;
168 
169  return true;
170 }
171 
173 {
175  "Classification strategy not initialized" );
176 
177  // Creating the output raster
178 
179  std::vector< int > dt;
180  dt.push_back( te::dt::UINT32_TYPE );
181 
182  std::vector< double > noDataValues;
183  noDataValues.push_back( (double)( m_highestTrainClassID + 2 ) );
184 
186  "Output raster creation error" );
187 
189  "Output raster palette creation error" );
190 
193 
194  std::vector< double > inputNoDataValues;
195  for( unsigned int inputRasterBandsIdx = 0 ; inputRasterBandsIdx < m_inputRasterBands.size() ;
196  ++inputRasterBandsIdx )
197  {
198  inputNoDataValues.push_back( m_inputRasterPtr->getBand(
199  m_inputRasterBands[ inputRasterBandsIdx ] )->getProperty()->m_noDataValue );
200  }
201 
203  m_inputRasterBands, inputNoDataValues, outputRasterAdp, 0,
204  m_outputRasterPtr->getBand( 0 )->getProperty()->m_noDataValue,
205  m_progressInterfaceEnabled ), "Classifier execution error" );
206 
207  return true;
208 }
209 
210 //-----------------------------------------------------------------------------
211 
213  : te::rp::ClassifierStrategyFactory("map")
214 {
215 }
216 
218 
220 {
221  return new te::rp::ClassifierMAPStrategy();
222 }
unsigned int m_prioriCalcSampleStep
A positive non-zero sample step used when calculating piori probabilities (default:5 - 1/5 of samples...
Definition: MAP.h:67
ClassifierMAPStrategy::Parameters m_initParams
Initialization parameters.
MClassesSamplesCTPtr m_trainSamplesPtr
A shared pointer to a always-valid structure where trainning samples are stored.
Maximum a posteriori probability strategy factory.
te::cl::MAP m_genClassInstance
A generir classifier instance.
Classifier Parameters.
Definition: MAP.h:62
Classifier Adaptors.
unsigned int m_prioriCalcSampleStep
A positive non-zero sample step used when calculating piori probabilities (default:5 - 1/5 of samples...
Maximum a posteriori probability strategy.
Base exception class for plugin module.
bool createOutputRaster(const std::vector< int > &bandsDataTypes, const std::vector< double > &noDataValues)
Create the output raster using the EXPANSIBLE driver.
bool train(const InputAdaptor< double > &samples, const std::vector< unsigned int > &attributesIndices, const std::vector< unsigned int > &sampleLabels, const bool enableProgressInterface)
Train this classifier instance using the initialization parameters and the suppied train data...
Definition: MAP.cpp:126
const Parameters & operator=(const Parameters &params)
std::vector< double > m_prioriProbs
Priori probabilities, one for each class. Values from 0 to 1 (use an empty vector to allow internal c...
Definition: MAP.h:66
double m_noDataValue
Value to indicate elements where there is no data, default is std::numeric_limits<double>::max().
Definition: BandProperty.h:136
bool initialize(const Parameters &params)
Initialize this classifier instance with new parameters.
Definition: MAP.cpp:74
std::vector< unsigned int > m_inputRasterBands
Input raster bands.
std::vector< double > m_prioriProbs
Priori probabilities, one for each class. Values from 0 to 1 (use an empty vector to allow internal c...
Raster classifier strategy factory base class.
bool classify(const InputAdaptor< double > &input, const std::vector< unsigned int > &attributesIndices, const std::vector< double > &inputNoDataValues, OutputAdaptor< unsigned int > &output, const unsigned int outputIndex, const double outputNoDataValue, const bool enableProgressInterface)
Classify an input iterated data and save the result on the output iterated data.
Definition: MAP.cpp:346
bool execute()
Executes the classification strategy.
BandProperty * getProperty()
Returns the band property.
URI C++ Library.
Definition: Attributes.h:37
static te::dt::TimeDuration dt(20, 30, 50, 11)
bool m_isInitialized
Is this instance initialized?
virtual const Band * getBand(std::size_t i) const =0
Returns the raster i-th band.
Classifiers raster input data adaptor.
Maximum a posteriori probability strategy.
std::unique_ptr< te::rst::Raster > m_outputRasterPtr
A pointer to the output raster.
Abstract parameters base interface.
bool m_progressInterfaceEnabled
Progress interface status.
te::rp::ClassifierStrategy * build()
Concrete factories (derived from this one) must implement this method in order to create objects...
AbstractParameters * clone() const
Create a clone copy of this instance.
te::rst::Raster const * m_inputRasterPtr
A pointer to the input raster.
Raster classifier strategy base class.
Classifiers raster output data adaptor.
bool initialize(ClassifierStrategyParameters const *const strategyParams)
Initialize the classification strategy.
void reset()
Clear all internal allocated resources and reset the parameters instance to its initial state...
Parameters::ClassIDT m_highestTrainClassID
The highest train sample lable.
#define TERP_INSTANCE_TRUE_OR_RETURN_FALSE(value, message)
Checks if value is true. For false values a warning message will be logged, the current instance erro...
Definition: Macros.h:200
bool setOutputRasterPalette(const unsigned int size)
Create and set the output raster palette folowing the current internal settings.