ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/gen/gendaymtx.c
Revision: 2.19
Committed: Tue Dec 30 20:35:34 2014 UTC (9 years, 4 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.18: +3 -2 lines
Log Message:
Changed "secret" -5 option so it now takes sun diameter (in degrees) as arg

File Contents

# User Rev Content
1 greg 2.1 #ifndef lint
2 greg 2.19 static const char RCSid[] = "$Id: gendaymtx.c,v 2.18 2014/10/26 17:37:34 greg Exp $";
3 greg 2.1 #endif
4     /*
5     * gendaymtx.c
6     *
7     * Generate a daylight matrix based on Perez Sky Model.
8     *
9     * Most of this code is borrowed (see copyright below) from Ian Ashdown's
10     * excellent re-implementation of Jean-Jacques Delaunay's gendaylit.c
11     *
12     * Created by Greg Ward on 1/16/13.
13     */
14    
15     /*********************************************************************
16     *
17     * H32_gendaylit.CPP - Perez Sky Model Calculation
18     *
19     * Version: 1.00A
20     *
21     * History: 09/10/01 - Created.
22     * 11/10/08 - Modified for Unix compilation.
23     * 11/10/12 - Fixed conditional __max directive.
24     * 1/11/13 - Tweaks and optimizations (G.Ward)
25     *
26     * Compilers: Microsoft Visual C/C++ Professional V10.0
27     *
28     * Author: Ian Ashdown, P.Eng.
29     * byHeart Consultants Limited
30     * 620 Ballantree Road
31     * West Vancouver, B.C.
32     * Canada V7S 1W3
33     * e-mail: [email protected]
34     *
35     * References: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R.
36     * Stewart. 1990. ìModeling Daylight Availability and
37     * Irradiance Components from Direct and Global
38     * Irradiance,î Solar Energy 44(5):271-289.
39     *
40     * Perez, R., R. Seals, and J. Michalsky. 1993.
41     * ìAll-Weather Model for Sky Luminance Distribution -
42     * Preliminary Configuration and Validation,î Solar Energy
43     * 50(3):235-245.
44     *
45     * Perez, R., R. Seals, and J. Michalsky. 1993. "ERRATUM to
46     * All-Weather Model for Sky Luminance Distribution -
47     * Preliminary Configuration and Validation,î Solar Energy
48     * 51(5):423.
49     *
50     * NOTE: This program is a completely rewritten version of
51     * gendaylit.c written by Jean-Jacques Delaunay (1994).
52     *
53     * Copyright 2009-2012 byHeart Consultants Limited. All rights
54     * reserved.
55     *
56     * Redistribution and use in source and binary forms, with or without
57     * modification, are permitted for personal and commercial purposes
58     * provided that redistribution of source code must retain the above
59     * copyright notice, this list of conditions and the following
60     * disclaimer:
61     *
62     * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
63     * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
64     * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
65     * DISCLAIMED. IN NO EVENT SHALL byHeart Consultants Limited OR
66     * ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
67     * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
68     * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
69     * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
70     * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
71     * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
72     * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
73     * POSSIBILITY OF SUCH DAMAGE.
74     *
75     *********************************************************************/
76    
77     /* Zenith is along the Z-axis */
78     /* X-axis points east */
79     /* Y-axis points north */
80     /* azimuth is measured as degrees or radians east of North */
81    
82     /* Include files */
83     #define _USE_MATH_DEFINES
84     #include <stdio.h>
85     #include <stdlib.h>
86     #include <string.h>
87     #include <ctype.h>
88     #include "rtmath.h"
89 greg 2.14 #include "platform.h"
90 greg 2.1 #include "color.h"
91 greg 2.17 #include "resolu.h"
92 greg 2.1
93     char *progname; /* Program name */
94     char errmsg[128]; /* Error message buffer */
95     const double DC_SolarConstantE = 1367.0; /* Solar constant W/m^2 */
96     const double DC_SolarConstantL = 127.5; /* Solar constant klux */
97    
98     double altitude; /* Solar altitude (radians) */
99     double azimuth; /* Solar azimuth (radians) */
100     double apwc; /* Atmospheric precipitable water content */
101     double dew_point = 11.0; /* Surface dew point temperature (deg. C) */
102     double diff_illum; /* Diffuse illuminance */
103     double diff_irrad; /* Diffuse irradiance */
104     double dir_illum; /* Direct illuminance */
105     double dir_irrad; /* Direct irradiance */
106     int julian_date; /* Julian date */
107     double perez_param[5]; /* Perez sky model parameters */
108     double sky_brightness; /* Sky brightness */
109     double sky_clearness; /* Sky clearness */
110     double solar_rad; /* Solar radiance */
111     double sun_zenith; /* Sun zenith angle (radians) */
112     int input = 0; /* Input type */
113 greg 2.11 int output = 0; /* Output type */
114 greg 2.1
115     extern double dmax( double, double );
116     extern double CalcAirMass();
117     extern double CalcDiffuseIllumRatio( int );
118     extern double CalcDiffuseIrradiance();
119     extern double CalcDirectIllumRatio( int );
120     extern double CalcDirectIrradiance();
121     extern double CalcEccentricity();
122     extern double CalcPrecipWater( double );
123     extern double CalcRelHorzIllum( float *parr );
124     extern double CalcRelLuminance( double, double );
125     extern double CalcSkyBrightness();
126     extern double CalcSkyClearness();
127     extern int CalcSkyParamFromIllum();
128     extern int GetCategoryIndex();
129     extern void CalcPerezParam( double, double, double, int );
130     extern void CalcSkyPatchLumin( float *parr );
131     extern void ComputeSky( float *parr );
132    
133     /* Degrees into radians */
134     #define DegToRad(deg) ((deg)*(PI/180.))
135    
136     /* Radiuans into degrees */
137     #define RadToDeg(rad) ((rad)*(180./PI))
138    
139    
140     /* Perez sky model coefficients */
141    
142     /* Reference: Perez, R., R. Seals, and J. Michalsky, 1993. "All- */
143     /* Weather Model for Sky Luminance Distribution - */
144     /* Preliminary Configuration and Validation," Solar */
145     /* Energy 50(3):235-245, Table 1. */
146    
147     static const double PerezCoeff[8][20] =
148     {
149     /* Sky clearness (epsilon): 1.000 to 1.065 */
150     { 1.3525, -0.2576, -0.2690, -1.4366, -0.7670,
151     0.0007, 1.2734, -0.1233, 2.8000, 0.6004,
152     1.2375, 1.0000, 1.8734, 0.6297, 0.9738,
153     0.2809, 0.0356, -0.1246, -0.5718, 0.9938 },
154     /* Sky clearness (epsilon): 1.065 to 1.230 */
155     { -1.2219, -0.7730, 1.4148, 1.1016, -0.2054,
156     0.0367, -3.9128, 0.9156, 6.9750, 0.1774,
157     6.4477, -0.1239, -1.5798, -0.5081, -1.7812,
158     0.1080, 0.2624, 0.0672, -0.2190, -0.4285 },
159     /* Sky clearness (epsilon): 1.230 to 1.500 */
160     { -1.1000, -0.2515, 0.8952, 0.0156, 0.2782,
161     -0.1812, - 4.5000, 1.1766, 24.7219, -13.0812,
162     -37.7000, 34.8438, -5.0000, 1.5218, 3.9229,
163     -2.6204, -0.0156, 0.1597, 0.4199, -0.5562 },
164     /* Sky clearness (epsilon): 1.500 to 1.950 */
165     { -0.5484, -0.6654, -0.2672, 0.7117, 0.7234,
166     -0.6219, -5.6812, 2.6297, 33.3389, -18.3000,
167     -62.2500, 52.0781, -3.5000, 0.0016, 1.1477,
168     0.1062, 0.4659, -0.3296, -0.0876, -0.0329 },
169     /* Sky clearness (epsilon): 1.950 to 2.800 */
170     { -0.6000, -0.3566, -2.5000, 2.3250, 0.2937,
171     0.0496, -5.6812, 1.8415, 21.0000, -4.7656 ,
172     -21.5906, 7.2492, -3.5000, -0.1554, 1.4062,
173     0.3988, 0.0032, 0.0766, -0.0656, -0.1294 },
174     /* Sky clearness (epsilon): 2.800 to 4.500 */
175     { -1.0156, -0.3670, 1.0078, 1.4051, 0.2875,
176     -0.5328, -3.8500, 3.3750, 14.0000, -0.9999,
177     -7.1406, 7.5469, -3.4000, -0.1078, -1.0750,
178     1.5702, -0.0672, 0.4016, 0.3017, -0.4844 },
179     /* Sky clearness (epsilon): 4.500 to 6.200 */
180     { -1.0000, 0.0211, 0.5025, -0.5119, -0.3000,
181     0.1922, 0.7023, -1.6317, 19.0000, -5.0000,
182     1.2438, -1.9094, -4.0000, 0.0250, 0.3844,
183     0.2656, 1.0468, -0.3788, -2.4517, 1.4656 },
184     /* Sky clearness (epsilon): 6.200 to ... */
185     { -1.0500, 0.0289, 0.4260, 0.3590, -0.3250,
186     0.1156, 0.7781, 0.0025, 31.0625, -14.5000,
187     -46.1148, 55.3750, -7.2312, 0.4050, 13.3500,
188     0.6234, 1.5000, -0.6426, 1.8564, 0.5636 }
189     };
190    
191     /* Perez irradiance component model coefficients */
192    
193     /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
194     /* Stewart. 1990. ìModeling Daylight Availability and */
195     /* Irradiance Components from Direct and Global */
196     /* Irradiance,î Solar Energy 44(5):271-289. */
197    
198     typedef struct
199     {
200     double lower; /* Lower bound */
201     double upper; /* Upper bound */
202     } CategoryBounds;
203    
204     /* Perez sky clearness (epsilon) categories (Table 1) */
205     static const CategoryBounds SkyClearCat[8] =
206     {
207     { 1.000, 1.065 }, /* Overcast */
208     { 1.065, 1.230 },
209     { 1.230, 1.500 },
210     { 1.500, 1.950 },
211     { 1.950, 2.800 },
212     { 2.800, 4.500 },
213     { 4.500, 6.200 },
214 greg 2.12 { 6.200, 12.01 } /* Clear */
215 greg 2.1 };
216    
217     /* Luminous efficacy model coefficients */
218     typedef struct
219     {
220     double a;
221     double b;
222     double c;
223     double d;
224     } ModelCoeff;
225    
226     /* Diffuse luminous efficacy model coefficients (Table 4, Eqn. 7) */
227     static const ModelCoeff DiffuseLumEff[8] =
228     {
229     { 97.24, -0.46, 12.00, -8.91 },
230     { 107.22, 1.15, 0.59, -3.95 },
231     { 104.97, 2.96, -5.53, -8.77 },
232     { 102.39, 5.59, -13.95, -13.90 },
233     { 100.71, 5.94, -22.75, -23.74 },
234     { 106.42, 3.83, -36.15, -28.83 },
235     { 141.88, 1.90, -53.24, -14.03 },
236     { 152.23, 0.35, -45.27, -7.98 }
237     };
238    
239     /* Direct luminous efficacy model coefficients (Table 4, Eqn. 8) */
240     static const ModelCoeff DirectLumEff[8] =
241     {
242     { 57.20, -4.55, -2.98, 117.12 },
243     { 98.99, -3.46, -1.21, 12.38 },
244     { 109.83, -4.90, -1.71, -8.81 },
245     { 110.34, -5.84, -1.99, -4.56 },
246     { 106.36, -3.97, -1.75, -6.16 },
247     { 107.19, -1.25, -1.51, -26.73 },
248     { 105.75, 0.77, -1.26, -34.44 },
249     { 101.18, 1.58, -1.10, -8.29 }
250     };
251    
252 greg 2.3 #ifndef NSUNPATCH
253 greg 2.10 #define NSUNPATCH 4 /* max. # patches to spread sun into */
254 greg 2.3 #endif
255    
256 greg 2.1 extern int jdate(int month, int day);
257     extern double stadj(int jd);
258     extern double sdec(int jd);
259     extern double salt(double sd, double st);
260     extern double sazi(double sd, double st);
261     /* sun calculation constants */
262     extern double s_latitude;
263     extern double s_longitude;
264     extern double s_meridian;
265    
266 greg 2.10 int nsuns = NSUNPATCH; /* number of sun patches to use */
267     double fixed_sun_sa = -1; /* fixed solid angle per sun? */
268    
269 greg 2.1 int verbose = 0; /* progress reports to stderr? */
270    
271     int outfmt = 'a'; /* output format */
272    
273     int rhsubdiv = 1; /* Reinhart sky subdivisions */
274    
275 greg 2.4 COLOR skycolor = {.96, 1.004, 1.118}; /* sky coloration */
276     COLOR suncolor = {1., 1., 1.}; /* sun color */
277     COLOR grefl = {.2, .2, .2}; /* ground reflectance */
278 greg 2.1
279     int nskypatch; /* number of Reinhart patches */
280     float *rh_palt; /* sky patch altitudes (radians) */
281     float *rh_pazi; /* sky patch azimuths (radians) */
282     float *rh_dom; /* sky patch solid angle (sr) */
283    
284     #define vector(v,alt,azi) ( (v)[1] = tcos(alt), \
285     (v)[0] = (v)[1]*tsin(azi), \
286     (v)[1] *= tcos(azi), \
287     (v)[2] = tsin(alt) )
288    
289     #define rh_vector(v,i) vector(v,rh_palt[i],rh_pazi[i])
290    
291     #define rh_cos(i) tsin(rh_palt[i])
292    
293     extern int rh_init(void);
294     extern float * resize_dmatrix(float *mtx_data, int nsteps, int npatch);
295     extern void AddDirect(float *parr);
296    
297 greg 2.14
298     static const char *
299     getfmtname(int fmt)
300     {
301     switch (fmt) {
302     case 'a':
303     return("ascii");
304     case 'f':
305     return("float");
306     case 'd':
307     return("double");
308     }
309     return("unknown");
310     }
311    
312    
313 greg 2.1 int
314     main(int argc, char *argv[])
315     {
316     char buf[256];
317 greg 2.14 int doheader = 1; /* output header? */
318 greg 2.8 double rotation = 0; /* site rotation (degrees) */
319 greg 2.1 double elevation; /* site elevation (meters) */
320     int dir_is_horiz; /* direct is meas. on horizontal? */
321     float *mtx_data = NULL; /* our matrix data */
322     int ntsteps = 0; /* number of rows in matrix */
323 greg 2.16 int step_alloc = 0;
324 greg 2.1 int last_monthly = 0; /* month of last report */
325     int mo, da; /* month (1-12) and day (1-31) */
326     double hr; /* hour (local standard time) */
327     double dir, dif; /* direct and diffuse values */
328     int mtx_offset;
329     int i, j;
330    
331     progname = argv[0];
332     /* get options */
333     for (i = 1; i < argc && argv[i][0] == '-'; i++)
334     switch (argv[i][1]) {
335 greg 2.4 case 'g': /* ground reflectance */
336     grefl[0] = atof(argv[++i]);
337     grefl[1] = atof(argv[++i]);
338     grefl[2] = atof(argv[++i]);
339 greg 2.1 break;
340 greg 2.4 case 'v': /* verbose progress reports */
341 greg 2.1 verbose++;
342     break;
343 greg 2.14 case 'h': /* turn off header */
344     doheader = 0;
345     break;
346 greg 2.4 case 'o': /* output format */
347 greg 2.1 switch (argv[i][2]) {
348     case 'f':
349     case 'd':
350     case 'a':
351     outfmt = argv[i][2];
352     break;
353     default:
354     goto userr;
355     }
356     break;
357 greg 2.11 case 'O': /* output type */
358     switch (argv[i][2]) {
359     case '0':
360     output = 0;
361     break;
362     case '1':
363     output = 1;
364     break;
365     default:
366     goto userr;
367     }
368     if (argv[i][3])
369     goto userr;
370     break;
371 greg 2.4 case 'm': /* Reinhart subdivisions */
372 greg 2.1 rhsubdiv = atoi(argv[++i]);
373     break;
374 greg 2.4 case 'c': /* sky color */
375 greg 2.1 skycolor[0] = atof(argv[++i]);
376     skycolor[1] = atof(argv[++i]);
377     skycolor[2] = atof(argv[++i]);
378     break;
379 greg 2.4 case 'd': /* solar (direct) only */
380 greg 2.1 skycolor[0] = skycolor[1] = skycolor[2] = 0;
381 greg 2.4 if (suncolor[1] <= 1e-4)
382     suncolor[0] = suncolor[1] = suncolor[2] = 1;
383 greg 2.1 break;
384 greg 2.4 case 's': /* sky only (no direct) */
385     suncolor[0] = suncolor[1] = suncolor[2] = 0;
386 greg 2.1 if (skycolor[1] <= 1e-4)
387     skycolor[0] = skycolor[1] = skycolor[2] = 1;
388     break;
389 greg 2.8 case 'r': /* rotate distribution */
390     if (argv[i][2] && argv[i][2] != 'z')
391     goto userr;
392     rotation = atof(argv[++i]);
393     break;
394 greg 2.10 case '5': /* 5-phase calculation */
395     nsuns = 1;
396 greg 2.19 fixed_sun_sa = PI/360.*atof(argv[++i]);
397     fixed_sun_sa *= fixed_sun_sa*PI;
398 greg 2.10 break;
399 greg 2.1 default:
400     goto userr;
401     }
402     if (i < argc-1)
403     goto userr;
404     if (i == argc-1 && freopen(argv[i], "r", stdin) == NULL) {
405     fprintf(stderr, "%s: cannot open '%s' for input\n",
406     progname, argv[i]);
407     exit(1);
408     }
409     if (verbose) {
410     if (i == argc-1)
411     fprintf(stderr, "%s: reading weather tape '%s'\n",
412     progname, argv[i]);
413     else
414     fprintf(stderr, "%s: reading weather tape from <stdin>\n",
415     progname);
416     }
417     /* read weather tape header */
418 greg 2.2 if (scanf("place %[^\r\n] ", buf) != 1)
419 greg 2.1 goto fmterr;
420     if (scanf("latitude %lf\n", &s_latitude) != 1)
421     goto fmterr;
422     if (scanf("longitude %lf\n", &s_longitude) != 1)
423     goto fmterr;
424     if (scanf("time_zone %lf\n", &s_meridian) != 1)
425     goto fmterr;
426     if (scanf("site_elevation %lf\n", &elevation) != 1)
427     goto fmterr;
428     if (scanf("weather_data_file_units %d\n", &input) != 1)
429     goto fmterr;
430     switch (input) { /* translate units */
431     case 1:
432     input = 1; /* radiometric quantities */
433     dir_is_horiz = 0; /* direct is perpendicular meas. */
434     break;
435     case 2:
436     input = 1; /* radiometric quantities */
437     dir_is_horiz = 1; /* solar measured horizontally */
438     break;
439     case 3:
440     input = 2; /* photometric quantities */
441     dir_is_horiz = 0; /* direct is perpendicular meas. */
442     break;
443     default:
444     goto fmterr;
445     }
446     rh_init(); /* initialize sky patches */
447     if (verbose) {
448     fprintf(stderr, "%s: location '%s'\n", progname, buf);
449     fprintf(stderr, "%s: (lat,long)=(%.1f,%.1f) degrees north, west\n",
450     progname, s_latitude, s_longitude);
451     fprintf(stderr, "%s: %d sky patches per time step\n",
452     progname, nskypatch);
453 greg 2.8 if (rotation != 0)
454     fprintf(stderr, "%s: rotating output %.0f degrees\n",
455     progname, rotation);
456 greg 2.1 }
457 greg 2.2 /* convert quantities to radians */
458     s_latitude = DegToRad(s_latitude);
459     s_longitude = DegToRad(s_longitude);
460     s_meridian = DegToRad(s_meridian);
461 greg 2.1 /* process each time step in tape */
462     while (scanf("%d %d %lf %lf %lf\n", &mo, &da, &hr, &dir, &dif) == 5) {
463     double sda, sta;
464     /* make space for next time step */
465     mtx_offset = 3*nskypatch*ntsteps++;
466 greg 2.15 if (ntsteps > step_alloc) {
467 greg 2.16 step_alloc += (step_alloc>>1) + ntsteps + 7;
468 greg 2.15 mtx_data = resize_dmatrix(mtx_data, step_alloc, nskypatch);
469     }
470 greg 2.1 if (dif <= 1e-4) {
471     memset(mtx_data+mtx_offset, 0, sizeof(float)*3*nskypatch);
472     continue;
473     }
474     if (verbose && mo != last_monthly)
475     fprintf(stderr, "%s: stepping through month %d...\n",
476     progname, last_monthly=mo);
477     /* compute solar position */
478     julian_date = jdate(mo, da);
479     sda = sdec(julian_date);
480     sta = stadj(julian_date);
481     altitude = salt(sda, hr+sta);
482 greg 2.8 azimuth = sazi(sda, hr+sta) + PI - DegToRad(rotation);
483 greg 2.1 /* convert measured values */
484     if (dir_is_horiz && altitude > 0.)
485     dir /= sin(altitude);
486     if (input == 1) {
487     dir_irrad = dir;
488     diff_irrad = dif;
489     } else /* input == 2 */ {
490     dir_illum = dir;
491     diff_illum = dif;
492     }
493     /* compute sky patch values */
494     ComputeSky(mtx_data+mtx_offset);
495 greg 2.4 AddDirect(mtx_data+mtx_offset);
496 greg 2.1 }
497     /* check for junk at end */
498     while ((i = fgetc(stdin)) != EOF)
499     if (!isspace(i)) {
500     fprintf(stderr, "%s: warning - unexpected data past EOT: ",
501     progname);
502     buf[0] = i; buf[1] = '\0';
503     fgets(buf+1, sizeof(buf)-1, stdin);
504     fputs(buf, stderr); fputc('\n', stderr);
505     break;
506     }
507     /* write out matrix */
508 greg 2.14 if (outfmt != 'a')
509     SET_FILE_BINARY(stdout);
510 greg 2.1 #ifdef getc_unlocked
511     flockfile(stdout);
512     #endif
513     if (verbose)
514     fprintf(stderr, "%s: writing %smatrix with %d time steps...\n",
515     progname, outfmt=='a' ? "" : "binary ", ntsteps);
516 greg 2.14 if (doheader) {
517     newheader("RADIANCE", stdout);
518     printargs(argc, argv, stdout);
519     printf("LATLONG= %.8f %.8f\n", RadToDeg(s_latitude),
520     -RadToDeg(s_longitude));
521     printf("NROWS=%d\n", nskypatch);
522     printf("NCOLS=%d\n", ntsteps);
523     printf("NCOMP=3\n");
524 greg 2.18 fputformat((char *)getfmtname(outfmt), stdout);
525 greg 2.14 putchar('\n');
526     }
527 greg 2.1 /* patches are rows (outer sort) */
528     for (i = 0; i < nskypatch; i++) {
529     mtx_offset = 3*i;
530     switch (outfmt) {
531     case 'a':
532     for (j = 0; j < ntsteps; j++) {
533 greg 2.3 printf("%.3g %.3g %.3g\n", mtx_data[mtx_offset],
534 greg 2.1 mtx_data[mtx_offset+1],
535     mtx_data[mtx_offset+2]);
536     mtx_offset += 3*nskypatch;
537     }
538 greg 2.2 if (ntsteps > 1)
539     fputc('\n', stdout);
540 greg 2.1 break;
541     case 'f':
542     for (j = 0; j < ntsteps; j++) {
543     fwrite(mtx_data+mtx_offset, sizeof(float), 3,
544     stdout);
545     mtx_offset += 3*nskypatch;
546     }
547     break;
548     case 'd':
549     for (j = 0; j < ntsteps; j++) {
550     double ment[3];
551     ment[0] = mtx_data[mtx_offset];
552     ment[1] = mtx_data[mtx_offset+1];
553     ment[2] = mtx_data[mtx_offset+2];
554     fwrite(ment, sizeof(double), 3, stdout);
555     mtx_offset += 3*nskypatch;
556     }
557     break;
558     }
559     if (ferror(stdout))
560     goto writerr;
561     }
562     if (fflush(stdout) == EOF)
563     goto writerr;
564     if (verbose)
565     fprintf(stderr, "%s: done.\n", progname);
566     exit(0);
567     userr:
568 greg 2.14 fprintf(stderr, "Usage: %s [-v][-h][-d|-s][-r deg][-m N][-g r g b][-c r g b][-o{f|d}][-O{0|1}] [tape.wea]\n",
569 greg 2.1 progname);
570     exit(1);
571     fmterr:
572     fprintf(stderr, "%s: input weather tape format error\n", progname);
573     exit(1);
574     writerr:
575     fprintf(stderr, "%s: write error on output\n", progname);
576     exit(1);
577     }
578    
579     /* Return maximum of two doubles */
580     double dmax( double a, double b )
581     { return (a > b) ? a : b; }
582    
583     /* Compute sky patch radiance values (modified by GW) */
584     void
585     ComputeSky(float *parr)
586     {
587     int index; /* Category index */
588     double norm_diff_illum; /* Normalized diffuse illuimnance */
589     int i;
590    
591     /* Calculate atmospheric precipitable water content */
592     apwc = CalcPrecipWater(dew_point);
593    
594 greg 2.6 /* Calculate sun zenith angle (don't let it dip below horizon) */
595     /* Also limit minimum angle to keep circumsolar off zenith */
596     if (altitude <= 0.0)
597     sun_zenith = DegToRad(90.0);
598     else if (altitude >= DegToRad(87.0))
599     sun_zenith = DegToRad(3.0);
600     else
601     sun_zenith = DegToRad(90.0) - altitude;
602 greg 2.1
603     /* Compute the inputs for the calculation of the sky distribution */
604    
605     if (input == 0) /* XXX never used */
606     {
607     /* Calculate irradiance */
608     diff_irrad = CalcDiffuseIrradiance();
609     dir_irrad = CalcDirectIrradiance();
610    
611     /* Calculate illuminance */
612     index = GetCategoryIndex();
613     diff_illum = diff_irrad * CalcDiffuseIllumRatio(index);
614     dir_illum = dir_irrad * CalcDirectIllumRatio(index);
615     }
616     else if (input == 1)
617     {
618     sky_brightness = CalcSkyBrightness();
619     sky_clearness = CalcSkyClearness();
620    
621 greg 2.9 /* Limit sky clearness */
622     if (sky_clearness > 11.9)
623     sky_clearness = 11.9;
624    
625     /* Limit sky brightness */
626     if (sky_brightness < 0.01)
627 greg 2.11 sky_brightness = 0.01;
628 greg 2.9
629 greg 2.1 /* Calculate illuminance */
630     index = GetCategoryIndex();
631     diff_illum = diff_irrad * CalcDiffuseIllumRatio(index);
632     dir_illum = dir_irrad * CalcDirectIllumRatio(index);
633     }
634     else if (input == 2)
635     {
636     /* Calculate sky brightness and clearness from illuminance values */
637     index = CalcSkyParamFromIllum();
638     }
639    
640 greg 2.11 if (output == 1) { /* hack for solar radiance */
641     diff_illum = diff_irrad * WHTEFFICACY;
642     dir_illum = dir_irrad * WHTEFFICACY;
643     }
644    
645 greg 2.2 if (bright(skycolor) <= 1e-4) { /* 0 sky component? */
646     memset(parr, 0, sizeof(float)*3*nskypatch);
647     return;
648     }
649 greg 2.1 /* Compute ground radiance (include solar contribution if any) */
650 greg 2.3 parr[0] = diff_illum;
651 greg 2.1 if (altitude > 0)
652 greg 2.3 parr[0] += dir_illum * sin(altitude);
653 greg 2.4 parr[2] = parr[1] = parr[0] *= (1./PI/WHTEFFICACY);
654     multcolor(parr, grefl);
655 greg 2.1
656     /* Calculate Perez sky model parameters */
657     CalcPerezParam(sun_zenith, sky_clearness, sky_brightness, index);
658    
659     /* Calculate sky patch luminance values */
660     CalcSkyPatchLumin(parr);
661    
662     /* Calculate relative horizontal illuminance */
663     norm_diff_illum = CalcRelHorzIllum(parr);
664    
665 greg 2.13 /* Check for zero sky -- make uniform in that case */
666     if (norm_diff_illum <= FTINY) {
667     for (i = 1; i < nskypatch; i++)
668     setcolor(parr+3*i, 1., 1., 1.);
669     norm_diff_illum = PI;
670     }
671 greg 2.1 /* Normalization coefficient */
672     norm_diff_illum = diff_illum / norm_diff_illum;
673    
674     /* Apply to sky patches to get absolute radiance values */
675     for (i = 1; i < nskypatch; i++) {
676 greg 2.7 scalecolor(parr+3*i, norm_diff_illum*(1./WHTEFFICACY));
677 greg 2.1 multcolor(parr+3*i, skycolor);
678     }
679     }
680    
681     /* Add in solar direct to nearest sky patches (GW) */
682     void
683     AddDirect(float *parr)
684     {
685     FVECT svec;
686 greg 2.3 double near_dprod[NSUNPATCH];
687     int near_patch[NSUNPATCH];
688     double wta[NSUNPATCH], wtot;
689 greg 2.1 int i, j, p;
690    
691 greg 2.4 if (dir_illum <= 1e-4 || bright(suncolor) <= 1e-4)
692 greg 2.1 return;
693 greg 2.10 /* identify nsuns closest patches */
694     if (nsuns > NSUNPATCH)
695     nsuns = NSUNPATCH;
696     else if (nsuns <= 0)
697     nsuns = 1;
698     for (i = nsuns; i--; )
699 greg 2.1 near_dprod[i] = -1.;
700     vector(svec, altitude, azimuth);
701     for (p = 1; p < nskypatch; p++) {
702     FVECT pvec;
703     double dprod;
704     rh_vector(pvec, p);
705     dprod = DOT(pvec, svec);
706 greg 2.10 for (i = 0; i < nsuns; i++)
707 greg 2.1 if (dprod > near_dprod[i]) {
708 greg 2.10 for (j = nsuns; --j > i; ) {
709 greg 2.1 near_dprod[j] = near_dprod[j-1];
710     near_patch[j] = near_patch[j-1];
711     }
712     near_dprod[i] = dprod;
713     near_patch[i] = p;
714     break;
715     }
716     }
717     wtot = 0; /* weight by proximity */
718 greg 2.10 for (i = nsuns; i--; )
719 greg 2.1 wtot += wta[i] = 1./(1.002 - near_dprod[i]);
720     /* add to nearest patch radiances */
721 greg 2.10 for (i = nsuns; i--; ) {
722 greg 2.2 float *pdest = parr + 3*near_patch[i];
723 greg 2.10 float val_add = wta[i] * dir_illum / (WHTEFFICACY * wtot);
724    
725     val_add /= (fixed_sun_sa > 0) ? fixed_sun_sa
726     : rh_dom[near_patch[i]] ;
727 greg 2.4 *pdest++ += val_add*suncolor[0];
728     *pdest++ += val_add*suncolor[1];
729     *pdest++ += val_add*suncolor[2];
730 greg 2.2 }
731 greg 2.1 }
732    
733     /* Initialize Reinhart sky patch positions (GW) */
734     int
735     rh_init(void)
736     {
737     #define NROW 7
738     static const int tnaz[NROW] = {30, 30, 24, 24, 18, 12, 6};
739     const double alpha = (PI/2.)/(NROW*rhsubdiv + .5);
740     int p, i, j;
741     /* allocate patch angle arrays */
742     nskypatch = 0;
743     for (p = 0; p < NROW; p++)
744     nskypatch += tnaz[p];
745     nskypatch *= rhsubdiv*rhsubdiv;
746     nskypatch += 2;
747     rh_palt = (float *)malloc(sizeof(float)*nskypatch);
748     rh_pazi = (float *)malloc(sizeof(float)*nskypatch);
749     rh_dom = (float *)malloc(sizeof(float)*nskypatch);
750     if ((rh_palt == NULL) | (rh_pazi == NULL) | (rh_dom == NULL)) {
751     fprintf(stderr, "%s: out of memory in rh_init()\n", progname);
752     exit(1);
753     }
754     rh_palt[0] = -PI/2.; /* ground & zenith patches */
755     rh_pazi[0] = 0.;
756     rh_dom[0] = 2.*PI;
757     rh_palt[nskypatch-1] = PI/2.;
758     rh_pazi[nskypatch-1] = 0.;
759     rh_dom[nskypatch-1] = 2.*PI*(1. - cos(alpha*.5));
760     p = 1; /* "normal" patches */
761     for (i = 0; i < NROW*rhsubdiv; i++) {
762     const float ralt = alpha*(i + .5);
763     const int ninrow = tnaz[i/rhsubdiv]*rhsubdiv;
764 greg 2.3 const float dom = 2.*PI*(sin(alpha*(i+1)) - sin(alpha*i)) /
765     (double)ninrow;
766 greg 2.1 for (j = 0; j < ninrow; j++) {
767     rh_palt[p] = ralt;
768     rh_pazi[p] = 2.*PI * j / (double)ninrow;
769     rh_dom[p++] = dom;
770     }
771     }
772     return nskypatch;
773     #undef NROW
774     }
775    
776     /* Resize daylight matrix (GW) */
777     float *
778     resize_dmatrix(float *mtx_data, int nsteps, int npatch)
779     {
780     if (mtx_data == NULL)
781     mtx_data = (float *)malloc(sizeof(float)*3*nsteps*npatch);
782     else
783     mtx_data = (float *)realloc(mtx_data,
784     sizeof(float)*3*nsteps*npatch);
785     if (mtx_data == NULL) {
786     fprintf(stderr, "%s: out of memory in resize_dmatrix(%d,%d)\n",
787     progname, nsteps, npatch);
788     exit(1);
789     }
790     return(mtx_data);
791     }
792    
793     /* Determine category index */
794     int GetCategoryIndex()
795     {
796     int index; /* Loop index */
797    
798     for (index = 0; index < 8; index++)
799     if ((sky_clearness >= SkyClearCat[index].lower) &&
800     (sky_clearness < SkyClearCat[index].upper))
801     break;
802    
803     return index;
804     }
805    
806     /* Calculate diffuse illuminance to diffuse irradiance ratio */
807    
808     /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
809     /* Stewart. 1990. ìModeling Daylight Availability and */
810     /* Irradiance Components from Direct and Global */
811     /* Irradiance,î Solar Energy 44(5):271-289, Eqn. 7. */
812    
813     double CalcDiffuseIllumRatio( int index )
814     {
815     ModelCoeff const *pnle; /* Category coefficient pointer */
816    
817     /* Get category coefficient pointer */
818     pnle = &(DiffuseLumEff[index]);
819    
820     return pnle->a + pnle->b * apwc + pnle->c * cos(sun_zenith) +
821     pnle->d * log(sky_brightness);
822     }
823    
824     /* Calculate direct illuminance to direct irradiance ratio */
825    
826     /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
827     /* Stewart. 1990. ìModeling Daylight Availability and */
828     /* Irradiance Components from Direct and Global */
829     /* Irradiance,î Solar Energy 44(5):271-289, Eqn. 8. */
830    
831     double CalcDirectIllumRatio( int index )
832     {
833     ModelCoeff const *pnle; /* Category coefficient pointer */
834    
835     /* Get category coefficient pointer */
836     pnle = &(DirectLumEff[index]);
837    
838     /* Calculate direct illuminance from direct irradiance */
839    
840     return dmax((pnle->a + pnle->b * apwc + pnle->c * exp(5.73 *
841     sun_zenith - 5.0) + pnle->d * sky_brightness),
842     0.0);
843     }
844    
845     /* Calculate sky brightness */
846    
847     /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
848     /* Stewart. 1990. ìModeling Daylight Availability and */
849     /* Irradiance Components from Direct and Global */
850     /* Irradiance,î Solar Energy 44(5):271-289, Eqn. 2. */
851    
852     double CalcSkyBrightness()
853     {
854     return diff_irrad * CalcAirMass() / (DC_SolarConstantE *
855     CalcEccentricity());
856     }
857    
858     /* Calculate sky clearness */
859    
860     /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
861     /* Stewart. 1990. ìModeling Daylight Availability and */
862     /* Irradiance Components from Direct and Global */
863     /* Irradiance,î Solar Energy 44(5):271-289, Eqn. 1. */
864    
865     double CalcSkyClearness()
866     {
867     double sz_cubed; /* Sun zenith angle cubed */
868    
869     /* Calculate sun zenith angle cubed */
870 greg 2.11 sz_cubed = sun_zenith*sun_zenith*sun_zenith;
871 greg 2.1
872     return ((diff_irrad + dir_irrad) / diff_irrad + 1.041 *
873     sz_cubed) / (1.0 + 1.041 * sz_cubed);
874     }
875    
876     /* Calculate diffuse horizontal irradiance from Perez sky brightness */
877    
878     /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
879     /* Stewart. 1990. ìModeling Daylight Availability and */
880     /* Irradiance Components from Direct and Global */
881     /* Irradiance,î Solar Energy 44(5):271-289, Eqn. 2 */
882     /* (inverse). */
883    
884     double CalcDiffuseIrradiance()
885     {
886     return sky_brightness * DC_SolarConstantE * CalcEccentricity() /
887     CalcAirMass();
888     }
889    
890     /* Calculate direct normal irradiance from Perez sky clearness */
891    
892     /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
893     /* Stewart. 1990. ìModeling Daylight Availability and */
894     /* Irradiance Components from Direct and Global */
895     /* Irradiance,î Solar Energy 44(5):271-289, Eqn. 1 */
896     /* (inverse). */
897    
898     double CalcDirectIrradiance()
899     {
900     return CalcDiffuseIrradiance() * ((sky_clearness - 1.0) * (1 + 1.041
901 greg 2.11 * sun_zenith*sun_zenith*sun_zenith));
902 greg 2.1 }
903    
904     /* Calculate sky brightness and clearness from illuminance values */
905     int CalcSkyParamFromIllum()
906     {
907     double test1 = 0.1;
908     double test2 = 0.1;
909     int counter = 0;
910     int index = 0; /* Category index */
911    
912     /* Convert illuminance to irradiance */
913     diff_irrad = diff_illum * DC_SolarConstantE /
914     (DC_SolarConstantL * 1000.0);
915     dir_irrad = dir_illum * DC_SolarConstantE /
916     (DC_SolarConstantL * 1000.0);
917    
918     /* Calculate sky brightness and clearness */
919     sky_brightness = CalcSkyBrightness();
920     sky_clearness = CalcSkyClearness();
921    
922     /* Limit sky clearness */
923     if (sky_clearness > 12.0)
924     sky_clearness = 12.0;
925    
926     /* Limit sky brightness */
927 greg 2.9 if (sky_brightness < 0.01)
928 greg 2.1 sky_brightness = 0.01;
929    
930     while (((fabs(diff_irrad - test1) > 10.0) ||
931     (fabs(dir_irrad - test2) > 10.0)) && !(counter == 5))
932     {
933     test1 = diff_irrad;
934     test2 = dir_irrad;
935     counter++;
936    
937     /* Convert illuminance to irradiance */
938     index = GetCategoryIndex();
939     diff_irrad = diff_illum / CalcDiffuseIllumRatio(index);
940     dir_irrad = dir_illum / CalcDirectIllumRatio(index);
941    
942     /* Calculate sky brightness and clearness */
943     sky_brightness = CalcSkyBrightness();
944     sky_clearness = CalcSkyClearness();
945    
946     /* Limit sky clearness */
947     if (sky_clearness > 12.0)
948     sky_clearness = 12.0;
949    
950     /* Limit sky brightness */
951 greg 2.9 if (sky_brightness < 0.01)
952 greg 2.1 sky_brightness = 0.01;
953     }
954    
955     return GetCategoryIndex();
956     }
957    
958     /* Calculate relative luminance */
959    
960     /* Reference: Perez, R., R. Seals, and J. Michalsky. 1993. */
961     /* ìAll-Weather Model for Sky Luminance Distribution - */
962     /* Preliminary Configuration and Validation,î Solar Energy */
963     /* 50(3):235-245, Eqn. 1. */
964    
965     double CalcRelLuminance( double gamma, double zeta )
966     {
967     return (1.0 + perez_param[0] * exp(perez_param[1] / cos(zeta))) *
968     (1.0 + perez_param[2] * exp(perez_param[3] * gamma) +
969     perez_param[4] * cos(gamma) * cos(gamma));
970     }
971    
972     /* Calculate Perez sky model parameters */
973    
974     /* Reference: Perez, R., R. Seals, and J. Michalsky. 1993. */
975     /* ìAll-Weather Model for Sky Luminance Distribution - */
976     /* Preliminary Configuration and Validation,î Solar Energy */
977     /* 50(3):235-245, Eqns. 6 - 8. */
978    
979     void CalcPerezParam( double sz, double epsilon, double delta,
980     int index )
981     {
982     double x[5][4]; /* Coefficents a, b, c, d, e */
983     int i, j; /* Loop indices */
984    
985     /* Limit sky brightness */
986     if (epsilon > 1.065 && epsilon < 2.8)
987     {
988     if (delta < 0.2)
989     delta = 0.2;
990     }
991    
992     /* Get Perez coefficients */
993     for (i = 0; i < 5; i++)
994     for (j = 0; j < 4; j++)
995     x[i][j] = PerezCoeff[index][4 * i + j];
996    
997     if (index != 0)
998     {
999     /* Calculate parameter a, b, c, d and e (Eqn. 6) */
1000     for (i = 0; i < 5; i++)
1001     perez_param[i] = x[i][0] + x[i][1] * sz + delta * (x[i][2] +
1002     x[i][3] * sz);
1003     }
1004     else
1005     {
1006     /* Parameters a, b and e (Eqn. 6) */
1007     perez_param[0] = x[0][0] + x[0][1] * sz + delta * (x[0][2] +
1008     x[0][3] * sz);
1009     perez_param[1] = x[1][0] + x[1][1] * sz + delta * (x[1][2] +
1010     x[1][3] * sz);
1011     perez_param[4] = x[4][0] + x[4][1] * sz + delta * (x[4][2] +
1012     x[4][3] * sz);
1013    
1014     /* Parameter c (Eqn. 7) */
1015     perez_param[2] = exp(pow(delta * (x[2][0] + x[2][1] * sz),
1016     x[2][2])) - x[2][3];
1017    
1018     /* Parameter d (Eqn. 8) */
1019     perez_param[3] = -exp(delta * (x[3][0] + x[3][1] * sz)) +
1020     x[3][2] + delta * x[3][3];
1021     }
1022     }
1023    
1024     /* Calculate relative horizontal illuminance (modified by GW) */
1025    
1026     /* Reference: Perez, R., R. Seals, and J. Michalsky. 1993. */
1027     /* ìAll-Weather Model for Sky Luminance Distribution - */
1028     /* Preliminary Configuration and Validation,î Solar Energy */
1029     /* 50(3):235-245, Eqn. 3. */
1030    
1031     double CalcRelHorzIllum( float *parr )
1032     {
1033     int i;
1034     double rh_illum = 0.0; /* Relative horizontal illuminance */
1035    
1036     for (i = 1; i < nskypatch; i++)
1037 greg 2.7 rh_illum += parr[3*i+1] * rh_cos(i) * rh_dom[i];
1038 greg 2.1
1039 greg 2.7 return rh_illum;
1040 greg 2.1 }
1041    
1042     /* Calculate earth orbit eccentricity correction factor */
1043    
1044     /* Reference: Sen, Z. 2008. Solar Energy Fundamental and Modeling */
1045     /* Techniques. Springer, p. 72. */
1046    
1047     double CalcEccentricity()
1048     {
1049     double day_angle; /* Day angle (radians) */
1050     double E0; /* Eccentricity */
1051    
1052     /* Calculate day angle */
1053     day_angle = (julian_date - 1.0) * (2.0 * PI / 365.0);
1054    
1055     /* Calculate eccentricity */
1056     E0 = 1.00011 + 0.034221 * cos(day_angle) + 0.00128 * sin(day_angle)
1057     + 0.000719 * cos(2.0 * day_angle) + 0.000077 * sin(2.0 *
1058     day_angle);
1059    
1060     return E0;
1061     }
1062    
1063     /* Calculate atmospheric precipitable water content */
1064    
1065     /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
1066     /* Stewart. 1990. ìModeling Daylight Availability and */
1067     /* Irradiance Components from Direct and Global */
1068     /* Irradiance,î Solar Energy 44(5):271-289, Eqn. 3. */
1069    
1070     /* Note: The default surface dew point temperature is 11 deg. C */
1071     /* (52 deg. F). Typical values are: */
1072    
1073     /* Celsius Fahrenheit Human Perception */
1074     /* > 24 > 75 Extremely uncomfortable */
1075     /* 21 - 24 70 - 74 Very humid */
1076     /* 18 - 21 65 - 69 Somewhat uncomfortable */
1077     /* 16 - 18 60 - 64 OK for most people */
1078     /* 13 - 16 55 - 59 Comfortable */
1079     /* 10 - 12 50 - 54 Very comfortable */
1080     /* < 10 < 49 A bit dry for some */
1081    
1082     double CalcPrecipWater( double dpt )
1083     { return exp(0.07 * dpt - 0.075); }
1084    
1085     /* Calculate relative air mass */
1086    
1087     /* Reference: Kasten, F. 1966. "A New Table and Approximation Formula */
1088     /* for the Relative Optical Air Mass," Arch. Meteorol. */
1089     /* Geophys. Bioklimataol. Ser. B14, pp. 206-233. */
1090    
1091     /* Note: More sophisticated relative air mass models are */
1092     /* available, but they differ significantly only for */
1093     /* sun zenith angles greater than 80 degrees. */
1094    
1095     double CalcAirMass()
1096     {
1097     return (1.0 / (cos(sun_zenith) + 0.15 * pow(93.885 -
1098     RadToDeg(sun_zenith), -1.253)));
1099     }
1100    
1101     /* Calculate Perez All-Weather sky patch luminances (modified by GW) */
1102    
1103     /* NOTE: The sky patches centers are determined in accordance with the */
1104     /* BRE-IDMP sky luminance measurement procedures. (See for example */
1105     /* Mardaljevic, J. 2001. "The BRE-IDMP Dataset: A New Benchmark */
1106     /* for the Validation of Illuminance Prediction Techniques," */
1107     /* Lighting Research & Technology 33(2):117-136.) */
1108    
1109     void CalcSkyPatchLumin( float *parr )
1110     {
1111     int i;
1112     double aas; /* Sun-sky point azimuthal angle */
1113     double sspa; /* Sun-sky point angle */
1114     double zsa; /* Zenithal sun angle */
1115    
1116     for (i = 1; i < nskypatch; i++)
1117     {
1118     /* Calculate sun-sky point azimuthal angle */
1119     aas = fabs(rh_pazi[i] - azimuth);
1120    
1121     /* Calculate zenithal sun angle */
1122     zsa = PI * 0.5 - rh_palt[i];
1123    
1124     /* Calculate sun-sky point angle (Equation 8-20) */
1125     sspa = acos(cos(sun_zenith) * cos(zsa) + sin(sun_zenith) *
1126     sin(zsa) * cos(aas));
1127    
1128     /* Calculate patch luminance */
1129     parr[3*i] = CalcRelLuminance(sspa, zsa);
1130     if (parr[3*i] < 0) parr[3*i] = 0;
1131     parr[3*i+2] = parr[3*i+1] = parr[3*i];
1132     }
1133     }