示例#1
0
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();
}
示例#2
0
文件: unitTest.cpp 项目: corburn/ISIS
int main(int argc, char *argv[]) {
  Preference::Preferences(true);
  cout << setprecision(9);

  try {
    FileName fromList("FromList.lst");
    QString holdList = "HoldList.lst";

    cout << "UnitTest for Equalization" << endl;
    HiEqualization equalizer(fromList.toString());
    equalizer.addHolds(holdList);

    equalizer.calculateStatistics();

    // Open input cube
    FileList imageList(fromList);
    for (int i = 0; i < imageList.size(); i++) {
      ProcessByLine p;
      CubeAttributeInput att;
      QString inp = imageList[i].toString();
      Cube *inputCube = p.SetInputCube(inp, att);
      TestFunctor func(&equalizer, inputCube->lineCount(), i);
      p.ProcessCubeInPlace(func, false);
      p.EndProcess();
    }
  }
  catch (IException &e) {
    e.print();
  }
}
示例#3
0
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();
}
示例#4
0
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();
}
示例#5
0
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();
}
示例#6
0
文件: makecube.cpp 项目: corburn/ISIS
void IsisMain() {
  // Create a process by line object
  ProcessByLine p;

  // Get the value to put in the cube
  UserInterface &ui = Application::GetUserInterface();
  QString pixels = ui.GetString("PIXELS");

  double value = Null;
  if(pixels == "NULL") {
    value = NULL8;
  }
  else if(pixels == "LIS") {
    value = LOW_INSTR_SAT8;
  }
  else if(pixels == "LRS") {
    value = LOW_REPR_SAT8;
  }
  else if(pixels == "HIS") {
    value = HIGH_INSTR_SAT8;
  }
  else if(pixels == "HRS") {
    value = HIGH_REPR_SAT8;
  }
  else {
    value = ui.GetDouble("VALUE");
  }

  // Need to pick good min/maxs to ensure the user's value
  // doesn't get saturated
  CubeAttributeOutput &att = ui.GetOutputAttribute("TO");
  if(IsValidPixel(value)) {
    if(value == 0.0) {
      att.setMinimum(value);
      att.setMaximum(value + 1.0);
    }
    if(value < 0.0) {
      att.setMinimum(value);
      att.setMaximum(-value);
    }
    else {
      att.setMinimum(-value);
      att.setMaximum(value);
    }
  }
  else {
    att.setMinimum(0.0);
    att.setMaximum(1.0);
  }

  // Get the size of the cube and create the cube
  int samps = ui.GetInteger("SAMPLES");
  int lines = ui.GetInteger("LINES");
  int bands = ui.GetInteger("BANDS");
  p.SetOutputCube(ui.GetFileName("TO"), att, samps, lines, bands);

  // Make the cube
  p.ProcessCubeInPlace(ConstantValueFunctor(value), false);
  p.EndProcess();
}
示例#7
0
文件: vimscal.cpp 项目: jlaura/isis3
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();
}
示例#8
0
  void HiEqualization::calculateStatistics() {
    // TODO member variable
    const FileList &imageList = getInputs();
    QString maxCubeStr = toString((int) imageList.size());

    // Adds statistics for whole and side regions of every cube
    vector<Statistics *> statsList;
    vector<Statistics *> leftStatsList;
    vector<Statistics *> rightStatsList;
    for (int img = 0; img < imageList.size(); img++) {
      Statistics *stats = new Statistics();
      Statistics *statsLeft = new Statistics();
      Statistics *statsRight = new Statistics();

      QString cubeStr = toString((int) img + 1);

      ProcessByLine p;
      p.Progress()->SetText("Calculating Statistics for Cube " +
          cubeStr + " of " + maxCubeStr);
      CubeAttributeInput att;
      QString inp = imageList[img].toString();
      p.SetInputCube(inp, att);
      HiCalculateFunctor func(stats, statsLeft, statsRight, 100.0);
      p.ProcessCubeInPlace(func, false);

      statsList.push_back(stats);
      leftStatsList.push_back(statsLeft);
      rightStatsList.push_back(statsRight);
    }

    // Initialize the object that will calculate the gains and offsets
    OverlapNormalization oNorm(statsList);

    // Add the known overlaps between two cubes, and apply a weight to each
    // overlap equal the number of pixels in the overlapping area
    for (int i = 0; i < imageList.size() - 1; i++) {
      int j = i + 1;
      oNorm.AddOverlap(*rightStatsList[i], i, *leftStatsList[j], j,
          rightStatsList[i]->ValidPixels());
    }

    loadHolds(&oNorm);

    // Attempt to solve the least squares equation
    oNorm.Solve(OverlapNormalization::Both);

    clearAdjustments();
    for (int img = 0; img < imageList.size(); img++) {
      ImageAdjustment *adjustment = new ImageAdjustment(OverlapNormalization::Both);
      adjustment->addGain(oNorm.Gain(img));
      adjustment->addOffset(oNorm.Offset(img));
      adjustment->addAverage(oNorm.Average(img));
      addAdjustment(adjustment);
    }

    addValid(imageList.size() - 1);
    setResults();
  }
