void IsisMain() { // We will be processing by line ProcessByLine p; // Setup the input and output files UserInterface &ui = Application::GetUserInterface(); // Setup the input and output cubes p.SetInputCube("FROM1"); if (ui.WasEntered ("FROM2")) p.SetInputCube("FROM2"); p.SetOutputCube ("TO"); // Get the coefficients Isisa = ui.GetDouble ("A"); Isisb = ui.GetDouble ("B"); Isisc = ui.GetDouble ("C"); Isisd = ui.GetDouble ("D"); Isise = ui.GetDouble ("E"); // Start the processing based on the operator string op = ui.GetString ("OPERATOR"); if (op == "ADD" ) p.StartProcess(add); if (op == "SUBTRACT") p.StartProcess(sub); if (op == "MULTIPLY") p.StartProcess(mult); if (op == "DIVIDE") p.StartProcess(div); if (op == "UNARY") p.StartProcess(unary); // Cleanup p.EndProcess(); }
void IsisMain() { latLonGrid = NULL; // We will be processing by line ProcessByLine p; Cube *icube = p.SetInputCube("FROM"); UserInterface &ui = Application::GetUserInterface(); string mode = ui.GetString("MODE"); outline = ui.GetBoolean("OUTLINE"); inputSamples = icube->Samples(); inputLines = icube->Lines(); // Line & sample based grid if(mode == "IMAGE") { p.SetOutputCube ("TO"); baseLine = ui.GetInteger("BASELINE"); baseSample = ui.GetInteger("BASESAMPLE"); lineInc = ui.GetInteger("LINC"); sampleInc = ui.GetInteger("SINC"); p.StartProcess(imageGrid); p.EndProcess(); } // Lat/Lon based grid else { CubeAttributeOutput oatt("+32bit"); p.SetOutputCube (ui.GetFilename("TO"), oatt, icube->Samples(), icube->Lines(), icube->Bands()); baseLat = ui.GetDouble("BASELAT"); baseLon = ui.GetDouble("BASELON"); latInc = ui.GetDouble("LATINC"); lonInc = ui.GetDouble("LONINC"); UniversalGroundMap *gmap = new UniversalGroundMap(*icube); latLonGrid = new GroundGrid(gmap, icube->Samples(), icube->Lines()); Progress progress; progress.SetText("Calculating Grid"); latLonGrid->CreateGrid(baseLat, baseLon, latInc, lonInc, &progress); p.StartProcess(groundGrid); p.EndProcess(); delete latLonGrid; latLonGrid = NULL; delete gmap; gmap = NULL; } }
/** * Set the output cube to specified file name and specified input images * and output attributes and lat,lons */ Isis::Cube *ProcessMapMosaic::SetOutputCube(const QString &inputFile, double xmin, double xmax, double ymin, double ymax, double slat, double elat, double slon, double elon, int nbands, CubeAttributeOutput &oAtt, const QString &mosaicFile) { Pvl fileLab(inputFile); PvlGroup &mapping = fileLab.findGroup("Mapping", Pvl::Traverse); mapping["UpperLeftCornerX"] = toString(xmin); mapping["UpperLeftCornerY"] = toString(ymax); mapping.addKeyword(PvlKeyword("MinimumLatitude", toString(slat)), Pvl::Replace); mapping.addKeyword(PvlKeyword("MaximumLatitude", toString(elat)), Pvl::Replace); mapping.addKeyword(PvlKeyword("MinimumLongitude", toString(slon)), Pvl::Replace); mapping.addKeyword(PvlKeyword("MaximumLongitude", toString(elon)), Pvl::Replace); Projection *firstProj = ProjectionFactory::CreateFromCube(fileLab); int samps = (int)(ceil(firstProj->ToWorldX(xmax) - firstProj->ToWorldX(xmin)) + 0.5); int lines = (int)(ceil(firstProj->ToWorldY(ymin) - firstProj->ToWorldY(ymax)) + 0.5); delete firstProj; if (p_createMosaic) { Pvl newMap; newMap.addGroup(mapping); // Initialize the mosaic CubeAttributeInput inAtt; ProcessByLine p; p.SetInputCube(inputFile, inAtt); p.PropagateHistory(false); p.PropagateLabels(false); p.PropagateTables(false); p.PropagatePolygons(false); p.PropagateOriginalLabel(false); // If track set, create the origin band if (GetTrackFlag()) { nbands += 1; } // For average priority, get the new band count else if (GetImageOverlay() == AverageImageWithMosaic) { nbands *= 2; } Cube *ocube = p.SetOutputCube(mosaicFile, oAtt, samps, lines, nbands); p.Progress()->SetText("Initializing mosaic"); p.ClearInputCubes(); p.StartProcess(ProcessMapMosaic::FillNull); // CreateForCube created some keywords in the mapping group that needs to be added ocube->putGroup(newMap.findGroup("Mapping", Pvl::Traverse)); p.EndProcess(); } Cube *mosaicCube = new Cube(); mosaicCube->open(mosaicFile, "rw"); mosaicCube->addCachingAlgorithm(new UniqueIOCachingAlgorithm(2)); AddOutputCube(mosaicCube); return mosaicCube; }
void IsisMain() { // Create a process by line object ProcessByLine p; // Get the size of the cube Cube *icube = p.SetInputCube("FROM"); // Open output text file UserInterface &ui = Application::GetUserInterface(); QString to = ui.GetFileName("TO", "txt"); fout.open(to.toAscii().data()); // Print header if needed if(ui.GetBoolean("HEADER")) { fout << "Input Cube: " << icube->fileName() << endl; fout << "Samples:Lines:Bands: " << icube->sampleCount() << ":" << icube->lineCount() << ":" << icube->bandCount() << endl; } // List the cube p.StartProcess(isis2ascii); p.EndProcess(); fout.close(); }
void IsisMain() { // We will be processing by line ProcessByLine p; // Set up the input cube and get camera information Cube *icube = p.SetInputCube("FROM"); // Create the output cube Cube *ocube = p.SetOutputCube("TO"); // Set up the user interface UserInterface &ui = Application::GetUserInterface(); // Get the name of the parameter file Pvl par(ui.GetFileName("PHOPAR")); auto_ptr<Hillier> photom = auto_ptr<Hillier> (new Hillier(par, *icube)); pho = photom.get(); // Start the processing p.StartProcess(hillier); PvlGroup photo("Photometry"); pho->Report(photo); ocube->putGroup(photo); Application::Log(photo); p.EndProcess(); }
void IsisMain() { // We will be processing by line ProcessByLine p; // Setup the input and get the camera model icube = p.SetInputCube("FROM"); cam = icube->Camera(); // Create the output cube p.SetOutputCube ("TO"); // Get the trim angles UserInterface &ui = Application::GetUserInterface(); minPhase = ui.GetDouble ("MINPHASE"); maxPhase = ui.GetDouble ("MAXPHASE"); minEmission = ui.GetDouble ("MINEMISSION"); maxEmission = ui.GetDouble ("MAXEMISSION"); minIncidence = ui.GetDouble ("MININCIDENCE"); maxIncidence = ui.GetDouble ("MAXINCIDENCE"); // Start the processing lastBand = 0; p.StartProcess(photrim); p.EndProcess(); }
void IsisMain() { ProcessByLine p; p.SetInputCube("NUMERATOR"); p.SetInputCube("DENOMINATOR"); p.SetOutputCube("TO"); p.StartProcess(ratio); p.EndProcess(); }
void IsisMain() { UserInterface &ui = Application::GetUserInterface(); tempFiles.clear(); specificEnergyCorrections.clear(); sampleBasedDarkCorrections.clear(); lineBasedDarkCorrections.clear(); solarRemoveCoefficient = 1.0; iof = (ui.GetString("UNITS") == "IOF"); calibInfo = PvlGroup("Results"); ProcessByLine p; Cube *icube = p.SetInputCube("FROM"); bool isVims = true; try { isVims = (icube->label()->findGroup("Instrument", Pvl::Traverse)["InstrumentId"][0] == "VIMS"); } catch(IException &e) { isVims = false; } if(!isVims) { QString msg = "The input cube [" + QString(ui.GetAsString("FROM")) + "] is not a Cassini VIMS cube"; throw IException(IException::User, msg, _FILEINFO_); } if(icube->label()->findObject("IsisCube").hasGroup("AlphaCube")) { QString msg = "The input cube [" + QString(ui.GetAsString("FROM")) + "] has had its dimensions modified and can not be calibrated"; throw IException(IException::User, msg, _FILEINFO_); } // done first since it's likely to cause an error if one exists calculateSolarRemove(icube, &p); if(ui.GetBoolean("DARK")) calculateDarkCurrent(icube); chooseFlatFile(icube, &p); calculateSpecificEnergy(icube); calibInfo += PvlKeyword("OutputUnits", ((iof) ? "I/F" : "Specific Energy")); Application::Log(calibInfo); p.SetOutputCube("TO"); p.StartProcess(calibrate); p.EndProcess(); for(unsigned int i = 0; i < tempFiles.size(); i++) { QFile::remove(tempFiles[i]); } tempFiles.clear(); }
void IsisMain () { ProcessByLine p; Cube *icube = p.SetInputCube("FROM"); cam = icube->Camera(); maxinc = Application::GetUserInterface().GetDouble("MAXINC"); p.SetOutputCube("TO"); p.StartProcess(divide); p.EndProcess(); }
/** * Set the output cube to specified file name and specified input images * and output attributes and lat,lons */ Isis::Cube *ProcessMapMosaic::SetOutputCube(const QString &inputFile, PvlGroup mapping, CubeAttributeOutput &oAtt, const QString &mosaicFile) { if (OutputCubes.size() != 0) { QString msg = "You can only specify one output cube and projection"; throw IException(IException::Programmer, msg, _FILEINFO_); } if (mapping.hasKeyword("UpperLeftCornerX")) mapping.deleteKeyword("UpperLeftCornerX"); if (mapping.hasKeyword("UpperLeftCornerY")) mapping.deleteKeyword("UpperLeftCornerY"); if (p_createMosaic) { Pvl newMap; newMap.addGroup(mapping); int samps, lines, bands; delete ProjectionFactory::CreateForCube(newMap, samps, lines, false); // Initialize the mosaic ProcessByLine p; CubeAttributeInput inAtt(inputFile); Cube *propCube = p.SetInputCube(inputFile, inAtt); bands = propCube->bandCount(); // If track set, create the origin band if (GetTrackFlag()) { bands += 1; } // For average priority, get the new band count else if (GetImageOverlay() == AverageImageWithMosaic) { bands *= 2; } p.PropagateHistory(false); p.PropagateLabels(false); Cube *ocube = p.SetOutputCube(mosaicFile, oAtt, samps, lines, bands); p.Progress()->SetText("Initializing mosaic"); p.ClearInputCubes(); p.StartProcess(ProcessMapMosaic::FillNull); // CreateForCube created some keywords in the mapping group that needs to be added ocube->putGroup(newMap.findGroup("Mapping", Pvl::Traverse)); p.EndProcess(); } Cube *mosaicCube = new Cube(); AddOutputCube(mosaicCube); mosaicCube->open(mosaicFile, "rw"); mosaicCube->addCachingAlgorithm(new UniqueIOCachingAlgorithm(2)); return mosaicCube; }
void IsisMain() { ProcessByLine p; // Setup the input and output cubes p.SetInputCube("FROM"); p.SetInputCube("MATCH"); p.SetOutputCube("TO"); p.StartProcess(specadd); p.EndProcess(); }
void IsisMain() { // We will be processing by line ProcessByLine p; // Setup the input and output cubes p.SetInputCube("FROM"); p.SetOutputCube("TO"); // Start the processing p.StartProcess(mirror); p.EndProcess(); }
void IsisMain() { // Setup the input and output cubes ProcessByLine p; // used for getting histograms from input cubes Cube *icube = p.SetInputCube("FROM", Isis::OneBand); p.SetOutputCube ("TO"); // Histogram parameters UserInterface &ui = Application::GetUserInterface(); double minimum = ui.GetDouble("MINPER"); double maximum = ui.GetDouble("MAXPER"); int increment = ui.GetInteger("INCREMENT"); // Histograms from input cubes Histogram *from = icube->Histogram(); Histogram *match = icube->Histogram(); double fromMin = from->Percent(minimum); double fromMax = from->Percent(maximum); int fromBins = from->Bins(); double data[fromBins]; double slope = (fromMax - fromMin) / (fromBins - 1); // Set "match" to have the same data range and number of bins as "to" match->SetBins(fromBins); match->SetValidRange(fromMin, fromMax); for (int i = 0; i < fromBins; i++) { data[i] = fromMin + (slope * i); } match->AddData(data, fromBins); stretch.ClearPairs(); double lastPer = from->Percent(minimum); stretch.AddPair(lastPer, match->Percent(minimum)); for (double i = increment+minimum; i < maximum; i += increment) { double curPer = from->Percent(i); if (lastPer < curPer) { if(abs(lastPer - curPer) > DBL_EPSILON) { stretch.AddPair(curPer, match->Percent(i)); lastPer = curPer; } } } double curPer = from->Percent(maximum); if (lastPer < curPer && abs(lastPer - curPer) > DBL_EPSILON) { stretch.AddPair(curPer, match->Percent(maximum)); } // Start the processing p.StartProcess(remap); p.EndProcess(); }
void IsisMain() { // We will be processing by line ProcessByLine p; // Setup the input and output cubes p.SetInputCube("FROM"); p.SetOutputCube ("TO"); UserInterface &ui = Application::GetUserInterface(); // Which function is it to be? string func = ui.GetString ("FUNCTION"); if (func == "COS") Function = COS; if (func == "SIN") Function = SIN; if (func == "TAN") Function = TAN; if (func == "ACOS") Function = ACOS; if (func == "ASIN") Function = ASIN; if (func == "ATAN") Function = ATAN; if (func == "INV") Function = INV; if (func == "SQRT") Function = SQRT; if (func == "POW10") Function = POW10; if (func == "EXP") Function = EXP; if (func == "XTOY") Function = XTOY; if (func == "LOG10") Function = LOG10; if (func == "LN") Function = LN; if (func == "ABS") Function = ABS; if (Function == XTOY) { if (ui.WasEntered ("Y")) { y = ui.GetDouble("Y"); } else { string message = "For the XTOY function, you must enter a value for y"; throw iException::Message(iException::User,message,_FILEINFO_); } } // Start the processing p.StartProcess(cubefunc); if (bad != 0) { PvlGroup results ("Results"); string message = "Invalid input pixels converted to Isis NULL values"; results += PvlKeyword ("Error", message); results += PvlKeyword ("Count",bad); Application::Log (results); } p.EndProcess(); }
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"); iString id; id = (string)lab["DATA_SET_ID"]; id.ConvertWhiteSpace(); id.Compress(); id.Trim(" "); if (id.find("CLEM") == string::npos) { string msg = "Invalid DATA_SET_ID [" + id + "]"; throw iException::Message(iException::Pvl,msg,_FILEINFO_); } } catch (iException &e) { string msg = "Input file [" + in.Expanded() + "] does not appear to be " + "in Clementine EDR format"; throw iException::Message(iException::Io,msg, _FILEINFO_); } //Checks if in file is rdr if( projected ) { string msg = "[" + in.Name() + "] appears to be an rdr file."; msg += " Use pds2isis."; throw iException::Message(iException::User,msg, _FILEINFO_); } //Decompress the file long int lines = 0; long int samps = 0; iString filename = in.Expanded(); pdsi = PDSR((char *)filename.c_str(),&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 (); }
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(); }
void IsisMain() { // Setup the input and output cubes along with histograms ProcessByLine p; Cube *mcube = p.SetInputCube("MATCH", Isis::OneBand); Histogram *match = mcube->histogram(); p.ClearInputCubes(); Cube *icube = p.SetInputCube("FROM", Isis::OneBand); Histogram *from = icube->histogram(); p.SetOutputCube("TO"); // Histogram specifications UserInterface &ui = Application::GetUserInterface(); double minimum = ui.GetDouble("MINPER"); double maximum = ui.GetDouble("MAXPER"); stretch.ClearPairs(); // CDF mode selected if(ui.GetString("STRETCH") == "CDF") { int increment = ui.GetInteger("INCREMENT"); double lastPer = from->Percent(minimum); stretch.AddPair(lastPer, match->Percent(minimum)); for(double i = increment + minimum; i < maximum; i += increment) { double curPer = from->Percent(i); if(lastPer < curPer && abs(lastPer - curPer) > DBL_EPSILON) { stretch.AddPair(curPer, match->Percent(i)); lastPer = curPer; } } double curPer = from->Percent(maximum); if(lastPer < curPer && abs(lastPer - curPer) > DBL_EPSILON) { stretch.AddPair(curPer, match->Percent(maximum)); } } // Modal mode is selected else { stretch.AddPair(from->Percent(minimum), match->Percent(minimum)); stretch.AddPair(from->Mode(), match->Mode()); stretch.AddPair(from->Percent(maximum), match->Percent(maximum)); } // Start the processing p.StartProcess(remap); p.EndProcess(); }
void IsisMain() { ProcessByLine p; Cube *icube = p.SetInputCube("FROM"); p.SetOutputCube("TO"); double gsigma = Isis::Application::GetUserInterface().GetDouble("GSIGMA"); for(int i = 0; i < icube->bandCount(); i++) { Histogram hist = *(icube->histogram(i + 1)); double mean = (hist.Maximum() + hist.Minimum()) / 2.0; double stdev = (hist.Maximum() - hist.Minimum()) / (2.0 * gsigma); stretch.push_back(new GaussianStretch(hist, mean, stdev)); } p.StartProcess(gauss); for(int i = 0; i < icube->bandCount(); i++) delete stretch[i]; stretch.clear(); p.EndProcess(); }
void IsisMain() { // We will be processing by line ProcessByLine p; // Setup the input and output cubes Cube *icube = p.SetInputCube("FROM"); p.SetOutputCube ("TO"); // Override the defaults if the user entered a value UserInterface &ui = Application::GetUserInterface(); top = ui.GetInteger ("TOP"); bottom = ui.GetInteger ("BOTTOM"); lleft = ui.GetInteger ("LEFT"); rright = ui.GetInteger ("RIGHT"); // Will anything be trimmed from the cube? bool notrim = false; if (top == 0 && bottom == 0 && lleft == 0 && rright == 0) { notrim = true; } // Adjust bottom and right bottom = icube->Lines() - bottom; rright = icube->Samples() - rright; // Start the processing p.StartProcess(trim); p.EndProcess(); //The user didn't trim anything if (notrim == true) { string message = "No trimming was done-output equals input file"; throw iException::Message(iException::User,message,_FILEINFO_); } }
void IsisMain() { // We will be processing by line ProcessByLine p; // Setup the input and output cubes Cube *icube = p.SetInputCube("FROM"); p.SetOutputCube ("TO"); // Get exposure duration and tranfer time // Override the lable values if the user entered a value double expTime,xferTime; UserInterface &ui = Application::GetUserInterface(); if (ui.WasEntered ("DURATION")) { expTime = ui.GetDouble ("DURATION"); } else { PvlGroup grp = icube->GetGroup("ISIS_INSTRUMENT"); expTime = grp["EXPOSURE_DURATION"]; } if (ui.WasEntered ("TRANSFER")) { xferTime = ui.GetDouble ("TRANSFER"); } else { PvlGroup grp = icube->GetGroup("ISIS_INSTRUMENT"); xferTime = grp["TRANSFER_TIME"]; } // Calculate the smear scale smearScale = xferTime / expTime / icube->Lines(); // Start the processing p.StartProcess(desmear); p.EndProcess(); }
void IsisMain() { // Get the list of cubes to mosaic FileList imageList; UserInterface &ui = Application::GetUserInterface(); imageList.Read(ui.GetFilename("FROMLIST")); if (imageList.size() < 1) { std::string msg = "The list file [" + ui.GetFilename("FROMLIST") + "] does not contain any data"; throw iException::Message(iException::User,msg,_FILEINFO_); } // Make sure the user enters a "OUTSTATS" file if the CALCULATE option // is selected std::string processOpt = ui.GetString("PROCESS"); if (processOpt == "CALCULATE") { if (!ui.WasEntered("OUTSTATS")) { std::string msg = "If the CALCULATE option is selected, you must enter"; msg += " an OUTSTATS file"; throw iException::Message(iException::User,msg,_FILEINFO_); } } // Make sure number of bands and projection parameters match for all cubes for (unsigned int i=0; i<imageList.size(); i++) { Cube cube1; cube1.Open(imageList[i]); g_maxBand = cube1.Bands(); for (unsigned int j=(i+1); j<imageList.size(); j++) { Cube cube2; cube2.Open(imageList[j]); // Make sure number of bands match if (g_maxBand != cube2.Bands()) { string msg = "Number of bands do not match between cubes [" + imageList[i] + "] and [" + imageList[j] + "]"; throw iException::Message(iException::User,msg,_FILEINFO_); } //Create projection from each cube Projection *proj1 = cube1.Projection(); Projection *proj2 = cube2.Projection(); // Test to make sure projection parameters match if (*proj1 != *proj2) { string msg = "Mapping groups do not match between cubes [" + imageList[i] + "] and [" + imageList[j] + "]"; throw iException::Message(iException::User,msg,_FILEINFO_); } } } // Read hold list if one was entered std::vector<int> hold; if (ui.WasEntered("HOLD")) { FileList holdList; holdList.Read(ui.GetFilename("HOLD")); // Make sure each file in the holdlist matches a file in the fromlist for (int i=0; i<(int)holdList.size(); i++) { bool matched = false; for (int j=0; j<(int)imageList.size(); j++) { if (holdList[i] == imageList[j]) { matched = true; hold.push_back(j); break; } } if (!matched) { std::string msg = "The hold list file [" + holdList[i] + "] does not match a file in the from list"; throw iException::Message(iException::User,msg,_FILEINFO_); } } } // Read to list if one was entered FileList outList; if (ui.WasEntered("TOLIST")) { outList.Read(ui.GetFilename("TOLIST")); // Make sure each file in the tolist matches a file in the fromlist if (outList.size() != imageList.size()) { std::string msg = "Each input file in the FROM LIST must have a "; msg += "corresponding output file in the TO LIST."; throw iException::Message(iException::User,msg,_FILEINFO_); } // Make sure that all output files do not have the same names as their // corresponding input files for (unsigned i = 0; i < outList.size(); i++) { if (outList[i].compare(imageList[i]) == 0) { std::string msg = "The to list file [" + outList[i] + "] has the same name as its corresponding from list file."; throw iException::Message(iException::User,msg,_FILEINFO_); } } } // Test to ensure sampling percent in bound double sampPercent = ui.GetDouble("PERCENT"); if (sampPercent <= 0.0 || sampPercent > 100.0) { string msg = "The sampling percent must be a decimal (0.0, 100.0]"; throw iException::Message(iException::User,msg,_FILEINFO_); } int mincnt = ui.GetInteger("MINCOUNT"); bool wtopt = ui.GetBoolean("WEIGHT"); if (processOpt != "APPLY") { // Loop through all the input cubes, calculating statistics for each cube to use later iString maxCubeStr ((int)imageList.size()); for (int band=1; band<=g_maxBand; band++) { std::vector<Statistics> statsList; for (int img=0; img<(int)imageList.size(); img++) { Process p; const CubeAttributeInput att; const std::string inp = imageList[img]; Cube *icube = p.SetInputCube(inp, att); // Add a Statistics object to the list for every band of every input cube g_imageIndex = img; Statistics stats = GatherStatistics(*icube, band, sampPercent, maxCubeStr); statsList.push_back(stats); p.EndProcess(); } // Create a separate OverlapNormalization object for every band OverlapNormalization *oNorm = new OverlapNormalization (statsList); for (int h=0; h<(int)hold.size(); h++) oNorm->AddHold(hold[h]); g_oNormList.push_back(oNorm); } // A list for keeping track of which input cubes are known to overlap another std::vector<bool> doesOverlapList; for (unsigned int i=0; i<imageList.size(); i++) doesOverlapList.push_back(false); // Find overlapping areas and add them to the set of known overlaps for each // band shared amongst cubes for (unsigned int i=0; i<imageList.size(); i++){ Cube cube1; cube1.Open(imageList[i]); for (unsigned int j=(i+1); j<imageList.size(); j++) { Cube cube2; cube2.Open(imageList[j]); iString cubeStr1 ((int)(i+1)); iString cubeStr2 ((int)(j+1)); string statMsg = "Gathering Overlap Statisitcs for Cube " + cubeStr1 + " vs " + cubeStr2 + " of " + maxCubeStr; // Get overlap statistics for cubes OverlapStatistics oStats(cube1, cube2, statMsg, sampPercent); // Only push the stats onto the oList vector if there is an overlap in at // least one of the bands if (oStats.HasOverlap()) { oStats.SetMincount(mincnt); g_overlapList.push_back(oStats); for (int band=1; band<=g_maxBand; band++) { // Fill wt vector with 1's if the overlaps are not to be weighted, or // fill the vector with the number of valid pixels in each overlap int weight = 1; if (wtopt) weight = oStats.GetMStats(band).ValidPixels(); // Make sure overlap has at least MINCOUNT pixels and add if (oStats.GetMStats(band).ValidPixels() >= mincnt) { g_oNormList[band-1]->AddOverlap(oStats.GetMStats(band).X(), i, oStats.GetMStats(band).Y(), j, weight); doesOverlapList[i] = true; doesOverlapList[j] = true; } } } } } // Print an error if one or more of the images does not overlap another { std::string badFiles = ""; for (unsigned int img=0; img<imageList.size(); img++) { // Print the name of each input cube without an overlap if (!doesOverlapList[img]) { badFiles += "[" + imageList[img] + "] "; } } if (badFiles != "") { std::string msg = "File(s) " + badFiles; msg += " do(es) not overlap any other input images with enough valid pixels"; throw iException::Message(iException::User,msg,_FILEINFO_); } } // Determine whether to calculate gains or offsets std::string adjust = ui.GetString("ADJUST"); OverlapNormalization::SolutionType sType = OverlapNormalization::Both; if (adjust == "CONTRAST") sType = OverlapNormalization::Gains; if (adjust == "BRIGHTNESS") sType = OverlapNormalization::Offsets; // Loop through each band making all necessary calculations for (int band=0; band<g_maxBand; band++) { g_oNormList[band]->Solve(sType); } } // Print gathered statistics to the gui and the print file int validCnt = 0; int invalidCnt = 0; if (processOpt != "APPLY") { PvlGroup results("Results"); // Compute the number valid and invalid overlaps for (unsigned int o=0; o<g_overlapList.size(); o++) { for (int band=1; band<=g_maxBand; band++) { if (g_overlapList[o].IsValid(band)) validCnt++; else invalidCnt++; } } results += PvlKeyword("TotalOverlaps", validCnt+invalidCnt); results += PvlKeyword("ValidOverlaps", validCnt); results += PvlKeyword("InvalidOverlaps", invalidCnt); std::string weightStr = "false"; if (wtopt) weightStr = "true"; results += PvlKeyword("Weighted", weightStr); results += PvlKeyword("MinCount", mincnt); // Name and band modifiers for each image for (unsigned int img=0; img<imageList.size(); img++) { results += PvlKeyword("FileName", imageList[img]); // Band by band statistics for (int band=1; band<=g_maxBand; band++) { iString mult (g_oNormList[band-1]->Gain(img)); iString base (g_oNormList[band-1]->Offset(img)); iString avg (g_oNormList[band-1]->Average(img)); iString bandNum (band); std::string bandStr = "Band" + bandNum; PvlKeyword bandStats(bandStr); bandStats += mult; bandStats += base; bandStats += avg; results += bandStats; } } // Write the results to the log Application::Log(results); } // Setup the output text file if the user requested one if (ui.WasEntered("OUTSTATS")) { PvlObject equ("EqualizationInformation"); PvlGroup gen("General"); gen += PvlKeyword("TotalOverlaps", validCnt+invalidCnt); gen += PvlKeyword("ValidOverlaps", validCnt); gen += PvlKeyword("InvalidOverlaps", invalidCnt); std::string weightStr = "false"; if (wtopt) weightStr = "true"; gen += PvlKeyword("Weighted", weightStr); gen += PvlKeyword("MinCount", mincnt); equ.AddGroup(gen); for (unsigned int img=0; img<imageList.size(); img++) { // Format and name information PvlGroup norm("Normalization"); norm.AddComment("Formula: newDN = (oldDN - AVERAGE) * GAIN + AVERAGE + OFFSET"); norm.AddComment("BandN = (GAIN, OFFSET, AVERAGE)"); norm += PvlKeyword("FileName", imageList[img]); // Band by band statistics for (int band=1; band<=g_maxBand; band++) { iString mult (g_oNormList[band-1]->Gain(img)); iString base (g_oNormList[band-1]->Offset(img)); iString avg (g_oNormList[band-1]->Average(img)); iString bandNum (band); std::string bandStr = "Band" + bandNum; PvlKeyword bandStats(bandStr); bandStats += mult; bandStats += base; bandStats += avg; norm += bandStats; } equ.AddGroup(norm); } // Write the equalization and overlap statistics to the file std::string out = Filename(ui.GetFilename("OUTSTATS")).Expanded(); std::ofstream os; os.open(out.c_str(),std::ios::app); Pvl p; p.SetTerminator(""); p.AddObject(equ); os << p << std::endl; for (unsigned int i=0; i<g_overlapList.size(); i++) { os << g_overlapList[i]; if (i != g_overlapList.size()-1) os << std::endl; } os << "End"; } // Check for errors with the input statistics if (processOpt == "APPLY") { Pvl inStats (ui.GetFilename("INSTATS")); PvlObject &equalInfo = inStats.FindObject("EqualizationInformation"); // Make sure each file in the instats matches a file in the fromlist if (imageList.size() > (unsigned)equalInfo.Groups()-1) { std::string msg = "Each input file in the FROM LIST must have a "; msg += "corresponding input file in the INPUT STATISTICS."; throw iException::Message(iException::User,msg,_FILEINFO_); } // Check that each file in the FROM LIST is present in the INPUT STATISTICS for (unsigned i = 0; i < imageList.size(); i++) { std::string fromFile = imageList[i]; bool foundFile = false; for (int j = 1; j < equalInfo.Groups(); j++) { PvlGroup &normalization = equalInfo.Group(j); std::string normFile = normalization["Filename"][0]; if (fromFile == normFile) { // Store the index in INPUT STATISTICS file corresponding to the // current FROM LIST file normIndices.push_back(j); foundFile = true; } } if (!foundFile) { std::string msg = "The from list file [" + fromFile + "] does not have any corresponding file in the stats list."; throw iException::Message(iException::User,msg,_FILEINFO_); } } } // Apply the correction to the images if the user wants this done if (processOpt != "CALCULATE") { iString maxCubeStr ((int)imageList.size()); for (int img=0; img<(int)imageList.size(); img++) { // Set up for progress bar ProcessByLine p; iString curCubeStr (img+1); p.Progress()->SetText("Equalizing Cube " + curCubeStr + " of " + maxCubeStr); // Open input cube CubeAttributeInput att; const std::string inp = imageList[img]; Cube *icube = p.SetInputCube(inp, att); // Establish the output file depending upon whether or not a to list // was entered std::string out; if (ui.WasEntered("TOLIST")) { out = outList[img]; } else { Filename file = imageList[img]; out = file.Path() + "/" + file.Basename() + ".equ." + file.Extension(); } // Allocate output cube CubeAttributeOutput outAtt; p.SetOutputCube(out,outAtt,icube->Samples(),icube->Lines(),icube->Bands()); // Apply gain/offset to the image g_imageIndex = img; if (processOpt == "APPLY") { // Apply correction based on pre-determined statistics information Pvl inStats (ui.GetFilename("INSTATS")); PvlObject &equalInfo = inStats.FindObject("EqualizationInformation"); PvlGroup &normalization = equalInfo.Group(normIndices[g_imageIndex]); gains.clear(); offsets.clear(); avgs.clear(); // Get and store the modifiers for each band for (int band = 1; band < normalization.Keywords(); band++) { gains.push_back(normalization[band][0]); offsets.push_back(normalization[band][1]); avgs.push_back(normalization[band][2]); } p.StartProcess(ApplyViaFile); } else { // Apply correction based on the statistics gathered in this run p.StartProcess(ApplyViaObject); } p.EndProcess(); } } // Clean-up for batch list runs for (unsigned int o=0; o<g_oNormList.size(); o++) delete g_oNormList[o]; g_oNormList.clear(); g_overlapList.clear(); normIndices.clear(); gains.clear(); offsets.clear(); avgs.clear(); }
// Main Program void IsisMain() { UserInterface &ui = Application::GetUserInterface(); Isis::FileName fromFile = ui.GetFileName("FROM"); Isis::Cube inputCube; inputCube.open(fromFile.expanded()); //Check to make sure we got the cube properly if(!inputCube.isOpen()) { QString msg = "Could not open FROM cube" + fromFile.expanded(); throw IException(IException::User, msg, _FILEINFO_); } ProcessByLine processByLine; Cube *icube = processByLine.SetInputCube("FROM"); int totalSamples = icube->sampleCount(); //We'll be going through the cube by line, manually differentiating // between phases Isis::LineManager lineManager(inputCube); lineManager.begin(); Table hifix("HiRISE Ancillary"); int channel = icube->group("Instrument")["ChannelNumber"]; if(channel == 0) { phases = channel0Phases; } else { phases = channel1Phases; } int binning_mode = icube->group("Instrument")["Summing"]; if(binning_mode != 1 && binning_mode != 2) { /*IString msg = "You may only use input with binning mode 1 or 2, not"; msg += binning_mode; throw iException::Message(iException::User, msg, _FILEINFO_);*/ DestripeForOtherBinningModes(totalSamples); } else { //Adjust phase breaks based on the binning mode for(int i = 0 ; i < num_phases ; i++) { phases[i] /= binning_mode; } //Phases must be able to stretch across the entire cube if(totalSamples != phases[3]) { QString required_samples(phases[3]); QString bin_QString(binning_mode); QString msg = "image must have exactly "; msg += required_samples; msg += " samples per line for binning mode "; msg += bin_QString; throw IException(IException::User, msg, _FILEINFO_); } //Index starts at 1 and will go up to totalLines. This must be done since // lines go into different statistics vectors based on their index myIndex = 1; processByLine.StartProcess(getStats); //This program is trying to find horizontal striping in the image that occurs // in every other line, but at runtime we do not know whether that striping // occurs on the odd numbered lines (1, 3, 5, etc.) or the even numbered // ones (2, 4, 6, etc.). The below algorithm determines which of these is the // case. QString parity = ui.GetString("PARITY"); if(parity == "EVEN") { offset = 1; } else if(parity == "ODD") { offset = 0; } else { //PRECONDITION: getStats must have been run long double maxDiff = 0; int maxDiffIndex = 0; for(int i = 0 ; i < num_phases ; i++) { long double thisDiff; thisDiff = lineStats[i].Average() - stats.Average(); if(thisDiff < 0) { thisDiff *= -1; } if(thisDiff > maxDiff) { maxDiff = thisDiff; maxDiffIndex = i; } } if(maxDiffIndex == 1 || maxDiffIndex == 3) { offset = 1; } else { offset = 0; } } //Again we must reset the index, because we apply corrections only on every // other line and the fix processing function has no concept of where it is // in the cube. myIndex = 1; mode = (ui.GetString("CORRECTION") == "MULTIPLY"); processByLine.SetOutputCube("TO"); processByLine.StartProcess(fix); processByLine.EndProcess(); } }
void IsisMain() { PvlGroup mapping("Mapping"); { mapping += PvlKeyword("ProjectionName","SimpleCylindrical"); mapping += PvlKeyword("CenterLongitude","227.83197474005"); mapping += PvlKeyword("TargetName","Mars"); mapping += PvlKeyword("EquatorialRadius", "3396190.0"); mapping += PvlKeyword("PolarRadius","3376200.0"); mapping += PvlKeyword("LatitudeType","Planetocentric"); mapping += PvlKeyword("LongitudeDirection","PositiveEast"); mapping += PvlKeyword("LongitudeDomain","360"); mapping += PvlKeyword("MinimumLatitude","10.786871290848"); mapping += PvlKeyword("MaximumLatitude","34.44480953463"); mapping += PvlKeyword("MinimumLongitude", "219.70338590854"); mapping += PvlKeyword("MaximumLongitude","235.96056357156"); mapping += PvlKeyword("UpperLeftCornerX","-483000.0"); mapping += PvlKeyword("UpperLeftCornerY","2043000.0 "); mapping += PvlKeyword("PixelResolution","1000.0"); mapping += PvlKeyword("Scale","59.274697523306"); } Pvl pvl; pvl.AddGroup(mapping); PvlGroup vimsMapping("Mapping"); { vimsMapping += PvlKeyword("ProjectionName","Sinusoidal"); vimsMapping += PvlKeyword("CenterLongitude","308.47990638953"); vimsMapping += PvlKeyword("TargetName","TITAN"); vimsMapping += PvlKeyword("EquatorialRadius", "2575000.0"); vimsMapping += PvlKeyword("PolarRadius","575000.0"); vimsMapping += PvlKeyword("LatitudeType","Planetocentric"); vimsMapping += PvlKeyword("LongitudeDirection","PositiveEast"); vimsMapping += PvlKeyword("LongitudeDomain","360"); vimsMapping += PvlKeyword("MinimumLatitude","9.916425315167"); vimsMapping += PvlKeyword("MaximumLatitude","10.087679837429"); vimsMapping += PvlKeyword("MinimumLongitude", "308.42684479508"); vimsMapping += PvlKeyword("MaximumLongitude","308.53296798387"); vimsMapping += PvlKeyword("PixelResolution","498.46721637851"); vimsMapping += PvlKeyword("Scale","90.160850627992"); } cout << "Testing Isis::ProcessGroundPolygons Class ... " << endl; ProcessGroundPolygons p; ProcessByLine pbl; CubeAttributeInput atts0; QStringList vimsCube; vimsCube << "$Cassini/testData/CM_1540484927_1_001.ir.cub" << "$Cassini/testData/CM_1540484927_1_002.ir.cub" << "$Cassini/testData/CM_1540484927_1_003.ir.cub"; std::vector<double> vimsSamps, vimsLines, vect; Pvl vimsPvl; vimsPvl.AddGroup(vimsMapping); CubeAttributeOutput out_atts; out_atts.PixelType(Real); const string output1 = "ProcessGroundPolygonsTest.cub"; const string output2 = "ProcessGroundPolygonsTest_count.cub"; p.SetOutputCube(output1 , output2 , out_atts, vimsPvl, 2); for (int f = 0; f<vimsCube.size(); f++) { Pvl vimsCubePvl(vimsCube[f].toStdString()); UniversalGroundMap *groundMap = new UniversalGroundMap(vimsCubePvl); vimsValues.clear(); pbl.SetInputCube(vimsCube[f].toStdString(), atts0, 0); pbl.StartProcess(readValues); pbl.EndProcess(); double latitude, longitude; int i = 0; for (int b = 1; b<3; b++) { for (int l = 0; l<1; l++) { for (int s = 0; s<13; s++) { vimsSamps.push_back(s+0.5); vimsSamps.push_back(s+1.5); vimsSamps.push_back(s+1.5); vimsSamps.push_back(s+0.5); vimsLines.push_back(l+0.5); vimsLines.push_back(l+0.5); vimsLines.push_back(l+1.4375); vimsLines.push_back(l+1.4375); //Now need to convert all samps and lines to lat lon. for (unsigned int j = 0; j<vimsSamps.size(); j++) { if (groundMap->SetImage(vimsSamps[j], vimsLines[j])) { latitude = groundMap->UniversalLatitude(); longitude = groundMap->UniversalLongitude(); lat.push_back(latitude); lon.push_back(longitude); } } if (lat.size() > 3) { p.Rasterize(lat, lon, b, vimsValues[i]); } lat.clear(); lon.clear(); vimsSamps.clear(); vimsLines.clear(); i++; }//end for each s -- sample }// end for each l -- line }//end for each b -- band delete groundMap; } //end for each vims file. p.EndProcess(); /* Write out the data */ CubeAttributeInput atts; std::cout << "File Name: " << output1 << std::endl; pbl.SetInputCube(output1, atts, 0); pbl.StartProcess(writeAscii); pbl.EndProcess(); std::cout << "File Name: " << output2 << std::endl; pbl.SetInputCube(output2, atts, 0); pbl.StartProcess(writeAscii); pbl.EndProcess(); remove(output1.c_str()); remove(output2.c_str()); }
void IsisMain(){ const QString hical_program = "hicalbeta"; const QString hical_version = "5.0"; const QString hical_revision = "$Revision: 1.15 $"; const QString hical_runtime = Application::DateTime(); UserInterface &ui = Application::GetUserInterface(); QString procStep("prepping phase"); try { // The output from the last processing is the input into subsequent processing ProcessByLine p; Cube *hifrom = p.SetInputCube("FROM"); int nsamps = hifrom->sampleCount(); int nlines = hifrom->lineCount(); // Initialize the configuration file QString conf(ui.GetAsString("CONF")); HiCalConf hiconf(*(hifrom->label()), conf); DbProfile hiprof = hiconf.getMatrixProfile(); // Check for label propagation and set the output cube Cube *ocube = p.SetOutputCube("TO"); if ( !IsTrueValue(hiprof,"PropagateTables", "TRUE") ) { RemoveHiBlobs(*(ocube->label())); } // Set specified profile if entered by user if (ui.WasEntered("PROFILE")) { hiconf.selectProfile(ui.GetAsString("PROFILE")); } // Add OPATH parameter to profiles if (ui.WasEntered("OPATH")) { hiconf.add("OPATH",ui.GetAsString("OPATH")); } else { // Set default to output directory hiconf.add("OPATH", FileName(ocube->fileName()).path()); } // Do I/F output DN conversions QString units = ui.GetString("UNITS"); // Allocate the calibration list calVars = new MatrixList; // Set up access to HiRISE ancillary data (tables, blobs) here. Note it they // are gone, this will error out. See PropagateTables in conf file. HiCalData caldata(*hifrom); //////////////////////////////////////////////////////////////////////////// // Drift Correction (Zf) using buffer pixels // Extracts specified regions of the calibration buffer pixels and runs // series of lowpass filters. Apply spline fit if any missing data // remains. Config file contains parameters for this operation. procStep = "ZeroBufferSmooth module"; hiconf.selectProfile("ZeroBufferSmooth"); hiprof = hiconf.getMatrixProfile(); HiHistory ZbsHist; ZbsHist.add("Profile["+ hiprof.Name()+"]"); if ( !SkipModule(hiprof) ) { ZeroBufferSmooth zbs(caldata, hiconf); calVars->add("ZeroBufferSmooth", zbs.ref()); ZbsHist = zbs.History(); if ( hiprof.exists("DumpModuleFile") ) { zbs.Dump(hiconf.getMatrixSource("DumpModuleFile",hiprof)); } } else { // NOT RECOMMENDED! This is required for the next step! // SURELY must be skipped with ZeroBufferSmooth step as well! calVars->add("ZeroBufferSmooth", HiVector(nlines, 0.0)); ZbsHist.add("Debug::SkipModule invoked!"); } ///////////////////////////////////////////////////////////////////// // ZeroBufferFit // Compute second level of drift correction. The high level noise // is removed from a modeled non-linear fit. // procStep = "ZeroBufferFit module"; HiHistory ZbfHist; hiconf.selectProfile("ZeroBufferFit"); hiprof = hiconf.getMatrixProfile(); ZbfHist.add("Profile["+ hiprof.Name()+"]"); if (!SkipModule(hiprof) ) { ZeroBufferFit zbf(hiconf); calVars->add(hiconf.getProfileName(), zbf.Normalize(zbf.Solve(calVars->get("ZeroBufferSmooth")))); ZbfHist = zbf.History(); if ( hiprof.exists("DumpModuleFile") ) { zbf.Dump(hiconf.getMatrixSource("DumpModuleFile",hiprof)); } } else { calVars->add(hiconf.getProfileName(), HiVector(nlines, 0.0)); ZbfHist.add("Debug::SkipModule invoked!"); } //////////////////////////////////////////////////////////////////// // ZeroReverse procStep = "ZeroReverse module"; hiconf.selectProfile("ZeroReverse"); hiprof = hiconf.getMatrixProfile(); HiHistory ZrHist; ZrHist.add("Profile["+ hiprof.Name()+"]"); if ( !SkipModule(hiprof) ) { ZeroReverse zr(caldata, hiconf); calVars->add(hiconf.getProfileName(), zr.ref()); ZrHist = zr.History(); if ( hiprof.exists("DumpModuleFile") ) { zr.Dump(hiconf.getMatrixSource("DumpModuleFile",hiprof)); } } else { calVars->add(hiconf.getProfileName(), HiVector(nsamps, 0.0)); ZrHist.add("Debug::SkipModule invoked!"); } ///////////////////////////////////////////////////////////////// // ZeroDark removes dark current // procStep = "ZeroDark module"; hiconf.selectProfile("ZeroDark"); hiprof = hiconf.getMatrixProfile(); HiHistory ZdHist; ZdHist.add("Profile["+ hiprof.Name()+"]"); if ( !SkipModule(hiprof) ) { ZeroDark zd(hiconf); calVars->add(hiconf.getProfileName(), zd.ref()); ZdHist = zd.History(); if ( hiprof.exists("DumpModuleFile") ) { zd.Dump(hiconf.getMatrixSource("DumpModuleFile",hiprof)); } } else { calVars->add(hiconf.getProfileName(), HiVector(nsamps, 0.0)); ZdHist.add("Debug::SkipModule invoked!"); } //////////////////////////////////////////////////////////////////// // GainLineDrift correct for gain-based drift // procStep = "GainLineDrift module"; hiconf.selectProfile("GainLineDrift"); hiprof = hiconf.getMatrixProfile(); HiHistory GldHist; GldHist.add("Profile["+ hiprof.Name()+"]"); if ( !SkipModule(hiprof) ) { GainLineDrift gld(hiconf); calVars->add(hiconf.getProfileName(), gld.ref()); GldHist = gld.History(); if ( hiprof.exists("DumpModuleFile") ) { gld.Dump(hiconf.getMatrixSource("DumpModuleFile",hiprof)); } } else { calVars->add(hiconf.getProfileName(), HiVector(nlines, 1.0)); GldHist.add("Debug::SkipModule invoked!"); } //////////////////////////////////////////////////////////////////// // GainNonLinearity Correct for non-linear gain procStep = "GainNonLinearity module"; hiconf.selectProfile("GainNonLinearity"); hiprof = hiconf.getMatrixProfile(); HiHistory GnlHist; GnlHist.add("Profile["+ hiprof.Name()+"]"); if ( !SkipModule(hiprof) ) { GainNonLinearity gnl(hiconf); calVars->add(hiconf.getProfileName(), gnl.ref()); GnlHist = gnl.History(); if ( hiprof.exists("DumpModuleFile") ) { gnl.Dump(hiconf.getMatrixSource("DumpModuleFile",hiprof)); } } else { calVars->add(hiconf.getProfileName(), HiVector(1, 0.0)); GnlHist.add("Debug::SkipModule invoked!"); } //////////////////////////////////////////////////////////////////// // GainChannelNormalize Correct for sample gain with the G matrix procStep = "GainChannelNormalize module"; hiconf.selectProfile("GainChannelNormalize"); hiprof = hiconf.getMatrixProfile(); HiHistory GcnHist; GcnHist.add("Profile["+ hiprof.Name()+"]"); if ( !SkipModule(hiprof) ) { GainChannelNormalize gcn(hiconf); calVars->add(hiconf.getProfileName(), gcn.ref()); GcnHist = gcn.History(); if ( hiprof.exists("DumpModuleFile") ) { gcn.Dump(hiconf.getMatrixSource("DumpModuleFile",hiprof)); } } else { calVars->add(hiconf.getProfileName(), HiVector(nsamps, 1.0)); GcnHist.add("Debug::SkipModule invoked!"); } //////////////////////////////////////////////////////////////////// // GainFlatField Flat field correction with A matrix procStep = "GainFlatField module"; hiconf.selectProfile("GainFlatField"); hiprof = hiconf.getMatrixProfile(); HiHistory GffHist; GffHist.add("Profile["+ hiprof.Name()+"]"); if ( !SkipModule(hiprof) ) { GainFlatField gff(hiconf); calVars->add(hiconf.getProfileName(), gff.ref()); GffHist = gff.History(); if ( hiprof.exists("DumpModuleFile") ) { gff.Dump(hiconf.getMatrixSource("DumpModuleFile",hiprof)); } } else { calVars->add(hiconf.getProfileName(), HiVector(nsamps, 1.0)); GffHist.add("Debug::SkipModule invoked!"); } //////////////////////////////////////////////////////////////////// // GainTemperature - Temperature-dependant gain correction procStep = "GainTemperature module"; hiconf.selectProfile("GainTemperature"); hiprof = hiconf.getMatrixProfile(); HiHistory GtHist; GtHist.add("Profile["+ hiprof.Name()+"]"); if ( !SkipModule(hiprof) ) { GainTemperature gt(hiconf); calVars->add(hiconf.getProfileName(), gt.ref()); GtHist = gt.History(); if ( hiprof.exists("DumpModuleFile") ) { gt.Dump(hiconf.getMatrixSource("DumpModuleFile",hiprof)); } } else { calVars->add(hiconf.getProfileName(), HiVector(nsamps, 1.0)); GtHist.add("Debug::SkipModule invoked!"); } //////////////////////////////////////////////////////////////////// // GainUnitConversion converts to requested units // procStep = "GainUnitConversion module"; hiconf.selectProfile("GainUnitConversion"); hiprof = hiconf.getMatrixProfile(); HiHistory GucHist; GucHist.add("Profile["+ hiprof.Name()+"]"); if ( !SkipModule(hiprof) ) { GainUnitConversion guc(hiconf, units); calVars->add(hiconf.getProfileName(), guc.ref()); GucHist = guc.History(); if ( hiprof.exists("DumpModuleFile") ) { guc.Dump(hiconf.getMatrixSource("DumpModuleFile",hiprof)); } } else { calVars->add(hiconf.getProfileName(), HiVector(1,1.0)); GucHist.add("Debug::SkipModule invoked!"); GucHist.add("Units[Unknown]"); } // Reset the profile selection to default hiconf.selectProfile(); //---------------------------------------------------------------------- // ///////////////////////////////////////////////////////////////////////// // Call the processing function procStep = "calibration phase"; p.StartProcess(calibrate); // Get the default profile for logging purposes hiprof = hiconf.getMatrixProfile(); const QString conf_file = hiconf.filepath(conf); // Quitely dumps parameter history to alternative format file. This // is completely controlled by the configuration file if ( hiprof.exists("DumpHistoryFile") ) { procStep = "logging/reporting phase"; FileName hdump(hiconf.getMatrixSource("DumpHistoryFile",hiprof)); QString hdumpFile = hdump.expanded(); ofstream ofile(hdumpFile.toAscii().data(), ios::out); if (!ofile) { QString mess = "Unable to open/create history dump file " + hdump.expanded(); IException(IException::User, mess, _FILEINFO_).print(); } else { ofile << "Program: " << hical_program << endl; ofile << "RunTime: " << hical_runtime << endl; ofile << "Version: " << hical_version << endl; ofile << "Revision: " << hical_revision << endl << endl; ofile << "FROM: " << hifrom->fileName() << endl; ofile << "TO: " << ocube->fileName() << endl; ofile << "CONF: " << conf_file << endl << endl; ofile << "/* " << hical_program << " application equation */\n" << "/* hdn = (idn - ZeroBufferFit(ZeroBufferSmooth) - ZeroReverse - ZeroDark) */\n" << "/* odn = hdn / GainLineDrift * GainNonLinearity * GainChannelNormalize */\n" << "/* * GainFlatField * GainTemperature / GainUnitConversion */\n\n"; ofile << "****** PARAMETER GENERATION HISTORY *******" << endl; ofile << "\nZeroBufferSmooth = " << ZbsHist << endl; ofile << "\nZeroBufferFit = " << ZbfHist << endl; ofile << "\nZeroReverse = " << ZrHist << endl; ofile << "\nZeroDark = " << ZdHist << endl; ofile << "\nGainLineDrift = " << GldHist << endl; ofile << "\nGainNonLinearity = " << GnlHist << endl; ofile << "\nGainChannelNormalize = " << GcnHist << endl; ofile << "\nGainFlatField = " << GffHist << endl; ofile << "\nGainTemperature = " << GtHist << endl; ofile << "\nGainUnitConversion = " << GucHist << endl; ofile.close(); } } // Ensure the RadiometricCalibration group is out there const QString rcalGroup("RadiometricCalibration"); if (!ocube->hasGroup(rcalGroup)) { PvlGroup temp(rcalGroup); ocube->putGroup(temp); } PvlGroup &rcal = ocube->group(rcalGroup); rcal += PvlKeyword("Program", hical_program); rcal += PvlKeyword("RunTime", hical_runtime); rcal += PvlKeyword("Version",hical_version); rcal += PvlKeyword("Revision",hical_revision); PvlKeyword key("Conf", conf_file); key.addCommentWrapped("/* " + hical_program + " application equation */"); key.addComment("/* hdn = idn - ZeroBufferFit(ZeroBufferSmooth) */"); key.addComment("/* - ZeroReverse - ZeroDark */"); key.addComment("/* odn = hdn / GainLineDrift * GainNonLinearity */"); key.addComment("/* * GainChannelNormalize * GainFlatField */"); key.addComment("/* * GainTemperature / GainUnitConversion */"); rcal += key; // Record parameter generation history. Controllable in configuration // file. Note this is optional because of a BUG!! in the ISIS label // writer as this application was initially developed if ( IsEqual(ConfKey(hiprof,"LogParameterHistory",QString("TRUE")),"TRUE")) { rcal += ZbsHist.makekey("ZeroBufferSmooth"); rcal += ZbfHist.makekey("ZeroBufferFit"); rcal += ZrHist.makekey("ZeroReverse"); rcal += ZdHist.makekey("ZeroDark"); rcal += GldHist.makekey("GainLineDrift"); rcal += GnlHist.makekey("GainNonLinearity"); rcal += GcnHist.makekey("GainChannelNormalize"); rcal += GffHist.makekey("GainFlatField"); rcal += GtHist.makekey("GainTemperature"); rcal += GucHist.makekey("GainUnitConversion"); } p.EndProcess(); } catch (IException &ie) { delete calVars; calVars = 0; QString mess = "Failed in " + procStep; throw IException(ie, IException::User, mess, _FILEINFO_); } // Clean up parameters delete calVars; calVars = 0; }
void IsisMain(){ const std::string hical_program = "hicalbeta"; const std::string hical_version = "3.5"; const std::string hical_revision = "$Revision: 1.14 $"; const std::string hical_runtime = Application::DateTime(); UserInterface &ui = Application::GetUserInterface(); string procStep("prepping phase"); try { // The output from the last processing is the input into subsequent processing ProcessByLine p; Cube *hifrom = p.SetInputCube("FROM"); int nsamps = hifrom->Samples(); int nlines = hifrom->Lines(); // Initialize the configuration file string conf(ui.GetAsString("CONF")); HiCalConf hiconf(*(hifrom->Label()), conf); DbProfile hiprof = hiconf.getMatrixProfile(); // Check for label propagation and set the output cube Cube *ocube = p.SetOutputCube("TO"); if ( !IsTrueValue(hiprof,"PropagateTables", "TRUE") ) { RemoveHiBlobs(*(ocube->Label())); } // Set specified profile if entered by user if (ui.WasEntered("PROFILE")) { hiconf.selectProfile(ui.GetAsString("PROFILE")); } // Add OPATH parameter to profiles if (ui.WasEntered("OPATH")) { hiconf.add("OPATH",ui.GetAsString("OPATH")); } else { // Set default to output directory hiconf.add("OPATH", Filename(ocube->Filename()).Path()); } // Do I/F output DN conversions string units = ui.GetString("UNITS"); // Allocate the calibration list calVars = new MatrixList; // Set up access to HiRISE ancillary data (tables, blobs) here. Note it they // are gone, this will error out. See PropagateTables in conf file. HiCalData caldata(*hifrom); //////////////////////////////////////////////////////////////////////////// // FixGaps (Z_f) Get buffer pixels and compute coefficients for equation // y = a[0] + a[1]*x + a[2] * exp(a[3] * x) // where y is the average of the buffer pixel region, // and x is the time at each line in electrons/sec/pixel procStep = "Zf module"; hiconf.selectProfile("Zf"); hiprof = hiconf.getMatrixProfile(); HiHistory ZfHist; ZfHist.add("Profile["+ hiprof.Name()+"]"); if ( !SkipModule(hiprof) ) { DriftBuffer driftB(caldata, hiconf); calVars->add("Zf", driftB.ref()); ZfHist = driftB.History(); if ( hiprof.exists("DumpModuleFile") ) { driftB.Dump(hiconf.getMatrixSource("DumpModuleFile",hiprof)); } } else { // NOT RECOMMENDED! This is required for the next step! // SURELY must be skipped with Z_d step as well! calVars->add("Zf", HiVector(nlines, 0.0)); ZfHist.add("Debug::SkipModule invoked!"); } ///////////////////////////////////////////////////////////////////// // DriftCorrect (Z_d) // Now compute the equation of fit // procStep = "Zd module"; HiHistory ZdHist; hiconf.selectProfile("Zd"); hiprof = hiconf.getMatrixProfile(); ZdHist.add("Profile["+ hiprof.Name()+"]"); if (!SkipModule(hiconf.getMatrixProfile("Zd")) ) { DriftCorrect driftC(hiconf); calVars->add("Zd", driftC.Normalize(driftC.Solve(calVars->get("Zf")))); ZdHist = driftC.History(); if ( hiprof.exists("DumpModuleFile") ) { driftC.Dump(hiconf.getMatrixSource("DumpModuleFile",hiprof)); } } else { calVars->add("Zd", HiVector(nlines, 0.0)); ZdHist.add("Debug::SkipModule invoked!"); } //////////////////////////////////////////////////////////////////// // ZeroCorrect (Z_z) Get reverse clock procStep = "Zz module"; hiconf.selectProfile("Zz"); hiprof = hiconf.getMatrixProfile(); HiHistory ZzHist; ZzHist.add("Profile["+ hiprof.Name()+"]"); if ( !SkipModule(hiprof) ) { OffsetCorrect zoff(caldata, hiconf); calVars->add("Zz", zoff.ref()); ZzHist = zoff.History(); if ( hiprof.exists("DumpModuleFile") ) { zoff.Dump(hiconf.getMatrixSource("DumpModuleFile",hiprof)); } } else { calVars->add("Zz", HiVector(nsamps, 0.0)); ZzHist.add("Debug::SkipModule invoked!"); } ///////////////////////////////////////////////////////////////// // DarkSubtract (Z_b) Remove dark current // procStep = "Zb module"; hiconf.selectProfile("Zb"); hiprof = hiconf.getMatrixProfile(); HiHistory ZbHist; ZbHist.add("Profile["+ hiprof.Name()+"]"); if ( !SkipModule(hiprof) ) { DarkSubtractComp dark(hiconf); calVars->add("Zb", dark.ref()); ZbHist = dark.History(); if ( hiprof.exists("DumpModuleFile") ) { dark.Dump(hiconf.getMatrixSource("DumpModuleFile",hiprof)); } } else { calVars->add("Zb", HiVector(nsamps, 0.0)); ZbHist.add("Debug::SkipModule invoked!"); } //////////////////////////////////////////////////////////////////// // GainVLineCorrect (Z_g) Correct for gain-based drift // procStep = "Zg module"; hiconf.selectProfile("Zg"); hiprof = hiconf.getMatrixProfile(); HiHistory ZgHist; ZgHist.add("Profile["+ hiprof.Name()+"]"); if ( !SkipModule(hiprof) ) { GainVLineComp gainV(hiconf); calVars->add("Zg", gainV.ref()); ZgHist = gainV.History(); if ( hiprof.exists("DumpModuleFile") ) { gainV.Dump(hiconf.getMatrixSource("DumpModuleFile",hiprof)); } } else { calVars->add("Zg", HiVector(nlines, 1.0)); ZgHist.add("Debug::SkipModule invoked!"); } //////////////////////////////////////////////////////////////////// // GainCorrect (Z_gg) Correct for gain with the G matrix procStep = "Zgg module"; hiconf.selectProfile("Zgg"); hiprof = hiconf.getMatrixProfile(); HiHistory ZggHist; ZggHist.add("Profile["+ hiprof.Name()+"]"); if ( !SkipModule(hiprof) ) { double bin = ToDouble(hiprof("Summing")); double tdi = ToDouble(hiprof("Tdi")); double factor = 128.0 / tdi / (bin*bin); HiVector zgg = hiconf.getMatrix("G", hiprof); for ( int i = 0 ; i < zgg.dim() ; i++ ) { zgg[i] *= factor; } calVars->add("Zgg", zgg);; ZggHist.add("LoadMatrix(G[" + hiconf.getMatrixSource("G",hiprof) + "],Band[" + ToString(hiconf.getMatrixBand(hiprof)) + "],Factor[" + ToString(factor) + "])"); if ( hiprof.exists("DumpModuleFile") ) { Component zg("GMatrix", ZggHist); zg.Process(zgg); zg.Dump(hiconf.getMatrixSource("DumpModuleFile",hiprof)); } } else { calVars->add("Zgg", HiVector(nsamps, 1.0)); ZggHist.add("Debug::SkipModule invoked!"); } //////////////////////////////////////////////////////////////////// // FlatField (Z_a) Flat field correction with A matrix procStep = "Za module"; hiconf.selectProfile("Za"); hiprof = hiconf.getMatrixProfile(); HiHistory ZaHist; ZaHist.add("Profile["+ hiprof.Name()+"]"); if ( !SkipModule(hiprof) ) { FlatFieldComp flat(hiconf); calVars->add("Za", flat.ref()); ZaHist = flat.History(); if ( hiprof.exists("DumpModuleFile") ) { flat.Dump(hiconf.getMatrixSource("DumpModuleFile",hiprof)); } } else { calVars->add("Za", HiVector(nsamps, 1.0)); ZaHist.add("Debug::SkipModule invoked!"); } //////////////////////////////////////////////////////////////////// // FlatField (Z_t) Temperature-dependant gain correction procStep = "Zt module"; hiconf.selectProfile("Zt"); hiprof = hiconf.getMatrixProfile(); HiHistory ZtHist; ZtHist.add("Profile["+ hiprof.Name()+"]"); if ( !SkipModule(hiprof) ) { TempGainCorrect tcorr(hiconf); calVars->add("Zt", tcorr.ref()); ZtHist = tcorr.History(); if ( hiprof.exists("DumpModuleFile") ) { tcorr.Dump(hiconf.getMatrixSource("DumpModuleFile",hiprof)); } } else { calVars->add("Zt", HiVector(nsamps, 1.0)); ZtHist.add("Debug::SkipModule invoked!"); } //////////////////////////////////////////////////////////////////// // I/FCorrect (Z_iof) Conversion to I/F // procStep = "Ziof module"; hiconf.selectProfile("Ziof"); hiprof = hiconf.getMatrixProfile(); HiHistory ZiofHist; ZiofHist.add("Profile["+ hiprof.Name()+"]"); if ( !SkipModule(hiprof) ) { double sed = ToDouble(hiprof("ScanExposureDuration")); // units = us if ( IsEqual(units, "IOF") ) { // Add solar I/F correction parameters double au = hiconf.sunDistanceAU(); ZiofHist.add("SunDist[" + ToString(au) + " (AU)]"); double suncorr = 1.5 / au; suncorr *= suncorr; double zbin = ToDouble(hiprof("ZiofBinFactor")); ZiofHist.add("ZiofBinFactor[" + ToString(zbin) + "]"); double zgain = ToDouble(hiprof("FilterGainCorrection")); ZiofHist.add("FilterGainCorrection[" + ToString(zgain) + "]"); ZiofHist.add("ScanExposureDuration[" + ToString(sed) + "]"); double ziof = (zbin * zgain) * (sed * 1.0e-6) * suncorr; calVars->add("Ziof", HiVector(1, ziof)); ZiofHist.add("I/F_Factor[" + ToString(ziof) + "]"); ZiofHist.add("Units[I/F Reflectance]"); } else if ( IsEqual(units, "DN/US") ) { // Ziof is a divisor in calibration equation double ziof = sed; calVars->add("Ziof", HiVector(1, ziof)); ZiofHist.add("ScanExposureDuration[" + ToString(sed) + "]"); ZiofHist.add("DN/US_Factor[" + ToString(ziof) + "]"); ZiofHist.add("Units[DNs/microsecond]"); } else { // Units are already in DN double ziof = 1.0; calVars->add("Ziof", HiVector(1, ziof)); ZiofHist.add("DN_Factor[" + ToString(ziof) + "]"); ZiofHist.add("Units[DN]"); } } else { calVars->add("Ziof", HiVector(1,1.0)); ZiofHist.add("Debug::SkipModule invoked!"); ZiofHist.add("Units[Unknown]"); } // Reset the profile selection to default hiconf.selectProfile(); //---------------------------------------------------------------------- // ///////////////////////////////////////////////////////////////////////// // Call the processing function procStep = "calibration phase"; p.StartProcess(calibrate); // Get the default profile for logging purposes hiprof = hiconf.getMatrixProfile(); const std::string conf_file = hiconf.filepath(conf); // Quitely dumps parameter history to alternative format file. This // is completely controlled by the configuration file if ( hiprof.exists("DumpHistoryFile") ) { procStep = "logging/reporting phase"; Filename hdump(hiconf.getMatrixSource("DumpHistoryFile",hiprof)); string hdumpFile = hdump.Expanded(); ofstream ofile(hdumpFile.c_str(), ios::out); if (!ofile) { string mess = "Unable to open/create history dump file " + hdump.Expanded(); iException::Message(iException::User, mess, _FILEINFO_).Report(); } else { ofile << "Program: " << hical_program << endl; ofile << "RunTime: " << hical_runtime << endl; ofile << "Version: " << hical_version << endl; ofile << "Revision: " << hical_revision << endl << endl; ofile << "FROM: " << hifrom->Filename() << endl; ofile << "TO: " << ocube->Filename() << endl; ofile << "CONF: " << conf_file << endl << endl; ofile << "/* " << hical_program << " application equation */" << endl << "/* hdn = (idn - Zd(Zf) - Zz - Zb) */" << endl << "/* odn = hdn / Zg * Zgg * Za * Zt / Ziof */" << endl << endl; ofile << "****** PARAMETER GENERATION HISTORY *******" << endl; ofile << "\nZf = " << ZfHist << endl; ofile << "\nZd = " << ZdHist << endl; ofile << "\nZz = " << ZzHist << endl; ofile << "\nZb = " << ZbHist << endl; ofile << "\nZg = " << ZgHist << endl; ofile << "\nZgg = " << ZggHist << endl; ofile << "\nZa = " << ZaHist << endl; ofile << "\nZt = " << ZtHist << endl; ofile << "\nZiof = " << ZiofHist << endl; ofile.close(); } } // Ensure the RadiometricCalibration group is out there const std::string rcalGroup("RadiometricCalibration"); if (!ocube->HasGroup(rcalGroup)) { PvlGroup temp(rcalGroup); ocube->PutGroup(temp); } PvlGroup &rcal = ocube->GetGroup(rcalGroup); rcal += PvlKeyword("Program", hical_program); rcal += PvlKeyword("RunTime", hical_runtime); rcal += PvlKeyword("Version",hical_version); rcal += PvlKeyword("Revision",hical_revision); PvlKeyword key("Conf", conf_file); key.AddCommentWrapped("/* " + hical_program + " application equation */"); key.AddComment("/* hdn = (idn - Zd(Zf) - Zz - Zb) */"); key.AddComment("/* odn = hdn / Zg * Zgg * Za * Zt / Ziof */"); rcal += key; // Record parameter generation history. Controllable in configuration // file. Note this is optional because of a BUG!! in the ISIS label // writer as this application was initially developed if ( IsEqual(ConfKey(hiprof,"LogParameterHistory",string("TRUE")),"TRUE")) { rcal += ZfHist.makekey("Zf"); rcal += ZdHist.makekey("Zd"); rcal += ZzHist.makekey("Zz"); rcal += ZbHist.makekey("Zb"); rcal += ZgHist.makekey("Zg"); rcal += ZggHist.makekey("Zgg"); rcal += ZaHist.makekey("Za"); rcal += ZiofHist.makekey("Ziof"); } p.EndProcess(); } catch (iException &ie) { delete calVars; calVars = 0; string mess = "Failed in " + procStep; ie.Message(iException::User, mess.c_str(), _FILEINFO_); throw; } // Clean up parameters delete calVars; calVars = 0; }
void IsisMain() { // Get the projection UserInterface &ui = Application::GetUserInterface (); Pvl pvl(ui.GetFilename("FROM")); proj = ProjectionFactory::CreateFromCube(pvl); // Determine ground range to crop and/or trim if (ui.WasEntered ("MINLAT")) { slat = ui.GetDouble ("MINLAT"); elat = ui.GetDouble ("MAXLAT"); slon = ui.GetDouble ("MINLON"); elon = ui.GetDouble ("MAXLON"); } else if (proj->HasGroundRange()) { slat = proj->MinimumLatitude(); elat = proj->MaximumLatitude(); slon = proj->MinimumLongitude(); elon = proj->MaximumLongitude(); } else { string msg = "Latitude and longitude range not defined in projection"; throw iException::Message(iException::User,msg,_FILEINFO_); } string mode = ui.GetString("MODE"); if(mode != "TRIM") { smallestLine = smallestSample = INT_MAX; biggestLine = biggestSample = -INT_MAX; ProcessByLine p; p.SetInputCube("FROM"); p.StartProcess(getSize); p.EndProcess(); int samples = biggestSample - smallestSample + 1; int lines = biggestLine - smallestLine + 1; // Run external crop string cropParams = ""; cropParams += "from=\"" + ui.GetFilename("FROM") + "\""; if(mode == "CROP") { cropParams += " to=\"" + ui.GetAsString("TO") + "\""; } else { cropParams += " to=TEMPORARYcropped.cub "; } cropParams += " sample= " + iString(smallestSample); cropParams += " nsamples= " + iString(samples); cropParams += " line= " + iString(smallestLine); cropParams += " nlines= " + iString(lines); try { Isis::iApp->Exec("crop", cropParams); } catch(iException &e) { string msg = "Could not execute crop with params: [" + cropParams + "]"; throw Isis::iException::Message(Isis::iException::Programmer, msg, _FILEINFO_); } if(mode == "BOTH") { delete proj; proj = NULL; Pvl pvl("TEMPORARYcropped.cub"); proj = ProjectionFactory::CreateFromCube(pvl); } } // Trim image if necessary if(mode != "CROP") { ProcessByLine p; CubeAttributeInput att; if(mode == "BOTH") { p.SetInputCube("TEMPORARYcropped.cub", att); } else { //if its trim p.SetInputCube("FROM"); } p.SetOutputCube("TO"); p.StartProcess(trim); p.EndProcess(); if(mode == "BOTH") remove("TEMPORARYcropped.cub"); } // Add mapping to print.prt PvlGroup mapping = proj->Mapping(); Application::Log(mapping); delete proj; proj = NULL; }
void IsisMain() { latLonGrid = NULL; // We will be processing by line ProcessByLine p; Cube *icube = p.SetInputCube("FROM"); UserInterface &ui = Application::GetUserInterface(); QString mode = ui.GetString("MODE"); outline = ui.GetBoolean("OUTLINE"); ticks = ui.GetBoolean("TICKS"); if (ticks) { tickSize = ui.GetInteger("TICKSIZE") / 2; diagonalTicks = ui.GetBoolean("DIAGONALTICKS"); } lineWidth = ui.GetInteger("LINEWIDTH") / 2; QString bval = ui.GetString("BKGNDVALUE").toUpper(); image = (bval == "IMAGE"); bkgndValue = Null; if (bval == "HRS") { bkgndValue = Hrs; } else if (bval == "LRS") { bkgndValue = Lrs; } else if (bval == "DN") { bkgndValue = ui.GetDouble("BKGNDDNVALUE"); } QString lval = ui.GetString("LINEVALUE").toUpper(); if (lval == "HRS") { lineValue = Hrs; } else if (lval == "LRS") { lineValue = Lrs; } else if (lval == "NULL") { lineValue = Null; } else if (lval == "DN") { if (ui.WasEntered("DNVALUE")) { lineValue = ui.GetDouble("DNVALUE"); } else { throw IException(IException::User, "Must enter value in DNVALUE", _FILEINFO_); } } else { IString msg = "Invalid LINEVALUE string [" + ui.GetString("LINEVALUE"); msg += "], must be one of HRS, LRS, NULL, or DN."; throw IException(IException::User, msg, _FILEINFO_); } inputSamples = icube->sampleCount(); inputLines = icube->lineCount(); // Line & sample based grid if (mode == "IMAGE") { p.SetOutputCube("TO"); baseLine = ui.GetInteger("BASELINE"); baseSample = ui.GetInteger("BASESAMPLE"); lineInc = ui.GetInteger("LINC"); sampleInc = ui.GetInteger("SINC"); p.StartProcess(imageGrid); p.EndProcess(); } // Lat/Lon based grid else { CubeAttributeOutput oatt("+32bit"); p.SetOutputCube(ui.GetFileName("TO"), oatt, icube->sampleCount(), icube->lineCount(), icube->bandCount()); UniversalGroundMap *gmap = new UniversalGroundMap(*icube, UniversalGroundMap::ProjectionFirst); latLonGrid = new GroundGrid(gmap, ticks, icube->sampleCount(), icube->lineCount()); baseLat = Latitude(ui.GetDouble("BASELAT"), *latLonGrid->GetMappingGroup(), Angle::Degrees); baseLon = Longitude(ui.GetDouble("BASELON"), *latLonGrid->GetMappingGroup(), Angle::Degrees); latInc = Angle(ui.GetDouble("LATINC"), Angle::Degrees); lonInc = Angle(ui.GetDouble("LONINC"), Angle::Degrees); Progress progress; progress.SetText("Calculating Grid"); Latitude minLat, maxLat; if (ui.WasEntered("MINLAT")) minLat = Latitude(ui.GetDouble("MINLAT"), *latLonGrid->GetMappingGroup(), Angle::Degrees); if (ui.WasEntered("MAXLAT")) maxLat = Latitude(ui.GetDouble("MAXLAT"), *latLonGrid->GetMappingGroup(), Angle::Degrees); Longitude minLon, maxLon; if (ui.WasEntered("MINLON")) minLon = Longitude(ui.GetDouble("MINLON"), *latLonGrid->GetMappingGroup(), Angle::Degrees); if (ui.WasEntered("MAXLON")) maxLon = Longitude(ui.GetDouble("MAXLON"), *latLonGrid->GetMappingGroup(), Angle::Degrees); latLonGrid->SetGroundLimits(minLat, minLon, maxLat, maxLon); latLonGrid->CreateGrid(baseLat, baseLon, latInc, lonInc, &progress); if (ui.GetBoolean("BOUNDARY")) latLonGrid->WalkBoundary(); p.StartProcess(groundGrid); p.EndProcess(); delete latLonGrid; latLonGrid = NULL; delete gmap; gmap = NULL; } }
void IsisMain() { // Open the input cube ProcessByLine p; Cube *input = p.SetInputCube("FROM"); // Check for filter type of A-D Pvl *label = input->Label(); iString wave = (string)label->FindGroup("BandBin", Pvl::Traverse)["FilterName"]; if ((wave != "A") && (wave != "B") && (wave != "C") && (wave != "D")) { string message = "Invalid FilterName [" + wave + "], can only handle A-D filters"; throw iException::Message(Isis::iException::None, message, _FILEINFO_); } // Determine and load calibration flat field file wave.DownCase(); iString flatFile("$Clementine1/calibration/hires/lh" + wave + "_flat.cub"); CubeAttributeInput cubeAtt; p.SetInputCube(flatFile, cubeAtt); // Check the offset mode for validity int index = label->FindGroup("Instrument", Pvl::Traverse)["OffsetModeID"]; if (index < 0 || index > 5) { string message = "Invalid OffsetModeID, can only handle offests 0-5"; throw iException::Message(Isis::iException::None, message, _FILEINFO_); } // Set the offset (b0) value based on mode double dataOffset[] = {-49.172, -41.0799, -32.8988, -24.718, -16.98, -8.0}; offset = dataOffset[index]; // Computer the K value to convert to I/F. The K value per MCP and wavelength // were obtained from JGR publication Vol 108, A radiometric calibration for the // Clementine HIRES camera: Robinson, Malart, White, page 17 UserInterface &ui = Application::GetUserInterface(); if (ui.GetString("KFROM").compare("COMPUTED") == 0) { wave.UpCase(); int MCP = label->FindGroup("Instrument", Pvl::Traverse)["MCPGainModeID"]; // Two possible MCP gains for filter A if (wave == "A") { if (MCP == 156) { abscoef = 0.00105; } else if (MCP == 159) { abscoef = 0.00089; } else { string message = "Image is not one of supported MCP Gain Mode IDs, enter your own K value"; throw Isis::iException::Message(Isis::iException::User, message, _FILEINFO_); } } // Three possiblities for filter D else if (wave == "D") { if (MCP == 151) { abscoef = 0.001655; } else if (MCP == 154) { abscoef = 0.001375; } else if (MCP == 158) { abscoef = 0.00097; } else { string message = "Image is not one of supported MCP Gain Mode IDs, enter your own K value"; throw Isis::iException::Message(Isis::iException::User, message, _FILEINFO_); } } // Other filters not supported for preset K value else { string message = "Image is of filter [" + wave + "], not supported type A or D, enter your own K value"; throw Isis::iException::Message(Isis::iException::User, message, _FILEINFO_); } } // Otherwise get K value from user else { abscoef = ui.GetDouble("KVALUE"); } // K, Offset, and flat file are defined. Create output cube and process // each line p.SetOutputCube("TO"); p.StartProcess(clemhirescal); p.EndProcess(); }
void IsisMain() { // We will be processing by line ProcessByLine p; // Setup the input and output cubes Cube *icube = p.SetInputCube("FROM"); PvlKeyword &status = icube->group("RESEAUS")["STATUS"]; UserInterface &ui = Application::GetUserInterface(); QString in = ui.GetFileName("FROM"); // Check reseau status and make sure it is not nominal or removed if((QString)status == "Nominal") { QString msg = "Input file [" + in + "] appears to have nominal reseau status. You must run findrx first."; throw IException(IException::User, msg, _FILEINFO_); } if((QString)status == "Removed") { QString msg = "Input file [" + in + "] appears to already have reseaus removed."; throw IException(IException::User, msg, _FILEINFO_); } status = "Removed"; p.SetOutputCube("TO"); // Start the processing p.StartProcess(cpy); p.EndProcess(); // Get the user entered dimensions sdim = ui.GetInteger("SDIM"); ldim = ui.GetInteger("LDIM"); // Get other user entered options QString out = ui.GetFileName("TO"); resvalid = ui.GetBoolean("RESVALID"); action = ui.GetString("ACTION"); // Open the output cube Cube cube; cube.open(out, "rw"); PvlGroup &res = cube.label()->findGroup("RESEAUS", Pvl::Traverse); // Get reseau line, sample, type, and valid Keywords PvlKeyword lines = res.findKeyword("LINE"); PvlKeyword samps = res.findKeyword("SAMPLE"); PvlKeyword type = res.findKeyword("TYPE"); PvlKeyword valid = res.findKeyword("VALID"); int numres = lines.size(); Brick brick(sdim, ldim, 1, cube.pixelType()); for(int res = 0; res < numres; res++) { if((resvalid == 0 || toInt(valid[res]) == 1) && toInt(type[res]) != 0) { int baseSamp = (int)(toDouble(samps[res]) + 0.5) - (sdim / 2); int baseLine = (int)(toDouble(lines[res]) + 0.5) - (ldim / 2); brick.SetBasePosition(baseSamp, baseLine, 1); cube.read(brick); if(action == "NULL") { for(int i = 0; i < brick.size(); i++) brick[i] = Isis::Null; } else if(action == "BILINEAR") { Statistics stats; double array[sdim][ldim]; for(int s = 0; s < sdim; s++) { for(int l = 0; l < ldim; l++) { int index = l * sdim + s; array[s][l] = brick[index]; // Add perimeter data to stats object for calculations if(s == 0 || l == 0 || s == (sdim - 1) || l == (ldim - 1)) { stats.AddData(&array[s][l], 1); } } } // Get the average and standard deviation of the perimeter of the brick double avg = stats.Average(); double sdev = stats.StandardDeviation(); // Top Edge Reseau if(toInt(type[res]) == 2) { int l1 = 0; int l2 = ldim - 1; for(int s = 0; s < sdim; s++) { array[s][l1] = array[s][l2]; } } // Left Edge Reseau else if(toInt(type[res]) == 4) { int s1 = 0; int s2 = sdim - 1; for(int l = 0; l < ldim; l++) { array[s1][l] = array[s2][l]; } } // Right Edge Reseau else if(toInt(type[res]) == 6) { int s1 = 0; int s2 = sdim - 1; for(int l = 0; l < ldim; l++) { array[s2][l] = array[s1][l]; } } // Bottom Edge Reseau else if(toInt(type[res]) == 8) { int l1 = 0; int l2 = ldim - 1; for(int s = 0; s < sdim; s++) { array[s][l2] = array[s][l1]; } } // Walk top edge & replace data outside of 2devs with the avg for(int s = 0; s < sdim; s++) { int l = 0; double diff = fabs(array[s][l] - avg); if(diff > (2 * sdev)) array[s][l] = avg; } // Walk bottom edge & replace data outside of 2devs with the avg for(int s = 0; s < sdim; s++) { int l = ldim - 1; double diff = fabs(array[s][l] - avg); if(diff > (2 * sdev)) array[s][l] = avg; } // Walk left edge & replace data outside of 2devs with the avg for(int l = 0; l < ldim; l++) { int s = 0; double diff = fabs(array[s][l] - avg); if(diff > (2 * sdev)) array[s][l] = avg; } // Walk right edge & replace data outside of 2devs with the avg for(int l = 0; l < ldim; l++) { int s = sdim - 1; double diff = fabs(array[s][l] - avg); if(diff > (2 * sdev)) array[s][l] = avg; } srand(0); double dn, gdn1, gdn2; for(int l = 0; l < ldim; l++) { int c = l * sdim; //count // Top Edge Reseau if(toInt(type[res]) == 2 && l < (ldim / 2)) continue; // Bottom Edge Reseau if(toInt(type[res]) == 8 && l > (ldim / 2 + 1)) continue; for(int s = 0; s < sdim; s++, c++) { // Left Edge Reseau if(toInt(type[res]) == 4 && s < (sdim / 2)) continue; // Right Edge Reseau if(toInt(type[res]) == 6 && s > (sdim / 2 + 1)) continue; double sum = 0.0; int gline1 = 0; int gline2 = ldim - 1; gdn1 = array[s][gline1]; gdn2 = array[s][gline2]; // Linear Interpolation to get pixel value dn = gdn2 + (l - gline2) * (gdn1 - gdn2) / (gline1 - gline2); sum += dn; int gsamp1 = 0; int gsamp2 = sdim - 1; gdn1 = array[gsamp1][l]; gdn2 = array[gsamp2][l]; // Linear Interpolation to get pixel value dn = gdn2 + (s - gsamp2) * (gdn1 - gdn2) / (gsamp1 - gsamp2); sum += dn; dn = sum / 2; int rdm = rand(); double drandom = rdm / (double)RAND_MAX; double offset = 0.0; if(drandom < .333) offset = -1.0; if(drandom > .666) offset = 1.0; brick[c] = dn + offset; } } } } cube.write(brick); } cube.close(); }
void IsisMain() { // We will be processing by line ProcessByLine p; // Setup the input and make sure it is a mariner10 file UserInterface & ui = Application::GetUserInterface(); Isis::Pvl lab(ui.GetFileName("FROM")); Isis::PvlGroup & inst = lab.findGroup("Instrument", Pvl::Traverse); QString mission = inst["SpacecraftName"]; if (mission != "Mariner_10") { string msg = "This is not a Mariner 10 image. Mar10cal requires a Mariner 10 image."; throw IException(IException::User, msg, _FILEINFO_); } Cube * icube = p.SetInputCube("FROM", OneBand); // If it is already calibrated then complain if (icube->hasGroup("Radiometry")) { QString msg = "This Mariner 10 image [" + icube->fileName() + "] has " "already been radiometrically calibrated"; throw IException(IException::User, msg, _FILEINFO_); } // Get label parameters we will need for calibration equation QString instId = inst["InstrumentId"]; QString camera = instId.mid(instId.size()-1); QString filter = (QString)(icube->group("BandBin"))["FilterName"]; filter = filter.toUpper().mid(0,3); QString target = inst["TargetName"]; iTime startTime((QString) inst["StartTime"]); double exposure = inst["ExposureDuration"]; double exposureOffset = 0.0; if (ui.WasEntered("EXPOFF")) { exposureOffset = ui.GetDouble("EXPOFF"); } else { if (camera == "A") { exposureOffset = 0.316; } else if (camera == "B") { exposureOffset = 3.060; } else { QString msg = "Camera [" + camera + "] is not supported."; throw IException(IException::User, msg, _FILEINFO_); } } correctedExp = exposure + exposureOffset; Cube * dcCube; if (ui.WasEntered ("DCCUBE") ) { dcCube = p.SetInputCube("DCCUBE"); } else { // Mercury Dark current // ??? NOTE: Need to find Mark's dc for venus and moon ???? QString dcFile("$mariner10/calibration/mariner_10_" + camera + "_dc.cub"); CubeAttributeInput cubeAtt; dcCube = p.SetInputCube(dcFile, cubeAtt); } // Open blemish removal file Cube * blemCube = 0; useBlem = (ui.GetBoolean("BLEMMASK")) ? true : false; if (useBlem) { QString blemFile("$mariner10/calibration/mariner_10_blem_" + camera + ".cub"); CubeAttributeInput cubeAtt; blemCube = p.SetInputCube(blemFile, cubeAtt); } if (filter == "FAB" || filter == "WAF") { QString msg = "Filter type [" + filter + "] is not supported at this time."; throw IException(IException::User, msg, _FILEINFO_); } if (ui.WasEntered ("COEFCUBE")) { coCube.open(ui.GetFileName("COEFCUBE")); } else { FileName coFile("$mariner10/calibration/mariner_10_" + filter + "_" + camera + "_coef.cub"); coCube.open(coFile.expanded()); } coef = new Brick(icube->sampleCount(), 1, 6, coCube.pixelType()); if (ui.WasEntered("ABSCOEF")) { absCoef = ui.GetDouble("ABSCOEF"); } else { if (camera == "A") { absCoef = 16.0; } else if (camera == "B") { absCoef = 750.0; } else { QString msg = "Camera [" + camera + "] is not supported."; throw IException(IException::User, msg, _FILEINFO_); } } mask = ui.GetBoolean("MASK"); xparm = ui.GetDouble("XPARM"); // Get the distance between Mars and the Sun at the given time in // Astronomical Units (AU) Camera * cam = icube->camera(); bool camSuccess = cam->SetImage(icube->sampleCount()/2,icube->lineCount()/2); if (!camSuccess) { throw IException(IException::Unknown, "Unable to calculate the Solar Distance on [" + icube->fileName() + "]", _FILEINFO_); } sunDist = cam->SolarDistance(); // Setup the output cube Cube *ocube = p.SetOutputCube("TO"); // Add the radiometry group PvlGroup calgrp("Radiometry"); calgrp += PvlKeyword("DarkCurrentCube", dcCube->fileName()); if (useBlem) { calgrp += PvlKeyword("BlemishRemovalCube", blemCube->fileName()); } calgrp += PvlKeyword("CoefficientCube", coCube.fileName()); calgrp += PvlKeyword("AbsoluteCoefficient", toString(absCoef)); ocube->putGroup(calgrp); // Start the line-by-line calibration sequence p.StartProcess(Mar10Cal); p.EndProcess(); }