Commit d2c91fe5 authored by Ken Edmundson's avatar Ken Edmundson
Browse files

changed filenames to main.cpp

parent eaabec1a
Loading
Loading
Loading
Loading
+0 −209
Original line number Diff line number Diff line
#include "Isis.h"

#include <cmath>
#include <iostream>

#include <QFile>
#include <QMap>
#include <QPair>
#include <QString>
#include <QTextStream>
#include <QVector>

#include "Camera.h"
#include "Cube.h"
#include "FileList.h"
#include "FileName.h"
#include "Histogram.h"
#include "IException.h"
#include "PiecewisePolynomial.h"
#include "Progress.h"
#include "SpicePosition.h"
#include "SpiceRotation.h"
#include "UserInterface.h"

using namespace std;
using namespace Isis;

QVector< QPair<double, double> > testFit(FileName inCubeFile,
                                         int positionDegree, int positionSegments,
                                         int pointingDegree, int pointingSegments);

void IsisMain() {
  UserInterface &ui = Application::GetUserInterface();

  // Read in the list of cubes to check
  FileList cubeList;
  cubeList.read( ui.GetFileName("FROMLIST") );

  // Get the fit parameters
  int positionDegree = ui.GetInteger("SPKDEGREE");
  int positionSegments = ui.GetInteger("SPKSEGMENTS");
  int pointingDegree = ui.GetInteger("CKDEGREE");
  int pointingSegments = ui.GetInteger("CKSEGMENTS");

  // Setup the map for storing fit quality
  QMap<QString, QVector< QPair<double, double> > > qualityMap;

  // Setup the progress tracker
  Progress cubeProgress;
  cubeProgress.SetMaximumSteps(cubeList.size());
  cubeProgress.CheckStatus();

  // Compute a test fit for each cube
  for (int cubeIndex = 0; cubeIndex < cubeList.size(); cubeIndex++) {
    FileName cubeFileName = cubeList[cubeIndex];
    QVector< QPair<double, double> > fitQuality;
    try {
      cubeProgress.CheckStatus();
      fitQuality = testFit(cubeFileName,
                           positionDegree, positionSegments,
                           pointingDegree, pointingSegments);
    }
    catch(IException &e) {
      QString warning = "**WARNING** Failed checking cube [" + cubeFileName.expanded() + "].";
      std::cerr << warning << std::endl << e.toString() << std::endl;
      continue;
    }
    qualityMap.insert(cubeFileName.expanded(), fitQuality);
  }

  // Open the TO file for writing
  FileName outFileName = ui.GetFileName("TO");
  QFile outFile(outFileName.expanded());
  if (outFile.open(QFile::WriteOnly |QFile::Truncate)) {
    QTextStream outWriter(&outFile);
    // Output the header
    outWriter << "Cube,"
              << "Position Segments,Position Fit Degree,Minimum Position Error,"
              << "Median Position Error,Maximum Position Error,RMS Position Error,"
              << "Mean Position Error,Standard Deviation of Position Error,"
              << "Chebyshev Minimum Position Error,Chebyshev Maximum Position Error,"
              << "Pointing Segments,Pointing Fit Degree,Minimum Pointing Error,"
              << "Median Pointing Error,Maximum Pointing Error,RMS Pointing Error,"
              << "Mean Pointing Error,Standard Deviation of Pointing Error,"
              << "Chebyshev Minimum Pointing Error,Chebyshev Maximum Pointing Error"
              << "\n";
    QList<QString> cubeNames = qualityMap.keys();
    for (int i = 0; i < cubeNames.size(); i++) {
      QString cubeName = cubeNames[i];
      QVector< QPair<double, double> > fitQuality = qualityMap.value(cubeName);
      outWriter << cubeName;
      // Output Position Error Stats
      for (int j = 0; j < fitQuality.size(); j++) {
        outWriter  << "," << toString(fitQuality[j].first);
      }
      // Output Pointing Error Stats
      for (int j = 0; j < fitQuality.size(); j++) {
        outWriter  << "," << toString(fitQuality[j].second);
      }
      outWriter << "\n";
    }
  }
  else {
    QString msg = "Failed opening output file [" + outFileName.expanded() + "].";
    throw IException(IException::Io, msg, _FILEINFO_);
  }
}

