ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/gen/gendaymtx.c
Revision: 2.8
Committed: Tue Feb 5 06:00:19 2013 UTC (11 years, 2 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.7: +12 -3 lines
Log Message:
Added -r option to gendaymtx for rotating the sky about the zenith

File Contents

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