コード例 #1
0
ファイル: fileUtil.c プロジェクト: glshort/MapReady
/* returns a newly allocated string, returns just the filename portion. */
char *
get_filename(const char *in)
{
   char *dir = MALLOC(sizeof(char)*(strlen(in)+2));
   char *file = MALLOC(sizeof(char)*(strlen(in)+2));
   split_dir_and_file(in,dir,file);
   free(dir);
   return file;
}
コード例 #2
0
ファイル: fileUtil.c プロジェクト: glshort/MapReady
/* returns a newly allocated string, strips off any extension
   and directory info */
char *
get_basename(const char *in)
{
   char *dir = MALLOC(sizeof(char)*(strlen(in)+2));
   char *file = MALLOC(sizeof(char)*(strlen(in)+2));
   split_dir_and_file(in,dir,file);
   free(dir);
   char *ext=findExt(file);
   if (ext) *ext = '\0';
   return file;
}
コード例 #3
0
ファイル: fileUtil.c プロジェクト: glshort/MapReady
char *
getPath(const char *in)
{
  char *dir = malloc(sizeof(char)*(strlen(in) + 2));
  char *file = malloc(sizeof(char)*(strlen(in) + 2));

  split_dir_and_file(in, dir, file);
  free(file);

  // On Windows, allow / as a separator, too, since cygwin does
  if (strlen(dir) > 0) {
    if (dir[strlen(dir) - 1] == DIR_SEPARATOR || dir[strlen(dir) - 1] == '/')
      dir[strlen(dir) - 1] = '\0';
  }

  return dir;
}
コード例 #4
0
ファイル: meta_check.c プロジェクト: rudigens/ASF_MapReady
static int checkMatrixFile(char *type, char *path, char *file, char *reference,
			   char *matrix, char **error)
{
  char *message = NULL, dirName[1024], fileName[1024];
  int ret = TRUE;
  split_dir_and_file(file, dirName, fileName);
  char *file_name = getFileName(path, reference);
  if (!fileExists(file_name)) {
    message = (char *) MALLOC(sizeof(char)*1024);
    sprintf(message, "%s file (%s) of %s matrix element missing.",
	    type, reference, matrix);
    ret = FALSE;
  }
  FREE(file_name);
  *error = message;
  return ret;
}
コード例 #5
0
ファイル: meta_check.c プロジェクト: rudigens/ASF_MapReady
int isCEOS(const char *dataFile, char **error)
{
  char **inBandName = NULL, **inMetaName = NULL, tmp[1024], *message = NULL;
  char baseName[512];
  int ret = TRUE, nBands, trailer;
  ceos_metadata_ext_t metadata_ext;
  ceos_data_ext_t     data_ext;

  if (strlen(dataFile) <= 0)
    return FALSE;

  char *dirName = (char *) MALLOC(sizeof(char)*1024);
  char *fileName = (char *) MALLOC(sizeof(char)*1024);
  split_dir_and_file(dataFile, dirName, fileName);
  metadata_ext = get_ceos_metadata_name(dataFile, &inMetaName, &trailer);
  data_ext = get_ceos_data_name(dataFile, baseName, &inBandName, &nBands);
  if (data_ext == NO_CEOS_DATA) {
    message = (char *) MALLOC(sizeof(char)*1024);
    strcpy(message, "");
    sprintf(tmp, "Data file%s of original data (%s) missing.\n",
	    (nBands>1) ? "s" : "", fileName);
    strcat(message, tmp);
    ret = FALSE;
  }    
  if (metadata_ext == NO_CEOS_METADATA) {
    if (!message) {
      message = (char *) MALLOC(sizeof(char)*1024);
      strcpy(message, "");
    }
    sprintf(tmp, "Metadata file of original data (%s) missing.\n", fileName);
    strcat(message, tmp);
    ret = FALSE;
  }

  *error = message;
  FREE(dirName);
  FREE(fileName);
  free_ceos_names(inBandName, inMetaName);
  return ret;
}
コード例 #6
0
ファイル: meta_check.c プロジェクト: rudigens/ASF_MapReady
int isPolsarproParameter(char *dataFile, char **error)
{
  int parameter = TRUE;
  char *message = NULL, dirName[1024], fileName[1024], headerFile[1024];
  if (!dataFile || strlen(dataFile)<=0)
    return FALSE;
  split_dir_and_file(dataFile, dirName, fileName);
  sprintf(headerFile, "%s", dataFile);
  if (!fileExists(dataFile)) {
    message = (char *) MALLOC(sizeof(char)*1024);
    sprintf(message, "PolSARPro ata file for parameter missing.");
    parameter = FALSE;
  }
  else if (!fileExists(headerFile)) {
    message = (char *) MALLOC(sizeof(char)*1024);
    sprintf(message, "PolSARPro metadata file (%s.hdr) for parameter missing.",
      fileName);
    parameter = FALSE;
  }
  *error = message;
    
  return parameter;
}
コード例 #7
0
ファイル: meta_check.c プロジェクト: rudigens/ASF_MapReady
int isPolsarproSegmentation(const char *dataFile, char **error)
{
  int segmentation = TRUE;
  char *message = NULL, dirName[1024], fileName[1024], headerFile[1024];
  if (!dataFile || strlen(dataFile)<=0)
    return FALSE;
  split_dir_and_file(dataFile, dirName, fileName);
  sprintf(headerFile, "%s", dataFile);
  if (!fileExists(dataFile)) {
    message = (char *) MALLOC(sizeof(char)*1024);
    sprintf(message, "PolSARPro data file for segmentation missing.");
    segmentation = FALSE;
  }
  else if (!fileExists(headerFile)) {
    message = (char *) MALLOC(sizeof(char)*1024);
    sprintf(message,
      "PolSARPro metadata file (%s.hdr) for segmentation missing.",
      fileName);
    segmentation = FALSE;
  }
  *error = message;
  
  return segmentation;
}
コード例 #8
0
ファイル: meta_check.c プロジェクト: rudigens/ASF_MapReady
static int checkDecompositionFile(char *type, char *path, char *file, 
            				                         char *reference, char *decomposition, 
             				  				         char **error)
{
  char *message = NULL, dirName[1024], fileName[1024];
  int ret = TRUE;
  split_dir_and_file(file, dirName, fileName);
  char *file_name = getFileName(path, reference);
  if (!fileExists(file) || is_dir(file)) {
    message = (char *) MALLOC(sizeof(char)*1024);
    sprintf(message, "Decomposition file (%s) does not exist.",
      fileName);
    ret = FALSE;
  }
  else if (!fileExists(file_name)) {
    message = (char *) MALLOC(sizeof(char)*1024);
    sprintf(message, "%s file (%s) of %s decomposition missing.",
      type, reference, decomposition);
    ret = FALSE;
  }
  *error = message;

  return ret;
}
コード例 #9
0
ファイル: meta2radarsat.c プロジェクト: rudigens/ASF_MapReady
radarsat2_meta *read_radarsat2_meta_ext(const char *dataFile, int cal)
{
    int ii, numStateVectors, numDopplerEstimates;
    ymd_date imgStartDate, date;
    hms_time imgStartTime, time;
    julian_date julianDate;
    char timeStr[30], str[150];
    radarsat2_doppler_params *r2_doppler;

    radarsat2_meta *radarsat2 = radarsat2_meta_init();

    if (!fileExists(dataFile))
        asfPrintError("Metadata file (%s) does not exist!\n", dataFile);
    char *path = (char *) MALLOC(sizeof(char)*512);
    char *file = (char *) MALLOC(sizeof(char)*128);
    split_dir_and_file(dataFile, path, file);

    xmlDoc *doc = xmlReadFile(dataFile, NULL, 0);
    if (!doc)
        asfPrintError("Could not parse file %s\n", dataFile);

    strcpy(radarsat2->satellite, xml_get_string_value(doc,
            "product.sourceAttributes.satellite"));
    strcpy(radarsat2->sensor, xml_get_string_value(doc,
            "product.sourceAttributes.sensor"));
    strcpy(radarsat2->beamModeMnemonic, xml_get_string_value(doc,
            "product.sourceAttributes.beamModeMnemonic"));
    strcpy(radarsat2->acquisitionType, xml_get_string_value(doc,
            "product.sourceAttributes.radarParameters.acquisitionType"));
    strcpy(radarsat2->productType, xml_get_string_value(doc,
            "product.imageGenerationParameters.generalProcessingInformation."
            "productType"));
    strcpy(radarsat2->dataType, xml_get_string_value(doc,
            "product.imageAttributes.rasterAttributes.dataType"));
    strcpy(radarsat2->processingFacility, xml_get_string_value(doc,
            "product.imageGenerationParameters.generalProcessingInformation."
            "processingFacility"));
    strcpy(radarsat2->zeroDopplerAzimuthTime, xml_get_string_value(doc,
            "product.imageGenerationParameters.slantRangeToGroundRange."
            "zeroDopplerAzimuthTime"));
    strcpy(radarsat2->softwareVersion, xml_get_string_value(doc,
            "product.imageGenerationParameters.generalProcessingInformation."
            "softwareVersion"));
    radarsat2->bitsPerSample = xml_get_int_value(doc,
                               "product.productInfo.imageDataInfo.imageDataDepth");
    //radarsat2->absOrbit =
    //xml_get_int_value(doc, "product.productInfo.missionInfo.absOrbit");
    strcpy(radarsat2->passDirection, xml_get_string_value(doc,
            "product.sourceAttributes.orbitAndAttitude.orbitInformation."
            "passDirection"));
    // Number of bands needs to be derived from polarizations string
    int band_count = 0;
    char *attribute = (char *) MALLOC(sizeof(char)*128);
    char *fileName = (char *) MALLOC(sizeof(char)*512);
    strcpy(radarsat2->polarizations, xml_get_string_value(doc,
            "product.sourceAttributes.radarParameters.polarizations"));
    for (ii=0; ii<strlen(radarsat2->polarizations)-1; ii++)
        if (radarsat2->polarizations[ii] == ' ')
            radarsat2->polarizations[ii] = ',';
    if (strstr(radarsat2->polarizations, "HH"))
        band_count++;
    if (strstr(radarsat2->polarizations, "VV"))
        band_count++;
    if (strstr(radarsat2->polarizations, "HV"))
        band_count++;
    if (strstr(radarsat2->polarizations, "VH"))
        band_count++;
    radarsat2->band_count = band_count;
    strcpy(radarsat2->filename, "");
    strcpy(radarsat2->bands, "");
    // Park the filenames in the basename field of the metadata and replace
    // it with the directory name once we are done with importing the data
    for (ii=0; ii<band_count; ii++) {
        sprintf(str,
                "product.imageAttributes.fullResolutionImageData[%d].pole", ii);
        strcpy(attribute, xml_get_string_attribute(doc, str));
        sprintf(str, "product.imageAttributes.fullResolutionImageData[%d]", ii);
        strcpy(fileName, xml_get_string_value(doc, str));
        if (ii == 0) {
            sprintf(radarsat2->filename, "%s", fileName);
            sprintf(radarsat2->bands, "AMP-%s,PHASE-%s",
                    uc(attribute), uc(attribute));
        }
        else {
            strcat(radarsat2->filename, ",");
            strcat(radarsat2->filename, fileName);
            strcat(radarsat2->bands, ",");
            sprintf(str, "AMP-%s,PHASE-%s", uc(attribute), uc(attribute));
            strcat(radarsat2->bands, str);
        }
    }
    FREE(fileName);
    FREE(attribute);
    radarsat2->numberOfLines = xml_get_int_value(doc,
                               "product.imageAttributes.rasterAttributes.numberOfLines");
    radarsat2->numberOfSamplesPerLine = xml_get_int_value(doc,
                                        "product.imageAttributes.rasterAttributes.numberOfSamplesPerLine");
    radarsat2->sampledPixelSpacing = xml_get_double_value(doc,
                                     "product.imageAttributes.rasterAttributes.sampledPixelSpacing");
    radarsat2->sampledLineSpacing = xml_get_double_value(doc,
                                    "product.imageAttributes.rasterAttributes.sampledLineSpacing");
    radarsat2->semiMajorAxis = xml_get_double_value(doc,
                               "product.imageAttributes.geographicInformation."
                               "referenceEllipsoidParameters.semiMajorAxis");
    radarsat2->semiMinorAxis = xml_get_double_value(doc,
                               "product.imageAttributes.geographicInformation."
                               "referenceEllipsoidParameters.semiMinorAxis");
    strcpy(radarsat2->lineTimeOrdering, xml_get_string_value(doc,
            "product.imageAttributes.rasterAttributes.lineTimeOrdering"));
    strcpy(radarsat2->pixelTimeOrdering, xml_get_string_value(doc,
            "product.imageAttributes.rasterAttributes.pixelTimeOrdering"));
    strcpy(radarsat2->antennaPointing, xml_get_string_value(doc,
            "product.sourceAttributes.radarParameters.antennaPointing"));
    radarsat2->numberOfAzimuthLooks = xml_get_int_value(doc,
                                      "product.imageGenerationParameters.sarProcessingInformation."
                                      "numberOfAzimuthLooks");
    radarsat2->numberOfRangeLooks = xml_get_int_value(doc,
                                    "product.imageGenerationParameters.sarProcessingInformation."
                                    "numberOfRangeLooks");
    radarsat2->slantRangeNearEdge = xml_get_double_value(doc,
                                    "product.imageGenerationParameters.sarProcessingInformation."
                                    "slantRangeNearEdge");
    radarsat2->radarCenterFrequency = xml_get_double_value(doc,
                                      "product.sourceAttributes.radarParameters.radarCenterFrequency");
    radarsat2->pulseRepetitionFrequency = xml_get_double_value(doc,
                                          "product.sourceAttributes.radarParameters.pulseRepetitionFrequency");
    radarsat2->satelliteHeight = xml_get_double_value(doc,
                                 "product.imageGenerationParameters.sarProcessingInformation."
                                 "satelliteHeight");
    radarsat2->totalProcessedAzimuthBandwidth = xml_get_double_value(doc,
            "product.imageGenerationParameters.sarProcessingInformation."
            "totalProcessedAzimuthBandwidth");
    // chirp rate ???
    radarsat2->pulseLength = xml_get_double_value(doc,
                             "product.sourceAttributes.radarParameters.pulseLength");
    radarsat2->adcSamplingRate = xml_get_double_value(doc,
                                 "product.sourceAttributes.radarParameters.adcSamplingRate");
    // pitch, roll, yaw ???

    // read Doppler values
    radarsat2->doppler = meta_doppler_init();
    radarsat2->doppler->type = radarsat2_doppler;
    char *dopplerCentroidStr;
    dopplerCentroidStr = (char *) MALLOC(sizeof(char)*512);
    strcpy(dopplerCentroidStr, xml_get_string_value(doc,
            "product.imageGenerationParameters.dopplerCentroid."
            "dopplerCentroidCoefficients"));
    numDopplerEstimates = getNumParamsInString(dopplerCentroidStr);
    r2_doppler = radarsat2_doppler_init(numDopplerEstimates);
    radarsat2->doppler->r2 = r2_doppler;
    r2_doppler->ref_time_centroid = xml_get_double_value(doc,
                                    "product.imageGenerationParameters.dopplerCentroid."
                                    "dopplerCentroidReferenceTime");
    r2_doppler->ref_time_rate = xml_get_double_value(doc,
                                "product.imageGenerationParameters.dopplerRateValues."
                                "dopplerRateReferenceTime");
    char *dopplerRateStr;
    dopplerRateStr = (char *) MALLOC(sizeof(char)*512);
    strcpy(dopplerRateStr, xml_get_string_value(doc,
            "product.imageGenerationParameters.dopplerRateValues."
            "dopplerRateValuesCoefficients"));
    r2_doppler->time_first_sample = xml_get_double_value(doc,
                                    "product.imageGenerationParameters.slantRangeToGroundRange."
                                    "slantRangeTimeToFirstRangeSample");
    char *p, *q;
    p = dopplerCentroidStr;
    for (ii=0; ii<numDopplerEstimates; ii++) {
        if (ii == 0)
            q = p;
        else {
            if (strchr(p, ' ')) {
                q = strchr(p, ' ');
                q++;
            }
        }
        sscanf(q, "%lf", &r2_doppler->centroid[ii]);
        p = q;
    }
    FREE(dopplerCentroidStr);
    p = dopplerRateStr;
    for (ii=0; ii<numDopplerEstimates; ii++) {
        if (ii == 0)
            q = p;
        else {
            if (strchr(p, ' ')) {
                q = strchr(p, ' ');
                q++;
            }
        }
        sscanf(q, "%lf", &r2_doppler->rate[ii]);
        p = q;
    }
    FREE(dopplerRateStr);

    // read state vectors
    strcpy(radarsat2->zeroDopplerTimeFirstLine, xml_get_string_value(doc,
            "product.imageGenerationParameters.sarProcessingInformation."
            "zeroDopplerTimeFirstLine"));
    date_terrasar2date(radarsat2->zeroDopplerTimeFirstLine,
                       &imgStartDate, &imgStartTime);
    strcpy(radarsat2->zeroDopplerTimeLastLine, xml_get_string_value(doc,
            "product.imageGenerationParameters.sarProcessingInformation."
            "zeroDopplerTimeLastLine"));
    // Accommodate data stored in reverse time
    if (strcmp_case(radarsat2->lineTimeOrdering, "DECREASING") == 0)
        date_terrasar2date(radarsat2->zeroDopplerTimeLastLine,
                           &imgStartDate, &imgStartTime);

    // FIXME: determine numStateVector from data - count the entries
    //numStateVectors = xml_get_int_value(doc,
    //   "product.platform.orbit.orbitHeader.numStateVectors");
    numStateVectors = 5;
    radarsat2->state_vectors = meta_state_vectors_init(numStateVectors);
    radarsat2->state_vectors->year = imgStartDate.year;
    date_ymd2jd(&imgStartDate, &julianDate);
    radarsat2->state_vectors->julDay = julianDate.jd;
    radarsat2->state_vectors->second = date_hms2sec(&imgStartTime);
    for (ii=0; ii<numStateVectors; ii++) {
        sprintf(str, "product.sourceAttributes.orbitAndAttitude.orbitInformation."
                "stateVector[%d].timeStamp", ii);
        strcpy(timeStr, xml_get_string_value(doc, str));
        date_terrasar2date(timeStr, &date, &time);
        radarsat2->state_vectors->vecs[ii].time =
            time_difference(&date, &time, &imgStartDate, &imgStartTime);
        sprintf(str, "product.sourceAttributes.orbitAndAttitude.orbitInformation."
                "stateVector[%d].xPosition", ii);
        radarsat2->state_vectors->vecs[ii].vec.pos.x =
            xml_get_double_value(doc, str);
        sprintf(str, "product.sourceAttributes.orbitAndAttitude.orbitInformation."
                "stateVector[%d].yPosition", ii);
        radarsat2->state_vectors->vecs[ii].vec.pos.y =
            xml_get_double_value(doc, str);
        sprintf(str, "product.sourceAttributes.orbitAndAttitude.orbitInformation."
                "stateVector[%d].zPosition", ii);
        radarsat2->state_vectors->vecs[ii].vec.pos.z =
            xml_get_double_value(doc, str);
        sprintf(str, "product.sourceAttributes.orbitAndAttitude.orbitInformation."
                "stateVector[%d].xVelocity", ii);
        radarsat2->state_vectors->vecs[ii].vec.vel.x =
            xml_get_double_value(doc, str);
        sprintf(str, "product.sourceAttributes.orbitAndAttitude.orbitInformation."
                "stateVector[%d].yVelocity", ii);
        radarsat2->state_vectors->vecs[ii].vec.vel.y =
            xml_get_double_value(doc, str);
        sprintf(str, "product.sourceAttributes.orbitAndAttitude.orbitInformation."
                "stateVector[%d].zVelocity", ii);
        radarsat2->state_vectors->vecs[ii].vec.vel.z =
            xml_get_double_value(doc, str);
    }

    // read location information from the tie points
    ii = 0;
    int line=-99, pixel=-99, found=TRUE;
    while (found) {
        sprintf(str, "product.imageAttributes.geographicInformation."
                "geolocationGrid.imageTiePoint[%d].imageCoordinate.line", ii);
        line = (int) xml_get_double_value(doc, str);
        sprintf(str, "product.imageAttributes.geographicInformation."
                "geolocationGrid.imageTiePoint[%d].imageCoordinate.pixel", ii);
        pixel = (int) xml_get_double_value(doc, str);
        if (line < 0 || pixel < 0)
            found = FALSE;
        if (found) {
            if (line == 0 && pixel == 0) {
                sprintf(str, "product.imageAttributes.geographicInformation."
                        "geolocationGrid.imageTiePoint[%d].geodeticCoordinate."
                        "latitude", ii);
                radarsat2->sceneCornerCoord1Lat = xml_get_double_value(doc, str);
                sprintf(str, "product.imageAttributes.geographicInformation."
                        "geolocationGrid.imageTiePoint[%d].geodeticCoordinate."
                        "longitude", ii);
                radarsat2->sceneCornerCoord1Lon = xml_get_double_value(doc, str);
            }
            if (line == 0 && pixel == radarsat2->numberOfSamplesPerLine-1) {
                sprintf(str, "product.imageAttributes.geographicInformation."
                        "geolocationGrid.imageTiePoint[%d].geodeticCoordinate."
                        "latitude", ii);
                radarsat2->sceneCornerCoord2Lat = xml_get_double_value(doc, str);
                sprintf(str, "product.imageAttributes.geographicInformation."
                        "geolocationGrid.imageTiePoint[%d].geodeticCoordinate."
                        "longitude", ii);
                radarsat2->sceneCornerCoord2Lon = xml_get_double_value(doc, str);
            }
            if (line == radarsat2->numberOfLines-1 && pixel == 0) {
                sprintf(str, "product.imageAttributes.geographicInformation."
                        "geolocationGrid.imageTiePoint[%d].geodeticCoordinate."
                        "latitude", ii);
                radarsat2->sceneCornerCoord3Lat = xml_get_double_value(doc, str);
                sprintf(str, "product.imageAttributes.geographicInformation."
                        "geolocationGrid.imageTiePoint[%d].geodeticCoordinate."
                        "longitude", ii);
                radarsat2->sceneCornerCoord3Lon = xml_get_double_value(doc, str);
            }
            if (line == radarsat2->numberOfLines-1 &&
                    pixel == radarsat2->numberOfSamplesPerLine-1) {
                sprintf(str, "product.imageAttributes.geographicInformation."
                        "geolocationGrid.imageTiePoint[%d].geodeticCoordinate."
                        "latitude", ii);
                radarsat2->sceneCornerCoord4Lat = xml_get_double_value(doc, str);
                sprintf(str, "product.imageAttributes.geographicInformation."
                        "geolocationGrid.imageTiePoint[%d].geodeticCoordinate."
                        "longitude", ii);
                radarsat2->sceneCornerCoord4Lon = xml_get_double_value(doc, str);
            }
        }
        ii++;
    }

    // Read calibration information
    if (cal) {
        double sample_count = radarsat2->numberOfSamplesPerLine;
        attribute = (char *) MALLOC(sizeof(char)*128);
        fileName = (char *) MALLOC(sizeof(char)*512);
        for (ii=0; ii<3; ii++) {
            sprintf(str,
                    "product.imageAttributes.lookupTable[%d].incidenceAngleCorrection",
                    ii);
            strcpy(attribute, xml_get_string_attribute(doc, str));
            sprintf(str, "product.imageAttributes.lookupTable[%d]", ii);
            if (strlen(path) > 0)
                sprintf(fileName, "%s%s", path, xml_get_string_value(doc, str));
            else
                strcpy(fileName, xml_get_string_value(doc, str));
            if (strcmp_case(attribute, "Beta Nought") == 0)
                radarsat2->gains_beta = read_radarsat2_lut(fileName, sample_count);
            else if (strcmp_case(attribute, "Sigma Nought") == 0)
                radarsat2->gains_sigma = read_radarsat2_lut(fileName, sample_count);
            else if (strcmp_case(attribute, "Gamma") == 0)
                radarsat2->gains_gamma = read_radarsat2_lut(fileName, sample_count);
        }
        FREE(attribute);
        FREE(fileName);
    }

    xmlFreeDoc(doc);
    xmlCleanupParser();

    return radarsat2;
}
コード例 #10
0
int main(int argc, char **argv)
{
  extern int currArg; /* from cla.h in asf.h... initialized to 1 */
  logflag = 0;
  
  // Parse command line args
  while (currArg < (argc-2)) {
    char *key=argv[currArg++];
    if (strmatch(key,"-log")) {
      sprintf(logFile, "%s", argv[currArg]);
      logflag = 1;
    }
    else {
      printf("\n   ***Invalid option:  %s\n\n",
	     argv[currArg-1]);
      usage(argv[0]);
    }
  }
  if ((argc-currArg) < 2) {
    printf("Insufficient arguments.\n");
    usage(argv[0]);
  }
  
  asfSplashScreen(argc, argv);
  
  char *inFile = (char *) MALLOC(sizeof(char)*(strlen(argv[1])+1));
  strcpy(inFile, argv[1]);
  char *outFile = (char *) MALLOC(sizeof(char)*(strlen(argv[2])+1));
  strcpy(outFile, argv[2]);

  char *path = (char *) MALLOC(sizeof(char)*strlen(outFile));
  char *csvFile = (char *) MALLOC(sizeof(char)*strlen(outFile));
  split_dir_and_file(outFile, path, csvFile);
  
  char isoStr[30], dateStr[30], citation[255], sw_version[25], description[50];
  char data_region[50], ref_id[30], source_image[50], target_image[50];
  char product_id[50];
  int create_year, source_year, target_year, num_grids;
  double create_time, source_time, target_time;
  float srcUL_lat, srcUL_lon, srcUR_lat, srcUR_lon, srcLL_lat, srcLL_lon;
  float srcLR_lat, srcLR_lon, trgUL_lat, trgUL_lon, trgUR_lat, trgUR_lon;
  float trgLL_lat, trgLL_lon, trgLR_lat, trgLR_lon, time_diff, pixel_size;
  float grid_spacing, avg_disp_x, avg_disp_y;

  // Open HDF file
  hid_t file_id = H5Fopen(inFile, H5F_ACC_RDONLY, H5P_DEFAULT);
  if (file_id < 0)
    asfPrintError("Cannot open file (%s)!\n", inFile);
    
  // Read global attributes
  h5_att_float(file_id, "/", "AVG_DISP_X(km):_GLOSDS", &avg_disp_x);
  h5_att_float(file_id, "/", "AVG_DISP_Y(km):_GLOSDS", &avg_disp_y);
  h5_att_double(file_id, "/", "CREATE_TIME:_GLOSDS", &create_time);
  h5_att_int(file_id, "/", "CREATE_YEAR:_GLOSDS", &create_year);
  h5_att_float(file_id, "/", "D_TIME between images(day):_GLOSDS", &time_diff);
  h5_att_str(file_id, "/", "Data Region:_GLOSDS", data_region);
  h5_att_float(file_id, "/", "Grid Spacing(km):_GLOSDS", &grid_spacing);
  h5_att_str(file_id, "/", "IMV Tracking REQID:_GLOSDS", ref_id);
  h5_att_float(file_id, "/", "Image Pixel Size(m):_GLOSDS", &pixel_size);
  h5_att_int(file_id, "/", "NGRID With Obs:_GLOSDS", &num_grids);
  h5_att_str(file_id, "/", "Product Description:_GLOSDS", description);
  h5_att_str(file_id, "/", "Product Identifier:_GLOSDS", product_id);
  h5_att_str(file_id, "/", "SW_VERSION:_GLOSDS", sw_version);
  h5_att_double(file_id, "/", "Source Img Center Time:_GLOSDS", &source_time);
  h5_att_str(file_id, "/", "Source Img ID:_GLOSDS", source_image);
  h5_att_float(file_id, "/", "Source Img Lower left lat:_GLOSDS", &srcLL_lat);
  h5_att_float(file_id, "/", "Source Img Lower left lon:_GLOSDS", &srcLL_lon);
  h5_att_float(file_id, "/", "Source Img Lower right lat:_GLOSDS", &srcLR_lat);
  h5_att_float(file_id, "/", "Source Img Lower right lon:_GLOSDS", &srcLR_lon);
  h5_att_float(file_id, "/", "Source Img Upper left lat:_GLOSDS", &srcUL_lat);
  h5_att_float(file_id, "/", "Source Img Upper left lon:_GLOSDS", &srcUL_lon);
  h5_att_float(file_id, "/", "Source Img Upper right lat:_GLOSDS", &srcUR_lat);
  h5_att_float(file_id, "/", "Source Img Upper right lon:_GLOSDS", &srcUR_lon);
  h5_att_int(file_id, "/", "Source Img Year:_GLOSDS", &source_year);
  h5_att_double(file_id, "/", "Target Img Center Time:_GLOSDS", &target_time);
  h5_att_str(file_id, "/", "Target Img ID:_GLOSDS", target_image);
  h5_att_float(file_id, "/", "Target Img Lower left lat:_GLOSDS", &trgLL_lat);
  h5_att_float(file_id, "/", "Target Img Lower left lon:_GLOSDS", &trgLL_lon);
  h5_att_float(file_id, "/", "Target Img Lower right lat:_GLOSDS", &trgLR_lat);
  h5_att_float(file_id, "/", "Target Img Lower right lon:_GLOSDS", &trgLR_lon);
  h5_att_float(file_id, "/", "Target Img Upper left lat:_GLOSDS", &trgUL_lat);
  h5_att_float(file_id, "/", "Target Img Upper left lon:_GLOSDS", &trgUL_lon);
  h5_att_float(file_id, "/", "Target Img Upper right lat:_GLOSDS", &trgUR_lat);
  h5_att_float(file_id, "/", "Target Img Upper right lon:_GLOSDS", &trgUR_lon);
  h5_att_int(file_id, "/", "Target Img Year:_GLOSDS", &target_year);
  
  // Read data
  int ii, num_values;
  short int *grid_qfg;
  double *x_grid, *y_grid, *src_lat, *src_lon, *trg_lat, *trg_lon;
  h5_value_doubles(file_id, "/", "grid_dx(km)", &x_grid, &num_values);
  h5_value_doubles(file_id, "/", "grid_dy(km)", &y_grid, &num_values);
  h5_value_shorts(file_id, "/", "grid_qfg", &grid_qfg, &num_values);
  h5_value_doubles(file_id, "/", "src_grid_lat(deg)", &src_lat, &num_values);
  h5_value_doubles(file_id, "/", "src_grid_lon(deg)", &src_lon, &num_values);
  h5_value_doubles(file_id, "/", "trg_grid_lat(deg)", &trg_lat, &num_values);
  h5_value_doubles(file_id, "/", "trg_grid_lon(deg)", &trg_lon, &num_values);
  
  H5Fclose(file_id);

  // Write CSV file
  double x, y;
  char projFile[50];
  quietflag = TRUE;
  strcpy(projFile, "polar_stereographic_north_ssmi.proj");
  FILE *fp = FOPEN(outFile, "w");
  fprintf(fp, "source_lat,source_lon,source_x,source_y,target_lat,target_lon,"
    "target_x,target_y,x_grid,y_grid,quality_flag\n");
  for (ii=0; ii<num_values; ii++) {
    latLon2proj(src_lat[ii], src_lon[ii], 0.0, projFile, &x, &y);
    fprintf(fp, "%.4f,%.4f,%.4f,%.4f,", src_lat[ii], src_lon[ii], x, y);
    latLon2proj(trg_lat[ii], trg_lon[ii], 0.0, projFile, &x, &y);
    fprintf(fp, "%.4f,%.4f,%.4f,%.4f,%.3f,%.3f,%d\n", trg_lat[ii], trg_lon[ii],
      x, y, x_grid[ii]*1000.0, y_grid[ii]*1000.0, grid_qfg[ii]);
  }
  FCLOSE(fp);
  
  float srcMinLat = minValue(srcLL_lat, srcLR_lat, srcUL_lat, srcUR_lat);
  float srcMaxLat = maxValue(srcLL_lat, srcLR_lat, srcUL_lat, srcUR_lat);
  float srcMinLon = minValue(srcLL_lon, srcLR_lon, srcUL_lon, srcUR_lon);
  float srcMaxLon = maxValue(srcLL_lon, srcLR_lon, srcUL_lon, srcUR_lon);
  float trgMinLat = minValue(trgLL_lat, trgLR_lat, trgUL_lat, trgUR_lat);
  float trgMaxLat = maxValue(trgLL_lat, trgLR_lat, trgUL_lat, trgUR_lat);
  float trgMinLon = minValue(trgLL_lon, trgLR_lon, trgUL_lon, trgUR_lon);
  float trgMaxLon = maxValue(trgLL_lon, trgLR_lon, trgUL_lon, trgUR_lon);
  double westBoundLon = minValue(srcMinLon, srcMaxLon, trgMinLon, trgMaxLon);
  double eastBoundLon = maxValue(srcMinLon, srcMaxLon, trgMinLon, trgMaxLon);
  double northBoundLat = maxValue(srcMinLat, srcMaxLat, trgMinLat, trgMaxLat);
  double southBoundLat = minValue(srcMinLat, srcMaxLat, trgMinLat, trgMaxLat);
  
  // Generate the XML metadata
  sprintf(isoStr, "%s", iso_date());
  char *xmlFile = appendExt(outFile, ".xml");
  FILE *fpXml = FOPEN(xmlFile, "w");
  fprintf(fpXml, "<rgps>\n");
  fprintf(fpXml, "  <granule>%s</granule>\n", stripExt(product_id));
  fprintf(fpXml, "  <metadata_creation>%s</metadata_creation>\n", isoStr);
  fprintf(fpXml, "  <metadata>\n");
  fprintf(fpXml, "    <product>\n");
  fprintf(fpXml, "      <file type=\"string\" definition=\"product identifier\""
    ">%s</file>\n", product_id);
  fprintf(fpXml, "      <format type=\"string\" definition=\"name of the data "
    "format\">CSV</format>\n");
  fprintf(fpXml, "      <description type=\"string\" definition=\"product "
    "description\">%s</description>\n", description);
  fprintf(fpXml, "      <duration type=\"float\" definition=\"time between "
    "source and target image acquisition\" units=\"days\">%.8f</duration>\n", 
    time_diff);
  fprintf(fpXml, "      <data_region type=\"string\" definition=\"region data "
    "was acquired in\">%s</data_region>\n", data_region);
  fprintf(fpXml, "      <ref_id type=\"string\" definition=\"IMV tracking REQID"
    "\">%s</ref_id>\n", ref_id);
  fprintf(fpXml, "      <num_grids type=\"int\" definition=\"number of grid "
    "points with observations\">%d</num_grids>\n", num_grids);
  fprintf(fpXml, "      <pixel_size type=\"float\" definition=\"image pixel "
    "size [m]\" units=\"m\">%.3f</pixel_size>\n", pixel_size);
  fprintf(fpXml, "      <grid_spacing type=\"float\" definition=\"grid spacing "
    "[m]\" units=\"m\">%.3f</grid_spacing>\n", grid_spacing*1000.0);
  fprintf(fpXml, "      <average_disp_x type=\"float\" definition=\"average "
    "displacement in x direction [m]\" units=\"m\">%.3f</average_disp_x>\n",
    avg_disp_x*1000.0);
  fprintf(fpXml, "      <average_disp_y type=\"float\" definition=\"average "
    "displacement in y direction [m]\" units=\"m\">%.3f</average_disp_y>\n",
    avg_disp_y*1000.0);
  fprintf(fpXml, "      <projection_string type=\"string\" definition=\"map "
    "projection information as well known text\">%s</projection_string>\n", 
    meta2esri_proj(NULL, NULL));
  fprintf(fpXml, "    </product>\n");
  fprintf(fpXml, "    <source>\n");
  fprintf(fpXml, "      <file type=\"string\" definition=\"source image "
    "identifier\">%s</file>\n", source_image);
  rgps2iso_date(source_year, source_time, dateStr);
  fprintf(fpXml, "      <acquisition type=\"string\" definition=\"source image "
    "acquisition\">%s</acquisition>\n", dateStr);
  fprintf(fpXml, "      <upper_left_lat type=\"float\" definition=\"latitude of"
    " upper left corner pixel\" units=\"degrees\">%.5f</upper_left_lat>\n", 
    srcUL_lat);
  fprintf(fpXml, "      <upper_left_lon type=\"float\" definition=\"longitude "
    "of upper left corner pixel\" units=\"degrees\">%.5f</upper_left_lon>\n", 
    srcUL_lon);
  fprintf(fpXml, "      <upper_right_lat type=\"float\" definition=\"latitude "
    "of upper right corner pixel\" units=\"degrees\">%.5f</upper_right_lat>\n", 
    srcUR_lat);
  fprintf(fpXml, "      <upper_right_lon type=\"float\" definition=\"longitude "
    "of upper right corner pixel\" units=\"degrees\">%.5f</upper_right_lon>\n", 
    srcUR_lon);
  fprintf(fpXml, "      <lower_left_lat type=\"float\" definition=\"latitude of"
    " lower left corner pixel\" units=\"degrees\">%.5f</lower_left_lat>\n", 
    srcLL_lat);
  fprintf(fpXml, "      <lower_left_lon type=\"float\" definition=\"longitude "
    "of lower left corner pixel\" units=\"degrees\">%.5f</lower_left_lon>\n", 
    srcLL_lon);
  fprintf(fpXml, "      <lower_right_lat type=\"float\" definition=\"latitude "
    "of lower right corner pixel\" units=\"degrees\">%.5f</lower_right_lat>\n", 
    srcLR_lat);
  fprintf(fpXml, "      <lower_right_lon type=\"float\" definition=\"longitude "
    "of lower right corner pixel\" units=\"degrees\">%.5f</lower_right_lon>\n", 
    srcLR_lon);
  fprintf(fpXml, "    </source>\n");
  fprintf(fpXml, "    <target>\n");
  fprintf(fpXml, "      <file type=\"string\" definition=\"target image "
    "identifier\">%s</file>\n", target_image);
  rgps2iso_date(target_year, target_time, dateStr);
  fprintf(fpXml, "      <acquisition type=\"string\" definition=\"source image "
    "acquisition\">%s</acquisition>\n", dateStr);
  fprintf(fpXml, "      <upper_left_lat type=\"float\" definition=\"latitude of"
    " upper left corner pixel\" units=\"degrees\">%.5f</upper_left_lat>\n", 
    trgUL_lat);
  fprintf(fpXml, "      <upper_left_lon type=\"float\" definition=\"longitude "
    "of upper left corner pixel\" units=\"degrees\">%.5f</upper_left_lon>\n", 
    trgUL_lon);
  fprintf(fpXml, "      <upper_right_lat type=\"float\" definition=\"latitude "
    "of upper right corner pixel\" units=\"degrees\">%.5f</upper_right_lat>\n", 
    trgUR_lat);
  fprintf(fpXml, "      <upper_right_lon type=\"float\" definition=\"longitude "
    "of upper right corner pixel\" units=\"degrees\">%.5f</upper_right_lon>\n", 
    trgUR_lon);
  fprintf(fpXml, "      <lower_left_lat type=\"float\" definition=\"latitude of"
    " lower left corner pixel\" units=\"degrees\">%.5f</lower_left_lat>\n", 
    trgLL_lat);
  fprintf(fpXml, "      <lower_left_lon type=\"float\" definition=\"longitude "
    "of lower left corner pixel\" units=\"degrees\">%.5f</lower_left_lon>\n", 
    trgLL_lon);
  fprintf(fpXml, "      <lower_right_lat type=\"float\" definition=\"latitude "
    "of lower right corner pixel\" units=\"degrees\">%.5f</lower_right_lat>\n", 
    trgLR_lat);
  fprintf(fpXml, "      <lower_right_lon type=\"float\" definition=\"longitude "
    "of lower right corner pixel\" units=\"degrees\">%.5f</lower_right_lon>\n", 
    trgLR_lon);
  fprintf(fpXml, "    </target>\n");
  fprintf(fpXml, "  </metadata>\n");
  fprintf(fpXml, "  <extent>\n");
  fprintf(fpXml, "    <product>\n");
  fprintf(fpXml, "      <westBoundLongitude>%.5f</westBoundLongitude>\n",
    westBoundLon);
  fprintf(fpXml, "      <eastBoundLongitude>%.5f</eastBoundLongitude>\n",
    eastBoundLon);
  fprintf(fpXml, "      <northBoundLatitude>%.5f</northBoundLatitude>\n",
    northBoundLat);
  fprintf(fpXml, "      <southBoundLatitude>%.5f</southBoundLatitude>\n",
    southBoundLat);
  rgps2iso_date(source_year, source_time, dateStr);
  snprintf(citation, 11, "%s", dateStr);
  strcat(citation, " to ");
  fprintf(fpXml, "      <start_datetime>%s</start_datetime>\n", dateStr);
  rgps2iso_date(target_year, target_time, dateStr);
  strcat(citation, dateStr);
  citation[24] = '\0';
  fprintf(fpXml, "      <end_datetime>%s</end_datetime>\n", dateStr);
  fprintf(fpXml, "    </product>\n");
  fprintf(fpXml, "  </extent>\n");
  fprintf(fpXml, "  <processing>\n");
  rgps2iso_date(create_year, create_time, dateStr);
  fprintf(fpXml, "    <creation_time>%s</creation_time>\n", dateStr);
  fprintf(fpXml, "    <software_version>%s</software_version>\n", sw_version);
  fprintf(fpXml, "  </processing>\n");
  fprintf(fpXml, "  <root>\n");
  fprintf(fpXml, "    <institution>Alaska Satellite Facility</institution>\n");
  fprintf(fpXml, "    <title>Kwok, Ron. 2008. MEaSUREs Small-Scale Kinematics of"
    " Arctic Ocean Sea Ice, Version 01, %s. Jet Propulsion Laboratory "
    "Pasadena, CA USA and Alaska Satellite Facility Fairbanks, AK USA. Digital "
    "media.</title>\n", citation);
  fprintf(fpXml, "    <source>Products derived from ENVISAT imagery at "
    "100 m resolution</source>\n");
  fprintf(fpXml, "    <comment>Imagery the products are derived from: Copyright "
    "European Space Agency (2002 to 2012)</comment>\n");
  fprintf(fpXml, "    <reference>Documentation available at: www.asf.alaska.edu"
    "</reference>\n");
  fprintf(fpXml, "    <history>%s: CSV file created.</history>\n", isoStr);
  fprintf(fpXml, "  </root>\n");
  fprintf(fpXml, "</rgps>\n");
  FCLOSE(fpXml);
  
  FREE(inFile);
  FREE(outFile);
  FREE(path);
  FREE(csvFile);
  FREE(xmlFile);
  
  return 0;
}
コード例 #11
0
int main(int argc, char *argv[])
{
    char inBaseName[256]="";
    char outBaseName[256]="";
    char *colormapName = NULL;
    char band_id[256]="";
    double wind_dir = 315.0; // Default to wind from the NW
    int cmod4 = 0;
    char *landmaskFile = NULL;
    double landmaskHeight = atof(DEFAULT_LANDMASK_HEIGHT);
    platform_type_t platform_type;
    char *demFile = NULL;
    int ii;
    int flags[NUM_WINDSPEED_FLAGS];

    /* Set all flags to 'not set' */
    for (ii=0; ii<NUM_WINDSPEED_FLAGS; ii++) {
        flags[ii] = FLAG_NOT_SET;
    }

    /**********************BEGIN COMMAND LINE PARSING STUFF**********************/
    if (   (checkForOption("--help", argc, argv) != FLAG_NOT_SET)
        || (checkForOption("-h", argc, argv) != FLAG_NOT_SET)
        || (checkForOption("-help", argc, argv) != FLAG_NOT_SET) ) {
        print_help();
    }
    handle_license_and_version_args(argc, argv, ASF_NAME_STRING);

    /*Check to see if any options were provided*/
    flags[f_LOG] = checkForOption("-log", argc, argv);
    flags[f_QUIET] = checkForOption("-quiet", argc, argv);
    flags[f_REAL_QUIET] = checkForOption("-real-quiet", argc, argv);
    flags[f_BAND] = checkForOption("-band", argc, argv);
    flags[f_COLORMAP] = checkForOption("-colormap", argc, argv);
    flags[f_WINDDIR] = checkForOption("-wind-dir", argc, argv);
    flags[f_CMOD4] = checkForOption("-cmod4", argc, argv);
    flags[f_LANDMASK] = checkForOption("-landmask", argc, argv);
    flags[f_LANDMASK_HEIGHT] = checkForOption("-landmask-height", argc, argv);
    flags[f_DEM] = checkForOption("-dem", argc, argv);

    { /*We need to make sure the user specified the proper number of arguments*/
        int needed_args = 1 + REQUIRED_ARGS;    /*command + REQUIRED_ARGS*/
        if(flags[f_LOG] != FLAG_NOT_SET)      needed_args += 2;/*option & parameter*/
        if(flags[f_QUIET] != FLAG_NOT_SET)    needed_args += 1;/*option*/
        if(flags[f_REAL_QUIET] != FLAG_NOT_SET) needed_args += 1;/*option*/
        if(flags[f_BAND] != FLAG_NOT_SET)     needed_args += 2;/*option & parameter*/
        if(flags[f_COLORMAP] != FLAG_NOT_SET)   needed_args += 2; /*option & parameter*/
        if(flags[f_WINDDIR] != FLAG_NOT_SET) needed_args += 2; /*option & parameter*/
        if(flags[f_CMOD4] != FLAG_NOT_SET) needed_args += 2; /*option & parameter*/
        if(flags[f_LANDMASK] != FLAG_NOT_SET) needed_args += 2; /*option & parameter*/
        if(flags[f_LANDMASK_HEIGHT] != FLAG_NOT_SET) needed_args += 2; /*option & parameter*/
        if(flags[f_DEM] != FLAG_NOT_SET) needed_args += 2; /*option & parameter*/

        /*Make sure we have enough arguments*/
        if(argc != needed_args)
            print_usage();/*This exits with a failure*/
    }

    if(flags[f_LOG] != FLAG_NOT_SET)
        /*Make sure the field following -log isn't another option*/
        if(   argv[flags[f_LOG]+1][0] == '-'
            || flags[f_LOG] >= argc-REQUIRED_ARGS)
            print_usage();
    if(flags[f_BAND] != FLAG_NOT_SET)
      /*Make sure the field following -format isn't another option*/
      if(   argv[flags[f_BAND]+1][0] == '-'
            || flags[f_BAND] >= argc-REQUIRED_ARGS)
        print_usage();
    if(flags[f_COLORMAP] != FLAG_NOT_SET)
      /*Make sure the field following -colormap isn't another option*/
      if(   argv[flags[f_COLORMAP]+1][0] == '-'
            || flags[f_COLORMAP] >= argc-REQUIRED_ARGS)
        print_usage();
    if(flags[f_WINDDIR] != FLAG_NOT_SET)
      if(   argv[flags[f_WINDDIR]+1][0] == '-'
            || flags[f_WINDDIR] >= argc-REQUIRED_ARGS)
        print_usage();
    if(flags[f_CMOD4] != FLAG_NOT_SET)
      if(   argv[flags[f_CMOD4]+1][0] == '-'
            || flags[f_CMOD4] >= argc-REQUIRED_ARGS)
        print_usage();
    if(flags[f_LANDMASK] != FLAG_NOT_SET)
      if(   argv[flags[f_LANDMASK]+1][0] == '-'
            || flags[f_LANDMASK] >= argc-REQUIRED_ARGS)
        print_usage();
    if(flags[f_LANDMASK_HEIGHT] != FLAG_NOT_SET)
      if(   argv[flags[f_LANDMASK_HEIGHT]+1][0] == '-'
            || flags[f_LANDMASK_HEIGHT] >= argc-REQUIRED_ARGS)
        print_usage();
    if(flags[f_DEM] != FLAG_NOT_SET)
      if(   argv[flags[f_DEM]+1][0] == '-'
            || flags[f_DEM] >= argc-REQUIRED_ARGS)
        print_usage();

    /* Be sure to open log ASAP */
    if(flags[f_LOG] != FLAG_NOT_SET)
        strcpy(logFile, argv[flags[f_LOG] + 1]);
    else /*default behavior: log to tmp<pid>.log*/
        sprintf(logFile, "tmp%i.log", (int)getpid());
    logflag = TRUE; /* Since we always log, set the old school logflag to true */

    // Open log file in output folder
    char path[1024], tmp[1024];
    split_dir_and_file(argv[argc-1], path, tmp);
    strcpy(tmp, logFile);
    sprintf(logFile, "%s%s", path, tmp);
    fLog = fopen(logFile, "a");
    if ( fLog == NULL ) {
      logflag = FALSE;
    }

    /* Set old school quiet flag (for use in our libraries) */
    quietflag = flags[f_QUIET] != FLAG_NOT_SET;
    if (flags[f_REAL_QUIET] != FLAG_NOT_SET) quietflag = 2;

    /* We must be close to good enough at this point... log & quiet flags are set
       Report what was retrieved at the command line */
    asfSplashScreen(argc, argv);

    if(flags[f_COLORMAP] != FLAG_NOT_SET) {
      colormapName = (char *) MALLOC(sizeof(char)*1024);
      strcpy(colormapName, argv[flags[f_COLORMAP] + 1]);
    }
    if (flags[f_WINDDIR] != FLAG_NOT_SET) {
      wind_dir = atof(argv[flags[f_WINDDIR]+1]);
    }
    if (flags[f_LANDMASK] != FLAG_NOT_SET) {
      landmaskFile = (char *) MALLOC(sizeof(char)*1024);
      strncpy(landmaskFile, argv[flags[f_LANDMASK]], 8);
    }
    if (flags[f_LANDMASK_HEIGHT] != FLAG_NOT_SET) {
      landmaskHeight = atof(argv[flags[f_LANDMASK_HEIGHT]]);
    }
    if (flags[f_DEM] != FLAG_NOT_SET) {
      demFile = (char *) MALLOC(sizeof(char)*1024);
      strncpy(demFile, argv[flags[f_DEM]], 8);
    }

    // Check validity
    if (flags[f_LANDMASK] != FLAG_NOT_SET &&
        (flags[f_LANDMASK_HEIGHT] != FLAG_NOT_SET || flags[f_DEM] != FLAG_NOT_SET)) {
      asfPrintStatus("\nCannot use the -landmask option together with -landmask-height\n"
                     "or -dem.\n\n");
      print_usage();
    }
    if (wind_dir < 0.0 || wind_dir >= 360.0) {
      asfPrintError("Wind direction specified with the -wind-dir argument must range\n"
          "from 0.0 up to, but not including, 360.0.  Wind direction is specified\n"
          "as being the direction the wind blows FROM in degrees clockwise from\n"
          "North, with North being 0.0 degrees.\n");
    }
    if (landmaskHeight <= 0.0) {
      asfPrintStatus("\nLandmask height set with -landmask-height must be a positive height\n\n");
      print_usage();
    }

    if(flags[f_BAND] != FLAG_NOT_SET) {
      strcpy(band_id, argv[flags[f_BAND] + 1]);
      if (strlen(band_id) && strcmp("ALL", uc(band_id)) == 0) {
        strcpy(band_id, "");
      }
    }

    /* Fetch required arguments */
    strcpy(inBaseName,  argv[argc - 2]);
    strcpy(outBaseName, argv[argc - 1]);

    /***********************END COMMAND LINE PARSING STUFF***********************/

    asfSplashScreen (argc, argv);

    // Check the metadata to find out if this is data we an process
    meta_parameters *md = meta_read(inBaseName);
    meta_general *mg = md->general; // convenience ptr
    meta_sar *ms = md->sar; // convenience ptr
    if ((strncmp(mg->sensor, "RSAT-1", 6) != 0 &&
         strncmp(mg->sensor, "ERS1",   4) != 0 &&
         strncmp(mg->sensor, "ALOS",   4) != 0 &&
         strncmp(mg->sensor, "TSX-1",  5) != 0) ||
        strncmp(mg->sensor_name, "SAR", 3) != 0)
    {
      asfPrintError("Only SAR products from RSAT1, ERS1, ALOS PALSAR, and TERRASAR\n"
          "are supported.  Found sensor %s, sensor_name %s in metadata.\n",
          mg->sensor, mg->sensor_name);
    }
    if (mg->radiometry != r_SIGMA) {
      asfPrintError("Only sigma-nought products (not in decibels) are currently supported.\n"
          "See asf_import -help for more info on how to produce these from \n"
          "original format data.\n");
    }
    if (!strstr(mg->bands, "HH") && !strstr(mg->bands, "VV")) {
      asfPrintError("Only HH and VV polarizations are supported.  Found bands %s\n",
                    mg->bands);
    }
    if (ms->image_type != 'G') {
      asfPrintError("Only ground range images are currently supported.  Found %s image\n",
                    (ms->image_type == 'R') ? "GEOREFERENCED" :
                    (ms->image_type == 'S') ? "SLANT RANGE"   :
                    (ms->image_type == 'P') ? "MAP PROJECTED" : "UNKNOWN TYPE");
    }

    // As-yet unimplemented feature bail-outs...
    if (strncmp(mg->sensor, "RSAT-1", 6) != 0) {
      // Temporary bail-out until we add the other platforms
      asfPrintError("Platforms other than RSAT1 not yet supported...\n");
    }
    if (flags[f_COLORMAP]        != FLAG_NOT_SET ||
        flags[f_CMOD4]           != FLAG_NOT_SET ||
        flags[f_LANDMASK]        != FLAG_NOT_SET ||
        flags[f_LANDMASK_HEIGHT] != FLAG_NOT_SET ||
        flags[f_DEM]             != FLAG_NOT_SET)
    {
      asfPrintError("The following options are not yet supported:\n"
          "  -colormap\n"
          "  -cmod4\n"
          "  -landmask\n"
          "  -landmask-height\n"
          "  -dem\n");
    }

    // Determine platform type
    // RSAT-1 (C-band), ERS1 (C-band), ALOS (L-band), TSX-1 (X-band)
    platform_type = (strncmp(mg->sensor, "RSAT-1", 6) == 0) ? p_RSAT1     :
                    (strncmp(mg->sensor, "ERS1",   4) == 0) ? p_ERS1      :
                    (strncmp(mg->sensor, "ALOS",   4) == 0) ? p_PALSAR    :
                    (strncmp(mg->sensor, "TSX-1",  5) == 0) ? p_TERRASARX : 0;
    meta_free(md);

    asf_windspeed(platform_type, band_id, wind_dir, cmod4,
                  landmaskHeight, landmaskFile, demFile,
                  inBaseName, colormapName, outBaseName);

    FREE(colormapName);
    FREE(landmaskFile);
    FREE(demFile);

    /* If the user didn't ask for a log file then we can nuke the one that
       we've been keeping since we've finished everything  */
    if (logflag) {
        fclose (fLog);
        remove(logFile);
    }

    exit(EXIT_SUCCESS);
}
コード例 #12
0
ファイル: meta2uavsar.c プロジェクト: asfadmin/ASF_MapReady
uavsar_polsar *
read_uavsar_polsar_params(const char *dataFile, uavsar_type_t type)
{
  uavsar_polsar *params = (uavsar_polsar *) MALLOC(sizeof(uavsar_polsar));

  // Determine ID
  char *dirName = (char *) MALLOC(sizeof(char) * 1024);
  char *fileName = (char *) MALLOC(sizeof(char) * 1024);
  split_dir_and_file(dataFile, dirName, fileName);
  sprintf(params->id, "%s", stripExt(fileName));

  // Read annotation file
  char line[MAX_LINE], key[MAX_LINE], value[MAX_LINE];
  FILE *fp = FOPEN(dataFile, "r");
  while (fgets(line, MAX_LINE, fp)) {
    if(!parse_annotation_line(line, key, value)) {
      asfPrintWarning("Unable to parse line in annotation file: %s", line);
      continue;
    }
    if (!strcmp(key, ""))
      continue;
    if (!strcmp(key, "Site Description"))
      strcpy(params->site, value);
    if (!strcmp(key, "Acquisition Mode"))
      strcpy(params->acquisition_mode, value);
    if (type == POLSAR_SLC) {
      params->type = POLSAR_SLC;
      if (!strcmp(key, "slc_mag.set_rows"))
        params->row_count = atoi(value);
      else if (!strcmp(key, "slc_mag.set_cols"))
        params->column_count = atoi(value);
      else if (!strcmp(key, "slc_mag.set_proj"))
        strcpy(params->projection, value);
      else if (!strcmp(key, "slc_mag.row_addr"))
        params->along_track_offset = atof(value);
      else if (!strcmp(key, "slc_mag.col_addr"))
        params->cross_track_offset = atof(value);
      else if (!strcmp(key, "slc_mag.row_mult"))
        params->azimuth_pixel_spacing = atof(value);
      else if (!strcmp(key, "slc_mag.col_mult"))
        params->range_pixel_spacing = atof(value);
      else if (!strcmp(key, "slc_mag.val_size"))
        params->bytes_per_pixel = atoi(value);
      else if (!strcmp(key, "slc_mag.val_frmt"))
        strcpy(params->value_format, value);
      params->range_look_count = 1;
      params->azimuth_look_count = 1;
      if (!strcmp(key, "SLC Data Units"))
        strcpy(params->data_units, value);
    }
    else if (type == POLSAR_MLC) {
      params->type = POLSAR_MLC;
      if (!strcmp(key, "mlc_pwr.set_rows"))
        params->row_count = atoi(value);
      else if (!strcmp(key, "mlc_pwr.set_cols"))
        params->column_count = atoi(value);
      else if (!strcmp(key, "mlc_pwr.set_proj"))
        strcpy(params->projection, value);
      else if (!strcmp(key, "mlc_pwr.row_addr"))
        params->along_track_offset = atof(value);
      else if (!strcmp(key, "mlc_pwr.col_addr"))
        params->cross_track_offset = atof(value);
      else if (!strcmp(key, "mlc_pwr.row_mult"))
        params->azimuth_pixel_spacing = atof(value);
      else if (!strcmp(key, "mlc_pwr.col_mult"))
        params->range_pixel_spacing = atof(value);
      else if (!strcmp(key, "mlc_pwr.val_size"))
        params->bytes_per_pixel = atoi(value);
      else if (!strcmp(key, "mlc_pwr.val_frmt"))
        strcpy(params->value_format, value);
      else if (!strcmp(key, "Number of Range Looks in MLC"))
        params->range_look_count = atoi(value);
      else if (!strcmp(key, "Number of Azimuth Looks in MLC"))
        params->azimuth_look_count = atoi(value);
      else if (!strcmp(key, "MLC Data Units"))
        strcpy(params->data_units, value);
      params->range_look_count = 1;
      params->azimuth_look_count = 1;
    }
    else if (type == POLSAR_DAT) {
      params->type = POLSAR_DAT;
      if (!strcmp(key, "dat.set_rows"))
        params->row_count = atoi(value);
      else if (!strcmp(key, "dat.set_cols"))
        params->column_count = atoi(value);
      else if (!strcmp(key, "dat.set_proj"))
        strcpy(params->projection, value);
      else if (!strcmp(key, "dat.row_addr"))
        params->along_track_offset = atof(value);
      else if (!strcmp(key, "dat.col_addr"))
        params->cross_track_offset = atof(value);
      else if (!strcmp(key, "dat.row_mult"))
        params->azimuth_pixel_spacing = atof(value);
      else if (!strcmp(key, "dat.col_mult"))
        params->range_pixel_spacing = atof(value);
      else if (!strcmp(key, "dat.val_size"))
        params->bytes_per_pixel = atoi(value);
      else if (!strcmp(key, "dat.val_frmt"))
        strcpy(params->value_format, value);
      params->range_look_count = 1;
      params->azimuth_look_count = 1;
      strcpy(params->data_units, MAGIC_UNSET_STRING);
    }
    else if (type == POLSAR_GRD) {
      params->type = POLSAR_GRD;
      if (!strcmp(key, "grd_pwr.set_rows"))
        params->row_count = atoi(value);
      else if (!strcmp(key, "grd_pwr.set_cols"))
        params->column_count = atoi(value);
      else if (!strcmp(key, "grd_pwr.set_proj"))
        strcpy(params->projection, value);
      else if (!strcmp(key, "grd_pwr.row_addr"))
        params->along_track_offset = atof(value);
      else if (!strcmp(key, "grd_pwr.col_addr"))
        params->cross_track_offset = atof(value);
      else if (!strcmp(key, "grd_pwr.row_mult"))
        params->azimuth_pixel_spacing = atof(value);
      else if (!strcmp(key, "grd_pwr.col_mult"))
        params->range_pixel_spacing = atof(value);
      else if (!strcmp(key, "grd_pwr.val_size"))
        params->bytes_per_pixel = atoi(value);
      else if (!strcmp(key, "grd_pwr.val_frmt"))
        strcpy(params->value_format, value);
      else if (!strcmp(key, "Number of Range Looks in MLC"))
        params->range_look_count = atoi(value);
      else if (!strcmp(key, "Number of Azimuth Looks in MLC"))
        params->azimuth_look_count = atoi(value);
      else if (!strcmp(key, "GRD Data Units"))
        strcpy(params->data_units, value);
    }
    else if (type == POLSAR_HGT) {
      params->type = POLSAR_HGT;
      if (!strcmp(key, "hgt.set_rows"))
        params->row_count = atoi(value);
      else if (!strcmp(key, "hgt.set_cols"))
        params->column_count = atoi(value);
      else if (!strcmp(key, "hgt.set_proj"))
        strcpy(params->projection, value);
      else if (!strcmp(key, "hgt.row_addr"))
        params->along_track_offset = atof(value);
      else if (!strcmp(key, "hgt.col_addr"))
        params->cross_track_offset = atof(value);
      else if (!strcmp(key, "hgt.row_mult"))
        params->azimuth_pixel_spacing = atof(value);
      else if (!strcmp(key, "hgt.col_mult"))
        params->range_pixel_spacing = atof(value);
      else if (!strcmp(key, "hgt.val_size"))
        params->bytes_per_pixel = atoi(value);
      else if (!strcmp(key, "hgt.val_frmt"))
        strcpy(params->value_format, value);
      params->range_look_count = 1;
      params->azimuth_look_count = 1;
      if (!strcmp(key, "HGT Data Units"))
        strcpy(params->data_units, value);
    }
    if (!strcmp(key, "set_hddr"))
      params->header_bytes = atoi(value);
    else if (!strcmp(key, "set_tail"))
      params->tail_bytes = atoi(value);
    else if (!strcmp(key, "set_plat"))
      params->lat_peg_point = atof(value);
    else if (!strcmp(key, "set_plon"))
      params->lon_peg_point = atof(value);
    else if (!strcmp(key, "set_phdg"))
      params->head_peg_point = atof(value);
    else if (!strcmp(key, "val_endi"))
      strcpy(params->endianess, value);
    else if (!strcmp(key, "val_mult"))
      params->data_scale = atof(value);
    else if (!strcmp(key, "val_addr"))
      params->data_shift = atof(value);
    else if (!strcmp(key, "val_minv"))
      params->min_value = atof(value);
    else if (!strcmp(key, "val_maxv"))
      params->max_value = atof(value);
    else if (!strcmp(key, "Center Wavelength"))
      params->wavelength = atof(value);
    else if (!strcmp(key, "Ellipsoid Semi-major Axis"))
      params->semi_major = atof(value);
    else if (!strcmp(key, "Ellipsoid Eccentricity Squared"))
      params->eccentricity = atof(value);
    else if (!strcmp(key, "Look Direction"))
      strcpy(params->look_direction, value);
    else if (!strcmp(key, "Range Spacing per Bin"))
      params->range_spacing = atof(value);
    else if (!strcmp(key, "Azimuth Spacing"))
      params->azimuth_spacing = atof(value);
    else if (!strcmp(key, "Image Starting Range"))
      params->slant_range_first_pixel = atof(value);
    else if (!strcmp(key, "Global Average Yaw"))
      params->yaw = atof(value);
    else if (!strcmp(key, "Global Average Pitch"))
      params->pitch = atof(value);
    else if (!strcmp(key, "Global Average Roll"))
      params->roll = atof(value);
    else if (!strcmp(key, "Global Average ESA"))
      params->steering_angle = atof(value);
    else if (!strcmp(key, "Global Average Altitude"))
      params->altitude = atof(value);
    else if (!strcmp(key, "Average GPS Altitude"))
      params->altitude = atof(value);
    else if (!strcmp(key, "Global Average Terrain Height"))
      params->terrain_height = atof(value);
    else if (!strcmp(key, "Global Average Squint Angle"))
      params->squint_angle = atof(value);
    else if (!strcmp(key, "Pulse Length"))
      params->pulse_length = atof(value);
    else if (!strcmp(key, "Bandwidth"))
      params->bandwidth = atof(value);
    else if (!strcmp(key, "Approximate Upper Left Latitude"))
      params->lat_upper_left = atof(value);
    else if (!strcmp(key, "Approximate Upper Left Longitude"))
      params->lon_upper_left = atof(value);
    else if (!strcmp(key, "Approximate Upper Right Latitude"))
      params->lat_upper_right = atof(value);
    else if (!strcmp(key, "Approximate Upper Right Longitude"))
      params->lon_upper_right = atof(value);
    else if (!strcmp(key, "Approximate Lower Left Latitude"))
      params->lat_lower_left = atof(value);
    else if (!strcmp(key, "Approximate Lower Left Longitude"))
      params->lon_lower_left = atof(value);
    else if (!strcmp(key, "Approximate Lower Right Latitude"))
      params->lat_lower_right = atof(value);
    else if (!strcmp(key, "Approximate Lower Right Longitude"))
      params->lon_lower_right = atof(value);
    else if (!strcmp(key, "Date of Acquisition"))
      strcpy(params->acquisition_date, value);
    else if (!strcmp(key, "Processor Version Number"))
      strcpy(params->processor, value);
  }
  FCLOSE(fp);

  return params;
}
コード例 #13
0
ファイル: meta2uavsar.c プロジェクト: asfadmin/ASF_MapReady
uavsar_insar *
read_uavsar_insar_params(const char *dataFile, uavsar_type_t type)
{
  uavsar_insar *params = (uavsar_insar *) MALLOC(sizeof(uavsar_insar));
  char time1[50]="", time2[50]="";

  // Determine ID
  char *dirName = (char *) MALLOC(sizeof(char) * 1024);
  char *fileName = (char *) MALLOC(sizeof(char) * 1024);
  split_dir_and_file(dataFile, dirName, fileName);
  sprintf(params->id, "%s", stripExt(fileName));

  // Read annotation file
  char line[MAX_LINE], key[MAX_LINE], value[MAX_LINE];
  FILE *fp = FOPEN(dataFile, "r");
  while (fgets(line, MAX_LINE, fp)) {
    if(!parse_annotation_line(line, key, value)) {
      asfPrintWarning("Unable to parse line in annotation file: %s", line);
      continue;
    }
    if(!strcmp(key, ""))
      continue;
    if (!strcmp(key, "Site Description"))
      strcpy(params->site, value);
    if (!strcmp(key, "Processing Mode"))
      strcpy(params->processing_mode, value);
    if (!strcmp(key, "Polarization"))
      strcpy(params->polarization, value);
    if (!strcmp(key, "Number of Looks in Range"))
      params->range_look_count = atoi(value);
    if (!strcmp(key, "Number of Looks in Azimuth"))
      params->azimuth_look_count = atoi(value);
    if (type == INSAR_INT) {
      params->type = INSAR_INT;
      if (!strcmp(key, "Interferogram Bytes Per Pixel"))
        params->bytes_per_pixel = atoi(value);
      else if (!strcmp(key, "Interferogram Pixel Format"))
        strcpy(params->value_format, value);
      else if (!strcmp(key, "Interferogram Units"))
        strcpy(params->data_units, value);
    }
    else if (type == INSAR_UNW) {
      params->type = INSAR_UNW;
      if (!strcmp(key, "Unwrapped Phase Bytes Per Pixel"))
        params->bytes_per_pixel = atoi(value);
      else if (!strcmp(key, "Unwrapped Phase Pixel Format"))
        strcpy(params->value_format, value);
      else if (!strcmp(key, "Unwrapped Phase Units"))
        strcpy(params->data_units, value);
    }
    else if (type == INSAR_COR) {
      params->type = INSAR_COR;
      if (!strcmp(key, "Correlation Bytes Per Pixel"))
        params->bytes_per_pixel = atoi(value);
      else if (!strcmp(key, "Correlation Pixel Format"))
        strcpy(params->value_format, value);
      else if (!strcmp(key, "Correlation Units"))
        strcpy(params->data_units, value);
    }
    else if (type == INSAR_AMP) {
      params->type = INSAR_AMP;
      if (!strcmp(key, "Amplitude Bytes Per Pixel"))
        params->bytes_per_pixel = atoi(value);
      else if (!strcmp(key, "Amplitude Pixel Format"))
        strcpy(params->value_format, value);
      else if (!strcmp(key, "Amplitude Units"))
        strcpy(params->data_units, value);
    }
    if (type >= INSAR_AMP && type <= INSAR_COR) {
      if (!strcmp(key, "Slant Range Data Azimuth Lines"))
        params->row_count = atoi(value);
      else if (!strcmp(key, "Slant Range Data Range Samples"))
        params->column_count = atoi(value);
      else if (!strcmp(key, "slt.set_proj"))
        strcpy(params->projection, value);
      else if (!strcmp(key, "slt.row_addr"))
        params->along_track_offset = atof(value);
      else if (!strcmp(key, "slt.col_addr"))
        params->cross_track_offset = atof(value);
      else if (!strcmp(key, "Slant Range Data at Near Range")) {
        params->slant_range_first_pixel = atof(value);
        params->slant_range_first_pixel /= 1000.0;
      }
      else if (!strcmp(key, "Slant Range Data Azimuth Spacing"))
        params->azimuth_pixel_spacing = atof(value);
      else if (!strcmp(key, "Slant Range Data Range Spacing"))
        params->range_pixel_spacing = atof(value);
    }
    else if (type >= INSAR_AMP_GRD && type <= INSAR_HGT_GRD) {
      if (!strcmp(key, "Ground Range Data Latitude Lines"))
        params->row_count = atoi(value);
      else if (!strcmp(key, "Ground Range Data Longitude Samples"))
        params->column_count = atoi(value);
      else if (!strcmp(key, "grd.set_proj"))
        strcpy(params->projection, value);
      else if (!strcmp(key, "grd.row_addr"))
        params->along_track_offset = atof(value);
      else if (!strcmp(key, "grd.col_addr"))
        params->cross_track_offset = atof(value);
      else if (!strcmp(key, "Ground Range Data Latitude Spacing"))
        params->azimuth_pixel_spacing = atof(value);
      else if (!strcmp(key, "Ground Range Data Longitude Spacing"))
        params->range_pixel_spacing = atof(value);
    }
    if (type == INSAR_INT_GRD) {
      params->type = INSAR_INT_GRD;
      if (!strcmp(key, "Interferogram Bytes Per Pixel"))
        params->bytes_per_pixel = atoi(value);
      else if (!strcmp(key, "Interferogram Pixel Format"))
        strcpy(params->value_format, value);
      else if (!strcmp(key, "Interferogram Units"))
        strcpy(params->data_units, value);
    }
    else if (type == INSAR_UNW_GRD) {
      params->type = INSAR_UNW_GRD;
      if (!strcmp(key, "Unwrapped Phase Bytes Per Pixel"))
        params->bytes_per_pixel = atoi(value);
      else if (!strcmp(key, "Unwrapped Phase Pixel Format"))
        strcpy(params->value_format, value);
      else if (!strcmp(key, "Unwrapped Phase Units"))
        strcpy(params->data_units, value);
    }
    else if (type == INSAR_COR_GRD) {
      params->type = INSAR_COR_GRD;
      if (!strcmp(key, "Correlation Bytes Per Pixel"))
        params->bytes_per_pixel = atoi(value);
      else if (!strcmp(key, "Correlation Pixel Format"))
        strcpy(params->value_format, value);
      else if (!strcmp(key, "Correlation Units"))
        strcpy(params->data_units, value);
    }
    else if (type == INSAR_AMP_GRD) {
      params->type = INSAR_AMP_GRD;
      if (!strcmp(key, "Amplitude Bytes Per Pixel"))
        params->bytes_per_pixel = atoi(value);
      else if (!strcmp(key, "Amplitude Pixel Format"))
        strcpy(params->value_format, value);
      else if (!strcmp(key, "Amplitude Units"))
        strcpy(params->data_units, value);
    }
    else if (type == INSAR_HGT_GRD) {
      params->type = INSAR_HGT_GRD;
      if (!strcmp(key, "DEM Bytes Per Pixel"))
        params->bytes_per_pixel = atoi(value);
      else if (!strcmp(key, "DEM Pixel Format"))
        strcpy(params->value_format, value);
      else if (!strcmp(key, "DEM Units"))
        strcpy(params->data_units, value);
    }
    if (!strcmp(key, "set_hddr"))
      params->header_bytes = atoi(value);
    else if (!strcmp(key, "set_tail"))
      params->tail_bytes = atoi(value);
    else if (!strcmp(key, "set_plat"))
      params->lat_peg_point = atof(value);
    else if (!strcmp(key, "set_plon"))
      params->lon_peg_point = atof(value);
    else if (!strcmp(key, "set_phdg"))
      params->head_peg_point = atof(value);
    else if (!strcmp(key, "val_endi"))
      strcpy(params->endianess, value);
    else if (!strcmp(key, "val_mult"))
      params->data_scale = atof(value);
    else if (!strcmp(key, "val_addr"))
      params->data_shift = atof(value);
    else if (!strcmp(key, "val_minv"))
      params->min_value = atof(value);
    else if (!strcmp(key, "val_maxv"))
      params->max_value = atof(value);
    else if (!strcmp(key, "Center Wavelength"))
      params->wavelength = atof(value);
    else if (!strcmp(key, "Ellipsoid Semi-major Axis"))
      params->semi_major = atof(value);
    else if (!strcmp(key, "Ellipsoid Eccentricity Squared"))
      params->eccentricity = atof(value);
    else if (!strcmp(key, "Look Direction"))
      strcpy(params->look_direction, value);
    else if (!strcmp(key, "Range Spacing per Bin"))
      params->range_spacing = atof(value);
    else if (!strcmp(key, "Azimuth Spacing"))
      params->azimuth_spacing = atof(value);
    else if (!strcmp(key, "Image Starting Range"))
      params->slant_range_first_pixel = atof(value);
    else if (!strcmp(key, "Global Average Yaw"))
      params->yaw = atof(value);
    else if (!strcmp(key, "Global Average Pitch"))
      params->pitch = atof(value);
    else if (!strcmp(key, "Global Average Roll"))
      params->roll = atof(value);
    else if (!strcmp(key, "Global Average ESA"))
      params->steering_angle = atof(value);
    else if (!strcmp(key, "Global Average Altitude"))
      params->altitude = atof(value);
    else if (!strcmp(key, "Average GPS Altitude"))
      params->altitude = atof(value);
    else if (!strcmp(key, "Global Average Terrain Height"))
      params->terrain_height = atof(value);
    else if (!strcmp(key, "Global Average Squint Angle"))
      params->squint_angle = atof(value);
    else if (!strcmp(key, "Pulse Length"))
      params->pulse_length = atof(value);
    else if (!strcmp(key, "Bandwidth"))
      params->bandwidth = atof(value);
    else if (!strcmp(key, "Approximate Upper Left Latitude")) {
      if (strcmp_case(value, "N/A") == 0)
        params->lat_upper_left = MAGIC_UNSET_DOUBLE;
      else
        params->lat_upper_left = atof(value);
    }
    else if (!strcmp(key, "Approximate Upper Left Longitude")) {
      if (strcmp_case(value, "N/A") == 0)
        params->lon_upper_left = MAGIC_UNSET_DOUBLE;
      else
        params->lon_upper_left = atof(value);
    }
    else if (!strcmp(key, "Approximate Upper Right Latitude")) {
      if (strcmp_case(value, "N/A") == 0)
        params->lat_upper_right = MAGIC_UNSET_DOUBLE;
      else
        params->lat_upper_right = atof(value);
    }
    else if (!strcmp(key, "Approximate Upper Right Longitude")) {
      if (strcmp_case(value, "N/A") == 0)
        params->lon_upper_right = MAGIC_UNSET_DOUBLE;
      else
        params->lon_upper_right = atof(value);
    }
    else if (!strcmp(key, "Approximate Lower Left Latitude")) {
      if (strcmp_case(value, "N/A") == 0)
        params->lat_lower_left = MAGIC_UNSET_DOUBLE;
      else
        params->lat_lower_left = atof(value);
    }
    else if (!strcmp(key, "Approximate Lower Left Longitude")) {
      if (strcmp_case(value, "N/A") == 0)
        params->lon_lower_left = MAGIC_UNSET_DOUBLE;
      else
        params->lon_lower_left = atof(value);
    }
    else if (!strcmp(key, "Approximate Lower Right Latitude")) {
      if (strcmp_case(value, "N/A") == 0)
        params->lat_lower_right = MAGIC_UNSET_DOUBLE;
      else
        params->lat_lower_right = atof(value);
    }
    else if (!strcmp(key, "Approximate Lower Right Longitude")) {
      if (strcmp_case(value, "N/A") == 0)
        params->lon_lower_right = MAGIC_UNSET_DOUBLE;
      else
        params->lon_lower_right = atof(value);
    }
    else if (!strcmp(key, "Time of Acquisition for Pass 1"))
      strcpy(time1, value);
    else if (!strcmp(key, "Time of Acquisition for Pass 2"))
      strcpy(time2, value);
    else if (!strcmp(key, "Processor Version Number"))
      strcpy(params->processor, value);
  }
  FCLOSE(fp);

  sprintf(params->acquisition_date, "%s, %s", time1, time2);

  return params;
}
コード例 #14
0
int main(int argc, char **argv)
{
  FILE *fpIn, *fpOut, *fpInList, *fpOutList, *fpXml;
  meta_parameters *meta;
  extern int currArg; /* from cla.h in asf.h... initialized to 1 */
  logflag = 0;
  
  // Parse command line args
  while (currArg < (argc-2)) {
    char *key=argv[currArg++];
    if (strmatch(key,"-log")) {
      sprintf(logFile, "%s", argv[currArg]);
      logflag = 1;
    }
    else {
      printf("\n   ***Invalid option:  %s\n\n",
	     argv[currArg-1]);
      usage(argv[0]);
    }
  }
  if ((argc-currArg) < 2) {
    printf("Insufficient arguments.\n");
    usage(argv[0]);
  }
  
  asfSplashScreen(argc, argv);
  
  char *listInFile = (char *) MALLOC(sizeof(char)*(strlen(argv[1])+1));
  strcpy(listInFile, argv[1]);
  char *outFile = (char *) MALLOC(sizeof(char)*(strlen(argv[2])+1));
  strcpy(outFile, argv[2]);
  
  // Setup file names
  char outDirName[512], outFileName[512];
  split_dir_and_file(outFile, outDirName, outFileName);
  char *tmpDir = (char *) MALLOC(sizeof(char)*512);
  sprintf(tmpDir, "%smeasures-", outDirName);
  char *tsdir = time_stamp_dir();
  strcat(tmpDir, tsdir);
  FREE(tsdir);
  create_clean_dir(tmpDir);
  char *isoStr = iso_date();

  // Read header information
  char inFile[512], imgFile[768], metaFile[768];
  char listOutFile[768], citation[50], start[30], end[30], first[30];
  char header[120], baseName[512], dirName[512], ext[5];
  float x_pix, y_pix, x_map_ll, y_map_ll, x_map_ur, y_map_ur, inc, cat;
  double lat, lon, height, x, y, z;
  int ii, kk, nFiles=0, num = 1, sample_count, line_count;
  image_data_type_t image_data_type;
  sprintf(listOutFile, "%s%crgps.xml", tmpDir, DIR_SEPARATOR);

  // Preparing map projection information
  project_parameters_t pps;
  projection_type_t proj_type;
  datum_type_t datum;
  spheroid_type_t spheroid;
  read_proj_file("polar_stereographic_north_ssmi.proj", 
     &pps, &proj_type, &datum, &spheroid);
  pps.ps.false_easting = 0.0;
  pps.ps.false_northing = 0.0;
  meta_projection *proj = meta_projection_init();
  proj->type = proj_type;
  proj->datum = HUGHES_DATUM;
  proj->spheroid = HUGHES_SPHEROID;
  proj->param = pps;
  strcpy(proj->units, "meters");
  proj->hem = 'N';
  spheroid_axes_lengths(spheroid, &proj->re_major, &proj->re_minor);
  FREE(proj);

  // Set up supplemental file names: water mask, lat/lon, x/y grids
  char maskFile[768], latFile[768], lonFile[768], xFile[768], yFile[768]; 
  sprintf(maskFile, "%s%cwater_mask.img", tmpDir, DIR_SEPARATOR);
  sprintf(latFile, "%s%clatitude.img", tmpDir, DIR_SEPARATOR);
  sprintf(lonFile, "%s%clongitude.img", tmpDir, DIR_SEPARATOR);
  sprintf(xFile, "%s%cxgrid.img", tmpDir, DIR_SEPARATOR);
  sprintf(yFile, "%s%cygrid.img", tmpDir, DIR_SEPARATOR);

  // Generating output XML file
  fpInList = FOPEN(listInFile, "r");
  fpOutList = FOPEN(listOutFile, "w");
  fprintf(fpOutList, "<netcdf>\n");
  fprintf(fpOutList, "  <data>\n");
  fprintf(fpOutList, "    <latitude>%s</latitude>\n", latFile);
  fprintf(fpOutList, "    <longitude>%s</longitude>\n", lonFile);
  fprintf(fpOutList, "    <xgrid>%s</xgrid>\n", xFile);
  fprintf(fpOutList, "    <ygrid>%s</ygrid>\n", yFile);
  fprintf(fpOutList, "    <mask>%s</mask>\n", maskFile);
  
  julian_date jdStart, jdEnd, jdRef;
  hms_time hms;
  hms.hour = 0;
  hms.min = 0;
  hms.sec = 0.0;

  asfPrintStatus("Working through the file list:\n");
  int myrFlag=FALSE, divFlag=FALSE, vrtFlag=FALSE, shrFlag=FALSE;
  int firstYear, firstDay, startYear, startDay, endYear, endDay;
  double westBoundLon, eastBoundLon, northBoundLat, southBoundLat;
  double minLat=90.0, maxLat=-90.0, minLon=180.0, maxLon=-180.0;

  while (fgets(inFile, 512, fpInList)) {

    chomp(inFile);
    char inDirName[512], inFileName[512];
    split_dir_and_file(inFile, inDirName, inFileName);

    // Preparing map projection information
    project_parameters_t pps;
    projection_type_t proj_type;
    datum_type_t datum;
    spheroid_type_t spheroid;
    read_proj_file("polar_stereographic_north_ssmi.proj", 
       &pps, &proj_type, &datum, &spheroid);
    pps.ps.false_easting = 0.0;
    pps.ps.false_northing = 0.0;
    meta_projection *proj = meta_projection_init();
    proj->type = proj_type;
    proj->datum = HUGHES_DATUM;
    proj->spheroid = HUGHES_SPHEROID;
    proj->param = pps;
    strcpy(proj->units, "meters");
    proj->hem = 'N';
    spheroid_axes_lengths(spheroid, &proj->re_major, &proj->re_minor);

    // Sort out dates
    startYear = subInt(inFileName, 0, 4);
    startDay = subInt(inFileName, 4, 3);
    endYear = subInt(inFileName, 8, 4);
    endDay = subInt(inFileName, 12, 3);
    if (nFiles == 0) {
      firstYear = startYear;
      firstDay = startDay;
    }
    sprintf(citation, "%d%03d to %d%03d", startYear, startDay, endYear, endDay);
    rgps2iso_date(startYear, (double) startDay, start);
    rgps2iso_date(endYear, (double) endDay, end);
    rgps2iso_date(firstYear, (double) firstDay, first);
    
    // Read header information
    FILE *fpIn = FOPEN(inFile, "r");
    fgets(header, 100, fpIn);
    sscanf(header, "%f %f %f %f %f %f", &x_pix, &y_pix, &x_map_ll, &y_map_ll, 
      &x_map_ur, &y_map_ur);
    fgets(header, 100, fpIn);
    int params = sscanf(header, "%f %f %d %d", 
      &inc, &cat, &sample_count, &line_count);
    if (params == 3) {
      sscanf(header, "%f %d %d", &cat, &sample_count, &line_count);
      inc = 0;
    }
    else if (params == 2) {
      sscanf(header, "%d %d", &sample_count, &line_count);
      inc = 0;
      cat = 1;
    }
    num = (int) cat;
    if (num > 1)
      asfPrintError("Multiband imagery (%s) not supported for netCDF "
        "generation!\n", inFile);

    /*  
    printf("x_pix: %f, y_pix: %f\n", x_pix, y_pix);
    printf("x_map_ll: %f, y_map_ll: %f\n", x_map_ll, y_map_ll);
    printf("x_map_ur: %f, y_map_ur: %f\n", x_map_ur, y_map_ur);
    printf("sample_count: %d, line_count: %d\n\n", sample_count, line_count);
    */
      
    // Check extension
    split_base_and_ext(inFileName, 1, '.', baseName, ext);
    asfPrintStatus("Processing %s ...\n", inFileName);
    sprintf(imgFile, "%s%c%s_%s.img", tmpDir, DIR_SEPARATOR, baseName, &ext[1]);
    sprintf(metaFile, "%s%c%s_%s.meta", tmpDir, DIR_SEPARATOR, baseName, 
      &ext[1]);
    
    jdRef.year = firstYear;
    jdRef.jd = 1;
    jdStart.year = startYear;
    jdStart.jd = startDay;
    jdEnd.year = endYear;
    jdEnd.jd = endDay;
    double startSec = date2sec(&jdStart, &hms) - date2sec(&jdRef, &hms);
    double endSec = date2sec(&jdEnd, &hms) - date2sec(&jdRef, &hms);
    if (strcmp_case(ext, ".MYR") == 0) {
      fprintf(fpOutList, "    <multiyear_ice_fraction start=\"%.0f\" end=\"%.0f"
        "\">%s</multiyear_ice_fraction>\n", startSec, endSec, imgFile);
      image_data_type = MULTIYEAR_ICE_FRACTION;
      myrFlag = TRUE;
    }
    else if (strcmp_case(ext, ".DIV") == 0) {
      fprintf(fpOutList, "    <divergence start=\"%.0f\" end=\"%.0f\">%s"
        "</divergence>\n", startSec, endSec, imgFile);
      image_data_type = DIVERGENCE;
      divFlag = TRUE;
    }
    else if (strcmp_case(ext, ".VRT") == 0) {
      fprintf(fpOutList, "    <vorticity start=\"%.0f\" end=\"%.0f\">%s"
        "</vorticity>\n", startSec, endSec, imgFile);
      image_data_type = VORTICITY;
      vrtFlag = TRUE;
    }
    else if (strcmp_case(ext, ".SHR") == 0) {
      fprintf(fpOutList, "    <shear start=\"%.0f\" end=\"%.0f\">%s</shear>", 
        startSec, endSec, imgFile);
      image_data_type = SHEAR;
      shrFlag = TRUE;
    }

    // Generate basic metadata
    meta = raw_init();
    meta->general->line_count = line_count;
    meta->general->sample_count = sample_count;
    meta->general->band_count = 1;
    meta->general->data_type = REAL32;
    meta->general->image_data_type = image_data_type;
    strcpy(meta->general->basename, inFile);
    meta->general->x_pixel_size = x_pix*1000.0;
    meta->general->y_pixel_size = y_pix*1000.0;
    meta->general->start_line = 0;
    meta->general->start_sample = 0;
    meta->general->no_data = MAGIC_UNSET_DOUBLE;
    strcpy(meta->general->sensor, "RGPS MEaSUREs");
    char *tmp = image_data_type2str(meta->general->image_data_type);
    sprintf(meta->general->bands, "%s", lc(tmp));
    FREE(tmp);
    sprintf(meta->general->acquisition_date, "%s", baseName);
    
    // Sort out map projection
    proj->startX = x_map_ll*1000.0;
    proj->startY = y_map_ur*1000.0;
    proj->perX = x_pix*1000.0;
    proj->perY = -y_pix*1000.0;
    meta->projection = proj;
    meta_write(meta, metaFile);
    strcpy(meta->general->bands, "water mask");
    sprintf(metaFile, "%s%cwater_mask.meta", tmpDir, DIR_SEPARATOR);
    meta_write(meta, metaFile);  
    sprintf(metaFile, "%s%c%s_%s.meta", tmpDir, DIR_SEPARATOR, baseName, 
      &ext[1]);
    
    float *floatBuf = (float *) MALLOC(sizeof(float)*sample_count);

    // Write gridded data to ASF internal format
    fpOut = FOPEN(imgFile, "wb");
    for (ii=0; ii<line_count; ii++) {
      for (kk=0; kk<sample_count; kk++) {
	      ASF_FREAD(&floatBuf[kk], sizeof(float), 1, fpIn);
	      ieee_big32(floatBuf[kk]);
        if (floatBuf[kk] > 10000000000.0 || 
          FLOAT_EQUIVALENT(floatBuf[kk], 10000000000.0))
          floatBuf[kk] = MAGIC_UNSET_DOUBLE;
      }
      put_float_line(fpOut, meta, line_count-ii-1, floatBuf);
    }
    FCLOSE(fpOut);
    FREE(floatBuf);
    
    double lat1, lon1, lat2, lon2, lat3, lon3, lat4, lon4;
    proj_to_latlon(proj, x_map_ll*1000.0, y_map_ll*1000.0, 0.0, 
      &lat1, &lon1, &height);
    proj_to_latlon(proj, x_map_ll*1000.0, y_map_ur*1000.0, 0.0, 
      &lat2, &lon2, &height);
    proj_to_latlon(proj, x_map_ur*1000.0, y_map_ur*1000.0, 0.0, 
      &lat3, &lon3, &height);
    proj_to_latlon(proj, x_map_ur*1000.0, y_map_ll*1000.0, 0.0, 
      &lat4, &lon4, &height);
    westBoundLon = minValue(lon1*R2D, lon2*R2D, lon3*R2D, lon4*R2D);
    eastBoundLon = maxValue(lon1*R2D, lon2*R2D, lon3*R2D, lon4*R2D);
    northBoundLat = maxValue(lat1*R2D, lat2*R2D, lat3*R2D, lat4*R2D);
    southBoundLat = minValue(lat1*R2D, lat2*R2D, lat3*R2D, lat4*R2D);
    if (westBoundLon < minLon)
      minLon = westBoundLon;
    if (eastBoundLon > maxLon)
      maxLon = eastBoundLon;
    if (southBoundLat < minLat)
      minLat = southBoundLat;
    if (northBoundLat > maxLat)
      maxLat = northBoundLat;

    meta_free(meta);
    nFiles++;
  }
  FCLOSE(fpInList);
  
  fprintf(fpOutList, "  </data>\n");
  fprintf(fpOutList, "  <metadata>\n");
  fprintf(fpOutList, "    <time>\n");
  fprintf(fpOutList, "      <axis type=\"string\" definition=\"name of axis\">T"
    "</axis>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">serial date</long_name>\n");
  fprintf(fpOutList, "      <references type=\"string\" definition=\"reference "
    "of the value\">start time of 3-day average</references>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">time</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">seconds since %d-01-01T00:00:00Z</units>\n",
    firstYear);
  fprintf(fpOutList, "      <bounds type=\"string\" definition=\"variable "
    "containing data range\">time_bounds</bounds>\n");
  fprintf(fpOutList, "      <FillValue type=\"double\" definition=\"default "
    "value\">0</FillValue>\n");
  fprintf(fpOutList, "    </time>\n");
  fprintf(fpOutList, "    <time_bounds>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">serial date</long_name>\n");
  fprintf(fpOutList, "      <references type=\"string\" definition=\"reference "
    "of the value\">start and end time of 3-day average</references>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">time</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">seconds since %d-01-01T00:00:00Z</units>\n",
    firstYear);
  fprintf(fpOutList, "      <FillValue type=\"double\" definition=\"default "
    "value\">0</FillValue>\n");
  fprintf(fpOutList, "    </time_bounds>\n");
  fprintf(fpOutList, "    <latitude>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">latitude</long_name>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">latitude</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">degrees_north</units>\n");
  fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
    "value\">-999</FillValue>\n");
  fprintf(fpOutList, "      <valid_min type=\"float\" definition=\"minimum "
    "valid value\">-90.0</valid_min>\n");
  fprintf(fpOutList, "      <valid_max type=\"float\" definition=\"minimum "
    "valid value\">90.0</valid_max>\n");
  fprintf(fpOutList, "    </latitude>\n");
  fprintf(fpOutList, "    <longitude>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">longitude</long_name>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">longitude</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">degrees_east</units>\n");
  fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
    "value\">-999</FillValue>\n");
  fprintf(fpOutList, "      <valid_min type=\"float\" definition=\"minimum "
    "valid value\">-180.0</valid_min>\n");
  fprintf(fpOutList, "      <valid_max type=\"float\" definition=\"minimum "
    "valid value\">180.0</valid_max>\n");
  fprintf(fpOutList, "    </longitude>\n");
  fprintf(fpOutList, "    <xgrid>\n");
  fprintf(fpOutList, "      <axis type=\"string\" definition=\"name of axis\">X"
    "</axis>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">projection_grid_x_center</long_name>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">projection_x_coordinate"
    "</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">meters</units>\n");
  fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
    "value\">NaN</FillValue>\n");
  fprintf(fpOutList, "    </xgrid>\n");
  fprintf(fpOutList, "    <ygrid>\n");
  fprintf(fpOutList, "      <axis type=\"string\" definition=\"name of axis\">Y"
    "</axis>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">projection_grid_y_center</long_name>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">projection_y_coordinate"
    "</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">meters</units>\n");
  fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
    "value\">NaN</FillValue>\n");
  fprintf(fpOutList, "    </ygrid>\n");
  fprintf(fpOutList, "    <Polar_Stereographic>\n");
  fprintf(fpOutList, "      <grid_mapping_name>polar_stereographic"
    "</grid_mapping_name>\n");
  fprintf(fpOutList, "      <straight_vertical_longitude_from_pole>%.1f"
    "</straight_vertical_longitude_from_pole>\n", pps.ps.slon);
  fprintf(fpOutList, "      <longitude_of_central_meridian>90.0"
    "</longitude_of_central_meridian>\n");
  fprintf(fpOutList, "      <standard_parallel>%.1f</standard_parallel>\n", 
    pps.ps.slat);
  fprintf(fpOutList, "      <false_easting>%.1f</false_easting>\n", 
    pps.ps.false_easting);
  fprintf(fpOutList, "      <false_northing>%.1f</false_northing>\n",
    pps.ps.false_northing);
  fprintf(fpOutList, "      <projection_x_coordinate>xgrid"
    "</projection_x_coordinate>\n");
  fprintf(fpOutList, "      <projection_y_coordinate>ygrid"
    "</projection_y_coordinate>\n");
  fprintf(fpOutList, "      <units>meters</units>\n");
  fprintf(fpOutList, "    </Polar_Stereographic>\n");
  fprintf(fpOutList, "    <mask>\n");
  fprintf(fpOutList, "      <coordinates type=\"string\" definition=\""
    "coordinate reference\">ygrid xgrid</coordinates>\n");
  fprintf(fpOutList, "      <grid_mapping type=\"string\" definition=\"\">"
    "Polar_Stereographic</grid_mapping>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">projection_grid_y_center</long_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">1</units>\n");
  fprintf(fpOutList, "      <units_description type=\"string\" definition=\""
    "descriptive information about dimensionless quantity\">unitless"
    "</units_description>\n");
  fprintf(fpOutList, "      <FillValue type=\"int\" definition=\"default "
    "value\">0</FillValue>\n");
  fprintf(fpOutList, "    </mask>\n");
  if (myrFlag) {
    fprintf(fpOutList, "    <multiyear_ice_fraction>\n");
    fprintf(fpOutList, "      <cell_methods type=\"string\" definition=\""
      "characteristic of a field that is represented by cell values\">area: "
      "multiyear ice fraction value</cell_methods>\n");
    fprintf(fpOutList, "      <coordinates type=\"string\" definition=\""
      "coordinate reference\">ygrid xgrid</coordinates>\n");
    fprintf(fpOutList, "      <grid_mapping type=\"string\" definition=\"\">"
      "Polar_Stereographic</grid_mapping>\n");
    fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
      "descriptive name\">RGPS MEaSUREs multiyear ice fraction</long_name>\n");
    fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
      "dimensional quantity\">1</units>\n");
    fprintf(fpOutList, "      <units_description type=\"string\" definition=\""
      "descriptive information about dimensionless quantity\">unitless"
      "</units_description>\n");
    fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
      "value\">NaN</FillValue>\n");
    fprintf(fpOutList, "    </multiyear_ice_fraction>\n");
  }
  if (divFlag) {
    fprintf(fpOutList, "    <divergence>\n");
    fprintf(fpOutList, "      <cell_methods type=\"string\" definition=\""
      "characteristic of a field that is represented by cell values\">area: "
      "divergence value</cell_methods>\n");
    fprintf(fpOutList, "      <coordinates type=\"string\" definition=\""
      "coordinate reference\">ygrid xgrid</coordinates>\n");
    fprintf(fpOutList, "      <grid_mapping type=\"string\" definition=\"\">"
      "Polar_Stereographic</grid_mapping>\n");
    fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
      "descriptive name\">RGPS MEaSUREs divergence</long_name>\n");
    fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
      "dimensional quantity\">1</units>\n");
    fprintf(fpOutList, "      <units_description type=\"string\" definition=\""
      "descriptive information about dimensionless quantity\">unitless"
      "</units_description>\n");
    fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
      "value\">NaN</FillValue>\n");
    fprintf(fpOutList, "    </divergence>\n");
  }
  if (vrtFlag) {
    fprintf(fpOutList, "    <vorticity>\n");
    fprintf(fpOutList, "      <cell_methods type=\"string\" definition=\""
      "characteristic of a field that is represented by cell values\">area: "
      "vorticity value</cell_methods>\n");
    fprintf(fpOutList, "      <coordinates type=\"string\" definition=\""
      "coordinate reference\">ygrid xgrid</coordinates>\n");
    fprintf(fpOutList, "      <grid_mapping type=\"string\" definition=\"\">"
      "Polar_Stereographic</grid_mapping>\n");
    fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
      "descriptive name\">RGPS MEaSUREs vorticity</long_name>\n");
    fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
      "dimensional quantity\">1</units>\n");
    fprintf(fpOutList, "      <units_description type=\"string\" definition=\""
      "descriptive information about dimensionless quantity\">unitless"
      "</units_description>\n");
    fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
      "value\">NaN</FillValue>\n");
    fprintf(fpOutList, "    </vorticity>\n");
  }
  if (shrFlag) {
    fprintf(fpOutList, "    <shear>\n");
    fprintf(fpOutList, "      <cell_methods type=\"string\" definition=\""
      "characteristic of a field that is represented by cell values\">area: "
      "shear value</cell_methods>\n");
    fprintf(fpOutList, "      <coordinates type=\"string\" definition=\""
      "coordinate reference\">ygrid xgrid</coordinates>\n");
    fprintf(fpOutList, "      <grid_mapping type=\"string\" definition=\"\">"
      "Polar_Stereographic</grid_mapping>\n");
    fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
      "descriptive name\">RGPS MEaSUREs shear</long_name>\n");
    fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
      "dimensional quantity\">1</units>\n");
    fprintf(fpOutList, "      <units_description type=\"string\" definition=\""
      "descriptive information about dimensionless quantity\">unitless"
      "</units_description>\n");
    fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
      "value\">NaN</FillValue>\n");
    fprintf(fpOutList, "    </shear>\n");
  }
  fprintf(fpOutList, "  </metadata>\n");
  fprintf(fpOutList, "  <parameter>\n");
  if (myrFlag)
    fprintf(fpOutList, "    <multiyear_ice_fraction type=\"float\"/>\n");
  if (divFlag)
    fprintf(fpOutList, "    <divergence type=\"float\"/>\n");
  if (vrtFlag)
    fprintf(fpOutList, "    <vorticity type=\"float\"/>\n");
  if (shrFlag)
    fprintf(fpOutList, "    <shear type=\"float\"/>\n");
  fprintf(fpOutList, "  </parameter>\n");
  
  char startStr[15], endStr[15];
  jdStart.year = firstYear;
  jdStart.jd = firstDay;
  jdEnd.year = endYear;
  jdEnd.jd = endDay;
  jd2date(&jdStart, startStr);
  jd2date(&jdEnd, endStr);
  if (firstYear != endYear || firstDay != endDay)
    sprintf(citation, "%s to %s", startStr, endStr);
  else
    sprintf(citation, "%s", startStr);
  fprintf(fpOutList, "  <root>\n");
  fprintf(fpOutList, "    <Conventions>CF-1.6</Conventions>\n");
  fprintf(fpOutList, "    <institution>Alaska Satellite Facility</institution>\n");
  fprintf(fpOutList, "    <title>Kwok, Ron. 2008. MEaSUREs Small-Scale Kinematics"
    " of Arctic Ocean Sea Ice, Version 01, %s. Jet Propulsion Laboratory "
    "Pasadena, CA USA and Alaska Satellite Facility Fairbanks, AK USA. "
    "Digital media.</title>\n", citation);
  fprintf(fpOutList, "    <source>Products derived from RADARSAT-1 SWB imagery at "
    "100 m resolution</source>\n");
  fprintf(fpOutList, "    <comment>Imagery the products are derived from: Copyright "
    "Canadian Space Agency (1996 to 2008)</comment>\n");
  fprintf(fpOutList, "    <reference>Documentation available at: www.asf.alaska.edu"
    "</reference>\n");
  fprintf(fpOutList, "    <history>%s: netCDF file created.</history>\n", isoStr);
  fprintf(fpOutList, "  </root>\n");
  fprintf(fpOutList, "</netcdf>\n");
  FCLOSE(fpOutList);

  // Generate supplemental files: water mask, lat/lon, x/y grids
  asfPrintStatus("Generating supplemental files ...\n");
  float *floatBuf = (float *) MALLOC(sizeof(float)*sample_count);
  float *maskBuf = (float *) MALLOC(sizeof(float)*sample_count);
  float *latBuf = (float *) MALLOC(sizeof(float)*sample_count);
  float *lonBuf = (float *) MALLOC(sizeof(float)*sample_count);
  float *xBuf = (float *) MALLOC(sizeof(float)*sample_count);
  float *yBuf = (float *) MALLOC(sizeof(float)*sample_count);
  meta = meta_read(metaFile);
  
  fpIn = FOPEN(inFile, "r");
  fgets(header, 100, fpIn);
  sscanf(header, "%f %f %f %f %f %f", &x_pix, &y_pix, &x_map_ll, &y_map_ll, 
    &x_map_ur, &y_map_ur);
  fgets(header, 100, fpIn);
  sscanf(header, "%d %d", &sample_count, &line_count);
  
  FILE *fpMask = FOPEN(maskFile, "wb");
  FILE *fpLat = FOPEN(latFile, "wb");
  FILE *fpLon = FOPEN(lonFile, "wb");
  FILE *fpXgrid = FOPEN(xFile, "wb");
  FILE *fpYgrid = FOPEN(yFile, "wb");
  for (ii=0; ii<line_count; ii++) {
    for (kk=0; kk<sample_count; kk++) {
      ASF_FREAD(&floatBuf[kk], sizeof(float), 1, fpIn);
      ieee_big32(floatBuf[kk]);
    }
    for (kk=0; kk<sample_count; kk++) {
      meta_get_latLon(meta, line_count-ii-1, kk, 0.0, &lat, &lon);
      latlon_to_proj(meta->projection, 'R', lat*D2R, lon*D2R, 0.0, &x, &y, &z);
      latBuf[kk] = lat;
      lonBuf[kk] = lon;
      xBuf[kk] = x;
      yBuf[kk] = y;
      if (floatBuf[kk] < 10000000000.0) {
        maskBuf[kk] = 1.0;
      }
      else if (floatBuf[kk] > 10000000000.0) {
        maskBuf[kk] = 1.0;
      }
      else {
        maskBuf[kk] = 0.0;
      }
    }
    put_float_line(fpMask, meta, line_count-ii-1, maskBuf);
    put_float_line(fpLat, meta, line_count-ii-1, latBuf);
    put_float_line(fpLon, meta, line_count-ii-1, lonBuf);
    put_float_line(fpXgrid, meta, line_count-ii-1, xBuf);
    put_float_line(fpYgrid, meta, line_count-ii-1, yBuf);
  }
  FCLOSE(fpIn);
  FCLOSE(fpMask);
  FCLOSE(fpLat);
  FCLOSE(fpLon);
  FREE(floatBuf);
  FREE(maskBuf);
  FREE(latBuf);
  FREE(lonBuf);
  FREE(xBuf);
  FREE(yBuf);
  meta_write(meta, latFile);
  meta_write(meta, lonFile);
  meta_write(meta, xFile);
  meta_write(meta, yFile);

  // Write ISO meatadata for netCDF
  asfPrintStatus("Generating metadata for netCDF file ...\n");

  char *ncXmlBase = get_basename(outFile);
  char *ncXmlFile = appendExt(outFile, ".xml");
  fpXml = FOPEN(ncXmlFile, "w");
  fprintf(fpXml, "<rgps>\n");
  fprintf(fpXml, "  <granule>%s</granule>\n", ncXmlBase);
  fprintf(fpXml, "  <metadata_creation>%s</metadata_creation>\n", isoStr);
  fprintf(fpXml, "  <metadata>\n");
  fprintf(fpXml, "    <product>\n");
  fprintf(fpXml, "      <file type=\"string\" definition=\"name of product "
    "file\">%s.nc</file>\n", ncXmlBase);
  if (divFlag && vrtFlag && shrFlag)
    fprintf(fpXml, "      <type type=\"string\" definition=\"product type\">"
    "divergence, vorticity, shear</type>\n");
  else if (myrFlag)
    fprintf(fpXml, "      <type type=\"string\" definition=\"product type\">"
    "multiyear ice fraction</type>\n");
  fprintf(fpXml, "      <format type=\"string\" definition=\"name of the data "
    "format\">netCDF</format>\n");

  fpInList = FOPEN(listInFile, "r");
  while (fgets(inFile, 512, fpInList)) {
    chomp(inFile);
    split_dir_and_file(inFile, dirName, baseName);
    fprintf(fpXml, "      <source type=\"string\" definition=\"name of the data"
    " source\">%s</source>\n", baseName);
  }
  FCLOSE(fpInList);

  fprintf(fpXml, "      <cell_size_x type=\"double\" definition=\"cell size "
    "in x direction\" units=\"m\">%.2f</cell_size_x>\n", x_pix*1000.0);
  fprintf(fpXml, "      <cell_size_y type=\"double\" definition=\"cell size "
    "in y direction\" units=\"m\">%.2f</cell_size_y>\n", y_pix*1000.0);
  fprintf(fpXml, "      <map_x_lower_left type=\"double\" definition=\"x "
    "coordinate of lower left corner\" units=\"m\">%.6f</map_x_lower_left>\n",
    x_map_ll*1000.0);
  fprintf(fpXml, "      <map_y_lower_left type=\"double\" definition=\"y "
    "coordinate of lower left corner\" units=\"m\">%.6f</map_y_lower_left>\n",
    y_map_ll*1000.0);
  fprintf(fpXml, "      <map_x_upper_right type=\"double\" definition=\"x "
    "coordinate of upper right corner\" units=\"m\">%.6f</map_x_upper_right>"
    "\n", x_map_ur*1000.0);
  fprintf(fpXml, "      <map_y_upper_right type=\"double\" definition=\"y "
    "coordinate of upper right corner\" units=\"m\">%.6f</map_y_upper_right>"
    "\n", y_map_ur*1000.0);
  fprintf(fpXml, "      <cell_dimension_x type=\"int\" definition=\"cell "
    "dimension in x direction\">%d</cell_dimension_x>\n", 
    sample_count);
  fprintf(fpXml, "      <cell_dimension_y type=\"int\" definition=\"cell "
    "dimension in y direction\">%d</cell_dimension_y>\n",
      line_count);
  fprintf(fpXml, "      <projection_string type=\"string\" definition=\"map "
    "projection information as well known text\">%s</projection_string>\n", 
  meta2esri_proj(meta, NULL));
  fprintf(fpXml, "    </product>\n");
  fprintf(fpXml, "  </metadata>\n");
  fprintf(fpXml, "  <extent>\n");
  fprintf(fpXml, "    <product>\n");
  fprintf(fpXml, "      <westBoundLongitude>%.5f</westBoundLongitude>\n",
    minLon);
  fprintf(fpXml, "      <eastBoundLongitude>%.5f</eastBoundLongitude>\n",
    maxLon);
  fprintf(fpXml, "      <northBoundLatitude>%.5f</northBoundLatitude>\n",
    maxLat);
  fprintf(fpXml, "      <southBoundLatitude>%.5f</southBoundLatitude>\n",
    minLat);
  fprintf(fpXml, "      <start_datetime>%s</start_datetime>\n", first);
  fprintf(fpXml, "      <end_datetime>%s</end_datetime>\n", end);
  fprintf(fpXml, "    </product>\n");
  fprintf(fpXml, "  </extent>\n");
  fprintf(fpXml, "</rgps>\n");
  FCLOSE(fpXml);
  FREE(ncXmlBase);
  FREE(ncXmlFile);
  meta_free(meta);

  // Export to netCDF
  asfPrintStatus("Exporting to netCDF file ...\n");
  export_netcdf_xml(listOutFile, outFile);

  // Clean up
  remove_dir(tmpDir);
  FREE(tmpDir);
  FREE(outFile);
  FREE(listInFile);
  FREE(isoStr);

  return 0;
}
コード例 #15
0
ファイル: meta_check.c プロジェクト: rudigens/ASF_MapReady
int isPolsarproDecomposition(char *dataFile, char **decompositionType,
                                              char **error)
{
  char path[1024], fileName[1024], headerFile[1024], metaFile[1024];
  int decomposition = FALSE;
  if (!dataFile || strlen(dataFile)<=0)
    return FALSE;
  int ii;
  split_dir_and_file(dataFile, path, fileName);
  char *decompositionStr = (char *) MALLOC(sizeof(char)*strlen(dataFile));
  strcpy(decompositionStr, "");
  // check files for Freeman 2 components decomposition
  if (strstr(fileName, "Freeman2_")) {
    strcpy(decompositionStr, "Freeman 2");
    for (ii=0; ii<2; ii++) {
      if (!checkDecompositionFile("Data", path, dataFile,
        freeman2_decomposition[ii],
        decompositionStr,error))
        return FALSE;
      sprintf(headerFile, "%s.hdr", freeman2_decomposition[ii]);
      sprintf(metaFile, "%s.hdr", dataFile);
      if (!checkDecompositionFile("Header", path, metaFile, headerFile,
        decompositionStr, error))
        return FALSE;
    }
    decomposition = TRUE;
  }
  // check files for Freeman 3 components decomposition
  else if (strstr(fileName, "Freeman_")) {
    strcpy(decompositionStr, "Freeman 3");
    for (ii=0; ii<3; ii++) {
      if (!checkDecompositionFile("Data", path, dataFile,
        freeman3_decomposition[ii],
        decompositionStr, error))
        return FALSE;
        sprintf(headerFile, "%s.hdr", freeman3_decomposition[ii]);
        sprintf(metaFile, "%s.hdr", dataFile);
        if (!checkDecompositionFile("Header", path, metaFile, headerFile, 
          decompositionStr, error))
          return FALSE;
    }
    decomposition = TRUE;
  }
  // check files for Van Zyl 3 components decomposition
  else if (strstr(fileName, "VanZyl3_")) {
    strcpy(decompositionStr, "Van Zyl 3");
    for (ii=0; ii<3; ii++) {
      if (!checkDecompositionFile("Data", path, dataFile,
		vanZyl3_decomposition[ii], 
		decompositionStr, error))
        return FALSE;
      sprintf(headerFile, "%s.hdr", vanZyl3_decomposition[ii]);
      sprintf(metaFile, "%s.hdr", dataFile);
      if (!checkDecompositionFile("Header", path, metaFile, headerFile,
        decompositionStr, error))
        return FALSE;
    }
    decomposition = TRUE;
  }
  // check files for Yamaguchi 3 components decomposition
  else if (strstr(fileName, "Yamaguchi3_")) {
    strcpy(decompositionStr, "Yamaguchi 3");
    for (ii=0; ii<3; ii++) {
      if (!checkDecompositionFile("Data", path, dataFile,
        yamaguchi3_decomposition[ii],
        decompositionStr, error))
        return FALSE;
      sprintf(headerFile, "%s.hdr", yamaguchi3_decomposition[ii]);
      sprintf(metaFile, "%s.hdr", dataFile);
      if (!checkDecompositionFile("Header", path, metaFile, headerFile,
        decompositionStr, error))
        return FALSE;
    }
    decomposition = TRUE;
  }
  // check files for Yamaguchi 4 components decomposition
  else if (strstr(fileName, "Yamaguchi4_")) {
    strcpy(decompositionStr, "Yamaguchi 4");
    for (ii=0; ii<4; ii++) {
      if (!checkDecompositionFile("Data", path, dataFile,
        yamaguchi4_decomposition[ii],
        decompositionStr, error))
        return FALSE;
      sprintf(headerFile, "%s.hdr", yamaguchi4_decomposition[ii]);
      sprintf(metaFile, "%s.hdr", dataFile);
      if (!checkDecompositionFile("Header", path, metaFile, headerFile,
        decompositionStr, error))
        return FALSE;
    }
    decomposition = TRUE;
  }
  // check files for Krogager components decomposition
  else if (strstr(fileName, "Krogager_")) {
    strcpy(decompositionStr, "Krogager");
    for (ii=0; ii<3; ii++) {
      if (!checkDecompositionFile("Data", path, dataFile,
        krogager_decomposition[ii], 
        decompositionStr, error))
        return FALSE;
      sprintf(headerFile, "%s.hdr", krogager_decomposition[ii]);
      sprintf(metaFile, "%s.hdr", dataFile);
      if (!checkDecompositionFile("Header", path, metaFile, headerFile, 
		decompositionStr, error))
		return FALSE;
	}
	decomposition = TRUE;
  }
  // check files for Touzi Alpha_s decomposition
  else if (strcmp_case(fileName, "TSVM_alpha_s1.bin") == 0 ||
    strcmp_case(fileName, "TSVM_alpha_s2.bin") == 0 ||
    strcmp_case(fileName, "TSVM_alpha_s3.bin") == 0) {
    strcpy(decompositionStr, "Touzi alpha_s");
    for (ii=0; ii<3; ii++) {
      if (!checkDecompositionFile("Data", path, dataFile,
        touzi1_decomposition[ii],
        decompositionStr, error))
        return FALSE;
      sprintf(headerFile, "%s.hdr", touzi1_decomposition[ii]);
      sprintf(metaFile, "%s.hdr", dataFile);
      if (!checkDecompositionFile("Header", path, metaFile, headerFile,
        decompositionStr, error))
        return FALSE;
    }
    decomposition = TRUE;
  }
  // check files for Touzi Phi_s decomposition
  else if (strcmp_case(fileName, "TSVM_phi_s1.bin") == 0 ||
    strcmp_case(fileName, "TSVM_phi_s2.bin") == 0 ||
    strcmp_case(fileName, "TSVM_phi_s3.bin") == 0) {
    strcpy(decompositionStr, "Touzi phi_s");
    for (ii=0; ii<3; ii++) {
      if (!checkDecompositionFile("Data", path, dataFile,
        touzi2_decomposition[ii],
        decompositionStr, error))
        return FALSE;
      sprintf(headerFile, "%s.hdr", touzi2_decomposition[ii]);
      sprintf(metaFile, "%s.hdr", dataFile);
      if (!checkDecompositionFile("Header", path, metaFile, headerFile,
        decompositionStr, error))
        return FALSE;
    }
    decomposition = TRUE;
  }
  // check files for Touzi Tau_m decomposition
  else if (strcmp_case(fileName, "TSVM_tau_m1.bin") == 0 ||
    strcmp_case(fileName, "TSVM_tau_m2.bin") == 0 ||
    strcmp_case(fileName, "TSVM_tau_m3.bin") == 0) {
    strcpy(decompositionStr, "Touzi tau_m");
    for (ii=0; ii<3; ii++) {
      if (!checkDecompositionFile("Data", path, dataFile,
        touzi3_decomposition[ii],
        decompositionStr, error))
        return FALSE;
        sprintf(headerFile, "%s.hdr", touzi3_decomposition[ii]);
        sprintf(metaFile, "%s.hdr", dataFile);
        if (!checkDecompositionFile("Header", path, metaFile, headerFile,
          decompositionStr, error))
          return FALSE;
    }
    decomposition = TRUE;
  }
  // check files for Touzi Psi decomposition
  else if (strcmp_case(fileName, "TSVM_psi1.bin") == 0 ||
    strcmp_case(fileName, "TSVM_psi2.bin") == 0 ||
	strcmp_case(fileName, "TSVM_psi3.bin") == 0) {
	strcpy(decompositionStr, "Touzi psi");
    for (ii=0; ii<3; ii++) {
      if (!checkDecompositionFile("Data", path, dataFile,
        touzi4_decomposition[ii],
        decompositionStr, error))
        return FALSE;
      sprintf(headerFile, "%s.hdr", touzi4_decomposition[ii]);
      sprintf(metaFile, "%s.hdr", dataFile);
      if (!checkDecompositionFile("Header", path, metaFile, headerFile,
        decompositionStr, error))
        return FALSE;
    }
    decomposition = TRUE;
  }
  // check files for Touzi 4 components decomposition
  else if (strstr(fileName, "TSVM_")) {
    strcpy(decompositionStr, "Touzi 4 components");
    for (ii=0; ii<4; ii++) {
      if (!checkDecompositionFile("Data", path, dataFile,
        touzi5_decomposition[ii],
        decompositionStr, error))
        return FALSE;
      sprintf(headerFile, "%s.hdr", touzi5_decomposition[ii]);
      sprintf(metaFile, "%s.hdr", dataFile);
      if (!checkDecompositionFile("Header", path, metaFile, headerFile,
        decompositionStr, error))
        return FALSE;
    }
    decomposition = TRUE;
  }
  else {
    *error = STRDUP("Decomposition file does not exist.");
  }
  *decompositionType = decompositionStr;
  
  return decomposition;
}