示例#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;
  }
示例#2
0
  private static FilterBand createFilterBand(Filter filter, String bandName, int iterationCount) {
    RasterDataNode sourceRaster = (RasterDataNode) VisatApp.getApp().getSelectedProductNode();

    FilterBand targetBand;
    Product product = sourceRaster.getProduct();

    if (filter.getOperation() == Filter.Operation.CONVOLVE) {
      targetBand =
          new ConvolutionFilterBand(bandName, sourceRaster, getKernel(filter), iterationCount);
      if (sourceRaster instanceof Band) {
        ProductUtils.copySpectralBandProperties((Band) sourceRaster, targetBand);
      }
    } else {
      GeneralFilterBand.OpType opType = getOpType(filter.getOperation());
      targetBand =
          new GeneralFilterBand(bandName, sourceRaster, opType, getKernel(filter), iterationCount);
      if (sourceRaster instanceof Band) {
        ProductUtils.copySpectralBandProperties((Band) sourceRaster, targetBand);
      }
    }

    targetBand.setDescription(
        String.format(
            "Filter '%s' (=%s) applied to '%s'",
            filter.getName(), filter.getOperation(), sourceRaster.getName()));
    if (sourceRaster instanceof Band) {
      ProductUtils.copySpectralBandProperties((Band) sourceRaster, targetBand);
    }
    product.addBand(targetBand);
    targetBand.fireProductNodeDataChanged();
    return targetBand;
  }
示例#3
0
  private void createTargetProduct() {

    // construct target product
    targetProduct =
        new Product(
            PRODUCT_NAME,
            sourceProduct.getProductType(),
            sourceProduct.getSceneRasterWidth(),
            sourceProduct.getSceneRasterHeight());

    OperatorUtils.copyProductNodes(sourceProduct, targetProduct);

    for (final Band band : targetProduct.getBands()) {
      targetProduct.removeBand(band);
    }

    for (String key : targetMap.keySet()) {
      String bandName = targetMap.get(key).targetBandName_I;
      targetProduct.addBand(bandName, ProductData.TYPE_FLOAT32);
      targetProduct.getBand(bandName).setUnit(Unit.METERS);
    }

    //        targetProduct.setPreferredTileSize(1,1);

  }
  private void assertCreateRightGeneralFilterBand(Element xmlElement) {
    final Object object = _generalFilterBandPersistable.createObjectFromXml(xmlElement, _product);
    _product.addBand((Band) object);

    assertNotNull(object);
    assertTrue(object instanceof GeneralFilterBand);
    final GeneralFilterBand gfb = (GeneralFilterBand) object;
    assertEquals(1, _product.getBandIndex(gfb.getName()));
    assertEquals(-1, gfb.getSpectralBandIndex());
    assertEquals("filtered_coffee", gfb.getName());
    assertEquals("with milk & sugar", gfb.getDescription());
    assertEquals(_source.getGeophysicalDataType(), gfb.getDataType());
    assertEquals("l", gfb.getUnit());
    assertEquals(0.0, gfb.getSolarFlux(), EPS);
    assertEquals(0.0, gfb.getSpectralWavelength(), EPS);
    assertEquals(0.0, gfb.getSpectralBandwidth(), EPS);
    assertEquals(1.0, gfb.getScalingFactor(), EPS);
    assertEquals(0.0, gfb.getScalingOffset(), EPS);
    assertFalse(gfb.isLog10Scaled());
    assertEquals(gfb.getSource().getName(), _source.getName());
    assertEquals(5, gfb.getSubWindowSize());
    assertEquals(5, gfb.getSubWindowWidth());
    assertEquals(5, gfb.getSubWindowHeight());
    assertTrue(gfb.getOperator() instanceof GeneralFilterBand.Mean);
  }
