예제 #1
0
vector<ImportDescriptor*> CgmImporter::getImportDescriptors(const string& filename)
{
   vector<ImportDescriptor*> descriptors;
   if (!filename.empty())
   {
      FactoryResource<Filename> pFullFilename;
      pFullFilename->setFullPathAndName(filename);

      ImportDescriptor* pImportDescriptor = mpModel->createImportDescriptor(filename, "AnnotationElement", NULL);
      if (pImportDescriptor != NULL)
      {
         DataDescriptor* pDescriptor = pImportDescriptor->getDataDescriptor();
         if (pDescriptor != NULL)
         {
            FactoryResource<FileDescriptor> pFileDescriptor;
            if (pFileDescriptor.get() != NULL)
            {
               pFileDescriptor->setFilename(filename);
               pDescriptor->setFileDescriptor(pFileDescriptor.get());
            }
         }

         descriptors.push_back(pImportDescriptor);
      }
   }

   return descriptors;
}
예제 #2
0
void PreviewWidget::updateCurrentDataset()
{
   ChippingWidget* pChippingWidget = dynamic_cast<ChippingWidget*>(mpImporterWidget);
   if (pChippingWidget == NULL)
   {
      return;
   }

   ImportDescriptor* pActiveDataset = getCurrentDataset();
   if (pActiveDataset != NULL)
   {
      RasterDataDescriptor* pDescriptor = dynamic_cast<RasterDataDescriptor*>(pActiveDataset->getDataDescriptor());
      if (pDescriptor != NULL)
      {
         // Rows
         vector<DimensionDescriptor> rows = pChippingWidget->getChipRows();
         transform(rows.begin(), rows.end(), rows.begin(), UnsetActiveNumber());
         pDescriptor->setRows(rows);

         // Columns
         vector<DimensionDescriptor> columns = pChippingWidget->getChipColumns();
         transform(columns.begin(), columns.end(), columns.begin(), UnsetActiveNumber());
         pDescriptor->setColumns(columns);

         // Bands -- ignore if the user deselected all bands
         vector<DimensionDescriptor> bands = pChippingWidget->getChipBands();
         if (bands.empty() == false)
         {
            transform(bands.begin(), bands.end(), bands.begin(), UnsetActiveNumber());
            pDescriptor->setBands(bands);
         }
      }
   }
}
예제 #3
0
void PreviewWidget::setCurrentFile(const QString& filename)
{
   // Always clear the current file even if the filename is the same as the current filename
   // to ensure that the previous and next dataset buttons are enabled properly
   mCurrentFile.clear();

   // Activate the label indicating that no preview is available
   mpStack->setCurrentIndex(0);

   // Get a data set to activate
   ImportDescriptor* pDataset = NULL;
   if (filename.isEmpty() == false)
   {
      // Do not update the preview if the file does not exist in the map
      QMap<QString, vector<ImportDescriptor*> >::iterator iter = mDatasets.find(filename);
      if (iter != mDatasets.end())
      {
         mCurrentFile = filename;

         // Activate the file widget
         mpStack->setCurrentIndex(1);

         // Update the file label
         updateFileNumber();

         // Activate the label indicating that no file preview is available
         mpFileStack->setCurrentIndex(0);

         // Update the preview with the first imported data set in the file
         unsigned int numImportedDatasets = 0;

         vector<ImportDescriptor*> fileDatasets = iter.value();
         for (vector<ImportDescriptor*>::iterator datasetIter = fileDatasets.begin();
            datasetIter != fileDatasets.end();
            ++datasetIter)
         {
            ImportDescriptor* pCurrentDataset = *datasetIter;
            if ((pCurrentDataset != NULL) && (pCurrentDataset->isImported() == true))
            {
               if (pDataset == NULL)
               {
                  pDataset = pCurrentDataset;
               }

               ++numImportedDatasets;

               // Activate the data set widget
               mpFileStack->setCurrentIndex(1);
            }
         }

         // Enable the data set buttons
         mpPreviousDatasetButton->setEnabled(numImportedDatasets > 1);
         mpNextDatasetButton->setEnabled(numImportedDatasets > 1);
      }
   }

   setCurrentDataset(pDataset);
}
예제 #4
0
vector<ImportDescriptor*> Jpeg2000Importer::getImportDescriptors(const string& filename)
{
   vector<ImportDescriptor*> descriptors;
   if (filename.empty() == true)
   {
      return descriptors;
   }

   vector<string>& warnings = msWarnings[filename];
   warnings.clear();

   vector<string>& errors = msErrors[filename];
   errors.clear();

   ImportDescriptor* pImportDescriptor = mpModel->createImportDescriptor(filename, "RasterElement", NULL);
   if (pImportDescriptor != NULL)
   {
      RasterDataDescriptor* pDescriptor = dynamic_cast<RasterDataDescriptor*>(pImportDescriptor->getDataDescriptor());
      if (pDescriptor != NULL)
      {
         vector<EncodingType> validDataTypes;
         validDataTypes.push_back(INT1UBYTE);
         validDataTypes.push_back(INT1SBYTE);
         validDataTypes.push_back(INT2UBYTES);
         validDataTypes.push_back(INT2SBYTES);
         validDataTypes.push_back(INT4UBYTES);
         validDataTypes.push_back(INT4SBYTES);
         validDataTypes.push_back(FLT4BYTES);
         pDescriptor->setValidDataTypes(validDataTypes);
         pDescriptor->setProcessingLocation(IN_MEMORY);

         // Create and set a file descriptor in the data descriptor
         FactoryResource<RasterFileDescriptor> pFileDescriptor;
         pFileDescriptor->setEndian(BIG_ENDIAN_ORDER);
         if (pFileDescriptor.get() != NULL)
         {
            pFileDescriptor->setFilename(filename);
            pDescriptor->setFileDescriptor(pFileDescriptor.get());
         }

         // Populate the data descriptor from the file
         bool bSuccess = populateDataDescriptor(pDescriptor);
         if (bSuccess == true)
         {
            descriptors.push_back(pImportDescriptor);
         }
         else
         {
            // Delete the import descriptor
            mpModel->destroyImportDescriptor(pImportDescriptor);
         }
      }
   }

   return descriptors;
}
예제 #5
0
vector<ImportDescriptor*> LayerImporter::getImportDescriptors(const string& filename, bool reportErrors)
{
   vector<ImportDescriptor*> descriptors;
   if (!filename.empty())
   {
      MessageLog* pLog = NULL;
      if (reportErrors == true)
      {
         Service<MessageLogMgr> pLogMgr;
         pLog = pLogMgr->getLog();
      }

      XmlReader xml(pLog);
      XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument* pDoc = xml.parse(filename, "metadata");
      DOMElement* pRootElement = NULL;
      if (pDoc != NULL)
      {
         pRootElement = pDoc->getDocumentElement();
      }
      if (pRootElement != NULL)
      {
         for (DOMNode* pChild = pRootElement->getFirstChild();
            pChild != NULL;
            pChild = pChild->getNextSibling())
         {
            if (pChild->getNodeType() == DOMNode::ELEMENT_NODE)
            {
               DOMElement* pChildElement = static_cast<DOMElement*>(pChild);
               string cNodeName = A(pChildElement->getNodeName());

               ImportDescriptor* pImportDescriptor = ModelImporter::populateImportDescriptor(pChildElement, filename);
               if (pImportDescriptor != NULL)
               {
                  DataDescriptor* pDataDescriptor = pImportDescriptor->getDataDescriptor();
                  if (NULL != pDataDescriptor)
                  {
                     DynamicObject* pMetadataZ = pDataDescriptor->getMetadata();
                     VERIFYRV(pMetadataZ, descriptors);
                     if (!pMetadataZ->getAttributeByPath("Layer/Import Options/Use Pixel Coordinates").isValid())
                     {
                        pMetadataZ->setAttributeByPath("Layer/Import Options/Use Pixel Coordinates", false);
                     }
                  }
                  descriptors.push_back(pImportDescriptor);
               }
            }
         }
      }
   }

   return descriptors;
}
예제 #6
0
ImportDescriptor* ModelServicesImp::createImportDescriptor(DataDescriptor* pDescriptor, bool bImported) const
{
    ImportDescriptor* pImportDescriptor = NULL;
    if (pDescriptor != NULL)
    {
        pImportDescriptor = new ImportDescriptorImp(pDescriptor);
        if (pImportDescriptor != NULL)
        {
            pImportDescriptor->setImported(bImported);
        }
    }

    return pImportDescriptor;
}
예제 #7
0
void PreviewWidget::displayPreviousDataset()
{
   // Get the descriptor of the previous imported data set in the vector
   ImportDescriptor* pCurrentDataset = getCurrentDataset();
   ImportDescriptor* pPreviousDataset = NULL;
   ImportDescriptor* pLastDataset = NULL;
   bool bNextDataset = (pCurrentDataset == NULL);

   QMap<QString, vector<ImportDescriptor*> >::iterator fileIter = mDatasets.find(mCurrentFile);
   VERIFYNRV(fileIter != mDatasets.end());

   vector<ImportDescriptor*> fileDatasets = fileIter.value();

   vector<ImportDescriptor*>::reverse_iterator iter;
   for (iter = fileDatasets.rbegin(); iter != fileDatasets.rend(); ++iter)
   {
      ImportDescriptor* pDataset = *iter;
      if ((pDataset != NULL) && (pDataset->isImported() == true))
      {
         if (pLastDataset == NULL)
         {
            pLastDataset = pDataset;
         }

         if (bNextDataset == true)
         {
            pPreviousDataset = pDataset;
            break;
         }

         if (pDataset == pCurrentDataset)
         {
            bNextDataset = true;
         }
      }
   }

   // The previous imported data set was not found so cycle around to the last imported data set
   if (pPreviousDataset == NULL)
   {
      pPreviousDataset = pLastDataset;
   }

   // Update the active data set
   setCurrentDataset(pPreviousDataset);
}
예제 #8
0
void ImportOptionsDlg::accept()
{
   // Apply changes to the data descriptor
   applyChanges();

   // Check if the user has no selected data sets for a file and display a message box if necessary
   if (mAllowDeselectedFiles == true)
   {
      for (int i = 0; i < mpDatasetTree->topLevelItemCount(); ++i)
      {
         QTreeWidgetItem* pFileItem = mpDatasetTree->topLevelItem(i);
         if ((pFileItem != NULL) && (pFileItem->checkState(0) == Qt::Unchecked))
         {
            int returnValue = QMessageBox::question(this, windowTitle(), "At least one file does not have any data "
               "sets that will be imported.  Do you want to continue?", QMessageBox::Yes | QMessageBox::No);
            if (returnValue == QMessageBox::No)
            {
               return;
            }

            break;
         }
      }
   }

   // Apply changes to the imported data sets
   for (map<ImportDescriptor*, QTreeWidgetItem*>::iterator iter = mDatasets.begin(); iter != mDatasets.end(); ++iter)
   {
      ImportDescriptor* pDataset = iter->first;
      if (pDataset != NULL)
      {
         QTreeWidgetItem* pItem = iter->second;
         if (pItem != NULL)
         {
            bool bImport = (pItem->checkState(0) != Qt::Unchecked);
            pDataset->setImported(bImport);
         }
      }
   }

   // Close the dialog
   QDialog::accept();
}
예제 #9
0
vector<ImportDescriptor*> ShapeFileImporter::getImportDescriptors(const string& filename)
{
   vector<ImportDescriptor*> descriptors;

   if (getFileAffinity(filename) != Importer::CAN_NOT_LOAD)
   {
      Service<ModelServices> pModel;

      ImportDescriptor* pImportDescriptor = pModel->createImportDescriptor(filename, "AnnotationElement", NULL);
      VERIFYRV(pImportDescriptor != NULL, descriptors);

      DataDescriptor* pDescriptor = pImportDescriptor->getDataDescriptor();
      VERIFYRV(pDescriptor != NULL, descriptors);

      FactoryResource<FileDescriptor> pFileDescriptor;
      pFileDescriptor->setFilename(filename);
      pDescriptor->setFileDescriptor(pFileDescriptor.get());

      descriptors.push_back(pImportDescriptor);
   }

   return descriptors;
}
예제 #10
0
vector<ImportDescriptor*> EnviLibraryImporter::getImportDescriptors(const string& filename)
{
   vector<ImportDescriptor*> descriptors;

   string headerFile = filename;
   string dataFile;
   // assume filename is a header file and try to parse
   bool bSuccess = mFields.populateFromHeader(filename);
   if (bSuccess == false)
   {
      dataFile = filename;           // was passed data file name instead of header file name
      headerFile = findHeaderFile(dataFile);
      if (headerFile.empty() == false)
      {
         bSuccess = mFields.populateFromHeader(headerFile);
      }
   }
   if (bSuccess == true)
   {
      if (dataFile.empty())  // was passed header file name and now need to find the data file name
      {
         dataFile = findDataFile(headerFile);
      }
      if (dataFile.empty())  // no data file found for the header
      {
         return descriptors;
      }

      EnviField* pField = mFields.find("file type");
      if (pField != NULL)
      {
         if (pField->mValue == "ENVI Spectral Library" || 
             pField->mValue == "Spectral Library")
         {
            // Get the name and dataset from the header values
            string name;
            string dataset;

            EnviField* pBandNamesField = mFields.find("band names");
            if (pBandNamesField != NULL)
            {
               if (pBandNamesField->mChildren.empty() == false)
               {
                  EnviField* pNameField = pBandNamesField->mChildren.front();
                  if (pNameField != NULL)
                  {
                     name = pNameField->mValue;
                  }
               }
            }

            EnviField* pDescriptionField = mFields.find("description");
            if (pDescriptionField != NULL)
            {
               // Library name
               if (name.empty() == true)
               {
                  EnviField* pNameField = pDescriptionField->find("library name");
                  if (pNameField != NULL)
                  {
                     name = pNameField->mValue;
                  }
               }

               // Dataset
               EnviField* pDatasetField = pDescriptionField->find("dataset");
               if (pDatasetField != NULL)
               {
                  dataset = pDatasetField->mValue;
               }
            }

            // Create the data descriptor
            Service<ModelServices> pModel;

            RasterElement* pRasterElement = NULL;
            if (dataset.empty() == false)
            {
               pRasterElement = dynamic_cast<RasterElement*>(pModel->getElement(dataset, "RasterElement", NULL));
            }

            if (name.empty() == true)
            {
               // Create a unique default name
               unsigned int libraryNumber = pModel->getElements(pRasterElement, "SignatureLibrary").size();

               DataElement* pSignatureLibrary = NULL;
               do
               {
                  char buffer[64];
                  sprintf(buffer, "%u", ++libraryNumber);

                  name = "Spectral Library " + string(buffer);
                  pSignatureLibrary = pModel->getElement(name, "SignatureLibrary", pRasterElement);
               }
               while (pSignatureLibrary != NULL);
            }

            ImportDescriptor* pImportDescriptor =
               pModel->createImportDescriptor(name, "SignatureLibrary", pRasterElement);
            if (pImportDescriptor != NULL)
            {
               SignatureDataDescriptor* pDescriptor =
                  dynamic_cast<SignatureDataDescriptor*>(pImportDescriptor->getDataDescriptor());
               if (pDescriptor != NULL)
               {
                  // Metadata
                  FactoryResource<DynamicObject> pMetadata;
                  if (pDescriptionField != NULL)
                  {
                     vector<EnviField*>& children = pDescriptionField->mChildren;
                     for (vector<EnviField*>::iterator iter = children.begin(); iter != children.end(); ++iter)
                     {
                        EnviField* pField = *iter;
                        if (pField != NULL)
                        {
                           if ((pField->mTag.empty() == false) && (pField->mValue.empty() == false))
                           {
                              pMetadata->setAttribute(pField->mTag, pField->mValue);
                           }
                        }
                     }
                  }

                  // Signature names
                  EnviField* pSigNamesField = mFields.find("spectra names");
                  if (pSigNamesField != NULL)
                  {
                     vector<string> sigNames;
                     for (unsigned int i = 0; i < pSigNamesField->mChildren.size(); i++)
                     {
                        EnviField* pField = pSigNamesField->mChildren[i];
                        if (pField != NULL)
                        {
                           vector<char> bufferVector(pField->mValue.size() + 1);
                           char* pBuffer = &bufferVector.front();
                           strcpy(pBuffer, pField->mValue.c_str());

                           char* pPtr = strtok(pBuffer, ",");
                           while (pPtr != NULL)
                           {
                              string sigName = StringUtilities::stripWhitespace(string(pPtr));
                              sigNames.push_back(sigName);

                              pPtr = strtok(NULL, ",");
                           }
                        }
                     }

                     if (sigNames.empty() == false)
                     {
                        pMetadata->setAttribute("Signature Names", sigNames);
                     }
                  }

                  // Signature units - Set custom units into the data descriptor so that the
                  // user can modify them even though units are not loaded from the file
                  FactoryResource<Units> pUnits;
                  pUnits->setUnitName("Custom");
                  pUnits->setUnitType(CUSTOM_UNIT);
                  pDescriptor->setUnits("Reflectance", pUnits.get());

                  // Wavelengths
                  EnviField* pSamplesField = mFields.find("samples");
                  if (pSamplesField != NULL)
                  {
                     unsigned int numWavelengths = StringUtilities::fromXmlString<unsigned int>(pSamplesField->mValue);

                     vector<double> wavelengths;
                     unsigned int uiNanometerValues = 0;

                     EnviField* pWavelengthField = mFields.find("wavelength");
                     if (pWavelengthField != NULL)
                     {
                        vector<unsigned int> goodBands;
                        EnviField* pBblField = mFields.find("bbl");
                        if (pBblField != NULL)
                        {
                           // Parse the bad bands list. This method puts the indices of good bands in ascending order.
                           EnviImporter::parseBbl(pBblField, goodBands);

                           // Sort in descending order so that the last one can be popped later
                           // A pop_back is much faster than an erase on the first element
                           reverse(goodBands.begin(), goodBands.end());
                        }

                        unsigned int numWavelengthsRead = 0;
                        for (std::vector<EnviField*>::const_iterator iter = pWavelengthField->mChildren.begin();
                           iter != pWavelengthField->mChildren.end();
                           ++iter)
                        {
                           EnviField* pField = *iter;
                           if (pField != NULL)
                           {
                              vector<char> bufferVector(pField->mValue.size() + 1);
                              char* pBuffer = &(bufferVector.front());
                              strcpy(pBuffer, pField->mValue.c_str());

                              char* pPtr = strtok(pBuffer, ",");
                              while (pPtr != NULL)
                              {
                                 double dWavelength = 0.0;
                                 if (sscanf(pPtr, "%lf", &dWavelength) == 1)
                                 {
                                    if (dWavelength > 50.0)    // Assumed to be in nanometers
                                    {
                                       uiNanometerValues++;
                                    }

                                    // Restrict the number of wavelengths to the number of samples in the header file
                                    if (numWavelengthsRead < numWavelengths)
                                    {
                                       // Only write the wavelength if the value is valid
                                       // Since the bands are in descending order,
                                       // goodBands.back() always holds the next good band.
                                       if (pBblField == NULL ||
                                          (goodBands.empty() == false && goodBands.back() == numWavelengthsRead))
                                       {
                                          if (goodBands.empty() == false)
                                          {
                                             goodBands.pop_back();
                                          }

                                          wavelengths.push_back(dWavelength);
                                       }
                                    }

                                    ++numWavelengthsRead;
                                 }

                                 pPtr = strtok(NULL, ",");
                              }
                           }
                        }

                        VERIFYNR(goodBands.empty() == true);
                     }

                     // Wavelength units
                     bool bConvertWavelengths = false;
                     bool bDetermineUnits = true;

                     EnviField* pUnitsField = mFields.find("wavelength units");
                     if (pUnitsField != NULL)
                     {
                        if (pUnitsField->mValue == "Micrometers")
                        {
                           bDetermineUnits = false;
                        }
                        else if (pUnitsField->mValue == "Nanometers")
                        {
                           bDetermineUnits = false;
                           bConvertWavelengths = true;
                        }
                     }

                     if (bDetermineUnits)
                     {
                        if ((uiNanometerValues * 100) / wavelengths.size() > 50)
                        {
                           bConvertWavelengths = true;
                        }
                     }

                     if (bConvertWavelengths == true)
                     {
                        for (vector<double>::size_type i = 0; i < wavelengths.size(); i++)
                        {
                           wavelengths[i] *= 0.001;
                        }
                     }

                     string pCenterPath[] = { SPECIAL_METADATA_NAME, BAND_METADATA_NAME, 
                        CENTER_WAVELENGTHS_METADATA_NAME, END_METADATA_NAME };
                     pMetadata->setAttributeByPath(pCenterPath, wavelengths);
                  }

                  if (pMetadata->getNumAttributes() > 0)
                  {
                     pDescriptor->setMetadata(pMetadata.get());
                  }

                  // Create the file descriptor
                  FactoryResource<SignatureFileDescriptor> pFileDescriptor;
                  if (pFileDescriptor.get() != NULL)
                  {
                     pFileDescriptor->setFilename(dataFile);
                     pDescriptor->setFileDescriptor(pFileDescriptor.get());
                  }
               }
               descriptors.push_back(pImportDescriptor);
            }
         }
      }
   }

   return descriptors;
}
예제 #11
0
bool ImportOptionsDlg::validateDataset(DataDescriptor* pDescriptor, QString& validationMessage)
{
   validationMessage.clear();
   if (pDescriptor == NULL)
   {
      return false;
   }

   // Validate the user inputs from the importer
   bool validDataset = false;
   if (mpImporter != NULL)
   {
      string errorMessage;
      validDataset = mpImporter->validate(pDescriptor, errorMessage);
      if (!errorMessage.empty())
      {
         validationMessage = QString::fromStdString(errorMessage);
      }
   }

   // Update the validation icon for the dataset
   map<ImportDescriptor*, QTreeWidgetItem*>::iterator iter;
   if (pDescriptor == mpEditDescriptor)
   {
      iter = mDatasets.find(mpCurrentDataset);
   }
   else
   {
      for (iter = mDatasets.begin(); iter != mDatasets.end(); ++iter)
      {
         ImportDescriptor* pImportDescriptor = iter->first;
         if (pImportDescriptor != NULL)
         {
            if (pImportDescriptor->getDataDescriptor() == pDescriptor)
            {
               break;
            }
         }
      }
   }

   if (iter != mDatasets.end())
   {
      QTreeWidgetItem* pItem = iter->second;
      if (pItem != NULL)
      {
         bool disconnected = disconnect(mpDatasetTree, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this,
            SLOT(datasetItemChanged(QTreeWidgetItem*)));

         if (validDataset == true)
         {
            pItem->setIcon(0, QIcon(":/icons/Ok"));
         }
         else
         {
            pItem->setIcon(0, QIcon(":/icons/Critical"));
         }

         pItem->setData(0, Qt::UserRole, QVariant(validDataset));

         if (disconnected)
         {
            //only connect, if the signal was originally connected
            VERIFYNR(connect(mpDatasetTree, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this,
               SLOT(datasetItemChanged(QTreeWidgetItem*))));
         }
      }
예제 #12
0
ImportOptionsDlg::ImportOptionsDlg(Importer* pImporter, const QMap<QString, vector<ImportDescriptor*> >& files,
   QWidget* pParent) :
   QDialog(pParent),
   mpImporter(pImporter),
   mpCurrentDataset(NULL),
   mpEditDescriptor(NULL),
   mEditDataDescriptorModified(false),
   mPromptForChanges(true),
   mAllowDeselectedFiles(true),
   mpDatasetTree(NULL),
   mpClassificationLabel(NULL),
   mpTabWidget(NULL),
   mpDataPage(NULL),
   mpFilePage(NULL),
   mpClassificationPage(NULL),
   mpSubsetPage(NULL),
   mpMetadataPage(NULL),
   mpWavelengthsPage(NULL),
   mpImporterPage(NULL),
   mpValidationLabel(NULL)
{
   QSplitter* pSplitter = new QSplitter(this);

   // Dataset list
   QWidget* pDatasetWidget = new QWidget(pSplitter);
   QLabel* pDatasetLabel = new QLabel("Data Sets:", pDatasetWidget);

   mpDatasetTree = new QTreeWidget(pDatasetWidget);
   mpDatasetTree->setSelectionMode(QAbstractItemView::SingleSelection);
   mpDatasetTree->setSelectionBehavior(QAbstractItemView::SelectItems);
   mpDatasetTree->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
   mpDatasetTree->setTextElideMode(Qt::ElideLeft);
   mpDatasetTree->setMinimumWidth(225);
   mpDatasetTree->setHeaderHidden(true);

   QPushButton* pImportAllButton = new QPushButton("Import All", pDatasetWidget);
   QPushButton* pImportNoneButton = new QPushButton("Import None", pDatasetWidget);

   // Classification label
   QWidget* pInfoWidget = new QWidget(pSplitter);

   QFont labelFont = font();
   labelFont.setBold(true);

   mpClassificationLabel = new QLabel(pInfoWidget);
   mpClassificationLabel->setFont(labelFont);
   mpClassificationLabel->setAlignment(Qt::AlignCenter);

   // Tab widget
   mpTabWidget = new QTabWidget(pInfoWidget);
   mpDataPage = new DataDescriptorWidget();
   mpFilePage = new FileDescriptorWidget();
   mpClassificationPage = new ClassificationWidget();
   mpSubsetPage = new SubsetWidget();
   mpMetadataPage = new MetadataWidget();
   mpWavelengthsPage = new WavelengthsWidget();

   mpTabWidget->addTab(mpDataPage, "Data");
   mpTabWidget->addTab(mpFilePage, "File");
   mpTabWidget->addTab(mpClassificationPage, "Classification");
   mpTabWidget->addTab(mpSubsetPage, "Subset");
   mpTabWidget->addTab(mpMetadataPage, "Metadata");

   // Validation label
   mpValidationLabel = new QLabel(this);
   mpValidationLabel->setWordWrap(true);

   QFont validationFont = mpValidationLabel->font();
   validationFont.setBold(true);
   mpValidationLabel->setFont(validationFont);

   // Dialog buttons
   mpOkButton = new QPushButton("&OK", this);
   QPushButton* pCancelButton = new QPushButton("&Cancel", this);

   // Layout
   QLayout* pDataLayout = mpDataPage->layout();
   if (pDataLayout != NULL)
   {
      pDataLayout->setMargin(10);
   }

   QLayout* pFileLayout = mpFilePage->layout();
   if (pFileLayout != NULL)
   {
      pFileLayout->setMargin(10);
   }

   QLayout* pClassificationLayout = mpClassificationPage->layout();
   if (pClassificationLayout != NULL)
   {
      pClassificationLayout->setMargin(10);
   }

   QLayout* pSubsetLayout = mpSubsetPage->layout();
   if (pSubsetLayout != NULL)
   {
      pSubsetLayout->setMargin(10);
   }

   QLayout* pMetadataLayout = mpMetadataPage->layout();
   if (pMetadataLayout != NULL)
   {
      pMetadataLayout->setMargin(10);
   }

   QLayout* pWavelengthsLayout = mpWavelengthsPage->layout();
   if (pWavelengthsLayout != NULL)
   {
      pWavelengthsLayout->setMargin(10);
   }

   QGridLayout* pDatasetLayout = new QGridLayout(pDatasetWidget);
   pDatasetLayout->setMargin(0);
   pDatasetLayout->setSpacing(5);
   pDatasetLayout->addWidget(pDatasetLabel, 0, 0, 1, 2);
   pDatasetLayout->addWidget(mpDatasetTree, 1, 0, 1, 2);
   pDatasetLayout->addWidget(pImportAllButton, 2, 0, Qt::AlignRight);
   pDatasetLayout->addWidget(pImportNoneButton, 2, 1);
   pDatasetLayout->setRowStretch(1, 10);
   pDatasetLayout->setColumnStretch(0, 10);

   QVBoxLayout* pInfoLayout = new QVBoxLayout(pInfoWidget);
   pInfoLayout->setMargin(0);
   pInfoLayout->setSpacing(10);
   pInfoLayout->addWidget(mpClassificationLabel);
   pInfoLayout->addWidget(mpTabWidget, 10);

   QHBoxLayout* pButtonLayout = new QHBoxLayout();
   pButtonLayout->setMargin(0);
   pButtonLayout->setSpacing(5);
   pButtonLayout->addWidget(mpValidationLabel, 10);
   pButtonLayout->addWidget(mpOkButton, 0, Qt::AlignBottom);
   pButtonLayout->addWidget(pCancelButton, 0, Qt::AlignBottom);

   QVBoxLayout* pVBox = new QVBoxLayout(this);
   pVBox->setMargin(10);
   pVBox->setSpacing(10);
   pVBox->addWidget(pSplitter, 10);
   pVBox->addLayout(pButtonLayout);

   // Initialization
   setWindowTitle("Import Options");
   setModal(true);
   resize(700, 450);

   pSplitter->addWidget(pDatasetWidget);
   pSplitter->addWidget(pInfoWidget);

   // Populate the data set tree widget
   QTreeWidgetItem* pSelectItem = NULL;

   QMap<QString, vector<ImportDescriptor*> >::const_iterator fileIter;
   for (fileIter = files.begin(); fileIter != files.end(); ++fileIter)
   {
      // Filename item
      QString filename = fileIter.key();
      if (filename.isEmpty() == true)
      {
         continue;
      }

      QTreeWidgetItem* pFileItem = new QTreeWidgetItem(mpDatasetTree);

      QFileInfo fileInfo(filename);
      pFileItem->setText(0, fileInfo.fileName());
      pFileItem->setIcon(0, style()->standardIcon(QStyle::SP_FileIcon));
      pFileItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
      pFileItem->setToolTip(0, filename);
      pFileItem->setCheckState(0, Qt::Unchecked);

      // Dataset items
      vector<ImportDescriptor*> fileDatasets = fileIter.value();
      vector<ImportDescriptor*> datasets;
      copy(fileDatasets.begin(), fileDatasets.end(), back_inserter(datasets));
      stable_sort(datasets.begin(), datasets.end(), ElementDepthComparitor());

      map<vector<string>, QTreeWidgetItem*> parentPaths;

      vector<ImportDescriptor*>::iterator datasetIter;
      for (datasetIter = datasets.begin(); datasetIter != datasets.end(); ++datasetIter)
      {
         ImportDescriptor* pImportDescriptor = *datasetIter;
         if (pImportDescriptor == NULL)
         {
            continue;
         }

         DataDescriptor* pDescriptor = pImportDescriptor->getDataDescriptor();
         if (pDescriptor == NULL)
         {
            continue;
         }

         const string& name = pDescriptor->getName();
         if (name.empty())
         {
            continue;
         }

         QTreeWidgetItem* pItem = new QTreeWidgetItem(static_cast<QTreeWidget*>(NULL),
            QStringList() << QString::fromStdString(name));
         if (pItem == NULL)
         {
            continue;
         }

         // Tool tip
         pItem->setToolTip(0, QString::fromStdString(name));

         // Check state
         Qt::ItemFlags itemFlags = pItem->flags();
         itemFlags |= Qt::ItemIsUserCheckable;
         pItem->setFlags(itemFlags);

         if (pImportDescriptor->isImported())
         {
            pItem->setCheckState(0, Qt::Checked);

            if (pSelectItem == NULL)
            {
               pSelectItem = pItem;
            }
         }
         else
         {
            pItem->setCheckState(0, Qt::Unchecked);
         }

         // Add to the proper parent
         map<vector<string>, QTreeWidgetItem*>::iterator parent = parentPaths.find(pDescriptor->getParentDesignator());
         if (parent != parentPaths.end())
         {
            parent->second->addChild(pItem);
         }
         else
         {
            pFileItem->addChild(pItem);
         }

         vector<string> myDesignator = pDescriptor->getParentDesignator();
         myDesignator.push_back(pDescriptor->getName());
         parentPaths[myDesignator] = pItem;

         mDatasets[pImportDescriptor] = pItem;
         validateDataset(pDescriptor);
         enforceSelections(pItem);
      }
   }

   mpDatasetTree->expandAll();

   // Update the tab widget for the selected data set
   if (pSelectItem == NULL)
   {
      // No data set is set to import by default so select the first data set in the tree widget
      for (int i = 0; i < mpDatasetTree->topLevelItemCount() && pSelectItem == NULL; ++i)
      {
         QTreeWidgetItem* pParentItem = mpDatasetTree->topLevelItem(i);
         if ((pParentItem != NULL) && (pParentItem->childCount() > 0))
         {
            pSelectItem = pParentItem->child(0);
         }
      }
   }

   if (pSelectItem != NULL)
   {
      mpDatasetTree->setItemSelected(pSelectItem, true);
      updateEditDataset();
   }

   // Connections
   VERIFYNR(connect(mpDatasetTree, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this,
      SLOT(datasetItemChanged(QTreeWidgetItem*))));
   VERIFYNR(connect(mpDatasetTree, SIGNAL(itemSelectionChanged()), this, SLOT(updateEditDataset())));
   VERIFYNR(connect(pImportAllButton, SIGNAL(clicked()), this, SLOT(selectAllDatasets())));
   VERIFYNR(connect(pImportNoneButton, SIGNAL(clicked()), this, SLOT(deselectAllDatasets())));
   VERIFYNR(connect(mpOkButton, SIGNAL(clicked()), this, SLOT(accept())));
   VERIFYNR(connect(pCancelButton, SIGNAL(clicked()), this, SLOT(reject())));
   updateConnections(true);
}
예제 #13
0
vector<ImportDescriptor*> SampleHdf4Importer::getImportDescriptors(const string& filename)
{
   vector<ImportDescriptor*> descriptors;

   Hdf4File parsedFile(filename);
   bool bSuccess = getFileData(parsedFile);
   if (bSuccess == true)
   {
      const Hdf4Dataset* pDataset =
         dynamic_cast<const Hdf4Dataset*>(parsedFile.getRootGroup()->getElement("EV_500_RefSB"));
      if ((pDataset != NULL) && (mpModel.get() != NULL))
      {
         Hdf4FileResource pFile(filename.c_str());
         if (pFile.get() != NULL)
         {
            ImportDescriptor* pImportDescriptor = mpModel->createImportDescriptor(filename, "RasterElement", NULL);
            if (pImportDescriptor != NULL)
            {
               RasterDataDescriptor* pDescriptor =
                  dynamic_cast<RasterDataDescriptor*>(pImportDescriptor->getDataDescriptor());
               if (pDescriptor != NULL)
               {
                  FactoryResource<RasterFileDescriptor> pFileDescriptor;
                  if (pFileDescriptor.get() != NULL)
                  {
                     int32 numDims = 0;
                     int32 dataType = 0;
                     int32 numAttr = 0;

                     pFileDescriptor->setFilename(filename);

                     Hdf4DatasetResource pDataHandle(*pFile, pDataset->getName().c_str());
                     int32 dimSizes[MAX_VAR_DIMS] = {0};
                     if (pDataHandle != NULL && *pDataHandle != FAIL)
                     {
                        pFileDescriptor->setDatasetLocation(pDataset->getName());

                        int32 success = SDgetinfo(*pDataHandle, const_cast<char*>(pDataset->getName().c_str()),
                                                  &numDims, dimSizes, &dataType, &numAttr);
                        // find out what type this Dataset is
                        string strDataType = hdf4TypeToString(dataType, 1);
                        if (success == SUCCEED && numDims == 3 && strDataType == "unsigned short")
                        {
                           // Bands
                           vector<DimensionDescriptor> bands =
                              RasterUtilities::generateDimensionVector(dimSizes[0], true, false, true);

                           pDescriptor->setBands(bands);
                           pFileDescriptor->setBands(bands);

                           // Rows
                           vector<DimensionDescriptor> rows =
                              RasterUtilities::generateDimensionVector(dimSizes[1], true, false, true);

                           pDescriptor->setRows(rows);
                           pFileDescriptor->setRows(rows);

                           // Columns
                           vector<DimensionDescriptor> columns =
                              RasterUtilities::generateDimensionVector(dimSizes[2], true, false, true);

                           pDescriptor->setColumns(columns);
                           pFileDescriptor->setColumns(columns);
                        }
                     }

                     // Data type
                     EncodingType e;
                     pDataset->getDataEncoding(e);
                     pDescriptor->setDataType(e);
                     pFileDescriptor->setBitsPerElement(pDescriptor->getBytesPerElement() * 8);

                     // Interleave format
                     pDescriptor->setInterleaveFormat(BSQ);
                     pFileDescriptor->setInterleaveFormat(BSQ);

                     // Metadata
                     FactoryResource<DynamicObject> pMetadata;
                     if (pMetadata.get() != NULL)
                     {
                        const Hdf4Dataset::AttributeContainer& attributes = pDataset->getAttributes();
                        for (Hdf4Dataset::AttributeContainer::const_iterator it = attributes.begin();
                           it != attributes.end(); ++it)
                        {
                           Hdf4Attribute* pAttribute = it->second;
                           if (pAttribute != NULL)
                           {
                              const string& name = pAttribute->getName();
                              const DataVariant& var = pAttribute->getVariant();
                              const unsigned short* pValue = var.getPointerToValue<unsigned short>();
                              if (name == "_FillValue" && pValue != NULL)
                              {
                                 // Bad values
                                 vector<int> badValues;
                                 badValues.push_back(*pValue);

                                 pDescriptor->setBadValues(badValues);
                              }
                              else
                              {
                                 pMetadata->setAttribute(name, var);
                              }
                           }
                        }

                        pDescriptor->setMetadata(pMetadata.get());
                     }
                     pDescriptor->setFileDescriptor(pFileDescriptor.get());
                  }
               }

               descriptors.push_back(pImportDescriptor);
            }
         }
      }
   }

   return descriptors;
}
예제 #14
0
vector<ImportDescriptor*> EnviImporter::getImportDescriptors(const string& filename)
{
   string headerFile = filename;
   string dataFile;
   bool bSuccess = parseHeader(headerFile);
   if (bSuccess == false)
   {
      dataFile = filename;           // was passed data file name instead of header file name
      headerFile = findHeaderFile(headerFile);
      if (headerFile.empty() == false)
      {
         bSuccess = parseHeader(headerFile);
      }
   }

   EnviField* pField = NULL;
   vector<ImportDescriptor*> descriptors;
   if (bSuccess == true)
   {
      if (dataFile.empty() == true)  // was passed header file name and now need to find the data file name
      {
         dataFile = findDataFile(headerFile);
      }

      if (dataFile.empty() == false)
      {
         ImportDescriptor* pImportDescriptor = mpModel->createImportDescriptor(dataFile, "RasterElement", NULL);
         if (pImportDescriptor != NULL)
         {
            RasterDataDescriptor* pDescriptor =
               dynamic_cast<RasterDataDescriptor*>(pImportDescriptor->getDataDescriptor());
            if (pDescriptor != NULL)
            {
               FactoryResource<RasterFileDescriptor> pFileDescriptor;
               if (pFileDescriptor.get() != NULL)
               {
                  // Filename
                  pFileDescriptor->setFilename(dataFile);

                  // Coordinate offset
                  int columnOffset = 0;
                  int rowOffset = 0;

                  pField = mFields.find("x start");
                  if (pField != NULL)
                  {
                     // ENVI numbers are 1 based vs Opticks being 0 based
                     columnOffset = atoi(pField->mValue.c_str()) - 1;
                  }

                  pField = mFields.find("y start");
                  if (pField != NULL)
                  {
                     rowOffset = atoi(pField->mValue.c_str()) - 1; // ENVI numbers are 1 based vs Opticks being 0 based
                  }

                  // Rows
                  vector<DimensionDescriptor> rows;
                  pField = mFields.find("lines");
                  if (pField != NULL)
                  {
                     int numRows = atoi(pField->mValue.c_str());
                     for (int i = 0; i < numRows; ++i)
                     {
                        DimensionDescriptor rowDim;
                        rowDim.setOriginalNumber(static_cast<unsigned int>(rowOffset + i));
                        rowDim.setOnDiskNumber(static_cast<unsigned int>(i));
                        rows.push_back(rowDim);
                     }

                     pDescriptor->setRows(rows);
                     pFileDescriptor->setRows(rows);
                  }

                  string samplesStr = "samples";
                  string bandsStr = "bands";

                  // Special case: if the file type is an ENVI Spectral Library, then swap samples with bands
                  // If no file type field exists, assume this is a normal ENVI header (not a Spectral Library)
                  EnviField* pFileTypeField = mFields.find("file type");
                  if (pFileTypeField != NULL && (pFileTypeField->mValue ==
                     "ENVI Spectral Library" || pFileTypeField->mValue == "Spectral Library"))
                  {
                     samplesStr = "bands";
                     bandsStr = "samples";

                     // Since bands and samples are swapped, force the interleave to BIP
                     pField = mFields.find("interleave");
                     if (pField != NULL)
                     {
                        pField->mValue = "bip";
                     }
                  }

                  // Columns
                  vector<DimensionDescriptor> columns;
                  pField = mFields.find(samplesStr);
                  if (pField != NULL)
                  {
                     int numColumns = atoi(pField->mValue.c_str());
                     for (int i = 0; i < numColumns; ++i)
                     {
                        DimensionDescriptor columnDim;
                        columnDim.setOriginalNumber(static_cast<unsigned int>(columnOffset + i));
                        columnDim.setOnDiskNumber(static_cast<unsigned int>(i));
                        columns.push_back(columnDim);
                     }

                     pDescriptor->setColumns(columns);
                     pFileDescriptor->setColumns(columns);
                  }

                  // Bands
                  vector<DimensionDescriptor> bands;
                  pField = mFields.find(bandsStr);
                  if (pField != NULL)
                  {
                     int numBands = atoi(pField->mValue.c_str());
                     bands = RasterUtilities::generateDimensionVector(numBands, true, false, true);
                     pDescriptor->setBands(bands);
                     pFileDescriptor->setBands(bands);
                  }

                  // Description
                  list<GcpPoint> gcps;

                  pField = mFields.find("description");
                  if (pField != NULL)
                  {
                     // Metadata
                     if (pField->mChildren.empty() == false)
                     {
                        FactoryResource<DynamicObject> pMetadata;
                        for (unsigned int i = 0; i < pField->mChildren.size(); ++i)
                        {
                           EnviField* pChild = pField->mChildren[i];
                           if (pChild != NULL)
                           {
                              if (pChild->mTag == "classification")
                              {
                                 // Classification
                                 FactoryResource<Classification> pClassification;
                                 if (pClassification.get() != NULL)
                                 {
                                    string classLevel;
                                    classLevel.append(1, *(pChild->mValue.data()));
                                    pClassification->setLevel(classLevel);

                                    pDescriptor->setClassification(pClassification.get());
                                 }
                              }
                              else if ((pChild->mTag == "ll") || (pChild->mTag == "lr") || (pChild->mTag == "ul") ||
                                 (pChild->mTag == "ur") || (pChild->mTag == "center"))
                              {
                                 GcpPoint gcp;
                                 bool dmsFormat = false;
                                 char ns;
                                 char ew;

                                 sscanf(pChild->mValue.c_str(), "%lg%c %lg%c", &gcp.mCoordinate.mY, &ew,
                                    &gcp.mCoordinate.mX, &ns);
                                 if (fabs(gcp.mCoordinate.mY) > 180.0 || fabs(gcp.mCoordinate.mX) > 90.0)
                                 {
                                    dmsFormat = true;
                                 }

                                 double deg;
                                 double min;
                                 double sec;
                                 if (dmsFormat == true)
                                 {
                                    deg = static_cast<int>(gcp.mCoordinate.mY / 10000.0);
                                    min = static_cast<int>((gcp.mCoordinate.mY - 10000.0 * deg) / 100.0);
                                    sec = gcp.mCoordinate.mY - 10000.0 * deg - 100.0 * min;
                                    gcp.mCoordinate.mY = deg + (min / 60.0) + (sec / 3600.0);
                                 }

                                 if (ew == 'W' || ew == 'w')
                                 {
                                    gcp.mCoordinate.mY = -gcp.mCoordinate.mY;
                                 }

                                 if (dmsFormat)
                                 {
                                    deg = static_cast<int>(gcp.mCoordinate.mX / 10000.0);
                                    min = static_cast<int>((gcp.mCoordinate.mX - 10000.0 * deg) / 100.0);
                                    sec = gcp.mCoordinate.mX - 10000.0 * deg - 100.0 * min;
                                    gcp.mCoordinate.mX = deg + (min / 60.0) + (sec / 3600.0);
                                 }

                                 if (ns == 'S' || ns == 's')
                                 {
                                    gcp.mCoordinate.mX = -gcp.mCoordinate.mX;
                                 }

                                 // ENVI uses a 1-based pixel coordinate system, with each coordinate referring
                                 // to the top-left corner of the pixel, e.g. (1,1) is the top-left
                                 // corner of the pixel in the top-left of the raster cube
                                 // The ENVI pixel coordinate format is described on p. 1126 of the ENVI 4.2 User's Guide
                                 if (pChild->mTag == "ll")
                                 {
                                    gcp.mPixel.mX = 0.0;
                                    gcp.mPixel.mY = 0.0;
                                 }
                                 else if (pChild->mTag == "lr")
                                 {
                                    gcp.mPixel.mX = columns.size() - 1.0;
                                    gcp.mPixel.mY = 0.0;
                                 }
                                 else if (pChild->mTag == "ul")
                                 {
                                    gcp.mPixel.mX = 0.0;
                                    gcp.mPixel.mY = rows.size() - 1.0;
                                 }
                                 else if (pChild->mTag == "ur")
                                 {
                                    gcp.mPixel.mX = columns.size() - 1.0;
                                    gcp.mPixel.mY = rows.size() - 1.0;
                                 }
                                 else if (pChild->mTag == "center")
                                 {
                                    gcp.mPixel.mX = floor((columns.size() - 1.0) / 2.0);
                                    gcp.mPixel.mY = floor((rows.size() - 1.0) / 2.0);
                                 }

                                 gcps.push_back(gcp);
                              }
                              else if (pChild->mTag.empty() == false)
                              {
                                 pMetadata->setAttribute(pChild->mTag, pChild->mValue);
                              }
                           }
                        }

                        if (pMetadata->getNumAttributes() > 0)
                        {
                           pDescriptor->setMetadata(pMetadata.get());
                        }
                     }
                  }

                  if (gcps.empty())  // not in description, check for geo points keyword
                  {
                     pField = mFields.find("geo points");
                     if (pField != NULL)
                     {
                        vector<double> geoValues;
                        const int expectedNumValues = 16;  // 4 values for each of the 4 corners
                        geoValues.reserve(expectedNumValues);
                        for (unsigned int i = 0; i < pField->mChildren.size(); i++)
                        {
                           vectorFromField(pField->mChildren.at(i), geoValues, "%lf");
                        }

                        if (geoValues.size() == expectedNumValues)
                        {
                           vector<double>::iterator iter = geoValues.begin();
                           GcpPoint gcp;
                           while (iter != geoValues.end())
                           {
                              gcp.mPixel.mX = *iter++ - 1.0;  // adjust ref point for ENVI's use of
                              gcp.mPixel.mY = *iter++ - 1.0;  // upper left corner and one-based first pixel
                              gcp.mCoordinate.mX = *iter++;   // GcpPoint has lat as mX and Lon as mY 
                              gcp.mCoordinate.mY = *iter++;   // geo point field has lat then lon value
                              gcps.push_back(gcp);
                           }
                        }
                     }
                  }

                  // GCPs
                  if (gcps.empty() == false)
                  {
                     pFileDescriptor->setGcps(gcps);
                  }

                  // Header bytes
                  pField = mFields.find("header offset");
                  if (pField != NULL)
                  {
                     int headerBytes = atoi(pField->mValue.c_str());
                     pFileDescriptor->setHeaderBytes(static_cast<unsigned int>(headerBytes));
                  }

                  // Data type
                  pField = mFields.find("data type");
                  if (pField != NULL)
                  {
                     vector<EncodingType> validDataTypes;
                     switch (atoi(pField->mValue.c_str()))
                     {
                        case 1:     // char
                           pDescriptor->setDataType(INT1UBYTE);
                           pFileDescriptor->setBitsPerElement(8);
                           
                           // signed char cannot be represented in ENVI header so use the closest thing
                           validDataTypes.push_back(INT1SBYTE);
                           break;

                        case 2:     // short
                           pDescriptor->setDataType(INT2SBYTES);
                           pFileDescriptor->setBitsPerElement(16);
                           break;

                        case 3:     // int
                           pDescriptor->setDataType(INT4SBYTES);
                           pFileDescriptor->setBitsPerElement(32);
                           break;

                        case 4:     // float
                           pDescriptor->setDataType(FLT4BYTES);
                           pFileDescriptor->setBitsPerElement(32);
                           break;

                        case 5:     // double
                           pDescriptor->setDataType(FLT8BYTES);
                           pFileDescriptor->setBitsPerElement(64);
                           break;

                        case 6:     // float complex
                           pDescriptor->setDataType(FLT8COMPLEX);
                           pFileDescriptor->setBitsPerElement(64);
                           break;

                        case 9:     // double complex
                           // not supported
                           break;

                        case 12:    // unsigned short
                           pDescriptor->setDataType(INT2UBYTES);
                           pFileDescriptor->setBitsPerElement(16);
                           break;

                        case 13:    // unsigned int
                           pDescriptor->setDataType(INT4UBYTES);
                           pFileDescriptor->setBitsPerElement(32);
                           break;

                        case 14:    // 64-bit int
                        case 15:    // unsigned 64-bit int
                           // not supported
                           break;

                        case 99:    // integer complex (recognized only by this application)
                           pDescriptor->setDataType(INT4SCOMPLEX);
                           pFileDescriptor->setBitsPerElement(32);
                           break;

                        default:
                           break;
                     }

                     // Bad values
                     EncodingType dataType = pDescriptor->getDataType();
                     if ((dataType != FLT4BYTES) && (dataType != FLT8COMPLEX) && (dataType != FLT8BYTES))
                     {
                        vector<int> badValues;
                        badValues.push_back(0);

                        pDescriptor->setBadValues(badValues);
                     }

                     validDataTypes.push_back(dataType);
                     pDescriptor->setValidDataTypes(validDataTypes);
                  }

                  // Interleave format
                  pField = mFields.find("interleave");
                  if (pField != NULL)
                  {
                     string interleave = StringUtilities::toLower(pField->mValue);
                     if (interleave == "bip")
                     {
                        pDescriptor->setInterleaveFormat(BIP);
                        pFileDescriptor->setInterleaveFormat(BIP);
                     }
                     else if (interleave == "bil")
                     {
                        pDescriptor->setInterleaveFormat(BIL);
                        pFileDescriptor->setInterleaveFormat(BIL);
                     }
                     else if (interleave == "bsq")
                     {
                        pDescriptor->setInterleaveFormat(BSQ);
                        pFileDescriptor->setInterleaveFormat(BSQ);
                     }
                  }

                  // Endian
                  pField = mFields.find("byte order");
                  if (pField != NULL)
                  {
                     int byteOrder = atoi(pField->mValue.c_str());
                     if (byteOrder == 0)
                     {
                        pFileDescriptor->setEndian(LITTLE_ENDIAN_ORDER);
                     }
                     else if (byteOrder == 1)
                     {
                        pFileDescriptor->setEndian(BIG_ENDIAN_ORDER);
                     }
                  }

                  // check for scaling factor
                  pField = mFields.find("reflectance scale factor");
                  if (pField != NULL)
                  {
                     double scalingFactor = 0.0;
                     stringstream scaleStream(pField->mValue);
                     scaleStream >> scalingFactor;
                     if (!scaleStream.fail() && scalingFactor != 0.0)
                     {
                        Units* pUnits = pDescriptor->getUnits();
                        if (pUnits != NULL)
                        {
                           pUnits->setScaleFromStandard(1.0 / scalingFactor);
                           pUnits->setUnitName("Reflectance");
                           pUnits->setUnitType(REFLECTANCE);
                        }
                     }
                  }

                  // Pixel size
                  pField = mFields.find("pixel size");
                  if (pField != NULL)
                  {
                     if (pField->mChildren.size() == 2)
                     {
                        pField = pField->mChildren[0];
                        if (pField != NULL)
                        {
                           double pixelSize = 1.0;
                           if (sscanf(pField->mValue.c_str(), "%g", &pixelSize) == 1)
                           {
                              pDescriptor->setXPixelSize(pixelSize);
                              pFileDescriptor->setXPixelSize(pixelSize);
                           }
                        }

                        pField = pField->mChildren[1];
                        if (pField != NULL)
                        {
                           double pixelSize = 1.0;
                           if (sscanf(pField->mValue.c_str(), "%g", &pixelSize) == 1)
                           {
                              pDescriptor->setYPixelSize(pixelSize);
                              pFileDescriptor->setYPixelSize(pixelSize);
                           }
                        }
                     }
                  }

                  // Default bands
                  pField = mFields.find("default bands");
                  if (pField != NULL)
                  {
                     vector<unsigned int> displayBands;
                     parseDefaultBands(pField, &displayBands);

                     if (displayBands.size() == 1)
                     {
                        DimensionDescriptor grayBand = pFileDescriptor->getOriginalBand(displayBands[0]);

                        pDescriptor->setDisplayBand(GRAY, grayBand);
                        pDescriptor->setDisplayMode(GRAYSCALE_MODE);
                     }
                     else if (displayBands.size() == 3)
                     {
                        DimensionDescriptor redBand = pFileDescriptor->getOriginalBand(displayBands[0]);
                        DimensionDescriptor greenBand = pFileDescriptor->getOriginalBand(displayBands[1]);
                        DimensionDescriptor blueBand = pFileDescriptor->getOriginalBand(displayBands[2]);

                        pDescriptor->setDisplayBand(RED, redBand);
                        pDescriptor->setDisplayBand(GREEN, greenBand);
                        pDescriptor->setDisplayBand(BLUE, blueBand);
                        pDescriptor->setDisplayMode(RGB_MODE);
                     }
                  }

                  // Bad bands
                  pField = mFields.find("bbl");
                  if (pField != NULL)
                  {
                     vector<unsigned int> validBands;
                     parseBbl(pField, validBands);

                     vector<DimensionDescriptor> bandsToLoad;
                     for (vector<unsigned int>::const_iterator iter = validBands.begin();
                        iter != validBands.end();
                        ++iter)
                     {
                        const unsigned int onDiskNumber = *iter;
                        const DimensionDescriptor dim = pFileDescriptor->getOnDiskBand(onDiskNumber);
                        if (dim.isValid())
                        {
                           bandsToLoad.push_back(dim);
                        }
                     }

                     pDescriptor->setBands(bandsToLoad);
                  }

                  DynamicObject* pMetadata = pDescriptor->getMetadata();

                  // Band names
                  pField = mFields.find("band names");
                  if (pField != NULL)
                  {
                     vector<string> bandNames;
                     bandNames.reserve(bands.size());
                     vector<string> strNames;
                     for (vector<EnviField*>::size_type i = 0; i < pField->mChildren.size(); ++i)
                     {
                        strNames = StringUtilities::split(pField->mChildren[i]->mValue, ',');
                        copy(strNames.begin(), strNames.end(), back_inserter(bandNames));
                     }
                     vector<string>::iterator it;
                     for (it = bandNames.begin(); it != bandNames.end(); ++it)
                     {
                        *it = StringUtilities::stripWhitespace(*it);
                     }

                     if (pMetadata != NULL)
                     {
                        string pNamesPath[] = { SPECIAL_METADATA_NAME, BAND_METADATA_NAME,
                           NAMES_METADATA_NAME, END_METADATA_NAME };
                        pMetadata->setAttributeByPath(pNamesPath, bandNames);
                     }
                  }

                  // wavelength units
                  pField = mFields.find("wavelength units");
                  if (pField != NULL)
                  {
                     mWavelengthUnits = strToType(pField->mValue);
                  }

                  // Wavelengths
                  vector<double> centerWavelengths;
                  pField = mFields.find("wavelength");
                  if (pField != NULL)
                  {
                     if ((parseWavelengths(pField, &centerWavelengths) == true) && (pMetadata != NULL))
                     {
                        string pCenterPath[] = { SPECIAL_METADATA_NAME, BAND_METADATA_NAME,
                           CENTER_WAVELENGTHS_METADATA_NAME, END_METADATA_NAME };
                        pMetadata->setAttributeByPath(pCenterPath, centerWavelengths);
                     }
                  }

                  // FWHM
                  pField = mFields.find("fwhm");
                  if (pField != NULL)
                  {
                     vector<double> startWavelengths;
                     vector<double> endWavelengths;

                     if ((parseFwhm(pField, &startWavelengths, &centerWavelengths, &endWavelengths) == true) &&
                        (pMetadata != NULL))
                     {
                        string pStartPath[] = { SPECIAL_METADATA_NAME, BAND_METADATA_NAME,
                           START_WAVELENGTHS_METADATA_NAME, END_METADATA_NAME };
                        pMetadata->setAttributeByPath(pStartPath, startWavelengths);
                        string pEndPath[] = { SPECIAL_METADATA_NAME, BAND_METADATA_NAME,
                           END_WAVELENGTHS_METADATA_NAME, END_METADATA_NAME };
                        pMetadata->setAttributeByPath(pEndPath, endWavelengths);
                     }
                  }

                  // File descriptor
                  pDescriptor->setFileDescriptor(pFileDescriptor.get());
               }
예제 #15
0
bool SioImporter::ensureStatisticsReadProperly(Progress *pProgress, std::ostream& failure)
{
   bool success = true;
   success &= setBatch();
   PlugInArgList* pInList = NULL;
   PlugInArgList* pOutList = NULL;
   isseas(getInputSpecification(pInList) != false, failure);
   isseas(getOutputSpecification(pOutList) != false, failure);
   PlugInArg* pRasterElementArg = NULL;
   isseas(pInList->getArg(Importer::ImportElementArg(), pRasterElementArg) != false, failure);

   string testFilePath = TestUtilities::getTestDataPath() + "tipjul5bands.sio";

   RasterElement* pRasterElement = NULL;
   if (success)
   {
      vector<ImportDescriptor*> descriptors = getImportDescriptors(testFilePath);
      if (descriptors.empty() == false)
      {
         ImportDescriptor* pImportDescriptor = descriptors.front();
         if (pImportDescriptor != NULL)
         {
            DataDescriptor* pDescriptor = pImportDescriptor->getDataDescriptor();
            if (pDescriptor != NULL)
            {
               Service<ModelServices> pModel;
               pRasterElement = dynamic_cast<RasterElement*>(pModel->createElement(pDescriptor));
               if (pRasterElement != NULL)
               {
                  pRasterElementArg->setActualValue(pRasterElement);
               }
            }
         }
      }
   }

   isseas(execute(pInList, pOutList) != false, failure);
   isseas(pRasterElement != NULL, failure);
   if (success)
   {
      RasterDataDescriptor* pDescriptor = dynamic_cast<RasterDataDescriptor*>(pRasterElement->getDataDescriptor());
      isseas(pDescriptor != NULL, failure);

      const vector<DimensionDescriptor>& loadedBands = pDescriptor->getBands();
      isseas(loadedBands.size() == 5, failure);
      int iNumBandsWithStats = 0;
      for (int i = 0; i < 5; ++i)
      {
         // we don't want to do an assert yet... only when we know 4 bands have computed statistics
         Statistics* pStatistics = pRasterElement->getStatistics(loadedBands[i]);
         if (pStatistics != NULL)
         {
            if (pStatistics->areStatisticsCalculated() == true)
            {
               if (success)
               {
                  iNumBandsWithStats++;
               }
            }
         }
      }

      // success of the band computation is dependent on 4 bands with statistics
      isseas(iNumBandsWithStats == 3, failure);
   }
   if (pRasterElement != NULL)
   {
      Service<ModelServices> pModel;
      pModel->destroyElement(pRasterElement);
      pRasterElement = NULL;
   }
   Service<PlugInManagerServices> pPim;
   if (pInList)
   {
      pPim->destroyPlugInArgList(pInList);
   }

   if (pOutList)
   {
      pPim->destroyPlugInArgList(pOutList);
   }

   return success;
}
예제 #16
0
vector<ImportDescriptor*> SioImporter::getImportDescriptors(const string& filename)
{
   vector<ImportDescriptor*> descriptors;
   if (filename.empty() == false)
   {
      // Read the header values
      FileResource pFile(filename.c_str(), "rb");

      SioFile sioFile;
      bool bSuccess = sioFile.deserialize(pFile.get());
      if (bSuccess == false)
      {
         return descriptors;
      }

      if (sioFile.mOriginalVersion == 9)
      {
         mVersion9Sio = true;
      }


      // Create the import descriptor
      ImportDescriptor* pImportDescriptor = mpModel->createImportDescriptor(filename, "RasterElement", NULL);
      if (pImportDescriptor != NULL)
      {
         RasterDataDescriptor* pDescriptor =
            dynamic_cast<RasterDataDescriptor*>(pImportDescriptor->getDataDescriptor());
         if (pDescriptor != NULL)
         {
            FactoryResource<RasterFileDescriptor> pFileDescriptor;
            if (pFileDescriptor.get() != NULL)
            {
               // Filename
               pFileDescriptor->setFilename(filename);

               // Endian
               pFileDescriptor->setEndian(sioFile.mEndian);

               // Rows
               vector<DimensionDescriptor> rows;
               for (int i = 0; i < sioFile.mRows; ++i)
               {
                  DimensionDescriptor rowDim;

                  // Do not set an active number since the user has not selected the rows to load
                  if (static_cast<unsigned int>(i) < sioFile.mOrigRowNumbers.size())
                  {
                     rowDim.setOriginalNumber(sioFile.mOrigRowNumbers[i]);
                  }
                  else
                  {
                     rowDim.setOriginalNumber(i);
                  }

                  rowDim.setOnDiskNumber(i);
                  rows.push_back(rowDim);
               }

               pDescriptor->setRows(rows);
               pFileDescriptor->setRows(rows);

               // Columns
               vector<DimensionDescriptor> columns;
               for (int i = 0; i < sioFile.mColumns; ++i)
               {
                  DimensionDescriptor columnDim;

                  // Do not set an active number since the user has not selected the rows to load
                  if (static_cast<unsigned int>(i) < sioFile.mOrigColumnNumbers.size())
                  {
                     columnDim.setOriginalNumber(sioFile.mOrigColumnNumbers[i]);
                  }
                  else
                  {
                     columnDim.setOriginalNumber(i);
                  }

                  columnDim.setOnDiskNumber(i);
                  columns.push_back(columnDim);
               }

               pDescriptor->setColumns(columns);
               pFileDescriptor->setColumns(columns);

               // Bands
               vector<DimensionDescriptor> bands;
               for (int i = 0; i < (sioFile.mBands - sioFile.mBadBands); ++i)
               {
                  DimensionDescriptor bandDim;
                  // Do not set an active number since the user has not selected the rows to load
                  if (static_cast<unsigned int>(i) < sioFile.mOrigBandNumbers.size())
                  {
                     bandDim.setOriginalNumber(sioFile.mOrigBandNumbers[i]);
                  }
                  else
                  {
                     bandDim.setOriginalNumber(i);
                  }

                  bandDim.setOnDiskNumber(i);
                  bands.push_back(bandDim);
               }

               pDescriptor->setBands(bands);
               pFileDescriptor->setBands(bands);

               // Bits per pixel
               pFileDescriptor->setBitsPerElement(sioFile.mBitsPerElement);

               // Data type
               pDescriptor->setDataType(sioFile.mDataType);
               pDescriptor->setValidDataTypes(vector<EncodingType>(1, sioFile.mDataType));

               // Interleave format
               pDescriptor->setInterleaveFormat(BIP);
               pFileDescriptor->setInterleaveFormat(BIP);

               // Bad values
               if (sioFile.mBadValues.empty() == true)
               {
                  if ((sioFile.mDataType != FLT4BYTES) && (sioFile.mDataType != FLT8COMPLEX) &&
                     (sioFile.mDataType != FLT8BYTES))
                  {
                     vector<int> badValues;
                     badValues.push_back(0);

                     pDescriptor->setBadValues(badValues);
                  }
               }

               // Header bytes
               pFileDescriptor->setHeaderBytes(28);

               // Trailer bytes
               struct stat statBuffer;
               if (stat(filename.c_str(), &statBuffer) == 0)
               {
                  double dataBytes = 28 + (sioFile.mRows * sioFile.mColumns * (sioFile.mBands - sioFile.mBadBands) *
                     (sioFile.mBitsPerElement / 8));
                  pFileDescriptor->setTrailerBytes(static_cast<unsigned int>(statBuffer.st_size - dataBytes));
               }

               // Units
               FactoryResource<Units> pUnits;
               pUnits->setUnitType(sioFile.mUnitType);
               pUnits->setUnitName(sioFile.mUnitName);
               pUnits->setRangeMin(sioFile.mRangeMin);
               pUnits->setRangeMax(sioFile.mRangeMax);
               pUnits->setScaleFromStandard(sioFile.mScale);

               pDescriptor->setUnits(pUnits.get());
               pFileDescriptor->setUnits(pUnits.get());

               // GCPs
               GcpPoint gcpLowerLeft;
               gcpLowerLeft.mPixel.mX = 0.0;
               gcpLowerLeft.mPixel.mY = 0.0;

               GcpPoint gcpLowerRight;
               gcpLowerRight.mPixel.mX = sioFile.mColumns - 1.0;
               gcpLowerRight.mPixel.mY = 0.0;

               GcpPoint gcpUpperLeft;
               gcpUpperLeft.mPixel.mX = 0.0;
               gcpUpperLeft.mPixel.mY = sioFile.mRows - 1.0;

               GcpPoint gcpUpperRight;
               gcpUpperRight.mPixel.mX = sioFile.mColumns - 1.0;
               gcpUpperRight.mPixel.mY = sioFile.mRows - 1.0;

               GcpPoint gcpCenter;
               gcpCenter.mPixel.mX = sioFile.mColumns / 2.0 - 0.5;
               gcpCenter.mPixel.mY = sioFile.mRows / 2.0 - 0.5;

               bool bValidGcps = false;
               for (int i = ORIGINAL_SENSOR; i < INVALID_LAST_ENUM_ITEM_FLAG; ++i)
               {
                  if (sioFile.mParameters[i].eParameter_Initialized == true)
                  {
                     switch (i)
                     {
                        case UPPER_LEFT_CORNER_LAT:
                           if ((sioFile.mVersion == 5) || (sioFile.mVersion == 6))
                           {
                              gcpUpperLeft.mCoordinate.mY = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           else if ((sioFile.mVersion == 7) || (sioFile.mVersion == 8))
                           {
                              gcpUpperLeft.mCoordinate.mX = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           bValidGcps = true;
                           break;

                        case UPPER_LEFT_CORNER_LONG:
                           if ((sioFile.mVersion == 5) || (sioFile.mVersion == 6))
                           {
                              gcpUpperLeft.mCoordinate.mX = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           else if ((sioFile.mVersion == 7) || (sioFile.mVersion == 8))
                           {
                              gcpUpperLeft.mCoordinate.mY = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           bValidGcps = true;
                           break;

                        case LOWER_LEFT_CORNER_LAT:
                           if ((sioFile.mVersion == 5) || (sioFile.mVersion == 6))
                           {
                              gcpLowerLeft.mCoordinate.mY = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           else if ((sioFile.mVersion == 7) || (sioFile.mVersion == 8))
                           {
                              gcpLowerLeft.mCoordinate.mX = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           bValidGcps = true;
                           break;

                        case LOWER_LEFT_CORNER_LONG:
                           if ((sioFile.mVersion == 5) || (sioFile.mVersion == 6))
                           {
                              gcpLowerLeft.mCoordinate.mX = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           else if ((sioFile.mVersion == 7) || (sioFile.mVersion == 8))
                           {
                              gcpLowerLeft.mCoordinate.mY = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           bValidGcps = true;
                           break;

                        case UPPER_RIGHT_CORNER_LAT:
                           if ((sioFile.mVersion == 5) || (sioFile.mVersion == 6))
                           {
                              gcpUpperRight.mCoordinate.mY = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           else if ((sioFile.mVersion == 7) || (sioFile.mVersion == 8))
                           {
                              gcpUpperRight.mCoordinate.mX = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           bValidGcps = true;
                           break;

                        case UPPER_RIGHT_CORNER_LONG:
                           if ((sioFile.mVersion == 5) || (sioFile.mVersion == 6))
                           {
                              gcpUpperRight.mCoordinate.mX = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           else if ((sioFile.mVersion == 7) || (sioFile.mVersion == 8))
                           {
                              gcpUpperRight.mCoordinate.mY = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           bValidGcps = true;
                           break;

                        case LOWER_RIGHT_CORNER_LAT:
                           if ((sioFile.mVersion == 5) || (sioFile.mVersion == 6))
                           {
                              gcpLowerRight.mCoordinate.mY = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           else if ((sioFile.mVersion == 7) || (sioFile.mVersion == 8))
                           {
                              gcpLowerRight.mCoordinate.mX = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           bValidGcps = true;
                           break;

                        case LOWER_RIGHT_CORNER_LONG:
                           if ((sioFile.mVersion == 5) || (sioFile.mVersion == 6))
                           {
                              gcpLowerRight.mCoordinate.mX = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           else if ((sioFile.mVersion == 7) || (sioFile.mVersion == 8))
                           {
                              gcpLowerRight.mCoordinate.mY = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           bValidGcps = true;
                           break;

                        case CENTER_LAT:
                           if ((sioFile.mVersion == 5) || (sioFile.mVersion == 6))
                           {
                              gcpCenter.mCoordinate.mY = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           else if ((sioFile.mVersion == 7) || (sioFile.mVersion == 8))
                           {
                              gcpCenter.mCoordinate.mX = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           bValidGcps = true;
                           break;

                        case CENTER_LONG:
                           if ((sioFile.mVersion == 5) || (sioFile.mVersion == 6))
                           {
                              gcpCenter.mCoordinate.mX = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           else if ((sioFile.mVersion == 7) || (sioFile.mVersion == 8))
                           {
                              gcpCenter.mCoordinate.mY = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           bValidGcps = true;
                           break;

                        default:
                           break;
                     }
                  }
               }

               if (bValidGcps == true)
               {
                  list<GcpPoint> gcps;
                  gcps.push_back(gcpLowerLeft);
                  gcps.push_back(gcpLowerRight);
                  gcps.push_back(gcpUpperLeft);
                  gcps.push_back(gcpUpperRight);
                  gcps.push_back(gcpCenter);

                  pFileDescriptor->setGcps(gcps);
               }

               // Classification
               pDescriptor->setClassification(sioFile.mpClassification.get());

               // Metadata
               pDescriptor->setMetadata(sioFile.mpMetadata.get());

               DynamicObject* pMetadata = pDescriptor->getMetadata();
               if (pMetadata != NULL)
               {
                  vector<double> startWavelengths(sioFile.mStartWavelengths.size());
                  copy(sioFile.mStartWavelengths.begin(), sioFile.mStartWavelengths.end(), startWavelengths.begin());
                  vector<double> endWavelengths(sioFile.mEndWavelengths.size());
                  copy(sioFile.mEndWavelengths.begin(), sioFile.mEndWavelengths.end(), endWavelengths.begin());
                  vector<double> centerWavelengths(sioFile.mCenterWavelengths.size());
                  copy(sioFile.mCenterWavelengths.begin(), sioFile.mCenterWavelengths.end(), centerWavelengths.begin());

                  string pStartPath[] = { SPECIAL_METADATA_NAME, BAND_METADATA_NAME,
                     START_WAVELENGTHS_METADATA_NAME, END_METADATA_NAME };
                  pMetadata->setAttributeByPath(pStartPath, startWavelengths);
                  string pEndPath[] = { SPECIAL_METADATA_NAME, BAND_METADATA_NAME,
                     END_WAVELENGTHS_METADATA_NAME, END_METADATA_NAME };
                  pMetadata->setAttributeByPath(pEndPath, endWavelengths);
                  string pCenterPath[] = { SPECIAL_METADATA_NAME, BAND_METADATA_NAME,
                     CENTER_WAVELENGTHS_METADATA_NAME, END_METADATA_NAME };
                  pMetadata->setAttributeByPath(pCenterPath, centerWavelengths);
               }

               // File descriptor
               pDescriptor->setFileDescriptor(pFileDescriptor.get());
            }
         }

         descriptors.push_back(pImportDescriptor);
      }
   }

   return descriptors;
}