Beispiel #1
1
  public Map<Band, Variable> addBands(
      Product product, Variable idxVariable, List<Variable> l3ProdVars) {

    final Structure binListStruc = (Structure) idxVariable;

    final Map<Band, Variable> bandToVariableMap = new HashMap<Band, Variable>();

    //        bandToVariableMap.put(addBand(product, "bin_num", ProductData.TYPE_UINT32),
    // binListStruc.select("bin_num").findVariable("bin_num"));
    bandToVariableMap.put(
        addBand(product, "weights", ProductData.TYPE_FLOAT32),
        binListStruc.select("weights").findVariable("weights"));
    bandToVariableMap.put(
        addBand(product, "nobs", ProductData.TYPE_UINT16),
        binListStruc.select("nobs").findVariable("nobs"));
    bandToVariableMap.put(
        addBand(product, "nscenes", ProductData.TYPE_UINT16),
        binListStruc.select("nscenes").findVariable("nscenes"));
    //        ncFile.getRootGroup().findGroup("Level-3 Binned Data").findVariable("BinList");
    if (ncFile.getRootGroup().findGroup("Level-3_Binned_Data").findVariable("qual_l3") != null) {
      bandToVariableMap.put(
          addBand(product, "qual_l3", ProductData.TYPE_UINT8),
          ncFile.getRootGroup().findGroup("Level-3_Binned_Data").findVariable("qual_l3"));
    }
    String groupnames = "";
    for (Variable l3Var : l3ProdVars) {
      String varName = l3Var.getShortName();
      final int dataType = ProductData.TYPE_FLOAT32;

      if (!varName.contains("Bin")
          && (!varName.startsWith("qual"))
          && (!varName.equalsIgnoreCase("SEAGrid"))
          && (!varName.equalsIgnoreCase("Input_Files"))) {
        final Structure binStruc = (Structure) l3Var;
        if (groupnames.length() == 0) {
          groupnames = varName;
        } else {
          groupnames = groupnames + ":" + varName;
        }

        List<String> vnames = binStruc.getVariableNames();
        for (String bandvar : vnames) {
          bandToVariableMap.put(
              addBand(product, bandvar, dataType), binStruc.select(bandvar).findVariable(bandvar));
        }
        // Add virtual band for product mean
        StringBuilder prodname = new StringBuilder(varName);
        prodname.append("_mean");

        String calcmean = ComputeBinMeans(varName);
        Band varmean =
            new VirtualBand(
                prodname.toString(),
                ProductData.TYPE_FLOAT32,
                product.getSceneRasterWidth(),
                product.getSceneRasterHeight(),
                calcmean);
        varmean.setNoDataValue(Double.NaN);
        varmean.setNoDataValueUsed(true);
        product.addBand(varmean);

        // Add virtual band for product stdev
        int underscore = prodname.indexOf("_mean");
        prodname.delete(underscore, underscore + 5);
        prodname.append("_stdev");

        String calcstdev = ComputeBinVariances(varName);

        Band varstdev =
            new VirtualBand(
                prodname.toString(),
                ProductData.TYPE_FLOAT32,
                product.getSceneRasterWidth(),
                product.getSceneRasterHeight(),
                calcstdev);
        varstdev.setNoDataValue(Double.NaN);
        varstdev.setNoDataValueUsed(true);

        product.addBand(varstdev);
      }
    }
    product.setAutoGrouping(groupnames);
    return bandToVariableMap;
  }
  private static void setSubsetSRGRCoefficients(
      final Product sourceProduct,
      final Product targetProduct,
      final ProductSubsetDef subsetDef,
      final MetadataElement absRoot,
      final boolean nearRangeOnLeft) {

    final MetadataElement SRGRCoefficientsElem = absRoot.getElement("SRGR_Coefficients");
    if (SRGRCoefficientsElem != null) {
      final double rangeSpacing = absRoot.getAttributeDouble("RANGE_SPACING", 0);
      final double colIndex = subsetDef.getRegion() == null ? 0 : subsetDef.getRegion().getX();

      for (MetadataElement srgrList : SRGRCoefficientsElem.getElements()) {
        final double grO = srgrList.getAttributeDouble("ground_range_origin", 0);
        double ground_range_origin_subset;
        if (nearRangeOnLeft) {
          ground_range_origin_subset = grO + colIndex * rangeSpacing;
        } else {
          final double colIndexFromRight =
              sourceProduct.getSceneRasterWidth() - colIndex - targetProduct.getSceneRasterWidth();
          ground_range_origin_subset = grO + colIndexFromRight * rangeSpacing;
        }
        srgrList.setAttributeDouble("ground_range_origin", ground_range_origin_subset);
      }
    }
  }
 private static boolean isNearRangeOnLeft(final Product product) {
   final TiePointGrid incidenceAngle = product.getTiePointGrid("incident_angle");
   if (incidenceAngle != null) {
     final double incidenceAngleToFirstPixel = incidenceAngle.getPixelDouble(0, 0);
     final double incidenceAngleToLastPixel =
         incidenceAngle.getPixelDouble(product.getSceneRasterWidth() - 1, 0);
     return (incidenceAngleToFirstPixel < incidenceAngleToLastPixel);
   } else {
     return true;
   }
 }