示例#5
0
 @Override
 public void decode(ProfileReadContext ctx, Product p) throws IOException {
   RasterDigest rasterDigest = ctx.getRasterDigest();
   final Variable[] variables = rasterDigest.getRasterVariables();
   for (Variable variable : variables) {
     final int rasterDataType = DataTypeUtils.getRasterDataType(variable);
     final Band band = p.addBand(variable.getShortName(), rasterDataType);
     CfBandPart.readCfBandAttributes(variable, band);
     band.setSourceImage(new NetcdfMultiLevelImage(band, variable, ctx));
   }
   ScaledVariable[] scaledVariables = rasterDigest.getScaledVariables();
   for (ScaledVariable scaledVariable : scaledVariables) {
     Variable variable = scaledVariable.getVariable();
     final int rasterDataType = DataTypeUtils.getRasterDataType(variable);
     final Band band = p.addBand(variable.getShortName(), rasterDataType);
     CfBandPart.readCfBandAttributes(variable, band);
     band.setSourceImage(new ScaledMultiLevelImage(band, scaledVariable, ctx));
   }
 }
  /**
   * Initializes this operator and sets the one and only target product.
   *
   * <p>The target product can be either defined by a field of type {@link
   * org.esa.beam.framework.datamodel.Product} annotated with the {@link
   * org.esa.beam.framework.gpf.annotations.TargetProduct TargetProduct} annotation or by calling
   * {@link #setTargetProduct} method.
   *
   * <p>The framework calls this method after it has created this operator. Any client code that
   * must be performed before computation of tile data should be placed here.
   *
   * @throws org.esa.beam.framework.gpf.OperatorException If an error occurs during operator
   *     initialisation.
   * @see #getTargetProduct()
   */
  @Override
  public void initialize() throws OperatorException {

    productName = sourceProduct.getName() + "_vgtComp";

    targetProduct =
        new Product(
            productName,
            "VGT_COMP",
            sourceProduct.getSceneRasterWidth(),
            sourceProduct.getSceneRasterHeight());
    // Some target products may require more aid from ProductUtils methods...
    ProductUtils.copyGeoCoding(sourceProduct, targetProduct);

    sourceBandS1_B0 = sourceProduct.getBand(sourceBandNameS1_B0);
    sourceBandS1_B2 = sourceProduct.getBand(sourceBandNameS1_B2);
    sourceBandS1_B3 = sourceProduct.getBand(sourceBandNameS1_B3);
    sourceBandS1_MIR = sourceProduct.getBand(sourceBandNameS1_MIR);
    sourceBandS1_SM = sourceProduct.getBand(sourceBandNameS1_SM);

    sourceBandP_B0 = sourceProduct.getBand(sourceBandNameP_B0);
    sourceBandP_B2 = sourceProduct.getBand(sourceBandNameP_B2);
    sourceBandP_B3 = sourceProduct.getBand(sourceBandNameP_B3);
    sourceBandP_MIR = sourceProduct.getBand(sourceBandNameP_MIR);
    sourceBandP_SM = sourceProduct.getBand(sourceBandNameP_SM);

    sourceBandP_Idepix = sourceProduct.getBand(sourceBandNameP_Idepix);

    targetDifferenceBandB0 =
        targetProduct.addBand(targetDifferenceBandNameB0, ProductData.TYPE_FLOAT32);
    targetDifferenceBandB2 =
        targetProduct.addBand(targetDifferenceBandNameB2, ProductData.TYPE_FLOAT32);
    targetDifferenceBandB3 =
        targetProduct.addBand(targetDifferenceBandNameB3, ProductData.TYPE_FLOAT32);
    targetDifferenceBandMIR =
        targetProduct.addBand(targetDifferenceBandNameMIR, ProductData.TYPE_FLOAT32);

    targetProduct.setPreferredTileSize(
        new Dimension(targetProduct.getSceneRasterWidth(), targetProduct.getSceneRasterHeight()));
  }
  public void testReadAndWrite() {
    final Element xmlElement = createXmlElement(GeneralFilterBandPersistable.VERSION_1_1);

    final Object object = _generalFilterBandPersistable.createObjectFromXml(xmlElement, _product);
    _product.addBand((Band) object);

    final Element xmlFromObject = _generalFilterBandPersistable.createXmlFromObject(object);

    assertNotNull(xmlFromObject);
    final List expChildren = xmlElement.getChildren();
    final List actChildren = xmlFromObject.getChildren();
    assertEquals(expChildren.size(), actChildren.size());
    assertEqualElement(xmlElement, xmlFromObject);
  }
  private void setTargetBands() {
    Band aot550Band =
        targetProduct.addBand(SynergyConstants.OUTPUT_AOT_BAND_NAME, ProductData.TYPE_FLOAT32);
    aot550Band.setNoDataValue(SynergyConstants.OUTPUT_AOT_BAND_NODATAVALUE);
    aot550Band.setNoDataValueUsed(SynergyConstants.OUTPUT_AOT_BAND_NODATAVALUE_USED);
    aot550Band.setUnit("dl");
    Band aot550ErrBand =
        targetProduct.addBand(SynergyConstants.OUTPUT_AOTERR_BAND_NAME, ProductData.TYPE_FLOAT32);
    aot550ErrBand.setNoDataValue(SynergyConstants.OUTPUT_AOT_BAND_NODATAVALUE);
    aot550ErrBand.setNoDataValueUsed(SynergyConstants.OUTPUT_AOT_BAND_NODATAVALUE_USED);
    aot550ErrBand.setUnit("dl");

    if (!computeLand) {
      // write more bands specific for ocean retrieval
      Band angBand =
          targetProduct.addBand(SynergyConstants.OUTPUT_ANG_BAND_NAME, ProductData.TYPE_FLOAT32);
      angBand.setNoDataValue(SynergyConstants.OUTPUT_ANG_BAND_NODATAVALUE);
      angBand.setNoDataValueUsed(SynergyConstants.OUTPUT_ANG_BAND_NODATAVALUE_USED);
      Band angErrBand =
          targetProduct.addBand(SynergyConstants.OUTPUT_ANGERR_BAND_NAME, ProductData.TYPE_FLOAT32);
      angErrBand.setNoDataValue(SynergyConstants.OUTPUT_ANG_BAND_NODATAVALUE);
      angErrBand.setNoDataValueUsed(SynergyConstants.OUTPUT_ANG_BAND_NODATAVALUE_USED);
    }
  }
  public static Product createDummySourceProduct(int width, int height) {
    Product product = new Product("dummy", "dummy", width, height);
    Band b = product.addBand("b1", ProductData.TYPE_FLOAT32);

    float[] bData = new float[width * height];
    for (int i = 0; i < width; i++) {
      for (int j = 0; j < height; j++) {
        bData[i * width + j] = 1.0f;
      }
    }
    b.setDataElems(bData);

    product.setPreferredTileSize(product.getSceneRasterWidth(), 45);

    return product;
  }
示例#10
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;
 }
示例#11
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;
  }
示例#12
0
 protected void addBands(Product product, GCTileFile gcTileFile) {
   final List<BandDescriptor> bandDescriptorList = gcTileFile.getBandDescriptorList();
   for (BandDescriptor descriptor : bandDescriptorList) {
     final Band band =
         new Band(
             descriptor.getName(),
             descriptor.getDataType(),
             product.getSceneRasterWidth(),
             product.getSceneRasterHeight());
     band.setScalingFactor(descriptor.getScaleFactor());
     band.setScalingOffset(descriptor.getOffsetValue());
     band.setDescription(descriptor.getDescription());
     band.setUnit(descriptor.getUnit());
     band.setNoDataValueUsed(descriptor.isFillValueUsed());
     band.setNoDataValue(descriptor.getFillValue());
     product.addBand(band);
     band.setSourceImage(getMultiLevelImage(band));
   }
 }
