ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/gen/gendaymtx.c
Revision: 2.1
Committed: Fri Jan 18 01:12:59 2013 UTC (11 years, 3 months ago) by greg
Content type: text/plain
Branch: MAIN
Log Message:
Wrote gendaymtx based on Ian Ashdown's H32_gendaylit.c -- untested as yet

File Contents

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