Beispiel #4
0
 private Band addBand(Product product, String varName, int productType) {
   Band band =
       new Band(
           varName, productType, product.getSceneRasterWidth(), product.getSceneRasterHeight());
   band.setScalingOffset(0.0);
   band.setScalingFactor(1.0);
   band.setLog10Scaled(false);
   if (productType == ProductData.TYPE_FLOAT32) {
     band.setNoDataValue(Double.NaN);
   } else {
     band.setNoDataValue(-999);
   }
   band.setNoDataValueUsed(true);
   product.addBand(band);
   return band;
 }
Beispiel #5
0
  protected Band addNewBand(Product product, Variable variable) {
    final int sceneRasterWidth = product.getSceneRasterWidth();
    final int sceneRasterHeight = product.getSceneRasterHeight();
    Band band = null;

    int variableRank = variable.getRank();
    if (variableRank == 2) {
      final int[] dimensions = variable.getShape();
      final int height = dimensions[0] - leadLineSkip - tailLineSkip;
      final int width = dimensions[1];
      if (height == sceneRasterHeight && width == sceneRasterWidth) {
        final String name = variable.getShortName();
        final int dataType = getProductDataType(variable);
        band = new Band(name, dataType, width, height);
        final String validExpression = bandInfoMap.get(name);
        if (validExpression != null && !validExpression.equals("")) {
          band.setValidPixelExpression(validExpression);
        }
        product.addBand(band);

        try {
          band.setNoDataValue(
              (double) variable.findAttribute("bad_value_scaled").getNumericValue().floatValue());
          band.setNoDataValueUsed(true);
        } catch (Exception ignored) {
        }

        final List<Attribute> list = variable.getAttributes();
        for (Attribute hdfAttribute : list) {
          final String attribName = hdfAttribute.getShortName();
          if ("units".equals(attribName)) {
            band.setUnit(hdfAttribute.getStringValue());
          } else if ("long_name".equals(attribName)) {
            band.setDescription(hdfAttribute.getStringValue());
          } else if ("slope".equals(attribName)) {
            band.setScalingFactor(hdfAttribute.getNumericValue(0).doubleValue());
          } else if ("intercept".equals(attribName)) {
            band.setScalingOffset(hdfAttribute.getNumericValue(0).doubleValue());
          }
        }
      }
    }
    return band;
  }
  @Override
  protected void addFlagsAndMasks(Product product) {
    Band QFBand = product.getBand("l3m_qual");
    if (QFBand != null) {
      FlagCoding flagCoding = new FlagCoding("SST_Quality");
      flagCoding.addFlag("Best", 0x00, "Highest quality retrieval");
      flagCoding.addFlag("Good", 0x01, "Good quality retrieval");
      flagCoding.addFlag("Questionable", 0x02, "Questionable quality retrieval");
      flagCoding.addFlag("Bad", 0x03, "Bad quality retrieval");
      product.getFlagCodingGroup().add(flagCoding);
      QFBand.setSampleCoding(flagCoding);

      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "Best",
                  "Highest quality retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l3m_qual == 0",
                  SeadasFileReader.Cornflower,
                  0.6));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "Good",
                  "Good quality retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l3m_qual == 1",
                  SeadasFileReader.LightPurple,
                  0.6));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "Questionable",
                  "Questionable quality retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l3m_qual == 2",
                  SeadasFileReader.BurntUmber,
                  0.6));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "Bad",
                  "Bad quality retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l3m_qual == 3",
                  SeadasFileReader.FailRed,
                  0.6));
    }
    QFBand = product.getBand("qual_sst");
    if (QFBand != null) {
      FlagCoding flagCoding = new FlagCoding("SST_Quality");
      flagCoding.addFlag("Best", 0x00, "Highest quality retrieval");
      flagCoding.addFlag("Good", 0x01, "Good quality retrieval");
      flagCoding.addFlag("Questionable", 0x02, "Questionable quality retrieval");
      flagCoding.addFlag("Bad", 0x03, "Bad quality retrieval");
      product.getFlagCodingGroup().add(flagCoding);
      QFBand.setSampleCoding(flagCoding);

      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "Best",
                  "Highest quality retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "qual_sst == 0",
                  SeadasFileReader.Cornflower,
                  0.6));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "Good",
                  "Good quality retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "qual_sst == 1",
                  SeadasFileReader.LightPurple,
                  0.6));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "Questionable",
                  "Questionable quality retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "qual_sst == 2",
                  SeadasFileReader.BurntUmber,
                  0.6));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "Bad",
                  "Bad quality retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "qual_sst == 3",
                  SeadasFileReader.FailRed,
                  0.6));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "No Data",
                  "No data retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "qual_sst == -1",
                  SeadasFileReader.MediumGray,
                  0.6));
    }
    QFBand = product.getBand("qual_sst4");
    if (QFBand != null) {
      FlagCoding flagCoding = new FlagCoding("SST_Quality");
      flagCoding.addFlag("Best", 0x00, "Highest quality retrieval");
      flagCoding.addFlag("Good", 0x01, "Good quality retrieval");
      flagCoding.addFlag("Questionable", 0x02, "Questionable quality retrieval");
      flagCoding.addFlag("Bad", 0x03, "Bad quality retrieval");
      product.getFlagCodingGroup().add(flagCoding);
      QFBand.setSampleCoding(flagCoding);

      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "Best",
                  "Highest quality retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "qual_sst4 == 0",
                  SeadasFileReader.Cornflower,
                  0.6));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "Good",
                  "Good quality retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "qual_sst4 == 1",
                  SeadasFileReader.LightPurple,
                  0.6));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "Questionable",
                  "Questionable quality retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "qual_sst4 == 2",
                  SeadasFileReader.BurntUmber,
                  0.6));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "Bad",
                  "Bad quality retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "qual_sst4 == 3",
                  SeadasFileReader.FailRed,
                  0.6));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "No Data",
                  "No data retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "qual_sst4 == -1",
                  SeadasFileReader.MediumGray,
                  0.6));
    }
  }
  public void addGeocoding(Product product) throws IOException {

    double pixelX = 0.5;
    double pixelY = 0.5;
    double easting;
    double northing;
    double pixelSizeX;
    double pixelSizeY;
    boolean pixelRegistered = true;
    if (productReader.getProductType() == SeadasProductReader.ProductType.ANCNRT) {
      pixelRegistered = false;
    }
    if (productReader.getProductType() == SeadasProductReader.ProductType.OISST) {

      Variable lon = ncFile.findVariable("lon");
      Variable lat = ncFile.findVariable("lat");
      Array lonData = lon.read();
      // TODO: handle the 180 degree shift with the NOAA products - need to modify
      // SeaDasFileReader:readBandData
      // Below is a snippet from elsewhere in BEAM that deals with this issue...
      // SPECIAL CASE: check if we have a global geographic lat/lon with lon from 0..360 instead of
      // -180..180
      //            if (isShifted180(lonData)) {
      //                // if this is true, subtract 180 from all longitudes and
      //                // add a global attribute which will be analyzed when setting up the
      // image(s)
      //                final List<Variable> variables = ncFile.getVariables();
      //                for (Variable next : variables) {
      //                    next.getAttributes().add(new Attribute("LONGITUDE_SHIFTED_180", 1));
      //                }
      //                for (int i = 0; i < lonData.getSize(); i++) {
      //                    final Index ii = lonData.getIndex().set(i);
      //                    final double theLon = lonData.getDouble(ii) - 180.0;
      //                    lonData.setDouble(ii, theLon);
      //                }
      //            }
      final Array latData = lat.read();

      final int lonSize = lon.getShape(0);
      final Index i0 = lonData.getIndex().set(0);
      final Index i1 = lonData.getIndex().set(lonSize - 1);

      pixelSizeX =
          (lonData.getDouble(i1) - lonData.getDouble(i0)) / (product.getSceneRasterWidth() - 1);
      easting = lonData.getDouble(i0);

      final int latSize = lat.getShape(0);
      final Index j0 = latData.getIndex().set(0);
      final Index j1 = latData.getIndex().set(latSize - 1);
      pixelSizeY =
          (latData.getDouble(j1) - latData.getDouble(j0)) / (product.getSceneRasterHeight() - 1);

      // this should be the 'normal' case
      if (pixelSizeY < 0) {
        pixelSizeY = -pixelSizeY;
        northing = latData.getDouble(latData.getIndex().set(0));
      } else {
        northing = latData.getDouble(latData.getIndex().set(latSize - 1));
      }
      northing -= pixelSizeX / 2.0;
      easting += pixelSizeY / 2.0;

      try {
        product.setGeoCoding(
            new CrsGeoCoding(
                DefaultGeographicCRS.WGS84,
                product.getSceneRasterWidth(),
                product.getSceneRasterHeight(),
                easting,
                northing,
                pixelSizeX,
                pixelSizeY,
                pixelX,
                pixelY));
      } catch (FactoryException e) {
        throw new IllegalStateException(e);
      } catch (TransformException e) {
        throw new IllegalStateException(e);
      }

    } else {

      String east = "Easternmost_Longitude";
      String west = "Westernmost_Longitude";
      String north = "Northernmost_Latitude";
      String south = "Southernmost_Latitude";
      Attribute latmax = ncFile.findGlobalAttributeIgnoreCase("geospatial_lat_max");
      if (latmax != null) {
        east = "geospatial_lon_max";
        west = "geospatial_lon_min";
        north = "geospatial_lat_max";
        south = "geospatial_lat_min";
      } else {
        latmax = ncFile.findGlobalAttributeIgnoreCase("upper_lat");
        if (latmax != null) {
          east = "right_lon";
          west = "left_lon";
          north = "upper_lat";
          south = "lower_lat";
        }
      }

      final MetadataElement globalAttributes =
          product.getMetadataRoot().getElement("Global_Attributes");
      easting = (float) globalAttributes.getAttribute(east).getData().getElemDouble();
      float westing = (float) globalAttributes.getAttribute(west).getData().getElemDouble();
      pixelSizeX = Math.abs(easting - westing) / product.getSceneRasterWidth();
      northing = (float) globalAttributes.getAttribute(north).getData().getElemDouble();
      float southing = (float) globalAttributes.getAttribute(south).getData().getElemDouble();
      if (northing < southing) {
        mustFlipY = true;
        northing = (float) globalAttributes.getAttribute(south).getData().getElemDouble();
        southing = (float) globalAttributes.getAttribute(north).getData().getElemDouble();
      }
      pixelSizeY = Math.abs(northing - southing) / product.getSceneRasterHeight();
      if (pixelRegistered) {
        northing -= pixelSizeY / 2.0;
        westing += pixelSizeX / 2.0;
      } else {
        pixelX = 0.0;
        pixelY = 0.0;
      }
      try {
        product.setGeoCoding(
            new CrsGeoCoding(
                DefaultGeographicCRS.WGS84,
                product.getSceneRasterWidth(),
                product.getSceneRasterHeight(),
                westing,
                northing,
                pixelSizeX,
                pixelSizeY,
                pixelX,
                pixelY));
      } catch (FactoryException e) {
        throw new IllegalStateException(e);
      } catch (TransformException e) {
        throw new IllegalStateException(e);
      }
    }
  }
  protected Map<Band, Variable> addSmiBands(Product product, List<Variable> variables) {
    final int sceneRasterWidth = product.getSceneRasterWidth();
    final int sceneRasterHeight = product.getSceneRasterHeight();
    Map<Band, Variable> bandToVariableMap = new HashMap<Band, Variable>();
    for (Variable variable : variables) {
      int variableRank = variable.getRank();
      if (variableRank == 2) {
        final int[] dimensions = variable.getShape();
        final int height = dimensions[0];
        final int width = dimensions[1];
        if (height == sceneRasterHeight && width == sceneRasterWidth) {
          String name = variable.getShortName();
          if (name.equals("l3m_data")) {
            try {
              name = getStringAttribute("Parameter") + " " + getStringAttribute("Measure");
            } catch (Exception e) {
              e.printStackTrace();
            }
          }

          final int dataType = getProductDataType(variable);
          final Band band = new Band(name, dataType, width, height);
          //                    band = new Band(name, dataType, width, height);

          product.addBand(band);

          try {
            Attribute fillvalue = variable.findAttribute("_FillValue");
            if (fillvalue == null) {
              fillvalue = variable.findAttribute("Fill");
            }
            if (fillvalue != null) {
              band.setNoDataValue((double) fillvalue.getNumericValue().floatValue());
              band.setNoDataValueUsed(true);
            }
          } catch (Exception ignored) {

          }
          bandToVariableMap.put(band, variable);
          // Set units, if defined
          try {
            band.setUnit(getStringAttribute("Units"));
          } catch (Exception ignored) {

          }

          final List<Attribute> list = variable.getAttributes();
          double[] validMinMax = {0.0, 0.0};
          for (Attribute hdfAttribute : list) {
            final String attribName = hdfAttribute.getShortName();
            if ("units".equals(attribName)) {
              band.setUnit(hdfAttribute.getStringValue());
            } else if ("long_name".equalsIgnoreCase(attribName)) {
              band.setDescription(hdfAttribute.getStringValue());
            } else if ("slope".equalsIgnoreCase(attribName)) {
              band.setScalingFactor(hdfAttribute.getNumericValue(0).doubleValue());
            } else if ("intercept".equalsIgnoreCase(attribName)) {
              band.setScalingOffset(hdfAttribute.getNumericValue(0).doubleValue());
            } else if ("scale_factor".equals(attribName)) {
              band.setScalingFactor(hdfAttribute.getNumericValue(0).doubleValue());
            } else if ("add_offset".equals(attribName)) {
              band.setScalingOffset(hdfAttribute.getNumericValue(0).doubleValue());
            } else if (attribName.startsWith("valid_")) {
              if ("valid_min".equals(attribName)) {
                validMinMax[0] = hdfAttribute.getNumericValue(0).doubleValue();
              } else if ("valid_max".equals(attribName)) {
                validMinMax[1] = hdfAttribute.getNumericValue(0).doubleValue();
              } else if ("valid_range".equals(attribName)) {
                validMinMax[0] = hdfAttribute.getNumericValue(0).doubleValue();
                validMinMax[1] = hdfAttribute.getNumericValue(1).doubleValue();
              }
            }
          }
          if (validMinMax[0] != validMinMax[1]) {
            double[] minmax = {0.0, 0.0};
            minmax[0] = validMinMax[0];
            minmax[1] = validMinMax[1];

            if (band.getScalingFactor() != 1.0) {
              minmax[0] *= band.getScalingFactor();
              minmax[1] *= band.getScalingFactor();
            }
            if (band.getScalingOffset() != 0.0) {
              minmax[0] += band.getScalingOffset();
              minmax[1] += band.getScalingOffset();
            }

            String validExp = format("%s >= %.2f && %s <= %.2f", name, minmax[0], name, minmax[1]);
            band.setValidPixelExpression(
                validExp); // .format(name, validMinMax[0], name, validMinMax[1]));
          }
        }
      } else if (variableRank == 4) {
        final int[] dimensions = variable.getShape();
        final int height = dimensions[2];
        final int width = dimensions[3];
        if (height == sceneRasterHeight && width == sceneRasterWidth) {
          String name = variable.getShortName();

          final int dataType = getProductDataType(variable);
          final Band band = new Band(name, dataType, width, height);
          //                    band = new Band(name, dataType, width, height);

          Variable sliced = null;
          try {
            sliced = variable.slice(0, 0).slice(0, 0);
          } catch (InvalidRangeException e) {
            e.printStackTrace(); // Todo change body of catch statement.
          }

          bandToVariableMap.put(band, sliced);
          product.addBand(band);

          try {
            Attribute fillvalue = variable.findAttribute("_FillValue");
            if (fillvalue != null) {
              band.setNoDataValue((double) fillvalue.getNumericValue().floatValue());
              band.setNoDataValueUsed(true);
            }
          } catch (Exception ignored) {

          }
          // Set units, if defined
          try {
            band.setUnit(getStringAttribute("units"));
          } catch (Exception ignored) {

          }

          final List<Attribute> list = variable.getAttributes();
          for (Attribute hdfAttribute : list) {
            final String attribName = hdfAttribute.getShortName();
            if ("scale_factor".equals(attribName)) {
              band.setScalingFactor(hdfAttribute.getNumericValue(0).doubleValue());
            } else if ("add_offset".equals(attribName)) {
              band.setScalingOffset(hdfAttribute.getNumericValue(0).doubleValue());
            }
          }
        }
      }
    }
    return bandToVariableMap;
  }