示例#13
0
  private Product createClostProduct(RenderedOp blueAerosolPanCirrusImage) {

    Product product =
        new Product(
            sourceProduct.getName() + "_clost",
            sourceProduct.getProductType() + " (clost)",
            sourceProduct.getSceneRasterWidth(),
            sourceProduct.getSceneRasterHeight());

    product.setGeoCoding(sourceProduct.getGeoCoding());
    product.setDescription("Product holding Clost Image");

    Band band = product.addBand(CLOST_BAND_NAME, ProductData.TYPE_FLOAT32);
    band.setSourceImage(blueAerosolPanCirrusImage);
    band.setUnit("dl");
    band.setDescription("CLOST Image: aerosol * blue * pan * cirrus ");

    return product;
  }
  /**
   * This method copies all bands which contain a flagcoding from the source product to the target
   * product.
   *
   * @param sourceProduct the source product
   * @param targetProduct the target product
   */
  public static void copyDownscaledFlagBands(
      Product sourceProduct, Product targetProduct, float scalingFactor) {
    Guardian.assertNotNull("source", sourceProduct);
    Guardian.assertNotNull("target", targetProduct);
    if (sourceProduct.getFlagCodingGroup().getNodeCount() > 0) {

      ProductUtils.copyFlagCodings(sourceProduct, targetProduct);
      ProductUtils.copyMasks(sourceProduct, targetProduct);

      // loop over bands and check if they have a flags coding attached
      for (int i = 0; i < sourceProduct.getNumBands(); i++) {
        Band sourceBand = sourceProduct.getBandAt(i);
        FlagCoding coding = sourceBand.getFlagCoding();
        if (coding != null) {
          Band targetBand = AerosolHelpers.downscaleBand(sourceBand, scalingFactor);
          targetBand.setSampleCoding(coding);
          targetProduct.addBand(targetBand);
        }
      }
    }
  }
  /**
   * This method copies the flag bands from the synergy product to the target product
   *
   * @param synergyProduct - the Synergy product
   * @param targetProduct - the target product
   */
  public static void copySynergyFlagBands(Product synergyProduct, Product targetProduct) {
    final Band aatsrConfidFlagNadirBand =
        targetProduct.addBand(SynergyConstants.CONFID_NADIR_FLAGS_AATSR, ProductData.TYPE_INT16);
    final Band aatsrConfidFlagFwardBand =
        targetProduct.addBand(SynergyConstants.CONFID_FWARD_FLAGS_AATSR, ProductData.TYPE_INT16);
    final Band aatsrCloudFlagNadirBand =
        targetProduct.addBand(SynergyConstants.CLOUD_NADIR_FLAGS_AATSR, ProductData.TYPE_INT16);
    final Band aatsrCloudFlagFwardBand =
        targetProduct.addBand(SynergyConstants.CLOUD_FWARD_FLAGS_AATSR, ProductData.TYPE_INT16);
    final Band merisL1FlagsBand =
        targetProduct.addBand(SynergyConstants.L1_FLAGS_MERIS, ProductData.TYPE_INT16);
    final Band merisCloudFlagBand =
        targetProduct.addBand(SynergyConstants.CLOUD_FLAG_MERIS, ProductData.TYPE_INT16);

    final FlagCoding aatsrConfidNadirFlagCoding =
        synergyProduct.getFlagCodingGroup().get(SynergyConstants.CONFID_NADIR_FLAGS_AATSR);
    ProductUtils.copyFlagCoding(aatsrConfidNadirFlagCoding, targetProduct);
    aatsrConfidFlagNadirBand.setSampleCoding(aatsrConfidNadirFlagCoding);

    final FlagCoding aatsrConfidFwardFlagCoding =
        synergyProduct.getFlagCodingGroup().get(SynergyConstants.CONFID_FWARD_FLAGS_AATSR);
    ProductUtils.copyFlagCoding(aatsrConfidFwardFlagCoding, targetProduct);
    aatsrConfidFlagFwardBand.setSampleCoding(aatsrConfidFwardFlagCoding);

    final FlagCoding aatsrCloudNadirFlagCoding =
        synergyProduct.getFlagCodingGroup().get(SynergyConstants.CLOUD_NADIR_FLAGS_AATSR);
    ProductUtils.copyFlagCoding(aatsrCloudNadirFlagCoding, targetProduct);
    aatsrCloudFlagNadirBand.setSampleCoding(aatsrCloudNadirFlagCoding);

    final FlagCoding aatsrCloudFwardFlagCoding =
        synergyProduct.getFlagCodingGroup().get(SynergyConstants.CLOUD_FWARD_FLAGS_AATSR);
    ProductUtils.copyFlagCoding(aatsrCloudFwardFlagCoding, targetProduct);
    aatsrCloudFlagFwardBand.setSampleCoding(aatsrCloudFwardFlagCoding);

    final FlagCoding merisL1FlagsCoding =
        synergyProduct.getFlagCodingGroup().get(SynergyConstants.L1_FLAGS_MERIS);
    ProductUtils.copyFlagCoding(merisL1FlagsCoding, targetProduct);
    merisL1FlagsBand.setSampleCoding(merisL1FlagsCoding);

    final FlagCoding merisCloudFlagCoding =
        synergyProduct.getFlagCodingGroup().get(SynergyConstants.CLOUD_FLAG_MERIS);
    ProductUtils.copyFlagCoding(merisCloudFlagCoding, targetProduct);
    merisCloudFlagBand.setSampleCoding(merisCloudFlagCoding);
  }
