Ejemplo n.º 1
0
void c2p(const char *infile, const char *outfile, 
         int multilook, int banded)
{
  char *meta_name = appendExt(infile, ".meta");
  char *data_name = appendExt(infile, ".img");
  c2p_ext(data_name, meta_name, outfile, multilook, banded);
  FREE(meta_name);
  FREE(data_name);
}
Ejemplo n.º 2
0
int main(int argc, char *argv[])
{
  // Allocate some memory
  char *inFile = (char *) MALLOC(sizeof(char)*512);
  char *outFile = (char *) MALLOC(sizeof(char)*512);

  // Parse command line
  if (argc < 3) {
    printf("Insufficient arguments.\n"); 
    usage(argv[0]);
  }  
  strcpy(inFile, argv[1]);
  strcpy(outFile, argv[2]);
  int grid_line_count = atoi(argv[3]);

  asfSplashScreen (argc, argv);

  // Deal with metadata
  meta_parameters *metaIn = meta_read(inFile);
  meta_parameters *metaOut = meta_read(inFile);
  int nl = metaIn->general->line_count;
  int ns = metaIn->general->sample_count;
  metaOut->general->data_type = ASF_BYTE;
  meta_write(metaOut, outFile);

  // Replace image with grid
  float on_grid = 0.0;
  float off_grid = 255.0;
  float *outLine = (float *) MALLOC(sizeof(float)*ns);
  float *inLine = (float *) MALLOC(sizeof(float)*ns);

  FILE *fpIn = FOPEN(appendExt(inFile, ".img"), "rb");
  FILE *fpOut = FOPEN(appendExt(outFile, ".img"), "wb");
  int ii, kk;;
  for (ii=0; ii<nl; ii++) {
    get_float_line(fpIn, metaIn, ii, inLine);
    for (kk=0; kk<ns; kk++) {
      if (ii == 0 || ii == nl -1 || ii % (ns/grid_line_count) == 0)
	outLine[kk] = on_grid;
      else if (kk % (ns/grid_line_count) == 0)
	outLine[kk] = on_grid;
      else
	outLine[kk] = off_grid;
    }
    outLine[0] = outLine[ns-1] = on_grid;
    put_float_line(fpOut, metaOut, ii, outLine);
    asfLineMeter(ii, nl);
  }

  // Clean up
  FREE(inFile);
  FREE(outFile);
  meta_free(metaIn);
  meta_free(metaOut);

  exit(0);
}
Ejemplo n.º 3
0
int make_gr_dem(meta_parameters *meta_sar, const char *demBase, const char *output_name)
{
  char *demImg = appendExt(demBase, ".img");
  char *demMeta = appendExt(demBase, ".meta");
  int ret = make_gr_dem_ext(meta_sar, demImg, demMeta, 0, .1, output_name, 0);
  FREE(demImg);
  FREE(demMeta);
  return ret;
}
Ejemplo n.º 4
0
int handle_asf_file(const char *filename, char *meta_name, char *data_name,
                    char **err)
{
    char *ext = findExt(filename);
    int has_ext = ext && strlen(ext) > 0;
    int has_asf_ext = has_ext &&
        (strcmp_case(ext,".img")==0 || strcmp_case(ext,".meta")==0);

    // either they gave us an ASF Internal extension, or we try adding it
    // to a user-provided basename, and that file does exist
    if (has_asf_ext || try_ext(filename, ".img"))
    {
        char *m = appendExt(filename, ".meta");
        char *d = appendExt(filename, ".img");

        strcpy(meta_name, m);
        strcpy(data_name, d);

        int ret;
        if (!fileExists(meta_name) || !fileExists(data_name)) {
            int l = sizeof(char)*strlen(filename)*2+255;
            *err = MALLOC(l);
            snprintf(*err, l,
                "Error opening ASF Internal Format file.\n"
                "  Metadata file: %s - %s\n"
                "      Data file: %s - %s\n",
                m, fileExists(m) ? "Found" : "NOT FOUND",
                d, fileExists(d) ? "Found" : "NOT FOUND");

            ret = FALSE;
        }
        else
            ret = TRUE;

        free(m);
        free(d);

        return ret;
    }
    else {
        // in theory this shouldn't happen, if try_ext is working
        assert(!try_ext(filename, ".img"));
        int l = sizeof(char)*strlen(filename)*2+255;
        *err = MALLOC(l);
        snprintf(*err, l,
            "Failed to open %s as an ASF Internal Format File.\n", filename);
        return FALSE;
    }

    // not reached
    assert(FALSE);
    return FALSE;
}
Ejemplo n.º 5
0
int handle_brs_file(const char *filename, char *meta_name, char *data_name,
                    char **err)
{
    char *ext = findExt(filename);
    int has_ext = ext && strlen(ext) > 0;
    int has_brs_ext = has_ext && strcmp_case(ext,".brs")==0;
    char *file;

    if (!has_ext) {
        has_brs_ext = try_ext(filename, ".brs");
        if (!has_brs_ext) {
            has_brs_ext = try_ext(filename, ".BRS");
            if (has_brs_ext)
                file = appendExt(filename, ".BRS");
        }
        else {
            file = appendExt(filename, ".brs");
        }
    }
    else
        file = STRDUP(filename);

    if (has_brs_ext)
    {
        strcpy(meta_name, file);
        strcpy(data_name, file);

        int ret;
        if (!fileExists(data_name)) {
            // I don't think this will actually ever run
            int l = sizeof(char)*strlen(filename)+255;
            *err = MALLOC(l);
            snprintf(*err, l, "Error opening BRS file: %s\n", data_name);
            ret = FALSE;
        }
        else
            ret = TRUE;

        free(file);
        return ret;
    }
    else {
        int l = sizeof(char)*strlen(filename)+255;
        *err = MALLOC(l);
        snprintf(*err, l, "Failed to open %s as a BRS File.\n", filename);
        free(file);
        return FALSE;
    }

    // not reached
    assert(FALSE);
    return FALSE;
}
Ejemplo n.º 6
0
static void clean(const char *file)
{
    if (file)
    {
        char *img_file = appendExt(file, ".img");
        char *meta_file = appendExt(file, ".meta");

        remove_file(img_file);
        remove_file(meta_file);
        remove_file(file);

        free(img_file);
        free(meta_file);
    }
}
Ejemplo n.º 7
0
int child_func(void *params)
{
  child_params_t *cp = (child_params_t *)params;
  c2v_config *cfg = init_fill_c2v_config();

  char *lf = appendExt(cp->out_file, ".log");
  strcpy(logFile, lf);
  free(lf);

  quietflag = FALSE;
  logflag = TRUE;

  fLog = FOPEN(logFile, "a");

  strcpy(cfg->input_file, cp->in_file);
  strcpy(cfg->output_file, cp->out_file);
  strcpy(cfg->input_format, cp->in_format);
  strcpy(cfg->output_format, cp->out_format);
  int ret = convert2vector(cfg);

  asfPrintStatus("Successful completion!\n");

  FCLOSE(fLog);
  return ret==1 ? 0 : 1;
}
Ejemplo n.º 8
0
void FUNCTION c_lsmknm(const char *inname,const char *ext,char *outname)
{
char *newName=appendExt(inname,ext);
strcpy(outname,newName);
free(newName);
return;
}
Ejemplo n.º 9
0
int extExists(const char *name, const char *newExt)
{
  char *fName = appendExt (name,newExt);
  int exists = fileExists (fName);
  free (fName);
  return exists;
}
Ejemplo n.º 10
0
void import_gridfloat(char *inBaseName, char *outBaseName)
{
    int i, j;
    int column_count, row_count;
    char *flt_file = appendExt(inBaseName, ".flt");

    // create the metadata
    char *meta_filename = appendExt(outBaseName, ".meta");

    asfPrintStatus("Building %s ...\n", meta_filename);

    meta_parameters *meta = read_meta_gridfloat_ext(inBaseName, flt_file,
						    &column_count, &row_count);

    meta_write(meta, meta_filename);

    // Now read/write the actual data.  Read as INT16, cast to
    // floats so we can use put_float_line (which will write
    // INT16 data, since we asked for it in the metadata)
    char *data_filename = appendExt(outBaseName, ".img");

    asfPrintStatus("Reading %s, writing %s ...\n", flt_file, data_filename);

    float *floats = MALLOC(sizeof(float)*column_count);
    FILE *fp = FOPEN(flt_file, "rb");
    FILE *out = FOPEN(data_filename, "wb");

    for (i=0; i<row_count; ++i) {
        FREAD(floats, sizeof(float), column_count, fp);
	//if (msbfirst) {
            for (j=0; j<column_count; ++j) {
                big32(floats[j]);
            }
	    //}
        put_float_line(out, meta, i, floats);
        asfLineMeter(i,row_count);
    }

    fclose(fp);
    fclose(out);

    free(data_filename);
    free(floats);

    free(flt_file);
}
Ejemplo n.º 11
0
void renameImgAndMeta(const char *src, const char *dst)
{
    char * src_meta_file = appendExt(src, ".meta");
    char * src_img_file = appendExt(src, ".img");

    char * dst_meta_file = appendExt(dst, ".meta");
    char * dst_img_file = appendExt(dst, ".img");

    fileRename(src_meta_file, dst_meta_file);
    fileRename(src_img_file, dst_img_file);

    free(src_meta_file);
    free(src_img_file);

    free(dst_meta_file);
    free(dst_img_file);
}
Ejemplo n.º 12
0
int handle_terrasar_file(const char *filename, char *meta_name, char *data_name,
			 char **err)
{
  // allocate error buffer, just in case we need it
  *err = (char *) MALLOC(sizeof(char)*1024);
  
  // check for metadata
  if (!fileExists(filename))
    meta_name = appendExt(filename, ".xml");
  else
    strcpy(meta_name, filename);
  if (!fileExists(meta_name)) {
    sprintf(*err, "Error opening TerraSAR-X file, metadata file (%s) does "
	    "not exist!\n", meta_name);
    return FALSE;
  }
  xmlDoc *doc = xmlReadFile(meta_name, NULL, 0);
  if (!doc) {
    sprintf(*err, "Could not parse file %s\n", meta_name);
    return FALSE;
  }
  
  // path from the xml (metadata) file
  char *path = get_dirname(filename);
  if (strlen(path)>0) {
    strcpy(data_name, path);
    if (data_name[strlen(data_name)-1] != '/')
      strcat(data_name, "/");
  }
  else
    strcpy(data_name, "");
  free(path);
  
  // strcat() on the path & file from the XML entry
  strcat(data_name, xml_get_string_value(doc, 
    "level1Product.productComponents.imageData[0].file.location.path"));
  strcat(data_name, "/");
  strcat(data_name, xml_get_string_value(doc, 
    "level1Product.productComponents.imageData[0].file.location.filename"));
  if (!fileExists(data_name)) {
    sprintf(*err, "Data file (%s) does not exist!\n", data_name);
    return FALSE;
  }

  // check data type
  terrasar_meta *terrasar = read_terrasar_meta(meta_name);
  if (!strcmp_case(terrasar->imageDataType, "COMPLEX") == 0 &&
      !strcmp_case(terrasar->imageDataFormat, "COSAR") == 0) {
    sprintf(*err, "Data type (%s) and data format (%s) currently not "
	    "supported!\n", 
	    terrasar->imageDataType, terrasar->imageDataFormat);
    return FALSE;
  }

  FREE(*err);
  err = NULL;
  return TRUE;
}
Ejemplo n.º 13
0
int asf_logscale(const char *inFile, const char *outFile)
{
  int ii, jj, kk;
  meta_parameters *meta = meta_read(inFile);
  int band_count = meta->general->band_count;
  int sample_count = meta->general->sample_count;
  int line_count = meta->general->line_count;
  float *bufIn = (float *) MALLOC(sizeof(float)*sample_count);
  float *bufOut = (float *) MALLOC(sizeof(float)*sample_count);
  
  char *input = appendExt(inFile, ".img");
  char *output = appendExt(outFile, ".img");
  FILE *fpIn = FOPEN(input, "rb");
  FILE *fpOut = FOPEN(output, "wb");
  for (kk=0; kk<band_count; kk++) {
    for (ii=0; ii<line_count; ii++) {
      get_band_float_line(fpIn, meta, kk, ii, bufIn);
      for (jj=0; jj<sample_count; jj++) {
	if (FLOAT_EQUIVALENT(bufIn[jj], 0.0))
	  bufOut[jj] = 0.0;
	else
	  bufOut[jj] = 10.0 * log10(bufIn[jj]);
      }
      put_band_float_line(fpOut, meta, kk, ii, bufOut);
      asfLineMeter(ii, line_count);
    }
  }
  meta_write(meta, outFile);
  meta_free(meta);
  FCLOSE(fpIn);
  FCLOSE(fpOut);
  FREE(bufIn);
  FREE(bufOut);
  FREE(input);
  FREE(output);

  return FALSE;
}
Ejemplo n.º 14
0
int handle_png_file(const char *filename, char *meta_name, char *data_name,
                    char **err)
{
    char *ext = findExt(filename);
    int has_ext = ext && strlen(ext) > 0;
    int has_png_ext = has_ext && strcmp_case(ext,".png")==0;

    if (!has_ext) {
        has_png_ext = try_ext(filename, ".png");
    }

    if (has_png_ext)
    {
        char *d=NULL;
        if (has_ext)
            d = STRDUP(filename);
        else if (has_png_ext)
            d = appendExt(filename, ".png");
        assert(d);

        strcpy(meta_name, d);
        strcpy(data_name, d);
        free(d);

        int ret;
        if (!fileExists(data_name)) {
            // I don't think this will actually ever run
            int l = sizeof(char)*strlen(filename)+255;
            *err = MALLOC(l);
            snprintf(*err, l, "Error opening PNG file: %s\n", data_name);
            ret = FALSE;
        }
        else
            ret = TRUE;

        return ret;
    }
    else {
        // in theory this shouldn't happen, if try_ext is working
        assert(!try_ext(filename, ".png"));
        int l = sizeof(char)*strlen(filename)+255;
        *err = MALLOC(l);
        snprintf(*err, l, "Failed to open %s as a PNG File.\n", filename);
        return FALSE;
    }

    // not reached
    assert(FALSE);
    return FALSE;
}
Ejemplo n.º 15
0
int combine(char **infiles, int n_inputs, char *outfile)
{
  int ret, ii, size_x, size_y;
  double start_x, start_y;
  double per_x, per_y;

  // Determine image parameters
  determine_extents(infiles, n_inputs, &size_x, &size_y, &start_x, &start_y,
		    &per_x, &per_y);
  
  asfPrintStatus("\nCombined image size: %dx%d LxS\n", size_y, size_x);
  asfPrintStatus("  Start X,Y: %f,%f\n", start_x, start_y);
  asfPrintStatus("    Per X,Y: %lg,%lg\n", per_x, per_y);
  
  // float_image will handle cacheing of the large output image
  FloatImage *out = float_image_new(size_x, size_y);
  
  // loop over the input images, last to first, so that the files listed
  // first have their pixels overwrite files listed later on the command line
  for (ii=n_inputs-1; ii>=0; ii--) {
    asfPrintStatus("\nProcessing %s... \n", infiles[ii]);
      
    // Add this image's pixels
    add_pixels(out, infiles[ii], start_x, start_y, per_x, per_y);
  }
  
  asfPrintStatus("Writing metadata.\n");
  
  meta_parameters *meta_out = meta_read(infiles[0]);
  
  meta_out->projection->startX = start_x;
  meta_out->projection->startY = start_y;
  meta_out->general->line_count = size_y;
  meta_out->general->sample_count = size_x;
  
  meta_write(meta_out, outfile);
  meta_free(meta_out);

  char *outfile_full = appendExt(outfile, ".img");
  asfPrintStatus("Saving image (%s).\n", outfile_full);
  ret = float_image_store(out, outfile_full, fibo_be);
  if (ret!=0) 
    asfPrintError("Error storing output image!\n");
  float_image_free(out);
  free(outfile_full);
  
  return ret;
}
Ejemplo n.º 16
0
/***********************************************************
 * meta_is_new_style:
 * Does the metadata file with the given base name exist and
 * conform to the new all-in-one standard?  */