/**
 * <p>
 * Computes the position and pointing fit error, then outputs statistics on
 * them. The statistics are output as a vector of pairs. Each element of the
 * vector contains a pair of values for a specific statistic. The first value
 * is the value of the statistic for position error in km. The second value is
 * the value of the statistic for pointing error in radians.
 * </p>
 * <p>
 * The output statistics are:
 * </p>
 * <ol>
 *   <li>Number of Segments</li>
 *   <li>Min Error</li>
 *   <li>Median Error</li>
 *   <li>Maximum Error</li>
 *   <li>RMS Error</li>
 *   <li>Mean Error</li>
 *   <li>Standard Deviation of the Error</li>
 *   <li>Chebyshev Minimum Error</li>
 *   <li>Chebyshev Maximum Error</li>
 * </ol>
 * 
 * @param inCubeFile The cube file to test
 * @param positionDegree The degree of the position fit
 * @param positionSegments The number of segments used in the position fit.
 * @param pointingDegree The degree of the pointing fit
 * @param pointingSegments The number of segments used in the pointing fit.
 * 
 * @return @b QVector<QPair<double,double>> A vector containing pairs of
 *                                          statistic values for the position
 *                                          and pointing error in km and
 *                                          radians respectively.
 */
QVector< QPair<double, double> > testFit(FileName inCubeFile,
                                         int positionDegree, int positionSegments,
                                         int pointingDegree, int pointingSegments) {
  // TODO validate these pointers
  Cube inCube(inCubeFile);
  Camera *inCam = inCube.camera();
  SpicePosition *instPosition = inCam->instrumentPosition();
  SpiceRotation *instRotation = inCam->instrumentRotation();

  // Fit the position
  PiecewisePolynomial positionPoly;
  try {
    positionPoly = instPosition->fitPolynomial(positionDegree, positionSegments);
  }
  catch (IException &e) {
    QString msg = "Failed Fitting Instrument Position.";
    throw IException(e, IException::Unknown, msg, _FILEINFO_);
  }

  // Fit the rotation
  PiecewisePolynomial rotationPoly;
  try {
    rotationPoly = instRotation->fitPolynomial(pointingDegree, pointingSegments);
  }
  catch (IException &e) {
    QString msg = "Failed Fitting Instrument Pointing.";
    throw IException(e, IException::Unknown, msg, _FILEINFO_);
  }

  // Calculate and store the error statistics
  QVector< QPair<double, double> > fitStats;
  Histogram positionHist = instPosition->computeError(positionPoly);
  Histogram rotationHist = instRotation->computeError(rotationPoly);

  // Number of Segments
  fitStats.push_back( QPair<double, double>( positionPoly.segments(), rotationPoly.segments() ) );

  // Fit Degree
  fitStats.push_back( QPair<double, double>( positionPoly.degree(), rotationPoly.degree() ) );

  // Min Error
  fitStats.push_back( QPair<double, double>( positionHist.Minimum(), rotationHist.Minimum() ) );

  // Median Error
  fitStats.push_back( QPair<double, double>( positionHist.Median(), rotationHist.Median() ) );

  // Maximum Error
  fitStats.push_back( QPair<double, double>( positionHist.Maximum(), rotationHist.Maximum() ) );

  // RMS Error
  fitStats.push_back( QPair<double, double>( positionHist.Rms(), rotationHist.Rms() ) );

  // Mean Error
  fitStats.push_back( QPair<double, double>( positionHist.Average(), rotationHist.Average() ) );

  // Standard Deviation of the Error
  fitStats.push_back( QPair<double, double>( positionHist.StandardDeviation(), rotationHist.StandardDeviation() ) );

  // Chebyshev Minimum Error
  fitStats.push_back( QPair<double, double>( positionHist.ChebyshevMinimum(), rotationHist.ChebyshevMinimum() ) );

  // Chebyshev Maximum Error
  fitStats.push_back( QPair<double, double>( positionHist.ChebyshevMaximum(), rotationHist.ChebyshevMaximum() ) );

  return fitStats;
}
+0 −199
Original line number Diff line number Diff line
#include "Isis.h"

