int main () { Isis::Preference::Preferences(true); /** * @brief Test ImagePolygon object for accuracy and correct behavior. * * @author 2005-11-22 Tracie Sucharski * * @history 2007-01-19 Tracie Sucharski, Removed ToGround method (for now) * because of round off problems going back and forth between * lat/lon,line/samp. * @history 2007-01-31 Tracie Sucharski, Added WKT method to return polygon * in string as WKT. * @history 2007-11-09 Tracie Sucharski, Remove WKT method, geos now has * a method to return a WKT string. * @history 2007-11-20 Tracie Sucharski, Added test for sub-polys */ // simple MOC image string inFile = "/usgs/cpkgs/isis3/data/mgs/testData/ab102401.cub"; //string inFile = "/work1/tsucharski/poly/I17621017RDR_lev2.cub"; // same MOC image, but sinusoidal projection //string inFile = "/farm/prog1/tsucharski/isis3/ab102401.lev2.cub"; // same MOC image, but sinusoidal projection , doctored left edge //string inFile = "/farm/prog1/tsucharski/isis3/ab102401.lev2.leftTrim.cub"; // MOC north pole image //string inFile = "/work1/tsucharski/isis3/poly/e0202226.lev1.cub"; // MOC image with 0/360 boundary // orkin //string inFile = "/farm/prog1/tsucharski/isis3/cubes/m0101631.lev1.cub"; // blackflag //string inFile = "/work1/tsucharski/isis3/poly/m0101631.lev1.cub"; // galileo ssi image //string inFile = "/farm/prog1/tsucharski/isis3/6700r.cub"; // Open the cube Cube cube; Cube cube1; cube.Open(inFile,"r"); ImagePolygon poly; try { poly.Create(cube); } catch (iException &e) { std::string msg = "Cannot create polygon for [" + cube.Filename() + "]"; throw iException::Message(iException::Programmer,msg,_FILEINFO_); } // write poly as WKT std::cout<< poly.Polys()->toString()<<std::endl; // Test sub-poly option try { poly.Create(cube,12,1,384,640,385); } catch (iException &e) { std::string msg = "Cannot create sub-polygon for [" + cube.Filename() + "]"; throw iException::Message(iException::Programmer,msg,_FILEINFO_); } // write poly as WKT std::cout<< poly.Polys()->toString()<<std::endl; // Test lower quality option try { poly.Create(cube,10,12,1,384,640,385); } catch (iException &e) { std::string msg = "Cannot create lower quality polygon for [" + cube.Filename() + "]"; throw iException::Message(iException::Programmer,msg,_FILEINFO_); } // write poly as WKT std::cout<< poly.Polys()->toString()<<std::endl; cube.Close(); }
/** * This is the main method. Makeflat runs in three steps: * * 1) Calculate statistics * - For all cameras, this checks for one band and matching * sample counts. * - For framing cameras, this checks the standard deviation of * the images and records the averages of each image * - For push frame cameras, this calls CheckFramelets for each * image. * * 2) Create the temporary file, collect more detailed statistics * - For all cameras, this generates the temporary file and calculates * the final exclusion list * - For framing/push frame cameras, the temporary file is * 2 bands, where the first is a sum of DNs from each image/framelet * and the second band is a count of valid DNs that went into each sum * * 3) Create the final flat field file * - For all cameras, this processes the temporary file to create the final flat * field file. */ void IsisMain() { // Initialize variables ResetGlobals(); UserInterface &ui = Application::GetUserInterface(); maxStdev = ui.GetDouble("STDEVTOL"); if(ui.GetString("IMAGETYPE") == "FRAMING") { cameraType = Framing; // framing cameras need to figure this out automatically // during step 1 numFrameLines = -1; } else if(ui.GetString("IMAGETYPE") == "LINESCAN") { cameraType = LineScan; numFrameLines = ui.GetInteger("NUMLINES"); } else { cameraType = PushFrame; numFrameLines = ui.GetInteger("FRAMELETHEIGHT"); } FileList inList(ui.GetFilename("FROMLIST")); Progress progress; tempFileLength = 0; numOutputSamples = 0; /** * Line scan progress is based on the input list, whereas * the other cameras take much longer and are based on the * images themselves. Prepare the progress if we're doing * line scan. */ if(cameraType == LineScan) { progress.SetText("Calculating Number of Image Lines"); progress.SetMaximumSteps(inList.size()); progress.CheckStatus(); } /** * For a push frame camera, the temp file is one framelet. * Technically this is the same for the framing, but we * don't know the height of a framelet yet. */ if(cameraType == PushFrame) { tempFileLength = numFrameLines; } /** * Start pass 1, use global currImage so that methods called * know the image we're processing. */ for(currImage = 0; currImage < inList.size(); currImage++) { /** * Read the current cube into memory */ Cube tmp; tmp.Open(Filename(inList[currImage]).Expanded()); /** * If we haven't determined how many samples the output * should have, we can do so now */ if(numOutputSamples == 0 && tmp.Bands() == 1) { numOutputSamples = tmp.Samples(); } /** * Try and validate the image, quick tests first! * * (imageValid &= means imageValid = imageValid && ...) */ bool imageValid = true; // Only single band images are acceptable imageValid &= (tmp.Bands() == 1); // Sample sizes must always match imageValid &= (numOutputSamples == tmp.Samples()); // For push frame cameras, there must be valid all framelets if(cameraType == PushFrame) { imageValid &= (tmp.Lines() % numFrameLines == 0); } // For framing cameras, we need to figure out the size... // setTempFileLength is used to revert if the file // is decided to be invalid bool setTempFileLength = false; if(cameraType == Framing) { if(tempFileLength == 0 && imageValid) { tempFileLength = tmp.Lines(); numFrameLines = tempFileLength; setTempFileLength = true; } imageValid &= (tempFileLength == tmp.Lines()); } // Statistics are necessary at this point for push frame and framing cameras // because the framing camera standard deviation tolerance is based on // entire images, and push frame framelet exclusion stats can not be collected // during pass 2 cleanly if((cameraType == Framing || cameraType == PushFrame) && imageValid) { string prog = "Calculating Standard Deviation " + iString((int)currImage+1) + "/"; prog += iString((int)inList.size()) + " (" + Filename(inList[currImage]).Name() + ")"; if(cameraType == Framing) { Statistics *stats = tmp.Statistics(1, prog); imageValid &= !IsSpecial(stats->StandardDeviation()); imageValid &= !IsSpecial(stats->Average()); imageValid &= stats->StandardDeviation() <= maxStdev; vector<double> fileStats; fileStats.push_back(stats->Average()); inputFrameletAverages.push_back(fileStats); delete stats; } else if(cameraType == PushFrame) { imageValid &= CheckFramelets(prog, tmp); } if(setTempFileLength && !imageValid) { tempFileLength = 0; } } // The line scan camera needs to actually count the number of lines in each image to know // how many total frames there are before beginning pass 2. if(imageValid && (cameraType == LineScan)) { int lines = (tmp.Lines() / numFrameLines); // partial frame? if(tmp.Lines() % numFrameLines != 0) { lines ++; } tempFileLength += lines; } else if(!imageValid) { excludedFiles.insert(pair<int, bool>(currImage, true)); } tmp.Close(); if(cameraType == LineScan) { progress.CheckStatus(); } } /** * If the number of output samples could not be determined, we never * found a legitimate cube. */ if(numOutputSamples <= 0) { string msg = "No valid input cubes were found"; throw iException::Message(iException::User,msg,_FILEINFO_); } /** * If theres no temp file length, which is based off of valid data in * the input cubes, then we havent found any valid data. */ if(tempFileLength <= 0) { string msg = "No valid input data was found"; throw iException::Message(iException::User,msg,_FILEINFO_); } /** * ocube is now the temporary file (for pass 2). */ ocube = new Cube(); ocube->SetDimensions(numOutputSamples, tempFileLength, 2); PvlGroup &prefs = Preference::Preferences().FindGroup("DataDirectory", Pvl::Traverse); iString outTmpName = (string)prefs["Temporary"][0] + "/"; outTmpName += Filename(ui.GetFilename("TO")).Basename() + ".tmp.cub"; ocube->Create(outTmpName); oLineMgr = new LineManager(*ocube); oLineMgr->SetLine(1); ProcessByBrick p; int excludedCnt = 0; if(cameraType == LineScan) { outputTmpAverages.resize(numOutputSamples); outputTmpCounts.resize(numOutputSamples); numInputDns.resize(numOutputSamples); } cubeInitialized = false; for(currImage = 0; currImage < inList.size(); currImage++) { if(Excluded(currImage)) { excludedCnt ++; continue; } PvlObject currFile("Exclusions"); currFile += PvlKeyword("Filename", inList[currImage]); currFile += PvlKeyword("Tolerance", maxStdev); if(cameraType == LineScan) { currFile += PvlKeyword("FrameLines", numFrameLines); } else if(cameraType == PushFrame) { currFile += PvlKeyword("FrameletLines", numFrameLines); } excludedDetails.push_back(currFile); CubeAttributeInput inAtt; // This needs to be set constantly because ClearInputCubes // seems to be removing the input brick size. if(cameraType == LineScan) { p.SetBrickSize(1, numFrameLines, 1); } else if(cameraType == Framing || cameraType == PushFrame) { p.SetBrickSize(numOutputSamples, 1, 1); } p.SetInputCube(inList[currImage], inAtt); iString progText = "Calculating Averages " + iString((int)currImage+1); progText += "/" + iString((int)inList.size()); progText += " (" + Filename(inList[currImage]).Name() + ")"; p.Progress()->SetText(progText); p.StartProcess(CreateTemporaryData); p.EndProcess(); p.ClearInputCubes(); if(excludedDetails[excludedDetails.size()-1].Groups() == 0) { excludedDetails.resize(excludedDetails.size()-1); } } /** * Pass 2 completed. The processing methods were responsible for writing * the entire temporary cube. */ if(oLineMgr) { delete oLineMgr; oLineMgr = NULL; } if(ocube) { ocube->Close(); delete ocube; } /** * ocube is now the final output */ ocube = new Cube(); if(cameraType == LineScan) { ocube->SetDimensions(numOutputSamples, 1, 1); } else if(cameraType == Framing || cameraType == PushFrame) { ocube->SetDimensions(numOutputSamples, tempFileLength, 1); } ocube->Create(Filename(ui.GetFilename("TO")).Expanded()); oLineMgr = new LineManager(*ocube); oLineMgr->SetLine(1); // We now have the necessary temp file, let's go ahead and combine it into // the final output! p.SetInputBrickSize(numOutputSamples, 1, 2); p.SetOutputBrickSize(numOutputSamples, 1, 1); cubeInitialized = false; CubeAttributeInput inAtt; p.Progress()->SetText("Calculating Final Flat Field"); p.SetInputCube(outTmpName, inAtt); p.StartProcess(ProcessTemporaryData); p.EndProcess(); if(cameraType == LineScan) { ocube->Write(*oLineMgr); } if(oLineMgr) { delete oLineMgr; oLineMgr = NULL; } if(ocube) { ocube->Close(); delete ocube; ocube = NULL; } /** * Build a list of excluded files */ PvlGroup excludedFiles("ExcludedFiles"); for(currImage = 0; currImage < inList.size(); currImage++) { if(Excluded(currImage)) { excludedFiles += PvlKeyword("File", inList[currImage]); } } // log the results Application::Log(excludedFiles); if(ui.WasEntered("EXCLUDE")) { Pvl excludeFile; // Find excluded files excludeFile.AddGroup(excludedFiles); for(unsigned int i = 0; i < excludedDetails.size(); i++) { excludeFile.AddObject(excludedDetails[i]); } excludeFile.Write(Filename(ui.GetFilename("EXCLUDE")).Expanded()); } remove(outTmpName.c_str()); // Clean up settings ResetGlobals(); }
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_); } }
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(); } }
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