示例#16
0
  /**
   * Adds requested bands to the output product.
   *
   * @param description a description template for the new bands to be created
   * @param bConvertMerisName it set to true, the MERIS l1b band name is converted from
   *     <i>radiance_n</i> to <i>reflectance_n</i>
   */
  private void addBandsToOutput(String description, boolean bConvertMerisName) {

    for (Band inBand : _inputBandList) {
      String newBandName;
      String bandUnit;
      if (bConvertMerisName) {
        newBandName = convertMerisBandName(inBand);
        bandUnit = "dl";
      } else {
        newBandName = inBand.getName();
        bandUnit = inBand.getUnit();
      }
      Band outBand =
          new Band(
              newBandName,
              inBand.getGeophysicalDataType(),
              inBand.getSceneRasterWidth(),
              inBand.getSceneRasterHeight());
      outBand.setUnit(bandUnit);
      ProductUtils.copySpectralBandProperties(inBand, outBand);
      outBand.setDescription(description + inBand.getName());
      _outputProduct.addBand(outBand);
    }
  }
 @Override
 public void setUp() throws Exception {
   _generalFilterBandPersistable = new GeneralFilterBandPersistable();
   _product = new Product("p", "doesntMatter", 2, 2);
   _source = _product.addBand("anyBand", ProductData.TYPE_UINT16);
 }
  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;
  }
  public void testCreateXmlFromObject() {
    final GeneralFilterBand gfb =
        new GeneralFilterBand("filteredBand", _source, 2, GeneralFilterBand.MAX);
    gfb.setDescription("somehow explainig");
    gfb.setUnit("someUnit");
    _product.addBand(gfb);

    final Element xmlElement = _generalFilterBandPersistable.createXmlFromObject(gfb);

    assertNotNull(xmlElement);
    assertEquals(DimapProductConstants.TAG_SPECTRAL_BAND_INFO, xmlElement.getName());
    assertEquals(14, xmlElement.getChildren().size());
    assertTrue(xmlElement.getChild(DimapProductConstants.TAG_BAND_INDEX) != null);
    assertEquals(
        gfb.getProduct().getBandIndex(gfb.getName()),
        Integer.parseInt(xmlElement.getChildTextTrim(DimapProductConstants.TAG_BAND_INDEX)));
    assertTrue(xmlElement.getChild(DimapProductConstants.TAG_BAND_NAME) != null);
    assertEquals(gfb.getName(), xmlElement.getChildTextTrim(DimapProductConstants.TAG_BAND_NAME));
    assertTrue(xmlElement.getChild(DimapProductConstants.TAG_BAND_DESCRIPTION) != null);
    assertEquals(
        gfb.getDescription(),
        xmlElement.getChildTextTrim(DimapProductConstants.TAG_BAND_DESCRIPTION));
    assertTrue(xmlElement.getChild(DimapProductConstants.TAG_DATA_TYPE) != null);
    assertEquals(
        ProductData.getTypeString(gfb.getDataType()),
        xmlElement.getChildTextTrim(DimapProductConstants.TAG_DATA_TYPE));
    assertTrue(xmlElement.getChild(DimapProductConstants.TAG_PHYSICAL_UNIT) != null);
    assertEquals(
        gfb.getUnit(), xmlElement.getChildTextTrim(DimapProductConstants.TAG_PHYSICAL_UNIT));
    assertTrue(xmlElement.getChild(DimapProductConstants.TAG_SOLAR_FLUX) != null);
    assertEquals(
        gfb.getSolarFlux(),
        Float.parseFloat(xmlElement.getChildTextTrim(DimapProductConstants.TAG_SOLAR_FLUX)),
        EPS);
    assertTrue(xmlElement.getChild(DimapProductConstants.TAG_BAND_WAVELEN) != null);
    assertEquals(
        gfb.getSpectralWavelength(),
        Float.parseFloat(xmlElement.getChildTextTrim(DimapProductConstants.TAG_BAND_WAVELEN)),
        EPS);
    assertTrue(xmlElement.getChild(DimapProductConstants.TAG_BANDWIDTH) != null);
    assertEquals(
        gfb.getSpectralBandwidth(),
        Float.parseFloat(xmlElement.getChildTextTrim(DimapProductConstants.TAG_BANDWIDTH)),
        EPS);
    assertTrue(xmlElement.getChild(DimapProductConstants.TAG_SCALING_FACTOR) != null);
    assertEquals(
        gfb.getScalingFactor(),
        Double.parseDouble(xmlElement.getChildTextTrim(DimapProductConstants.TAG_SCALING_FACTOR)),
        EPS);
    assertTrue(xmlElement.getChild(DimapProductConstants.TAG_SCALING_OFFSET) != null);
    assertEquals(
        gfb.getScalingOffset(),
        Double.parseDouble(xmlElement.getChildTextTrim(DimapProductConstants.TAG_SCALING_OFFSET)),
        EPS);
    assertTrue(xmlElement.getChild(DimapProductConstants.TAG_SCALING_LOG_10) != null);
    assertEquals(
        gfb.isLog10Scaled(),
        Boolean.parseBoolean(
            xmlElement.getChildTextTrim(DimapProductConstants.TAG_SCALING_LOG_10)));
    assertTrue(xmlElement.getChild(DimapProductConstants.TAG_NO_DATA_VALUE_USED) != null);
    assertEquals(
        gfb.isNoDataValueUsed(),
        Boolean.parseBoolean(
            xmlElement.getChildTextTrim(DimapProductConstants.TAG_NO_DATA_VALUE_USED)));
    assertTrue(xmlElement.getChild(DimapProductConstants.TAG_NO_DATA_VALUE) != null);
    assertEquals(
        gfb.getNoDataValue(),
        Double.parseDouble(xmlElement.getChildTextTrim(DimapProductConstants.TAG_NO_DATA_VALUE)),
        EPS);

    final Element filterInfo = xmlElement.getChild(DimapProductConstants.TAG_FILTER_BAND_INFO);
    assertNotNull(filterInfo);
    assertEquals(
        GeneralFilterBandPersistable.GENERAL_FILTER_BAND_TYPE,
        filterInfo.getAttributeValue(GeneralFilterBandPersistable.ATTRIBUTE_BAND_TYPE));
    assertEquals(
        GeneralFilterBandPersistable.VERSION_1_1,
        filterInfo.getAttributeValue(GeneralFilterBandPersistable.ATTRIBUTE_VERSION));
    assertEquals(3, filterInfo.getChildren().size());
    assertTrue(filterInfo.getChild(DimapProductConstants.TAG_FILTER_SOURCE) != null);
    assertEquals(
        gfb.getSource().getName(),
        filterInfo.getChildTextTrim(DimapProductConstants.TAG_FILTER_SOURCE));
    assertTrue(filterInfo.getChild(DimapProductConstants.TAG_FILTER_SUB_WINDOW_SIZE) != null);
    assertEquals(
        gfb.getSubWindowSize(),
        Integer.parseInt(
            filterInfo.getChildTextTrim(DimapProductConstants.TAG_FILTER_SUB_WINDOW_SIZE)));
    assertTrue(filterInfo.getChild(DimapProductConstants.TAG_FILTER_OPERATOR_CLASS_NAME) != null);
    assertEquals(
        gfb.getOperator().getClass().getName(),
        filterInfo.getChildTextTrim(DimapProductConstants.TAG_FILTER_OPERATOR_CLASS_NAME));
  }
  @Override
  protected Product readProductNodesImpl() throws IOException {
    final String s = getInput().toString();

    final File file0 = new File(s);
    final File dir = file0.getParentFile();

    final S2FilenameInfo fni0 = S2FilenameInfo.create(file0.getName());
    if (fni0 == null) {
      throw new IOException();
    }
    Header metadataHeader = null;
    final Map<Integer, BandInfo> fileMap = new HashMap<Integer, BandInfo>();
    if (dir != null) {
      File[] files =
          dir.listFiles(
              new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                  return name.endsWith(Sentinel2ProductReaderPlugIn.JP2_EXT);
                }
              });
      if (files != null) {
        for (File file : files) {
          int bandIndex = fni0.getBand(file.getName());
          if (bandIndex >= 0 && bandIndex < WAVEBAND_INFOS.length) {
            final S2WavebandInfo wavebandInfo = WAVEBAND_INFOS[bandIndex];
            BandInfo bandInfo =
                new BandInfo(
                    file, bandIndex, wavebandInfo, imageLayouts[wavebandInfo.resolution.id]);
            fileMap.put(bandIndex, bandInfo);
          }
        }
      }
      File[] metadataFiles =
          dir.listFiles(
              new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                  return name.startsWith("MTD_") && name.endsWith(".xml");
                }
              });
      if (metadataFiles != null && metadataFiles.length > 0) {
        File metadataFile = metadataFiles[0];
        try {
          metadataHeader = Header.parseHeader(metadataFile);
        } catch (JDOMException e) {
          BeamLogManager.getSystemLogger()
              .warning("Failed to parse metadata file: " + metadataFile);
        }
      } else {
        BeamLogManager.getSystemLogger().warning("No metadata file found");
      }
    }

    final ArrayList<Integer> bandIndexes = new ArrayList<Integer>(fileMap.keySet());
    Collections.sort(bandIndexes);

    if (bandIndexes.isEmpty()) {
      throw new IOException("No valid bands found.");
    }

    String prodType = "S2_MSI_" + fni0.procLevel;
    final Product product =
        new Product(
            String.format("%s_%s_%s", prodType, fni0.orbitNo, fni0.tileId),
            prodType,
            imageLayouts[S2Resolution.R10M.id].width,
            imageLayouts[S2Resolution.R10M.id].height);

    try {
      product.setStartTime(ProductData.UTC.parse(fni0.start, "yyyyMMddHHmmss"));
    } catch (ParseException e) {
      // warn
    }

    try {
      product.setEndTime(ProductData.UTC.parse(fni0.stop, "yyyyMMddHHmmss"));
    } catch (ParseException e) {
      // warn
    }

    if (metadataHeader != null) {
      SceneDescription sceneDescription = SceneDescription.create(metadataHeader);
      int tileIndex = sceneDescription.getTileIndex(fni0.tileId);
      Envelope2D tileEnvelope = sceneDescription.getTileEnvelope(tileIndex);
      Header.Tile tile = metadataHeader.getTileList().get(tileIndex);

      try {
        product.setGeoCoding(
            new CrsGeoCoding(
                tileEnvelope.getCoordinateReferenceSystem(),
                imageLayouts[S2Resolution.R10M.id].width,
                imageLayouts[S2Resolution.R10M.id].height,
                tile.tileGeometry10M.upperLeftX,
                tile.tileGeometry10M.upperLeftY,
                tile.tileGeometry10M.xDim,
                -tile.tileGeometry10M.yDim,
                0.0,
                0.0));
      } catch (FactoryException e) {
        // todo - handle e
      } catch (TransformException e) {
        // todo - handle e
      }
    }

    for (Integer bandIndex : bandIndexes) {
      final BandInfo bandInfo = fileMap.get(bandIndex);
      final Band band = product.addBand(bandInfo.wavebandInfo.bandName, ProductData.TYPE_UINT16);
      band.setSpectralWavelength((float) bandInfo.wavebandInfo.centralWavelength);
      band.setSpectralBandwidth((float) bandInfo.wavebandInfo.bandWidth);
      band.setSpectralBandIndex(bandIndex);
      band.setSourceImage(new DefaultMultiLevelImage(new Jp2MultiLevelSource(bandInfo)));
    }

    product.setNumResolutionLevels(imageLayouts[0].numResolutions);

    return product;
  }
  public static void addAerosolFlagBand(Product targetProduct, int rasterWidth, int rasterHeight) {
    FlagCoding aerosolFlagCoding = new FlagCoding(SynergyConstants.aerosolFlagCodingName);
    aerosolFlagCoding.addFlag(
        SynergyConstants.flagCloudyName,
        SynergyConstants.cloudyMask,
        SynergyConstants.flagCloudyDesc);
    aerosolFlagCoding.addFlag(
        SynergyConstants.flagOceanName, SynergyConstants.oceanMask, SynergyConstants.flagOceanDesc);
    aerosolFlagCoding.addFlag(
        SynergyConstants.flagSuccessName,
        SynergyConstants.successMask,
        SynergyConstants.flagSuccessDesc);
    aerosolFlagCoding.addFlag(
        SynergyConstants.flagBorderName,
        SynergyConstants.borderMask,
        SynergyConstants.flagBorderDesc);
    aerosolFlagCoding.addFlag(
        SynergyConstants.flagFilledName,
        SynergyConstants.filledMask,
        SynergyConstants.flagFilledDesc);
    aerosolFlagCoding.addFlag(
        SynergyConstants.flagNegMetricName,
        SynergyConstants.negMetricMask,
        SynergyConstants.flagNegMetricDesc);
    aerosolFlagCoding.addFlag(
        SynergyConstants.flagAotLowName,
        SynergyConstants.aotLowMask,
        SynergyConstants.flagAotLowDesc);
    aerosolFlagCoding.addFlag(
        SynergyConstants.flagErrHighName,
        SynergyConstants.errHighMask,
        SynergyConstants.flagErrHighDesc);
    aerosolFlagCoding.addFlag(
        SynergyConstants.flagCoastName, SynergyConstants.coastMask, SynergyConstants.flagCoastDesc);
    targetProduct.getFlagCodingGroup().add(aerosolFlagCoding);
    ProductNodeGroup<Mask> maskGroup = targetProduct.getMaskGroup();
    maskGroup.add(
        Mask.BandMathsType.create(
            SynergyConstants.flagCloudyName,
            SynergyConstants.flagCloudyDesc,
            rasterWidth,
            rasterHeight,
            SynergyConstants.aerosolFlagCodingName + "." + SynergyConstants.flagCloudyName,
            Color.lightGray,
            0.2f));
    maskGroup.add(
        Mask.BandMathsType.create(
            SynergyConstants.flagOceanName,
            SynergyConstants.flagOceanDesc,
            rasterWidth,
            rasterHeight,
            SynergyConstants.aerosolFlagCodingName + "." + SynergyConstants.flagOceanName,
            Color.blue,
            0.2f));
    maskGroup.add(
        Mask.BandMathsType.create(
            SynergyConstants.flagSuccessName,
            SynergyConstants.flagSuccessDesc,
            rasterWidth,
            rasterHeight,
            SynergyConstants.aerosolFlagCodingName + "." + SynergyConstants.flagSuccessName,
            Color.pink,
            0.2f));
    maskGroup.add(
        Mask.BandMathsType.create(
            SynergyConstants.flagBorderName,
            SynergyConstants.flagBorderDesc,
            rasterWidth,
            rasterHeight,
            SynergyConstants.aerosolFlagCodingName + "." + SynergyConstants.flagBorderName,
            Color.orange,
            0.2f));
    maskGroup.add(
        Mask.BandMathsType.create(
            SynergyConstants.flagFilledName,
            SynergyConstants.flagFilledDesc,
            rasterWidth,
            rasterHeight,
            SynergyConstants.aerosolFlagCodingName + "." + SynergyConstants.flagFilledName,
            Color.magenta,
            0.2f));
    maskGroup.add(
        Mask.BandMathsType.create(
            SynergyConstants.flagNegMetricName,
            SynergyConstants.flagNegMetricDesc,
            rasterWidth,
            rasterHeight,
            SynergyConstants.aerosolFlagCodingName + "." + SynergyConstants.flagNegMetricName,
            Color.magenta,
            0.2f));
    maskGroup.add(
        Mask.BandMathsType.create(
            SynergyConstants.flagAotLowName,
            SynergyConstants.flagAotLowDesc,
            rasterWidth,
            rasterHeight,
            SynergyConstants.aerosolFlagCodingName + "." + SynergyConstants.flagAotLowName,
            Color.magenta,
            0.2f));
    maskGroup.add(
        Mask.BandMathsType.create(
            SynergyConstants.flagErrHighName,
            SynergyConstants.flagErrHighDesc,
            rasterWidth,
            rasterHeight,
            SynergyConstants.aerosolFlagCodingName + "." + SynergyConstants.flagErrHighName,
            Color.magenta,
            0.2f));
    maskGroup.add(
        Mask.BandMathsType.create(
            SynergyConstants.flagCoastName,
            SynergyConstants.flagCoastDesc,
            rasterWidth,
            rasterHeight,
            SynergyConstants.aerosolFlagCodingName + "." + SynergyConstants.flagCoastName,
            Color.magenta,
            0.2f));

    Band targetBand =
        new Band(
            SynergyConstants.aerosolFlagCodingName,
            ProductData.TYPE_UINT16,
            rasterWidth,
            rasterHeight);
    targetBand.setDescription(SynergyConstants.aerosolFlagCodingDesc);
    targetBand.setSampleCoding(aerosolFlagCoding);
    targetProduct.addBand(targetBand);
  }