示例#9
0
文件: cosi.cpp 项目: assutech/isis3
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();
}
示例#10
0
文件: mirror.cpp 项目: corburn/ISIS
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();
}
示例#11
0
文件: histeq.cpp 项目: assutech/isis3
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();
}
示例#12
0
  /**
   * 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;
  }
示例#13
0
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();
}
示例#14
0
void IsisMain () {
  // Grab the file to import
  UserInterface &ui = Application::GetUserInterface();
  Filename in = ui.GetFilename("FROM");
  Filename out = ui.GetFilename("TO");
 
  // Make sure it is a Clementine EDR
  bool projected;
  try {
    Pvl lab(in.Expanded());
    projected = lab.HasObject("IMAGE_MAP_PROJECTION");
    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 ();
}
示例#15
0
void IsisMain() {
  // Grab the file to import
  UserInterface &ui = Application::GetUserInterface();
  FileName in = ui.GetFileName("FROM");
  FileName out = ui.GetFileName("TO");

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

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

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

  ProcessByLine p;
  CubeAttributeOutput cubeAtt("+unsignedByte+1.0:254.0");
  Cube *ocube = p.SetOutputCube(ui.GetFileName("TO"), cubeAtt, pdsi->image_ncols, pdsi->image_nrows);
  p.StartProcess(WriteLine);
  TranslateLabels(in, ocube);
  p.EndProcess();
}
示例#16
0
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();
}
示例#17
0
文件: grid.cpp 项目: assutech/isis3
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;
  }
}
示例#18
0
文件: ratio.cpp 项目: corburn/ISIS
void IsisMain() {
  ProcessByLine p;
  p.SetInputCube("NUMERATOR");
  p.SetInputCube("DENOMINATOR");
  p.SetOutputCube("TO");
  p.StartProcess(ratio);
  p.EndProcess();
}
示例#19
0
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();
}
示例#20
0
文件: trim.cpp 项目: assutech/isis3
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_);
  }
	   
}
示例#21
0
文件: specadd.cpp 项目: corburn/ISIS
void IsisMain() {
  ProcessByLine p;

  // Setup the input and output cubes
  p.SetInputCube("FROM");
  p.SetInputCube("MATCH");
  p.SetOutputCube("TO");

  p.StartProcess(specadd);
  p.EndProcess();
}
示例#22
0
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();
}
示例#23
0
  /**
   * 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;
  }
示例#24
0
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;
}
示例#25
0
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();
}
示例#26
0
文件: reduce.cpp 项目: corburn/ISIS
void IsisMain() {
  try {
    // We will be processing by line
    ProcessByLine p;
    double sscale, lscale;
    int ins, inl, inb;
    int ons, onl;
    vector<QString> bands;
    Cube inCube;

    // To propogate labels, set input cube,
    // this cube will be cleared after output cube is set.
    p.SetInputCube("FROM");

    // Setup the input and output cubes
    UserInterface &ui = Application::GetUserInterface();
    QString replaceMode = ui.GetAsString("VPER_REPLACE");
    CubeAttributeInput cai(ui.GetAsString("FROM"));
    bands = cai.bands();

    inCube.setVirtualBands(bands);

    QString from = ui.GetFileName("FROM");
    inCube.open(from);

    ins = inCube.sampleCount();
    inl = inCube.lineCount();
    inb = inCube.bandCount();

    QString alg  = ui.GetString("ALGORITHM");
    double vper = ui.GetDouble("VALIDPER") / 100.;

    if(ui.GetString("MODE") == "TOTAL") {
      ons = ui.GetInteger("ONS");
      onl = ui.GetInteger("ONL");
      sscale = (double)ins / (double)ons;
      lscale = (double)inl / (double)onl;
    }
    else {
      sscale = ui.GetDouble("SSCALE");
      lscale = ui.GetDouble("LSCALE");
      ons = (int)((double)ins / sscale + 0.5);
      onl = (int)((double)inl / lscale + 0.5);
    }

    if(ons > ins || onl > inl) {
      QString msg = "Number of output samples/lines must be less than or equal";
      msg = msg + " to the input samples/lines.";
      throw IException(IException::User, msg, _FILEINFO_);
    }

    //  Allocate output file
    Cube *ocube = p.SetOutputCube("TO", ons, onl, inb);
    // Our processing routine only needs 1
    // the original set was for info about the cube only
    p.ClearInputCubes();

    // Start the processing
    PvlGroup results;
    if(alg == "AVERAGE"){
      Average average(&inCube, sscale, lscale, vper, replaceMode);
      p.ProcessCubeInPlace(average, false);
      results = average.UpdateOutputLabel(ocube);
    }
    else if(alg == "NEAREST") {
      Nearest near(&inCube, sscale, lscale);
      p.ProcessCubeInPlace(near, false);
      results = near.UpdateOutputLabel(ocube);
    }

    // Cleanup
    inCube.close();
    p.EndProcess();

    // Write the results to the log
    Application::Log(results);
  } // REFORMAT THESE ERRORS INTO ISIS TYPES AND RETHROW
  catch (IException &) {
    throw;
  }
  catch (std::exception const &se) {
    QString message = "std::exception: " + (QString)se.what();
    throw IException(IException::User, message, _FILEINFO_);
  }
  catch (...) {
    QString message = "Other Error";
    throw IException(IException::User, message, _FILEINFO_);
  }
}
示例#27
0
文件: grid.cpp 项目: corburn/ISIS
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;
  }
}
示例#28
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;
}
示例#29
0
文件: remrx.cpp 项目: jlaura/isis3
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();

}
示例#30
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;
}