Example #1
0
void IsisMain() {
  ProcessImportPds p;
  Pvl label;
  UserInterface &ui = Application::GetUserInterface();

  QString labelFile = ui.GetFileName("FROM");
  FileName inFile = ui.GetFileName("FROM");
  QString id;
  Pvl lab(inFile.expanded());

  try {
    id = (QString) lab.findKeyword("DATA_SET_ID");
  }
  catch(IException &e) {
    QString msg = "Unable to read [DATA_SET_ID] from input file [" +
                 inFile.expanded() + "]";
    throw IException(e, IException::Unknown, msg, _FILEINFO_);
  }

  id = id.simplified().trimmed();
  if(id != "TC_MAP" && id != "TCO_MAP") {
    QString msg = "Input file [" + inFile.expanded() + "] does not appear to be " +
                  "in Kaguya Terrain Camera level 2 format. " +
                  "DATA_SET_ID is [" + id + "]";
    throw IException(IException::Unknown, msg, _FILEINFO_);
  }

  p.SetPdsFile(labelFile, "", label);
  Cube *outcube = p.SetOutputCube("TO");

  p.SetOrganization(Isis::ProcessImport::BSQ);

  p.StartProcess();

  // Get the mapping labels
  Pvl otherLabels;
  p.TranslatePdsProjection(otherLabels);

  // Get the directory where the generic pds2isis level 2 translation tables are.
  PvlGroup dataDir(Preference::Preferences().findGroup("DataDirectory"));
  QString transDir = (QString) dataDir["base"] + "/translations/";

  // Translate the Archive group
  FileName transFile(transDir + "pdsImageArchive.trn");
  PvlTranslationManager archiveXlater(label, transFile.expanded());
  archiveXlater.Auto(otherLabels);

  // Write the Archive and Mapping groups to the output cube label
  outcube->putGroup(otherLabels.findGroup("Mapping"));
  outcube->putGroup(otherLabels.findGroup("Archive"));

  // Add the BandBin group
  PvlGroup bbin("BandBin");
  bbin += PvlKeyword("FilterName", "BroadBand");
  bbin += PvlKeyword("Center", "640nm");
  bbin += PvlKeyword("Width", "420nm");
  outcube->putGroup(bbin);

  p.EndProcess();
}
Example #2
0
// Main program
void IsisMain() {
  ProcessImportPds p;
  Pvl pdsLabel;
  UserInterface &ui = Application::GetUserInterface();
  FileName inFile = ui.GetFileName("FROM");

  p.SetPdsFile(inFile.expanded(), "", pdsLabel);

  QString filename = FileName(ui.GetFileName("FROM")).baseName();
  FileName toFile = ui.GetFileName("TO");
  
  apollo = new Apollo(filename);

  utcTime = (QString)pdsLabel["START_TIME"];  
  
  // Setup the output cube attributes for a 16-bit unsigned tiff
  Isis::CubeAttributeOutput cao;
  cao.setPixelType(Isis::Real);
  p.SetOutputCube(toFile.expanded(), cao);

  // Import image
  p.StartProcess();
  p.EndProcess();

  cube.open(toFile.expanded(), "rw");
  
  // Once the image is imported, we need to find and decrypt the code
  if (apollo->IsMetric() && FindCode())
    TranslateCode();
    
  CalculateTransform();
  // Once we have decrypted the code, we need to populate the image labels
  TranslateApolloLabels(filename, &cube);
  cube.close();
}
Example #3
0
void IsisMain() {
  UserInterface &ui = Application::GetUserInterface();

  // Determine whether input is a raw Mariner 10 image or an Isis 2 cube
  bool isRaw = false;
  FileName inputFile = ui.GetFileName("FROM");
  Pvl label(inputFile.expanded());

  // If the PVL created from the input labels is empty, then input is raw
  if(label.groups() + label.objects() + label.keywords() == 0) {
    isRaw = true;
  }

  // Import for RAW files
  if(isRaw) {
    ProcessImport p;

    // All mariner images from both cameras share this size
    p.SetDimensions(832, 700, 1);
    p.SetFileHeaderBytes(968);
    p.SaveFileHeader();
    p.SetPixelType(UnsignedByte);
    p.SetByteOrder(Lsb);
    p.SetDataSuffixBytes(136);

    p.SetInputFile(ui.GetFileName("FROM"));
    Cube *oCube = p.SetOutputCube("TO");

    p.StartProcess();
    unsigned char *header = (unsigned char *) p.FileHeader();
    QString labels = EbcdicToAscii(header);
    UpdateLabels(oCube, labels);
    p.EndProcess();
  }
  // Import for Isis 2 cubes
  else {
    ProcessImportPds p;

    // All mariner images from both cameras share this size
    p.SetDimensions(832, 700, 1);
    p.SetPixelType(UnsignedByte);
    p.SetByteOrder(Lsb);
    p.SetDataSuffixBytes(136);

    p.SetPdsFile(inputFile.expanded(), "", label);
    Cube *oCube = p.SetOutputCube("TO");

    TranslateIsis2Labels(inputFile, oCube);
    p.StartProcess();
    p.EndProcess();
  }
}
Example #4
0
void IsisMain() {
  // Grab the file to import
  UserInterface &ui = Application::GetUserInterface();
  FileName in = ui.GetFileName("FROM");
  FileName out = ui.GetFileName("TO");

  // Make sure it is a Clementine EDR
  bool projected;
  try {
    Pvl lab(in.expanded());
    projected = lab.hasObject("IMAGE_MAP_PROJECTION");
    QString id;
    id = (QString)lab["DATA_SET_ID"];
    id = id.simplified().trimmed();
    if(!id.contains("CLEM")) {
      QString msg = "Invalid DATA_SET_ID [" + id + "]";
      throw IException(IException::Unknown, msg, _FILEINFO_);
    }
  }
  catch(IException &e) {
    QString msg = "Input file [" + in.expanded() +
                  "] does not appear to be " +
                  "in Clementine EDR format";
    throw IException(IException::Unknown, msg, _FILEINFO_);
  }

  //Checks if in file is rdr
  if(projected) {
    QString msg = "[" + in.name() + "] appears to be an rdr file.";
    msg += " Use pds2isis.";
    throw IException(IException::User, msg, _FILEINFO_);
  }

  //Decompress the file
  long int lines = 0;
  long int samps = 0;
  QString filename = in.expanded();
  pdsi = PDSR(filename.toAscii().data(), &lines, &samps);

  ProcessByLine p;
  CubeAttributeOutput cubeAtt("+unsignedByte+1.0:254.0");
  Cube *ocube = p.SetOutputCube(ui.GetFileName("TO"), cubeAtt, pdsi->image_ncols, pdsi->image_nrows);
  p.StartProcess(WriteLine);
  TranslateLabels(in, ocube);
  p.EndProcess();
}
Example #5
0
void IsisMain() {

    //Get user parameters
    UserInterface &ui = Application::GetUserInterface();
    FileName inFile = ui.GetFileName("FROM");
    int numberOfLines = ui.GetInteger("NL");
    int lineOverlap   = ui.GetInteger("OVERLAP");

    //Throws exception if user is dumb
    if(lineOverlap >= numberOfLines) {
        throw IException(IException::User, "The Line Overlap (OVERLAP) must be less than the Number of Lines (LN).", _FILEINFO_);
    }

    //Opens the cube
    Cube cube;
    cube.open(inFile.expanded());

    //Loops through, cropping as desired
    int cropNum = 1;
    int startLine = 1;
    bool hasReachedEndOfCube = false;
    while(startLine <= cube.lineCount()  &&  not hasReachedEndOfCube) {
        //! Sets up the proper paramaters for running the crop program
        QString parameters = "FROM=" + inFile.expanded() +
                             " TO=" + inFile.path() + "/" + inFile.baseName() + ".segment" + toString(cropNum) + ".cub"
                             + " LINE=" + toString(startLine) + " NLINES=";

        if(startLine + numberOfLines > cube.lineCount()) {
            parameters += toString(cube.lineCount() - (startLine - 1));
            hasReachedEndOfCube = true;
        }
        else {
            parameters += toString(numberOfLines);
        }
        ProgramLauncher::RunIsisProgram("crop", parameters);
        //The starting line for next crop
        startLine = 1 + cropNum * (numberOfLines - lineOverlap);
        cropNum++;
    }
}
Example #6
0
  bool FileName::operator==(const FileName &rhs) {
    QString expandedOfThis = expanded();
    QString canonicalOfThis = QFileInfo(expandedOfThis).canonicalFilePath();

    QString expandedOfRhs = rhs.expanded();
    QString canonicalOfRhs = QFileInfo(expandedOfRhs).canonicalFilePath();

    // Cononical file paths return empty strings if the file does not exist. Either both canonicals
    //   are valid and the same (equal is initialized to true), or neither canonical is valid but
    //   the expandeds are the same (equal is set to true when it isn't initialized to true).
    bool equal = (!canonicalOfThis.isEmpty() && canonicalOfThis == canonicalOfRhs);

    if (!equal) {
      equal = (canonicalOfThis.isEmpty() && canonicalOfRhs.isEmpty() &&
               expandedOfThis == expandedOfRhs);
    }

    return equal;
  }
Example #7
0
  /**
   * Construct the importer.
   *
   * @param inputName The name of the input image
   */
  TiffImporter::TiffImporter(FileName inputName) : ImageImporter(inputName) {
    // Open the TIFF image
    m_image = NULL;
    if ((m_image = TIFFOpen(inputName.expanded().toAscii().data(), "r")) == NULL) {
      throw IException(IException::Programmer,
          "Could not open incoming image", _FILEINFO_);
    }

    // Get its constant dimensions.  Note, height seems to get reset to 0 if
    // called before setting width.
    uint32 height;
    TIFFGetField(m_image, TIFFTAG_IMAGELENGTH, &height);
    setLines(height);

    uint32 width;
    TIFFGetField(m_image, TIFFTAG_IMAGEWIDTH, &width);
    setSamples(width);

    TIFFGetField(m_image, TIFFTAG_SAMPLESPERPIXEL, &m_samplesPerPixel);

    // Setup the width and height of the image
    unsigned long imagesize = lines() * samples();
    m_raster = NULL;
    if ((m_raster = (uint32 *) malloc(sizeof(uint32) * imagesize)) == NULL) {
      throw IException(IException::Programmer,
          "Could not allocate enough memory", _FILEINFO_);
    }

    // Read the image into the memory buffer
    if (TIFFReadRGBAImage(m_image, samples(), lines(), m_raster, 0) == 0) {
      throw IException(IException::Programmer,
          "Could not read image", _FILEINFO_);
    }

    // Deal with photometric interpretations
    if (TIFFGetField(m_image, TIFFTAG_PHOTOMETRIC, &m_photo) == 0) {
      throw IException(IException::Programmer,
          "Image has an undefined photometric interpretation", _FILEINFO_);
    }

    setDefaultBands();
  }
Example #8
0
  /**
   * Creates a ControlPointList from a list of control point ids'
   *
   * @param psListFile The file withe list of control point ids'
   */
  ControlPointList::ControlPointList(const FileName &psListFile) {
    try {
      QList<QString> qList;
      FileList list(psListFile);
      int size = list.size();
      for(int i = 0; i < size; i++) {
        qList.insert(i, list[i].toString());
        mbFound.push_back(false);
      }
      mqCpList = QStringList(qList);

      //sort the list for faster searches - internally uses qsort()
      mqCpList.sort();
    }
    catch(IException &e) {
      QString msg = "Can't open or invalid file list [" +
          psListFile.expanded() + "]";
      throw IException(e, IException::User, msg, _FILEINFO_);
    }
  }
