/[radiance]/ray/src/gen/gendaymtx.c
ViewVC logotype

Contents of /ray/src/gen/gendaymtx.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2.30 - (show annotations) (download)
Thu Nov 7 23:15:07 2019 UTC (5 weeks, 2 days ago) by greg
Branch: MAIN
CVS Tags: HEAD
Changes since 2.29: +3 -14 lines
File MIME type: text/plain
Added more accurate Michalsky solar position calculation and made correction to old IES handbook formula (thanks to Axel Jacobs)

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

webmaster-btp@lbl.gov
ViewVC Help
Powered by ViewVC 1.1.27