int meta_is_new_style(const char *file_name)
{
 /* Maximum line length.  */
#define MAX_METADATA_LINE 1024
 /* Version where new metadata was adopted.  */
#define NEW_FORMAT_VERSION 1.0
  int return_value = FALSE;   /* Value to be returned.  */
  char *meta_name = appendExt(file_name, ".meta");
  FILE *meta_file = FOPEN(meta_name, "r");
  char              line[MAX_METADATA_LINE]; /* Metadata line.  */
  char version_string[MAX_METADATA_LINE]; /* Actual version string.  */

  /* Scan to the version field and read the actual version number,
     then return the appropriate response.  */
  int return_count = 0;
  char *end_ptr;    /* Used by strtod.  */
  double version;   /* Version as floating point.  */

  if (meta_file != NULL) {
    do {
      if ( fgets(line, MAX_METADATA_LINE, meta_file) == NULL ) {
        err_die("%s function: didn't find Meta version field\n",
                "meta_is_new_style");
      }
      /* Note: whitespace in a scanf conversion matches zero or more
         white space characters, %s matches non-white-space.  */
    } while ( (return_count = sscanf (line, " meta_version: %s \n",
              version_string)) != 1 );
    version = strtod (version_string, &end_ptr);
    if ( *end_ptr != '\0' ) {
        err_die ("%s function: error parsing Meta vesion field\n",
              "meta_is_new_style");
    }
    // If the given version is greater than or equal to our latest meta
    // version then we've got a new style meta file...
    if ( strtod(version_string, &end_ptr)
         >= NEW_FORMAT_VERSION - 0.0002 /* <-- for sloppy float compare */ ) {
      return_value = TRUE;
    }

    FCLOSE(meta_file);            /* Done using meta file directly.  */
  }
  free(meta_name);    /* Done with file name with extension.  */

  return return_value;
}
Ejemplo n.º 17
0
// if a file is a .img file, test it for overlap, otherwise do nothing
static void process_file(const char *file, int level,
                         char *overlapping_dems[], int *next_dem_number,
                         meta_parameters *meta, int *n_dems_total)
{
    char *base = get_filename(file);
    char *ext = findExt(base);
    if (ext && strcmp_case(ext, ".img") == 0)
    {
        char *does;
        ++(*n_dems_total);

        char *meta_filename = appendExt(file, ".meta");
        meta_parameters *meta_dem = meta_read(meta_filename);

        if (meta_dem->general->image_data_type != DEM) {
            does = "Not a DEM";
        } else if (test_overlap(meta, meta_dem)) {
            // overlaps!
            overlapping_dems[*next_dem_number] = STRDUP(file);
            ++(*next_dem_number);
            does = "Overlaps";
        } else {
            does = "No";
        }

        free(meta_filename);
        meta_free(meta_dem);

        asfPrintStatus("  %s%s - %s\n", spaces(level), base, does);
    }
    else if (ext && (strcmp_case(ext, ".meta") == 0 ||
                     strcmp_case(ext, ".ddr") == 0)) {
        // silently ignore the .meta, etc files -- they will be picked up
        // when processing the corresponding .img file
        ;
    }
    else {
        // loudly ignore other stuff in the directory
        asfPrintStatus("  %s%s (ignored)\n", spaces(level), base);
    }
    FREE(base);
}
Ejemplo n.º 18
0
/*********************************
 * outputReplica:
 * writes the given replica to the given file.  */