示例#22
0
  @Override
  public void initialize() throws OperatorException {
    if (computeErrorBands) {
      deactivateComputeTileMethod();
    }

    if (endmemberFile != null) {
      loadEndmemberFile();
    }

    if (sourceBandNames == null || sourceBandNames.length == 0) {
      Band[] bands = sourceProduct.getBands();
      ArrayList<String> bandNameList = new ArrayList<String>();
      for (Band band : bands) {
        if (band.getSpectralWavelength() > 0) {
          bandNameList.add(band.getName());
        }
      }
      sourceBandNames = bandNameList.toArray(new String[bandNameList.size()]);
    }

    validateParameters();

    sourceBands = new Band[sourceBandNames.length];
    for (int i = 0; i < sourceBandNames.length; i++) {
      String sourceBandName = sourceBandNames[i];
      Band sourceBand = sourceProduct.getBand(sourceBandName);
      if (sourceBand == null) {
        throw new OperatorException("Source band not found: " + sourceBandName);
      }
      if (sourceBand.getSpectralWavelength() <= 0) {
        throw new OperatorException("Source band without spectral wavelength: " + sourceBandName);
      }
      sourceBands[i] = sourceBand;
    }

    int numSourceBands = sourceBands.length;
    int numEndmembers = endmembers.length;

    if (numSourceBands < numEndmembers) {
      throw new OperatorException("Number of source bands must be >= number of endmembers.");
    }

    double[][] lsuMatrixElements = new double[numSourceBands][numEndmembers];
    for (int j = 0; j < numEndmembers; j++) {
      Endmember endmember = endmembers[j];
      double[] wavelengths = endmember.getWavelengths();
      double[] radiations = endmember.getRadiations();
      for (int i = 0; i < numSourceBands; i++) {
        Band sourceBand = sourceBands[i];
        float wavelength = sourceBand.getSpectralWavelength();
        float bandwidth = sourceBand.getSpectralBandwidth();
        int k =
            findEndmemberSpectralIndex(wavelengths, wavelength, Math.max(bandwidth, minBandwidth));
        if (k == -1) {
          throw new OperatorException(
              String.format(
                  "Band %s: No matching endmember wavelength found (%f nm)",
                  sourceBand.getName(), wavelength));
        }
        lsuMatrixElements[i][j] = radiations[k];
      }
    }

    if (UC_LSU.equals(unmixingModelName)) {
      spectralUnmixing = new UnconstrainedLSU(lsuMatrixElements);
    } else if (C_LSU.equals(unmixingModelName)) {
      spectralUnmixing = new ConstrainedLSU(lsuMatrixElements);
    } else if (FC_LSU.equals(unmixingModelName)) {
      spectralUnmixing = new FullyConstrainedLSU(lsuMatrixElements);
    } else if (unmixingModelName == null) {
      spectralUnmixing = new UnconstrainedLSU(lsuMatrixElements);
    }

    int width = sourceProduct.getSceneRasterWidth();
    int height = sourceProduct.getSceneRasterHeight();

    targetProduct =
        new Product(sourceProduct.getName() + "_unmixed", "SpectralUnmixing", width, height);

    abundanceBands = new Band[numEndmembers];
    for (int i = 0; i < numEndmembers; i++) {
      abundanceBands[i] =
          targetProduct.addBand(
              endmembers[i].getName() + abundanceBandNameSuffix, ProductData.TYPE_FLOAT32);
    }

    if (computeErrorBands) {
      errorBands = new Band[numSourceBands];
      for (int i = 0; i < errorBands.length; i++) {
        final String erroBandName = sourceBands[i].getName() + errorBandNameSuffix;
        errorBands[i] = targetProduct.addBand(erroBandName, ProductData.TYPE_FLOAT32);
        ProductUtils.copySpectralBandProperties(sourceBands[i], errorBands[i]);
      }
      summaryErrorBand = targetProduct.addBand("summary_error", ProductData.TYPE_FLOAT32);
      summaryErrorBand.setDescription("Root mean square error");
    }

    ProductUtils.copyMetadata(sourceProduct, targetProduct);
    ProductUtils.copyTiePointGrids(sourceProduct, targetProduct);
    ProductUtils.copyGeoCoding(sourceProduct, targetProduct);
  }
