]> Pileus Git - ~andy/rsl/blob - radar_to_uf.c
Changes from Bart (2011-02-01)
[~andy/rsl] / radar_to_uf.c
1 /*
2     NASA/TRMM, Code 910.1.
3     This is the TRMM Office Radar Software Library.
4     Copyright (C) 1996, 1997
5             John H. Merritt
6             Space Applications Corporation
7             Vienna, Virginia
8
9     This library is free software; you can redistribute it and/or
10     modify it under the terms of the GNU Library General Public
11     License as published by the Free Software Foundation; either
12     version 2 of the License, or (at your option) any later version.
13
14     This library is distributed in the hope that it will be useful,
15     but WITHOUT ANY WARRANTY; without even the implied warranty of
16     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17     Library General Public License for more details.
18
19     You should have received a copy of the GNU Library General Public
20     License along with this library; if not, write to the Free
21     Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23 #include <stdio.h>
24 #include <string.h>
25 #include <time.h>
26 #include <stdlib.h>
27
28 #define USE_RSL_VARS
29 #include "rsl.h"
30 extern int radar_verbose_flag;
31 /* Missing data flag : -32768 when a signed short. */
32 #define UF_NO_DATA 0X8000
33
34
35 /* Field names. Any convensions may be observed. */
36 /* Typically:
37  *    DZ = Reflectivity (dBZ).
38  *    VR = Radial Velocity.
39  *    SW = Spectrum Width.
40  *    CZ = Corrected Reflectivity. (Quality controlled: AP removed, etc.)
41  *    ZT = Total Reflectivity (dB(mW)).  Becomes UZ in UF files.
42  *    DR = Differential Reflectivity.
43  *    LR = Another DR (LDR).
44  *    ZD = Tina Johnson use this one.
45  *    DM = Received power.
46  *    RH = Rho coefficient.
47  *    PH = Phi (MCTEX parameter).
48  *    XZ = X-band reflectivity.
49  *    CD = Corrected ZD.
50  *    MZ = DZ mask for 1C-51 HDF.
51  *    MD = ZD mask for 1C-51 HDF.
52  *    ZE = Edited reflectivity.
53  *    VE = Edited velocity.
54  *    KD = KDP wavelength*deg/km
55  *    TI = TIME (units unknown).
56  * These fields may appear in any order in the UF file.
57  * There are more fields than appear here.  See rsl.h.
58  */
59
60
61 typedef short UF_buffer[16384]; /* Bigger than documented 4096. */
62
63 void swap_uf_buffer(UF_buffer uf);
64 void swap2(short *buf, int n);
65
66 /**********************************************************************/
67 /*                                                                    */
68 /*                     RSL_radar_to_uf_fp                             */
69 /*                                                                    */
70 /*  By: John Merritt                                                  */
71 /*      Space Applications Corporation                                */
72 /*      May  20, 1994                                                 */
73 /**********************************************************************/
74 void RSL_radar_to_uf_fp(Radar *r, FILE *fp)
75
76 {
77   /*
78    * 1. Fill the UF buffers with data from the Radar structure.
79    * 2. Write to a stream.  Assume open and leave it so.
80    */
81
82
83   UF_buffer uf;
84
85 /* These are pointers to various locations within the UF buffer 'uf'.
86  * They are used to index the different components of the UF structure in
87  * a manor consistant with the UF documentation.  For instance, uf_ma[1]
88  * will be equivalenced to the second word (2 bytes/each) of the UF
89  * buffer.
90  */
91   short *uf_ma;  /* Mandatory header block. */
92   short *uf_op;  /* Optional header block.  */
93   short *uf_lu;  /* Local Use header block.  */
94   short *uf_dh;  /* Data header.  */
95   short *uf_fh;  /* Field header. */
96   short *uf_data; /* Data. */
97
98 /* The length of each header. */
99   int len_ma, len_op, len_lu, len_dh, len_fh, len_data;
100
101 /* Booleans to flag inclusion of headers. */
102   int q_op, q_lu, q_dh, q_fh;
103
104   int current_fh_index; 
105   int scale_factor;
106   int rec_len, save_rec_len;
107   int nfield;
108   float vr_az;
109   int max_field_names;
110
111   struct tm *tm;
112   time_t the_time;
113
114   int i,j,k,m;
115   int degree, minute;
116   float second;
117
118   int uf_sweep_mode = 1;  /* default PPI */
119
120 /* Here are the arrays for each field type.  Each dimension is the number
121  * of fields in the radar structure.  I do this because the radar organization
122  * is by volumes (field types) and the UF demands that each ray contain
123  * all the field types.
124  */
125   Volume **volume;
126   Sweep  **sweep;
127   Ray     *ray;
128   int     *nsweeps;
129   int nvolumes, maxsweeps, nrays;
130   int true_nvolumes;
131   int sweep_num, ray_num, rec_num;
132   float x;
133
134   if (r == NULL) {
135     fprintf(stderr, "radar_to_uf_fp: radar pointer NULL\n");
136     return;
137   }
138
139 /* Do all the headers first time around.  Then, prune OP and LU. */
140   q_op = q_lu = q_dh = q_fh = 1;
141
142   memset(&uf, 0, sizeof(uf)); /* Init to 0 or NULL for pointers. */
143
144   sweep_num = ray_num = rec_num = 0;
145   true_nvolumes = nvolumes = maxsweeps = nrays = 0;
146
147   /* PPI and RHI are enum constants defined in rsl.h */
148   if (r->h.scan_mode == PPI) uf_sweep_mode = 1;
149   else if (r->h.scan_mode == RHI) uf_sweep_mode = 3;
150
151 /*
152  * The organization of the Radar structure is by volumes, then sweeps, then
153  * rays, then gates.  This is different from the UF file organization.
154  * The UF format wants sweeps, rays, then gates for all field types (volumes).
155  * So, we have to do a back flip, here.  This is achieved by maintaining 
156  * an array of volume pointers and sweep pointers, each dimensioned by 
157  * 'nvolumes', which contains the data for the different field types; this
158  * is our innermost loop.  The variables are 'volume[i]' and 'sweep[i]' where
159  * 'i' is the volume index.
160  *
161  * In other words, we are getting all the field types together, when we
162  * are looping on the number of rays in a sweep, so we can load the UF_buffer
163  * appropriately.
164  */
165
166   nvolumes = r->h.nvolumes;
167   volume   = (Volume **) calloc(nvolumes, sizeof(Volume *));
168   sweep    = (Sweep  **) calloc(nvolumes, sizeof(Sweep  *));
169   nsweeps  = (int *)     calloc(nvolumes, sizeof(int));
170
171 /* Get the the number of sweeps in the radar structure.  This will be
172  * the main controlling loop variable.
173  */
174   for (i=0; i<nvolumes; i++) {
175     volume[i] = r->v[i];
176     if(volume[i]) {
177       nsweeps[i] = volume[i]->h.nsweeps;
178       if (nsweeps[i] > maxsweeps) maxsweeps = nsweeps[i];
179       true_nvolumes++;
180     }
181   }
182
183   if (radar_verbose_flag) {
184     fprintf(stderr,"True number of volumes for UF is %d\n", true_nvolumes);
185     fprintf(stderr,"Maximum #   of volumes for UF is %d\n", nvolumes);
186   }
187
188   max_field_names = sizeof(RSL_ftype) / 4;
189
190 /*--------
191  *   LOOP for all sweeps (typically 11 or 16 for wsr88d data.
192  *
193  */
194   for (i=0; i<maxsweeps; i++) {
195     /* Get the array of volume and sweep pointers; one for each field type. */
196     nrays = 0;
197     for (k=0; k<nvolumes; k++) {
198       if (volume[k]) sweep[k] = volume[k]->sweep[i];
199       
200       /* Check if we really can access this sweep.  Paul discovered that
201        * if the actual number of sweeps is less than the maximum that we
202        * could be chasing a bad pointer (a NON-NULL garbage pointer).
203        */
204       if (i >= nsweeps[k]) sweep[k] = NULL;
205
206       if (sweep[k]) if (sweep[k]->h.nrays > nrays) nrays = sweep[k]->h.nrays;
207     }
208
209     sweep_num++;  /* I guess it will be ok to count NULL sweeps. */
210     ray_num = 0;
211   if (radar_verbose_flag) 
212     fprintf(stderr,"Processing sweep %d for %d rays.", i, nrays);
213   if (radar_verbose_flag)
214     if (little_endian()) fprintf(stderr," ... On Little endian.\n");
215     else fprintf(stderr,"\n");
216
217
218 /* Now LOOP for all rays within this particular sweep (i).
219  *    Get all the field types together for the ray, see ray[k], and
220  *    fill the UF data buffer appropriately.
221  */
222     for (j=0; j<nrays; j++) {
223       memset(uf, 0, sizeof(uf));
224       nfield = 0;
225       ray_num++;  /* And counting, possibly, NULL rays. */
226       current_fh_index = 0;
227
228
229       /* Find any ray for header information. It does not matter which
230        * ray, since the information for the MANDITORY, OPTIONAL, and LOCAL
231        * USE headers is common to any field type ray.
232        */
233       ray = NULL;
234       for (k=0; k<nvolumes; k++) {
235         if (sweep[k])
236           if (j < sweep[k]->h.nrays)
237             if (sweep[k]->ray)
238               if ((ray = sweep[k]->ray[j])) break;
239       }
240
241       /* If there is no such ray, then continue on to the next ray. */
242       if (ray) {
243 /*
244                   fprintf(stderr,"Ray: %.4d, Time: %2.2d:%2.2d:%f  %.2d/%.2d/%.4d\n", ray_num, ray->h.hour, ray->h.minute, ray->h.sec, ray->h.month, ray->h.day, ray->h.year);
245 */
246
247         /* 
248          * ---- Begining of MANDITORY HEADER BLOCK.
249          */
250         uf_ma = uf;
251         memcpy(&uf_ma[0], "UF", 2);
252         if (little_endian()) memcpy(&uf_ma[0], "FU", 2);
253         uf_ma[1]  = 0;  /* Not known yet. */
254         uf_ma[2]  = 0;  /* Not known yet. Really, I do. */
255         uf_ma[3]  = 0;  /* Not known yet. */
256         uf_ma[4]  = 0;  /* Not known yet. */
257
258         uf_ma[6]  = 1;
259         uf_ma[7]  = ray_num;
260         uf_ma[8 ] = 1;
261         uf_ma[9 ] = sweep_num;
262         memcpy(&uf_ma[10], r->h.radar_name, 8);
263         if (little_endian()) swap2(&uf_ma[10], 8/2);
264         memcpy(&uf_ma[14], r->h.name, 8);
265         if (little_endian()) swap2(&uf_ma[14], 8/2);
266         /* Convert decimal lat/lon to d:m:s */
267
268         if (ray->h.lat != 0.0) {
269           degree = (int)ray->h.lat;
270           minute = (int)((ray->h.lat - degree) * 60);
271           second = (ray->h.lat - degree - minute/60.0) * 3600.0;
272         } else {
273           degree = r->h.latd;
274           minute = r->h.latm;
275           second = r->h.lats;
276         }
277         uf_ma[18] = degree;
278         uf_ma[19] = minute;
279         if (second > 0.0) uf_ma[20] = second*64 + 0.5;
280         else uf_ma[20] = second*64 - 0.5;
281
282         if (ray->h.lon != 0.0) {
283           degree = (int)ray->h.lon;
284           minute = (int)((ray->h.lon - degree) * 60);
285           second = (ray->h.lon - degree - minute/60.0) * 3600.0;
286         } else {
287           degree = r->h.lond;
288           minute = r->h.lonm;
289           second = r->h.lons;
290         }
291         uf_ma[21] = degree;
292         uf_ma[22] = minute;
293         if (second > 0.0) uf_ma[23] = second*64 + 0.5;
294         else uf_ma[23] = second*64 - 0.5;
295         if (ray->h.alt != 0) 
296           uf_ma[24] = ray->h.alt;
297         else
298           uf_ma[24] = r->h.height;
299
300         uf_ma[25] = ray->h.year % 100; /* By definition: not year 2000 compliant. */
301         uf_ma[26] = ray->h.month;
302         uf_ma[27] = ray->h.day;
303         uf_ma[28] = ray->h.hour;
304         uf_ma[29] = ray->h.minute;
305         uf_ma[30] = ray->h.sec;
306         memcpy(&uf_ma[31], "UT", 2);
307         if (little_endian()) memcpy(&uf_ma[31], "TU", 2);
308         if (ray->h.azimuth > 0) uf_ma[32] = ray->h.azimuth*64 + 0.5;
309         else uf_ma[32] = ray->h.azimuth*64 - 0.5;
310         uf_ma[33] = ray->h.elev*64 + 0.5;
311         uf_ma[34] = uf_sweep_mode;
312         if (ray->h.fix_angle != 0.)
313              uf_ma[35] = ray->h.fix_angle*64.0 + 0.5;
314         else uf_ma[35] = sweep[k]->h.elev*64.0 + 0.5;
315         uf_ma[36] = ray->h.sweep_rate*(360.0/60.0)*64.0 + 0.5;
316         
317         the_time = time(NULL);
318         tm = gmtime(&the_time);
319         
320         uf_ma[37] = tm->tm_year % 100; /* Same format as data year */
321         uf_ma[38] = tm->tm_mon+1;
322         uf_ma[39] = tm->tm_mday;
323         memcpy(&uf_ma[40], "RSL" RSL_VERSION_STR, 8);
324         if (little_endian()) swap2(&uf_ma[40], 8/2);
325         uf_ma[44] = (signed short)UF_NO_DATA;
326         len_ma = 45;
327         uf_ma[2] = len_ma+1;
328         /*
329          * ---- End of MANDITORY HEADER BLOCK.
330          */
331         
332         /* ---- Begining of OPTIONAL HEADER BLOCK. */
333         len_op = 0;
334         if (q_op) {
335           q_op = 0;  /* Only once. */
336           uf_op = uf+len_ma;
337           memcpy(&uf_op[0], "TRMMGVUF", 8);
338           if (little_endian()) swap2(&uf_op[0], 8/2);
339           uf_op[4] = (signed short)UF_NO_DATA;
340           uf_op[5] = (signed short)UF_NO_DATA;
341           uf_op[6] = ray->h.hour;
342           uf_op[7] = ray->h.minute;
343           uf_op[8] = ray->h.sec;
344           memcpy(&uf_op[9], "RADAR_UF", 8);
345           if (little_endian()) swap2(&uf_op[9], 8/2);
346           uf_op[13] = 2;
347           len_op = 14;
348         }
349         /* ---- End of OPTIONAL HEADER BLOCK. */
350         
351         /* ---- Begining of LOCAL USE HEADER BLOCK. */
352         q_lu = 0;
353
354         /* Note: Code within "#ifdef LUHDR_VR_AZ" below is retained for testing
355          * and is not normally compiled.  It was used to deal with azimuth
356          * differences between DZ and VR in WSR-88D split-cuts, now handled in
357          * ingest routine.
358          */
359 /* 5/18/2010 Temporarily define LUHDR_VR_AZ until merge_split_cuts is
360    completed. */
361 #define LUHDR_VR_AZ
362 #ifdef LUHDR_VR_AZ
363         /* If DZ and VR azimuths are different, store VR azimuth in Local Use
364          * Header. This is done for WSR-88D split cuts.
365          */
366         if (sweep[DZ_INDEX] && sweep[VR_INDEX]) {
367             if (sweep[DZ_INDEX]->ray[j] && sweep[VR_INDEX]->ray[j]) {
368             vr_az = sweep[VR_INDEX]->ray[j]->h.azimuth;
369             if (sweep[DZ_INDEX]->ray[j]->h.azimuth != vr_az)
370                 q_lu = 1; /* Set to use Local Use Header block. */
371             }
372         }
373 #endif
374         len_lu = 0;
375         if (q_lu) {
376           /* Store azimuth for WSR-88D VR ray in Local Use Header. */
377           uf_lu = uf+len_ma+len_op;
378           memcpy(&uf_lu[0], "AZ", 2);
379           if (little_endian()) memcpy(&uf_lu[0], "ZA", 2);
380           if (vr_az > 0) uf_lu[1] = vr_az*64 + 0.5;
381           else uf_lu[1] = vr_az*64 - 0.5;
382           len_lu = 2;
383         }
384         /* ---- End  of LOCAL USE HEADER BLOCK. */
385
386
387        /* Here is where we loop on each field type.  We need to keep
388         * track of how many FIELD HEADER and FIELD DATA sections, one
389         * for each field type, we fill.  The variable that tracks this
390         * index into 'uf' is 'current_fh_index'.  It is bumped by
391         * the length of the FIELD HEADER and FIELD DATA for each field
392         * type encountered.  Field types expected are: Reflectivity,
393         * Velocity, and Spectrum width; this is a typicial list but it
394         * is not restricted to it.
395         */
396         
397          for (k=0; k<nvolumes; k++) {
398           if (sweep[k])
399             if (j < sweep[k]->h.nrays && sweep[k]->ray[j])
400               ray = sweep[k]->ray[j];
401             else
402               ray = NULL;
403           else ray = NULL;
404
405           if (ray) {
406             /* ---- Begining of DATA HEADER. */
407             nfield++;
408             if (q_dh) {
409               len_dh = 2*true_nvolumes + 3;
410               uf_dh = uf+len_ma+len_op+len_lu;
411               uf_dh[0] = nfield;
412               uf_dh[1] = 1;
413               uf_dh[2] = nfield;
414               /* 'nfield' indexes the field number.
415                * 'k' indexes the particular field from the volume.
416                *  RSL_ftype contains field names and is defined in rsl.h.
417                */
418               if (k > max_field_names-1) {
419                 fprintf(stderr,
420                   "RSL_uf_to_radar: No field name for volume index %d\n", k);
421                 fprintf(stderr,"RSL_ftype must be updated in rsl.h for new field.\n");
422                 fprintf(stderr,"Quitting now.\n");
423                 return;
424               }
425               memcpy(&uf_dh[3+2*(nfield-1)], RSL_ftype[k], 2);
426               if (little_endian()) swap2(&uf_dh[3+2*(nfield-1)], 2/2);
427               if (current_fh_index == 0) current_fh_index = len_ma+len_op+len_lu+len_dh;
428               uf_dh[4+2*(nfield-1)] = current_fh_index + 1;
429             }
430             /* ---- End of DATA HEADER. */
431             
432             /* ---- Begining of FIELD HEADER. */
433             if (q_fh) {
434               uf_fh = uf+current_fh_index;
435               uf_fh[1] = scale_factor = 100;
436               uf_fh[2] = ray->h.range_bin1/1000.0;
437               uf_fh[3] = ray->h.range_bin1 - (1000*uf_fh[2]);
438               uf_fh[4] = ray->h.gate_size;
439               uf_fh[5] = ray->h.nbins;
440               uf_fh[6] = ray->h.pulse_width*(RSL_SPEED_OF_LIGHT/1.0e6);
441               uf_fh[7] = sweep[k]->h.beam_width*64.0 + 0.5;
442               uf_fh[8] = sweep[k]->h.beam_width*64.0 + 0.5;
443               uf_fh[9] = ray->h.frequency*64.0 + 0.5; /* Bandwidth (mHz). */
444               uf_fh[10] = 0; /* Horizontal polarization. */ 
445               uf_fh[11] = ray->h.wavelength*64.0*100.0; /* m to cm. */
446               uf_fh[12] = ray->h.pulse_count;
447               memcpy(&uf_fh[13], "  ", 2);
448               uf_fh[14] = (signed short)UF_NO_DATA;
449               uf_fh[15] = (signed short)UF_NO_DATA;
450               if (k == DZ_INDEX || k == ZT_INDEX) {
451                 uf_fh[16] = volume[k]->h.calibr_const*100.0 + 0.5;
452               }
453               else {
454                 memcpy(&uf_fh[16], "  ", 2);
455               }
456               if (ray->h.prf != 0)
457                 uf_fh[17] = 1.0/ray->h.prf*1000000.0; /* Pulse repetition time(msec)  = 1/prf */
458               else
459                 uf_fh[17] = (signed short)UF_NO_DATA; /* Pulse repetition time  = 1/prf */
460               uf_fh[18] = 16;
461               if (VR_INDEX == k || VE_INDEX == k) {
462                 uf_fh[19] = scale_factor*ray->h.nyq_vel;
463                 uf_fh[20] = 1;
464                 len_fh = 21;
465               } else {
466                 len_fh = 19;
467               }
468               
469               uf_fh[0] = current_fh_index + len_fh + 1;
470               /* ---- End of FIELD HEADER. */
471               
472               /* ---- Begining of FIELD DATA. */
473               uf_data = uf+len_fh+current_fh_index;
474               len_data = ray->h.nbins;
475               for (m=0; m<len_data; m++) {
476                 x = ray->h.f(ray->range[m]);
477                 if (x == BADVAL || x == RFVAL || x == APFLAG || x == NOECHO)
478                   uf_data[m] = (signed short)UF_NO_DATA;
479                 else
480                   uf_data[m] = scale_factor * x;
481               }
482               
483               current_fh_index += (len_fh+len_data);
484             }
485           }
486         /* ---- End of FIELD DATA. */
487         }
488         /* Fill in some infomation we didn't know.  Like, buffer length,
489          * record number, etc.
490          */
491         rec_num++;
492         uf_ma[1] = current_fh_index;
493         uf_ma[3] = len_ma + len_op + 1;
494         uf_ma[4] = len_ma + len_op + len_lu + 1;
495         uf_ma[5] = rec_num;
496         
497         /* WRITE the UF buffer. */
498         rec_len =(int)uf_ma[1]*2;
499         save_rec_len = rec_len;  /* We destroy 'rec_len' when making it
500                         big endian on a little endian machine. */
501         if (little_endian()) swap_4_bytes(&rec_len);
502         (void)fwrite(&rec_len, sizeof(int), 1, fp);
503         if (little_endian()) swap_uf_buffer(uf);
504         (void)fwrite(uf, sizeof(char), save_rec_len, fp);
505         (void)fwrite(&rec_len, sizeof(int), 1, fp);
506       } /* if (ray) */
507     }
508   }
509 }
510
511 /**********************************************************************/
512 /*                                                                    */
513 /*                     RSL_radar_to_uf                                */
514 /*                                                                    */
515 /**********************************************************************/
516 void RSL_radar_to_uf(Radar *r, char *outfile)
517 {
518   FILE *fp;
519   if (r == NULL) {
520     fprintf(stderr, "radar_to_uf: radar pointer NULL\n");
521     return;
522   }
523
524   if ((fp = fopen(outfile, "w")) == NULL) {
525     perror(outfile);
526     return;
527   }
528
529   RSL_radar_to_uf_fp(r, fp);
530   fclose(fp);
531 }
532
533 /**********************************************************************/
534 /*                                                                    */
535 /*                     RSL_radar_to_uf_gzip                           */
536 /*                                                                    */
537 /**********************************************************************/
538 void RSL_radar_to_uf_gzip(Radar *r, char *outfile)
539 {
540   FILE *fp;
541   if (r == NULL) {
542     fprintf(stderr, "radar_to_uf_gzip: radar pointer NULL\n");
543     return;
544   }
545
546   if ((fp = fopen(outfile, "w")) == NULL) {
547     perror(outfile);
548     return;
549   }
550
551   fp = compress_pipe(fp);
552   RSL_radar_to_uf_fp(r, fp);
553   rsl_pclose(fp);
554 }