Ejemplo n.º 1
0
 @Override
 public boolean accept(Product sourceProduct) {
   final ProductData.UTC productStartTime = sourceProduct.getStartTime();
   final ProductData.UTC productEndTime = sourceProduct.getEndTime();
   final boolean hasStartTime = productStartTime != null;
   final boolean hasEndTime = productEndTime != null;
   final GeoCoding geoCoding = sourceProduct.getGeoCoding();
   if (geoCoding == null || !geoCoding.canGetGeoPos()) {
     return false;
   } else if (startTime != null
       && hasStartTime
       && productStartTime.getAsDate().after(startTime.getAsDate())
       && endTime != null
       && hasEndTime
       && productEndTime.getAsDate().before(endTime.getAsDate())) {
     return true;
   } else if (!hasStartTime && !hasEndTime) {
     return true;
   } else if (startTime != null
       && hasStartTime
       && productStartTime.getAsDate().after(startTime.getAsDate())
       && !hasEndTime) {
     return true;
   } else if (!hasStartTime
       && endTime != null
       && productEndTime.getAsDate().before(endTime.getAsDate())) {
     return true;
   } else {
     return false;
   }
 }
Ejemplo n.º 2
0
 private void setSceneRasterStartAndStopTime(Product product) {
   final Product sourceProduct = getSourceProduct();
   final ProductData.UTC startTime = sourceProduct.getStartTime();
   final ProductData.UTC stopTime = sourceProduct.getEndTime();
   final ProductSubsetDef subsetDef = getSubsetDef();
   if (startTime != null
       && stopTime != null
       && subsetDef != null
       && subsetDef.getRegion() != null) {
     final double height = sourceProduct.getSceneRasterHeight();
     final Rectangle region = subsetDef.getRegion();
     final double regionY = region.getY();
     final double regionHeight = region.getHeight();
     final double dStart = startTime.getMJD();
     final double dStop = stopTime.getMJD();
     final double vPerLine = (dStop - dStart) / (height - 1);
     final double newStart = vPerLine * regionY + dStart;
     final double newStop = vPerLine * (regionHeight - 1) + newStart;
     product.setStartTime(new ProductData.UTC(newStart));
     product.setEndTime(new ProductData.UTC(newStop));
   } else {
     product.setStartTime(startTime);
     product.setEndTime(stopTime);
   }
 }
Ejemplo n.º 3
0
 private static Product createProduct() throws Exception {
   Product product = new Product("p", "t", 32, 256);
   final TiePointGrid lat =
       new TiePointGrid("lat", 2, 2, 0f, 0f, 32f, 256f, new float[] {+40f, +40f, -40f, -40f});
   final TiePointGrid lon =
       new TiePointGrid("lon", 2, 2, 0f, 0f, 32f, 256f, new float[] {-80f, +80f, -80f, +80f});
   product.addTiePointGrid(lat);
   product.addTiePointGrid(lon);
   product.setGeoCoding(new TiePointGeoCoding(lat, lon));
   product.setPreferredTileSize(32, 16);
   product.setStartTime(ProductData.UTC.parse("2003-01-01", "yyyy-MM-dd"));
   product.setEndTime(ProductData.UTC.parse("2003-01-02", "yyyy-MM-dd"));
   return product;
 }
Ejemplo n.º 4
0
  /**
   * Returns the UTC for a global time attribute.
   *
   * @param product the product.
   * @param timeAttrName the name of the time attribute.
   * @return the attribute value as UTC or {@code null} if the attribute vallue cannot be parsed.
   * @see MetadataAttribute
   * @see ProductData.UTC
   */
  public static ProductData.UTC getTimeAttrValue(final Product product, final String timeAttrName) {
    final MetadataElement pa = product.getMetadataRoot().getElement(GLOBAL_ATTRIBUTES);
    if (pa == null) {
      return null;
    }
    final MetadataAttribute timeAttr = pa.getAttribute(timeAttrName);
    if (timeAttr == null) {
      return null;
    }
    final ProductData timeAttrData = timeAttr.getData();
    if (timeAttrData == null) {
      return null;
    }

    final String timeString = timeAttrData.getElemString();
    if ("".equals(timeString.trim())) {
      return null;
    }

    ProductData.UTC utc = null;
    for (final String pattern : DATE_TIME_PATTERNS) {
      try {
        utc = ProductData.UTC.parse(timeString, pattern);
        break; // utc is never null here
      } catch (ParseException ignored) {
        // ignore
      } catch (IllegalArgumentException ignored) {
        // ignore
      }
    }

    return utc;
  }
Ejemplo n.º 5
0
 @Override
 public ProductData.UTC parse(String text) throws ConversionException {
   try {
     return ProductData.UTC.parse(text, Constants.TIME_PATTERN);
   } catch (java.text.ParseException e) {
     throw new ConversionException(e);
   }
 }
