int _tmain(int argc, _TCHAR* argv[])
{
	Cube c;
	c.Write("output2.off");

	return 0;
}
Esempio n. 2
0
void IsisMain() {

  UserInterface &ui = Application::GetUserInterface();

  string from = ui.GetFilename("FROM");

  // Setup to read headers/labels
  ifstream input;
  input.open(from.c_str(), ios::in | ios::binary);

  // Check stream open status
  if (!input.is_open()) {
    string msg = "Cannot open input file [" + from + "]";
    throw Isis::iException::Message(Isis::iException::Io, msg, _FILEINFO_);
  }

  char reading[81];
  iString line = "";
  unsigned int place = 0;
  PvlGroup labels("OriginalLabels");

  // Load first line
  input.seekg(0);
  input.read(reading, 80);
  reading[80] = '\0';
  line = reading;
  place += 80;

  // Read in and place in PvlKeywords and a PvlGroup
  while (line.substr(0,3) != "END") {
    // Check for blank lines
    if (line.substr(0,1) != " " && line.substr(0,1) != "/") {
      // Name of keyword
      PvlKeyword label(line.Token(" ="));
      // Remove up to beginning of data
      line.TrimHead(" ='");
      line.TrimTail(" ");
      if (label.Name() == "COMMENT" || label.Name() == "HISTORY") {
        label += line;
      }
      else {
        // Access the data without the comment if there is one
        iString value = line.Token("/");
        // Clear to end of data, including single quotes
        value.TrimTail(" '");        
        label += value;
        line.TrimHead(" ");
        // If the remaining line string has anything, it is comments.
        if (line.size() > 0) {
          label.AddComment(line);
          // A possible format for units, other possiblites exist.
          if (line != line.Token("[")) {
            label.SetUnits(line.Token("[").Token("]"));
          }
        }
      }
      labels += label;
    }
    // Load next line
    input.seekg(place);
    input.read(reading, 80);
    reading[80] = '\0';
    place += 80;
    line = reading;
  }

  // Done with stream
  input.close();

  // Its possible they could have this instead of T, in which case we won't even try
  if (labels["SIMPLE"][0] == "F") {
    string msg = "The file [" + ui.GetFilename("FROM") + "] does not conform to the FITS standards";
    throw iException::Message(iException::User, msg, _FILEINFO_);
  }

  ProcessImport pfits;

  pfits.SetInputFile(ui.GetFilename("FROM"));

  // Header size will be a multiple of 2880
  int multiple = (int)((place + 2881)/2880);
  pfits.SetFileHeaderBytes(multiple * 2880);
  pfits.SaveFileHeader();

  // Find pixel type, there are several unsupported possiblites
  Isis::PixelType type;
  string msg = "";
  switch (labels["BITPIX"][0].ToInteger()) {
    case 8: 
      type = Isis::UnsignedByte;
      break;
    case 16: 
      type = Isis::SignedWord;
      break;
    case 32: 
      msg = "Signed 32 bit integer (int) pixel type is not supported at this time";
      throw iException::Message(iException::User, msg, _FILEINFO_);
      break;
    case 64:
      msg = "Signed 64 bit integer (long) pixel type is not supported at this time";
      throw iException::Message(iException::User, msg, _FILEINFO_);
      break;
    case -32: 
      type = Isis::Real;
      break;
    case -64: 
      msg = "64 bit floating point (double) pixel type is not supported at this time";
      throw iException::Message(iException::User, msg, _FILEINFO_);
      break;
    default:
      msg = "Unknown pixel type [" + labels["BITPIX"][0] + "] cannot be imported";
      throw iException::Message(iException::User, msg, _FILEINFO_);
      break; 
  }

  pfits.SetPixelType(type);

  // It is possible to have a NAXIS value of 0 meaning no data, the file could include 
  // xtensions with data, however, those aren't supported as of Oct '09  
  if (labels["NAXIS"][0].ToInteger() == 2) {
    pfits.SetDimensions(labels["NAXIS1"][0], labels["NAXIS2"][0], 1);
  }
  else if (labels["NAXIS"][0].ToInteger() == 3) {
    pfits.SetDimensions(labels["NAXIS1"][0], labels["NAXIS2"][0], labels["NAXIS3"][0]);
  }
  else {
    string msg = "NAXIS count of [" + labels["NAXIS"][0] + "] is not supported at this time";
    throw iException::Message(iException::User, msg, _FILEINFO_);
  }

  // Base and multiplier
  if (labels.HasKeyword("BZERO")) {
    pfits.SetBase(labels["BZERO"][0]);
  }
  if (labels.HasKeyword("BSCALE")) {
    pfits.SetMultiplier(labels["BSCALE"][0]);
  }

  // Byte order
  pfits.SetByteOrder(Isis::Msb);  

  // Limited section of standardized keywords that could exist
  bool instGrp = false;
  PvlGroup inst("Instrument");
  if (labels.HasKeyword("DATE-OBS")) {
    instGrp = true;
    inst += PvlKeyword("StartTime", labels["DATE-OBS"][0]);
  }
  if (labels.HasKeyword("OBJECT")) {
    instGrp = true;
    inst += PvlKeyword("Target", labels["OBJECT"][0]);
  }
  if (labels.HasKeyword("INSTRUME")) {
    instGrp = true;
    inst += PvlKeyword("InstrumentId", labels["INSTRUME"][0]);
  }
  if (labels.HasKeyword("OBSERVER")) {
    instGrp = true;
    inst += PvlKeyword("SpacecraftName", labels["OBSERVER"][0]);
  }

  Cube * output = pfits.SetOutputCube("TO");

  // Add instrument group if any relevant data exists
  Pvl * lbls = output->Label();
  if (instGrp) {
    lbls->FindObject("IsisCube") += inst;
  }

  // Save original labels
  Pvl pvl;
  pvl += labels;
  OriginalLabel originals(pvl);
  output->Write(originals);

  // Process...
  pfits.StartProcess();
  pfits.EndProcess();
}
Esempio n. 3
0
void IsisMain() {
  UserInterface &ui = Application::GetUserInterface();
  /*Processing steps
  1.  Open and read the jitter table, convert the pixel offsets to angles,
      and create the polynomials (solve for the coefficients) to use to do
      the high pass filter putting the results into a rotation matrix in the jitter class.
  2.  Apply the jitter correction in the LineScanCameraRotation object of the master cube.
  3.  Loop through FROMLIST correcting the pointing and writing out the
      updated camera pointing from the master cube
      */

  int degree = ui.GetInteger("DEGREE");

  // Get the input file list to make sure it is not empty and the master cube is included
  FileList list;
  list.Read(ui.GetFilename("FROMLIST"));

  if (list.size() < 1) {
    string msg = "The input list file [" + ui.GetFilename("FROMLIST") + "is empty";
    throw iException::Message(iException::User,msg,_FILEINFO_);
  }

  int ifile = 0;
  // Make sure the master file is included in the input file list
  while (ifile < (int) list.size() && Filename(list[ifile]).Expanded() != Filename(ui.GetFilename("MASTER")).Expanded()) {
    ifile++;
  }

  if (ifile >= (int) list.size()) {
    string msg = "The master file, [" + Filename(ui.GetFilename("MASTER")).Expanded() + " is not included in " + 
      "the input list file " + ui.GetFilename("FROMLIST") + "]";
    throw iException::Message(iException::User,msg,_FILEINFO_);
  }

  bool step2 = false;
  PvlGroup gp("AppjitResults");

  //Step 1:  Create the jitter rotation

  try {
    // Open the master cube
    Cube cube;
    cube.Open(ui.GetFilename("MASTER"),"rw");
    
    //check for existing polygon, if exists delete it
    if (cube.Label()->HasObject("Polygon")){
      cube.Label()->DeleteObject("Polygon");
    }

    // Get the camera
    Camera *cam = cube.Camera();
    if (cam->DetectorMap()->LineRate() == 0.0) {
      string msg = "[" + ui.GetFilename("MASTER") + "] is not a line scan camera image";
      throw iException::Message(Isis::iException::User,msg,_FILEINFO_);
    }

    // Create the master rotation to be corrected 
    int frameCode = cam->InstrumentRotation()->Frame();
    cam->SetImage(int(cube.Samples()/2), int(cube.Lines()/2) );
    double tol = cam->PixelResolution();

    if (tol < 0.) {
      // Alternative calculation of .01*ground resolution of a pixel
      tol = cam->PixelPitch()*cam->SpacecraftAltitude()*1000./cam->FocalLength()/100.;
    }
    LineScanCameraRotation crot(frameCode, *(cube.Label()), cam->InstrumentRotation()->GetFullCacheTime(), tol );
    crot.SetPolynomialDegree(ui.GetInteger("DEGREE"));
    crot.SetAxes(1, 2, 3);
    if (ui.WasEntered("PITCHRATE")) crot.ResetPitchRate(ui.GetDouble("PITCHRATE"));
    if (ui.WasEntered("YAW")) crot.ResetYaw(ui.GetDouble("YAW"));
    crot.SetPolynomial();
    double baseTime = crot.GetBaseTime();
    double timeScale = crot.GetTimeScale();
    double fl = cam->FocalLength();
    double pixpitch = cam->PixelPitch();
    std::vector<double> cacheTime = cam->InstrumentRotation()->GetFullCacheTime();

    // Get the jitter in pixels, compute jitter angles, and fit a polynomial to each angle
    PixelOffset jitter(ui.GetFilename("JITTERFILE"), fl, pixpitch, baseTime, timeScale, degree);
    jitter.LoadAngles(cacheTime);
    jitter.SetPolynomial();

    // Set the jitter and apply to the instrument rotation
    crot.SetJitter( &jitter );
    crot.ReloadCache();

    // Pull out the pointing cache as a table and write it
    Table cmatrix = crot.Cache("InstrumentPointing");
    cmatrix.Label().AddComment("Corrected using appjit and" + ui.GetFilename("JITTERFILE"));
    cube.Write(cmatrix);

    // Write out the instrument position table
    Isis::PvlGroup kernels = cube.Label()->FindGroup("Kernels",Isis::Pvl::Traverse);

    // Write out the "Table" label to the tabled kernels in the kernels group
    kernels["InstrumentPointing"] = "Table";
//    kernels["InstrumentPosition"] = "Table";
    cube.PutGroup(kernels);
    cube.Close();
    gp += PvlKeyword("StatusMaster",ui.GetFilename("MASTER") + ":  camera pointing updated");

    // Apply the dejittered pointing to the rest of the files
    step2 = true;
    for (int ifile = 0; ifile < (int) list.size(); ifile++) {
      if (list[ifile] != ui.GetFilename("MASTER")) {
        // Open the cube
        cube.Open(list[ifile],"rw");
        //check for existing polygon, if exists delete it
        if (cube.Label()->HasObject("Polygon")){
          cube.Label()->DeleteObject("Polygon");
        }
        // Get the camera and make sure it is a line scan camera
        Camera *cam = cube.Camera();
        if (cam->DetectorMap()->LineRate() == 0.0) {
          string msg = "[" + ui.GetFilename("FROM") + "] is not a line scan camera";
          throw iException::Message(Isis::iException::User,msg,_FILEINFO_);
        }
        // Pull out the pointing cache as a table and write it
        cube.Write(cmatrix);
        cube.PutGroup(kernels);
        cube.Close();
        gp += PvlKeyword("Status" + iString(ifile), list[ifile] + ":  camera pointing updated");
      }
    }
    Application::Log( gp );
  }
  catch (iException &e) {
    string msg;
    if (!step2) {
      msg = "Unable to fit pointing for [" + ui.GetFilename("MASTER") + "]";
    }
    else {
      msg = "Unable to update pointing for nonMaster file(s)";
    }
    throw iException::Message(Isis::iException::User,msg,_FILEINFO_);
  }
}
Esempio n. 4
0
void IsisMain(){

  Process p;

  // Reset all the stats objects because they are global
  latStat.Reset();
  lonStat.Reset();
  resStat.Reset();
  sampleResStat.Reset();
  lineResStat.Reset();
  aspectRatioStat.Reset();
  phaseStat.Reset();
  emissionStat.Reset();
  incidenceStat.Reset();
  localSolarTimeStat.Reset();
  localRaduisStat.Reset();
  northAzimuthStat.Reset();

  UserInterface &ui = Application::GetUserInterface();

  Cube *icube = p.SetInputCube("FROM");
  Camera *cam = icube->Camera();

//  Cube cube;
//  cube.Open(ui.GetFilename("FROM"));
//  Camera *cam = cube.Camera();

  int eband = cam->Bands();
  // if the camera is band independent that only run one band
  if (cam->IsBandIndependent()) eband = 1;
  int linc = ui.GetInteger("LINC");
  int sinc = ui.GetInteger("SINC");

  int pTotal = eband * ((cam->Lines()-2) / linc + 2) ;
  Progress progress;
  progress.SetMaximumSteps(pTotal);
  progress.CheckStatus();

  for (int band=1; band<=eband; band++) {
    cam->SetBand(band);
    for (int line=1; line<(int)cam->Lines(); line=line+linc) {
      for (int sample=1; sample< cam->Samples(); sample=sample+sinc) {
        buildStats(cam, sample, line);
      }
      //set the sample value to the last sample and run buildstats
      int sample = cam->Samples();
      buildStats(cam, sample, line);
      progress.CheckStatus();
    }
    //set the line value to the last line and run on all samples(sample + sinc)
    int line = cam->Lines();
    for (int sample=1; sample< cam->Samples(); sample=sample+sinc) {
      buildStats(cam, sample, line);
    }
    //set last sample and run with last line
    int sample = cam->Samples();
    buildStats(cam, sample, line);
    progress.CheckStatus();
  }

  //Set up the Pvl groups and get min, max, avg, and sd for each statstics object  
  PvlGroup pUser("User Parameters");
  pUser += PvlKeyword("Filename",ui.GetFilename("FROM"));
  pUser += PvlKeyword("Linc",ui.GetInteger("LINC"));
  pUser += PvlKeyword("Sinc",ui.GetInteger("SINC"));

  PvlGroup pLat("Latitude");
  pLat += ValidateKey("LatitudeMinimum",latStat.Minimum());
  pLat += ValidateKey("LatitudeMaximum",latStat.Maximum());
  pLat += ValidateKey("LatitudeAverage",latStat.Average());
  pLat += ValidateKey("LatitudeStandardDeviation",latStat.StandardDeviation());

  PvlGroup pLon("Longitude");
  pLon += ValidateKey("LongitudeMinimum",lonStat.Minimum());
  pLon += ValidateKey("LongitudeMaximum",lonStat.Maximum());
  pLon += ValidateKey("LongitudeAverage",lonStat.Average());
  pLon += ValidateKey("LongitudeStandardDeviation",lonStat.StandardDeviation());

  PvlGroup pSampleRes("SampleResolution");
  pSampleRes += ValidateKey("SampleResolutionMinimum",sampleResStat.Minimum(),
                           "meters/pixel");
  pSampleRes += ValidateKey("SampleResolutionMaximum",sampleResStat.Maximum(),
                           "meters/pixel");
  pSampleRes += ValidateKey("SampleResolutionAverage",sampleResStat.Average(),
                           "meters/pixel");
  pSampleRes += ValidateKey("SampleResolutionStandardDeviation",
                           sampleResStat.StandardDeviation(),"meters/pixel");

  PvlGroup pLineRes("LineResolution");
  pLineRes += ValidateKey("LineResolutionMinimum",lineResStat.Minimum(),
                         "meters/pixel");
  pLineRes += ValidateKey("LineResolutionMaximum",lineResStat.Maximum(),
                         "meters/pixel");
  pLineRes += ValidateKey("LineResolutionAverage",lineResStat.Average(),
                         "meters/pixel");
  pLineRes += ValidateKey("LineResolutionStandardDeviation",
                         lineResStat.StandardDeviation(),"meters/pixel");

  PvlGroup pResolution("Resolution");
  pResolution += ValidateKey("ResolutionMinimum",resStat.Minimum(),
                            "meters/pixel");
  pResolution += ValidateKey("ResolutionMaximum",resStat.Maximum(),
                            "meters/pixel");
  pResolution += ValidateKey("ResolutionAverage",resStat.Average(),
                            "meters/pixel");
  pResolution += ValidateKey("ResolutionStandardDeviation",
                            resStat.StandardDeviation(),"meters/pixel");

  PvlGroup pAspectRatio("AspectRatio");
  pAspectRatio += ValidateKey("AspectRatioMinimum",aspectRatioStat.Minimum());
  pAspectRatio += ValidateKey("AspectRatioMaximun",aspectRatioStat.Maximum());
  pAspectRatio += ValidateKey("AspectRatioAverage",aspectRatioStat.Average());
  pAspectRatio += ValidateKey("AspectRatioStandardDeviation",
                             aspectRatioStat.StandardDeviation());

  PvlGroup pPhase("PhaseAngle");
  pPhase += ValidateKey("PhaseMinimum",phaseStat.Minimum());
  pPhase += ValidateKey("PhaseMaximum",phaseStat.Maximum());
  pPhase += ValidateKey("PhaseAverage",phaseStat.Average());
  pPhase += ValidateKey("PhaseStandardDeviation",phaseStat.StandardDeviation());

  PvlGroup pEmission("EmissionAngle");
  pEmission += ValidateKey("EmissionMinimum",emissionStat.Minimum());
  pEmission += ValidateKey("EmissionMaximum",emissionStat.Maximum());
  pEmission += ValidateKey("EmissionAverage",emissionStat.Average());
  pEmission += ValidateKey("EmissionStandardDeviation",
                          emissionStat.StandardDeviation());

  PvlGroup pIncidence("IncidenceAngle");
  pIncidence += ValidateKey("IncidenceMinimum",incidenceStat.Minimum());
  pIncidence += ValidateKey("IncidenceMaximum",incidenceStat.Maximum());
  pIncidence += ValidateKey("IncidenceAverage",incidenceStat.Average());
  pIncidence += ValidateKey("IncidenceStandardDeviation",
                           incidenceStat.StandardDeviation());

  PvlGroup pTime("LocalSolarTime");
  pTime += ValidateKey("LocalSolarTimeMinimum",localSolarTimeStat.Minimum(),
                      "hours");
  pTime += ValidateKey("LocalSolarTimeMaximum",localSolarTimeStat.Maximum(),
                      "hours");
  pTime += ValidateKey("LocalSolarTimeAverage",localSolarTimeStat.Average(),
                      "hours");
  pTime += ValidateKey("LocalSolarTimeStandardDeviation",
                      localSolarTimeStat.StandardDeviation(),"hours");

  PvlGroup pLocalRadius("LocalRadius");
  pLocalRadius += ValidateKey("LocalRadiusMinimum",localRaduisStat.Minimum());
  pLocalRadius += ValidateKey("LocalRadiusMaximum",localRaduisStat.Maximum());
  pLocalRadius += ValidateKey("LocalRadiusAverage",localRaduisStat.Average());
  pLocalRadius += ValidateKey("LocalRadiusStandardDeviation",
                             localRaduisStat.StandardDeviation());

  PvlGroup pNorthAzimuth("NorthAzimuth");
  pNorthAzimuth += ValidateKey("NorthAzimuthMinimum",northAzimuthStat.Minimum());
  pNorthAzimuth += ValidateKey("NorthAzimuthMaximum",northAzimuthStat.Maximum());
  pNorthAzimuth += ValidateKey("NorthAzimuthAverage",northAzimuthStat.Average());
  pNorthAzimuth += ValidateKey("NorthAzimuthStandardDeviation",
                              northAzimuthStat.StandardDeviation());

  // Send the Output to the log area
  Application::Log(pUser);
  Application::Log(pLat);
  Application::Log(pLon);
  Application::Log(pSampleRes);
  Application::Log(pLineRes);
  Application::Log(pResolution);
  Application::Log(pAspectRatio);
  Application::Log(pPhase);
  Application::Log(pEmission);
  Application::Log(pIncidence);
  Application::Log(pTime);
  Application::Log(pLocalRadius);
  Application::Log(pNorthAzimuth);

  if (ui.WasEntered("TO")) {
    string from = ui.GetFilename("FROM");
    string outfile = Filename(ui.GetFilename("TO")).Expanded();
    bool exists = Filename(outfile).Exists();
    bool append = ui.GetBoolean("APPEND");

    //If the user chooses a fromat of PVL then write to the output file ("TO")
    if (ui.GetString("FORMAT") == "PVL") {
      Pvl temp;
      temp.SetTerminator("");
      temp.AddGroup(pUser);
      temp.AddGroup(pLat);
      temp.AddGroup(pLon);
      temp.AddGroup(pSampleRes);
      temp.AddGroup(pLineRes);
      temp.AddGroup(pResolution);
      temp.AddGroup(pAspectRatio);
      temp.AddGroup(pPhase);
      temp.AddGroup(pEmission);
      temp.AddGroup(pIncidence);
      temp.AddGroup(pTime);
      temp.AddGroup(pLocalRadius);
      temp.AddGroup(pNorthAzimuth);

      if (append) {
        temp.Append(outfile);
      }
      else {
        temp.Write(outfile);
      }
    }

    //Create a flatfile of the data with columhn headings 
    // the flatfile is comma delimited and can be imported in to spreadsheets
    else {
      ofstream os;
      bool writeHeader = true;
      if (append) {
        os.open(outfile.c_str(),ios::app);
        if (exists) {
          writeHeader = false;
        }
      }
      else {
        os.open(outfile.c_str(),ios::out);
      }

      // if new file or append and no file exists then write header
      if(writeHeader){
      os << "Filename,"<<
        "LatitudeMinimum,"<<
        "LatitudeMaximum,"<<
        "LatitudeAverage,"<<
        "LatitudeStandardDeviation,"<<
        "LongitudeMinimum,"<<
        "LongitudeMaximum,"<<
        "LongitudeAverage,"<<
        "LongitudeStandardDeviation,"<<
        "SampleResolutionMinimum,"<<
        "SampleResolutionMaximum,"<<
        "SampleResolutionAverage,"<<
        "SampleResolutionStandardDeviation,"<<
        "LineResolutionMinimum,"<<
        "LineResolutionMaximum,"<<
        "LineResolutionAverage,"<<
        "LineResolutionStandardDeviation,"<<
        "ResolutionMinimum,"<<
        "ResolutionMaximum,"<<
        "ResolutionAverage,"<<
        "ResolutionStandardDeviation,"<<
        "AspectRatioMinimum,"<<
        "AspectRatioMaximum,"<<
        "AspectRatioAverage,"<<
        "AspectRatioStandardDeviation,"<<
        "PhaseMinimum,"<<
        "PhaseMaximum,"<<
        "PhaseAverage,"<<
        "PhaseStandardDeviation,"<<
        "EmissionMinimum,"<<
        "EmissionMaximum,"<<
        "EmissionAverage,"<<
        "EmissionStandardDeviation,"<<
        "IncidenceMinimum,"<<
        "IncidenceMaximum,"<<
        "IncidenceAverage,"<<
        "IncidenceStandardDeviation,"<<
        "LocalSolarTimeMinimum,"<<
        "LocalSolarTimeMaximum,"<<
        "LocalSolarTimeAverage,"<<
        "LocalSolarTimeStandardDeviation,"<<
        "LocalRadiusMaximum,"<<
        "LocalRadiusMaximum,"<<
        "LocalRadiusAverage,"<<
        "LocalRadiusStandardDeviation,"<<
        "NorthAzimuthMinimum,"<<
        "NorthAzimuthMaximum,"<<
        "NorthAzimuthAverage,"<<
        "NorthAzimuthStandardDeviation,"<<endl;
      }
      os << Filename(from).Expanded() <<",";
        //call the function to write out the values for each group
        writeFlat(os, latStat);
        writeFlat(os, lonStat);
        writeFlat(os, sampleResStat);
        writeFlat(os, lineResStat);
        writeFlat(os, resStat);
        writeFlat(os, aspectRatioStat);
        writeFlat(os, phaseStat);
        writeFlat(os, emissionStat);
        writeFlat(os, incidenceStat);
        writeFlat(os, localSolarTimeStat);
        writeFlat(os, localRaduisStat);
        writeFlat(os, northAzimuthStat);
        os << endl;
    }
  }

  if( ui.GetBoolean("ATTACH") ) {

    string cam_name = "CameraStatistics";

    //Creates new CameraStatistics Table
    TableField fname( "Name", Isis::TableField::Text, 20 );
    TableField fmin( "Minimum", Isis::TableField::Double );
    TableField fmax( "Maximum", Isis::TableField::Double );
    TableField favg( "Average", Isis::TableField::Double );
    TableField fstd( "StandardDeviation", Isis::TableField::Double );

    TableRecord record;
    record += fname;
    record += fmin;
    record += fmax;
    record += favg;
    record += fstd;

    Table table( cam_name, record );

    vector<PvlGroup> grps;
    grps.push_back( pLat );
    grps.push_back( pLon );
    grps.push_back( pSampleRes );
    grps.push_back( pLineRes );
    grps.push_back( pResolution );
    grps.push_back( pAspectRatio );
    grps.push_back( pPhase );
    grps.push_back( pEmission );
    grps.push_back( pIncidence );
    grps.push_back( pTime );
    grps.push_back( pLocalRadius );
    grps.push_back( pNorthAzimuth );

    for( vector<PvlGroup>::iterator g = grps.begin(); g != grps.end(); g++ ) {
      int i = 0;
      record[i++] = g->Name();
      record[i++] = (double) (*g)[0][0];
      record[i++] = (double) (*g)[1][0];
      record[i++] = (double) (*g)[2][0];
      record[i++] = (double) (*g)[3][0];
      table += record;
    }

    icube->ReOpen( "rw" );
    icube->Write( table );
    p.WriteHistory(*icube);
    icube->Close();

  }

}
Esempio n. 5
0
void IsisMain() {

  // Get the list of cubes to mosaic

  UserInterface &ui = Application::GetUserInterface();
  FileList flist(ui.GetFilename("FROMLIST"));


  vector<Cube *> clist;
  try {
    if (flist.size() < 1) {
      string msg = "the list file [" +ui.GetFilename("FROMLIST") +
                   "does not contain any data";
      throw iException::Message(iException::User,msg,_FILEINFO_);
    }

    // open all the cube and place in vector clist  

    for (int i=0; i<(int)flist.size(); i++) {
      Cube *c = new Cube();
      clist.push_back(c);
      c->Open(flist[i]);
    }



    // run the compair function here.  This will conpair the 
    // labels of the first cube to the labels of each following cube. 
    PvlKeyword sourceProductId("SourceProductId");
    string ProdId;
    for (int i=0; i<(int)clist.size(); i++) {
      Pvl *pmatch = clist[0]->Label();
      Pvl *pcomp = clist[i]->Label();
      CompareLabels(*pmatch, *pcomp);
      PvlGroup g = pcomp->FindGroup("Instrument",Pvl::Traverse);
      if (g.HasKeyword("StitchedProductIds")) {
        PvlKeyword k = g["StitchedProductIds"];
        for (int j=0; j<(int)k.Size(); j++) {
          sourceProductId += g["stitchedProductIds"][j];
        }     
      }
      ProdId = (string)pmatch->FindGroup("Archive",Pvl::Traverse)["ObservationId"];
      iString bandname = (string)pmatch->FindGroup("BandBin",Pvl::Traverse)["Name"];
      bandname = bandname.UpCase();
      ProdId = ProdId + "_" + bandname;
    }
    bool runXY=true;

    //calculate the min and max lon
    double minLat = DBL_MAX;
    double maxLat = -DBL_MAX;
    double minLon = DBL_MAX;
    double maxLon = -DBL_MAX;
    double avgLat;
    double avgLon;
    for (int i=0; i<(int)clist.size(); i++) {
      Projection *proj = clist[i]->Projection();
      if (proj->MinimumLatitude() < minLat) minLat = proj->MinimumLatitude();
      if (proj->MaximumLatitude() > maxLat) maxLat = proj->MaximumLatitude();
      if (proj->MinimumLongitude() < minLon) minLon = proj->MinimumLongitude();
      if (proj->MaximumLongitude() > maxLon) maxLon = proj->MaximumLongitude();
    }
    avgLat = (minLat + maxLat) / 2;
    avgLon = (minLon + maxLon) / 2;
    Projection *proj = clist[0]->Projection();
    proj->SetGround(avgLat,avgLon);
    avgLat = proj->UniversalLatitude();
    avgLon = proj->UniversalLongitude();

    // Use camera class to get Inc., emi., phase, and other values
    double Cemiss;
    double Cphase;
    double Cincid;
    double ClocalSolTime;
    double CsolarLong;
    double CsunAzimuth;
    double CnorthAzimuth;
    for (int i=0; i<(int)clist.size(); i++) {
      Camera *cam = clist[i]->Camera();
      if (cam->SetUniversalGround(avgLat,avgLon)) {
        Cemiss = cam->EmissionAngle();
        Cphase = cam->PhaseAngle();
        Cincid = cam->IncidenceAngle();
        ClocalSolTime = cam->LocalSolarTime();
        CsolarLong = cam->SolarLongitude();
        CsunAzimuth = cam->SunAzimuth();
        CnorthAzimuth = cam->NorthAzimuth();
        runXY = false;
        break;
      }
    }

    //The code within the if runXY was added in 10/07 to find an intersect with
    //pole images that would fail when using projection set universal ground.  
    // This is run if no intersect is found when using lat and lon in 
    // projection space.
    if (runXY) {
      double startX = DBL_MAX;
      double endX = DBL_MIN;
      double startY = DBL_MAX;
      double endY =  DBL_MIN;
      for (int i=0; i<(int)clist.size(); i++) {
        Projection *proj = clist[i]->Projection();
        proj->SetWorld(0.5,0.5);
        if (i==0) {
          startX = proj->XCoord();
          endY = proj->YCoord();
        }
        else {
          if (proj->XCoord() < startX) startX =  proj->XCoord();
          if (proj->YCoord() > endY) endY = proj->YCoord();
        }
        Pvl *p = clist[i]->Label();
        double nlines = p->FindGroup("Dimensions",Pvl::Traverse)["Lines"];
        double nsamps = p->FindGroup("Dimensions",Pvl::Traverse)["Samples"];

        proj->SetWorld((nsamps+0.5),(nlines+0.5));
        if (i==0) {
          endX = proj->XCoord();
          startY = proj->YCoord();
        }
        else {
          if (proj->XCoord() > endX) endX =  proj->XCoord();
          if (proj->YCoord() < startY) startY = proj->YCoord();
        }
      }

      double avgX = (startX + endX) / 2;
      double avgY = (startY + endY) / 2;
      double sample = proj->ToWorldX(avgX);
      double line = proj->ToWorldY(avgY);

      for (int i=0; i<(int)clist.size(); i++) {
        Camera *cam = clist[i]->Camera();
        if (cam->SetImage(sample,line)) {
          Cemiss = cam->EmissionAngle();
          Cphase = cam->PhaseAngle();
          Cincid = cam->IncidenceAngle();
          ClocalSolTime = cam->LocalSolarTime();
          CsolarLong = cam->SolarLongitude();
          CsunAzimuth = cam->SunAzimuth();
          CnorthAzimuth = cam->NorthAzimuth();
          runXY = false;
          break;
        }
      }
    }
    if (runXY) {
      string msg = "Camera did not intersect images to gather stats";
      throw iException::Message(iException::User,msg,_FILEINFO_);
    }

    // get the min and max SCLK values ( do this with string comp.)
    // get the value from the original label blob
    string startClock;
    string stopClock;
    string startTime;
    string stopTime;
    for (int i=0; i<(int)clist.size(); i++) {
      OriginalLabel origLab;
      clist[i]->Read(origLab);
      PvlGroup timegrp = origLab.ReturnLabels().FindGroup("TIME_PARAMETERS",Pvl::Traverse);
      if (i==0) {
        startClock = (string)timegrp["SpacecraftClockStartCount"];
        stopClock = (string)timegrp["SpacecraftClockStopCount"];
        startTime = (string)timegrp["StartTime"];
        stopTime = (string)timegrp["StopTime"];
      }
      else {
        string testStartTime = (string)timegrp["StartTime"];
        string testStopTime = (string)timegrp["StopTime"];
        if (testStartTime < startTime) {
          startTime = testStartTime;
          startClock = (string)timegrp["SpacecraftClockStartCount"];
        }
        if (testStopTime > stopTime) {
          stopTime = testStopTime;
          stopClock = (string)timegrp["spacecraftClockStopCount"];
        }
      }
    }

    //  Concatenate all TDI's and summing and specialProcessingFlat into one keyword 
    PvlKeyword cpmmTdiFlag("cpmmTdiFlag");
    PvlKeyword cpmmSummingFlag("cpmmSummingFlag");
    PvlKeyword specialProcessingFlag("SpecialProcessingFlag");
    for (int i=0; i<14; i++) {
      cpmmTdiFlag +=(string)"";
      cpmmSummingFlag +=(string)"";
      specialProcessingFlag +=(string)"";
    }

    for (int i=0; i<(int)clist.size(); i++) {
      Pvl *clab = clist[i]->Label();
      PvlGroup cInst = clab->FindGroup("Instrument",Pvl::Traverse);
      OriginalLabel cOrgLab;
      clist[i]->Read(cOrgLab);
      PvlGroup cGrp = cOrgLab.ReturnLabels().FindGroup("INSTRUMENT_SETTING_PARAMETERS",Pvl::Traverse);
      cpmmTdiFlag[(int)cInst["CpmmNumber"]] = (string) cGrp["MRO:TDI"];
      cpmmSummingFlag[(int)cInst["CpmmNumber"]] = (string) cGrp["MRO:BINNING"];

      if (cInst.HasKeyword("Special_Processing_Flag")) {
        specialProcessingFlag[cInst["CpmmNumber"]] = (string) cInst["Special_Processing_Flag"];
      }
      else {
        // there may not be the keyword Special_Processing_Flag if no
        //keyword then set the output to NOMINAL
        specialProcessingFlag[cInst["CpmmNumber"]] = "NOMINAL";
      }
    }


    // Get the blob of original labels from first image in list
    OriginalLabel org;
    clist[0]->Read(org);

    //close all cubes
    for (int i=0; i<(int)clist.size(); i++) {
      clist[i]->Close();
      delete clist[i];
    }
    clist.clear();

    // automos step
    string list = ui.GetFilename("FROMLIST");
    string toMosaic = ui.GetFilename("TO");
    string MosaicPriority = ui.GetString("PRIORITY");

    string parameters = "FROMLIST=" + list + " MOSAIC=" + toMosaic + " PRIORITY=" + MosaicPriority;
    Isis::iApp ->Exec("automos",parameters);

    // write out new information to new group mosaic 

    PvlGroup mos("Mosaic");
    mos += PvlKeyword("ProductId ", ProdId);
    mos += PvlKeyword(sourceProductId); 
    mos += PvlKeyword("StartTime ", startTime);
    mos += PvlKeyword("SpacecraftClockStartCount ", startClock);
    mos += PvlKeyword("StopTime ", stopTime);
    mos += PvlKeyword("SpacecraftClockStopCount ", stopClock);
    mos += PvlKeyword("IncidenceAngle ", Cincid, "DEG");
    mos += PvlKeyword("EmissionAngle ", Cemiss, "DEG");
    mos += PvlKeyword("PhaseAngle ", Cphase, "DEG");
    mos += PvlKeyword("LocalTime ", ClocalSolTime, "LOCALDAY/24");
    mos += PvlKeyword("SolarLongitude ", CsolarLong, "DEG");
    mos += PvlKeyword("SubSolarAzimuth ", CsunAzimuth, "DEG");
    mos += PvlKeyword("NorthAzimuth ", CnorthAzimuth, "DEG");
    mos += cpmmTdiFlag;
    mos += cpmmSummingFlag;
    mos += specialProcessingFlag;

    Cube mosCube;
    mosCube.Open(ui.GetFilename("TO"), "rw");
    PvlObject &lab=mosCube.Label()->FindObject("IsisCube");
    lab.AddGroup(mos);
    //add orginal label blob to the output cube
    mosCube.Write(org);
    mosCube.Close();

  }
  catch (iException &e) {
    for (int i=0; i<(int)clist.size(); i++) {
      clist[i]->Close();
      delete clist[i];
    }
    string msg = "The mosaic [" + ui.GetFilename("TO") + "] was NOT created";
    throw iException::Message(iException::User,msg,_FILEINFO_);
  }
} // end of isis main