ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/gen/gendaymtx.c
Revision: 2.28
Committed: Tue Jun 25 17:06:36 2019 UTC (4 years, 10 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.27: +17 -17 lines
Log Message:
Fixed bug for first data being zero and renamed variables

File Contents

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