All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
BayesLocalDialog.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/sa/qt/BayesLocalDialog.cpp
22 
23  \brief A dialog to calculate the local empirical bayes of a dataset.
24 */
25 
26 // TerraLib
27 #include "../../common/Logger.h"
28 #include "../../common/progress/ProgressManager.h"
29 #include "../../common/Translator.h"
30 #include "../../common/STLUtils.h"
31 #include "../../dataaccess/datasource/DataSource.h"
32 #include "../../dataaccess/utils/Utils.h"
33 #include "../../geometry/GeometryProperty.h"
34 #include "../../maptools/DataSetLayer.h"
35 #include "../../qt/widgets/datasource/selector/DataSourceSelectorDialog.h"
36 #include "../../qt/widgets/progress/ProgressViewerDialog.h"
37 #include "../core/BayesLocalOperation.h"
38 #include "../core/BayesParams.h"
39 #include "../core/GPMBuilder.h"
40 #include "../core/GPMConstructorAdjacencyStrategy.h"
41 #include "../core/GPMWeightsNoWeightsStrategy.h"
42 #include "../core/SpatialWeightsExchanger.h"
43 #include "../core/Utils.h"
44 #include "../Exception.h"
45 #include "BayesLocalDialog.h"
46 #include "Utils.h"
47 #include "ui_BayesLocalDialogForm.h"
48 
49 // Qt
50 #include <QFileDialog>
51 #include <QFileInfo>
52 #include <QMessageBox>
53 #include <QValidator>
54 
55 // STL
56 #include <memory>
57 
58 // Boost
59 #include <boost/filesystem.hpp>
60 
62 
63 te::sa::BayesLocalDialog::BayesLocalDialog(QWidget* parent, Qt::WindowFlags f)
64  : QDialog(parent, f),
65  m_ui(new Ui::BayesLocalDialogForm)
66 {
67 // add controls
68  m_ui->setupUi(this);
69 
71 
72 // add icons
73  m_ui->m_imgLabel->setPixmap(QIcon::fromTheme("sa-bayeslocal-hint").pixmap(112,48));
74  m_ui->m_targetDatasourceToolButton->setIcon(QIcon::fromTheme("datasource"));
75 
76 // connectors
77  connect(m_ui->m_inputLayerComboBox, SIGNAL(activated(int)), this, SLOT(onInputLayerComboBoxActivated(int)));
78  connect(m_ui->m_okPushButton, SIGNAL(clicked()), this, SLOT(onOkPushButtonClicked()));
79  connect(m_ui->m_targetDatasourceToolButton, SIGNAL(pressed()), this, SLOT(onTargetDatasourceToolButtonPressed()));
80  connect(m_ui->m_targetFileToolButton, SIGNAL(pressed()), this, SLOT(onTargetFileToolButtonPressed()));
81  connect(m_ui->m_gpmToolButton, SIGNAL(clicked()), this, SLOT(onGPMToolButtonClicked()));
82 
83 // help info
84  m_ui->m_helpPushButton->setNameSpace("dpi.inpe.br.plugins");
85  m_ui->m_helpPushButton->setPageReference("plugins/sa/sa_bayeslocal.html");
86 }
87 
89 {
90 }
91 
92 void te::sa::BayesLocalDialog::setLayers(std::list<te::map::AbstractLayerPtr> layers)
93 {
94  std::list<te::map::AbstractLayerPtr>::iterator it = layers.begin();
95 
96  while(it != layers.end())
97  {
99 
100  if(l->isValid())
101  {
102  std::auto_ptr<te::da::DataSetType> dsType = l->getSchema();
103 
104  te::map::DataSetLayer* dsLayer = dynamic_cast<te::map::DataSetLayer*>(l.get());
105 
106  if(dsLayer && dsType->hasGeom())
107  m_ui->m_inputLayerComboBox->addItem(it->get()->getTitle().c_str(), QVariant::fromValue(l));
108  }
109 
110  ++it;
111  }
112 
113 // fill attributes combo
114  if(m_ui->m_inputLayerComboBox->count() > 0)
115  onInputLayerComboBoxActivated(0);
116 }
117 
119 {
120  return m_outputLayer;
121 }
122 
124 {
125  QVariant varLayer = m_ui->m_inputLayerComboBox->itemData(index, Qt::UserRole);
126 
128 
129  std::auto_ptr<te::da::DataSetType> dsType = l->getSchema();
130 
131  std::vector<te::dt::Property*> propVec = dsType->getProperties();
132 
133  m_ui->m_attrEventComboBox->clear();
134  m_ui->m_attrPopComboBox->clear();
135  m_ui->m_attrLinkComboBox->clear();
136 
137  for(std::size_t t = 0; t < propVec.size(); ++t)
138  {
139  int dataType = propVec[t]->getType();
140 
141  if (dataType == te::dt::INT16_TYPE || dataType == te::dt::UINT16_TYPE ||
142  dataType == te::dt::INT32_TYPE || dataType == te::dt::UINT32_TYPE ||
143  dataType == te::dt::INT64_TYPE || dataType == te::dt::UINT64_TYPE ||
144  dataType == te::dt::FLOAT_TYPE || dataType == te::dt::DOUBLE_TYPE)
145  {
146  m_ui->m_attrEventComboBox->addItem(propVec[t]->getName().c_str(), dataType);
147  m_ui->m_attrPopComboBox->addItem(propVec[t]->getName().c_str(), dataType);
148  }
149 
150  m_ui->m_attrLinkComboBox->addItem(propVec[t]->getName().c_str(), dataType);
151  }
152 }
153 
155 {
156  // check input parameters
157  if(m_ui->m_repositoryLineEdit->text().isEmpty())
158  {
159  QMessageBox::information(this, tr("Warning"), tr("Define a repository for the result."));
160  return;
161  }
162 
163  if(m_ui->m_newLayerNameLineEdit->text().isEmpty())
164  {
165  QMessageBox::information(this, tr("Warning"), tr("Define a name for the resulting layer."));
166  return;
167  }
168 
169  //get GPM
170  std::auto_ptr<te::sa::GeneralizedProximityMatrix> gpm;
171 
172  try
173  {
174  gpm = loadGPM();
175  }
176  catch(...)
177  {
178  QMessageBox::warning(this, tr("Warning"), tr("Internal error. GPM not loaded."));
179  return;
180  }
181 
182  if(!gpm.get())
183  return;
184 
185 //get selected layer
186  QVariant varLayer = m_ui->m_inputLayerComboBox->itemData(m_ui->m_inputLayerComboBox->currentIndex(), Qt::UserRole);
188 
189  std::auto_ptr<te::da::DataSetType> dataSetType = l->getSchema();
190  std::auto_ptr<te::da::DataSet> dataSet = l->getData();
191 
192 //create datasource to save the output information
193  std::string dataSetName = m_ui->m_newLayerNameLineEdit->text().toStdString();
194 
195  std::size_t idx = dataSetName.find(".");
196  if (idx != std::string::npos)
197  dataSetName=dataSetName.substr(0,idx);
198 
199  te::da::DataSourcePtr outputDataSource;
200 
201  if(m_toFile)
202  {
203  outputDataSource = te::sa::CreateOGRDataSource(m_ui->m_repositoryLineEdit->text().toStdString());
204  }
205  else
206  {
207  outputDataSource = te::da::GetDataSource(m_outputDatasource->getId());
208  }
209 
211 
212  inParams->m_ds = dataSet;
213  inParams->m_dsType = dataSetType;
214  inParams->m_eventAttrName = m_ui->m_attrEventComboBox->currentText().toStdString();
215  inParams->m_populationAttrName = m_ui->m_attrPopComboBox->currentText().toStdString();
216  inParams->m_rate = m_ui->m_rateComboBox->currentText().toDouble();
217  inParams->m_gpmAttrLink = gpm->getAttributeName();
218  inParams->m_gpm = gpm;
219 
221 
222  outParams->m_ds = outputDataSource;
223  outParams->m_outputDataSetName = dataSetName;
224 
225  //progress
228 
229  QApplication::setOverrideCursor(Qt::WaitCursor);
230 
231  try
232  {
234 
235  op.setParameters(inParams, outParams);
236 
237  op.execute();
238  }
239  catch(const std::exception& e)
240  {
241  QMessageBox::warning(this, tr("Warning"), e.what());
242 
243  QApplication::restoreOverrideCursor();
244 
246 
247  return;
248  }
249  catch(...)
250  {
251  QMessageBox::warning(this, tr("Warning"), tr("Internal error. Global Bayes not calculated."));
252 
253  QApplication::restoreOverrideCursor();
254 
256 
257  return;
258  }
259 
260  QApplication::restoreOverrideCursor();
261 
263 
264  //create layer
265  m_outputLayer = te::sa::CreateLayer(outputDataSource, dataSetName);
266 
267  //create legend
268  te::sa::CreateBayesGrouping(m_outputLayer.get());
269 
270  accept();
271 }
272 
274 {
275  m_ui->m_newLayerNameLineEdit->clear();
276  m_ui->m_newLayerNameLineEdit->setEnabled(true);
277 
279  dlg.exec();
280 
281  std::list<te::da::DataSourceInfoPtr> dsPtrList = dlg.getSelecteds();
282 
283  if(dsPtrList.size() <= 0)
284  return;
285 
286  std::list<te::da::DataSourceInfoPtr>::iterator it = dsPtrList.begin();
287 
288  m_ui->m_repositoryLineEdit->setText(QString(it->get()->getTitle().c_str()));
289 
290  m_outputDatasource = *it;
291 
292  m_toFile = false;
293 }
294 
296 {
297  m_ui->m_newLayerNameLineEdit->clear();
298  m_ui->m_repositoryLineEdit->clear();
299 
300  QString fileName = QFileDialog::getSaveFileName(this, tr("Save as..."), QString(), tr("Shapefile (*.shp *.SHP);;"),0, QFileDialog::DontConfirmOverwrite);
301 
302  if (fileName.isEmpty())
303  return;
304 
305  boost::filesystem::path outfile(fileName.toStdString());
306 
307  m_ui->m_repositoryLineEdit->setText(outfile.string().c_str());
308 
309  m_ui->m_newLayerNameLineEdit->setText(outfile.leaf().string().c_str());
310 
311  m_ui->m_newLayerNameLineEdit->setEnabled(false);
312 
313  m_toFile = true;
314 }
315 
317 {
318  QString fileName = QFileDialog::getOpenFileName(this, tr("Open Generalized Proximity Matrix File"), "", tr("GAL Files (*.gal *.GAL);; GWT Files (*.gwt *.GWT)"));
319 
320  if(fileName.isEmpty())
321  return;
322 
323  //get selected layer
324  QVariant varLayer = m_ui->m_inputLayerComboBox->itemData(m_ui->m_inputLayerComboBox->currentIndex(), Qt::UserRole);
326  te::map::DataSetLayer* dsLayer = dynamic_cast<te::map::DataSetLayer*>(l.get());
327 
328  //check if the selected gpm is valid for selected layer
329  std::string path = fileName.toStdString();
330  std::string dataSetName = "";
331  std::string attrName = "";
332 
334 
335  if(dsLayer->getDataSetName() != dataSetName)
336  {
337  QMessageBox::warning(this, tr("Warning"), tr("Invalid GPM file for selected layer."));
338  return;
339  }
340 
341  if(m_ui->m_attrLinkComboBox->currentText().toStdString() != attrName)
342  {
343  QMessageBox::warning(this, tr("Warning"), tr("Invalid GPM file for selected Attr Link."));
344  return;
345  }
346 
347  m_ui->m_gpmLineEdit->setText(fileName);
348 }
349 
351 {
352  m_ui->m_rateComboBox->clear();
353 
354  m_ui->m_rateComboBox->addItem("1");
355  m_ui->m_rateComboBox->addItem("10");
356  m_ui->m_rateComboBox->addItem("100");
357  m_ui->m_rateComboBox->addItem("1000");
358  m_ui->m_rateComboBox->addItem("10000");
359  m_ui->m_rateComboBox->addItem("100000");
360 }
361 
362 std::auto_ptr<te::sa::GeneralizedProximityMatrix> te::sa::BayesLocalDialog::loadGPM()
363 {
364  std::auto_ptr<te::sa::GeneralizedProximityMatrix> gpm;
365 
366  //get selected layer
367  QVariant varLayer = m_ui->m_inputLayerComboBox->itemData(m_ui->m_inputLayerComboBox->currentIndex(), Qt::UserRole);
369 
370  if(!l.get())
371  {
372  QMessageBox::warning(this, tr("Warning"), tr("Invalid selected layer."));
373  return gpm;
374  }
375 
376  te::map::DataSetLayer* dsLayer = dynamic_cast<te::map::DataSetLayer*>(l.get());
377 
378  //get gpm necessary parameters
380 
381  std::string dataSetName = dsLayer->getDataSetName();
382 
383  if(!m_ui->m_gpmGroupBox->isChecked())
384  {
385  //create gpm
386  if(QMessageBox::question(this, tr("Spatial Analysis"), tr("GPM not selected. Create default GPM?"), QMessageBox::No, QMessageBox::Yes) == QMessageBox::No)
387  return gpm;
388 
389  //get attrlink
390  std::auto_ptr<te::da::DataSetType> dsType = dsLayer->getSchema();
391 
392  if(!dsType->getPrimaryKey() || dsType->getPrimaryKey()->getProperties().empty())
393  {
394  QMessageBox::warning(this, tr("Warning"), tr("Invalid Data Set Primary Key."));
395  return gpm;
396  }
397 
398  std::string attrLink = dsType->getPrimaryKey()->getProperties()[0]->getName();
399 
400  //create default gpm
403 
404  te::sa::GPMBuilder builder(constructor, weights);
405 
406  builder.setGPMInfo(ds, dataSetName, attrLink);
407 
408  gpm = builder.build();
409  }
410  else
411  {
412  if(m_ui->m_gpmLineEdit->text().isEmpty())
413  {
414  QMessageBox::warning(this, tr("Warning"), tr("GPM File not selected."));
415  return gpm;
416  }
417 
418  //load gpm
419  QFileInfo file(m_ui->m_gpmLineEdit->text());
420 
421  std::string extension = file.suffix().toStdString();
422 
424 
425  if(extension == "gal" || extension == "GAL")
426  {
427  gpm.reset(swe.importFromGAL(m_ui->m_gpmLineEdit->text().toStdString(), ds.get()));
428  }
429  else if(extension == "gwt" || extension == "GWT")
430  {
431  gpm.reset(swe.importFromGWT(m_ui->m_gpmLineEdit->text().toStdString(), ds.get()));
432  }
433  }
434 
435  return gpm;
436 }
TEDATAACCESSEXPORT DataSourcePtr GetDataSource(const std::string &datasourceId, const bool opened=true)
Search for a data source with the informed id in the DataSourceManager.
Definition: Utils.cpp:262
This class defines a an adjacency strategy class for a GPM constructor.
Class that represents the Bayes output parameters.
Definition: BayesParams.h:94
std::auto_ptr< GeneralizedProximityMatrix > build()
Definition: GPMBuilder.cpp:78
Utility functions for the data access module.
const std::string & getDataSetName() const
boost::shared_ptr< DataSource > DataSourcePtr
Definition: DataSource.h:1435
TESAEXPORT te::da::DataSourcePtr CreateOGRDataSource(std::string repository)
Definition: Utils.cpp:63
std::auto_ptr< te::da::DataSet > m_ds
Attribute with data set.
Definition: BayesParams.h:76
bool setGPMInfo(te::da::DataSourcePtr ds, const std::string &dataSetName, const std::string &attributeName)
Function used to create a empty gpm (using a MEMORY DIRECT graph)
Definition: GPMBuilder.cpp:49
This class defines a class to calculates a weight for a GPM using No Weights strategy.
te::sa::GeneralizedProximityMatrix * importFromGAL(std::string pathFileName, te::da::DataSource *ds=0)
Function used to import a gpm from a Spatial Weights File GAL Format.
std::auto_ptr< te::sa::GeneralizedProximityMatrix > m_gpm
Attribute with gpm information (local bayes)
Definition: BayesParams.h:77
te::sa::GeneralizedProximityMatrix * importFromGWT(std::string pathFileName, te::da::DataSource *ds=0)
Function used to import a gpm from a Spatial Weights File GWT Format.
std::string m_outputDataSetName
Attribute that defines the output dataset name.
Definition: BayesParams.h:113
std::string m_eventAttrName
Attribute from dataset with event information.
Definition: BayesParams.h:79
void removeViewer(int viewerId)
Dettach a progress viewer.
static ProgressManager & getInstance()
It returns a reference to the singleton instance.
const std::string & getDataSourceId() const
TESAEXPORT void CreateBayesGrouping(te::map::AbstractLayerPtr layer)
Definition: Utils.cpp:131
void onInputLayerComboBoxActivated(int index)
static void getSpatialWeightsFileInfo(std::string pathFileName, std::string &dataSetName, std::string &attrName)
Function used to get information of how a Spatial Weights was generated.
te::da::DataSourcePtr m_ds
Pointer to the output datasource.
Definition: BayesParams.h:111
This class defines a an Abstract class for a GPM constructor.
int addViewer(AbstractProgressViewer *apv)
Attach a progress viewer.
This class defines a an Abstract class to calculates a weight for a GPM.
double m_rate
Attribute with multiplicative rate correction.
Definition: BayesParams.h:83
Class that represents the Bayes input parameters.
Definition: BayesParams.h:56
const std::list< te::da::DataSourceInfoPtr > & getSelecteds() const
BayesLocalDialog(QWidget *parent=0, Qt::WindowFlags f=0)
TESAEXPORT te::map::AbstractLayerPtr CreateLayer(te::da::DataSourcePtr ds, std::string dataSetName)
Definition: Utils.cpp:122
A dialog for selecting a data source.
te::map::AbstractLayerPtr getOutputLayer()
std::string m_populationAttrName
Attribute from dataset with population information.
Definition: BayesParams.h:80
This class defines functions used to load and save gpm's using GAL and GWT formats, both formats use a ' ' as separator.
A layer with reference to a dataset.
Definition: DataSetLayer.h:47
std::auto_ptr< LayerSchema > getSchema() const
It returns the layer schema.
This class defines the GPM Builder class.
Definition: GPMBuilder.h:54
A dialog to calculate the local empirical bayes of a dataset.
void setParameters(te::sa::BayesInputParams *inParams, te::sa::BayesOutputParams *outParams)
std::auto_ptr< te::sa::GeneralizedProximityMatrix > loadGPM()
void setLayers(std::list< te::map::AbstractLayerPtr > layers)
Set the layer that can be used.
std::auto_ptr< te::da::DataSetType > m_dsType
Attribute used to access the data set metadata.
Definition: BayesParams.h:75
boost::intrusive_ptr< AbstractLayer > AbstractLayerPtr
std::auto_ptr< Ui::BayesLocalDialogForm > m_ui
Q_DECLARE_METATYPE(te::map::AbstractLayerPtr)
void execute()
Function to execute the bayes operation.
std::string m_gpmAttrLink
Attribute from dataset that was used to generate the gpm.
Definition: BayesParams.h:81