Example #9
0
void IsisMain() {

  UserInterface &ui = Application::GetUserInterface();

  FileList addList(ui.GetFileName("ADDLIST"));

  bool log = false;
  FileName logFile;
  if (ui.WasEntered("LOG")) {
    log = true;
    logFile = ui.GetFileName("LOG");
  }
  Pvl results;
  results.setName("cnetadd_Results");
  PvlKeyword added("FilesAdded");
  PvlKeyword omitted("FilesOmitted");
  PvlKeyword pointsModified("PointsModified");

  bool checkMeasureValidity = ui.WasEntered("DEFFILE");
  ControlNetValidMeasure validator;
  if (checkMeasureValidity) {
    Pvl deffile(ui.GetFileName("DEFFILE"));
    validator = ControlNetValidMeasure(deffile);
  }

  SerialNumberList *fromSerials = ui.WasEntered("FROMLIST") ?
    new SerialNumberList(ui.GetFileName("FROMLIST")) : new SerialNumberList();

  ControlNet inNet = ControlNet(ui.GetFileName("CNET"));
  inNet.SetUserName(Application::UserName());
  inNet.SetModifiedDate(iTime::CurrentLocalTime()); //This should be done in ControlNet's Write fn

  QString retrievalOpt = ui.GetString("RETRIEVAL");
  PvlKeyword duplicates("DupSerialNumbers");
  if (retrievalOpt == "REFERENCE") {
    FileList list1(ui.GetFileName("FROMLIST"));
    SerialNumberList addSerials(ui.GetFileName("ADDLIST"));

    //Check for duplicate files in the lists by serial number
    for (int i = 0; i < addSerials.Size(); i++) {

      // Check for duplicate SNs accross the lists
      if (fromSerials->HasSerialNumber(addSerials.SerialNumber(i))) {
        duplicates.addValue(addSerials.FileName(i));
      }

      // Check for duplicate SNs within the addlist
      for (int j = i + 1; j < addSerials.Size(); j++) {
        if (addSerials.SerialNumber(i) == addSerials.SerialNumber(j)) {
          QString msg = "Add list files [" + addSerials.FileName(i) + "] and [";
          msg += addSerials.FileName(j) + "] share the same serial number.";
          throw IException(IException::User, msg, _FILEINFO_);
        }
      }
    }

    // Get the lat/long coords from the existing reference measure
    setControlPointLatLon(*fromSerials, inNet);
  }
  else {
    for (int cp = 0; cp < inNet.GetNumPoints(); cp++) {
      // Get the surface point from the current control point
      ControlPoint *point = inNet.GetPoint(cp);
      SurfacePoint surfacePoint = point->GetBestSurfacePoint();

      if (!surfacePoint.Valid()) {
        QString msg = "Unable to retreive lat/lon from Control Point [";
        msg += point->GetId() + "]. RETREIVAL=POINT cannot be used unless ";
        msg += "all Control Points have Latitude/Longitude keywords.";
        throw IException(IException::User, msg, _FILEINFO_);
      }

      g_surfacePoints[point->GetId()] = surfacePoint;
    }
  }

  FileName outNetFile(ui.GetFileName("ONET"));

  Progress progress;
  progress.SetText("Adding Images");
  progress.SetMaximumSteps(addList.size());
  progress.CheckStatus();

  STRtree coordTree;
  QList<ControlPoint *> pointList;
  bool usePolygon = ui.GetBoolean("POLYGON");
  if (usePolygon) {
    for (int cp = 0; cp < inNet.GetNumPoints(); cp++) {
      ControlPoint *point = inNet.GetPoint(cp);
      SurfacePoint surfacePoint = g_surfacePoints[point->GetId()];

      Longitude lon = surfacePoint.GetLongitude();
      Latitude lat = surfacePoint.GetLatitude();

      Coordinate *coord = new Coordinate(lon.degrees(), lat.degrees());
      Envelope *envelope = new Envelope(*coord);
      coordTree.insert(envelope, point);
    }
  }
  else {
    for (int cp = 0; cp < inNet.GetNumPoints(); cp++) {
      pointList.append(inNet.GetPoint(cp));
    }
  }

  // Loop through all the images
  for (int img = 0; img < addList.size(); img++) {
    Cube cube;
    cube.open(addList[img].toString());
    Pvl *cubepvl = cube.label();
    QString sn = SerialNumber::Compose(*cubepvl);
    Camera *cam = cube.camera();

    // Loop through all the control points
    QList<ControlPoint *> validPoints = usePolygon ?
        getValidPoints(cube, coordTree) : pointList;

    bool imageAdded = false;
    for (int cp = 0; cp < validPoints.size(); cp++) {
      ControlPoint *point = validPoints[cp];

      // If the point is locked and Apriori source is "AverageOfMeasures"
      // then do not add the measures.
      if (point->IsEditLocked() &&
          point->GetAprioriSurfacePointSource() ==
              ControlPoint::SurfacePointSource::AverageOfMeasures) {
        continue;
      }

      if (point->HasSerialNumber(sn)) continue;

      // Only use the surface point's latitude and longitude, rely on the DEM
      // for computing the radius.  We do this because otherwise we will receive
      // inconsistent results from successive runs of this program if the
      // different DEMs are used, or the point X, Y, Z was generated from the
      // ellipsoid.
      SurfacePoint surfacePoint = g_surfacePoints[point->GetId()];
      if (cam->SetGround(
              surfacePoint.GetLatitude(), surfacePoint.GetLongitude())) {

        // Make sure the samp & line are inside the image
        if (cam->InCube()) {
          ControlMeasure *newCm = new ControlMeasure();
          newCm->SetCoordinate(cam->Sample(), cam->Line(), ControlMeasure::Candidate);
          newCm->SetAprioriSample(cam->Sample());
          newCm->SetAprioriLine(cam->Line());
          newCm->SetCubeSerialNumber(sn);
          newCm->SetDateTime();
          newCm->SetChooserName("Application cnetadd");

          // Check the measure for DEFFILE validity
          if (checkMeasureValidity) {
            if (!validator.ValidEmissionAngle(cam->EmissionAngle())) {
              //TODO: log that it was Emission Angle that failed the check
              newCm->SetIgnored(true);
            }
            else if (!validator.ValidIncidenceAngle(cam->IncidenceAngle())) {
              //TODO: log that it was Incidence Angle that failed the check
              newCm->SetIgnored(true);
            }
            else if (!validator.ValidResolution(cam->resolution())) {
              //TODO: log that it was Resolution that failed the check
              newCm->SetIgnored(true);
            }
            else if (!validator.PixelsFromEdge((int)cam->Sample(), (int)cam->Line(), &cube)) {
              //TODO: log that it was Pixels from Edge that failed the check
              newCm->SetIgnored(true);
            }
            else {
              Portal portal(1, 1, cube.pixelType());
              portal.SetPosition(cam->Sample(), cam->Line(), 1);
              cube.read(portal);
              if (!validator.ValidDnValue(portal[0])) {
                //TODO: log that it was DN that failed the check
                newCm->SetIgnored(true);
              }
            }
          }

          point->Add(newCm); // Point takes ownership

          // Record the modified Point and Measure
          g_modifications[point->GetId()].insert(newCm->GetCubeSerialNumber());
          newCm = NULL; // Do not delete because the point has ownership

          if (retrievalOpt == "POINT" && point->GetNumMeasures() == 1)
            point->SetIgnored(false);

          imageAdded = true;
        }
      }
    }

    cubepvl = NULL;
    cam = NULL;

    if (log) {
      PvlKeyword &logKeyword = (imageAdded) ? added : omitted;
      logKeyword.addValue(addList[img].baseName());
    }

    progress.CheckStatus();
  }

  if (log) {
    // Add the list of modified points to the output log file
    QList<QString> modifiedPointsList = g_modifications.keys();
    for (int i = 0; i < modifiedPointsList.size(); i++)
      pointsModified += modifiedPointsList[i];

    results.addKeyword(added);
    results.addKeyword(omitted);
    results.addKeyword(pointsModified);
    if (duplicates.size() > 0) {
      results.addKeyword(duplicates);
    }

    results.write(logFile.expanded());
  }

  // List the modified points
  if (ui.WasEntered("MODIFIEDPOINTS")) {
    FileName pointList(ui.GetFileName("MODIFIEDPOINTS"));

    // Set up the output file for writing
    std::ofstream out_stream;
    out_stream.open(pointList.expanded().toAscii().data(), std::ios::out);
    out_stream.seekp(0, std::ios::beg);   //Start writing from beginning of file

    QList<QString> modifiedPointsList = g_modifications.keys();
    for (int i = 0; i < modifiedPointsList.size(); i++)
      out_stream << modifiedPointsList[i].toStdString() << std::endl;

    out_stream.close();
  }

  // Modify the inNet to only have modified points/measures
  if (ui.GetString("EXTRACT") == "MODIFIED") {
    for (int cp = inNet.GetNumPoints() - 1; cp >= 0; cp--) {
      ControlPoint *point = inNet.GetPoint(cp);

      // If the point was not modified, delete
      // Even get rid of edit locked points in this case
      if (!g_modifications.contains(point->GetId())) {
        point->SetEditLock(false);
        inNet.DeletePoint(cp);
      }
      // Else, remove the unwanted measures from the modified point
      else {
        for (int cm = point->GetNumMeasures() - 1; cm >= 0; cm--) {
          ControlMeasure *measure = point->GetMeasure(cm);

          // Even get rid of edit locked measures in this case
          if (point->GetRefMeasure() != measure &&
              !g_modifications[point->GetId()].contains(
                  measure->GetCubeSerialNumber())) {
            measure->SetEditLock(false);
            point->Delete(cm);
          }
        }
      }
    }
  }

  // Generate the TOLIST if wanted
  if (ui.WasEntered("TOLIST")) {
    SerialNumberList toList;

    SerialNumberList addSerials(ui.GetFileName("ADDLIST"));

    const QList<QString> snList = inNet.GetCubeSerials();
    for (int i = 0; i < snList.size(); i++) {
      QString sn = snList[i];

      if (addSerials.HasSerialNumber(sn))
        toList.Add(addSerials.FileName(sn));
      else if (fromSerials->HasSerialNumber(sn))
        toList.Add(fromSerials->FileName(sn));
    }

    IString name(ui.GetFileName("TOLIST"));
    std::fstream out_stream;
    out_stream.open(name.c_str(), std::ios::out);
    out_stream.seekp(0, std::ios::beg); //Start writing from beginning of file

    for (int f = 0; f < (int) toList.Size(); f++)
      out_stream << toList.FileName(f) << std::endl;

    out_stream.close();
  }

  inNet.Write(outNetFile.expanded());

  delete fromSerials;
}
Example #10
0
void IsisMain ()
{
  ProcessImportPds p;
  Pvl pdsLabel;
  UserInterface &ui = Application::GetUserInterface();

  FileName inFile = ui.GetFileName("FROM");
  QString imageFile("");
  if (ui.WasEntered("IMAGE")) {
    imageFile = ui.GetFileName("IMAGE");
  }


  // Generate the housekeeping filenames
  QString hkLabel("");
  QString hkData("");
  if (ui.WasEntered("HKFROM") ) {
    hkLabel = ui.GetFileName("HKFROM");
  }
  else {
    hkLabel = inFile.originalPath() + "/" + inFile.baseName() + "_HK.LBL";
    // Determine the housekeeping file
    FileName hkFile(hkLabel);
    if (!hkFile.fileExists()) {
      hkFile = hkLabel.replace("_1B_", "_1A_");
      if (hkFile.fileExists()) hkLabel = hkFile.expanded();
    }
  }

  if (ui.WasEntered("HKTABLE")) {
    hkData = ui.GetFileName("HKTABLE");
  }

  QString instid;
  QString missid;

  try {
    Pvl lab(inFile.expanded());
    instid = (QString) lab.findKeyword ("CHANNEL_ID");
    missid = (QString) lab.findKeyword ("INSTRUMENT_HOST_ID");
  }
  catch (IException &e) {
    QString msg = "Unable to read [INSTRUMENT_ID] or [MISSION_ID] from input file [" +
                 inFile.expanded() + "]";
    throw IException(e, IException::Io,msg, _FILEINFO_);
  }

  instid = instid.simplified().trimmed();
  missid = missid.simplified().trimmed();
  if (missid != "DAWN" && instid != "VIS" && instid != "IR") {
    QString msg = "Input file [" + inFile.expanded() + "] does not appear to be a " +
                 "DAWN Visual and InfraRed Mapping Spectrometer (VIR) EDR or RDR file.";
    throw IException(IException::Unknown, msg, _FILEINFO_);
  }

  QString target;
  if (ui.WasEntered("TARGET")) {
    target = ui.GetString("TARGET");
  }

//  p.SetPdsFile (inFile.expanded(),imageFile,pdsLabel);
//  QString labelFile = ui.GetFileName("FROM");
  p.SetPdsFile (inFile.expanded(),imageFile,pdsLabel);
  p.SetOrganization(Isis::ProcessImport::BIP);
  Cube *outcube = p.SetOutputCube ("TO");
//  p.SaveFileHeader();

  Pvl labelPvl (inFile.expanded());

  p.StartProcess ();

  // Get the directory where the DAWN translation tables are.
  PvlGroup dataDir (Preference::Preferences().findGroup("DataDirectory"));
  QString transDir = (QString) dataDir["Dawn"] + "/translations/";

  // Create a PVL to store the translated labels in
  Pvl outLabel;

  // Translate the BandBin group
  FileName transFile (transDir + "dawnvirBandBin.trn");
  PvlTranslationManager bandBinXlater (labelPvl, transFile.expanded());
  bandBinXlater.Auto(outLabel);

  // Translate the Archive group
  transFile = transDir + "dawnvirArchive.trn";
  PvlTranslationManager archiveXlater (labelPvl, transFile.expanded());
  archiveXlater.Auto(outLabel);

  // Translate the Instrument group
  transFile = transDir + "dawnvirInstrument.trn";
  PvlTranslationManager instrumentXlater (labelPvl, transFile.expanded());
  instrumentXlater.Auto(outLabel);

  //  Update target if user specifies it
  if (!target.isEmpty()) {
    PvlGroup &igrp = outLabel.findGroup("Instrument",Pvl::Traverse);
    igrp["TargetName"] = target;
  }

  // Write the BandBin, Archive, and Instrument groups
  // to the output cube label
  outcube->putGroup(outLabel.findGroup("BandBin",Pvl::Traverse));
  outcube->putGroup(outLabel.findGroup("Archive",Pvl::Traverse));
  outcube->putGroup(outLabel.findGroup("Instrument",Pvl::Traverse));

  PvlGroup kerns("Kernels");
  if (instid == "VIS") {
    kerns += PvlKeyword("NaifFrameCode","-203211");
  } else if (instid == "IR") {
    kerns += PvlKeyword("NaifFrameCode","-203213");
  } else {
    QString msg = "Input file [" + inFile.expanded() + "] has an invalid " +
                 "InstrumentId.";
    throw IException(IException::Unknown, msg, _FILEINFO_);
  }
  outcube->putGroup(kerns);

  // Now handle generation of housekeeping data
 try {
   ImportPdsTable hktable(hkLabel, hkData);
   hktable.setType("ScetTimeClock", "CHARACTER");
   hktable.setType("ShutterStatus", "CHARACTER");
   hktable.setType("MirrorSin", "DOUBLE");
   hktable.setType("MirrorCos", "DOUBLE");
   Table hktab = hktable.importTable("ScetTimeClock,ShutterStatus,MirrorSin,MirrorCos",
                                      "VIRHouseKeeping");
   hktab.Label().addKeyword(PvlKeyword("SourceFile", hkLabel));
   outcube->write(hktab);
 }
 catch (IException &e) {
   QString mess = "Cannot read/open housekeeping data";
   throw IException(e, IException::User, mess, _FILEINFO_);
 }

  p.EndProcess ();
}
Example #11
0
int main() {
  Preference::Preferences(true);

  try {

    PvlFormatPds *pdsFormatter;

    // Create a temp file for the keyword to type map
    {
      FileName fname = FileName::createTempFile("tempPvlFormatPDSunitTest_.tmp");
      QString pdsFile = fname.expanded();

      ofstream out;
      out.open(pdsFile.toAscii().data(), std::ios::out);

      {
        PvlKeyword key("skey", "string");
        out << key << endl;
      }
      {
        PvlKeyword key("ikey", "integer");
        out << key << endl;
      }
      {
        PvlKeyword key("fkey2", "rEaL");
        key.addValue(toString(2));
        out << key << endl;
      }
      {
        PvlKeyword key("bkey", "bool");
        out << key << endl;
      }
      {
        PvlKeyword key("fkey0", "real");
        key.addValue(toString(0));
        out << key << endl;
      }
      {
        PvlKeyword key("fkey", "real");
        out << key << endl;
      }
      {
        PvlKeyword key("ekey", "enum");
        out << key << endl;
      }
      {
        PvlKeyword key("hkey0", "hEX");
        out << key << endl;
      }
      {
        PvlKeyword key("hkey2", "hEX");
        key.addValue(toString(2));
        out << key << endl;
      }
      {
        PvlKeyword key("hkey4", "hEX");
        key.addValue(toString(4));
        out << key << endl;
      }
      {
        PvlKeyword key("binkey", "binary");
        key.addValue(toString(7));
        out << key << endl;
      }
      {
        PvlKeyword key("binkey16", "binary");
        key.addValue(toString(16));
        out << key << endl;
      }
      {
        PvlKeyword key("intkeyarray", "integer");
        out << key << endl;
      }
      {
        PvlKeyword key("dblkeyarray", "rEaL");
        key.addValue(toString(2));
        out << key << endl;
      }
      {
        PvlKeyword key("wrapword", "string");
        out << key << endl;
      }
      {
        PvlKeyword key("array", "integer");
        out << key << endl;
      }

      out.close();

      pdsFormatter = new PvlFormatPds(pdsFile);
      QFile::remove(pdsFile);
    }

    // Test Keywords
    {
      PvlKeyword key("skey", "somestringval");
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("skey", "string val", "chars");
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("sNAstring", "N/A");
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("sUNKquote", "\"UNK\"");
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("ssinglequote", "\'NA\'");
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("notinmap", "junk string");
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("myint", "12345");
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("myfloat", toString(-12345.67e+89), "degrees");
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("fkey", toString(-12345.6789));
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("fkey0", toString(-9876.543));
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("fkey0", toString(-9876.543e-99));
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("fkey2", toString(0.123456));
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("fkey2", toString(0.123456), "goofys");
      key.addValue(toString(987.123), "goofys");
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("fkey2", toString(0.123456), "goofys");
      key.addValue(toString(987.123));
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("ekey", "unsigned");
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("myarray", "(12345,\"a short string\",1.234)");
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("hkey0", toString((BigInt)0x123456789abcdeffLL));
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("hkey2", toString(0x7a8b));
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("hkey4", toString(0x1a2b3c4d));
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("binkey", toString(0xA));
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("binkey16", toString(0xffff));
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("intkeyarray", toString(1));
      key.addValue("NULL");
      key.addValue("3");
      key.addValue("NULL");
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("intkeyarray", toString(1), "m");
      key.addValue("NULL", "m");
      key.addValue("3", "m");
      key.addValue("N/A");
      key.addValue("UNK");
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }

    {
      PvlKeyword key("dblkeyarray", toString(1.01));
      key.addValue("NULL");
      key.addValue("3.4");
      key.addValue("UNK");
      cout << key << endl;
      key.setFormat(pdsFormatter);
      cout << key << pdsFormatter->formatEOL();
    }


    // Test Groups
    {
      PvlGroup grp("Group1");
      grp += PvlKeyword("skey", "stringval");
      grp += PvlKeyword("mystring", "string val");
      grp += PvlKeyword("sNULLstring", "NULL");   // should add quotes after format set
      grp += PvlKeyword("sUNKquote", "\"UNK\"");   // should not add more quotes
      grp += PvlKeyword("sNAsingle", "\'N/A\'");   // should not add more quotes
      grp += PvlKeyword("myint", toString(12345));
      grp += PvlKeyword("myfloat", toString(12345.67e+89));
      grp += PvlKeyword("myarray", "(12345,\"a short string\",1.234)");
      cout << "=============================== Before" << endl;
      cout << grp << endl;
      grp.setFormat(pdsFormatter);
      cout << "=============================== After" << endl;
      cout << grp << pdsFormatter->formatEOL();
    }


    // Test Objects
    {
      PvlGroup grp("Group1");
      grp += PvlKeyword("skey", "stringval");
      grp += PvlKeyword("mystring", "string val");
      grp += PvlKeyword("sNULLstring", "NULL");   // should add quotes after format set
      grp += PvlKeyword("sUNKquote", "\"UNK\"");   // should not add more quotes
      grp += PvlKeyword("sNAsingle", "\'N/A\'");   // should not add more quotes
      grp += PvlKeyword("myint", toString(12345));
      grp += PvlKeyword("myfloat", toString(12345.67e+89));
      grp += PvlKeyword("myarray", "(12345,\"a short string\",1.234)");
      PvlObject obj("Object1");
      obj.addGroup(grp);

      PvlObject obj2("Object2");
      obj2 += PvlKeyword("skey", "stringval");
      obj2 += PvlKeyword("mystring", "string val");
      obj2 += PvlKeyword("sNULLstring", "NULL");   // should add quotes after format set
      obj2 += PvlKeyword("sUNKquote", "\"UNK\"");   // should not add more quotes
      obj2 += PvlKeyword("sNAsingle", "\'N/A\'");   // should not add more quotes
      obj2 += PvlKeyword("myint", toString(12345));
      obj2 += PvlKeyword("myfloat", toString(12345.67e+89));
      obj2 += PvlKeyword("myarray", "(12345,\"a short string\",1.234)");
      obj.addObject(obj2);

      obj += PvlKeyword("skey", "stringval");
      obj += PvlKeyword("mystring", "string val");
      obj += PvlKeyword("sNULLstring", "NULL");   // should add quotes after format set
      obj += PvlKeyword("sUNKquote", "\"UNK\"");   // should not add more quotes
      obj += PvlKeyword("sNAsingle", "\'N/A\'");   // should not add more quotes
      obj += PvlKeyword("myint", toString(12345));
      obj += PvlKeyword("myfloat", toString(12345.67e+89));
      obj += PvlKeyword("myarray", "(12345,\"a short string\",1.234)");


      cout << "=============================== Before" << endl;
      cout << obj << endl;
      obj.setFormat(pdsFormatter);
      cout << "=============================== After" << endl;
      cout << obj << pdsFormatter->formatEOL();
    }


    // Test Pvl
    {
      Pvl pvl;

      PvlObject obj("Object1");

      PvlGroup grp("Group1");
      grp += PvlKeyword("skey", "stringval");
      grp += PvlKeyword("mystring", "string val");
      grp += PvlKeyword("sNULLstring", "NULL");   // should add quotes after format set
      grp += PvlKeyword("sUNKquote", "\"UNK\"");   // should not add more quotes
      grp += PvlKeyword("sNAsingle", "\'N/A\'");   // should not add more quotes
      grp += PvlKeyword("myint", toString(12345));
      grp += PvlKeyword("myfloat", toString(12345.67e+89));
      grp += PvlKeyword("myarray", "(12345,\"a short string\",1.234)");
      obj.addGroup(grp);

      PvlObject obj2("Object2");
      obj2 += PvlKeyword("skey", "stringval");
      obj2 += PvlKeyword("mystring", "string val");
      obj2 += PvlKeyword("sNULLstring", "NULL");   // should add quotes after format set
      obj2 += PvlKeyword("sUNKquote", "\"UNK\"");   // should not add more quotes
      obj2 += PvlKeyword("sNAsingle", "\'N/A\'");   // should not add more quotes
      obj2 += PvlKeyword("myint", toString(12345));
      obj2 += PvlKeyword("myfloat", toString(12345.67e+89));
      obj2 += PvlKeyword("myarray", "(12345,\"a short string\",1.234)");
      obj2 += PvlKeyword("binkey16", toString(0x01f0));
      obj.addObject(obj2);

      obj += PvlKeyword("skey", "stringval");
      obj += PvlKeyword("mystring", "string val");
      obj += PvlKeyword("sNULLstring", "NULL");   // should add quotes after format set
      obj += PvlKeyword("sUNKquote", "\"UNK\"");   // should not add more quotes
      obj += PvlKeyword("sNAsingle", "\'N/A\'");   // should not add more quotes
      obj += PvlKeyword("myint", toString(12345));
      obj += PvlKeyword("myfloat", toString(12345.67e+89));
      obj += PvlKeyword("myarray", "(12345,\"a short string\",1.234)");

      pvl += PvlKeyword("skey", "stringval");
      pvl += PvlKeyword("mystring", "string val");
      pvl += PvlKeyword("sNULLstring", "NULL");   // should add quotes after format set
      pvl += PvlKeyword("sUNKquote", "\"UNK\"");   // should not add more quotes
      pvl += PvlKeyword("sNAsingle", "\'N/A\'");   // should not add more quotes
      pvl += PvlKeyword("myint", toString(12345));
      pvl += PvlKeyword("myfloat", toString(12345.67e+89));
      pvl += PvlKeyword("myarray", "(12345,\"a short string\",1.234)");

      pvl.addObject(obj);

      PvlGroup grp2("Group2");
      grp2 += PvlKeyword("skey", "stringval");
      grp2 += PvlKeyword("mystring", "string val");
      grp2 += PvlKeyword("sNULLstring", "NULL");   // should add quotes after format set
      grp2 += PvlKeyword("sUNKquote", "\"UNK\"");   // should not add more quotes
      grp2 += PvlKeyword("sNAsingle", "\'N/A\'");   // should not add more quotes
      grp2 += PvlKeyword("myint", toString(12345));
      grp2 += PvlKeyword("myfloat", toString(12345.67e+89));
      grp2 += PvlKeyword("myarray", "(12345,\"a short string\",1.234)");
      grp2 += PvlKeyword("binkey16", toString(0x8001));
      grp2 += PvlKeyword("wrapword", "The quick brown fox jumped over the lazy duck. "
                               "Repunzel Repunzel let down your hair. The little toy dog is covered with dust,"
                               " but sturdy and staunch he stands; and the little toy soldier is red with rust.");
      PvlKeyword key(PvlKeyword("array", toString(12345)));
      key.addValue(toString(67890));
      key.addValue(toString(12345));
      key.addValue(toString(67890));
      key.addValue(toString(12345));
      key.addValue(toString(67890));
      key.addValue(toString(12345));
      key.addValue(toString(67890));
      key.addValue(toString(12345));
      key.addValue(toString(67890));
      key.addValue(toString(12345));
      key.addValue(toString(67890));
      key.addValue(toString(12345));
      key.addValue(toString(67890));
      key.addValue(toString(12345));
      grp2 += key;
      pvl.addGroup(grp2);


      cout << "=============================== Before" << endl;
      cout << pvl << endl;
      pvl.setFormat(pdsFormatter);
      cout << "=============================== After" << endl;
      cout << pvl << pdsFormatter->formatEOL();
    }


  }
  catch(IException &e) {
    e.print();
  }


}
Example #12
0
// Translate Isis 2 labels into Isis 3 labels.
void TranslateIsis2Labels(FileName &labelFile, Cube *oCube) {
  // Get the directory where the Mariner translation tables are.
  PvlGroup &dataDir = Preference::Preferences().findGroup("DataDirectory");

  // Transfer the instrument group to the output cube
  QString transDir = (QString) dataDir["Mariner10"] + "/translations/";
  Pvl inputLabel(labelFile.expanded());
  FileName transFile;

  transFile = transDir + "mariner10isis2.trn";

  // Get the translation manager ready
  PvlTranslationManager translation(inputLabel, transFile.expanded());
  Pvl *outputLabel = oCube->label();
  translation.Auto(*(outputLabel));

  //Instrument group
  PvlGroup &inst = outputLabel->findGroup("Instrument", Pvl::Traverse);

  PvlKeyword &instrumentId = inst.findKeyword("InstrumentId");
  instrumentId.setValue("M10_VIDICON_" + instrumentId[0]);

  PvlKeyword &targetName = inst.findKeyword("TargetName");
  QString targetTail(targetName[0].mid(1));
  targetTail = targetTail.toLower();
  targetName.setValue(targetName[0].at(0) + targetTail);

  PvlKeyword &startTime = inst.findKeyword("StartTime");
  startTime.setValue(startTime[0].mid(0, startTime[0].size() - 1));

  PvlGroup &archive = outputLabel->findGroup("Archive", Pvl::Traverse);
  PvlKeyword &imgNo = archive.findKeyword("ImageNumber");
  QString ino = imgNo[0];
  ino = ino.trimmed();
  imgNo.setValue(ino);

  iTime time(startTime[0]);
  if(time < iTime("1974-2-3T12:00:00")) {
    archive += PvlKeyword("Encounter", "Moon");
  }
  else if(time < iTime("1974-3-22T12:00:00")) {
    archive += PvlKeyword("Encounter", "Venus");
  }
  else if(time < iTime("1974-9-19T12:00:00")) {
    archive += PvlKeyword("Encounter", "Mercury_1");
  }
  else if(time < iTime("1975-3-14T12:00:00")) {
    archive += PvlKeyword("Encounter", "Mercury_2");
  }
  else {
    archive += PvlKeyword("Encounter", "Mercury_3");
  }

  inst.findKeyword("ExposureDuration").setUnits("milliseconds");

  PvlGroup &bBin = outputLabel->findGroup("BandBin", Pvl::Traverse);
  QString filter = inputLabel.findObject("QUBE")["FILTER_NAME"];
  if(filter != "F") {
    //Band Bin group
    bBin.findKeyword("Center").setUnits("micrometers");
  }

  // Kernels group
  PvlGroup &kernels = outputLabel->findGroup("Kernels", Pvl::Traverse);
  PvlGroup &reseaus = outputLabel->findGroup("Reseaus", Pvl::Traverse);
  PvlKeyword &templ = reseaus.findKeyword("Template");
  PvlKeyword &valid = reseaus.findKeyword("Valid");

  for(int i = 0; i < valid.size(); i++) {
    valid[i] = valid[i].mid(0, 1);
  }

  // Camera dependent information
  QString camera = "";
  if(QString("M10_VIDICON_A") == inst["InstrumentId"][0]) {
    templ = "$mariner10/reseaus/mar10a.template.cub";
    kernels.findKeyword("NaifFrameCode").setValue("-76110");
    camera = "M10_VIDICON_A_RESEAUS";
  }
  else {
    templ = "$mariner10/reseaus/mar10b.template.cub";
    kernels.findKeyword("NaifFrameCode").setValue("-76120");
    camera = "M10_VIDICON_B_RESEAUS";
  }
}
Example #13
0
// Main moccal routine
void IsisMain() {
  // We will be processing by line
  ProcessByLine p;

  // Setup the input and make sure it is a ctx file
  UserInterface &ui = Application::GetUserInterface();

  Isis::Pvl lab(ui.GetFileName("FROM"));
  Isis::PvlGroup &inst =
    lab.findGroup("Instrument", Pvl::Traverse);

  QString instId = inst["InstrumentId"];
  if(instId != "CTX") {
    QString msg = "This is not a CTX image.  Ctxcal requires a CTX image.";
    throw IException(IException::User, msg, _FILEINFO_);
  }

  Cube *icube = p.SetInputCube("FROM", OneBand);

  Cube flatFile;
  if(ui.WasEntered("FLATFILE")) {
    flatFile.open(ui.GetFileName("FLATFILE"));
  }
  else {
    FileName flat = FileName("$mro/calibration/ctxFlat_????.cub").highestVersion();
    flatFile.open(flat.expanded());
  }
  flat = new Brick(5000, 1, 1, flatFile.pixelType());
  flat->SetBasePosition(1, 1, 1);
  flatFile.read(*flat);

  // If it is already calibrated then complain
  if(icube->hasGroup("Radiometry")) {
    QString msg = "The CTX image [" + icube->fileName() + "] has already "
                 "been radiometrically calibrated";
    throw IException(IException::User, msg, _FILEINFO_);
  }

  // Get label parameters we will need for calibration equation
  iTime startTime((QString) inst["StartTime"]);
  double etStart = startTime.Et();

  //  Read exposure and convert to milliseconds
  exposure = inst["LineExposureDuration"];
  //exposure *= 1000.;

  sum = inst["SpatialSumming"];
  //  If firstSamp > 0, adjust by 38 to account for prefix pixels.
  firstSamp = inst["SampleFirstPixel"];
  if(firstSamp > 0) firstSamp -= 38;

  //  Read dark current info, if no dc exit?
  Table dcTable("Ctx Prefix Dark Pixels");
  icube->read(dcTable);
  //  TODO::  make sure dc records match cube nlines.

  //  If summing mode = 1 , average odd & even dc pixels separately for
  //  a & b channels.
  //  If summing mode != 1, average all dc pixels and use for both


  for(int rec = 0; rec < dcTable.Records(); rec++) {
    vector<int> darks = dcTable[rec]["DarkPixels"];

    bool aChannel = true;
    double dcASum = 0.;
    double dcBSum = 0.;
    int dcACount = 0;
    int dcBCount = 0;

    double dcSum = 0;
    int dcCount = 0;

    for(int i = 0; i < (int)darks.size(); i++) {

      if(sum == 1) {
        if(aChannel == true) {
          dcASum += (double)darks.at(i);
          dcACount++;
        }
        else {
          dcBSum += (double)darks.at(i);
          dcBCount++;
        }
        aChannel = !aChannel;
      }
      else if(sum > 1) {
        dcSum += (double)darks.at(i);
        dcCount ++;
      }
    }
    if(sum == 1) {
      dcA.push_back(dcASum / (double)dcACount);
      dcB.push_back(dcBSum / (double)dcBCount);
    }
    else {
      dc.push_back(dcSum / (double)dcCount);
    }
  }

  // See if the user wants counts/ms or i/f
  //    iof = conversion factor from counts/ms to i/f
  bool convertIOF = ui.GetBoolean("IOF");
  if(convertIOF) {
    // Get the distance between Mars and the Sun at the given time in
    // Astronomical Units (AU)
    QString bspKernel = p.MissionData("base", "/kernels/spk/de???.bsp", true);
    furnsh_c(bspKernel.toAscii().data());
    QString pckKernel = p.MissionData("base", "/kernels/pck/pck?????.tpc", true);
    furnsh_c(pckKernel.toAscii().data());
    double sunpos[6], lt;
    spkezr_c("sun", etStart, "iau_mars", "LT+S", "mars", sunpos, &lt);
    double dist1 = vnorm_c(sunpos);
    unload_c(bspKernel.toAscii().data());
    unload_c(pckKernel.toAscii().data());

    double dist = 2.07E8;
    double w0 = 3660.5;
    double w1 = w0 * ((dist * dist) / (dist1 * dist1));
    if(exposure *w1 == 0.0) {
      QString msg = icube->fileName() + ": exposure or w1 has value of 0.0 ";
      throw IException(IException::User, msg, _FILEINFO_);
    }
    iof = 1.0 / (exposure * w1);
  }
  else {
    iof = 1.0;
  }

  // Setup the output cube
  Cube *ocube = p.SetOutputCube("TO");

  // Add the radiometry group
  PvlGroup calgrp("Radiometry");

  calgrp += PvlKeyword("FlatFile", flatFile.fileName());
  calgrp += PvlKeyword("iof", toString(iof));


  ocube->putGroup(calgrp);

  // Start the line-by-line calibration sequence
  p.StartProcess(Calibrate);
  p.EndProcess();

}
Example #14
0
void IsisMain() {
  const QString caminfo_program  = "caminfo";
  UserInterface &ui = Application::GetUserInterface();

  QList< QPair<QString, QString> > *general = NULL, *camstats = NULL, *statistics = NULL;
  BandGeometry *bandGeom = NULL;

  // Get input filename
  FileName in = ui.GetFileName("FROM");

  // Get the format
  QString sFormat = ui.GetAsString("FORMAT");

  // if true then run spiceinit, xml default is FALSE
  // spiceinit will use system kernels
  if(ui.GetBoolean("SPICE")) {
    QString parameters = "FROM=" + in.expanded();
    ProgramLauncher::RunIsisProgram("spiceinit", parameters);
  }

  Process p;
  Cube *incube = p.SetInputCube("FROM");

  // General data gathering
  general = new QList< QPair<QString, QString> >;
  general->append(MakePair("Program",     caminfo_program));
  general->append(MakePair("IsisVersion", Application::Version()));
  general->append(MakePair("RunDate",     iTime::CurrentGMT()));
  general->append(MakePair("IsisId",      SerialNumber::Compose(*incube)));
  general->append(MakePair("From",        in.baseName() + ".cub"));
  general->append(MakePair("Lines",       toString(incube->lineCount())));
  general->append(MakePair("Samples",     toString(incube->sampleCount())));
  general->append(MakePair("Bands",       toString(incube->bandCount())));

  // Run camstats on the entire image (all bands)
  // another camstats will be run for each band and output
  // for each band.
  if(ui.GetBoolean("CAMSTATS")) {
    camstats = new QList< QPair<QString, QString> >;

    QString filename = ui.GetAsString("FROM");
    int sinc = ui.GetInteger("SINC");
    int linc = ui.GetInteger("LINC");
    CameraStatistics stats(filename, sinc, linc);
    Pvl camPvl = stats.toPvl();

    PvlGroup cg = camPvl.findGroup("Latitude", Pvl::Traverse);
    camstats->append(MakePair("MinimumLatitude", cg["latitudeminimum"][0]));
    camstats->append(MakePair("MaximumLatitude", cg["latitudemaximum"][0]));

    cg = camPvl.findGroup("Longitude", Pvl::Traverse);
    camstats->append(MakePair("MinimumLongitude", cg["longitudeminimum"][0]));
    camstats->append(MakePair("MaximumLongitude", cg["longitudemaximum"][0]));

    cg = camPvl.findGroup("Resolution", Pvl::Traverse);
    camstats->append(MakePair("MinimumResolution", cg["resolutionminimum"][0]));
    camstats->append(MakePair("MaximumResolution", cg["resolutionmaximum"][0]));

    cg = camPvl.findGroup("PhaseAngle", Pvl::Traverse);
    camstats->append(MakePair("MinimumPhase", cg["phaseminimum"][0]));
    camstats->append(MakePair("MaximumPhase", cg["phasemaximum"][0]));

    cg = camPvl.findGroup("EmissionAngle", Pvl::Traverse);
    camstats->append(MakePair("MinimumEmission", cg["emissionminimum"][0]));
    camstats->append(MakePair("MaximumEmission", cg["emissionmaximum"][0]));

    cg = camPvl.findGroup("IncidenceAngle", Pvl::Traverse);
    camstats->append(MakePair("MinimumIncidence", cg["incidenceminimum"][0]));
    camstats->append(MakePair("MaximumIncidence", cg["incidencemaximum"][0]));

    cg = camPvl.findGroup("LocalSolarTime", Pvl::Traverse);
    camstats->append(MakePair("LocalTimeMinimum", cg["localsolartimeMinimum"][0]));
    camstats->append(MakePair("LocalTimeMaximum", cg["localsolartimeMaximum"][0]));
  }

  // Compute statistics for entire cube
  if(ui.GetBoolean("STATISTICS")) {
    statistics = new QList< QPair<QString, QString> >;

    LineManager iline(*incube);
    Statistics stats;
    Progress progress;
    progress.SetText("Statistics...");
    progress.SetMaximumSteps(incube->lineCount()*incube->bandCount());
    progress.CheckStatus();
    iline.SetLine(1);
    for(; !iline.end() ; iline.next()) {
      incube->read(iline);
      stats.AddData(iline.DoubleBuffer(), iline.size());
      progress.CheckStatus();
    }

    //  Compute stats of entire cube
    double nPixels     = stats.TotalPixels();
    double nullpercent = (stats.NullPixels() / (nPixels)) * 100;
    double hispercent  = (stats.HisPixels() / (nPixels)) * 100;
    double hrspercent  = (stats.HrsPixels() / (nPixels)) * 100;
    double lispercent  = (stats.LisPixels() / (nPixels)) * 100;
    double lrspercent  = (stats.LrsPixels() / (nPixels)) * 100;

    // Statitics output for band
    statistics->append(MakePair("MeanValue", toString(stats.Average())));
    statistics->append(MakePair("StandardDeviation", toString(stats.StandardDeviation())));
    statistics->append(MakePair("MinimumValue", toString(stats.Minimum())));
    statistics->append(MakePair("MaximumValue", toString(stats.Maximum())));
    statistics->append(MakePair("PercentHIS", toString(hispercent)));
    statistics->append(MakePair("PercentHRS", toString(hrspercent)));
    statistics->append(MakePair("PercentLIS", toString(lispercent)));
    statistics->append(MakePair("PercentLRS", toString(lrspercent)));
    statistics->append(MakePair("PercentNull", toString(nullpercent)));
    statistics->append(MakePair("TotalPixels", toString(stats.TotalPixels())));
  }

  bool getFootBlob = ui.GetBoolean("USELABEL");
  bool doGeometry = ui.GetBoolean("GEOMETRY");
  bool doPolygon = ui.GetBoolean("POLYGON");
  if(doGeometry || doPolygon || getFootBlob) {
    Camera *cam = incube->camera();

    QString incType = ui.GetString("INCTYPE");
    int polySinc, polyLinc;
    if(doPolygon && incType.toUpper() == "VERTICES") {
      ImagePolygon poly;
      poly.initCube(*incube);
      polySinc = polyLinc = (int)(0.5 + (((poly.validSampleDim() * 2) +
                                 (poly.validLineDim() * 2) - 3.0) /
                                 ui.GetInteger("NUMVERTICES")));
    }
    else if (incType.toUpper() == "LINCSINC"){
      if(ui.WasEntered("POLYSINC")) {
        polySinc = ui.GetInteger("POLYSINC");
      }
      else {
        polySinc = (int)(0.5 + 0.10 * incube->sampleCount());
        if(polySinc == 0) polySinc = 1;
      }
      if(ui.WasEntered("POLYLINC")) {
        polyLinc = ui.GetInteger("POLYLINC");
      }
      else {
        polyLinc = (int)(0.5 + 0.10 * incube->lineCount());
        if(polyLinc == 0) polyLinc = 1;
      }
    }
    else {
      QString msg = "Invalid INCTYPE option[" + incType + "]";
      throw IException(IException::Programmer, msg, _FILEINFO_);
    }

    bandGeom = new BandGeometry();
    bandGeom->setSampleInc(polySinc);
    bandGeom->setLineInc(polyLinc);
    bandGeom->setMaxIncidence(ui.GetDouble("MAXINCIDENCE"));
    bandGeom->setMaxEmission(ui.GetDouble("MAXEMISSION"));
    bool precision = ui.GetBoolean("INCREASEPRECISION");

    if (getFootBlob) {
      // Need to read history to obtain parameters that were used to
      // create the footprint
      History hist("IsisCube", in.expanded());
      Pvl pvl = hist.ReturnHist();
      PvlObject::PvlObjectIterator objIter;
      bool found = false;
      PvlGroup fpgrp;
      for (objIter=pvl.endObject()-1; objIter>=pvl.beginObject(); objIter--) {
        if (objIter->name().toUpper() == "FOOTPRINTINIT") {
          found = true;
          fpgrp = objIter->findGroup("UserParameters");
          break;
        }
      }
      if (!found) {
        QString msg = "Footprint blob was not found in input image history";
        throw IException(IException::User, msg, _FILEINFO_);
      }
      QString prec = (QString)fpgrp.findKeyword("INCREASEPRECISION");
      prec = prec.toUpper();
      if (prec == "TRUE") {
        precision = true;
      }
      else {
        precision = false;
      }
      QString inctype = (QString)fpgrp.findKeyword("INCTYPE");
      inctype = inctype.toUpper();
      if (inctype == "LINCSINC") {
        int linc = fpgrp.findKeyword("LINC");
        int sinc = fpgrp.findKeyword("SINC");
        bandGeom->setSampleInc(sinc);
        bandGeom->setLineInc(linc);
      }
      else {
        int vertices = fpgrp.findKeyword("NUMVERTICES");
        int lincsinc = (int)(0.5 + (((incube->sampleCount() * 2) +
                       (incube->lineCount() * 2) - 3.0) /
                       vertices));
        bandGeom->setSampleInc(lincsinc);
        bandGeom->setLineInc(lincsinc);
      }
      if (fpgrp.hasKeyword("MAXINCIDENCE")) {
        double maxinc = fpgrp.findKeyword("MAXINCIDENCE");
        bandGeom->setMaxIncidence(maxinc);
      }
      if (fpgrp.hasKeyword("MAXEMISSION")) {
        double maxema = fpgrp.findKeyword("MAXEMISSION");
        bandGeom->setMaxEmission(maxema);
      }
    }
    
    bandGeom->collect(*cam, *incube, doGeometry, doPolygon, getFootBlob, precision);

    // Check if the user requires valid image center geometry
    if(ui.GetBoolean("VCAMERA") && (!bandGeom->hasCenterGeometry())) {
      QString msg = "Image center does not project in camera model";
      throw IException(IException::Unknown, msg, _FILEINFO_);
    }
  }

  if(sFormat.toUpper() == "PVL")
    GeneratePVLOutput(incube, general, camstats, statistics, bandGeom);
  else
    GenerateCSVOutput(incube, general, camstats, statistics, bandGeom);

  // Clean the data
  delete general;
  general = NULL;
  if(camstats) {
    delete camstats;
    camstats = NULL;
  }
  if(statistics) {
    delete statistics;
    statistics = NULL;
  }
  if(bandGeom) {
    delete bandGeom;
    bandGeom = NULL;
  }

}
Example #15
0
void TranslateLabels(FileName in, Cube *ocube) {
  // Get the directory where the Clementine translation tables are.
  PvlGroup &dataDir = Preference::Preferences().findGroup("DataDirectory");

  // Transfer the instrument group to the output cube
  QString transDir = (QString) dataDir["clementine1"];
  FileName transFile(transDir + "/translations/clementine.trn");

  Pvl pdsLab(in.expanded());
  PvlTranslationManager labelXlater(pdsLab, transFile.expanded());

  // Pvl outputLabels;
  Pvl *outputLabel = ocube->label();
  labelXlater.Auto(*(outputLabel));

  //Instrument group
  PvlGroup inst = outputLabel->findGroup("Instrument", Pvl::Traverse);

  PvlKeyword &startTime = inst.findKeyword("StartTime");
  startTime.setValue(startTime[0].mid(0, startTime[0].size() - 1));

  // Old PDS labels used keyword INSTRUMENT_COMPRESSION_TYPE & PDS Labels now use ENCODING_TYPE
  if(pdsLab.findObject("Image").hasKeyword("InstrumentCompressionType")) {
    inst += PvlKeyword("EncodingFormat", (QString) pdsLab.findObject("Image")["InstrumentCompressionType"]);
  }
  else {
    inst += PvlKeyword("EncodingFormat", (QString) pdsLab.findObject("Image")["EncodingType"]);
  }

  if(((QString)inst["InstrumentId"]) == "HIRES") {
    inst += PvlKeyword("MCPGainModeID", (QString)pdsLab["MCP_Gain_Mode_ID"], "");
  }

  ocube->putGroup(inst);

  PvlGroup bBin = outputLabel->findGroup("BandBin", Pvl::Traverse);
  QString filter = pdsLab["FilterName"];
  if(filter != "F") {
    //Band Bin group
    double center = pdsLab["CenterFilterWavelength"];
    center /= 1000.0;
    bBin.findKeyword("Center").setValue(toString(center), "micrometers");
  }
  double width = pdsLab["Bandwidth"];
  width /= 1000.0;
  bBin.findKeyword("Width").setValue(toString(width), "micrometers");
  ocube->putGroup(bBin);

  //Kernel group
  PvlGroup kern("Kernels");
  if(((QString)inst["InstrumentId"]) == "HIRES") {
    kern += PvlKeyword("NaifFrameCode", "-40001");
  }
  if(((QString)inst["InstrumentId"]) == "UVVIS") {
    kern += PvlKeyword("NaifFrameCode", "-40002");
  }
  if(((QString)inst["InstrumentId"]) == "NIR") {
    kern += PvlKeyword("NaifFrameCode", "-40003");
  }
  if(((QString)inst["InstrumentId"]) == "LWIR") {
    kern += PvlKeyword("NaifFrameCode", "-40004");
  }
  ocube->putGroup(kern);

  OriginalLabel org(pdsLab);
  ocube->write(org);
}
Example #16
0
void IsisMain () {
    Pvl pdsLab;

    FileList list;
    UserInterface &ui = Application::GetUserInterface();
    list.read(ui.GetFileName("FROMLIST"));

    if (list.size() < 1) {
        QString msg = "The list file [" + ui.GetFileName("FROMLIST") + "does not contain any data";
        throw IException(IException::User, msg, _FILEINFO_);
    }

    g_productVersionId = ui.GetString("VERSIONIDSTRING");

    for (int i = 0; i < list.size(); i++) {

        Pvl tempPvl;
        tempPvl.read(list[i].toString());

        OriginalLabel origLab(list[i].toString());
        pdsLab = origLab.ReturnLabels();

        QString prodId = pdsLab["PRODUCT_ID"][0];
        if (productId == "")
            productId = prodId;

        if (productId != prodId) {
            QString msg = "This program is intended for use on a single LROC WAC images only.";
            msg += "The ProductIds do not match.";
            throw IException(IException::User, msg, _FILEINFO_);
        }

        Isis::PvlGroup &inst = tempPvl.findGroup("Instrument", Pvl::Traverse);
        QString instId = (QString) inst["InstrumentId"];
        QString framelets = (QString) inst["Framelets"];
        QString numFrames = inst["NumFramelets"];

        if (instId != "WAC-VIS" && instId != "WAC-UV") {
            QString msg = "This program is intended for use on LROC WAC images only. [";
            msg += list[i].toString() + "] does not appear to be a WAC image.";
            throw IException(IException::User, msg, _FILEINFO_);
        }

        QString instModeId = (QString) inst["InstrumentModeId"];
        if (instrumentModeId == "")
            instrumentModeId = instModeId;
        if (numFramelets == 0)
            numFramelets = toInt(numFrames);
        g_isIoF = tempPvl.findGroup("Radiometry", Pvl::Traverse).findKeyword("RadiometricType")[0].toUpper() == "IOF";

        if (instId == "WAC-VIS" && framelets == "Even") {
            viseven = new Cube();
            viseven->open(list[i].toString());
        }
        else if (instId == "WAC-VIS" && framelets == "Odd") {
            visodd = new Cube();
            visodd->open(list[i].toString());
        }
        if (instId == "WAC-UV" && framelets == "Even") {
            uveven = new Cube();
            uveven->open(list[i].toString());
        }
        else if (instId == "WAC-UV" && framelets == "Odd") {
            uvodd = new Cube();
            uvodd->open(list[i].toString());
        }
    }

    // Determine our band information based on
    // INSTRUMENT_MODE_ID - FILTER_NUMBER is
    // only going to be used for BW images
    if (instrumentModeId == "COLOR") {
        numUVFilters = 2;
        numVisFilters = 5;

        numSamples = COLOR_SAMPLES;
    }
    else if (instrumentModeId == "VIS") {
        numUVFilters = 0;
        numVisFilters = 5;

        numSamples = VIS_SAMPLES;
    }
    else if (instrumentModeId == "UV") {
        numUVFilters = 2;
        numVisFilters = 0;

        numSamples = UV_SAMPLES;
    }
    else if (instrumentModeId == "BW") {
        numUVFilters = 0;
        numVisFilters = 1;

        numSamples = BW_SAMPLES;
    }

    numLines = numFramelets * (UV_LINES * numUVFilters + VIS_LINES * numVisFilters);

    out = new Cube();
    out->setDimensions(numSamples, numLines, 1);
    out->setPixelType(Isis::Real);

    FileName mergedCube = FileName::createTempFile(
        "$TEMPORARY/" + FileName(ui.GetFileName("TO")).baseName() + ".cub");
    out->create(mergedCube.expanded());

    mergeFramelets();

    /*

     FileName outFile(ui.GetFileName("TO", "img"));
     QString outFileName(outFile.expanded());
     ofstream oCube(outFileName.c_str());
     p.OutputLabel(oCube);
     p.StartProcess(oCube);
     oCube.close();
     p.EndProcess();

     */

    out->close();
    delete out;
    out = NULL;

    if (uveven) {
        uveven->close();
        delete uveven;
        uveven = NULL;
    }

    if (uvodd) {
        uvodd->close();
        delete uvodd;
        uvodd = NULL;
    }

    if (viseven) {
        viseven->close();
        delete viseven;
        viseven = NULL;
    }

    if (visodd) {
        visodd->close();
        delete visodd;
        visodd = NULL;
    }

    // Export data

    ProcessExport pe;

    // Setup the input cube
    Cube *inCube = pe.SetInputCube(mergedCube.expanded(), CubeAttributeInput());

    pe.SetOutputType(Isis::Real);
    pe.SetOutputEndian(Isis::Lsb);

    pe.SetOutputRange(Isis::VALID_MIN4, Isis::VALID_MAX4);

    pe.SetOutputNull(Isis::NULL4);
    pe.SetOutputLrs(Isis::LOW_REPR_SAT4);
    pe.SetOutputLis(Isis::LOW_INSTR_SAT4);
    pe.SetOutputHis(Isis::HIGH_INSTR_SAT4);
    pe.SetOutputHrs(Isis::HIGH_REPR_SAT4);

    FileName tempFile = FileName::createTempFile(
        "$TEMPORARY/" + FileName(ui.GetFileName("TO")).baseName() + ".temp");
    QString tempFileName(tempFile.expanded());
    ofstream temporaryFile(tempFileName.toAscii().data());

    pe.StartProcess(temporaryFile);
    temporaryFile.close();

    // Calculate MD5 Checksum
    g_md5Checksum = MD5Checksum(tempFileName);

    FileName outFile(ui.GetFileName("TO"));
    QString outFileName(outFile.expanded());
    ifstream inFile(tempFileName.toAscii().data());
    ofstream pdsFile(outFileName.toAscii().data());

    // Output the label
    OutputLabel(pdsFile, inCube, pdsLab);

    // Then copy the image data
    CopyData(inFile, pdsFile);

    pdsFile.close();

    pe.EndProcess();

    remove((mergedCube.expanded()).toAscii().data());
    remove(tempFileName.toAscii().data());
    return;
}
Example #17
0
void IsisMain() {
  ProcessImportPds p;
  Pvl pdsLabel;
  UserInterface &ui = Application::GetUserInterface();

  FileName inFile = ui.GetFileName("FROM");
  QString instid;
  QString missid;

  try {
    Pvl lab(inFile.expanded());
    instid = (QString) lab.findKeyword("INSTRUMENT_ID");
    missid = (QString) lab.findKeyword("MISSION_ID");
  }
  catch(IException &e) {
    QString msg = "Unable to read [INSTRUMENT_ID] or [MISSION_ID] from input file [" +
                 inFile.expanded() + "]";
    throw IException(IException::Io, msg, _FILEINFO_);
  }

  instid = instid.simplified().trimmed();
  missid = missid.simplified().trimmed();
  if(missid != "DAWN" && instid != "FC1" && instid != "FC2") {
    QString msg = "Input file [" + inFile.expanded() + "] does not appear to be " +
                 "a DAWN Framing Camera (FC) EDR or RDR file.";
    throw IException(IException::Io, msg, _FILEINFO_);
  }

  QString target;
  if(ui.WasEntered("TARGET")) {
    target = ui.GetString("TARGET");
  }


  p.SetPdsFile(inFile.expanded(), "", pdsLabel);
  p.SetOrganization(Isis::ProcessImport::BSQ);
  QString tmpName = "$TEMPORARY/" + inFile.baseName() + ".tmp.cub";
  FileName tmpFile(tmpName);
  CubeAttributeOutput outatt = CubeAttributeOutput("+Real");
  p.SetOutputCube(tmpFile.expanded(), outatt);
  p.SaveFileHeader();

  Pvl labelPvl(inFile.expanded());

  p.StartProcess();
  p.EndProcess();

  ProcessBySample p2;
  CubeAttributeInput inatt;
  p2.SetInputCube(tmpFile.expanded(), inatt);
  Cube *outcube = p2.SetOutputCube("TO");

  // Get the directory where the DAWN translation tables are.
  PvlGroup dataDir(Preference::Preferences().findGroup("DataDirectory"));
  QString transDir = (QString) dataDir["Dawn"] + "/translations/";

  // Create a PVL to store the translated labels in
  Pvl outLabel;

  // Translate the BandBin group
  FileName transFile(transDir + "dawnfcBandBin.trn");
  PvlTranslationManager bandBinXlater(labelPvl, transFile.expanded());
  bandBinXlater.Auto(outLabel);

  // Translate the Archive group
  transFile = transDir + "dawnfcArchive.trn";
  PvlTranslationManager archiveXlater(labelPvl, transFile.expanded());
  archiveXlater.Auto(outLabel);

  // Translate the Instrument group
  transFile = transDir + "dawnfcInstrument.trn";
  PvlTranslationManager instrumentXlater(labelPvl, transFile.expanded());
  instrumentXlater.Auto(outLabel);

  //  Update target if user specifies it
  if (!target.isEmpty()) {
    PvlGroup &igrp = outLabel.findGroup("Instrument",Pvl::Traverse);
    igrp["TargetName"] = target;
  }

  // Write the BandBin, Archive, and Instrument groups
  // to the output cube label
  outcube->putGroup(outLabel.findGroup("BandBin", Pvl::Traverse));
  outcube->putGroup(outLabel.findGroup("Archive", Pvl::Traverse));
  outcube->putGroup(outLabel.findGroup("Instrument", Pvl::Traverse));

  // Set the BandBin filter name, center, and width values based on the
  // FilterNumber.
  PvlGroup &bbGrp(outLabel.findGroup("BandBin", Pvl::Traverse));
  int filtno = bbGrp["FilterNumber"];
  int center;
  int width;
  QString filtname;
  if(filtno == 1) {
    center = 700;
    width = 700;
    filtname = "Clear_F1";
  }
  else if(filtno == 2) {
    center = 555;
    width = 43;
    filtname = "Green_F2";
  }
  else if(filtno == 3) {
    center = 749;
    width = 44;
    filtname = "Red_F3";
  }
  else if(filtno == 4) {
    center = 917;
    width = 45;
    filtname = "NIR_F4";
  }
  else if(filtno == 5) {
    center = 965;
    width = 85;
    filtname = "NIR_F5";
  }
  else if(filtno == 6) {
    center = 829;
    width = 33;
    filtname = "NIR_F6";
  }
  else if(filtno == 7) {
    center = 653;
    width = 42;
    filtname = "Red_F7";
  }
  else if(filtno == 8) {
    center = 438;
    width = 40;
    filtname = "Blue_F8";
  }
  else {
    QString msg = "Input file [" + inFile.expanded() + "] has an invalid " +
                 "FilterNumber. The FilterNumber must fall in the range 1 to 8.";
    throw IException(IException::Io, msg, _FILEINFO_);
  }
  bbGrp.addKeyword(PvlKeyword("Center", toString(center)));
  bbGrp.addKeyword(PvlKeyword("Width", toString(width)));
  bbGrp.addKeyword(PvlKeyword("FilterName", filtname));
  outcube->putGroup(bbGrp);

  PvlGroup kerns("Kernels");
  if(instid == "FC1") {
    kerns += PvlKeyword("NaifFrameCode", toString(-203110-filtno));
  }
  else if(instid == "FC2") {
    kerns += PvlKeyword("NaifFrameCode", toString(-203120-filtno));
  }
  else {
    QString msg = "Input file [" + inFile.expanded() + "] has an invalid " +
                 "InstrumentId.";
    throw IException(IException::Unknown, msg, _FILEINFO_);
  }
  outcube->putGroup(kerns);

  p2.StartProcess(flipbyline);
  p2.EndProcess();

  QString tmp(tmpFile.expanded());
  QFile::remove(tmp);
}
Example #18
0
void IsisMain() {
  const QString mdisddr_program = "mdisddr";
  const QString mdisddr_version = "1.0";
  const QString mdisddr_revision = "$Revision: 5086 $";
  const QString mdisddr_runtime = Application::DateTime();
  const QString dataSetID = "MESS-E/V/H-MDIS-6-DDR-GEOMDATA-V1.0";

  UserInterface &ui = Application::GetUserInterface();
  FileName input(ui.GetFileName("FROM"));
  QString to("");
  bool toEntered = ui.WasEntered("TO");
  if(toEntered) {
    to = ui.GetAsString("TO");
  }

  QString opath(".");    // Set default to local directory
  if(ui.WasEntered("OPATH")) {
    opath = ui.GetString("OPATH");
  }
  else {
    ui.PutAsString("OPATH", opath);
  }

  //  Generate the image cube that phocube produces for the DDR data
  FileName phoFile = FileName::createTempFile("$TEMPORARY/" + input.baseName() + "_phocube.cub");
  QString pfile = phoFile.expanded();
  QString parameters = "FROM=" + input.expanded() + " TO=" + pfile +
                      " LATITUDE=TRUE LONGITUDE=TRUE PHASE=TRUE EMISSION=TRUE INCIDENCE=TRUE";
  ProgramLauncher::RunIsisProgram("phocube", parameters);

  //  Wrap a try clause so that if anything goes wrong below, we can remove
  //  the phocube file.
  try {
    Pvl phoLabel(pfile);
    BandMap bandmap;
    PvlKeyword bn = phoLabel.findGroup("BandBin", Pvl::Traverse)["Name"];
    for(int i = 0 ; i < bn.size() ; i++) {
      bandmap.add(bn[i], i + 1);
    }

    // Set up the export.  Note that the attributes selects 5 bands from the
    // output of the phocube run.  It doesn't matter at this time which 5
    // bands it is, just so that we have this established so the right labels
    // and file size is created.
    ProcessExportPds processPds;
    (void) processPds.SetInputCube(pfile, CubeAttributeInput("+1-5"));

    //  Due to the nature of the phocube file, we cannot compute a histogram
    //  of the data (it includes lots of data we don't need).  So we will
    //  fix the range to the expected well defined angle ranges.
    double minmin = 0.0;
    double maxmax = 0.0;
    if(ui.GetString("TYPE").compare("AUTOMATIC") == 0) {
      minmin = -360.0;
      maxmax = 360.0;
    }
    else {
      minmin = ui.GetDouble("MIN");
      maxmax = ui.GetDouble("MAX");
    }

    processPds.SetOutputEndian(Isis::Msb);
    processPds.SetExportType(ProcessExportPds::Fixed);
    processPds.SetInputRange(minmin, maxmax);

    // Set the output pixel type and the special pixel values
    processPds.SetOutputType(Real);
    processPds.SetOutputRange(minmin, maxmax);
    processPds.SetOutputNull(NULL4);
    processPds.SetOutputLrs(LOW_REPR_SAT4);
    processPds.SetOutputLis(LOW_INSTR_SAT4);
    processPds.SetOutputHrs(HIGH_REPR_SAT4);
    processPds.SetOutputHis(HIGH_INSTR_SAT4);

    Progress p;
    p.SetText("Modifying Keywords");
    p.SetMaximumSteps(6);
    p.CheckStatus();

    // Get the PDS label from the process
    Pvl &pdsLabel = processPds.StandardPdsLabel(ProcessExportPds::Image);

    // Translate the keywords from the original EDR PDS label that go in
    // this DDR PDS label.  Note that we have to open the original (FROM)
    // cube as the phocube output goes into the specification of the
    // output PDS file (required for 5 band IMAGE object).
    Cube from;
    from.open(input.expanded());
    OriginalLabel origBlob;
    from.read(origBlob);
    Pvl origLabel;
    PvlObject origLabelObj = origBlob.ReturnLabels();
    origLabelObj.setName("OriginalLabelObject");
    origLabel.addObject(origLabelObj);
    p.CheckStatus();

    // Translates the ISIS labels along with the original EDR labels
    origLabel.addObject(*from.label());
    PvlTranslationManager labels(origLabel,
                                 "$messenger/translations/mdisDDRLabel.trn");
    labels.Auto(pdsLabel);
    p.CheckStatus();

    //  Add any new keywords
    QString lnote = "2007-12-20, S. Murchie (JHU/APL); "
                   "2008-01-02, S. Murchie (JHU/APL); "
                   "2008-01-11, J. Ward (GEO)";
    pdsLabel += PvlKeyword("LABEL_REVISION_NOTE", lnote);
    pdsLabel += PvlKeyword("SPACECRAFT_NAME", Quote("MESSENGER"));

    // Fixes bad keywords
    PvlKeyword &data_set_id = pdsLabel.findKeyword("DATA_SET_ID", Pvl::Traverse);
    data_set_id.setValue(dataSetID);
    QString prodid(input.baseName());
    PvlKeyword &product_id = pdsLabel.findKeyword("PRODUCT_ID", Pvl::Traverse);
    if((product_id.size() == 0) || ((product_id.size() > 0) && (product_id[0] == "N/A"))) {
      product_id.setValue(prodid);
    }
    else {
      QString pid = product_id[0];
      pid[0] = 'D';
      pid.remove(QRegExp("_.*"));
      pid.append("_DE_0");
      product_id.setValue(pid);
      prodid = pid;
    }

    // Now we have enough to establish output file name
    if(!toEntered) to = opath + "/" + prodid;
    FileName output(to);
    output = output.addExtension("IMG");
    if(!toEntered) ui.PutFileName("TO", output.expanded());

    PvlKeyword &product_creation_time = pdsLabel.findKeyword("PRODUCT_CREATION_TIME", Pvl::Traverse);
    product_creation_time.setValue(mdisddr_runtime);

    PvlKeyword &software_name = pdsLabel.findKeyword("SOFTWARE_NAME", Pvl::Traverse);
    software_name.setValue(mdisddr_program);

    PvlKeyword &software_version_id = pdsLabel.findKeyword("SOFTWARE_VERSION_ID", Pvl::Traverse);
    software_version_id.setValue(Quote(mdisddr_version));

    PvlKeyword &filter_number = pdsLabel.findKeyword("FILTER_NUMBER", Pvl::Traverse);
    if((filter_number.size() > 0)) {
      filter_number.setValue(Quote(filter_number[0]));
    }


    // Add quotes
    PvlKeyword &data_quality_id = pdsLabel.findKeyword("DATA_QUALITY_ID", Pvl::Traverse);
    data_quality_id.setValue(Quote(data_quality_id));
    PvlKeyword &sequence_name = pdsLabel.findKeyword("SEQUENCE_NAME", Pvl::Traverse);
    sequence_name.setValue(Quote(sequence_name));
    PvlKeyword &start_count = pdsLabel.findKeyword("SPACECRAFT_CLOCK_START_COUNT", Pvl::Traverse);
    start_count.setValue(Quote(start_count));
    PvlKeyword &stop_count = pdsLabel.findKeyword("SPACECRAFT_CLOCK_STOP_COUNT", Pvl::Traverse);
    stop_count.setValue(Quote(stop_count));

    //  For DDRs, the SOURCE_PRODUCT_ID is made up of SPICE kernels.  I need to
    //  go get em.
    Kernels kernels(from);
    QStringList kfiles = kernels.getKernelList();
    PvlKeyword &source_product_id = pdsLabel.findKeyword("SOURCE_PRODUCT_ID", Pvl::Traverse);
    source_product_id.clear();
    for(int i = 0; i < kfiles.size(); i++) {
      FileName kfile(kfiles[i]);
      source_product_id.addValue(Quote(kfile.name()));
    }

    //  Enforce parentheses for scalars
    if(source_product_id.size() == 1)
      source_product_id.setValue('(' + source_product_id[0] + ')');

    // Removes keywords
    PvlObject imageObject(pdsLabel.findObject("IMAGE"));
    if(imageObject.hasKeyword("CENTER_FILTER_WAVELENGTH")) imageObject.deleteKeyword("CENTER_FILTER_WAVELENGTH");
    if(imageObject.hasKeyword("BANDWIDTH")) imageObject.deleteKeyword("BANDWIDTH");
    if(imageObject.hasKeyword("UNIT")) imageObject.deleteKeyword("UNIT");
    if(imageObject.hasKeyword("DARK_STRIP_MEAN")) imageObject.deleteKeyword("DARK_STRIP_MEAN");
    if(imageObject.hasKeyword("OFFSET")) imageObject.deleteKeyword("OFFSET");
    if(imageObject.hasKeyword("SCALING_FACTOR")) imageObject.deleteKeyword("SCALING_FACTOR");
    if(imageObject.hasKeyword("SAMPLE_BIT_MASK")) imageObject.deleteKeyword("SAMPLE_BIT_MASK");

    // Add band names to image object
    PvlKeyword &bandNames = imageObject.findKeyword("FILTER_NAME");
    bandNames.setName("BAND_NAME");
    bandNames.clear();
    bandNames.addValue("Latitude, planetocentric, deg N");
    bandNames.addValue("Longitude, planetocentric, deg E");
    bandNames.addValue("Incidence angle at equipotential surface, deg");
    bandNames.addValue("Emission angle at equipotential surface, deg");
    bandNames.addValue("Phase angle at equipotential surface, deg");
    pdsLabel.deleteObject("IMAGE");
    pdsLabel.addObject(imageObject);

    p.CheckStatus();

    //  Fix all the hosed units upon ingest.  They are illformed.
    FixUnit(pdsLabel, "RETICLE_POINT_RA", "DEG");
    FixUnit(pdsLabel, "RETICLE_POINT_DECLINATION", "DEG");
    FixUnit(pdsLabel, "RETICLE_POINT_LATITUDE", "DEG");
    FixUnit(pdsLabel, "RETICLE_POINT_LONGITUDE", "DEG");

    //  Now address nested keywords in SUBFRAME groups
    for(int i = 1 ; i <= 5 ; i++) {
      QString n(toString(i));
      QString group = "SUBFRAME" + n + "_PARAMETERS";
      if(pdsLabel.hasGroup(group)) {
        PvlGroup &grp = pdsLabel.findGroup(group);
        ValidateUnit(grp.findKeyword("RETICLE_POINT_LATITUDE"), "DEG");
        ValidateUnit(grp.findKeyword("RETICLE_POINT_LONGITUDE"), "DEG");
      }
    }
    p.CheckStatus();


    //  Finally, fix keywords by Quoting missing N/A values
    FixLabels(pdsLabel);
    p.CheckStatus();

    // All done...write result.
    pdsLabel.setFormatTemplate("$messenger/templates/labels/mdisPdsDDR.pft");
    QString ofile(output.expanded());
    ofstream outstream(ofile.toAscii().data());
    processPds.OutputLabel(outstream);

    // Writing out the 5 bands is a bit tricky for this product.  The bands
    // must be ordered in a specific order, but phocube orders them in a
    // different order.  To make this approach work, determine the proper band
    // as ordered in the phocube output and select the desired bands one at a
    // time setting the input cube to the desired band and writing it out by
    // stream.

    //  Write latitude, longitude, incidence, emission, phase bands
    WriteBand(processPds, outstream, pfile, bandmap.get("Latitude"));
    WriteBand(processPds, outstream, pfile, bandmap.get("Longitude"));
    WriteBand(processPds, outstream, pfile, bandmap.get("Incidence Angle"));
    WriteBand(processPds, outstream, pfile, bandmap.get("Emission Angle"));
    WriteBand(processPds, outstream, pfile, bandmap.get("Phase Angle"));
    outstream.close();
    processPds.EndProcess();
    remove(pfile.toAscii().data());
  }
  catch(IException &) {
    remove(pfile.toAscii().data());
    throw;
  }
  catch(...) {
    remove(pfile.toAscii().data());
    throw IException(IException::Unknown, "Unexpected exception caught!",
                     _FILEINFO_);
  }

}
Example #19
0
void IsisMain() {

  // Create a process so we can output the noproj'd labels without overwriting
  Process p;

  // Open the user interface and get the input file and the ideal specs file
  UserInterface &ui = Application::GetUserInterface();
  Cube *mcube, *icube;

  // If a MATCH cube is entered, make sure to SetInputCube it first to get the SPICE blobs
  // from it propagated to the TO labels

  // Until polygon blobs are detached without "/" don't propagate them
  p.PropagatePolygons(false);

  if((ui.WasEntered("MATCH"))) {
    mcube = p.SetInputCube("MATCH");
    icube = p.SetInputCube("FROM");
  }
  else {
    mcube = icube = p.SetInputCube("FROM");
  }

  Camera *incam = mcube->camera();

  // Extract Instrument groups from input labels for the output match and noproj'd cubes
  PvlGroup inst = mcube->group("Instrument");
  PvlGroup fromInst = icube->group("Instrument");
  QString groupName = (QString) inst["SpacecraftName"] + "/";
  groupName += (QString) inst.findKeyword("InstrumentId");

  // Get Ideal camera specifications
  FileName specs;
  if((ui.WasEntered("SPECS"))) {
    specs = ui.GetFileName("SPECS");
  }
  else {
    specs = "$base/applications/noprojInstruments???.pvl";
    specs = specs.highestVersion();
  }
  Pvl idealSpecs(specs.expanded());
  PvlObject obSpecs = idealSpecs.findObject("IdealInstrumentsSpecifications");

  PvlGroup idealGp = obSpecs.findGroup(groupName);
  double transx, transy, transl, transs;
  transx = transy = transl = transs = 0.;
  if(idealGp.hasKeyword("TransX")) transx = idealGp["TransX"];
  if(idealGp.hasKeyword("TransY")) transy = idealGp["TransY"];
  if(idealGp.hasKeyword("ItransL")) transl = idealGp["ItransL"];
  if(idealGp.hasKeyword("ItransS")) transs = idealGp["ItransS"];
  int detectorSamples = mcube->sampleCount();
  if(idealGp.hasKeyword("DetectorSamples")) detectorSamples = idealGp["DetectorSamples"];
  int numberLines = mcube->lineCount();
  int numberBands = mcube->bandCount();

  if(idealGp.hasKeyword("DetectorLines")) numberLines = idealGp["DetectorLines"];

  int xDepend = incam->FocalPlaneMap()->FocalPlaneXDependency();

  // Get output summing mode
  if(ui.GetString("SOURCE") == "FROMMATCH") {
    LoadMatchSummingMode();
  }
  else if(ui.GetString("SOURCE") == "FROMINPUT") {
    LoadInputSummingMode();
  }

  double pixPitch = incam->PixelPitch() * ui.GetDouble("SUMMINGMODE");
  detectorSamples /= (int)(ui.GetDouble("SUMMINGMODE"));
  // Get the user options
  int sampleExpansion = int((ui.GetDouble("SAMPEXP") / 100.) * detectorSamples + .5);
  int lineExpansion = int((ui.GetDouble("LINEEXP") / 100.) * numberLines + .5);
  QString instType;

  // Adjust translations for summing mode
  transl /= ui.GetDouble("SUMMINGMODE");
  transs /= ui.GetDouble("SUMMINGMODE");

  detectorSamples += sampleExpansion;
  numberLines += lineExpansion;

  // Determine whether this ideal camera is a line scan or framing camera and
  // set the instrument id and exposure
  int detectorLines;
  int expandFlag;

  if(incam->DetectorMap()->LineRate() != 0.0) {
    instType = "LINESCAN";
    // Isis3 line rate is always in seconds so convert to milliseconds for the
    // Ideal instrument
    detectorLines = 1;
    expandFlag = 1;
  }
  else {
    instType = "FRAMING";
    detectorLines = numberLines;
    expandFlag = 0;
    // Framing cameras don't need exposure time
  }

  // Adjust focal plane translations with line expansion for scanners since
  // the CCD is only 1 line
  if(expandFlag) {
    transl += lineExpansion / 2;

    if(xDepend == CameraFocalPlaneMap::Line) {
      transx -= lineExpansion / 2.*pixPitch * expandFlag;
    }
    else {
      transy -= lineExpansion / 2.*pixPitch * expandFlag;
    }
  }

  // Get the start time for parent line 1
  AlphaCube alpha(*icube);
  double sample = alpha.BetaSample(.5);
  double line = alpha.BetaLine(.5);
  incam->SetImage(sample, line);
  double et = incam->time().Et();

  // Get the output file name and set its attributes
  CubeAttributeOutput cao;

  // Can we do a regular label? Didn't work on 12-15-2006
  cao.setLabelAttachment(Isis::DetachedLabel);

  // Determine the output image size from
  //   1) the idealInstrument pvl if there or
  //   2) the input size expanded by user specified percentage
  Cube *ocube = p.SetOutputCube("match.cub", cao, 1, 1, 1);

  // Extract the times and the target from the instrument group
  QString startTime = inst["StartTime"];
  QString stopTime;
  if(inst.hasKeyword("StopTime")) stopTime = (QString) inst["StopTime"];

  QString target = inst["TargetName"];

  // rename the instrument groups
  inst.setName("OriginalInstrument");
  fromInst.setName("OriginalInstrument");

  // add it back to the IsisCube object under a new group name
  ocube->putGroup(inst);

  // and remove the version from the IsisCube Object
  ocube->deleteGroup("Instrument");

  // Now rename the group back to the Instrument group and clear out old keywords
  inst.setName("Instrument");
  inst.clear();

  // Add keywords for the "Ideal" instrument
  Isis::PvlKeyword key("SpacecraftName", "IdealSpacecraft");
  inst.addKeyword(key);

  key.setName("InstrumentId");
  key.setValue("IdealCamera");
  inst.addKeyword(key);

  key.setName("TargetName");
  key.setValue(target);
  inst.addKeyword(key);

  key.setName("SampleDetectors");
  key.setValue(Isis::toString(detectorSamples));
  inst.addKeyword(key);

  key.setName("LineDetectors");
  key.setValue(Isis::toString(detectorLines));
  inst.addKeyword(key);

  key.setName("InstrumentType");
  key.setValue(instType);
  inst.addKeyword(key);

  Pvl &ocubeLabel = *ocube->label();
  PvlObject *naifKeywordsObject = NULL;

  if (ocubeLabel.hasObject("NaifKeywords")) {
    naifKeywordsObject = &ocubeLabel.findObject("NaifKeywords");

    // Clean up the naif keywords object... delete everything that isn't a radii
    for (int keyIndex = naifKeywordsObject->keywords() - 1; keyIndex >= 0; keyIndex--) {
      QString keyName = (*naifKeywordsObject)[keyIndex].name();
      
      if (!keyName.contains("RADII")) {
        naifKeywordsObject->deleteKeyword(keyIndex);
      }
    }

    // Clean up the kernels group... delete everything that isn't internalized or the orig frame
    //   code
    PvlGroup &kernelsGroup = ocube->group("Kernels");
    for (int keyIndex = kernelsGroup.keywords() - 1; keyIndex >= 0; keyIndex--) {
      PvlKeyword &kernelsKeyword = kernelsGroup[keyIndex];

      bool isTable = false;
      bool isFrameCode = kernelsKeyword.isNamed("NaifFrameCode") ||
                         kernelsKeyword.isNamed("NaifIkCode");
      bool isShapeModel = kernelsKeyword.isNamed("ShapeModel");

      for (int keyValueIndex = 0; keyValueIndex < kernelsKeyword.size(); keyValueIndex++) {
        if (kernelsKeyword[keyValueIndex] == "Table") {
          isTable = true;
        }
      }

      if (!isTable && !isFrameCode && !isShapeModel) {
        kernelsGroup.deleteKeyword(keyIndex);
      }
    }
  }

  if (naifKeywordsObject) {
    naifKeywordsObject->addKeyword(PvlKeyword("IDEAL_FOCAL_LENGTH", toString(incam->FocalLength())),
                                   Pvl::Replace);
  }
  else {
    inst.addKeyword(PvlKeyword("FocalLength", toString(incam->FocalLength()), "millimeters"));
  }

  double newPixelPitch = incam->PixelPitch() * ui.GetDouble("SUMMINGMODE");
  if (naifKeywordsObject) {
    naifKeywordsObject->addKeyword(PvlKeyword("IDEAL_PIXEL_PITCH", toString(newPixelPitch)),
                                   Pvl::Replace);
  }
  else {
    inst.addKeyword(PvlKeyword("PixelPitch", toString(newPixelPitch), "millimeters"));
  }

  key.setName("EphemerisTime");
  key.setValue(Isis::toString(et), "seconds");
  inst.addKeyword(key);

  key.setName("StartTime");
  key.setValue(startTime);
  inst.addKeyword(key);

  if(stopTime != "") {
    key.setName("StopTime");
    key.setValue(stopTime);
    inst.addKeyword(key);
  }

  key.setName("FocalPlaneXDependency");
  key.setValue(toString((int)incam->FocalPlaneMap()->FocalPlaneXDependency()));
  inst.addKeyword(key);

  int xDependency = incam->FocalPlaneMap()->FocalPlaneXDependency();

  double newInstrumentTransX = incam->FocalPlaneMap()->SignMostSigX();
  inst.addKeyword(PvlKeyword("TransX", toString(newInstrumentTransX)));

  double newInstrumentTransY = incam->FocalPlaneMap()->SignMostSigY();
  inst.addKeyword(PvlKeyword("TransY", toString(newInstrumentTransY)));

  storeSpice(&inst, naifKeywordsObject, "TransX0", "IDEAL_TRANSX", transx,
             newPixelPitch * newInstrumentTransX, (xDependency == CameraFocalPlaneMap::Sample));

  storeSpice(&inst, naifKeywordsObject, "TransY0", "IDEAL_TRANSY", transy,
             newPixelPitch * newInstrumentTransY, (xDependency == CameraFocalPlaneMap::Line));

  double transSXCoefficient = 1.0 / newPixelPitch * newInstrumentTransX;
  double transLXCoefficient = 1.0 / newPixelPitch * newInstrumentTransY;

  if (xDependency == CameraFocalPlaneMap::Line) {
    swap(transSXCoefficient, transLXCoefficient);
  }

  storeSpice(&inst, naifKeywordsObject, "TransS0", "IDEAL_TRANSS",
             transs, transSXCoefficient, (xDependency == CameraFocalPlaneMap::Sample));
  storeSpice(&inst, naifKeywordsObject, "TransL0", "IDEAL_TRANSL",
             transl, transLXCoefficient, (xDependency == CameraFocalPlaneMap::Line));

  if(instType == "LINESCAN") {
    key.setName("ExposureDuration");
    key.setValue(Isis::toString(incam->DetectorMap()->LineRate() * 1000.), "milliseconds");
    inst.addKeyword(key);
  }

  key.setName("MatchedCube");
  key.setValue(mcube->fileName());
  inst.addKeyword(key);

  ocube->putGroup(inst);

  p.EndProcess();

// Now adjust the label to fake the true size of the image to match without
// taking all the space it would require for the image data
  Pvl label;
  label.read("match.lbl");
  PvlGroup &dims = label.findGroup("Dimensions", Pvl::Traverse);
  dims["Lines"] = toString(numberLines);
  dims["Samples"] = toString(detectorSamples);
  dims["Bands"] = toString(numberBands);
  label.write("match.lbl");

// And run cam2cam to apply the transformation
  QString parameters;
  parameters += " FROM= " + ui.GetFileName("FROM");
  parameters += " MATCH= " + QString("match.cub");
  parameters += " TO= " + ui.GetFileName("TO");
  parameters += " INTERP=" + ui.GetString("INTERP");
  ProgramLauncher::RunIsisProgram("cam2cam", parameters);

//  Cleanup by deleting the match files
  remove("match.History.IsisCube");
  remove("match.lbl");
  remove("match.cub");
  remove("match.OriginalLabel.IsisCube");
  remove("match.Table.BodyRotation");
  remove("match.Table.HiRISE Ancillary");
  remove("match.Table.HiRISE Calibration Ancillary");
  remove("match.Table.HiRISE Calibration Image");
  remove("match.Table.InstrumentPointing");
  remove("match.Table.InstrumentPosition");
  remove("match.Table.SunPosition");

// Finally finish by adding the OriginalInstrument group to the TO cube
  Cube toCube;
  toCube.open(ui.GetFileName("TO"), "rw");
// Extract label and create cube object
  Pvl *toLabel = toCube.label();
  PvlObject &o = toLabel->findObject("IsisCube");
  o.deleteGroup("OriginalInstrument");
  o.addGroup(fromInst);
  toCube.close();
}
Example #20
0
//***********************************************************************
//   IsisMain()
//***********************************************************************
void IsisMain() {
  UserInterface &ui = Application::GetUserInterface();
  FileName in = ui.GetFileName("FROM");
  FileName outIr = ui.GetFileName("IR");
  FileName outVis = ui.GetFileName("VIS");
  Pvl lab(in.expanded());

  //Checks if in file is rdr
  if(lab.hasObject("IMAGE_MAP_PROJECTION")) {
    QString msg = "[" + in.name() + "] appears to be an rdr file.";
    msg += " Use pds2isis.";
    throw IException(IException::User, msg, _FILEINFO_);
  }

  //Make sure it is a vims cube
  try {
    PvlObject qube(lab.findObject("QUBE"));
    QString id;
    id = (QString)qube["INSTRUMENT_ID"];
    id = id.simplified().trimmed();
    if(id != "VIMS") {
      QString msg = "Invalid INSTRUMENT_ID [" + id + "]";
      throw IException(IException::Unknown, msg, _FILEINFO_);
    }
  }
  catch(IException &e) {
    QString msg = "Input file [" + in.expanded() +
                 "] does not appear to be " +
                 "in VIMS EDR/RDR format";
    throw IException(IException::Io, msg, _FILEINFO_);
  }

  FileName tempname(in.baseName() + ".bsq.cub");
  Pvl pdsLab(in.expanded());

  // It's VIMS, let's figure out if it has the suffix data or not
  if(toInt(lab.findObject("QUBE")["SUFFIX_ITEMS"][0]) == 0) {
    // No suffix data, we can use processimportpds
    ProcessImportPds p;

    p.SetPdsFile(in.expanded(), "", pdsLab);
    // Set up the temporary output cube
    //The temporary cube is set to Real pixeltype, regardless of input pixel type
    Isis::CubeAttributeOutput outatt = CubeAttributeOutput("+Real");
    p.SetOutputCube(tempname.name(), outatt);
    p.StartProcess();
    p.EndProcess();
  }
  else {
    // We do it the hard way
    ReadVimsBIL(in.expanded(), lab.findObject("QUBE")["SUFFIX_ITEMS"], tempname.name());
  }

  // Create holder for original labels
  OriginalLabel origLabel(pdsLab);

  //Now separate the cubes
  ProcessByLine l;

  PvlGroup status("Results");

  //VIS cube
  const PvlObject &qube = lab.findObject("Qube");
  if(qube["SAMPLING_MODE_ID"][1] != "N/A") {
    CubeAttributeInput inattvis = CubeAttributeInput("+1-96");
    l.SetInputCube(tempname.name(), inattvis);
    Cube *oviscube = l.SetOutputCube("VIS");
    oviscube->write(origLabel);
    l.StartProcess(ProcessCube);
    TranslateVimsLabels(pdsLab, oviscube, VIS);
    l.EndProcess();

    status += PvlKeyword("VisCreated", "true");
  }
  else {
    status += PvlKeyword("VisCreated", "false");
  }

  //IR cube
  if(qube["SAMPLING_MODE_ID"][0] != "N/A") {
    CubeAttributeInput inattir = CubeAttributeInput("+97-352");
    l.SetInputCube(tempname.name(), inattir);
    Cube *oircube = l.SetOutputCube("IR");
    oircube->write(origLabel);
    l.StartProcess(ProcessCube);
    TranslateVimsLabels(pdsLab, oircube, IR);
    l.EndProcess();

    status += PvlKeyword("IrCreated", "true");
  }
  else {
    status += PvlKeyword("IrCreated", "false");
  }

  Application::Log(status);

  //Clean up
  QString tmp(tempname.expanded());
  QFile::remove(tmp);
}