Beispiel #9
0
  protected void addFlagsAndMasks(Product product) {
    Band QFBand = product.getBand("l2_flags");
    if (QFBand != null) {
      FlagCoding flagCoding = new FlagCoding("L2Flags");
      flagCoding.addFlag("ATMFAIL", 0x01, "Atmospheric correction failure");
      flagCoding.addFlag("LAND", 0x02, "Land");
      flagCoding.addFlag("PRODWARN", 0x04, "One (or more) product algorithms generated a warning");
      flagCoding.addFlag("HIGLINT", 0x08, "High glint determined");
      flagCoding.addFlag("HILT", 0x10, "High (or saturating) TOA radiance");
      flagCoding.addFlag("HISATZEN", 0x20, "Large satellite zenith angle");
      flagCoding.addFlag("COASTZ", 0x40, "Shallow water (<30m)");
      flagCoding.addFlag("SPARE8", 0x80, "Unused");
      flagCoding.addFlag("STRAYLIGHT", 0x100, "Straylight determined");
      flagCoding.addFlag("CLDICE", 0x200, "Cloud/Ice determined");
      flagCoding.addFlag("COCCOLITH", 0x400, "Coccolithophores detected");
      flagCoding.addFlag("TURBIDW", 0x800, "Turbid water determined");
      flagCoding.addFlag("HISOLZEN", 0x1000, "High solar zenith angle");
      flagCoding.addFlag("SPARE14", 0x2000, "Unused");
      flagCoding.addFlag("LOWLW", 0x4000, "Low Lw @ 555nm (possible cloud shadow)");
      flagCoding.addFlag("CHLFAIL", 0x8000, "Chlorophyll algorithm failure");
      flagCoding.addFlag("NAVWARN", 0x10000, "Navigation suspect");
      flagCoding.addFlag("ABSAER", 0x20000, "Absorbing Aerosols determined");
      flagCoding.addFlag("SPARE19", 0x40000, "Unused");
      flagCoding.addFlag("MAXAERITER", 0x80000, "Maximum iterations reached for NIR iteration");
      flagCoding.addFlag("MODGLINT", 0x100000, "Moderate glint determined");
      flagCoding.addFlag("CHLWARN", 0x200000, "Chlorophyll out-of-bounds (<0.01 or >100 mg m^-3)");
      flagCoding.addFlag(
          "ATMWARN", 0x400000, "Atmospheric correction warning; Epsilon out-of-bounds");
      flagCoding.addFlag("SPARE24", 0x800000, "Unused");
      flagCoding.addFlag("SEAICE", 0x1000000, "Sea ice determined");
      flagCoding.addFlag("NAVFAIL", 0x2000000, "Navigation failure");
      flagCoding.addFlag("FILTER", 0x4000000, "Insufficient data for smoothing filter");
      flagCoding.addFlag("SSTWARN", 0x8000000, "Sea surface temperature suspect");
      flagCoding.addFlag("SSTFAIL", 0x10000000, "Sea surface temperature algorithm failure");
      flagCoding.addFlag("HIPOL", 0x20000000, "High degree of polariztion determined");
      flagCoding.addFlag(
          "PRODFAIL", 0x40000000, "One (or more) product algorithms produced a failure");
      flagCoding.addFlag("SPARE32", 0x80000000, "Unused");

      product.getFlagCodingGroup().add(flagCoding);
      QFBand.setSampleCoding(flagCoding);

      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "ATMFAIL",
                  "Atmospheric correction failure",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.ATMFAIL",
                  FailRed,
                  0.0));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "LAND",
                  "Land",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.LAND",
                  LandBrown,
                  0.0));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "PRODWARN",
                  "One (or more) product algorithms generated a warning",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.PRODWARN",
                  DeepBlue,
                  0.5));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "HILT",
                  "High (or saturating) TOA radiance",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.HILT",
                  Color.GRAY,
                  0.2));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "HIGLINT",
                  "High glint determined",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.HIGLINT",
                  BrightPink,
                  0.2));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "HISATZEN",
                  "Large satellite zenith angle",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.HISATZEN",
                  LightCyan,
                  0.5));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "COASTZ",
                  "Shallow water (<30m)",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.COASTZ",
                  BurntUmber,
                  0.5));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "STRAYLIGHT",
                  "Straylight determined",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.STRAYLIGHT",
                  Color.YELLOW,
                  0.2));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "CLDICE",
                  "Cloud/Ice determined",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.CLDICE",
                  Color.WHITE,
                  0.0));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "COCCOLITH",
                  "Coccolithophores detected",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.COCCOLITH",
                  Color.CYAN,
                  0.5));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "TURBIDW",
                  "Turbid water determined",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.TURBIDW",
                  LightBrown,
                  0.5));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "HISOLZEN",
                  "High solar zenith angle",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.HISOLZEN",
                  Purple,
                  0.5));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "LOWLW",
                  "Low Lw @ 555nm (possible cloud shadow)",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.LOWLW",
                  Cornflower,
                  0.5));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "CHLFAIL",
                  "Chlorophyll algorithm failure",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.CHLFAIL",
                  FailRed,
                  0.0));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "NAVWARN",
                  "Navigation suspect",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.NAVWARN",
                  Color.MAGENTA,
                  0.5));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "ABSAER",
                  "Absorbing Aerosols determined",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.ABSAER",
                  Color.ORANGE,
                  0.5));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "MAXAERITER",
                  "Maximum iterations reached for NIR correction",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.MAXAERITER",
                  MediumGray,
                  0.5));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "MODGLINT",
                  "Moderate glint determined",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.MODGLINT",
                  LightPurple,
                  0.5));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "CHLWARN",
                  "Chlorophyll out-of-bounds (<0.01 or >100 mg m^-3)",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.CHLWARN",
                  Color.LIGHT_GRAY,
                  0.5));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "ATMWARN",
                  "Atmospheric correction warning; Epsilon out-of-bounds",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.ATMWARN",
                  Color.MAGENTA,
                  0.5));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "SEAICE",
                  "Sea ice determined",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.SEAICE",
                  Color.DARK_GRAY,
                  0.5));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "NAVFAIL",
                  "Navigation failure",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.NAVFAIL",
                  FailRed,
                  0.0));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "FILTER",
                  "Insufficient data for smoothing filter",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.FILTER",
                  Color.LIGHT_GRAY,
                  0.5));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "SSTWARN",
                  "Sea surface temperature suspect",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.SSTWARN",
                  Color.MAGENTA,
                  0.5));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "SSTFAIL",
                  "Sea surface temperature algorithm failure",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.SSTFAIL",
                  FailRed,
                  0.1));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "HIPOL",
                  "High degree of polariztion determined",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.HIPOL",
                  Color.PINK,
                  0.5));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "PRODFAIL",
                  "One (or more) product algorithms produced a failure",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "l2_flags.PRODFAIL",
                  FailRed,
                  0.1));
    }
    Band QFBandSST = product.getBand("qual_sst");
    if (QFBandSST != null) {
      //            FlagCoding flagCoding = new FlagCoding("SSTFlags");
      //            product.getFlagCodingGroup().add(flagCoding);
      //
      //            QFBandSST.setSampleCoding(flagCoding);

      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "Best",
                  "Highest quality SST retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "qual_sst == 0",
                  SeadasFileReader.Cornflower,
                  0.6));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "Good",
                  "Good quality SST retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "qual_sst == 1",
                  SeadasFileReader.LightPurple,
                  0.6));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "Questionable",
                  "Questionable quality SST retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "qual_sst == 2",
                  SeadasFileReader.BurntUmber,
                  0.6));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "Bad",
                  "Bad quality SST retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "qual_sst == 3",
                  SeadasFileReader.FailRed,
                  0.6));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "No SST Retrieval",
                  "No SST retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "qual_sst == 4",
                  SeadasFileReader.FailRed,
                  0.6));
    }
    Band QFBandSST4 = product.getBand("qual_sst4");
    if (QFBandSST4 != null) {
      //            FlagCoding flagCoding = new FlagCoding("SST4Flags");
      //            product.getFlagCodingGroup().add(flagCoding);
      //            QFBandSST4.setSampleCoding(flagCoding);

      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "Best",
                  "Highest quality SST4 retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "qual_sst4 == 0",
                  SeadasFileReader.Cornflower,
                  0.6));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "Good",
                  "Good quality SST4 retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "qual_sst4 == 1",
                  SeadasFileReader.LightPurple,
                  0.6));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "Questionable",
                  "Questionable quality SST4 retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "qual_sst4 == 2",
                  SeadasFileReader.BurntUmber,
                  0.6));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "Bad",
                  "Bad quality SST4 retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "qual_sst4 == 3",
                  SeadasFileReader.FailRed,
                  0.6));
      product
          .getMaskGroup()
          .add(
              Mask.BandMathsType.create(
                  "No SST Retrieval",
                  "No SST retrieval",
                  product.getSceneRasterWidth(),
                  product.getSceneRasterHeight(),
                  "qual_sst4 == 4",
                  SeadasFileReader.FailRed,
                  0.6));
    }
  }
  private static void updateMetadata(
      final Product sourceProduct, final Product targetProduct, ProductSubsetDef subsetDef)
      throws IOException {

    try {
      final MetadataElement root = targetProduct.getMetadataRoot();
      if (root == null) return;

      final MetadataElement absRoot = root.getElement("Abstracted_Metadata");
      if (absRoot == null) return;

      boolean nearRangeOnLeft = isNearRangeOnLeft(targetProduct);

      final MetadataAttribute firstLineTime = absRoot.getAttribute("first_line_time");
      if (firstLineTime != null) {
        final ProductData.UTC startTime = targetProduct.getStartTime();
        if (startTime != null) firstLineTime.getData().setElems(startTime.getArray());
      }
      final MetadataAttribute lastLineTime = absRoot.getAttribute("last_line_time");
      if (lastLineTime != null) {
        final ProductData.UTC endTime = targetProduct.getEndTime();
        if (endTime != null) lastLineTime.getData().setElems(endTime.getArray());
      }
      final MetadataAttribute totalSize = absRoot.getAttribute("total_size");
      if (totalSize != null) totalSize.getData().setElemUInt(targetProduct.getRawStorageSize());

      if (nearRangeOnLeft) {
        setLatLongMetadata(targetProduct, absRoot, "first_near_lat", "first_near_long", 0.5f, 0.5f);
        setLatLongMetadata(
            targetProduct,
            absRoot,
            "first_far_lat",
            "first_far_long",
            targetProduct.getSceneRasterWidth() - 1 + 0.5f,
            0.5f);

        setLatLongMetadata(
            targetProduct,
            absRoot,
            "last_near_lat",
            "last_near_long",
            0.5f,
            targetProduct.getSceneRasterHeight() - 1 + 0.5f);
        setLatLongMetadata(
            targetProduct,
            absRoot,
            "last_far_lat",
            "last_far_long",
            targetProduct.getSceneRasterWidth() - 1 + 0.5f,
            targetProduct.getSceneRasterHeight() - 1 + 0.5f);
      } else {
        setLatLongMetadata(
            targetProduct,
            absRoot,
            "first_near_lat",
            "first_near_long",
            targetProduct.getSceneRasterWidth() - 1 + 0.5f,
            0.5f);
        setLatLongMetadata(targetProduct, absRoot, "first_far_lat", "first_far_long", 0.5f, 0.5f);

        setLatLongMetadata(
            targetProduct,
            absRoot,
            "last_near_lat",
            "last_near_long",
            targetProduct.getSceneRasterWidth() - 1 + 0.5f,
            targetProduct.getSceneRasterHeight() - 1 + 0.5f);
        setLatLongMetadata(
            targetProduct,
            absRoot,
            "last_far_lat",
            "last_far_long",
            0.5f,
            targetProduct.getSceneRasterHeight() - 1 + 0.5f);
      }

      final MetadataAttribute height = absRoot.getAttribute("num_output_lines");
      if (height != null) height.getData().setElemUInt(targetProduct.getSceneRasterHeight());

      final MetadataAttribute width = absRoot.getAttribute("num_samples_per_line");
      if (width != null) width.getData().setElemUInt(targetProduct.getSceneRasterWidth());

      final MetadataAttribute offsetX = absRoot.getAttribute("subset_offset_x");
      if (offsetX != null && subsetDef.getRegion() != null)
        offsetX.getData().setElemUInt(subsetDef.getRegion().x);

      final MetadataAttribute offsetY = absRoot.getAttribute("subset_offset_y");
      if (offsetY != null && subsetDef.getRegion() != null)
        offsetY.getData().setElemUInt(subsetDef.getRegion().y);

      final MetadataAttribute slantRange = absRoot.getAttribute("slant_range_to_first_pixel");
      if (slantRange != null) {
        final TiePointGrid srTPG = targetProduct.getTiePointGrid("slant_range_time");
        if (srTPG != null) {
          final double slantRangeTime;
          if (nearRangeOnLeft) {
            slantRangeTime = srTPG.getPixelDouble(0, 0) / 1000000000.0; // ns to s
          } else {
            slantRangeTime =
                srTPG.getPixelDouble(targetProduct.getSceneRasterWidth() - 1, 0)
                    / 1000000000.0; // ns to s
          }
          final double halfLightSpeed = 299792458.0 / 2.0;
          final double slantRangeDist = slantRangeTime * halfLightSpeed;
          slantRange.getData().setElemDouble(slantRangeDist);
        }
      }

      setSubsetSRGRCoefficients(sourceProduct, targetProduct, subsetDef, absRoot, nearRangeOnLeft);
    } catch (Exception e) {
      throw new IOException(e);
    }
  }