void outputReplica(const char *replN,iqType *replica,int repLen,
                   float repScale,double iBias,double qBias)
{
    int i,sampleStart;
    FILE *outFile;

/*Skip over zeros at start of pulse replica*/
    sampleStart=0;
    while(
        (fabs(replica[2*sampleStart]-iBias)<1.0)&&
        (fabs(replica[2*sampleStart+1]-qBias)<1.0))
        sampleStart++;

/*Write out the pulse replica.*/
    outFile=FOPEN(appendExt(replN,".replica"),"w");
    fprintf(outFile,"%d   ! Number of samples in reference function; I and Q data follow.\n",repLen-sampleStart);
    for (i=sampleStart;i<repLen;i++)
        fprintf(outFile,"%f\t%f\n",
            repScale*(replica[2*i]-iBias),repScale*(replica[2*i+1]-qBias));
    FCLOSE(outFile);

}
Ejemplo n.º 19
0
static char * find_uavsar_annotation_file(const char *data_file_name)
{
    char *ret = NULL;
    char *after_mission_name = STRDUP(data_file_name + 7);
    char *buf1 = asf_strReplace(after_mission_name, "HH", "");
    char *buf2 = asf_strReplace(buf1, "HV", "");
    char *polarization_stripped = asf_strReplace(buf2, "VV", "");
    char *fixed_name = STRDUP(data_file_name);
    fixed_name[7] = '\0';
    strcat(fixed_name, polarization_stripped);
    char *ann_try = appendExt(fixed_name, ".ann");
    if (fileExists(ann_try)) {
        ret = STRDUP(ann_try);
    }
    FREE(fixed_name);
    FREE(ann_try);
    FREE(polarization_stripped);
    FREE(buf2);
    FREE(buf1);
    FREE(after_mission_name);
    return ret;
}
Ejemplo n.º 20
0
void process()
{
  clear_results_message();

  child_params_t *cp = MALLOC(sizeof(child_params_t));
  strcpy(cp->in_file, get_string_from_entry("input_file_entry"));

  char *odir = get_string_from_entry("output_directory_entry");
  char *ofile = get_string_from_entry("output_file_entry");

  if (strlen(odir) > 0) {
#ifdef win32
    if (odir[strlen(odir)-1]=='/' || odir[strlen(odir)-1]=='\\')
#else
    if (odir[strlen(odir)-1]=='/')
#endif
      sprintf(cp->out_file, "%s%s", odir, ofile);
    else
      sprintf(cp->out_file, "%s/%s", odir, ofile);
  }
  else {
    strcpy(cp->out_file, ofile);
  }

  if (strlen(cp->in_file)==0) {
    message_box("No input file specified!");
    free(cp);
    return;
  }
  else if (strlen(cp->out_file)==0) {
    message_box("No output file selected!");
    free(cp);
    return;
  }
  else if (!fileExists(cp->in_file)) {
    message_box("Input file \"%s\" not found!", cp->in_file);
    free(cp);
    return;
  }

  int input_format = get_combo_box_item("input_format_combobox");
  int output_format = get_combo_box_item("output_format_combobox");

  if (input_format==INPUT_AUTO) {
    select_defaults_by_file_type(cp->in_file, FALSE);
    input_format = get_combo_box_item("input_format_combobox");
    if (input_format==INPUT_AUTO) {
      message_box("Can't figure out which type of data this is.\n"
                  "Please select the input format manually.");
      free(cp);
      return;
    }
  }

  strcpy(cp->in_format, input_format_to_str(input_format));
  strcpy(cp->out_format, output_format_to_str(output_format));
  char *logFile = appendExt(cp->out_file, ".log");

#ifdef win32
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    memset(&si, 0, sizeof(si));
    memset(&pi, 0, sizeof(pi));
    si.cb = sizeof(si);
    
    char *cmd = MALLOC(sizeof(char)*
        (strlen(cp->in_file) + strlen(cp->out_file) + strlen(get_asf_bin_dir_win()) + 512));
    sprintf(cmd,
        "\"%s/convert2vector.exe\" "
        "-log \"%s\" "
        "-input-format %s -output-format %s \"%s\" \"%s\"",
        get_asf_bin_dir_win(),
        logFile,
        cp->in_format, cp->out_format, cp->in_file, cp->out_file);

    // clear out any previously existing log file
    fLog = fopen(logFile, "a");
    FCLOSE(fLog);

    if (!CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
    {
        DWORD dw = GetLastError();
        //printf( "CreateProcess failed (%ld)\n", dw );

        LPVOID lpMsgBuf;
        FormatMessage(
          FORMAT_MESSAGE_ALLOCATE_BUFFER |
          FORMAT_MESSAGE_FROM_SYSTEM |
          FORMAT_MESSAGE_IGNORE_INSERTS,
          NULL,
          dw,
          MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),
          (LPTSTR)&lpMsgBuf,
          0,
          NULL);

        printf("CreateProcess() failed with error %ld: %s\n",
            dw, (char*)lpMsgBuf);
        printf("Failed command: %s\n", cmd);
    }

    DWORD dwWaitResult;

    // now wait for process to finish
    do {
        while (gtk_events_pending())
            gtk_main_iteration();
        dwWaitResult = WaitForSingleObject(pi.hProcess, 50);
    }
    while (dwWaitResult == WAIT_TIMEOUT);
#else
  asfFork(child_func, (void*)cp, parent_func, NULL);
#endif

  char message[1024];
  strcpy(message, "-");

  int success=FALSE;
  FILE *lfp = fopen(logFile, "r");
  if (!lfp) {
    sprintf(message, "Error Opening Log File '%s': %s\n",
            logFile, strerror(errno));
  }
  else {
    char *output = NULL;
    char line[1024];
    while (fgets(line, 1024, lfp)) {
      if (output) {
        output = realloc(output, sizeof(char)*(strlen(output)+strlen(line)+1));
        strcat(output, line);
      }
      else {
        output = malloc(sizeof(char)*(strlen(line)+1));
        strcpy(output, line);
      }
    }
    fclose(lfp);
    //unlink(logFile);

    char *p = output, *q;
    while (p) {
      q = strchr(p+1, '\n');
      if (q) {
        *q = '\0';
        if (strstr(p, "Error")!=NULL || strstr(p, "ERROR")!=NULL) {
          *q = '\n';
          int i,n = 0;
          do {
            p = q + 1;
            q = strchr(p, '\n') - 1;
            while (isspace(*q)) --q;
            if (q - p > 2) {
              // First 220 characters of the error string, unless line ends
              // first.  Don't cut off in the middle of a word, though
              strcpy(message, "Error: ");
              strncat(message, p, 220);
              while (isalnum(message[strlen(message)-1]))
                message[strlen(message)-1] = '\0';
              for (n=0; n<strlen(message); ++n)
                if (message[n] == '\n' || message[n] == '*') message[n] = ' ';
              int eating=FALSE;
              for (n=0,i=0; n<strlen(message); ++n) {
                if (isspace(message[n])) {
                  if (!eating) {
                    eating=TRUE;
                    message[i++] = message[n];
                  }
                } else {
                  eating=FALSE;
                  message[i++] = message[n];
                }
              }
              message[i]='\0';
              char *eoe = strstr(message, "End of error");
              if (eoe)
                *eoe = '\0';
              else if (strlen(message)>200)
                strcat(message, " ...");
              break;
            }
          }
          while (*p != '*' && ++n<5); // * flags the end of the error message
        }

        if (strstr(p,"Successful completion!") != NULL) {
          strcpy(message, "Processed successfully!");
          success=TRUE;
          break;
        }

        *q = '\n';
      }
      p=q;
    }

    if (strlen(message)==0) {
      // Did not find an error message, or the success message!
      // So, assume there was an error, but we don't know why
      strcpy(message, "Processing failed!");
    }

    FREE(output);
  }

  int open_output = get_checked("open_output_checkbutton");
  if (!success) open_output = FALSE;

  put_string_to_label("result_label", message);
  asfPrintStatus(message);
  asfPrintStatus("\n\nDone.\n\n");

  if (open_output) {
    switch (output_format) {
      case OUTPUT_KML:
        open_in_google_earth(cp->out_file);
        break;
      case OUTPUT_ALOS_CSV:
        open_in_excel(cp->out_file);
      default:
        // do nothing, output type has no natural associated app
        break;
    }
  }

  free(cp);
}
Ejemplo n.º 21
0
void deskew(const char *infile, const char *outfile)
{
    meta_parameters *meta = meta_read(infile);

    int nl = meta->general->line_count;
    int np = meta->general->sample_count;
    int nb = meta->general->band_count;
    char **band_name = extract_band_names(meta->general->bands, nb);
    int band, line, samp, deskewed = meta->sar->deskewed != 0;

    if (!meta->sar)
        asfPrintError("Cannot deskew data without a sar block!\n");

    char *tmp_outfile;
    int do_rename = FALSE;
    if (strcmp(infile, outfile) == 0 && nb>1) {
        // user wants to deskew in-place
        // we can't actually do that on multi-band data, too much to keep in memory
        // use a temporary file, then clobber input file
        tmp_outfile = appendToBasename(outfile, "_tmp");
        do_rename = TRUE;
    } else {
        // normal case: either
        // 1) single-band in-place deskew
        // 2) not in-place deskew (single or multi)
        tmp_outfile = STRDUP(outfile);
    }

    // calculate the amount of shift necessary
    double fac = calc_shift(meta, 0, 0);
    // Not sure if we need this or not...
    //fac *= meta->general->x_pixel_size / meta->general->y_pixel_size;

    // the "lower" array stores the required shifts, indexed by column
    // (the amount of shift is row-independent)
    int *lower = MALLOC(np * sizeof(int));
    for (samp=0; samp<np; ++samp)
        lower[samp] = (int) floor(fac*(double)samp);

    if (meta->sar->deskewed) {
        asfPrintStatus("Data is already deskewed.\n");
    } else {
        asfPrintStatus("Far-range shift amount: ");
        if (lower[np-1] > 0)
            asfPrintStatus("%d pixels down.\n", lower[np-1]);
        else
            asfPrintStatus("%d pixels up.\n", -lower[np-1]);
    }

    float *ibuf = MALLOC(np * sizeof(float));
    float *obuf = CALLOC(np*nl, sizeof(float));

    FILE *fpi = fopenImage(infile, "rb");

    for (band=0; band<nb; ++band) {
        if (nb>1)
            asfPrintStatus("Deskewing band: %s\n", band_name[band]);

        // apply deskewing to this band
        for (line=0; line<nl; ++line) {
            get_float_line(fpi, meta, line + nl*band, ibuf);

            for (samp=0; samp<np; ++samp) {
                int out_line = deskewed ? line : line + lower[samp];
                if (out_line >= 0 && out_line < nl)
                    obuf[out_line*np+samp] = ibuf[samp];
            }

            asfLineMeter(line,nl);
        }

        // write out this band
        FILE *fpo = fopenImage(tmp_outfile, band>0 ? "ab" : "wb");
        put_float_lines(fpo, meta, band*nl, nl, obuf);
        FCLOSE(fpo);
    }

    FCLOSE(fpi);
    FREE(obuf);
    FREE(ibuf);
    FREE(lower);

    // if we output to a temporary file, clobber the input
    if (do_rename) {
        char *tmp_outfile_img = appendExt(tmp_outfile, ".img");
        char *outfile_img = appendExt(outfile, ".img");
        //printf("Renaming: %s -> %s\n", tmp_outfile_img, outfile_img);
        rename(tmp_outfile_img, outfile_img);
        FREE(tmp_outfile_img);
        FREE(outfile_img);
    }
    FREE(tmp_outfile);

    // only need to update the deskewed flag in the metadata
    meta->sar->deskewed = 1;
    meta_write(meta, outfile);
    meta_free(meta);
}
Ejemplo n.º 22
0
static int save_as_asf(ImageInfo *ii,
                       const char *out_file, int what_to_save,
                       int strict_boundary, int load)
{
    // See if we can open the output file up front
    FILE *outFp = fopen(out_file, "wb");
    if (!outFp) {
        // failed to open the output file!
        char errbuf[1024];
        snprintf(errbuf, 1024, "Failed to open %s: %s", out_file,
            strerror(errno));
        message_box(errbuf);
        strcat(errbuf, "\n");
        printf("%s", errbuf);
        return FALSE; // failure
    }

    assert (g_poly->n > 0);
    assert (crosshair_line > 0 && crosshair_samp > 0);

    meta_parameters *meta = ii->meta;

    // figure out where to chop
    int line_min, line_max, samp_min, samp_max, nl, ns;
    compute_extent(meta, &line_min, &line_max, &samp_min, &samp_max,
        &nl, &ns);

    // generate metadata
    char *out_metaname = appendExt(out_file, ".meta");
    printf("Generating %s...\n", out_metaname);

    // data will be saved as floating point, except scaled pixel values,
    // which we can make bytes.
    data_type_t data_type = REAL32;
    if (what_to_save == SCALED_PIXEL_VALUE)
      data_type = ASF_BYTE;

    meta_parameters *out_meta =
      build_metadata(meta, out_file, nl, ns, line_min, samp_min, data_type,
                     what_to_save);

    // put_float_line() will always dump BYTE data if the optical block
    // is present... we want to be in control of the data type, so we must
    // wipe out this block
    if (out_meta->optical) {
      FREE(out_meta->optical);
      out_meta->optical=NULL;
    }

    if (what_to_save == LAT_LON_2_BAND) {
      out_meta->general->band_count = 2;
      strcpy(out_meta->general->bands, "LAT,LON");
    }

    // define clipping region, if necessary
    double xp[MAX_POLY_LEN+2], yp[MAX_POLY_LEN+2];
    int i,j,n=0;

    if (strict_boundary)
        define_clipping_region(meta, &n, xp, yp);

    float ndv = 0;
    if (meta_is_valid_double(out_meta->general->no_data))
        ndv = out_meta->general->no_data;
    else if (strict_boundary) // need to set a no data value in this case
        out_meta->general->no_data = 0.;

    meta_write(out_meta, out_metaname);

    // now actually write the data
    printf("Generating %s...\n", out_file);

    if (what_to_save == LAT_LON_2_BAND) {
      // dump a 2-band image, lat & lon data
      float *lats = MALLOC(sizeof(float)*ns);
      float *lons = MALLOC(sizeof(float)*ns);
      for (i=0; i<nl; ++i) {
        int l = line_min+i;
        for (j=0; j<ns; ++j) {
            int s = samp_min+j;
            if (!strict_boundary || pnpoly(n, xp, yp, s, l)) {
                double lat, lon;
                meta_get_latLon(meta, l, s, 0, &lat, &lon);
                lats[j] = (float)lat;
                lons[j] = (float)lon;
            }
            else {
                lats[j] = ndv;
                lons[j] = ndv;
            }
        }
        put_band_float_line(outFp, out_meta, 0, i, lats);
        put_band_float_line(outFp, out_meta, 1, i, lons);
        asfLineMeter(i,nl);
      }
      free(lats);
      free(lons);
    }
    else {
      // normal case
      float *buf = MALLOC(sizeof(float)*ns);
      for (i=0; i<nl; ++i) {
        int l = line_min+i;
        for (j=0; j<ns; ++j) {
            int s = samp_min+j;
            float val;
            if (!strict_boundary || pnpoly(n, xp, yp, s, l)) {
                val = get_data(ii, what_to_save, l, s);
            }
            else {
                val = ndv;
            }
            buf[j] = val;
        }
        put_float_line(outFp, out_meta, i, buf);
        asfLineMeter(i,nl);
      }
      free(buf);
    }
    fclose(outFp);
    meta_free(out_meta);

    // load the generated file if we were told to
    if (load)
        load_file(out_file);

    return TRUE;
}
Ejemplo n.º 23
0
int open_google_earth()
{
    char *kml_filename = appendExt(curr->filename, ".kml");

    char *basename = get_basename(curr->filename);
    char *dirname = get_dirname(curr->filename);

    char *arg;
    if (strlen(dirname)==0) {
        char *tmpdir = g_get_current_dir();
        dirname = escapify(tmpdir);
        arg = MALLOC(sizeof(char)*(strlen(dirname)+strlen(kml_filename)+20));
        sprintf(arg, "%s/%s", dirname, kml_filename);
        //free(tmpdir);
    }
    else {
        arg = STRDUP(kml_filename);
    }

    char *png_file = appendExt(arg, ".png");

    printf("png file: %s\n", png_file);
    printf("Temporary kml file: %s\n", arg);

    FILE *kml_file = fopen(arg, "w");
    if (!kml_file)
    {
        asfPrintWarning("Couldn't open kml file!\n");        
        return FALSE;
    }

    dbf_header_t *dbf;
    int nAttr, nCoords;
    double *lat, *lon, center_lat, center_lon;
    char configFile[255], *name;
    meta_parameters *meta;

    sprintf(configFile, "%s/convert2vector.config", get_asf_share_dir());
    c2v_config *cfg = read_c2v_config(configFile);

    kml_header(kml_file);

    meta = meta2vector(curr->filename, &dbf, &nAttr, &lat, &lon, &nCoords);
    //meta_parameters *meta = curr->meta;
    if (meta && meta->general &&
        meta_is_valid_double(meta->general->center_latitude) &&
        meta_is_valid_double(meta->general->center_longitude))
    {
        pixbuf2png(pixbuf_small, png_file);
        //kml_entry_with_overlay(kml_file, meta, basename, png_file, dirname);
        name = get_basename(kml_filename);
        center_lat = meta->general->center_latitude;
        center_lon = meta->general->center_longitude;
        write_kml_placemark(kml_file, name, center_lat, center_lon, png_file, 
          dbf, nAttr, lat, lon, nCoords, cfg);
        FREE(lat);
        FREE(lon);
        FREE(dbf);
    }
    else
    {
        asfPrintWarning(
            "Failed, metadata doesn't contain valid lat/lon info.\n");
        return FALSE;
    }

    kml_footer(kml_file);
    fclose(kml_file);

    gchar *ge;

    printf("kml: %s\n", kml_filename);
    printf("dir: %s\n", dirname);

#ifdef win32
    char path[1024];
    FindExecutable((LPCTSTR)kml_filename, (LPCTSTR)dirname, (LPTSTR)path);
    ge = escapify(path);
    printf("Path to google earth: %s\n", ge);
    
    asfSystem("\"%s\" \"%s\"", ge, arg);
#else
    ge = find_in_path("googleearth");
    if (!ge)
    {
       message_box("Couldn't find googleearth! Is it installed?");
       return FALSE;
    }

    int pid = fork();
    if (pid == 0) {
        asfSystem("\"%s\" \"%s\"", ge, arg);
        //unlink(kml_filename);
        exit(EXIT_SUCCESS);
    }
#endif

    free(kml_filename);
    free(basename);
    free(dirname);
    free(arg);

    return TRUE;
}
Ejemplo n.º 24
0
/***************************************************************
 * meta_read:
 * Reads a meta file and returns a meta structure filled with
 * both old backward compatability and new fields filled in.
 * Note that the appropriate extension is appended to the given
 * base name automagically if needed.  */