#include <QSharedPointer>
#include <QString>

#include "Angle.h"
#include "Camera.h"
#include "CSVReader.h"
#include "Cube.h"
#include "CubeManager.h"
#include "Distance.h"
#include "FileName.h"
#include "ID.h"

#include "IException.h"
#include "iTime.h"
#include "Latitude.h"
#include "LidarControlPoint.h"
#include "LidarData.h"
#include "Longitude.h"
#include "Target.h"
#include "SerialNumberList.h"
#include "UserInterface.h"

using namespace std;
using namespace Isis;


struct LidarCube {
  FileName name;
  QString sn;
  iTime startTime;
  iTime endTime;
};


void IsisMain() {

  UserInterface &ui = Application::GetUserInterface();
  FileName dataFile = ui.GetFileName("FROM");
  SerialNumberList cubeList = SerialNumberList(ui.GetFileName("CUBES"));
  double threshold = ui.GetDouble("THRESHOLD");
  double rangeSigma = ui.GetDouble("POINT_RANGE_SIGMA");

  double latSigma = Isis::Null;
  double lonSigma = Isis::Null;
  double radiusSigma = Isis::Null;

  if (ui.WasEntered("POINT_LATITUDE_SIGMA")) {
    latSigma = ui.GetDouble("POINT_LATITUDE_SIGMA");
  }
  if (ui.WasEntered("POINT_LONGITUDE_SIGMA")) {
    lonSigma = ui.GetDouble("POINT_LONGITUDE_SIGMA");
  }
  if (ui.WasEntered("POINT_RADIUS_SIGMA")) {
    radiusSigma = ui.GetDouble("POINT_RADIUS_SIGMA");
  }

  QList<LidarCube> images;
  
  for (int i = 0; i < cubeList.size(); i++) {
    LidarCube lidarCube;
    QString serialNumber = cubeList.serialNumber(i);
    FileName fileName = FileName(cubeList.fileName(serialNumber));
    Cube cube(fileName);
    
    lidarCube.name = fileName;
    lidarCube.sn = serialNumber;
    std::pair< double, double> startEndTime = cube.camera()->StartEndEphemerisTimes();
    lidarCube.startTime = iTime(startEndTime.first);
    lidarCube.endTime = iTime(startEndTime.second);
    
    images.append(lidarCube);
  }
  
  CSVReader lidarDataFile;
  lidarDataFile.read(dataFile.expanded());
  LidarData lidarDataSet;
  CubeManager cubeMgr;
  Distance  majorAx;
  Distance minorAx;
  Distance polarAx;
  
  // Set up an automatic id generator for the point ids
  ID pointId = ID(ui.GetString("POINTID"));
  
  //Start at 1 because there is a header. TODO actually set a header in lidarDataFile
  for (int i = 1; i < lidarDataFile.rows(); i++) {
    CSVReader::CSVAxis row = lidarDataFile.getRow(i);

    iTime time(row[0]);
    Latitude lat(row[2].toDouble(), Angle::Units::Degrees);
    Longitude lon(row[1].toDouble(), Angle::Units::Degrees);
    Distance radius(row[3].toDouble(), Distance::Units::Kilometers);
    double range = row[4].toDouble();
//     QString quality = row[]; //TODO figure out how/where to find this value
    
    LidarControlPoint *lidarPoint = new LidarControlPoint;
    lidarPoint->SetId(pointId.Next());

    lidarPoint->setTime(time);
    lidarPoint->setRange(range);
    lidarPoint->setSigmaRange(rangeSigma);

    // Just set the point coordinates for now.  We need to wait until we set
    // the target radii to be able to set the coordinate sigmas.  The sigmas
    // will be converted to angles and the target radii are needed to do that.
    SurfacePoint spoint(lat, lon, radius);
    // lidarPoint->SetAprioriSurfacePoint(SurfacePoint(lat, lon, radius));
    
    bool setSurfacePointRadii = true;
      
    for (int j = 0; j < images.size(); j++) {
      Cube *cube = cubeMgr.OpenCube(images[j].name.expanded());
        
      if (cube != NULL) {
          
        Camera *camera = cube->camera();
          
        if (camera != NULL) {
          if (camera->SetGround(spoint)) {
            double samp = camera->Sample();
            double line = camera->Line();
              
            if (samp > 0.5 - threshold   &&   line > 0.5 - threshold
                && samp < camera->Samples() + .5  &&  line < camera->Lines() + .5) {
        
              ControlMeasure *measure = new ControlMeasure;

              measure->SetCoordinate(camera->Sample(), camera->Line()); 
              measure->SetCubeSerialNumber(images[j].sn);

              if (setSurfacePointRadii) {
              // Get the radii and set the radii in the SurfacePoint
                std::vector<Distance>  targetRadii;
                targetRadii = camera->target()->radii();
                majorAx = targetRadii[0];
                minorAx = targetRadii[1];
                polarAx = targetRadii[2];
                setSurfacePointRadii = false;
                spoint.SetSphericalSigmasDistance(
                                     Distance(latSigma, Distance::Units::Meters),
                                     Distance(lonSigma, Distance::Units::Meters),
                                     Distance(radiusSigma, Distance::Units::Meters));
                lidarPoint->SetAprioriSurfacePoint(spoint);
                // if (camera->target()->shape()->hasValidTarget()) {
                //   targetRadii = camera->target()->shape()->targetRadii();
                // }
                // else {
                //   QString msg = "Valid target not defined in shape model ";
                //   throw IException(IException::Unknown, msg, _FILEINFO_);
                // }
                  
                // targid = camera->SpkTargetId();
                // Distance  targetRadii[3];
                // camera0>getDouble(
                // camera->radii(targetRadii);
                // majorAx = targetRadii[0];
                // minorAx = targetRadii[1];
                // polarAx = targetRadii[2];
                // setSurfacePointRadii = false;
              }
          
              lidarPoint->Add(measure);
              if (time >= images[j].startTime && time <= images[j].endTime) {
                QString newSerial = measure->GetCubeSerialNumber();
                lidarPoint->addSimultaneous(newSerial);
              }
            }
          }
        }
        else {
          QString msg = "Unable to create a camera from " + images[j].name.expanded();
          throw IException(IException::Unknown, msg, _FILEINFO_);
        }
      }
      else {
        QString msg = "Unable to open a cube from " + images[j].name.expanded();
        throw IException(IException::Unknown, msg, _FILEINFO_);
      }        
    }
    // end image loop
    
      if (lidarPoint->GetNumMeasures() <= 0 ||
          lidarPoint->snSimultaneous().size() <=0) {
      continue;
    }
    
    lidarDataSet.insert(QSharedPointer<LidarControlPoint>(lidarPoint));
  }

  
  if (ui.GetString("OUTPUTTYPE") == "JSON") {
    lidarDataSet.write(ui.GetFileName("TO"), LidarData::Format::Json);
  }
  else {
    lidarDataSet.write(ui.GetFileName("TO"), LidarData::Format::Binary);
  }
}
+0 −286
Original line number Diff line number Diff line
#include "IsisDebug.h"