Ejemplo n.º 6
0
  public void readOrbitData() throws IOException {

    if (_productFile instanceof DorisOrbitProductFile) {

      final DorisOrbitProductFile dorisProdFile = (DorisOrbitProductFile) _productFile;
      final Record orbitRecord = dorisProdFile.readOrbitData();

      OrbitVector orb = null;
      final SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss.SSSSSS");
      final ArrayList<OrbitVector> orbitVectorList = new ArrayList<OrbitVector>();

      final int numFields = orbitRecord.getNumFields();
      for (int i = 0; i < numFields; ++i) {

        final Field f = orbitRecord.getFieldAt(i);

        final String fieldName = f.getName();
        if (fieldName.contains("blank")) {
          continue;
        } else if (fieldName.contains("utc_time")) {
          orb = new OrbitVector();
          try {
            orb.utcTime = ProductData.UTC.parse(f.getData().getElemString()).getMJD();
          } catch (ParseException e) {
            throw new IllegalFileFormatException("Failed to parse UTC time " + e.getMessage());
          }
        } else if (fieldName.contains("delta_ut1")) {
          if (orb != null) orb.delta_ut1 = Double.parseDouble(f.getData().getElemString());
        } else if (fieldName.contains("abs_orbit")) {
          if (orb != null)
            orb.absOrbit = Integer.parseInt(f.getData().getElemString().replace("+", ""));
        } else if (fieldName.contains("x_pos")) {
          if (orb != null) orb.xPos = Double.parseDouble(f.getData().getElemString());
        } else if (fieldName.contains("y_pos")) {
          if (orb != null) orb.yPos = Double.parseDouble(f.getData().getElemString());
        } else if (fieldName.contains("z_pos")) {
          if (orb != null) orb.zPos = Double.parseDouble(f.getData().getElemString());
        } else if (fieldName.contains("x_vel")) {
          if (orb != null) orb.xVel = Double.parseDouble(f.getData().getElemString());
        } else if (fieldName.contains("y_vel")) {
          if (orb != null) orb.yVel = Double.parseDouble(f.getData().getElemString());
        } else if (fieldName.contains("z_vel")) {
          if (orb != null) orb.zVel = Double.parseDouble(f.getData().getElemString());
        } else if (fieldName.contains("qual_flags")) {
          if (orb != null) orb.qualFlags = f.getData().getElemString();
          orbitVectorList.add(orb);
        }
      }

      dataRecords = orbitVectorList.toArray(new OrbitVector[orbitVectorList.size()]);

      recordTimes = new double[dataRecords.length];
      for (int i = 0; i < dataRecords.length; i++) {
        recordTimes[i] = dataRecords[i].utcTime;
      }
    }
  }
Ejemplo n.º 7
0
  private ProductData.UTC getUTCAttribute(String key, List<Attribute> globalAttributes) {
    Attribute attribute = findAttribute(key, globalAttributes);
    Boolean isModis = false;
    try {
      isModis = findAttribute("MODIS_Resolution", globalAttributes).isString();
    } catch (Exception ignored) {
    }

    if (attribute != null) {
      String timeString = attribute.getStringValue().trim();
      final DateFormat dateFormat = ProductData.UTC.createDateFormat("yyyyDDDHHmmssSSS");
      final DateFormat dateFormatModis =
          ProductData.UTC.createDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
      final DateFormat dateFormatOcts =
          ProductData.UTC.createDateFormat("yyyyMMdd HH:mm:ss.SSSSSS");
      try {
        if (isModis) {
          final Date date = dateFormatModis.parse(timeString);
          String milliSeconds = timeString.substring(timeString.length() - 3);
          return ProductData.UTC.create(date, Long.parseLong(milliSeconds) * 1000);
        } else if (productReader.getProductType() == SeadasProductReader.ProductType.Level1A_OCTS) {
          final Date date = dateFormatOcts.parse(timeString);
          String milliSeconds = timeString.substring(timeString.length() - 3);
          return ProductData.UTC.create(date, Long.parseLong(milliSeconds) * 1000);
        } else {
          final Date date = dateFormat.parse(timeString);
          String milliSeconds = timeString.substring(timeString.length() - 3);
          return ProductData.UTC.create(date, Long.parseLong(milliSeconds) * 1000);
        }
      } catch (ParseException ignored) {
      }
    }
    return null;
  }
Ejemplo n.º 8
0
 @Override
 public String format(ProductData.UTC value) {
   final SimpleDateFormat sdf = new SimpleDateFormat(Constants.TIME_PATTERN);
   return sdf.format(value.getAsDate());
 }
Ejemplo n.º 9
0
 public ISO8601Converter() {
   super(ProductData.UTC.createDateFormat("yyyy-MM-dd'T'HH:mm:ss"));
 }
Ejemplo n.º 10
0
  @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;
  }
Ejemplo n.º 11
0
  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);
    }
  }