meta_parameters *meta_read(const char *inName)
{
  char              *meta_name      = appendExt(inName,".meta");
  char              *ddr_name       = appendExt(inName,".ddr");
  meta_parameters   *meta           = raw_init(); /* Allocate and initialize basic structs */
  char **junk=NULL;
  int junk2, ii;

  /* Read file with appropriate reader for version.  */
  if ( !fileExists(meta_name) && fileExists(ddr_name)) {

    meta_read_only_ddr(meta, ddr_name);
/*    printf("WARNING: * Unable to locate '%s';\n"
           "         * Using only '%s' for meta data;\n"
           "         * Errors due to lack of meta data are very likely.\n",
     meta_name, ddr_name);*/
  }
  else if ( fileExists(meta_name) ) {
    if ( !meta_is_new_style(meta_name) ) {
      meta_read_old(meta, meta_name);
    }
    else {
      parse_metadata(meta, meta_name);
    }
  }
  // Generate metadata if CEOS files could be detected
  else if (require_ceos_metadata(inName,&junk,&junk2) != NO_CEOS_METADATA) {
    ceos_init(inName, meta, REPORT_LEVEL_STATUS);
  }

  /* Remember the name and location of the meta struct */
  //add_meta_ddr_struct(inName, meta, NULL);
  
  // Add latlon block if data has a data has lat/lon bands
  // Currently only SMAP data has that kind of arrangement
  int lat_band = 
    get_band_num(meta->general->bands, meta->general->band_count, "LAT");
  int lon_band =
    get_band_num(meta->general->bands, meta->general->band_count, "LON");
  if (strcmp_case(meta->general->sensor, "SMAP") == 0 && 
      lat_band > 0 && lon_band > 0) {
    char *data_name = appendExt(inName, ".img");
    if (fileExists(data_name)) {
      meta->latlon = meta_latlon_init(meta->general->line_count, 
				      meta->general->sample_count);
      FILE *fp = FOPEN(data_name, "rb");
      get_band_float_lines(fp, meta, lat_band, 0, meta->general->line_count,
			   meta->latlon->lat);
      get_band_float_lines(fp, meta, lon_band, 0, meta->general->line_count,
			   meta->latlon->lon);
      FCLOSE(fp);
    }
    FREE(data_name);
  }

  FREE(ddr_name);
  FREE(meta_name);
  free_ceos_names(NULL, junk);

  return meta;
}
Ejemplo n.º 25
0
static void add_to_stack(char *out, int band, char *file,
                         int size_x, int size_y,
                         double start_x, double start_y,
                         double per_x, double per_y, int multiband)
{
    meta_parameters *metaIn = meta_read(file);
    meta_parameters *metaOut = meta_read(out);
    char *base = (char *) MALLOC(sizeof(char)*512);
    int start_line, start_sample;

    // this should work even if per_x / per_y are negative...
    start_sample = (int) ((start_x - metaIn->projection->startX) / per_x + .5);
    start_line = (int) ((start_y - metaIn->projection->startY) / per_y + .5);

    int ns = metaIn->general->sample_count;
    int nl = metaIn->general->line_count;

    asfPrintStatus("  Location in stacked image is S:%d-%d, L:%d-%d\n",
        start_sample, start_sample + size_x,
        start_line, start_line + size_y);

    if (start_sample + size_x > ns || start_line + size_y > nl) {
        asfPrintError("Image extents were not calculated correctly!\n");
    }

    FILE *fpIn = FOPEN(file, "rb");
    FILE *fpOut;
    char *metaFile = appendExt(out, ".meta");
    if (band > 0 || !multiband) {
      fpOut = FOPEN(out, "ab");
      sprintf(base, ",%s", get_basename(file));
      strcat(metaOut->general->bands, base);
    }
    else {
      fpOut = FOPEN(out, "wb");
      sprintf(base, "%s", get_basename(file));
      strcpy(metaOut->general->bands, base);
    }
    if (multiband)
      metaOut->general->band_count = band + 1;
    else
      metaOut->general->band_count = 1;
    meta_write(metaOut, metaFile);
    float *line = MALLOC(sizeof(float)*size_x);

    int y;
    for (y=start_line; y<start_line+size_y; ++y) {
      get_partial_float_line(fpIn, metaIn, y, start_sample, size_x, line);
      if (multiband) 
	put_band_float_line(fpOut, metaOut, band, y-start_line, line); 
      else
	put_float_line(fpOut, metaOut, y-start_line, line); 
      asfLineMeter(y, start_line+size_y);
    }

    FCLOSE(fpIn);
    FCLOSE(fpOut);
    FREE(line);
    FREE(metaFile);
    FREE(base);
    meta_free(metaIn);
    meta_free(metaOut);
}
Ejemplo n.º 26
0
/***************************************************************
 * meta_read_old:
 * Reads in old style meta file and fills new style meta struct
 * Note that the appropriate extension is appended to the given
 * base name automagically.  */
