ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/gen/gendaymtx.c
Revision: 2.10
Committed: Sat Apr 6 00:44:59 2013 UTC (10 years, 11 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.9: +23 -10 lines
Log Message:
Added -5 option for 5-phase calculation (1 sun with fixed 0.533-deg dia.)

File Contents

# User Rev Content
1 greg 2.1 #ifndef lint
2 greg 2.10 static const char RCSid[] = "$Id: gendaymtx.c,v 2.9 2013/02/09 00:20:24 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     #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 greg 2.3 #ifndef NSUNPATCH
250 greg 2.10 #define NSUNPATCH 4 /* max. # patches to spread sun into */
251 greg 2.3 #endif
252    
253 greg 2.1 extern int jdate(int month, int day);
254     extern double stadj(int jd);
255     extern double sdec(int jd);
256     extern double salt(double sd, double st);
257     extern double sazi(double sd, double st);
258     /* sun calculation constants */
259     extern double s_latitude;
260     extern double s_longitude;
261     extern double s_meridian;
262    
263 greg 2.10 int nsuns = NSUNPATCH; /* number of sun patches to use */
264     double fixed_sun_sa = -1; /* fixed solid angle per sun? */
265    
266 greg 2.1 int verbose = 0; /* progress reports to stderr? */
267    
268     int outfmt = 'a'; /* output format */
269    
270     int rhsubdiv = 1; /* Reinhart sky subdivisions */
271    
272 greg 2.4 COLOR skycolor = {.96, 1.004, 1.118}; /* sky coloration */
273     COLOR suncolor = {1., 1., 1.}; /* sun color */
274     COLOR grefl = {.2, .2, .2}; /* ground reflectance */
275 greg 2.1
276     int nskypatch; /* number of Reinhart patches */
277     float *rh_palt; /* sky patch altitudes (radians) */
278     float *rh_pazi; /* sky patch azimuths (radians) */
279     float *rh_dom; /* sky patch solid angle (sr) */
280    
281     #define vector(v,alt,azi) ( (v)[1] = tcos(alt), \
282     (v)[0] = (v)[1]*tsin(azi), \
283     (v)[1] *= tcos(azi), \
284     (v)[2] = tsin(alt) )
285    
286     #define rh_vector(v,i) vector(v,rh_palt[i],rh_pazi[i])
287    
288     #define rh_cos(i) tsin(rh_palt[i])
289    
290     extern int rh_init(void);
291     extern float * resize_dmatrix(float *mtx_data, int nsteps, int npatch);
292     extern void AddDirect(float *parr);
293    
294     int
295     main(int argc, char *argv[])
296     {
297     char buf[256];
298 greg 2.8 double rotation = 0; /* site rotation (degrees) */
299 greg 2.1 double elevation; /* site elevation (meters) */
300     int dir_is_horiz; /* direct is meas. on horizontal? */
301     float *mtx_data = NULL; /* our matrix data */
302     int ntsteps = 0; /* number of rows in matrix */
303     int last_monthly = 0; /* month of last report */
304     int mo, da; /* month (1-12) and day (1-31) */
305     double hr; /* hour (local standard time) */
306     double dir, dif; /* direct and diffuse values */
307     int mtx_offset;
308     int i, j;
309    
310     progname = argv[0];
311     /* get options */
312     for (i = 1; i < argc && argv[i][0] == '-'; i++)
313     switch (argv[i][1]) {
314 greg 2.4 case 'g': /* ground reflectance */
315     grefl[0] = atof(argv[++i]);
316     grefl[1] = atof(argv[++i]);
317     grefl[2] = atof(argv[++i]);
318 greg 2.1 break;
319 greg 2.4 case 'v': /* verbose progress reports */
320 greg 2.1 verbose++;
321     break;
322 greg 2.4 case 'o': /* output format */
323 greg 2.1 switch (argv[i][2]) {
324     case 'f':
325     case 'd':
326     case 'a':
327     outfmt = argv[i][2];
328     break;
329     default:
330     goto userr;
331     }
332     break;
333 greg 2.4 case 'm': /* Reinhart subdivisions */
334 greg 2.1 rhsubdiv = atoi(argv[++i]);
335     break;
336 greg 2.4 case 'c': /* sky color */
337 greg 2.1 skycolor[0] = atof(argv[++i]);
338     skycolor[1] = atof(argv[++i]);
339     skycolor[2] = atof(argv[++i]);
340     break;
341 greg 2.4 case 'd': /* solar (direct) only */
342 greg 2.1 skycolor[0] = skycolor[1] = skycolor[2] = 0;
343 greg 2.4 if (suncolor[1] <= 1e-4)
344     suncolor[0] = suncolor[1] = suncolor[2] = 1;
345 greg 2.1 break;
346 greg 2.4 case 's': /* sky only (no direct) */
347     suncolor[0] = suncolor[1] = suncolor[2] = 0;
348 greg 2.1 if (skycolor[1] <= 1e-4)
349     skycolor[0] = skycolor[1] = skycolor[2] = 1;
350     break;
351 greg 2.8 case 'r': /* rotate distribution */
352     if (argv[i][2] && argv[i][2] != 'z')
353     goto userr;
354     rotation = atof(argv[++i]);
355     break;
356 greg 2.10 case '5': /* 5-phase calculation */
357     nsuns = 1;
358     fixed_sun_sa = 6.797e-05;
359     break;
360 greg 2.1 default:
361     goto userr;
362     }
363     if (i < argc-1)
364     goto userr;
365     if (i == argc-1 && freopen(argv[i], "r", stdin) == NULL) {
366     fprintf(stderr, "%s: cannot open '%s' for input\n",
367     progname, argv[i]);
368     exit(1);
369     }
370     if (verbose) {
371     if (i == argc-1)
372     fprintf(stderr, "%s: reading weather tape '%s'\n",
373     progname, argv[i]);
374     else
375     fprintf(stderr, "%s: reading weather tape from <stdin>\n",
376     progname);
377     }
378     /* read weather tape header */
379 greg 2.2 if (scanf("place %[^\r\n] ", buf) != 1)
380 greg 2.1 goto fmterr;
381     if (scanf("latitude %lf\n", &s_latitude) != 1)
382     goto fmterr;
383     if (scanf("longitude %lf\n", &s_longitude) != 1)
384     goto fmterr;
385     if (scanf("time_zone %lf\n", &s_meridian) != 1)
386     goto fmterr;
387     if (scanf("site_elevation %lf\n", &elevation) != 1)
388     goto fmterr;
389     if (scanf("weather_data_file_units %d\n", &input) != 1)
390     goto fmterr;
391     switch (input) { /* translate units */
392     case 1:
393     input = 1; /* radiometric quantities */
394     dir_is_horiz = 0; /* direct is perpendicular meas. */
395     break;
396     case 2:
397     input = 1; /* radiometric quantities */
398     dir_is_horiz = 1; /* solar measured horizontally */
399     break;
400     case 3:
401     input = 2; /* photometric quantities */
402     dir_is_horiz = 0; /* direct is perpendicular meas. */
403     break;
404     default:
405     goto fmterr;
406     }
407     rh_init(); /* initialize sky patches */
408     if (verbose) {
409     fprintf(stderr, "%s: location '%s'\n", progname, buf);
410     fprintf(stderr, "%s: (lat,long)=(%.1f,%.1f) degrees north, west\n",
411     progname, s_latitude, s_longitude);
412     fprintf(stderr, "%s: %d sky patches per time step\n",
413     progname, nskypatch);
414 greg 2.8 if (rotation != 0)
415     fprintf(stderr, "%s: rotating output %.0f degrees\n",
416     progname, rotation);
417 greg 2.1 }
418 greg 2.2 /* convert quantities to radians */
419     s_latitude = DegToRad(s_latitude);
420     s_longitude = DegToRad(s_longitude);
421     s_meridian = DegToRad(s_meridian);
422 greg 2.1 /* process each time step in tape */
423     while (scanf("%d %d %lf %lf %lf\n", &mo, &da, &hr, &dir, &dif) == 5) {
424     double sda, sta;
425     /* make space for next time step */
426     mtx_offset = 3*nskypatch*ntsteps++;
427     mtx_data = resize_dmatrix(mtx_data, ntsteps, nskypatch);
428     if (dif <= 1e-4) {
429     memset(mtx_data+mtx_offset, 0, sizeof(float)*3*nskypatch);
430     continue;
431     }
432     if (verbose && mo != last_monthly)
433     fprintf(stderr, "%s: stepping through month %d...\n",
434     progname, last_monthly=mo);
435     /* compute solar position */
436     julian_date = jdate(mo, da);
437     sda = sdec(julian_date);
438     sta = stadj(julian_date);
439     altitude = salt(sda, hr+sta);
440 greg 2.8 azimuth = sazi(sda, hr+sta) + PI - DegToRad(rotation);
441 greg 2.1 /* convert measured values */
442     if (dir_is_horiz && altitude > 0.)
443     dir /= sin(altitude);
444     if (input == 1) {
445     dir_irrad = dir;
446     diff_irrad = dif;
447     } else /* input == 2 */ {
448     dir_illum = dir;
449     diff_illum = dif;
450     }
451     /* compute sky patch values */
452     ComputeSky(mtx_data+mtx_offset);
453 greg 2.4 AddDirect(mtx_data+mtx_offset);
454 greg 2.1 }
455     /* check for junk at end */
456     while ((i = fgetc(stdin)) != EOF)
457     if (!isspace(i)) {
458     fprintf(stderr, "%s: warning - unexpected data past EOT: ",
459     progname);
460     buf[0] = i; buf[1] = '\0';
461     fgets(buf+1, sizeof(buf)-1, stdin);
462     fputs(buf, stderr); fputc('\n', stderr);
463     break;
464     }
465     /* write out matrix */
466     #ifdef getc_unlocked
467     flockfile(stdout);
468     #endif
469     if (verbose)
470     fprintf(stderr, "%s: writing %smatrix with %d time steps...\n",
471     progname, outfmt=='a' ? "" : "binary ", ntsteps);
472     /* patches are rows (outer sort) */
473     for (i = 0; i < nskypatch; i++) {
474     mtx_offset = 3*i;
475     switch (outfmt) {
476     case 'a':
477     for (j = 0; j < ntsteps; j++) {
478 greg 2.3 printf("%.3g %.3g %.3g\n", mtx_data[mtx_offset],
479 greg 2.1 mtx_data[mtx_offset+1],
480     mtx_data[mtx_offset+2]);
481     mtx_offset += 3*nskypatch;
482     }
483 greg 2.2 if (ntsteps > 1)
484     fputc('\n', stdout);
485 greg 2.1 break;
486     case 'f':
487     for (j = 0; j < ntsteps; j++) {
488     fwrite(mtx_data+mtx_offset, sizeof(float), 3,
489     stdout);
490     mtx_offset += 3*nskypatch;
491     }
492     break;
493     case 'd':
494     for (j = 0; j < ntsteps; j++) {
495     double ment[3];
496     ment[0] = mtx_data[mtx_offset];
497     ment[1] = mtx_data[mtx_offset+1];
498     ment[2] = mtx_data[mtx_offset+2];
499     fwrite(ment, sizeof(double), 3, stdout);
500     mtx_offset += 3*nskypatch;
501     }
502     break;
503     }
504     if (ferror(stdout))
505     goto writerr;
506     }
507     if (fflush(stdout) == EOF)
508     goto writerr;
509     if (verbose)
510     fprintf(stderr, "%s: done.\n", progname);
511     exit(0);
512     userr:
513 greg 2.8 fprintf(stderr, "Usage: %s [-v][-d|-s][-r deg][-m N][-g r g b][-c r g b][-o{f|d}] [tape.wea]\n",
514 greg 2.1 progname);
515     exit(1);
516     fmterr:
517     fprintf(stderr, "%s: input weather tape format error\n", progname);
518     exit(1);
519     writerr:
520     fprintf(stderr, "%s: write error on output\n", progname);
521     exit(1);
522     }
523    
524     /* Return maximum of two doubles */
525     double dmax( double a, double b )
526     { return (a > b) ? a : b; }
527    
528     /* Compute sky patch radiance values (modified by GW) */
529     void
530     ComputeSky(float *parr)
531     {
532     int index; /* Category index */
533     double norm_diff_illum; /* Normalized diffuse illuimnance */
534     int i;
535    
536     /* Calculate atmospheric precipitable water content */
537     apwc = CalcPrecipWater(dew_point);
538    
539 greg 2.6 /* Calculate sun zenith angle (don't let it dip below horizon) */
540     /* Also limit minimum angle to keep circumsolar off zenith */
541     if (altitude <= 0.0)
542     sun_zenith = DegToRad(90.0);
543     else if (altitude >= DegToRad(87.0))
544     sun_zenith = DegToRad(3.0);
545     else
546     sun_zenith = DegToRad(90.0) - altitude;
547 greg 2.1
548     /* Compute the inputs for the calculation of the sky distribution */
549    
550     if (input == 0) /* XXX never used */
551     {
552     /* Calculate irradiance */
553     diff_irrad = CalcDiffuseIrradiance();
554     dir_irrad = CalcDirectIrradiance();
555    
556     /* Calculate illuminance */
557     index = GetCategoryIndex();
558     diff_illum = diff_irrad * CalcDiffuseIllumRatio(index);
559     dir_illum = dir_irrad * CalcDirectIllumRatio(index);
560     }
561     else if (input == 1)
562     {
563     sky_brightness = CalcSkyBrightness();
564     sky_clearness = CalcSkyClearness();
565    
566 greg 2.9 /* Limit sky clearness */
567     if (sky_clearness > 11.9)
568     sky_clearness = 11.9;
569    
570     /* Limit sky brightness */
571     if (sky_brightness < 0.01)
572     sky_brightness = 0.01;
573    
574 greg 2.1 /* Calculate illuminance */
575     index = GetCategoryIndex();
576     diff_illum = diff_irrad * CalcDiffuseIllumRatio(index);
577     dir_illum = dir_irrad * CalcDirectIllumRatio(index);
578     }
579     else if (input == 2)
580     {
581     /* Calculate sky brightness and clearness from illuminance values */
582     index = CalcSkyParamFromIllum();
583     }
584    
585 greg 2.2 if (bright(skycolor) <= 1e-4) { /* 0 sky component? */
586     memset(parr, 0, sizeof(float)*3*nskypatch);
587     return;
588     }
589 greg 2.1 /* Compute ground radiance (include solar contribution if any) */
590 greg 2.3 parr[0] = diff_illum;
591 greg 2.1 if (altitude > 0)
592 greg 2.3 parr[0] += dir_illum * sin(altitude);
593 greg 2.4 parr[2] = parr[1] = parr[0] *= (1./PI/WHTEFFICACY);
594     multcolor(parr, grefl);
595 greg 2.1
596     /* Calculate Perez sky model parameters */
597     CalcPerezParam(sun_zenith, sky_clearness, sky_brightness, index);
598    
599     /* Calculate sky patch luminance values */
600     CalcSkyPatchLumin(parr);
601    
602     /* Calculate relative horizontal illuminance */
603     norm_diff_illum = CalcRelHorzIllum(parr);
604    
605     /* Normalization coefficient */
606     norm_diff_illum = diff_illum / norm_diff_illum;
607    
608     /* Apply to sky patches to get absolute radiance values */
609     for (i = 1; i < nskypatch; i++) {
610 greg 2.7 scalecolor(parr+3*i, norm_diff_illum*(1./WHTEFFICACY));
611 greg 2.1 multcolor(parr+3*i, skycolor);
612     }
613     }
614    
615     /* Add in solar direct to nearest sky patches (GW) */
616     void
617     AddDirect(float *parr)
618     {
619     FVECT svec;
620 greg 2.3 double near_dprod[NSUNPATCH];
621     int near_patch[NSUNPATCH];
622     double wta[NSUNPATCH], wtot;
623 greg 2.1 int i, j, p;
624    
625 greg 2.4 if (dir_illum <= 1e-4 || bright(suncolor) <= 1e-4)
626 greg 2.1 return;
627 greg 2.10 /* identify nsuns closest patches */
628     if (nsuns > NSUNPATCH)
629     nsuns = NSUNPATCH;
630     else if (nsuns <= 0)
631     nsuns = 1;
632     for (i = nsuns; i--; )
633 greg 2.1 near_dprod[i] = -1.;
634     vector(svec, altitude, azimuth);
635     for (p = 1; p < nskypatch; p++) {
636     FVECT pvec;
637     double dprod;
638     rh_vector(pvec, p);
639     dprod = DOT(pvec, svec);
640 greg 2.10 for (i = 0; i < nsuns; i++)
641 greg 2.1 if (dprod > near_dprod[i]) {
642 greg 2.10 for (j = nsuns; --j > i; ) {
643 greg 2.1 near_dprod[j] = near_dprod[j-1];
644     near_patch[j] = near_patch[j-1];
645     }
646     near_dprod[i] = dprod;
647     near_patch[i] = p;
648     break;
649     }
650     }
651     wtot = 0; /* weight by proximity */
652 greg 2.10 for (i = nsuns; i--; )
653 greg 2.1 wtot += wta[i] = 1./(1.002 - near_dprod[i]);
654     /* add to nearest patch radiances */
655 greg 2.10 for (i = nsuns; i--; ) {
656 greg 2.2 float *pdest = parr + 3*near_patch[i];
657 greg 2.10 float val_add = wta[i] * dir_illum / (WHTEFFICACY * wtot);
658    
659     val_add /= (fixed_sun_sa > 0) ? fixed_sun_sa
660     : rh_dom[near_patch[i]] ;
661 greg 2.4 *pdest++ += val_add*suncolor[0];
662     *pdest++ += val_add*suncolor[1];
663     *pdest++ += val_add*suncolor[2];
664 greg 2.2 }
665 greg 2.1 }
666    
667     /* Initialize Reinhart sky patch positions (GW) */
668     int
669     rh_init(void)
670     {
671     #define NROW 7
672     static const int tnaz[NROW] = {30, 30, 24, 24, 18, 12, 6};
673     const double alpha = (PI/2.)/(NROW*rhsubdiv + .5);
674     int p, i, j;
675     /* allocate patch angle arrays */
676     nskypatch = 0;
677     for (p = 0; p < NROW; p++)
678     nskypatch += tnaz[p];
679     nskypatch *= rhsubdiv*rhsubdiv;
680     nskypatch += 2;
681     rh_palt = (float *)malloc(sizeof(float)*nskypatch);
682     rh_pazi = (float *)malloc(sizeof(float)*nskypatch);
683     rh_dom = (float *)malloc(sizeof(float)*nskypatch);
684     if ((rh_palt == NULL) | (rh_pazi == NULL) | (rh_dom == NULL)) {
685     fprintf(stderr, "%s: out of memory in rh_init()\n", progname);
686     exit(1);
687     }
688     rh_palt[0] = -PI/2.; /* ground & zenith patches */
689     rh_pazi[0] = 0.;
690     rh_dom[0] = 2.*PI;
691     rh_palt[nskypatch-1] = PI/2.;
692     rh_pazi[nskypatch-1] = 0.;
693     rh_dom[nskypatch-1] = 2.*PI*(1. - cos(alpha*.5));
694     p = 1; /* "normal" patches */
695     for (i = 0; i < NROW*rhsubdiv; i++) {
696     const float ralt = alpha*(i + .5);
697     const int ninrow = tnaz[i/rhsubdiv]*rhsubdiv;
698 greg 2.3 const float dom = 2.*PI*(sin(alpha*(i+1)) - sin(alpha*i)) /
699     (double)ninrow;
700 greg 2.1 for (j = 0; j < ninrow; j++) {
701     rh_palt[p] = ralt;
702     rh_pazi[p] = 2.*PI * j / (double)ninrow;
703     rh_dom[p++] = dom;
704     }
705     }
706     return nskypatch;
707     #undef NROW
708     }
709    
710     /* Resize daylight matrix (GW) */
711     float *
712     resize_dmatrix(float *mtx_data, int nsteps, int npatch)
713     {
714     if (mtx_data == NULL)
715     mtx_data = (float *)malloc(sizeof(float)*3*nsteps*npatch);
716     else
717     mtx_data = (float *)realloc(mtx_data,
718     sizeof(float)*3*nsteps*npatch);
719     if (mtx_data == NULL) {
720     fprintf(stderr, "%s: out of memory in resize_dmatrix(%d,%d)\n",
721     progname, nsteps, npatch);
722     exit(1);
723     }
724     return(mtx_data);
725     }
726    
727     /* Determine category index */
728     int GetCategoryIndex()
729     {
730     int index; /* Loop index */
731    
732     for (index = 0; index < 8; index++)
733     if ((sky_clearness >= SkyClearCat[index].lower) &&
734     (sky_clearness < SkyClearCat[index].upper))
735     break;
736    
737     return index;
738     }
739    
740     /* Calculate diffuse illuminance to diffuse irradiance ratio */
741    
742     /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
743     /* Stewart. 1990. ìModeling Daylight Availability and */
744     /* Irradiance Components from Direct and Global */
745     /* Irradiance,î Solar Energy 44(5):271-289, Eqn. 7. */
746    
747     double CalcDiffuseIllumRatio( int index )
748     {
749     ModelCoeff const *pnle; /* Category coefficient pointer */
750    
751     /* Get category coefficient pointer */
752     pnle = &(DiffuseLumEff[index]);
753    
754     return pnle->a + pnle->b * apwc + pnle->c * cos(sun_zenith) +
755     pnle->d * log(sky_brightness);
756     }
757    
758     /* Calculate direct illuminance to direct irradiance ratio */
759    
760     /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
761     /* Stewart. 1990. ìModeling Daylight Availability and */
762     /* Irradiance Components from Direct and Global */
763     /* Irradiance,î Solar Energy 44(5):271-289, Eqn. 8. */
764    
765     double CalcDirectIllumRatio( int index )
766     {
767     ModelCoeff const *pnle; /* Category coefficient pointer */
768    
769     /* Get category coefficient pointer */
770     pnle = &(DirectLumEff[index]);
771    
772     /* Calculate direct illuminance from direct irradiance */
773    
774     return dmax((pnle->a + pnle->b * apwc + pnle->c * exp(5.73 *
775     sun_zenith - 5.0) + pnle->d * sky_brightness),
776     0.0);
777     }
778    
779     /* Calculate sky brightness */
780    
781     /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
782     /* Stewart. 1990. ìModeling Daylight Availability and */
783     /* Irradiance Components from Direct and Global */
784     /* Irradiance,î Solar Energy 44(5):271-289, Eqn. 2. */
785    
786     double CalcSkyBrightness()
787     {
788     return diff_irrad * CalcAirMass() / (DC_SolarConstantE *
789     CalcEccentricity());
790     }
791    
792     /* Calculate sky clearness */
793    
794     /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
795     /* Stewart. 1990. ìModeling Daylight Availability and */
796     /* Irradiance Components from Direct and Global */
797     /* Irradiance,î Solar Energy 44(5):271-289, Eqn. 1. */
798    
799     double CalcSkyClearness()
800     {
801     double sz_cubed; /* Sun zenith angle cubed */
802    
803     /* Calculate sun zenith angle cubed */
804     sz_cubed = pow(sun_zenith, 3.0);
805    
806     return ((diff_irrad + dir_irrad) / diff_irrad + 1.041 *
807     sz_cubed) / (1.0 + 1.041 * sz_cubed);
808     }
809    
810     /* Calculate diffuse horizontal irradiance from Perez sky brightness */
811    
812     /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
813     /* Stewart. 1990. ìModeling Daylight Availability and */
814     /* Irradiance Components from Direct and Global */
815     /* Irradiance,î Solar Energy 44(5):271-289, Eqn. 2 */
816     /* (inverse). */
817    
818     double CalcDiffuseIrradiance()
819     {
820     return sky_brightness * DC_SolarConstantE * CalcEccentricity() /
821     CalcAirMass();
822     }
823    
824     /* Calculate direct normal irradiance from Perez sky clearness */
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. 1 */
830     /* (inverse). */
831    
832     double CalcDirectIrradiance()
833     {
834     return CalcDiffuseIrradiance() * ((sky_clearness - 1.0) * (1 + 1.041
835     * pow(sun_zenith, 3.0)));
836     }
837    
838     /* Calculate sky brightness and clearness from illuminance values */
839     int CalcSkyParamFromIllum()
840     {
841     double test1 = 0.1;
842     double test2 = 0.1;
843     int counter = 0;
844     int index = 0; /* Category index */
845    
846     /* Convert illuminance to irradiance */
847     diff_irrad = diff_illum * DC_SolarConstantE /
848     (DC_SolarConstantL * 1000.0);
849     dir_irrad = dir_illum * DC_SolarConstantE /
850     (DC_SolarConstantL * 1000.0);
851    
852     /* Calculate sky brightness and clearness */
853     sky_brightness = CalcSkyBrightness();
854     sky_clearness = CalcSkyClearness();
855    
856     /* Limit sky clearness */
857     if (sky_clearness > 12.0)
858     sky_clearness = 12.0;
859    
860     /* Limit sky brightness */
861 greg 2.9 if (sky_brightness < 0.01)
862 greg 2.1 sky_brightness = 0.01;
863    
864     while (((fabs(diff_irrad - test1) > 10.0) ||
865     (fabs(dir_irrad - test2) > 10.0)) && !(counter == 5))
866     {
867     test1 = diff_irrad;
868     test2 = dir_irrad;
869     counter++;
870    
871     /* Convert illuminance to irradiance */
872     index = GetCategoryIndex();
873     diff_irrad = diff_illum / CalcDiffuseIllumRatio(index);
874     dir_irrad = dir_illum / CalcDirectIllumRatio(index);
875    
876     /* Calculate sky brightness and clearness */
877     sky_brightness = CalcSkyBrightness();
878     sky_clearness = CalcSkyClearness();
879    
880     /* Limit sky clearness */
881     if (sky_clearness > 12.0)
882     sky_clearness = 12.0;
883    
884     /* Limit sky brightness */
885 greg 2.9 if (sky_brightness < 0.01)
886 greg 2.1 sky_brightness = 0.01;
887     }
888    
889     return GetCategoryIndex();
890     }
891    
892     /* Calculate relative luminance */
893    
894     /* Reference: Perez, R., R. Seals, and J. Michalsky. 1993. */
895     /* ìAll-Weather Model for Sky Luminance Distribution - */
896     /* Preliminary Configuration and Validation,î Solar Energy */
897     /* 50(3):235-245, Eqn. 1. */
898    
899     double CalcRelLuminance( double gamma, double zeta )
900     {
901     return (1.0 + perez_param[0] * exp(perez_param[1] / cos(zeta))) *
902     (1.0 + perez_param[2] * exp(perez_param[3] * gamma) +
903     perez_param[4] * cos(gamma) * cos(gamma));
904     }
905    
906     /* Calculate Perez sky model parameters */
907    
908     /* Reference: Perez, R., R. Seals, and J. Michalsky. 1993. */
909     /* ìAll-Weather Model for Sky Luminance Distribution - */
910     /* Preliminary Configuration and Validation,î Solar Energy */
911     /* 50(3):235-245, Eqns. 6 - 8. */
912    
913     void CalcPerezParam( double sz, double epsilon, double delta,
914     int index )
915     {
916     double x[5][4]; /* Coefficents a, b, c, d, e */
917     int i, j; /* Loop indices */
918    
919     /* Limit sky brightness */
920     if (epsilon > 1.065 && epsilon < 2.8)
921     {
922     if (delta < 0.2)
923     delta = 0.2;
924     }
925    
926     /* Get Perez coefficients */
927     for (i = 0; i < 5; i++)
928     for (j = 0; j < 4; j++)
929     x[i][j] = PerezCoeff[index][4 * i + j];
930    
931     if (index != 0)
932     {
933     /* Calculate parameter a, b, c, d and e (Eqn. 6) */
934     for (i = 0; i < 5; i++)
935     perez_param[i] = x[i][0] + x[i][1] * sz + delta * (x[i][2] +
936     x[i][3] * sz);
937     }
938     else
939     {
940     /* Parameters a, b and e (Eqn. 6) */
941     perez_param[0] = x[0][0] + x[0][1] * sz + delta * (x[0][2] +
942     x[0][3] * sz);
943     perez_param[1] = x[1][0] + x[1][1] * sz + delta * (x[1][2] +
944     x[1][3] * sz);
945     perez_param[4] = x[4][0] + x[4][1] * sz + delta * (x[4][2] +
946     x[4][3] * sz);
947    
948     /* Parameter c (Eqn. 7) */
949     perez_param[2] = exp(pow(delta * (x[2][0] + x[2][1] * sz),
950     x[2][2])) - x[2][3];
951    
952     /* Parameter d (Eqn. 8) */
953     perez_param[3] = -exp(delta * (x[3][0] + x[3][1] * sz)) +
954     x[3][2] + delta * x[3][3];
955     }
956     }
957    
958     /* Calculate relative horizontal illuminance (modified by GW) */
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. 3. */
964    
965     double CalcRelHorzIllum( float *parr )
966     {
967     int i;
968     double rh_illum = 0.0; /* Relative horizontal illuminance */
969    
970     for (i = 1; i < nskypatch; i++)
971 greg 2.7 rh_illum += parr[3*i+1] * rh_cos(i) * rh_dom[i];
972 greg 2.1
973 greg 2.7 return rh_illum;
974 greg 2.1 }
975    
976     /* Calculate earth orbit eccentricity correction factor */
977    
978     /* Reference: Sen, Z. 2008. Solar Energy Fundamental and Modeling */
979     /* Techniques. Springer, p. 72. */
980    
981     double CalcEccentricity()
982     {
983     double day_angle; /* Day angle (radians) */
984     double E0; /* Eccentricity */
985    
986     /* Calculate day angle */
987     day_angle = (julian_date - 1.0) * (2.0 * PI / 365.0);
988    
989     /* Calculate eccentricity */
990     E0 = 1.00011 + 0.034221 * cos(day_angle) + 0.00128 * sin(day_angle)
991     + 0.000719 * cos(2.0 * day_angle) + 0.000077 * sin(2.0 *
992     day_angle);
993    
994     return E0;
995     }
996    
997     /* Calculate atmospheric precipitable water content */
998    
999     /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
1000     /* Stewart. 1990. ìModeling Daylight Availability and */
1001     /* Irradiance Components from Direct and Global */
1002     /* Irradiance,î Solar Energy 44(5):271-289, Eqn. 3. */
1003    
1004     /* Note: The default surface dew point temperature is 11 deg. C */
1005     /* (52 deg. F). Typical values are: */
1006    
1007     /* Celsius Fahrenheit Human Perception */
1008     /* > 24 > 75 Extremely uncomfortable */
1009     /* 21 - 24 70 - 74 Very humid */
1010     /* 18 - 21 65 - 69 Somewhat uncomfortable */
1011     /* 16 - 18 60 - 64 OK for most people */
1012     /* 13 - 16 55 - 59 Comfortable */
1013     /* 10 - 12 50 - 54 Very comfortable */
1014     /* < 10 < 49 A bit dry for some */
1015    
1016     double CalcPrecipWater( double dpt )
1017     { return exp(0.07 * dpt - 0.075); }
1018    
1019     /* Calculate relative air mass */
1020    
1021     /* Reference: Kasten, F. 1966. "A New Table and Approximation Formula */
1022     /* for the Relative Optical Air Mass," Arch. Meteorol. */
1023     /* Geophys. Bioklimataol. Ser. B14, pp. 206-233. */
1024    
1025     /* Note: More sophisticated relative air mass models are */
1026     /* available, but they differ significantly only for */
1027     /* sun zenith angles greater than 80 degrees. */
1028    
1029     double CalcAirMass()
1030     {
1031     return (1.0 / (cos(sun_zenith) + 0.15 * pow(93.885 -
1032     RadToDeg(sun_zenith), -1.253)));
1033     }
1034    
1035     /* Calculate Perez All-Weather sky patch luminances (modified by GW) */
1036    
1037     /* NOTE: The sky patches centers are determined in accordance with the */
1038     /* BRE-IDMP sky luminance measurement procedures. (See for example */
1039     /* Mardaljevic, J. 2001. "The BRE-IDMP Dataset: A New Benchmark */
1040     /* for the Validation of Illuminance Prediction Techniques," */
1041     /* Lighting Research & Technology 33(2):117-136.) */
1042    
1043     void CalcSkyPatchLumin( float *parr )
1044     {
1045     int i;
1046     double aas; /* Sun-sky point azimuthal angle */
1047     double sspa; /* Sun-sky point angle */
1048     double zsa; /* Zenithal sun angle */
1049    
1050     for (i = 1; i < nskypatch; i++)
1051     {
1052     /* Calculate sun-sky point azimuthal angle */
1053     aas = fabs(rh_pazi[i] - azimuth);
1054    
1055     /* Calculate zenithal sun angle */
1056     zsa = PI * 0.5 - rh_palt[i];
1057    
1058     /* Calculate sun-sky point angle (Equation 8-20) */
1059     sspa = acos(cos(sun_zenith) * cos(zsa) + sin(sun_zenith) *
1060     sin(zsa) * cos(aas));
1061    
1062     /* Calculate patch luminance */
1063     parr[3*i] = CalcRelLuminance(sspa, zsa);
1064     if (parr[3*i] < 0) parr[3*i] = 0;
1065     parr[3*i+2] = parr[3*i+1] = parr[3*i];
1066     }
1067     }