#include <fcntl.h>
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

#include <QApplication>
#include <QCoreApplication>
#include <QFontDialog>
#include <QMdiArea>

#include "Application.h"
#include "AdvancedTrackTool.h"
#include "BandTool.h"
#include "BlinkTool.h"
#include "EditTool.h"
#include "EphemeridesPlotTool.h"
#include "FeatureNomenclatureTool.h"
#include "FileName.h"
#include "FileTool.h"
#include "FindTool.h"
#include "Gui.h"
#include "HelpTool.h"
#include "HistogramTool.h"
#include "IString.h"
#include "MatchTool.h"
#include "MeasureTool.h"
#include "PanTool.h"
#include "Preference.h"
#include "PvlGroup.h"
#include "QIsisApplication.h"
#include "RubberBandTool.h"
#include "ScatterPlotTool.h"
#include "SpecialPixelTool.h"
#include "SpatialPlotTool.h"
#include "SpectralPlotTool.h"
#include "SocketThread.h"
#include "StatisticsTool.h"
#include "StereoTool.h"
#include "StretchTool.h"
#include "SunShadowTool.h"
#include "ToolList.h"
#include "ViewportMainWindow.h"
#include "WindowTool.h"
#include "Workspace.h"
#include "ZoomTool.h"

using namespace Isis;