void meta_read_old(meta_parameters *meta, char *fileName)
{
  char *ddrName = appendExt(fileName,".ddr");
  struct DDR ddr;
  char *metaName = appendExt(fileName,".meta");
  meta_general *general = meta->general;
  meta_sar     *sar     = meta->sar;
  coniStruct   *coni    = coniOpen(metaName, asciiIn);

/* Fields that cannot be filled from the old structures */
  general->frame            = 0;
  general->band_count       = 1;
  general->center_latitude  = MAGIC_UNSET_DOUBLE;
  general->center_longitude = MAGIC_UNSET_DOUBLE;
  general->missing_lines    = -999999999;

/* Read old style meta file */
  coniIO_double(coni,"","meta_version:",&meta->meta_version,"ASF Metadata File.\n");

/*Geolocation parameters.*/
  coniIO_structOpen(coni,"geo {","begin parameters used in geolocating the image.");
  coniIO_char(coni,"geo.","type:",&sar->image_type,"Image type: [S=slant range; G=ground range; P=map projected]");
  if (sar->image_type=='P') {
  /*Projection Parameters.*/
    char projection_type[256];
    meta_projection *projection = meta->projection = meta_projection_init();
    coniIO_structOpen(coni,"proj {","Map Projection parameters");
    coniIO_str  (coni,"geo.proj.","type:",  projection_type,  "Projection Type: [U=utm; P=ps; L=Lambert; A=at/ct]");
    if ( !strcmp(projection_type, "UNIVERSAL_TRANSVERSE_MERCATOR") )
      projection->type = UNIVERSAL_TRANSVERSE_MERCATOR;
    else if ( !strcmp(projection_type, "POLAR_STEREOGRAPHIC") )
      projection->type = POLAR_STEREOGRAPHIC;
    else if ( !strcmp(projection_type, "ALBERS_EQUAL_AREA") )
      projection->type = ALBERS_EQUAL_AREA;
    else if ( !strcmp(projection_type, "LAMBERT_CONFORMAL_CONIC") )
      projection->type = LAMBERT_CONFORMAL_CONIC;
    else if ( !strcmp(projection_type, "LAMBERT_AZIMUTHAL_EQUAL_AREA") )
      projection->type = LAMBERT_AZIMUTHAL_EQUAL_AREA;
    else if ( !strcmp(projection_type, "STATE_PLANE") )
      projection->type = STATE_PLANE;
    else if ( !strcmp(projection_type, "SCANSAR_PROJECTION") )
      projection->type = SCANSAR_PROJECTION;
    else if ( !strcmp(projection_type, "U") )
      projection->type = UNIVERSAL_TRANSVERSE_MERCATOR;
    else if ( !strcmp(projection_type, "P") )
      projection->type = POLAR_STEREOGRAPHIC;
    else if ( !strcmp(projection_type, "L") )
      projection->type = LAMBERT_CONFORMAL_CONIC;
    else if ( !strcmp(projection_type, "A") )
      projection->type = SCANSAR_PROJECTION;
    else if ( !strcmp(projection_type, "G") )
      projection->type = LAT_LONG_PSEUDO_PROJECTION;
    else  projection->type = -1;
    coniIO_double(coni,"geo.proj.","startX:",&projection->startX,"Projection Coordinate at top-left, X direction");
    coniIO_double(coni,"geo.proj.","startY:",&projection->startY,"Projection Coordinate at top-left, Y direction");
    coniIO_double(coni,"geo.proj.","perX:",  &projection->perX,  "Projection Coordinate per pixel, X direction");
    coniIO_double(coni,"geo.proj.","perY:",  &projection->perY,  "Projection Coordinate per pixel, Y direction");
    coniIO_char  (coni,"geo.proj.","hem:",   &projection->hem,   "Hemisphere: [N=northern hemisphere; S=southern hemisphere]");
    if (meta->meta_version>0.8) {
    /*Read geoid from file*/
      coniIO_double(coni,"geo.proj.","re_major:",&projection->re_major,"Major (equator) Axis of earth (meters)");
      coniIO_double(coni,"geo.proj.","re_minor:",&projection->re_minor,"Minor (polar) Axis of earth (meters)");
    } else {
    /*Default: use the GEM-06 (Goddard Earth Model 6) Ellipsoid*/
      projection->re_major=6378144.0;
      projection->re_minor=6356754.9;
    }
    switch(projection->type) {
    case SCANSAR_PROJECTION:
      coniIO_double(coni,"geo.proj.","rlocal:",     &projection->param.atct.rlocal,"Local earth radius [m]");
      coniIO_double(coni,"geo.proj.","atct_alpha1:",&projection->param.atct.alpha1,"at/ct projection parameter");
      coniIO_double(coni,"geo.proj.","atct_alpha2:",&projection->param.atct.alpha2,"at/ct projection parameter");
      coniIO_double(coni,"geo.proj.","atct_alpha3:",&projection->param.atct.alpha3,"at/ct projection parameter");
      break;
    case LAMBERT_CONFORMAL_CONIC:
      coniIO_double(coni,"geo.proj.","lam_plat1:",&projection->param.lamcc.plat1,"Lambert first standard parallel");
      coniIO_double(coni,"geo.proj.","lam_plat2:",&projection->param.lamcc.plat2,"Lambert second standard parallel");
      coniIO_double(coni,"geo.proj.","lam_lat:",  &projection->param.lamcc.lat0, "Lambert original latitude");
      coniIO_double(coni,"geo.proj.","lam_lon:",  &projection->param.lamcc.lon0, "Lambert original longitude");
      break;
    case POLAR_STEREOGRAPHIC:
      coniIO_double(coni,"geo.proj.","ps_lat:",&projection->param.ps.slat,"Polar Stereographic reference Latitude");
      coniIO_double(coni,"geo.proj.","ps_lon:",&projection->param.ps.slon,"Polar Stereographic reference Longitude");
      break;
    case UNIVERSAL_TRANSVERSE_MERCATOR:
      coniIO_int(coni,"geo.proj.","utm_zone:",&projection->param.utm.zone,"UTM Zone Code");
      break;
    case LAT_LONG_PSEUDO_PROJECTION:
      break;
    // The following several cases get rid of compiler warnings
                case ALBERS_EQUAL_AREA:
                case LAMBERT_AZIMUTHAL_EQUAL_AREA:
                case STATE_PLANE:
                case UNKNOWN_PROJECTION:
                default:
                  break;
    /*
    default:
      printf("ERROR! Unrecognized map projection code '%c!'\n",projection->type);
      exit(1);
    */
    }
    coniIO_structClose(coni,"end proj");
  }
  coniIO_char(coni,"geo.","lookDir:",       &sar->look_direction,         "SAR Satellite look direction (normally R) [R=right; L=left]");
  coniIO_int(coni,"geo.","deskew:",         &sar->deskewed,               "Image moved to zero doppler? [1=yes; 0=no]");
  coniIO_double(coni,"geo.","xPix:",        &general->x_pixel_size,       "Pixel size in X direction [m]");
  coniIO_double(coni,"geo.","yPix:",        &general->y_pixel_size,       "Pixel size in Y direction [m]");
  coniIO_double(coni,"geo.","rngPixTime:",  &sar->range_time_per_pixel,   "Time/pixel, range (xPix/(c/2.0), or 1/fs) [s]");
  coniIO_double(coni,"geo.","azPixTime:",   &sar->azimuth_time_per_pixel, "Time/pixel, azimuth (yPix/swathVel, or 1/prf) [s]");
  coniIO_double(coni,"geo.","slantShift:",  &sar->slant_shift,            "Error correction factor, in slant range [m]");
  coniIO_double(coni,"geo.","timeShift:",   &sar->time_shift,             "Error correction factor, in time [s]");
  coniIO_double(coni,"geo.","slantFirst:",  &sar->slant_range_first_pixel,"Slant range to first image pixel [m]");
  coniIO_double(coni,"geo.","wavelength:",  &sar->wavelength,             "SAR Carrier Wavelength [m]");
  coniIO_double(coni,"geo.","dopRangeCen:", &sar->range_doppler_coefficients[0],  "Doppler centroid [Hz]");
  coniIO_double(coni,"geo.","dopRangeLin:", &sar->range_doppler_coefficients[1],  "Doppler per range pixel [Hz/pixel]");
  coniIO_double(coni,"geo.","dopRangeQuad:",&sar->range_doppler_coefficients[2],  "Doppler per range pixel sq. [Hz/(pixel^2)]");
  coniIO_double(coni,"geo.","dopAzCen:",    &sar->azimuth_doppler_coefficients[0],"Doppler centroid [Hz]");
  coniIO_double(coni,"geo.","dopAzLin:",    &sar->azimuth_doppler_coefficients[1],"Doppler per azimuth pixel [Hz/pixel]");
  coniIO_double(coni,"geo.","dopAzQuad:",   &sar->azimuth_doppler_coefficients[2],"Doppler per azimuth pixel sq. [Hz/(pixel^2)]");
  coniIO_structClose(coni,"end geo\n");

/*Interferometry parameters:*/
  coniIO_structOpen(coni,"ifm {","begin interferometry-related parameters");
  coniIO_double(coni,"ifm.","er:",&sar->earth_radius,"Local earth radius [m]");
  coniIO_double(coni,"ifm.","ht:",&sar->satellite_height,"Satellite height, from center of earth [m]");
  if (meta->meta_version>0.6)
    coniIO_int(coni,"ifm.","nLooks:",&sar->azimuth_look_count,           "Number of looks to take from SLC");
  coniIO_int(coni,"ifm.","orig_lines:",    &sar->original_line_count,  "Number of lines in original image");
  coniIO_int(coni,"ifm.","orig_samples:",  &sar->original_sample_count,"Number of samples in original image");
  coniIO_structClose(coni,"end ifm\n");

/*State Vectors:*/
  { /*Check to see if the state vectors even exist.*/
      int err,nVec;
      nVec=coniInt(coni,"state.number:",&err);
      coniReopen(coni);/*Seek back to beginning of file.*/
      if (err==CONI_OK && nVec!=0) {
      /*We have state vectors!*/
        meta->state_vectors = meta_state_vectors_init(nVec); /*Allocate state vectors.*/
        meta_io_state(coni, meta->state_vectors);  /*And initialize them.*/
      }
  }

/*Extra Info:*/
  { /* Check to see if extra info exists.*/
      int err;
      coniStr(coni,"extra.sensor:",&err);
      coniReopen(coni);/*Seek back to beginning of file.*/
      if (err==CONI_OK) {
    coniIO_str     (coni,"extra.","sensor:",       general->sensor,           "Imaging sensor");
    if (meta->meta_version>0.7)
      coniIO_str   (coni,"extra.","mode:",         general->mode,             "Imaging mode");
    if (meta->meta_version>0.6)
      coniIO_str   (coni,"extra.","processor:",    general->processor,        "Name & Version of SAR Processor");
    if (meta->meta_version>0.7) {
      coniIO_int   (coni,"extra.","orbit:",       &general->orbit,            "Orbit Number for this datatake");
      coniIO_double(coni,"extra.","bitErrorRate:",&general->bit_error_rate,   "Bit Error Rate");
      coniIO_str   (coni,"extra.","satBinTime:",   sar->satellite_binary_time,"Satellite Binary Time");
      coniIO_str   (coni,"extra.","satClkTime:",   sar->satellite_clock_time, "Satellite Clock Time (UTC)");
      coniIO_double(coni,"extra.","prf:",         &sar->prf,                  "Pulse Repetition Frequency");
    }
      }
  }

/* Info from ddr (if its there) */
  if (fileExists(ddrName)) {
    c_getddr(ddrName, &ddr);
    general->line_count     = ddr.nl;
    general->sample_count   = ddr.ns;
    general->start_line     = ddr.master_line - 1;
    general->start_sample   = ddr.master_sample - 1;
    sar->line_increment     = ddr.line_inc;
    sar->sample_increment   = ddr.sample_inc;
    if (sar->image_type=='P')
      {strcpy(meta->projection->units, ddr.proj_units);}
    switch ( ddr.dtype ) {
        case 0: /* BYTE */
        case DTYPE_BYTE:    general->data_type = ASF_BYTE;  break;
        case DTYPE_SHORT:   general->data_type = INTEGER16; break;
        case DTYPE_LONG:    general->data_type = INTEGER32; break;
        case DTYPE_FLOAT:   general->data_type = REAL32;    break;
        case DTYPE_DOUBLE:  general->data_type = REAL64;    break;
        case DTYPE_COMPLEX: general->data_type = COMPLEX_REAL32; break;
        default:
            printf("ERROR in meta_read_old(): Unrecognized DDR data type: (code %d)... Exit program.\n",ddr.dtype);
      exit(EXIT_FAILURE);
    }
  }
/*  else {
    printf("\n"
           "WARNING: * Failed to get DDR file while reading old style metadata.\n"
           "         * Some meta fields will not be correctly initialized.\n");
  }*/

/* Fields not yet filled */
  general->orbit_direction  = MAGIC_UNSET_CHAR;
  if (meta->state_vectors) {
    if (meta->state_vectors->vecs[0].vec.vel.z > 0)
      general->orbit_direction  = 'A';
    else if (meta->state_vectors->vecs[0].vec.vel.z < 0)
      general->orbit_direction  = 'D';
  }
  general->re_major = (meta->projection) ? meta->projection->re_major : 6378144.0;
  general->re_minor = (meta->projection) ? meta->projection->re_minor : 6356754.9;

/* Close coni structure */
  coniClose(coni);

} /* End pre-1.1 version read */
Ejemplo n.º 27
0
/*******************************************************************************
 * fopenImage:
 * first tries to open the given image name, then appends ".img" and tries again
 * It returns a pointer to the opened file.*/