示例#23
0
  protected void addBandsToProduct(Product product) {
    Debug.assertNotNull(getSourceProduct());
    Debug.assertNotNull(product);
    for (int i = 0; i < getSourceProduct().getNumBands(); i++) {
      Band sourceBand = getSourceProduct().getBandAt(i);
      String bandName = sourceBand.getName();
      if (isNodeAccepted(bandName)) {
        Band destBand;
        boolean treatVirtualBandsAsRealBands = false;
        if (getSubsetDef() != null && getSubsetDef().getTreatVirtualBandsAsRealBands()) {
          treatVirtualBandsAsRealBands = true;
        }

        // @todo 1 se/se - extract copy of a band or virtual band to create deep clone of band and
        // virtual band
        if (!treatVirtualBandsAsRealBands && sourceBand instanceof VirtualBand) {
          VirtualBand virtualSource = (VirtualBand) sourceBand;
          destBand =
              new VirtualBand(
                  bandName,
                  sourceBand.getDataType(),
                  getSceneRasterWidth(),
                  getSceneRasterHeight(),
                  virtualSource.getExpression());
        } else {
          destBand =
              new Band(
                  bandName,
                  sourceBand.getDataType(),
                  getSceneRasterWidth(),
                  getSceneRasterHeight());
        }
        if (sourceBand.getUnit() != null) {
          destBand.setUnit(sourceBand.getUnit());
        }
        if (sourceBand.getDescription() != null) {
          destBand.setDescription(sourceBand.getDescription());
        }
        destBand.setScalingFactor(sourceBand.getScalingFactor());
        destBand.setScalingOffset(sourceBand.getScalingOffset());
        destBand.setLog10Scaled(sourceBand.isLog10Scaled());
        destBand.setSpectralBandIndex(sourceBand.getSpectralBandIndex());
        destBand.setSpectralWavelength(sourceBand.getSpectralWavelength());
        destBand.setSpectralBandwidth(sourceBand.getSpectralBandwidth());
        destBand.setSolarFlux(sourceBand.getSolarFlux());
        if (sourceBand.isNoDataValueSet()) {
          destBand.setNoDataValue(sourceBand.getNoDataValue());
        }
        destBand.setNoDataValueUsed(sourceBand.isNoDataValueUsed());
        destBand.setValidPixelExpression(sourceBand.getValidPixelExpression());
        FlagCoding sourceFlagCoding = sourceBand.getFlagCoding();
        IndexCoding sourceIndexCoding = sourceBand.getIndexCoding();
        if (sourceFlagCoding != null) {
          String flagCodingName = sourceFlagCoding.getName();
          FlagCoding destFlagCoding = product.getFlagCodingGroup().get(flagCodingName);
          Debug.assertNotNull(
              destFlagCoding); // should not happen because flag codings should be already in
                               // product
          destBand.setSampleCoding(destFlagCoding);
        } else if (sourceIndexCoding != null) {
          String indexCodingName = sourceIndexCoding.getName();
          IndexCoding destIndexCoding = product.getIndexCodingGroup().get(indexCodingName);
          Debug.assertNotNull(
              destIndexCoding); // should not happen because index codings should be already in
                                // product
          destBand.setSampleCoding(destIndexCoding);
        } else {
          destBand.setSampleCoding(null);
        }
        if (isFullScene(getSubsetDef()) && sourceBand.isStxSet()) {
          copyStx(sourceBand, destBand);
        }
        product.addBand(destBand);
        bandMap.put(destBand, sourceBand);
      }
    }
    for (final Map.Entry<Band, RasterDataNode> entry : bandMap.entrySet()) {
      copyImageInfo(entry.getValue(), entry.getKey());
    }
  }
  @Override
  public void initialize() throws OperatorException {
    if (category == DataCategory.NDVI_MAXCOMPOSIT_NEW) {
      Arrays.sort(sourceProducts, new ProductNameComparator());
      sortedDataSourceProducts = sourceProducts;
    } else {
      final String sourceDataProductFilter = "_data";
      final String sourceFlagProductFilter = "_flag";
      sortedDataSourceProducts =
          DiversityAuxdataUtils.sortProductsByMonth(sourceProducts, sourceDataProductFilter, 2, 7);
      sortedFlagSourceProducts =
          DiversityAuxdataUtils.sortProductsByMonth(sourceProducts, sourceFlagProductFilter, 2, 7);
    }

    final Product yearlyNdviProduct = createYearlyProduct();

    if (writeFlags) {
      final FlagCoding ndviFlagCoding = DiversityAuxdataUtils.createNdviFlagCoding();
      yearlyNdviProduct.getFlagCodingGroup().add(ndviFlagCoding);
      TARGET_BAND_PREFIX += "flag_";
      DiversityAuxdataUtils.addPatternToAutoGrouping(yearlyNdviProduct, "ndvi_max_flag");
    } else {
      DiversityAuxdataUtils.addPatternToAutoGrouping(yearlyNdviProduct, "ndvi_max");
    }

    halfmonthlyDataProductsMap = new HashMap<String, List<Product>>();
    halfmonthlyFlagProductsMap = new HashMap<String, List<Product>>();

    for (int i = 0; i < Constants.MONTHS.length; i++) {
      final String month = Constants.MONTHS[i];
      List<Product> thisMonthDataProducts = new ArrayList<Product>();
      List<Product> thisMonthFlagProducts = new ArrayList<Product>();
      for (Product product : sortedDataSourceProducts) {
        if (category == DataCategory.NDVI_MAXCOMPOSIT_NEW) {
          if (product.getName().contains(String.format("_%02d_", i + 1))) {
            thisMonthDataProducts.add(product);
          }
        } else {
          if (product.getName().contains(month)) {
            thisMonthDataProducts.add(product);
          }
        }
      }
      if (category == DataCategory.NDVI_MAXCOMPOSIT) {
        for (Product product : sortedFlagSourceProducts) {
          if (product.getName().contains(month)) {
            thisMonthFlagProducts.add(product);
          }
        }
      }
      if (thisMonthDataProducts.size() == 2
          && (thisMonthFlagProducts.size() == 2 || category == DataCategory.NDVI_MAXCOMPOSIT_NEW)) {
        // the normal case
        halfmonthlyDataProductsMap.put(month, thisMonthDataProducts);
        halfmonthlyFlagProductsMap.put(month, thisMonthFlagProducts);

        Band targetBand =
            new Band(TARGET_BAND_PREFIX + month, ProductData.TYPE_FLOAT32, width, height);
        targetBand.setNoDataValue(Constants.NDVI_INVALID_VALUE);
        targetBand.setNoDataValueUsed(true);
        yearlyNdviProduct.addBand(targetBand);
      } else {
        System.err.println(
            "Warning: NDVI products for '" + month + "' missing or incomplete - skipping.");
      }
    }

    setTargetProduct(yearlyNdviProduct);
  }