template<typename ToolClass>
ToolClass *createTool(ViewportMainWindow *viewportMainWindow, ToolList *tools) {
  ToolClass *result = new ToolClass(viewportMainWindow);

  tools->append(result);
  ((Tool *)result)->addTo(viewportMainWindow);

  return result;
}

int main(int argc, char *argv[]) {
  Isis::Gui::checkX11();

  // Add the Qt plugin directory to the library path
  FileName qtpluginpath("$ISISROOT/3rdParty/plugins");
  QCoreApplication::addLibraryPath(qtpluginpath.expanded());

  // Check to see if the user wants to force a new window
  int newWindow = -1;
  for (int i = 1; i < argc; i++) {
    if (IString(argv[i]).UpCase() == "-NEW") {
      newWindow = i;
    }
  }

  QString p_socketFile = "/tmp/isis_plotspice_" + Application::UserName();
  if (newWindow < 0) {
    struct sockaddr_un p_socketName;
    p_socketName.sun_family = AF_UNIX;
    strcpy(p_socketName.sun_path, p_socketFile.toLatin1().data());
    int p_socket;

    if (((FileName)p_socketFile).fileExists()) {
      // Create a socket
      if ((p_socket = socket(PF_UNIX, SOCK_STREAM, 0)) >= 0) {
        // Try to connect to the socket
        if ((connect(p_socket, (struct sockaddr *)&p_socketName,
                    sizeof(p_socketName))) >= 0) {
          QString temp;
          /*
           * We need a very uncommon token to use for parsing.
           */
          QChar escape(27);
          for (int i = 1; i < argc; i++) {
            temp += QFileInfo(FileName(argv[i]).expanded()).absoluteFilePath();
            temp += QString(escape);
          }
          temp += "raise";
          // Try to send data to the socket
          if (send(p_socket, temp.toLatin1().data(), temp.size(), 0) >= 0) {
            // Success, the other plotspice will open this file.
            exit(0);
          }
          else {
            QString msg = "Unable to write to socket";
            std::cout << msg << std::endl;
            remove(p_socketFile.toLatin1().data());
          }
        }

        // If the file already exists but we can't connect to it, assume the
        //   socket is no longer running & remove the tmp file...it falls out &
        //   create a new one. This happens if plotspice is not already running.
        else {
          remove(p_socketFile.toLatin1().data());
        }
      }
      else {
        QString msg = "Unable to create socket";
        std::cout << msg << std::endl;
        remove(p_socketFile.toLatin1().data());
      }
    }
  }

  // Creates the plotspice application window
  QIsisApplication *app = new QIsisApplication(argc, argv);
  QApplication::setApplicationName("plotspice");

  // check for forcing of gui style
  PvlGroup &uiPref = Preference::Preferences().findGroup(
                             "UserInterface");
  if (uiPref.hasKeyword("GuiStyle")) {
    QString style = uiPref["GuiStyle"];
    QApplication::setStyle((QString) style);
  }

  ViewportMainWindow *vw = new ViewportMainWindow("plotspice");

  ToolList tools;
  Tool *rubberBandTool = createTool<RubberBandTool>(vw, &tools);

  Tool *fileTool = createTool<FileTool>(vw, &tools);
  vw->permanentToolBar()->addSeparator();

  Tool *bandTool = createTool<BandTool>(vw, &tools);

  Tool *zoomTool = createTool<ZoomTool>(vw, &tools);
  zoomTool->activate(true);
  vw->getMenu("&View")->addSeparator();

  Tool *panTool = createTool<PanTool>(vw, &tools);
  vw->getMenu("&View")->addSeparator();

  Tool *stretchTool = createTool<StretchTool>(vw, &tools);

  Tool *findTool = createTool<FindTool>(vw, &tools);

  Tool *blinkTool = createTool<BlinkTool>(vw, &tools);

  Tool *advancedTrackTool = createTool<AdvancedTrackTool>(vw, &tools);

  Tool *editTool = createTool<EditTool>(vw, &tools);

  Tool *windowTool = createTool<WindowTool>(vw, &tools);

  Tool *measureTool = createTool<MeasureTool>(vw, &tools);

  Tool *sunShadowTool = createTool<SunShadowTool>(vw, &tools);

  Tool *featureNomenclatureTool = createTool<FeatureNomenclatureTool>(vw, &tools);

  Tool *specialPixelTool = createTool<SpecialPixelTool>(vw, &tools);

  Tool *spatialPlotTool = createTool<SpatialPlotTool>(vw, &tools);

  Tool *spectralPlotTool = createTool<SpectralPlotTool>(vw, &tools);

  Tool *scatterPlotTool = createTool<ScatterPlotTool>(vw, &tools);

  Tool *histTool = createTool<HistogramTool>(vw, &tools);

  Tool *statsTool = createTool<StatisticsTool>(vw, &tools);

  Tool *stereoTool = createTool<StereoTool>(vw, &tools);

  Tool *matchTool = createTool<MatchTool>(vw, &tools);
  
  Tool *ephemeridesTool = createTool<EphemeridesPlotTool>(vw, &tools);

  Tool *helpTool = createTool<HelpTool>(vw, &tools);

  // Show the application window & open the cubes
  vw->show();

  bool openingAFileSucceeded = false;
  for (int i = 1; i < argc; i++) {
    if (i != newWindow) {
      try {
        vw->workspace()->addCubeViewport(QString(argv[i]));
        openingAFileSucceeded = true;
      }
      catch (IException &e) {
        e.print();

        // If we're trying to open more later or have opened a file, allow
        //   plotspice to continue running. Otherwise (this if), crash.
        if (i == argc - 1 && !openingAFileSucceeded) {
          // since we intend to exit, we need to cleanup our heap
          // (tools cleaned since they are vw's children)
          delete vw;
          vw = NULL;
          delete app;
          app = NULL;
          return 1;
        }
      }
    }
  }

  SocketThread *temp = NULL;
  // We don't want to start a thread if the user is forcing a new window
  if (newWindow < 0) {
    temp = new SocketThread();
    temp->connect(temp, SIGNAL(newImage(const QString &)),
                  vw->workspace(), SLOT(addCubeViewport(const QString &)));
    temp->connect(temp, SIGNAL(focusApp()), vw, SLOT(raise()));
    temp->start();
  }

  //Connect the editTool to the file tool in order to save and discard changes
  QObject::connect(editTool, SIGNAL(cubeChanged(bool)),
                   fileTool, SLOT(enableSave(bool)));
  QObject::connect(fileTool, SIGNAL(saveChanges(CubeViewport *)),
                   editTool, SLOT(save(CubeViewport *)));
  QObject::connect(fileTool, SIGNAL(discardChanges(CubeViewport *)),
                   editTool, SLOT(undoAll(CubeViewport *)));
  QObject::connect(editTool, SIGNAL(save()), fileTool, SLOT(save()));
  QObject::connect(editTool, SIGNAL(saveAs()), fileTool, SLOT(saveAs()));
  // Connect the FindTool to the AdvancedTrackTool to record the point if the
  // "record" button is clicked
  QObject::connect(findTool, SIGNAL(recordPoint(QPoint)),
                   advancedTrackTool, SLOT(record(QPoint)));

  //Connect the viewport's close signal to the all windows/subwindows
  QObject::connect(vw, SIGNAL(closeWindow()), fileTool, SLOT(exit()));

  int status = app->exec();

  // If we created a thread for listening to plotspice connections, then stop the thread and free its memory
  if (temp) {
    temp->stop();
    temp->wait(); // wait for the stop to finish
    delete temp;

    remove(p_socketFile.toLatin1().data());
  }

  delete panTool;
  delete statsTool;
  delete helpTool;
  delete ephemeridesTool;
  delete matchTool;
  delete stereoTool;
  delete histTool;
  delete spatialPlotTool;
  delete spectralPlotTool;
  delete scatterPlotTool;
  delete specialPixelTool;
  delete featureNomenclatureTool;
  delete sunShadowTool;
  delete measureTool;
  delete windowTool;
  delete advancedTrackTool;
  delete blinkTool;
  delete findTool;
  delete stretchTool;
  delete bandTool;
  delete rubberBandTool;
  delete vw;
  delete app;
  //delete QCoreApplication::instance();
  return status;
}