FILE *fopenImage(const char *fName,const char *access)
{
    int forWriting=0;
    FILE *fRet=NULL;
    char *openName=NULL;
        /* Check to make sure that the (bone-headed) user didn't ask
           us to open a .ddr image or .meta file.  findExt may return
           a pointer into its argument string, so fName isn't const
           anymore.  */
    char *ext=findExt( (char *) fName);
    if (NULL!=ext)
    {
      if ( (0==strcmp(ext,".ddr")) || (0==strcmp(ext,".meta")))
        ext[0]=0;/*Clip off stupid extention-- will append .img later*/
      else if ( ((0==strcmp(ext,".D"))||(0==strcmp(ext,".L"))) &&
          (access[0]=='w' || access[0]=='a'))
        ext[0]=0;/*Clip off stupid extention-- will append .img later*/
    }

/*Find the file's actual name, with the correct extension.*/
    if (access[0]=='w' || access[0]=='a')
    {/*We're opening for writing-- we have to be conservative.*/
        forWriting=1;
        if (NULL==findExt((char *)fName))/*If there is no extension,*/
            openName=appendExt(fName,".img");/*Append .img*/
        else /*There was an extension, so */
            openName=appendExt(fName,NULL);/*Do nothing to the name.*/
    }
    else
    {/*We're opening for reading-- search many extensions for the image.*/
        char *extTable[]={".img",".dem",".ht",".coh",NULL};
        int extNo=-1;
        do
        {
            char *ext=(extNo==-1)?NULL:extTable[extNo];
            if (extExists(fName,ext))
            {/*We found a file with the given basename and extension!*/
                openName=appendExt(fName,ext);
                break;/*Once we find one, we're done.*/
            }
            extNo++;
        }
        while (extTable[extNo]!=NULL);
    }
/*Try to open this name.*/
    if (NULL!=openName)
    {
        fRet=fopen(openName,access);
        if (fRet!=NULL)
        {/*We've sucessfully opened the file.*/
            free(openName);/*Free the name.*/
            return fRet;/*Return the file pointer.*/
        }
    }
/*An error occured-- tell the user and quit.*/
        if (errno) {
            asfPrintStatus("Errno %d: %s\n",
                           errno, strerror(errno));
        }
        asfPrintStatus("Tried to open: %s\n",
             (openName != NULL && strlen(openName)) ? openName : "invalid filename");


    fprintf(stderr,
            "********************** Error! ***********************\n"
            "An error occured trying to open for %s the\n"
            "file named '%s'.\n\n",forWriting?"write or create":"reading",
            fName);
    if (forWriting)
        fprintf(stderr,
            "This could be because you don't have write permissions\n"
            "in this directory, because your disk quota is full, or \n"
            "because your disk is full.\n");
    else /*for reading*/
        fprintf(stderr,
                "This could be because the file doesn't exist in this\n"
                "directory, or you don't have read permissions for the\n"
                "file.  I even searched for common image extensions.\n");
    exit(102);
    return NULL;
}
Ejemplo n.º 28
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;
}
Ejemplo n.º 29
0
int main(int argc,char **argv)
{
  int lines,samps;                   /* Number of image lines and samples     */
  int fftLen,start_line;             /* FFT length, & line to start processing at*/
  int x,y,i,k;                       /* Counters                              */
  int f_lo1,f_lo2,f_hi1,f_hi2;       /* Filter frequency indicies             */
  int chunk_size,chunk_int;          /* Size of current datablock, & temp value*/
  int last_chunk;                    /* Size of the last chunk                */
  int compensate_for_last_chunk=1;   /* If last chunk = 0 dont loop for last chunk*/
  char *inName, *parmName, *outName; /* Input filename                        */
  float filtStart[2], filtEnd[2];    /* Filter start and stop variables       */
  float df, stop;                    /* Delta and counter variables           */
  complexFloat *inBuf,*outBuf;       /* Input/Output Image Buffers            */
  complexFloat *fftBuf;              /* FFT Buffer for the image              */
  float *ampBuf,*phsBuf;             /* Amplitude and Phase Buffers           */
  float *time_vector,A,B,shift;      /* Time vector, & freq modulation shift vars*/
  float chunk_float;                 /* Temporary value                       */
  FILE *inF, *freqF, *outF1;         /* Input and Output file pointers        */
  float cur_time, f_s;               /* Current time to increment the time vector by */
  meta_parameters *inMeta, *outMeta; /* Meta info about the images            */

/* Usage is shown if the user doesn't give 3 arguements */
  if(argc!=4) { usage(argv[0]); }

  StartWatch();
  printf("Program cpx_filter\n");

/* Get the filename and filter start and end frequencies from the command line*/ 
  inName=argv[1];
  if(findExt(inName)==NULL)
          inName = appendExt(argv[1],".cpx");
  outName=argv[2];
  parmName=argv[3];

/* Get input metadata. Make sure data_type is complex */
  inMeta = meta_read(inName);
  if (inMeta->general->data_type < COMPLEX_BYTE) {
   switch (inMeta->general->data_type) {
     case ASF_BYTE:      inMeta->general->data_type=COMPLEX_BYTE;      break;
     case INTEGER16: inMeta->general->data_type=COMPLEX_INTEGER16; break;
     case INTEGER32: inMeta->general->data_type=COMPLEX_INTEGER32; break;
     case REAL32:    inMeta->general->data_type=COMPLEX_REAL32;    break;
     case REAL64:    inMeta->general->data_type=COMPLEX_REAL64;    break;
    }
    meta_write (inMeta, inName);
  }

/* Open the frequency parameter file and read the parameters */
  if((freqF=FOPEN(parmName,"r"))==NULL) {
    printf("Frequency Parameter File %s could not be Opened!\n",parmName);
    exit(EXIT_FAILURE);
  }
  fscanf(freqF,"%f\n",&f_s);
  fscanf(freqF,"%f\n",&shift);
  fscanf(freqF,"%f %f\n", &filtStart[0], &filtEnd[0]);
  fscanf(freqF,"%f %f\n", &filtStart[1], &filtEnd[1]);

  printf("\n");
  printf("Input file is %s\n",inName);
  printf("Output file is %s.cpx\n",outName);
  printf("Parameter file is %s\n",parmName);
  printf("Filtering from frequencies %.2f to %.2f Hz and %.2f to %.2f in Azimuth\n",filtStart[0],filtEnd[0],filtStart[1],filtEnd[1]);
  printf("The sampling frequency is %f Hz\n",f_s);
  printf("Shifting the spectrum by %.2f Hz\n",shift);

/* Get the number of lines and samples from the input meta file */
  lines = inMeta->general->line_count;
  samps = inMeta->general->sample_count;

  chunk_size  = BLOCK_SIZE;
  chunk_float = (float)lines/chunk_size;
  chunk_int   = lines/chunk_size;
  last_chunk  = (int)((chunk_float-(float)chunk_int) * (float)BLOCK_SIZE + 0.5);
  if( (2*TOSS_SIZE) > last_chunk)
    compensate_for_last_chunk=0;
  printf("Chunk Size is set to %d, the last chunk is %d lines\n",
         chunk_size, last_chunk);

/* Compute the FFT length based on the number of lines. Must be a power of 2 */
  i      = (log10(chunk_size)/log10(2)) + 1;
  fftLen = pow(2,i);
  printf("FFT Length is %d\n",fftLen);
  cfft1d(fftLen,NULL,0);

  printf("The Input Image has %d lines and %d samples\n",lines,samps);

/* Allocate the memory for all the buffers */
  inBuf  = (complexFloat *)MALLOC(sizeof(complexFloat)*samps*fftLen);
  outBuf = (complexFloat *)MALLOC(sizeof(complexFloat)*samps*fftLen);
  fftBuf = (complexFloat *)MALLOC(sizeof(complexFloat)*fftLen);
  ampBuf = (float *)MALLOC(sizeof(float)*fftLen);
  phsBuf = (float *)MALLOC(sizeof(float)*fftLen);
  time_vector = (float *)MALLOC(sizeof(float)*lines);

/* Open the Complex Image File */
  if((inF=FOPEN(inName,"rb"))==NULL) {        
    printf("Complex Image file %s could not be opened\n",inName);
    exit(EXIT_FAILURE);
  }

  strcat(outName,".cpx"); 
  if((outF1=FOPEN(outName,"wb"))==NULL) {
    printf("Unable to write output %s\n",outName);
    exit(EXIT_FAILURE);
  }

  outMeta = meta_copy(inMeta);
  outMeta->general->line_count = 
          chunk_int*(BLOCK_SIZE-2*TOSS_SIZE)+(last_chunk-2*TOSS_SIZE);
  outMeta->general->sample_count = samps; 
  meta_write(outMeta, outName);


/* Find the filter frequency index values */
  df   = f_s/fftLen;
  stop = 0;
  i    = 0;
  while(stop<filtStart[0]) {
    f_lo1 = i;
    stop  = df*i;
    i++;
  }

  stop = 0;
  i    = 0;
  while(stop<filtStart[1]) {
    f_lo2=i;
    stop=df*i;
    i++;
  }

  i    = fftLen;
  stop = df*i;  
  while(stop>filtEnd[0]) {
    f_hi1 = i;
    stop  = df*i;   
    i--;
  }

  i    = fftLen;
  stop = df*i;
  while(stop>filtEnd[1]) {
    f_hi2 = i;
    stop  = df*i;
    i--;
  }

/* Zero out all the arrays and begin processing data */
  cur_time = 0;
  for(i=0; i<fftLen; i++)
  {
    ampBuf[i] = 0;
    phsBuf[i] = 0;
  }

  for(k=0; k<chunk_int+compensate_for_last_chunk; k++)
  {
    printf("\nProcessing Chunk %d of %d\n",k,lines/chunk_size);

    start_line = (k==0) ? 0 : (k*chunk_size)-(2*TOSS_SIZE);

    if (k==chunk_int)
      chunk_size=last_chunk;

    cur_time=start_line*(1/f_s);

  /* Read in the data chunk & put in proper endian order */
    printf("Reading %d Lines Starting at Line %d\n",chunk_size,start_line);
    get_complexFloat_lines(inF, inMeta, start_line, chunk_size, inBuf);

  /* Process the each column */
    printf("Performing the FFT and Filtering Operations\n");
    for(x=0; x<samps; x++)
    {
      if(x%1000 == 0)  printf("Processing Column %d\n",x);

      for(y=0;y<fftLen;y++)
      {
        fftBuf[y].real = 0;
        fftBuf[y].imag = 0;
      }

      for(y=0;y<chunk_size;y++)
      {
        fftBuf[y].real = inBuf[y*samps+x].real;
        fftBuf[y].imag = inBuf[y*samps+x].imag;
      }

      cfft1d(fftLen,fftBuf,-1);

      for (i=0; i<fftLen; i++) 
      {
        ampBuf[i] = sqrt(fftBuf[i].real*fftBuf[i].real
                    + fftBuf[i].imag*fftBuf[i].imag);        

        if(fftBuf[i].imag!=0.0 || fftBuf[i].real!=0.0)
          phsBuf[i] = atan2(fftBuf[i].imag,fftBuf[i].real);
        else
          phsBuf[i] = 0;

        if(((i>f_lo1)&&(i<f_hi1)) || ((i>f_lo2) && (i<f_hi2)))
        {
          ampBuf[i] = 0;
          phsBuf[i] = 0;
        }

        fftBuf[i].real = ampBuf[i]*cos(phsBuf[i]);
        fftBuf[i].imag = ampBuf[i]*sin(phsBuf[i]);        
      }

      cfft1d(fftLen,fftBuf,1);

      for(i=0;i<chunk_size;i++)
      {        
        outBuf[i*samps+x].real = fftBuf[i].real;
        outBuf[i*samps+x].imag = fftBuf[i].imag;
      }        
    }
    printf("Finished the FFT and Filtering Operations\n");

  /* Perform the time-domain frequency shift */ 
    if(shift != 0.0)
    {
      for(i=0; i<chunk_size; i++)
        time_vector[i] = cur_time+(1/f_s)*i;

      printf("\nPerforming time-domain frequency shift of %.2f Hz\n",shift);
      for(y=0; y<chunk_size; y++)
      {
        for(x=0; x<samps; x++)
        {
          A = outBuf[y*samps+x].real;
          B = outBuf[y*samps+x].imag;
          outBuf[y*samps+x].real = A*cos(2*pi*shift*time_vector[y])
                                   - B*sin(2*pi*shift*time_vector[y]);
          outBuf[y*samps+x].imag = B*cos(2*pi*shift*time_vector[y])
                                   + A*sin(2*pi*shift*time_vector[y]);
        }
      }
    }

  /* Write out the data file in big endian format */
    printf("Writing the output lines %d to %d in file %s\n",
      start_line, start_line+chunk_size-TOSS_SIZE, outName);
    put_complexFloat_lines(outF1, outMeta, start_line,
      samps*(chunk_size-TOSS_SIZE), outBuf+(samps*TOSS_SIZE));
  }

  printf("\n");

  FCLOSE(outF1);
  StopWatch();
  return 0;
}
Ejemplo n.º 30
0
meta_parameters *read_meta_gridfloat_ext(char *inBaseName, char *flt_file,
					 int *column_count, int *row_count)
{
    // all three of these must be present
    char *hdr_file = appendExt(inBaseName, ".hdr");
    char *prj_file = appendExt(inBaseName, ".prj");
    flt_file = appendExt(inBaseName, ".flt");

    if (!fileExists(flt_file) || !fileExists(hdr_file) || !fileExists(prj_file))
    {
        asfPrintError(
            "The BIL and/or associated metadata files were not found:\n"
            "  FLT File: %s %s\n"
            "  PRJ File: %s %s\n"
            "  HDR File: %s %s\n",
          flt_file, fileExists(flt_file) ? "Found" : "NOT FOUND",
          prj_file, fileExists(prj_file) ? "Found" : "NOT FOUND",
          hdr_file, fileExists(hdr_file) ? "Found" : "NOT FOUND");
    }

    asfPrintStatus("Parsing %s ...\n", hdr_file);

    // Info we'll get from the header file
    int nrows=-1;
    int ncols=-1;
    double cell_size = 0;
    double lat_ll = -999;
    double lon_ll = -999;
    double nodata = -9999;
    int msbfirst = FALSE;

    // Read header file
    char line[1024], value[1024];
    FILE *fp = FOPEN(hdr_file, "r");
    while (NULL!=fgets(line, 1024, fp)) {
        if (matches(line, "ncols")) {
            get_value(line, value);
            ncols = atoi(value);
        } else if (matches(line, "nrows")) {
            get_value(line, value);
            nrows = atoi(value);
        } else if (matches(line, "xllcorner")) {
            get_value(line, value);
            lon_ll = atof(value);
        } else if (matches(line, "yllcorner")) {
            get_value(line, value);
            lat_ll = atof(value);
        } else if (matches(line, "cellsize")) {
            get_value(line, value);
            cell_size = atof(value);
        } else if (matches(line, "NODATA_value")) {
            get_value(line, value);
            nodata = atof(value);
        } else if (matches(line, "byteorder")) {
            get_value(line, value);
            if (strcmp(value, "LSBFIRST") == 0) {
                msbfirst = FALSE;
            } else if (strcmp(value, "MSBFIRST") == 0) {
                msbfirst = TRUE;
            } else {
                asfPrintError("Unsupported byte order (should be 'LSBFIRST' or 'MSBFIRST'): %s\n",
                    value);
            }
        }
    }
    fclose(fp);

    if (nrows < 0 || ncols < 0) {
        asfPrintError(
            "Header file did not contain Row/Column infomation.\n"
            "It is a valid .HDR file?\n");
    }

    // PRJ File
    asfPrintStatus("Parsing %s ...\n", prj_file);

    datum_type_t datum=UNKNOWN_DATUM;
    spheroid_type_t spheroid=UNKNOWN_SPHEROID;

    fp = FOPEN(prj_file, "r");
    while (NULL!=fgets(line, 1024, fp)) {
        if (matches(line, "Projection")) {
            get_value(line, value);
            if (strcmp(value, "GEOGRAPHIC") != 0)
                asfPrintError("Unsupported byte order (should be GEOGRAPHIC): %s\n",
                    value);
        } else if (matches(line, "Units")) {
            get_value(line, value);
            if (strcmp(value, "DD") != 0)
                asfPrintError("Unsupported Units (should be DD): %s\n",
                    value);
        } else if (matches(line, "Zunits")) {
            get_value(line, value);
            if (strcmp(value, "METERS") != 0)
                asfPrintError("Unsupported Zunits (should be METERS): %s\n",
                    value);
        } else if (matches(line, "Datum")) {
            get_value(line, value);
            if (strcmp_case(value, "NAD27") == 0)
                datum = NAD27_DATUM;
            else if (strcmp_case(value, "NAD83") == 0)
                datum = NAD83_DATUM;
            else if (strcmp_case(value, "WGS83") == 0)
                datum = WGS84_DATUM;
            else
                asfPrintError(
                    "Unsupported Datum (should be NAD27, NAD83, or WGS84): %s\n",
                    value);
        } else if (matches(line, "Spheroid")) {
            get_value(line, value);
            if (strcmp_case(value, "CLARKE1866") == 0)
                spheroid = CLARKE1866_SPHEROID;
            else if (strcmp_case(value, "BESSEL") == 0)
                spheroid = BESSEL_SPHEROID;
            else if (strcmp_case(value, "CLARKE1880") == 0)
                spheroid = CLARKE1880_SPHEROID;
            else if (strcmp_case(value, "GEM6") == 0)
                spheroid = GEM6_SPHEROID;
            else if (strcmp_case(value, "GEM10C") == 0)
                spheroid = GEM10C_SPHEROID;
            else if (strcmp_case(value, "GRS1980") == 0)
                spheroid = GRS1980_SPHEROID;
            else if (strcmp_case(value, "WGS72") == 0)
                spheroid = WGS72_SPHEROID;
            else if (strcmp_case(value, "WGS84") == 0)
                spheroid = WGS84_SPHEROID;
            else if (strcmp_case(value, "INTERNATIONAL1924") == 0)
                spheroid = INTERNATIONAL1924_SPHEROID;
            else if (strcmp_case(value, "INTERNATIONAL1967") == 0)
                spheroid = INTERNATIONAL1967_SPHEROID;
            else
                asfPrintError("Unsupported Spheroid: %s\n", value);
        }
    }
    fclose(fp);

    meta_parameters *meta = raw_init();
    meta->projection = meta_projection_init();
    meta->location = meta_location_init();

    // aliases
    meta_general *mg = meta->general;
    meta_projection *mp = meta->projection;
    meta_location *ml = meta->location;

    // populate general block info
    mg->data_type = REAL32;
    mg->image_data_type = DEM; //presumably!?

    mg->no_data = nodata;

    // these are supposed to be in meters
    // currently, cell_size_* is in arcsecs... so here is a kludgey
    // calculation, to round to the nearest 10m. usgs data is either
    // 30, 60, or 90 meter.
    // Note that the projection block will have the actual pixel size
    int cell_size_m = 10 * (int)(11131.95 * cell_size + .5);
    if (cell_size_m != 30 && cell_size_m != 60 && cell_size_m != 90)
    {
        asfPrintWarning("Unexpected pixel size of %dm (%.10f degree) detected.\n"
            "USGS Seamless data should be 30, 60, or 90 meter.\n",
            cell_size_m, cell_size);
    }
    mg->x_pixel_size = cell_size_m;
    mg->y_pixel_size = cell_size_m;

    mg->line_count = nrows;
    mg->sample_count = ncols;
    mg->band_count = 1;
    mg->start_line = 0;
    mg->start_sample = 0;

    char *basename = get_basename(inBaseName);
    strcpy(mg->basename, basename);
    free(basename);

    strcpy(mg->sensor, "USGS Seamless data (e.g., NED, STRM)");
    strcpy(mg->mode, "N/A");
    strcpy(mg->processor, "Unknown");

    mg->center_latitude = lat_ll + cell_size * ncols / 2.0;
    mg->center_longitude = lon_ll + cell_size * nrows / 2.0;

    // populate projection block info

    mp->type = LAT_LONG_PSEUDO_PROJECTION;
    mp->startX = lon_ll;
    mp->startY = lat_ll + cell_size * nrows;
    mp->perX = cell_size;
    mp->perY = -cell_size;
    strcpy(mp->units, "degrees");
    mp->hem = mg->center_latitude > 0 ? 'N' : 'S';

    // the datum for NED is NAD83, for SRTM it is WGS84
    mp->datum = datum;
    mp->spheroid = spheroid;

    spheroid_axes_lengths(spheroid,
        &mg->re_major, &mg->re_minor);

    mp->re_major = mg->re_major;
    mp->re_minor = mg->re_minor;

    // location block
    ml->lon_start_near_range = mp->startX;
    ml->lat_start_near_range = mp->startY;
    ml->lon_start_far_range = mp->startX + mp->perX * ncols;
    ml->lat_start_far_range = mp->startY;
    ml->lon_end_near_range = mp->startX;
    ml->lat_end_near_range = mp->startY + mp->perY * nrows;
    ml->lon_end_far_range = mp->startX + mp->perX * ncols;
    ml->lat_end_far_range = mp->startY + mp->perY * nrows;

    free(hdr_file);
    free(prj_file);

    *column_count = ncols;
    *row_count = nrows;
    
    return meta;
}