/[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.29 - (show annotations) (download)
Wed Aug 14 21:00:14 2019 UTC (4 weeks, 3 days ago) by greg
Branch: MAIN
CVS Tags: HEAD
Changes since 2.28: +3 -1 lines
File MIME type: text/plain
Added byte order to gendaymtx, rsplit, dctimestep, rcode_depth, and rcode_normal

1 #ifndef lint
2 static const char RCSid[] = "$Id: gendaymtx.c,v 2.28 2019/06/25 17:06:36 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 "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 if ((outfmt == 'f') | (outfmt == 'd'))
562 fputendian(stdout);
563 fputformat((char *)getfmtname(outfmt), stdout);
564 putchar('\n');
565 }
566 /* patches are rows (outer sort) */
567 for (i = 0; i < nskypatch; i++) {
568 mtx_offset = 3*i;
569 switch (outfmt) {
570 case 'a':
571 for (j = 0; j < nstored; j++) {
572 printf("%.3g %.3g %.3g\n", mtx_data[mtx_offset],
573 mtx_data[mtx_offset+1],
574 mtx_data[mtx_offset+2]);
575 mtx_offset += 3*nskypatch;
576 }
577 if (nstored > 1)
578 fputc('\n', stdout);
579 break;
580 case 'f':
581 for (j = 0; j < nstored; j++) {
582 putbinary(mtx_data+mtx_offset, sizeof(float), 3,
583 stdout);
584 mtx_offset += 3*nskypatch;
585 }
586 break;
587 case 'd':
588 for (j = 0; j < nstored; j++) {
589 double ment[3];
590 ment[0] = mtx_data[mtx_offset];
591 ment[1] = mtx_data[mtx_offset+1];
592 ment[2] = mtx_data[mtx_offset+2];
593 putbinary(ment, sizeof(double), 3, stdout);
594 mtx_offset += 3*nskypatch;
595 }
596 break;
597 }
598 if (ferror(stdout))
599 goto writerr;
600 }
601 if (fflush(stdout) == EOF)
602 goto writerr;
603 if (verbose)
604 fprintf(stderr, "%s: done.\n", progname);
605 exit(0);
606 userr:
607 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",
608 progname);
609 exit(1);
610 fmterr:
611 fprintf(stderr, "%s: input weather tape format error\n", progname);
612 exit(1);
613 writerr:
614 fprintf(stderr, "%s: write error on output\n", progname);
615 exit(1);
616 }
617
618 /* Return maximum of two doubles */
619 double dmax( double a, double b )
620 { return (a > b) ? a : b; }
621
622 /* Compute sky patch radiance values (modified by GW) */
623 void
624 ComputeSky(float *parr)
625 {
626 int index; /* Category index */
627 double norm_diff_illum; /* Normalized diffuse illuimnance */
628 int i;
629
630 /* Calculate atmospheric precipitable water content */
631 apwc = CalcPrecipWater(dew_point);
632
633 /* Calculate sun zenith angle (don't let it dip below horizon) */
634 /* Also limit minimum angle to keep circumsolar off zenith */
635 if (altitude <= 0.0)
636 sun_zenith = DegToRad(90.0);
637 else if (altitude >= DegToRad(87.0))
638 sun_zenith = DegToRad(3.0);
639 else
640 sun_zenith = DegToRad(90.0) - altitude;
641
642 /* Compute the inputs for the calculation of the sky distribution */
643
644 if (input == 0) /* XXX never used */
645 {
646 /* Calculate irradiance */
647 diff_irrad = CalcDiffuseIrradiance();
648 dir_irrad = CalcDirectIrradiance();
649
650 /* Calculate illuminance */
651 index = GetCategoryIndex();
652 diff_illum = diff_irrad * CalcDiffuseIllumRatio(index);
653 dir_illum = dir_irrad * CalcDirectIllumRatio(index);
654 }
655 else if (input == 1)
656 {
657 sky_brightness = CalcSkyBrightness();
658 sky_clearness = CalcSkyClearness();
659
660 /* Limit sky clearness */
661 if (sky_clearness > 11.9)
662 sky_clearness = 11.9;
663
664 /* Limit sky brightness */
665 if (sky_brightness < 0.01)
666 sky_brightness = 0.01;
667
668 /* Calculate illuminance */
669 index = GetCategoryIndex();
670 diff_illum = diff_irrad * CalcDiffuseIllumRatio(index);
671 dir_illum = dir_irrad * CalcDirectIllumRatio(index);
672 }
673 else if (input == 2)
674 {
675 /* Calculate sky brightness and clearness from illuminance values */
676 index = CalcSkyParamFromIllum();
677 }
678
679 if (output == 1) { /* hack for solar radiance */
680 diff_illum = diff_irrad * WHTEFFICACY;
681 dir_illum = dir_irrad * WHTEFFICACY;
682 }
683
684 if (bright(skycolor) <= 1e-4) { /* 0 sky component? */
685 memset(parr, 0, sizeof(float)*3*nskypatch);
686 return;
687 }
688 /* Compute ground radiance (include solar contribution if any) */
689 parr[0] = diff_illum;
690 if (altitude > 0)
691 parr[0] += dir_illum * sin(altitude);
692 parr[2] = parr[1] = parr[0] *= (1./PI/WHTEFFICACY);
693 multcolor(parr, grefl);
694
695 /* Calculate Perez sky model parameters */
696 CalcPerezParam(sun_zenith, sky_clearness, sky_brightness, index);
697
698 /* Calculate sky patch luminance values */
699 CalcSkyPatchLumin(parr);
700
701 /* Calculate relative horizontal illuminance */
702 norm_diff_illum = CalcRelHorzIllum(parr);
703
704 /* Check for zero sky -- make uniform in that case */
705 if (norm_diff_illum <= FTINY) {
706 for (i = 1; i < nskypatch; i++)
707 setcolor(parr+3*i, 1., 1., 1.);
708 norm_diff_illum = PI;
709 }
710 /* Normalization coefficient */
711 norm_diff_illum = diff_illum / norm_diff_illum;
712
713 /* Apply to sky patches to get absolute radiance values */
714 for (i = 1; i < nskypatch; i++) {
715 scalecolor(parr+3*i, norm_diff_illum*(1./WHTEFFICACY));
716 multcolor(parr+3*i, skycolor);
717 }
718 }
719
720 /* Add in solar direct to nearest sky patches (GW) */
721 void
722 AddDirect(float *parr)
723 {
724 FVECT svec;
725 double near_dprod[NSUNPATCH];
726 int near_patch[NSUNPATCH];
727 double wta[NSUNPATCH], wtot;
728 int i, j, p;
729
730 if (dir_illum <= 1e-4 || bright(suncolor) <= 1e-4)
731 return;
732 /* identify nsuns closest patches */
733 if (nsuns > NSUNPATCH)
734 nsuns = NSUNPATCH;
735 else if (nsuns <= 0)
736 nsuns = 1;
737 for (i = nsuns; i--; )
738 near_dprod[i] = -1.;
739 vector(svec, altitude, azimuth);
740 for (p = 1; p < nskypatch; p++) {
741 FVECT pvec;
742 double dprod;
743 rh_vector(pvec, p);
744 dprod = DOT(pvec, svec);
745 for (i = 0; i < nsuns; i++)
746 if (dprod > near_dprod[i]) {
747 for (j = nsuns; --j > i; ) {
748 near_dprod[j] = near_dprod[j-1];
749 near_patch[j] = near_patch[j-1];
750 }
751 near_dprod[i] = dprod;
752 near_patch[i] = p;
753 break;
754 }
755 }
756 wtot = 0; /* weight by proximity */
757 for (i = nsuns; i--; )
758 wtot += wta[i] = 1./(1.002 - near_dprod[i]);
759 /* add to nearest patch radiances */
760 for (i = nsuns; i--; ) {
761 float *pdest = parr + 3*near_patch[i];
762 float val_add = wta[i] * dir_illum / (WHTEFFICACY * wtot);
763
764 val_add /= (fixed_sun_sa > 0) ? fixed_sun_sa
765 : rh_dom[near_patch[i]] ;
766 *pdest++ += val_add*suncolor[0];
767 *pdest++ += val_add*suncolor[1];
768 *pdest++ += val_add*suncolor[2];
769 }
770 }
771
772 /* Initialize Reinhart sky patch positions (GW) */
773 int
774 rh_init(void)
775 {
776 #define NROW 7
777 static const int tnaz[NROW] = {30, 30, 24, 24, 18, 12, 6};
778 const double alpha = (PI/2.)/(NROW*rhsubdiv + .5);
779 int p, i, j;
780 /* allocate patch angle arrays */
781 nskypatch = 0;
782 for (p = 0; p < NROW; p++)
783 nskypatch += tnaz[p];
784 nskypatch *= rhsubdiv*rhsubdiv;
785 nskypatch += 2;
786 rh_palt = (float *)malloc(sizeof(float)*nskypatch);
787 rh_pazi = (float *)malloc(sizeof(float)*nskypatch);
788 rh_dom = (float *)malloc(sizeof(float)*nskypatch);
789 if ((rh_palt == NULL) | (rh_pazi == NULL) | (rh_dom == NULL)) {
790 fprintf(stderr, "%s: out of memory in rh_init()\n", progname);
791 exit(1);
792 }
793 rh_palt[0] = -PI/2.; /* ground & zenith patches */
794 rh_pazi[0] = 0.;
795 rh_dom[0] = 2.*PI;
796 rh_palt[nskypatch-1] = PI/2.;
797 rh_pazi[nskypatch-1] = 0.;
798 rh_dom[nskypatch-1] = 2.*PI*(1. - cos(alpha*.5));
799 p = 1; /* "normal" patches */
800 for (i = 0; i < NROW*rhsubdiv; i++) {
801 const float ralt = alpha*(i + .5);
802 const int ninrow = tnaz[i/rhsubdiv]*rhsubdiv;
803 const float dom = 2.*PI*(sin(alpha*(i+1)) - sin(alpha*i)) /
804 (double)ninrow;
805 for (j = 0; j < ninrow; j++) {
806 rh_palt[p] = ralt;
807 rh_pazi[p] = 2.*PI * j / (double)ninrow;
808 rh_dom[p++] = dom;
809 }
810 }
811 return nskypatch;
812 #undef NROW
813 }
814
815 /* Resize daylight matrix (GW) */
816 float *
817 resize_dmatrix(float *mtx_data, int nsteps, int npatch)
818 {
819 if (mtx_data == NULL)
820 mtx_data = (float *)malloc(sizeof(float)*3*nsteps*npatch);
821 else
822 mtx_data = (float *)realloc(mtx_data,
823 sizeof(float)*3*nsteps*npatch);
824 if (mtx_data == NULL) {
825 fprintf(stderr, "%s: out of memory in resize_dmatrix(%d,%d)\n",
826 progname, nsteps, npatch);
827 exit(1);
828 }
829 return(mtx_data);
830 }
831
832 /* Determine category index */
833 int GetCategoryIndex()
834 {
835 int index; /* Loop index */
836
837 for (index = 0; index < 8; index++)
838 if ((sky_clearness >= SkyClearCat[index].lower) &&
839 (sky_clearness < SkyClearCat[index].upper))
840 break;
841
842 return index;
843 }
844
845 /* Calculate diffuse illuminance to diffuse irradiance ratio */
846
847 /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
848 /* Stewart. 1990. ìModeling Daylight Availability and */
849 /* Irradiance Components from Direct and Global */
850 /* Irradiance,î Solar Energy 44(5):271-289, Eqn. 7. */
851
852 double CalcDiffuseIllumRatio( int index )
853 {
854 ModelCoeff const *pnle; /* Category coefficient pointer */
855
856 /* Get category coefficient pointer */
857 pnle = &(DiffuseLumEff[index]);
858
859 return pnle->a + pnle->b * apwc + pnle->c * cos(sun_zenith) +
860 pnle->d * log(sky_brightness);
861 }
862
863 /* Calculate direct illuminance to direct irradiance ratio */
864
865 /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
866 /* Stewart. 1990. ìModeling Daylight Availability and */
867 /* Irradiance Components from Direct and Global */
868 /* Irradiance,î Solar Energy 44(5):271-289, Eqn. 8. */
869
870 double CalcDirectIllumRatio( int index )
871 {
872 ModelCoeff const *pnle; /* Category coefficient pointer */
873
874 /* Get category coefficient pointer */
875 pnle = &(DirectLumEff[index]);
876
877 /* Calculate direct illuminance from direct irradiance */
878
879 return dmax((pnle->a + pnle->b * apwc + pnle->c * exp(5.73 *
880 sun_zenith - 5.0) + pnle->d * sky_brightness),
881 0.0);
882 }
883
884 /* Calculate sky brightness */
885
886 /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
887 /* Stewart. 1990. ìModeling Daylight Availability and */
888 /* Irradiance Components from Direct and Global */
889 /* Irradiance,î Solar Energy 44(5):271-289, Eqn. 2. */
890
891 double CalcSkyBrightness()
892 {
893 return diff_irrad * CalcAirMass() / (DC_SolarConstantE *
894 CalcEccentricity());
895 }
896
897 /* Calculate sky clearness */
898
899 /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
900 /* Stewart. 1990. ìModeling Daylight Availability and */
901 /* Irradiance Components from Direct and Global */
902 /* Irradiance,î Solar Energy 44(5):271-289, Eqn. 1. */
903
904 double CalcSkyClearness()
905 {
906 double sz_cubed; /* Sun zenith angle cubed */
907
908 /* Calculate sun zenith angle cubed */
909 sz_cubed = sun_zenith*sun_zenith*sun_zenith;
910
911 return ((diff_irrad + dir_irrad) / diff_irrad + 1.041 *
912 sz_cubed) / (1.0 + 1.041 * sz_cubed);
913 }
914
915 /* Calculate diffuse horizontal irradiance from Perez sky brightness */
916
917 /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
918 /* Stewart. 1990. ìModeling Daylight Availability and */
919 /* Irradiance Components from Direct and Global */
920 /* Irradiance,î Solar Energy 44(5):271-289, Eqn. 2 */
921 /* (inverse). */
922
923 double CalcDiffuseIrradiance()
924 {
925 return sky_brightness * DC_SolarConstantE * CalcEccentricity() /
926 CalcAirMass();
927 }
928
929 /* Calculate direct normal irradiance from Perez sky clearness */
930
931 /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
932 /* Stewart. 1990. ìModeling Daylight Availability and */
933 /* Irradiance Components from Direct and Global */
934 /* Irradiance,î Solar Energy 44(5):271-289, Eqn. 1 */
935 /* (inverse). */
936
937 double CalcDirectIrradiance()
938 {
939 return CalcDiffuseIrradiance() * ((sky_clearness - 1.0) * (1 + 1.041
940 * sun_zenith*sun_zenith*sun_zenith));
941 }
942
943 /* Calculate sky brightness and clearness from illuminance values */
944 int CalcSkyParamFromIllum()
945 {
946 double test1 = 0.1;
947 double test2 = 0.1;
948 int counter = 0;
949 int index = 0; /* Category index */
950
951 /* Convert illuminance to irradiance */
952 diff_irrad = diff_illum * DC_SolarConstantE /
953 (DC_SolarConstantL * 1000.0);
954 dir_irrad = dir_illum * DC_SolarConstantE /
955 (DC_SolarConstantL * 1000.0);
956
957 /* Calculate sky brightness and clearness */
958 sky_brightness = CalcSkyBrightness();
959 sky_clearness = CalcSkyClearness();
960
961 /* Limit sky clearness */
962 if (sky_clearness > 12.0)
963 sky_clearness = 12.0;
964
965 /* Limit sky brightness */
966 if (sky_brightness < 0.01)
967 sky_brightness = 0.01;
968
969 while (((fabs(diff_irrad - test1) > 10.0) ||
970 (fabs(dir_irrad - test2) > 10.0)) && !(counter == 5))
971 {
972 test1 = diff_irrad;
973 test2 = dir_irrad;
974 counter++;
975
976 /* Convert illuminance to irradiance */
977 index = GetCategoryIndex();
978 diff_irrad = diff_illum / CalcDiffuseIllumRatio(index);
979 dir_irrad = CalcDirectIllumRatio(index);
980 if (dir_irrad > 0.1)
981 dir_irrad = dir_illum / dir_irrad;
982
983 /* Calculate sky brightness and clearness */
984 sky_brightness = CalcSkyBrightness();
985 sky_clearness = CalcSkyClearness();
986
987 /* Limit sky clearness */
988 if (sky_clearness > 12.0)
989 sky_clearness = 12.0;
990
991 /* Limit sky brightness */
992 if (sky_brightness < 0.01)
993 sky_brightness = 0.01;
994 }
995
996 return GetCategoryIndex();
997 }
998
999 /* Calculate relative luminance */
1000
1001 /* Reference: Perez, R., R. Seals, and J. Michalsky. 1993. */
1002 /* ìAll-Weather Model for Sky Luminance Distribution - */
1003 /* Preliminary Configuration and Validation,î Solar Energy */
1004 /* 50(3):235-245, Eqn. 1. */
1005
1006 double CalcRelLuminance( double gamma, double zeta )
1007 {
1008 return (1.0 + perez_param[0] * exp(perez_param[1] / cos(zeta))) *
1009 (1.0 + perez_param[2] * exp(perez_param[3] * gamma) +
1010 perez_param[4] * cos(gamma) * cos(gamma));
1011 }
1012
1013 /* Calculate Perez sky model parameters */
1014
1015 /* Reference: Perez, R., R. Seals, and J. Michalsky. 1993. */
1016 /* ìAll-Weather Model for Sky Luminance Distribution - */
1017 /* Preliminary Configuration and Validation,î Solar Energy */
1018 /* 50(3):235-245, Eqns. 6 - 8. */
1019
1020 void CalcPerezParam( double sz, double epsilon, double delta,
1021 int index )
1022 {
1023 double x[5][4]; /* Coefficents a, b, c, d, e */
1024 int i, j; /* Loop indices */
1025
1026 /* Limit sky brightness */
1027 if (epsilon > 1.065 && epsilon < 2.8)
1028 {
1029 if (delta < 0.2)
1030 delta = 0.2;
1031 }
1032
1033 /* Get Perez coefficients */
1034 for (i = 0; i < 5; i++)
1035 for (j = 0; j < 4; j++)
1036 x[i][j] = PerezCoeff[index][4 * i + j];
1037
1038 if (index != 0)
1039 {
1040 /* Calculate parameter a, b, c, d and e (Eqn. 6) */
1041 for (i = 0; i < 5; i++)
1042 perez_param[i] = x[i][0] + x[i][1] * sz + delta * (x[i][2] +
1043 x[i][3] * sz);
1044 }
1045 else
1046 {
1047 /* Parameters a, b and e (Eqn. 6) */
1048 perez_param[0] = x[0][0] + x[0][1] * sz + delta * (x[0][2] +
1049 x[0][3] * sz);
1050 perez_param[1] = x[1][0] + x[1][1] * sz + delta * (x[1][2] +
1051 x[1][3] * sz);
1052 perez_param[4] = x[4][0] + x[4][1] * sz + delta * (x[4][2] +
1053 x[4][3] * sz);
1054
1055 /* Parameter c (Eqn. 7) */
1056 perez_param[2] = exp(pow(delta * (x[2][0] + x[2][1] * sz),
1057 x[2][2])) - x[2][3];
1058
1059 /* Parameter d (Eqn. 8) */
1060 perez_param[3] = -exp(delta * (x[3][0] + x[3][1] * sz)) +
1061 x[3][2] + delta * x[3][3];
1062 }
1063 }
1064
1065 /* Calculate relative horizontal illuminance (modified by GW) */
1066
1067 /* Reference: Perez, R., R. Seals, and J. Michalsky. 1993. */
1068 /* ìAll-Weather Model for Sky Luminance Distribution - */
1069 /* Preliminary Configuration and Validation,î Solar Energy */
1070 /* 50(3):235-245, Eqn. 3. */
1071
1072 double CalcRelHorzIllum( float *parr )
1073 {
1074 int i;
1075 double rh_illum = 0.0; /* Relative horizontal illuminance */
1076
1077 for (i = 1; i < nskypatch; i++)
1078 rh_illum += parr[3*i+1] * rh_cos(i) * rh_dom[i];
1079
1080 return rh_illum;
1081 }
1082
1083 /* Calculate earth orbit eccentricity correction factor */
1084
1085 /* Reference: Sen, Z. 2008. Solar Energy Fundamental and Modeling */
1086 /* Techniques. Springer, p. 72. */
1087
1088 double CalcEccentricity()
1089 {
1090 double day_angle; /* Day angle (radians) */
1091 double E0; /* Eccentricity */
1092
1093 /* Calculate day angle */
1094 day_angle = (julian_date - 1.0) * (2.0 * PI / 365.0);
1095
1096 /* Calculate eccentricity */
1097 E0 = 1.00011 + 0.034221 * cos(day_angle) + 0.00128 * sin(day_angle)
1098 + 0.000719 * cos(2.0 * day_angle) + 0.000077 * sin(2.0 *
1099 day_angle);
1100
1101 return E0;
1102 }
1103
1104 /* Calculate atmospheric precipitable water content */
1105
1106 /* Reference: Perez, R., P. Ineichen, R. Seals, J. Michalsky, and R. */
1107 /* Stewart. 1990. ìModeling Daylight Availability and */
1108 /* Irradiance Components from Direct and Global */
1109 /* Irradiance,î Solar Energy 44(5):271-289, Eqn. 3. */
1110
1111 /* Note: The default surface dew point temperature is 11 deg. C */
1112 /* (52 deg. F). Typical values are: */
1113
1114 /* Celsius Fahrenheit Human Perception */
1115 /* > 24 > 75 Extremely uncomfortable */
1116 /* 21 - 24 70 - 74 Very humid */
1117 /* 18 - 21 65 - 69 Somewhat uncomfortable */
1118 /* 16 - 18 60 - 64 OK for most people */
1119 /* 13 - 16 55 - 59 Comfortable */
1120 /* 10 - 12 50 - 54 Very comfortable */
1121 /* < 10 < 49 A bit dry for some */
1122
1123 double CalcPrecipWater( double dpt )
1124 { return exp(0.07 * dpt - 0.075); }
1125
1126 /* Calculate relative air mass */
1127
1128 /* Reference: Kasten, F. 1966. "A New Table and Approximation Formula */
1129 /* for the Relative Optical Air Mass," Arch. Meteorol. */
1130 /* Geophys. Bioklimataol. Ser. B14, pp. 206-233. */
1131
1132 /* Note: More sophisticated relative air mass models are */
1133 /* available, but they differ significantly only for */
1134 /* sun zenith angles greater than 80 degrees. */
1135
1136 double CalcAirMass()
1137 {
1138 return (1.0 / (cos(sun_zenith) + 0.15 * pow(93.885 -
1139 RadToDeg(sun_zenith), -1.253)));
1140 }
1141
1142 /* Calculate Perez All-Weather sky patch luminances (modified by GW) */
1143
1144 /* NOTE: The sky patches centers are determined in accordance with the */
1145 /* BRE-IDMP sky luminance measurement procedures. (See for example */
1146 /* Mardaljevic, J. 2001. "The BRE-IDMP Dataset: A New Benchmark */
1147 /* for the Validation of Illuminance Prediction Techniques," */
1148 /* Lighting Research & Technology 33(2):117-136.) */
1149
1150 void CalcSkyPatchLumin( float *parr )
1151 {
1152 int i;
1153 double aas; /* Sun-sky point azimuthal angle */
1154 double sspa; /* Sun-sky point angle */
1155 double zsa; /* Zenithal sun angle */
1156
1157 for (i = 1; i < nskypatch; i++)
1158 {
1159 /* Calculate sun-sky point azimuthal angle */
1160 aas = fabs(rh_pazi[i] - azimuth);
1161
1162 /* Calculate zenithal sun angle */
1163 zsa = PI * 0.5 - rh_palt[i];
1164
1165 /* Calculate sun-sky point angle (Equation 8-20) */
1166 sspa = acos(cos(sun_zenith) * cos(zsa) + sin(sun_zenith) *
1167 sin(zsa) * cos(aas));
1168
1169 /* Calculate patch luminance */
1170 parr[3*i] = CalcRelLuminance(sspa, zsa);
1171 if (parr[3*i] < 0) parr[3*i] = 0;
1172 parr[3*i+2] = parr[3*i+1] = parr[3*i];
1173 }
1174 }

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