Repository navigation
Expand file tree
/
Copy pathknowledge_base.json
More file actions
2212 lines (2200 loc) · 300 KB
/
Copy pathknowledge_base.json
File metadata and controls
2212 lines (2200 loc) · 300 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
[
{
"topic": "Radiance Philosophy: Visualization vs. Simulation",
"content": "Radiance is a lighting visualization and simulation tool, not just a photorealistic renderer. Its primary goal is to generate images where calculated light levels quantitatively match actual physical conditions, making it a research and engineering instrument for predicting visible radiation distribution with verifiable accuracy. The core unit is spectral radiance (W⋅sr−1⋅m−2), from which all other photometric metrics like illuminance (lux) can be derived. The validity of a simulation depends entirely on the accuracy of its inputs, following the principle of 'garbage in, garbage out'."
},
{
"topic": "How Radiance Defines Light Sources",
"content": "In Radiance, light is an attribute of a surface, not an independent entity. There are no disembodied 'point lights'. To create a light source, you must first define a geometric object (e.g., a polygon or sphere) and then assign it a material property that makes it self-luminous. The object itself becomes the light source."
},
{
"topic": "Radiance Ray-Tracing Algorithm",
"content": "Radiance uses a light-backwards ray-tracing algorithm. Instead of tracing rays forward from light sources, it traces rays backward from the viewpoint (a virtual camera or measurement point). These rays bounce off surfaces based on their defined properties. When a ray path terminates at a light-emitting surface, its radiance contribution is calculated and added to the total value for the initial pixel or point. This process simulates both direct and indirect (diffuse interreflection) illumination."
},
{
"topic": "Radiance Scene File (.rad) Structure",
"content": "A .rad file is a human-readable plain text file that describes a 3D environment, including geometry, materials, and light sources. It supports four basic statement types:\n- Comments: Lines beginning with '#' are ignored.\n- Primitives: Core definitions for surfaces (polygons, spheres) and modifiers (materials, textures).\n- Aliases: Associates a new name with a previously defined primitive.\n- External Commands: Lines beginning with '!' are executed by the system shell, allowing for procedural geometry, file inclusion, and complex scene construction."
},
{
"topic": "Radiance Universal Primitive Syntax",
"content": "Every primitive in Radiance (materials, surfaces, etc.) follows a universal syntax:\n\nmodifier type identifier\nN S1 S2... SN\nI I1 I2... II\nM R1 R2... RM\n\n- modifier: The name of a previously defined primitive (like a material) that modifies the current one. Use 'void' for base materials.\n- type: A keyword specifying the primitive type (e.g., polygon, plastic, light).\n- identifier: A unique, user-defined name for the new primitive.\n- Argument Blocks: The next three lines contain string (N), integer (I), and real/floating-point (M) arguments, each preceded by a count of the arguments on that line."
},
{
"topic": "Two-Step Principle of Creating a Light Source",
"content": "Adding an artificial light source in Radiance is a two-step procedure:\n1. Define a Light Material: Create a material primitive using a light-emitting type (e.g., 'light', 'spotlight'). This defines the light's color and intensity and gives it a unique name.\n2. Apply the Material to Geometry: Create a geometric primitive (e.g., a polygon or sphere) and use the name of the light material from Step 1 as its modifier. This transforms the geometric object into a luminaire."
},
{
"topic": "Example: Creating a Spherical Light Source",
"content": "This example shows the two-step process for creating a spherical light source:\n\n```\n# Step 1: Define the light-emitting material.\n# The modifier is \"void\", type is \"light\", identifier is \"bright\".\nvoid light bright\n0\n0\n3 100 100 100 # R G B (Radiance in W/sr/m^2)\n\n# Step 2: Define geometry and apply the material.\n# The modifier is \"bright\", the material defined above.\n# The type is \"sphere\", the identifier is \"fixture\".\nbright sphere fixture\n0\n0\n4 2 1 1.5 0.125 # x_cen y_cen z_cen radius\n```"
},
{
"topic": "Native Light Source Primitive: light",
"content": "The 'light' primitive is the most fundamental light-emitting material. It models a surface as a perfect, uniform, diffuse emitter (Lambertian distribution), radiating light equally in all directions. It is ideal for bare lamps or simple luminous panels.\n\nSyntax:\nvoid light light_identifier\n0\n0\n3 Red_emission Green_emission Blue_emission\n\nThe three real arguments define the spectral radiance in W⋅sr−1⋅m−2 for the R, G, and B channels, controlling both color and intensity."
},
{
"topic": "Native Light Source Primitive: spotlight",
"content": "The 'spotlight' primitive models luminaires with directed output, like downlights or track lights. It defines color, intensity, direction, and angular spread.\n\nSyntax:\nvoid spotlight spotlight_identifier\n0\n0\n7 Red Green Blue cone_angle dx dy dz\n\n- Red, Green, Blue: Radiance in W⋅sr−1⋅m−2.\n- cone_angle: Full angular width of the emission cone in degrees (0-360).\n- dx, dy, dz: A 3D vector defining the beam's orientation."
},
{
"topic": "spotlight: Direction Vector and Focal Length",
"content": "The direction vector (dx dy dz) in a 'spotlight' primitive serves a dual purpose. Its orientation aims the light, but its magnitude (length) defines an effective focal length, simulating how a real lens or reflector collimates light. This changes the light falloff from the standard 1/r² to something closer to 1/(r+e)², where 'e' is the vector's magnitude. To simply aim the spotlight without this focusing effect, you must use a normalized direction vector (a vector with a length of 1.0), such as (0 0 -1) to aim straight down."
},
{
"topic": "Native Light Source Primitive: glow",
"content": "The 'glow' primitive is for self-luminous surfaces where the contribution to scene illumination can be precisely controlled or eliminated, making it an essential optimization tool. It is ideal for sources that must be visible but have negligible photometric impact, like indicator LEDs or exit signs.\n\nSyntax:\nvoid glow glow_identifier\n0\n0\n4 Red Green Blue max_radius"
},
{
"topic": "glow: The max_radius Parameter",
"content": "The 'max_radius' parameter in a 'glow' material controls its participation in the lighting calculation:\n- If max_radius > 0: The surface acts as a light source, but only for objects within this specified radius.\n- If max_radius = 0 (default): The surface is visible and contributes to indirect (ambient) calculations, but never casts direct shadows.\n- If max_radius < 0: The surface is purely cosmetic. It is visible but completely excluded from all lighting calculations (direct and indirect). This is the most efficient option for things like indicator lights."
},
{
"topic": "Native Light Source Primitive: illum",
"content": "The 'illum' primitive is for modeling secondary light sources, like luminaire diffusers or windows. Its key feature is that it acts as a light source for calculations but adopts the appearance of a different, specified material when viewed directly. This provides a computationally efficient way to model things like translucent diffusers without modeling the lamp inside.\n\nSyntax:\nalternate_material illum illum_identifier\n0\n0\n3 Red Green Blue"
},
{
"topic": "illum: Modeling Luminaire Diffusers",
"content": "The expert workflow for modeling a luminaire with a diffuser uses the 'illum' primitive. Instead of modeling the fixture box and internal lamp, you only model the visible diffuser polygon. The process is:\n1. Define a standard material (e.g., 'trans' or 'plastic') that describes the visual appearance of the diffuser.\n2. Define an 'illum' material. Use the name of the appearance material from step 1 as its modifier. Set the RGB values to the desired light output of the fixture.\n3. Apply this 'illum' material to the diffuser polygon. This is more efficient because for the rest of the scene, the diffuser itself is the light source, but when viewed by the camera, it appears as the correct translucent material."
},
{
"topic": "Summary of Light-Emitting Material Primitives",
"content": "- light: General purpose diffuse emitter (bare bulb, luminous panel). Provides uniform, Lambertian emission.\n- spotlight: Directional luminaires (downlight, projector). Emits light within a defined cone; direction vector magnitude acts as a focal length.\n- glow: Computationally inexpensive sources (LEDs, screens). Contribution to scene illumination is controlled by `max_radius`, allowing for purely cosmetic sources.\n- illum: Secondary sources with a custom appearance (luminaire diffuser, luminous ceiling). Acts as a light source for calculations but appears as a different `alternate_material` when viewed directly."
},
{
"topic": "Incorporating Photometric Data with ies2rad",
"content": "Professional lighting design uses photometric data from manufacturers, typically in IES LM-63 format (.ies files). Radiance uses the 'ies2rad' command-line utility to translate this data into a Radiance scene description. It generates a .rad file containing the luminaire geometry and an 'illum' material, and a .dat file containing the interpolated photometric data that the 'illum' material references."
},
{
"topic": "Key ies2rad Command-Line Options",
"content": "- -o outname: Sets the root name for the output files.\n- -d units: Defines output dimensions ('m' for meters, 'f' for feet, etc.). Default is meters.\n- -m factor: Multiplies output by a factor. Used for applying a Light Loss Factor (LLF).\n- -c r g b: Sets a custom color. Used with -t default.\n- -t lamp: Specifies a lamp type to look up in lamp.tab. Using '-t default' forces the use of the -c color.\n- -p prefdir: Places output files into a subdirectory."
},
{
"topic": "Workflow: Using an IES File",
"content": "1. Acquire an .ies file from a manufacturer.\n2. Execute ies2rad in the terminal: `ies2rad downlight.ies`. This creates `downlight.rad` and `downlight.dat`.\n3. Integrate into your master scene file using the `!xform` command to place and orient the luminaire. Example: `!xform -t 1.5 2.0 2.8 -rx -90 downlight.rad`. This modular approach allows for easy placement of multiple instances."
},
{
"topic": "Photometric Data Best Practices: Units",
"content": "A mismatch between the units specified in the ies2rad command (-d flag) and the units used to model the main scene is one of the most common and catastrophic sources of error. If a scene is modeled in feet, but ies2rad is run with its default meter output, all lighting levels will be incorrect. It is imperative to ensure consistency."
},
{
"topic": "Photometric Data Best Practices: Color",
"content": "IES files do not contain spectral color information. For color consistency, the most robust practice is to override ies2rad's color inference. By using the `-t default` option along with `-c 1 1 1`, you can specify a color-balanced white light. Color temperature and chromaticity can then be adjusted globally in post-processing with the `pfilt` utility."
},
{
"topic": "Geometric Primitives for Light Sources",
"content": "A light-emitting material can be applied as a modifier to any standard geometric primitive to create a light source of a specific shape:\n- polygon: For flat, polygonal sources like troffers or linear fixtures.\n- sphere: For omnidirectional sources like bare lamps.\n- cylinder: For modeling linear fluorescent or LED tubes.\n- ring: For modeling the circular aperture of a recessed downlight."
},
{
"topic": "Geometric Transformations with xform",
"content": "`xform` is Radiance's utility for geometric transformations. Key options include:\n- -t x y z: Translate (Move).\n- -rx degrees: Rotate around the X-axis.\n- -ry degrees: Rotate around the Y-axis.\n- -rz degrees: Rotate around the Z-axis.\n- -s factor: Uniformly scale the object."
},
{
"topic": "xform: Order of Operations",
"content": "The order of transformation operations in `xform` is critical and non-commutative; they are applied sequentially. A common source of errors is incorrect ordering. The general rule of thumb is to perform scaling and rotation operations first, while the object is at the origin, and then perform the final translation to place it in the scene. For example, `!xform -rx 45 -t 5 0 0 object.rad` (rotate then translate) produces a different result than `!xform -t 5 0 0 -rx 45 object.rad` (translate then rotate)."
},
{
"topic": "Creating Arrays of Luminaires with xform",
"content": "`xform` can create arrays of objects efficiently using the `-a` (array) and `-i` (iterate) options.\n- `-a N`: Creates N copies of the input object. It works with the transform that immediately follows it, applying the transform cumulatively to each copy (0 times for the first, 1 time for the second, etc.).\n- `-i N`: Repeats the following transformation N times. It is often used to apply a global transformation to an entire array."
},
{
"topic": "Best Practices for Scene File Management",
"content": "For complex projects, it is best practice to use a modular file organization rather than a single monolithic .rad file. A typical project might be structured with separate files for materials (materials.rad), light definitions (lights.rad), and geometry (room_geom.rad). These components are then assembled in a master scene file using `!xform` and other commands. This approach makes scenes easier to manage, debug, and reuse."
},
{
"topic": "Compiling a Scene with oconv",
"content": "`oconv` is the Radiance scene compiler. It reads the textual .rad descriptions and builds a single binary file with a .oct extension. This octree is a spatial data structure that organizes the scene's geometry to make the ray-tracing process computationally feasible. Without this compilation step, rendering would be impossibly slow."
},
{
"topic": "oconv: The Importance of Input File Order",
"content": "A frequent source of errors is providing input files to `oconv` in the wrong order. A fundamental rule of Radiance is that a modifier must be defined before it is referenced. This means a file containing material definitions (e.g., materials.rad) must always be listed on the command line *before* any file containing geometry that uses those materials (e.g., room_geom.rad).\n- Correct: `oconv materials.rad room_geom.rad > scene.oct`\n- Incorrect: `oconv room_geom.rad materials.rad > scene.oct` (will cause an 'undefined modifier' error)."
},
{
"topic": "Rendering an Image with rpict",
"content": "`rpict` is the primary batch-mode rendering engine in Radiance. It takes a compiled .oct file and a set of parameters defining the view and calculation quality, and produces a high-dynamic-range (HDR) image. Key view parameters include:\n- -vp x y z: View point (camera location).\n- -vd dx dy dz: View direction (where the camera is pointing).\n- -vu ux uy uz: View up vector (defines 'up').\n- -vh angle / -vv angle: Horizontal and vertical field of view in degrees."
},
{
"topic": "Troubleshooting: Noise and Splotches",
"content": "The most common artifact in Radiance renderings is noise or splotchy patterns in indirectly lit areas. This is a direct result of insufficient sampling in the ambient calculation. The engine has not sent out enough rays to get a stable average of the incoming light. The solution is to increase the quality of the ambient calculation by raising the values of `-ad` (ambient divisions) and `-as` (ambient super-samples), which provides more samples to smooth out the result at the cost of longer render times."
},
{
"topic": "Troubleshooting: Caustics and Specular Noise ('Fireflies')",
"content": "Standard backward ray-tracing is inefficient at resolving focused specular reflections, like caustics from sunlight through glass or off a curved metal surface. Trying to solve this with `rpict` alone is often futile and results in extreme noise or 'fireflies'. For these cases, Radiance provides advanced tools like `mkillum` (a pre-calculation step for complex sources) or a full photon mapping extension, which is often the only viable method for cleanly rendering such scenes."
},
{
"topic": "Radiance Engine in Modern GUI Tools",
"content": "Many modern tools like ClimateStudio, Ladybug/Honeybee, and OpenStudio use Radiance as their simulation engine. These applications act as sophisticated wrappers, automatically generating .rad files and executing command-line programs like `oconv` and `rpict` behind the scenes. An understanding of the underlying Radiance principles is invaluable for troubleshooting unexpected results or extending the capabilities of these GUI-based tools."
},
{
"topic": "Material: plastic",
"content": "The 'plastic' material is for surfaces with uncolored specular highlights. It is defined by its RGB reflectance, its fraction of specularity, and its roughness value. Roughness is the RMS slope of surface facets, where 0 is perfectly smooth. Specularity fractions above 0.1 and roughness values above 0.2 are not very realistic.\n\nSyntax:\nvoid plastic id\n0\n0\n5 red green blue spec rough"
},
{
"topic": "Material: metal",
"content": "The 'metal' material is similar to plastic, but its specular highlights are modified by the material color. The specularity of metals is usually 0.9 or greater, and roughness values above 0.2 are uncommon.\n\nSyntax:\nvoid metal id\n0\n0\n5 red green blue spec rough"
},
{
"topic": "Material: trans",
"content": "'Trans' is a translucent material, similar to plastic but with added transmission properties. Transmissivity is the fraction of light that travels through the material. Transmitted specular is the fraction of transmitted light that is not diffusely scattered. Translucent objects are considered infinitely thin.\n\nSyntax:\nvoid trans id\n0\n0\n7 red green blue spec rough trans tspec"
},
{
"topic": "Material: glass",
"content": "The 'glass' material is optimized for thin glass surfaces (refractive index defaults to 1.52). It avoids modeling internal reflections by using a single surface. The primary specification is the transmissivity at normal incidence. To compute transmissivity (tn) from the more commonly measured transmittance (Tn), use the formula:\ntn = (sqrt(0.8402528435 + 0.0072522239*Tn*Tn) - 0.9166530661) / (0.0036261119*Tn)\n\nSyntax:\nvoid glass id\n0\n0\n3 rtn gtn btn"
},
{
"topic": "Material: mirror",
"content": "'Mirror' is for planar surfaces that produce virtual source reflections. It should be used sparingly as it can be computationally expensive. It is only supported for flat surfaces like polygons and rings. The arguments are the RGB reflectance values (0-1). An optional string argument can specify an alternate material for non-source rays, similar to 'illum'."
},
{
"topic": "Material: BSDF",
"content": "The 'BSDF' material type is used for complex fenestration systems. It references an XML file containing the Bidirectional Scattering Distribution Function data. The arguments include the thickness of the BSDF surface, the XML file path, and up, forward, and right-hand vectors.\n\nSyntax:\nvoid BSDF id\n6+ up_x up_y up_z fwd_x fwd_y fwd_z file.xml transform\n0\nN real_args..."
},
{
"topic": "Material: antimatter",
"content": "'Antimatter' is a material that can 'subtract' volumes from other volumes. A ray passing into an antimatter object becomes blind to all the specified modifiers. It does not work properly with the 'trans' material, and multiple antimatter surfaces should be disjoint. The viewpoint must be outside all concerned volumes for a correct rendering."
},
{
"topic": "Material: mist",
"content": "'Mist' is a virtual material used to delineate a volume of participating atmosphere, making light beams visible (e.g., from a spotlight). It can define an extinction coefficient, scattering albedo, and scattering eccentricity. It is often used to surround a beam from a spotlight or to model clouds."
},
{
"topic": "Application Workflow: Project & Scene Setup",
"content": "The user workflow begins with the left toolbar panels:\n1. Project Setup: Define project name, location (map or EPW file), and Radiance path.\n2. Dimensions: Set room width, length, height, and orientation.\n3. Apertures & Shading: Select walls in the 3D view to add windows and shading devices.\n4. Artificial Lighting & Materials: Configure surface properties and add light sources.\n5. Sensor Grid: Define points in space for simulation calculations."
},
{
"topic": "Application Workflow: Simulation and Execution",
"content": "After scene setup, the user configures the simulation using the right sidebar:\n1. Recipe Selection: Add simulation 'recipes' like 'Illuminance Map' or 'Annual Daylight'.\n2. Parameter Tuning: Configure settings for each recipe in its floating panel.\n3. Package Generation: The application gathers all data and generates a complete Radiance project folder with geometry (.rad), materials, and run scripts (.sh/.bat).\n4. Execution: In the Electron app, a 'Run Simulation' button executes the script. In a browser, the user downloads the package and runs it manually."
},
{
"topic": "Application Workflow: Results and Analysis",
"content": "The final stage involves analyzing the simulation output:\n1. Load Results: The user loads a result file (.ill, .hdr, .dgp) into the Analysis sidebar.\n2. Data Processing: A background web worker parses the file to prevent UI freezing, and the Results Manager calculates metrics (sDA, ASE, etc.).\n3. Visualization: Results are displayed as a false-color map on the 3D sensor grid and in specialized dashboards like the Annual Metrics Dashboard or HDR Image Viewer."
},
{
"topic": "Application Architecture: UI Layer (ui.js)",
"content": "`ui.js` is the central hub for user interaction. It caches DOM elements, manages all event listeners (sliders, buttons), controls the state of floating windows, updates UI labels, handles 3D scene interactions (wall/sensor clicks), and orchestrates the loading of result files and display of dashboards."
},
{
"topic": "Application Architecture: 3D Visualization Layer (scene.js, geometry.js)",
"content": "`scene.js` manages the Three.js environment, including the scene, cameras, renderer, and navigation controls. It contains the main `animate()` loop. `geometry.js` is responsible for creating and updating all 3D objects (room, windows, shading, sensor grids) based on parameters from the UI layer."
},
{
"topic": "Application Architecture: State & Persistence (project.js)",
"content": "The `Project` class in `project.js` is the single source of truth for the application's state. It gathers all settings into a comprehensive JSON object for saving, applies settings from a loaded project file, manages file system access, and orchestrates the generation of the final simulation package."
},
{
"topic": "Application Architecture: Scripting Layer (scriptGenerator.js)",
"content": "`scriptGenerator.js` is the core translation engine. It takes the consolidated project data object and generates the text content for all Radiance-compatible files, including geometry files (.rad), material files, and executable run scripts for different simulation recipes."
},
{
"topic": "Application Architecture: Data Analysis Layer (resultsManager.js)",
"content": "`resultsManager.js` is the engine for post-simulation analysis. It receives result files, offloads parsing to a web worker, stores all data (allowing for A/B comparison), calculates statistics and climate-based metrics (sDA, ASE, UDI), and provides methods for the UI to retrieve data for visualization."
},
{
"topic": "Recommended Project Directory Structure",
"content": "A well-organized project directory is critical for managing complexity. A recommended structure includes separate folders for different file types:\n- 01_geometry/: .rad files for scene geometry\n- 02_materials/: .mat or .rad files for materials\n- 04_skies/: .rad files for skies and .epw files\n- 06_octrees/: Compiled .oct files\n- 07_scripts/: BASH and Python scripts to run simulations\n- 08_results/: Raw numerical output (.ill, .dgp, .pts, etc.)\n- 09_images/: Final rendered images (.hdr, .png)"
},
{
"topic": "Core Calculation Parameter: -ab (Ambient Bounces)",
"content": "The `-ab` parameter specifies the maximum number of diffuse inter-reflections a ray will undergo. It controls the 'depth' of the indirect lighting simulation. A value of `-ab 0` disables indirect calculation. For most analyses, a value between 3 and 5 is a good balance of accuracy and speed. Higher values (6-7) are needed for complex geometries. A high `-ab` value is ineffective unless the ray weight limit (`-lw`) is set to a very small value."
},
{
"topic": "Core Calculation Parameter: -ad (Ambient Divisions)",
"content": "The `-ad` parameter sets the number of sample rays sent to probe the hemisphere for indirect illuminance. It is the primary control for resolving detail in indirect lighting. An insufficient `-ad` value is the most common cause of 'splotchy' or 'blotchy' artifacts in renderings. The first step in troubleshooting these artifacts is to increase the `-ad` value, often by doubling it."
},
{
"topic": "Core Calculation Parameter: -as (Ambient Super-samples)",
"content": "The `-as` parameter defines the number of additional samples used to refine the initial ambient divisions in areas where high variance is detected. After setting a reasonable base value for `-ad`, increasing `-as` can efficiently clean up remaining noise without the high cost of universally increasing `-ad`. A good starting point is to set `-as` to half the value of `-ad`."
},
{
"topic": "Core Calculation Parameter: -aa (Ambient Accuracy)",
"content": "The `-aa` parameter controls the allowable error for interpolation by the irradiance cache. It specifically manages *interpolation* error, not sampling error. Attempting to fix blotchy artifacts (an `-ad` problem) by lowering `-aa` is incorrect and will drastically increase computation time. A correct use for `-aa` is to resolve artifacts like smooth but incorrect gradients or light 'bleeding' around corners."
},
{
"topic": "Core Calculation Parameter: -dj (Direct Jittering)",
"content": "The `-dj` parameter introduces randomness to shadow rays for area light sources. A value of 0 produces sharp, unrealistic hard-edged shadows. A positive value (e.g., `-dj 0.7`) distributes shadow rays across the source, correctly simulating soft-edged shadows (penumbras). For direct sun analysis with `rcontrib`, it is often better to use `-dj 0` to ensure the ray is always sent to the center of the solar disc for consistency."
},
{
"topic": "Recommended Ambient Parameter Quality Presets",
"content": "- Draft/Preview: -ab 2 -ad 256 -as 128 -aa 0.25 (Fast, expects artifacts)\n- Standard/Good: -ab 4 -ad 1024 -as 512 -aa 0.2 (Balanced, good default)\n- High-Fidelity: -ab 7 -ad 4096 -as 2048 -aa 0.15 (For publication or complex scenes, slow)\n- Reference: -aa 0.0 (Disables interpolation, extremely slow, for research)"
},
{
"topic": "Point-in-Time Workflow: Grid-Based Illuminance (rtrace)",
"content": "This workflow calculates illuminance (lux) on a grid of sensor points. It uses the `rtrace` program with a sensor points file (.pts). Each line in the .pts file defines a sensor's location and orientation (X Y Z Vx Vy Vz). The `-I` switch is used to compute irradiance. The raw RGB output from `rtrace` is then converted to a single lux value using `rcalc` with the expression `'$1=179*($1*0.265+$2*0.670+$3*0.065)'`."
},
{
"topic": "Point-in-Time Workflow: Daylight Factor (DF)",
"content": "Daylight Factor (DF) is the ratio of interior illuminance to the available unobstructed exterior horizontal illuminance under a standard CIE Overcast Sky. The workflow involves using `gensky` with the `-c` flag for an overcast sky and the `-B` flag to set a reference horizontal irradiance (e.g., 55.866 W/m² to correspond to 10,000 lux). `rtrace` is used to find the interior illuminance, which is then divided by the reference value to get the DF percentage."
},
{
"topic": "Point-in-Time Workflow: Daylight Glare Probability (DGP)",
"content": "DGP analysis is a two-step process to assess visual discomfort. First, `rpict` is used to generate a high-quality 180° hemispherical fisheye HDR image (`-vth -vh 180 -vv 180`). Second, the `evalglare` program processes this image to calculate the DGP value. High-quality ambient parameters are essential for the `rpict` rendering, as an inaccurate background luminance will produce an incorrect DGP value."
},
{
"topic": "DGP Interpretation Scale",
"content": "The Daylight Glare Probability (DGP) value represents the fraction of people likely to be disturbed by glare. The scale is interpreted as follows:\n- DGP < 0.35: Imperceptible glare (Good)\n- 0.35 ≤ DGP < 0.40: Perceptible glare (Acceptable)\n- 0.40 ≤ DGP < 0.45: Disturbing glare (Poor)\n- DGP ≥ 0.45: Intolerable glare (Unacceptable)"
},
{
"topic": "Annual Simulation: Daylight Coefficient (DC) Method",
"content": "The Daylight Coefficient (DC) method is the foundation for annual simulations. It pre-calculates the relationship between a set of discrete sky patches and interior sensor points, storing this relationship in a Daylight Coefficient matrix (DC). The illuminance for any given sky condition can then be found with a simple matrix multiplication: E = DC * S, where S is the sky luminance vector. `rcontrib` is the primary tool for generating the DC matrix. The main limitation is inflexibility; if the glazing changes, the entire time-consuming calculation must be redone."
},
{
"topic": "Annual Simulation: Three-Phase Method (3PM)",
"content": "The Three-Phase Method (3PM) solves the inflexibility of the DC method by decoupling the light path into three matrices: V (View Matrix: window interior to sensor), T (Transmission Matrix: through the window, i.e., a BSDF file), and D (Daylight Matrix: sky to window exterior). The final illuminance is calculated by I = V * T * D * S. The great advantage is that different window systems (T matrices) can be tested rapidly without recalculating the V and D matrices, which are the most computationally intensive parts."
},
{
"topic": "Annual Simulation: Five-Phase Method (5PM)",
"content": "The Five-Phase Method (5PM) is the most accurate method for annual simulations where direct sunlight is critical (e.g., for calculating Annual Sunlight Exposure, ASE). It refines the 3PM by correcting for the 'smearing' of the sun's contribution across a large sky patch. It works by calculating the total 3PM result, subtracting the inaccurate direct-sun portion from the 3PM, and adding back a new, high-fidelity direct-sun portion calculated with a more accurate method. The equation is: I_5PM = I_3PM_total - I_3PM_direct + I_5PM_direct."
},
{
"topic": "Annual Metrics: sDA, UDI, and ASE",
"content": "After an annual simulation produces a raw .ill file, a post-processing script is used to calculate standard metrics:\n- sDA (Spatial Daylight Autonomy): A measure of sufficient daylight (e.g., % of area receiving at least 300 lux for 50% of occupied hours).\n- UDI (Useful Daylight Illuminance): Percentage of time a point is within a useful illuminance range (e.g., 100-2000 lux).\n- ASE (Annual Sunlight Exposure): A measure of excessive sunlight (% of area receiving at least 1000 lux of direct sun for 250 hours). ASE should be calculated using the 5-Phase Method."
},
{
"topic": "Five-Phase Method: Prerequisites",
"content": "To perform a five-phase simulation, you need a working Radiance installation, a Radiance model of the space (geometry and materials), a photocell points file (.pts) for sensor locations, an EPW weather file, and supporting calculation files like `klems_int.cal` and `reinhart.cal`."
},
{
"topic": "Five-Phase Method: Required BSDFs",
"content": "The five-phase method requires two different Bidirectional Scattering Distribution Functions (BSDFs) for the fenestration system:\n1. A tensor tree BSDF (e.g., fullwindow_t45.xml) for the accurate direct sun calculation (the Cds matrix).\n2. A Klems basis BSDF (e.g., fullwindow_klems.xml) for the standard three-phase components of the calculation. Both are typically generated using the `genBSDF` program."
},
{
"topic": "Five-Phase Method Step 2: Calculating the standard 3-Phase term (I_3ph)",
"content": "The first major calculation in the 5-phase method is to compute the standard three-phase result (I_3ph = V*T*D*S). This involves creating an octree for the scene (`oconv`), calculating the View Matrix (`rcontrib`), Daylight Matrix (`genklemsamp` | `rcontrib`), and Sky Matrix (`gendaymtx`), and then combining them with the Klems BSDF using `dctimestep`."
},
{
"topic": "Five-Phase Method Step 3: Isolating the inaccurate 3-Phase direct sun term (I_ds-3ph)",
"content": "To isolate the direct solar contribution from the standard 3-phase method, a special calculation is performed. This involves creating a 'black' octree where all scene surfaces are made non-reflective. Then, direct-only View (Vd) and Daylight (Dd) matrices are calculated using this black octree and modified ambient parameters (`-ab 1` or `-ab 0`). A direct-sun-only sky matrix (Sds) is generated using `gendaymtx -d`. These are combined with the Klems BSDF using `dctimestep`."
},
{
"topic": "Five-Phase Method Step 4: Calculating the accurate direct sun term (I_ds-5ph)",
"content": "To accurately calculate the direct solar contribution, a new high-resolution method is used. A `suns.rad` file with many (e.g., 5185) sun sources is created. A 'black' octree is generated that includes these suns and the high-resolution tensor tree BSDF. `rcontrib` is then run to create a Direct Sun Coefficient matrix (Cds). A special 5-phase sun matrix (Ssun) is created with `gendaymtx -5`. Finally, `dctimestep` combines the Cds and Ssun matrices."
},
{
"topic": "Five-Phase Method Step 5: Combining Components for Final Result",
"content": "The final 5-phase illuminance result is assembled by combining the three calculated terms using command-line tools like `rlam` and `rcalc`. The formula is applied to the output files from the previous steps: Final Result = (I_3ph) - (I_ds-3ph) + (I_ds-5ph). `rlam` pastes the records from the three files together, and `rcalc` performs the arithmetic on each channel (R, G, B) before converting the final result to lux."
},
{
"topic": "Limitations of Tristimulus (RGB) Simulation for Non-Visual Effects",
"content": "Standard RGB simulation is effective for visual rendering but discards significant spectral information. This is a problem for analyzing non-visual effects of light on human physiology, such as circadian rhythm synchronization, which is mediated by intrinsically photosensitive Retinal Ganglion Cells (ipRGCs). These cells contain melanopsin, which has a peak sensitivity in the blue region of the spectrum (~460-490 nm), different from the peak visual sensitivity (~555 nm). Therefore, a standard simulation cannot accurately predict these biological effects."
},
{
"topic": "Spectral Analysis (9-Channel): N-Channel Methodology",
"content": "The 9-channel spectral methodology overcomes the limitations of Radiance's 3-channel engine by running the simulation multiple times. The visible spectrum (380-780 nm) is partitioned into 'N' bins. The simulation is run N/3 times, with Radiance's R, G, and B channels repurposed in each run to represent three consecutive spectral bins. The results are then aggregated to reconstruct a full N-channel spectral result. This methodology uses a 9-channel approach, requiring 3 simulation runs."
},
{
"topic": "Spectral Analysis (9-Channel): Wavelength Bins",
"content": "The 9-channel simulation uses the following wavelength bins:\n- Channel 1: 380-424 nm\n- Channel 2: 425-454 nm\n- Channel 3: 455-479 nm\n- Channel 4: 480-504 nm\n- Channel 5: 505-529 nm\n- Channel 6: 530-559 nm\n- Channel 7: 560-599 nm\n- Channel 8: 600-644 nm\n- Channel 9: 645-780 nm"
},
{
"topic": "Spectral Analysis (9-Channel): Pre-Processing Spectral Data",
"content": "To prepare for a 9-channel spectral simulation, continuous spectral data (like an SPD for a light source or an SRD for a material) must be converted into a single representative value for each of the 9 channels. This is done by calculating the arithmetic mean of all spectral data points that fall within the defined wavelength range for each bin. This process results in a nine-element vector representing the binned spectral properties."
},
{
"topic": "Spectral Analysis (9-Channel): Two-Pass Method for Sky/Sun Generation",
"content": "To create a spectrally accurate yet energetically consistent sky model, Ray Modeler uses a 'two-pass' method with the `gendaylit` program. \nPass 1: `gendaylit` is run normally to get the correct baseline radiometric output (radiance) of a standard white sun.\nPass 2: A scaling coefficient is calculated to match the brightness of the custom binned solar spectrum to the baseline sun's brightness. `gendaylit` is then run again, but its output is programmatically modified (using `sed`) to apply the scaled binned colors to the sun and sky primitives."
},
{
"topic": "Spectral Analysis (9-Channel): Post-Processing and Metric Calculation",
"content": "The final stage transforms the raw 9-channel simulation output into meaningful metrics. The data from the three separate simulation runs is aggregated. Then, final metrics are calculated via a weighted sum, where the 9-channel spectral irradiance vector is multiplied by a vector of pre-calculated weighting coefficients specific to the desired metric (e.g., photopic, melanopic, neuropic)."
},
{
"topic": "Spectral Analysis (9-Channel): Weighting Coefficients for Metrics",
"content": "To calculate final metrics from the 9-channel spectral irradiance, the following weighting coefficients are used in a weighted sum:\n- Photopic Weights (V(λ)): [0.0003, 0.0232, 0.1465, 0.3644, 0.7386, 0.9859, 0.8654, 0.3804, 0.0535]\n- Melanopic Weights (S_mel(λ)): [0.0335, 0.4021, 0.7932, 0.8876, 0.6548, 0.3923, 0.1256, 0.0177, 0.0010]\n- Neuropic Weights (Neuropsin): [0.7259, 0.2312, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]"
},
{
"topic": "Three-Phase Method: Core Concept",
"content": "The Three-Phase Method is a powerful technique for analyzing complex fenestration systems. It calculates matrices representing each phase of light transport:\nD (Daylight Matrix): From the sky to the window exterior.\nT (Transmission Matrix): Through the window system (a BSDF file).\nV (View Matrix): From the window interior to the analysis points.\nS (Sky Matrix): The sky's luminance distribution.\nThe final illuminance is calculated by multiplying these matrices: i = V * T * D * S."
},
{
"topic": "Three-Phase Method: Sky Generation (Phase 1)",
"content": "This phase defines the luminous environment. For a single point in time, `gensky` is piped to `genskyvec` to create a sky vector (.skv). For an entire year, `epw2wea` converts a weather file to .wea format, which is then used by `gendaymtx` to generate an annual sky matrix (.smx) containing 8760 hourly sky vectors."
},
{
"topic": "Three-Phase Method: Transmission Matrix / BSDF (Phase 2)",
"content": "The Transmission Matrix (T) describes how light passes through the fenestration system. It is a Bidirectional Scattering Distribution Function (BSDF), typically generated as an .xml file using software like LBNL WINDOW. Inside the software, the user defines the glazing layers and shading systems and sets the angular basis to 'W6 standard basis' (Klems 145-patch basis) to generate the file."
},
{
"topic": "Three-Phase Method: Daylight Matrix (Phase 3)",
"content": "The Daylight Matrix (D) relates sky patches to incident light directions on the window exterior. It is generated using `rcontrib`. First, an octree of the building's exterior and any obstructions is created. Then, `genklemsamp` generates sampling rays from the window surface, which are piped to `rcontrib` to calculate the contribution coefficients from the sky patches, resulting in a .dmx file."
},
{
"topic": "Three-Phase Method: View Matrix (Phase 4)",
"content": "The View Matrix (V) characterizes how light leaving the window's interior surface contributes to sensor points. An octree of the room's interior is created where the window is modeled as a 'glow' light source. `rcontrib` is then used to trace rays from the sensor points (.pts file) back to this glowing window surface. The results are binned according to the Klems basis to match the BSDF, creating a .vmx file."
},
{
"topic": "Three-Phase Method: Final Calculation (Phase 5)",
"content": "The final results are calculated by multiplying the matrices using the `dctimestep` program. The command takes the V, T, D, and S matrices as input in that order. For an annual simulation, the `-n 8760` flag is used along with the annual sky matrix (.smx) to produce an annual results file (e.g., .ill)."
},
{
"topic": "Radiance Calculation Strategy: Backward Ray-Tracing",
"content": "The Radiance lighting simulation suite is a physically-based, backward ray-tracing engine renowned for its scientific accuracy. The term 'backward' refers to its computational strategy: instead of tracing millions of rays forward from light sources in the hope that some will enter the virtual camera, Radiance traces rays backward from each pixel of the virtual camera into the scene to determine what is visible. When a ray intersects a surface, the software calculates the light arriving at that point from all other sources in the environment. This approach is orders of magnitude more efficient for generating images and calculating values at specific points. Achieving accuracy is contingent upon a sophisticated understanding and correct application of its numerous calculation parameters."
},
{
"topic": "The Ambient Calculation and Irradiance Cache",
"content": "The majority of light within an architectural space arrives at a given point after reflecting off other surfaces. This indirect illumination is computationally intensive. Radiance employs a sophisticated algorithm known as the irradiance cache to manage this complexity efficiently. This cache is a form of adaptive sampling for global illumination. Instead of calculating the full hemispherical illumination at every single point, it computes it at select locations and then intelligently interpolates these values for nearby points, storing the results in an ambient file (.amb). The parameters that govern this process represent the most critical trade-offs between simulation speed and physical accuracy."
},
{
"topic": "Core Calculation Parameter: -ar (Ambient Resolution)",
"content": "The `-ar` parameter sets the density of the irradiance cache, effectively defining the maximum resolution for the indirect calculation relative to the overall scene size. It works in concert with `-aa`. The ambient resolution is divided by the scene's bounding box diagonal to determine the maximum density of cached values. This means the same `-ar` value will behave differently in a small room versus a large open-plan office. A very low `-aa` value (high accuracy) is of little use if `-ar` is also low, as the system will not have enough resolution to store the detailed ambient values it is being forced to calculate."
},
{
"topic": "Core Calculation Parameter: -ds (Direct Sampling Ratio)",
"content": "The `-ds` parameter controls the adaptive subdivision of large area light sources. It ensures that surfaces very close to a large source are sampled with sufficient detail to avoid artifacts, at a modest computational cost."
},
{
"topic": "Core Calculation Parameter: -dt (Direct Thresholding)",
"content": "The `-dt` parameter is an optimization that halts shadow testing for light sources whose potential contribution to a point falls below a specified fraction. In a scene with hundreds of lights, `-dt` allows Radiance to estimate the contribution of the farthest, least significant lights instead of tracing a shadow ray for every single one, saving time."
},
{
"topic": "Core Calculation Parameter: -dc (Direct Certainty)",
"content": "A value of 1 for the `-dc` parameter guarantees that all shadow lines resulting in a contrast change greater than the `-dt` value will be calculated explicitly. For high-accuracy simulations, especially those involving direct sunlight, it is standard practice to set `-dt 0` and `-dc 1`. This combination disables statistical approximation and forces a full, brute-force calculation for all light sources, ensuring maximum accuracy at the cost of longer simulation times."
},
{
"topic": "Full Point-in-Time Illuminance Workflow (rtrace)",
"content": "This workflow calculates illuminance (lux) on a grid of sensor points using the `rtrace` program. First, create a sensor points file (.pts) where each line defines a sensor's location and orientation (X Y Z Vx Vy Vz). For a horizontal work plane, the orientation vector is `0 0 1`. The core of the workflow is a single command pipeline that pipes the points file into `rtrace` and then pipes the `rtrace` output into `rcalc` for conversion to lux.\n\nExample shell script (`run_point_illuminance.sh`):\n```bash\n#!/bin/bash\n# --- Simulation Configuration ---\nPROJECT_NAME=\"office_test\"\nLATITUDE=34.05\nLONGITUDE=-118.24\nMERIDIAN=-120\nMONTH=6\nDAY=21\nTIME=14.5\n# Ambient Parameters (Standard Quality)\nAB=4\nAD=1024\nAS=512\nAR=512\nAA=0.2\n\n# --- File & Directory Setup ---\nGEOM_DIR=\"../01_geometry\"\nMAT_DIR=\"../02_materials\"\nSKY_DIR=\"../04_skies\"\nOCT_DIR=\"../06_octrees\"\nRESULTS_DIR=\"../08_results\"\n\nmkdir -p $SKY_DIR $OCT_DIR $RESULTS_DIR\n\n# 1. Generate Sky Description\nSKY_FILE=\"${SKY_DIR}/${PROJECT_NAME}_${MONTH}_${DAY}_${TIME}.rad\"\ngensky $MONTH $DAY $TIME -a $LATITUDE -o $LONGITUDE -m $MERIDIAN > $SKY_FILE\n\n# 2. Create Scene Octree\nOCTREE_FILE=\"${OCT_DIR}/${PROJECT_NAME}.oct\"\noconv ${MAT_DIR}/*.mat ${GEOM_DIR}/*.rad ${SKY_FILE} > $OCTREE_FILE\n\n# 3. Generate Analysis Grid (if it doesn't exist)\nPOINTS_FILE=\"${RESULTS_DIR}/grid.pts\"\nif [ ! -f \"$POINTS_FILE\" ]; then\n gengrid 10 10 5 5 0.85 > $POINTS_FILE\nfi\n\n# 4. Run Illuminance Calculation\nRESULTS_FILE=\"${RESULTS_DIR}/${PROJECT_NAME}_illuminance.txt\"\nrtrace -I -h -w -ab $AB -ad $AD -as $AS -ar $AR -aa $AA $OCTREE_FILE < $POINTS_FILE | \\\nrcalc -e '$1=179*($1*0.265+$2*0.670+$3*0.065)' > $RESULTS_FILE\n\necho \"Simulation complete. Results in ${RESULTS_FILE}\"\n```"
},
{
"topic": "Full Point-in-Time DGP Workflow (rpict & evalglare)",
"content": "Daylight Glare Probability (DGP) analysis is a two-step process. First, `rpict` is used to generate a high-quality 180° hemispherical fisheye HDR image (`-vth -vh 180 -vv 180`). Second, the `evalglare` program processes this image to calculate the DGP value. High-quality ambient parameters are essential for the `rpict` rendering. The view is defined in a separate .vf file.\n\nExample view file (`glare_view.vf`):\n`rvu -vth -vp 2.5 1.5 1.2 -vd 0 1 0 -vu 0 0 1 -vh 180 -vv 180`\n\nExample shell script (`run_dgp_analysis.sh`):\n```bash\n#!/bin/bash\n# --- Simulation Configuration ---\nPROJECT_NAME=\"office_test\"\nLATITUDE=34.05\nLONGITUDE=-118.24\nMERIDIAN=-120\nMONTH=6\nDAY=21\nTIME=14.5\n# Ambient Parameters (High Quality is ESSENTIAL)\nAB=6\nAD=2048\nAS=1024\nAR=512\nAA=0.15\n\n# --- File & Directory Setup ---\nGEOM_DIR=\"../01_geometry\"\nMAT_DIR=\"../02_materials\"\nSKY_DIR=\"../04_skies\"\nOCT_DIR=\"../06_octrees\"\nVIEW_DIR=\"../03_views\"\nRESULTS_DIR=\"../08_results\"\nIMG_DIR=\"../09_images/hdr\"\nmkdir -p $SKY_DIR $OCT_DIR $RESULTS_DIR $IMG_DIR\n\n# 1. Generate Sky\nSKY_FILE=\"${SKY_DIR}/${PROJECT_NAME}_${MONTH}_${DAY}_${TIME}.rad\"\ngensky $MONTH $DAY $TIME -a $LATITUDE -o $LONGITUDE -m $MERIDIAN > $SKY_FILE\n\n# 2. Create Octree\nOCTREE_FILE=\"${OCT_DIR}/${PROJECT_NAME}.oct\"\noconv ${MAT_DIR}/*.mat ${GEOM_DIR}/*.rad ${SKY_FILE} > $OCTREE_FILE\n\n# 3. Render Fisheye Image\nVIEW_FILE=\"${VIEW_DIR}/glare_view.vf\"\nHDR_IMAGE=\"${IMG_DIR}/${PROJECT_NAME}_glare.hdr\"\nrpict -vf $VIEW_FILE -x 1500 -y 1500 \\\n -ab $AB -ad $AD -as $AS -ar $AR -aa $AA \\\n $OCTREE_FILE > $HDR_IMAGE\n\n# 4. Run evalglare\nGLARE_RESULTS=\"${RESULTS_DIR}/${PROJECT_NAME}_dgp.txt\"\nGLARE_CHECK_IMG=\"${IMG_DIR}/${PROJECT_NAME}_glare_check.hdr\"\nevalglare -d -c $GLARE_CHECK_IMG $HDR_IMAGE > $GLARE_RESULTS\n\necho \"Glare analysis complete. Results in ${GLARE_RESULTS}\"\n```"
},
{
"topic": "Post-Processing Annual Metrics with Python",
"content": "After running an annual simulation (e.g., with the Three-Phase Method), the raw .ill file contains 8760 illuminance values for every point. This data can be processed into meaningful metrics like sDA, UDI, and ASE using a Python script with the numpy and pandas libraries.\n\nExample script (`post_process_annual.py`):\n```python\nimport numpy as np\nimport pandas as pd\nimport argparse\nimport os\n\ndef calculate_metrics(illuminance_file: str, output_dir: str, num_points: int):\n try:\n data = np.fromfile(illuminance_file, dtype=np.float32)\n annual_illuminance = data.reshape(8760, num_points)\n except Exception as e:\n print(f\"Error reading file: {e}\")\n return\n\n # Occupancy: Weekdays, 8 AM to 6 PM (17:00)\n time_index = pd.to_datetime(pd.date_range(start='2023-01-01', periods=8760, freq='h'))\n occupied_mask = (time_index.hour >= 8) & (time_index.hour <= 17) & (time_index.dayofweek < 5)\n occupied_illuminance = annual_illuminance[occupied_mask, :]\n\n # sDA (300 lux, 50% of hours)\n sDA_points = np.sum(occupied_illuminance >= 300, axis=0) / occupied_illuminance.shape[0]\n sDA = np.sum(sDA_points >= 0.5) / num_points * 100\n\n # ASE (1000 lux, 250 hours) - requires 5-Phase method for accuracy\n ASE_points = np.sum(occupied_illuminance >= 1000, axis=0)\n ASE = np.sum(ASE_points >= 250) / num_points * 100\n\n # UDI\n udi_f = np.mean(occupied_illuminance < 100, axis=0) * 100\n udi_s = np.mean((occupied_illuminance >= 100) & (occupied_illuminance < 500), axis=0) * 100\n udi_a = np.mean((occupied_illuminance >= 500) & (occupied_illuminance < 2000), axis=0) * 100\n udi_e = np.mean(occupied_illuminance >= 2000, axis=0) * 100\n\n # Save results\n summary = {'sDA_300_50%': [f\"{sDA:.2f}%\"], 'ASE_1000_250h': [f\"{ASE:.2f}%\"]}\n summary_df = pd.DataFrame(summary)\n summary_path = os.path.join(output_dir, \"annual_metrics_summary.csv\")\n summary_df.to_csv(summary_path, index=False)\n print(f\"Summary results saved to {summary_path}\")\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"illuminance_file\", type=str)\n parser.add_argument(\"--points\", type=int, required=True)\n parser.add_argument(\"--outdir\", type=str, default=\"../08_results\")\n args = parser.parse_args()\n calculate_metrics(args.illuminance_file, args.outdir, args.points)\n```"
},
{
"topic": "Troubleshooting Common Simulation Issues",
"content": "Common simulation problems and their solutions:\n- **Light leaks at corners:** Caused by coincident surfaces. Ensure geometry is well-constructed with no gaps.\n- **Large, splotchy, or blotchy patches:** The `-ad` (Ambient Divisions) parameter is too low. Solution: Double the value of `-ad` and re-render. Do not try to fix this by lowering `-aa`.\n- **Smooth shadows with blocky boundaries:** The `-aa` (Ambient Accuracy) is too high or `-ar` (Ambient Resolution) is too low, causing poor interpolation. Solution: Decrease `-aa` and/or increase `-ar`.\n- **Scene appears too dark far from windows:** Insufficient light propagation. The `-ab` value is too low, or the `-lw` (limit weight) value is too high. Solution: Increase `-ab` to 5 or higher and decrease `-lw` to 1e-5 or lower.\n- **Incorrect DGP results:** Could be multiple causes: 1) Input image was not a 180° fisheye view. 2) Rendering quality was too low, giving inaccurate background luminance. 3) Wrong threshold method in `evalglare`. Solution: Verify `rpict` command used `-vth -vh 180 -vv 180`, re-render with High-Fidelity settings, and use the `-t` option in `evalglare`."
},
{
"topic": "Radiance Program: dctimestep",
"content": "`dctimestep` computes annual simulation results by multiplying pre-calculated matrices. It typically takes a View matrix, a Transmission matrix (BSDF), a Daylight matrix, and a Sky matrix as input. Key options:\n- `-n nsteps`: Specifies the number of time steps (e.g., 8760 for an annual simulation).\n- `-o ospec`: Specifies an output file or a pattern for multiple output files (e.g., for generating an image per time step)."
},
{
"topic": "Radiance Program: epw2wea",
"content": "`epw2wea` is a utility that transforms an EnergyPlus weather data file (.epw) into the DAYSIM weather file format (.wea). This converted format is then suitable for use with the `gendaymtx` program to create annual sky matrices."
},
{
"topic": "Radiance Program: evalglare",
"content": "`evalglare` evaluates glare sources within a 180-degree fisheye HDR image to calculate metrics like Daylight Glare Probability (DGP). Key options:\n- `-d`: Produces detailed output, listing properties of each detected glare source.\n- `-c fname`: Creates a 'check file,' which is a copy of the input image with detected glare sources highlighted in color for verification.\n- `-t xpos ypos angle`: Defines a task area on the image. This is the recommended method for determining the glare source threshold, which is based on the average luminance within this task area."
},
{
"topic": "Radiance Program: genBSDF",
"content": "`genBSDF` computes a bidirectional scattering distribution function (BSDF) from a Radiance scene description of a fenestration system. The output is an XML file conforming to the LBNL Window 6 standard. Key options:\n- `-c Nsamp`: Specifies the number of samples per incident direction (default 2000).\n- `-n Nproc`: Specifies the number of simultaneous processes to run.\n- `-t4 Nlog2`: Computes a non-uniform BSDF represented as a rank 4 tensor tree, suitable for high-accuracy direct sun calculations in the 5-Phase Method."
},
{
"topic": "Radiance Program: gendaymtx",
"content": "`gendaymtx` generates an annual Perez sky matrix (.smx) from a weather file (.wea). The output matrix contains luminance values for each sky patch for every hour of the year. Key options:\n- `-m N`: Increases sky resolution using Reinhart subdivision (e.g., `-m 1` for 146 patches, `-m 4` for 2306 patches).\n- `-d`: Produces a sun-only matrix with no sky contributions.\n- `-s`: Excludes the direct solar component.\n- `-5`: A special option used in the 5-Phase Method to generate a high-resolution direct sun matrix."
},
{
"topic": "Radiance Program: gensky",
"content": "`gensky` generates a Radiance scene description for the CIE standard sky distribution for a specific month, day, and time. Key options:\n- `-c`: Generates a cloudy (overcast) sky.\n- `+s`: Generates a sunny sky with the sun.\n- `-s`: Generates a sunny sky without the sun.\n- `-a lat -o lon -m mer`: Specifies site latitude, longitude, and standard meridian for accurate sun position.\n- `-B irrad`: Sets the zenith brightness based on a specified horizontal diffuse irradiance (in W/m²). Used in Daylight Factor workflows."
},
{
"topic": "Radiance Program: pcomb",
"content": "`pcomb` is used to combine Radiance pictures of equal size. It can perform linear combinations or more complex pixel-by-pixel operations defined by an expression. It is used in the image-based 5-Phase Method to combine the results from the different calculation phases using an expression like `-e 'ro=ri(1)-ri(2)+ri(3);...'`."
},
{
"topic": "Radiance Program: rcontrib",
"content": "`rcontrib` is a core program used to compute contribution coefficients, forming the basis of matrix-based methods. It traces rays from sensors and bins the results based on which source modifier (e.g., a sky patch) the ray terminates on. Key options:\n- `-I+`: Specifies that irradiance contributions should be calculated.\n- `-f file.cal`: A function file that defines how to map ray directions to bin numbers.\n- `-b var -bn N`: Specifies the bin variable and the total number of bins.\n- `-m modifier`: The base name of the modifier for which to calculate coefficients."
},
{
"topic": "Radiance Program: rfluxmtx",
"content": "`rfluxmtx` is a utility that acts as a wrapper for `rcontrib` to simplify the process of creating flux transfer matrices, such as the View (V) and Daylight (D) matrices in the Three-Phase Method. It samples rays uniformly over a sender surface and records their arrival at receiver surfaces."
},
{
"topic": "Radiance Program: rmtxop",
"content": "`rmtxop` performs matrix operations on files. It is used in annual simulation workflows to convert the RGB irradiance output from `dctimestep` into a single lux value. It can also be used to add and subtract matrices, which is essential for assembling the final result in the 5-Phase Method."
},
{
"topic": "Radiance Program: vwrays",
"content": "`vwrays` computes the ray origin and direction for each pixel of a specified view. Its output is typically piped directly into another program like `rtrace` or `rcontrib`. It is a key component in generating image-based View Matrices for the Three-Phase Method, where it generates the initial rays for a camera view that are then traced back to the window surface by `rcontrib`."
},
{
"topic": "Core Parameter Deep Dive: -ab (Ambient Bounces)",
"content": "The `-ab` parameter specifies the maximum number of diffuse inter-reflections a ray will undergo. It controls the 'depth' of the simulation. A value of `-ab 0` disables the indirect calculation entirely, useful for isolating direct solar contribution or for very fast previews. For most analyses, a value between 3 and 5 is a good balance of accuracy and speed. Higher values (6-7) are necessary for complex geometries like deep rooms or spaces with light shelves, where light must follow a tortuous path. A high `-ab` value is ineffective unless the ray weight limit (`-lw`) is set to a very small value (e.g., 1e-6) and the reflection limit (`-lr`) is also increased, otherwise rays will terminate prematurely."
},
{
"topic": "Core Parameter Deep Dive: -ad (Ambient Divisions)",
"content": "The `-ad` parameter sets the number of sample rays sent to probe the hemisphere for indirect illuminance and is the primary control for resolving detail in the first-bounce indirect lighting. An insufficient `-ad` value is the most common cause of 'splotchy' or 'blotchy' artifacts, which are a clear sign of undersampling the hemispherical environment. The scale of these splotches is much larger than a single pixel, indicating a fundamental issue with the ambient calculation. The first and most effective step in troubleshooting these artifacts is to increase the `-ad` value, often by doubling it."
},
{
"topic": "Core Parameter Deep Dive: -as (Ambient Super-samples)",
"content": "The `-as` parameter defines the number of additional samples used to refine the initial ambient divisions in areas where high variance is detected. It is a secondary, more targeted refinement. If the initial `-ad` samples show high variation (e.g., one hits a dark wall, the next a bright window), Radiance sends out `-as` extra samples to get a more accurate average]. After setting a reasonable base value for `-ad`, increasing `-as` can efficiently clean up remaining noise without the high cost of universally increasing `-ad`. A good starting point is to set `-as` to half the value of `-ad`."
},
{
"topic": "Core Parameter Deep Dive: -aa (Ambient Accuracy)",
"content": "The `-aa` parameter controls the allowable error for the interpolation performed by the irradiance cache. It specifically manages *interpolation* error, not sampling error. Attempting to fix blotchy artifacts (an `-ad` problem) by lowering `-aa` is incorrect and will drastically increase computation time. The correct use for `-aa` is to resolve artifacts that appear as smooth but incorrect gradients or light 'bleeding' around corners. A special value of `-aa 0` disables interpolation entirely, which is computationally prohibitive and reserved for generating reference results."
},
{
"topic": "Core Parameter Deep Dive: -dj (Direct Jittering)",
"content": "The `-dj` parameter introduces a random element to shadow rays for area light sources. A value of 0 produces sharp, unrealistic hard-edged shadows. A positive value (e.g., `-dj 0.7`) distributes shadow rays across the source, correctly simulating soft-edged shadows (penumbras). For direct sun analysis with `rcontrib`, it is often better to use `-dj 0` to ensure the ray is always sent to the center of the solar disc for maximum consistency."
},
{
"topic": "rpict View Types (-vt)",
"content": "Radiance supports several camera projection models using the `-vt` option:\n- **v (Perspective):** Standard rectilinear projection for realistic architectural visualization. \n- **l (Parallel):** Orthographic projection with no perspective, used for elevations, plans, and axonometric views. \n- **c (Cylindrical Panorama):** Creates 360° panoramic images. \n- **h (Hemispherical Fisheye):** Equidistant projection of a 180° hemisphere. Required for `evalglare` analysis. \n- **a (Angular Fisheye):** Distance from center is proportional to view angle. Also suitable for glare analysis. \n- **s (Planisphere):** Stereographic projection that preserves angles, used for sun-path diagrams."
},
{
"topic": "Daylight Factor (DF) Workflow Steps",
"content": "The Daylight Factor (DF) workflow calculates interior illuminance under a standard CIE Overcast Sky and normalizes the results. The steps are:\n1. **Create the Sky:** Use `gensky` with the `-c` flag for an overcast sky and the `-B` flag to set a reference horizontal irradiance. To get 10,000 lux, the command is `!gensky -c -B 55.866 > sky.rad` (since 10000 lux / 179 lm/W ≈ 55.866 W/m²). \n2. **Create Octree:** Combine the sky, geometry, and materials with `oconv`. \n3. **Calculate Interior Illuminance:** Use the standard `rtrace` workflow with the generated octree and a points file. A minimum of `-ab 3` is recommended for overcast conditions. \n4. **Calculate DF:** Use `rcalc` to process the raw irradiance. The expression converts the result to illuminance, divides by the 10,000 lux reference, and multiplies by 100 to get a percentage. \nExample rcalc command: `cat interior_irradiance.dat | rcalc -e '$1=100 * (179*($1*0.265+$2*0.670+$3*0.065)) / 10000' > results_df.txt`"
},
{
"topic": "Three-Phase Method (3PM) Matrix Definitions",
"content": "The Three-Phase Method (3PM) decouples the annual simulation light path into four distinct matrices, allowing for modular and rapid re-calculation. The governing equation is `I = V * T * D * S`. The matrices are:\n- **S (Sky Matrix):** A matrix of sky patch luminances for every time step in a year, generated from a climate file using `gendaymtx`. \n- **D (Daylight Matrix):** Describes light transport from the sky patches to the exterior surface of the fenestration. Calculated with `rcontrib`. \n- **T (Transmission Matrix):** Describes the optical behavior of the fenestration system itself. This is a Bidirectional Scattering Distribution Function (BSDF), typically an XML file generated by `genBSDF` or LBNL WINDOW. \n- **V (View Matrix):** Describes light transport from the interior surface of the fenestration to the final sensor points. Calculated with `rcontrib`."
},
{
"topic": "Five-Phase Method (5PM) Correction Logic",
"content": "The Five-Phase Method (5PM) refines the 3PM by performing a high-accuracy calculation for the direct sun component and using it to correct the base resultThis is critical for calculating Annual Sunlight Exposure (ASE) or analyzing light-redirecting systemsThe logic is to calculate three separate illuminance time-series and combine them.\nThe final equation is:\n`I_5PM = I_3PM_total - I_3PM_direct + I_5PM_direct`\nWhere:\n- `I_3PM_total` is the result from a standard 3-Phase simulation. \n- `I_3PM_direct` is the inaccurate direct-sun-only portion calculated using the 3PM. \n- `I_5PM_direct` is the new, high-fidelity direct-sun-only portion calculated with a more accurate method."
},
{
"topic": "Five-Phase Method: Advanced Matrices (Vd, Dd, Cds)",
"content": "The 5-Phase method introduces new matrices to isolate and accurately calculate the direct sun component:\n- **Vd and Dd (Direct-only View and Daylight Matrices):** These are generated using `rcontrib` with `-ab 0` (or `-ab 1`) and a special 'black' octree where all non-source surfaces are perfect absorbers. This ensures only the direct, un-reflected light paths are calculated for the subtraction step. \n- **Cds (Direct Sun Coefficient Matrix):** This is a new high-fidelity matrix that directly relates the sun's position to the interior sensors, bypassing the coarse sky patch discretization of the 3PM. It is calculated using `rcontrib` with an octree that contains many explicit sun sources (`suns.rad`) and a high-resolution tensor tree BSDF for the window. "
},
{
"topic": "Radiance Program: rtrace (Detailed Options)",
"content": "`rtrace` traces rays from standard input through a scene octree. Its behavior is controlled by numerous options, many of which are shared with `rpict`. Key options unique to or commonly used with `rtrace` include:\n- **-I (Uppercase i):** A boolean switch to compute irradiance instead of radiance, interpreting input as a measurement point and surface normal. This is essential for grid-based illuminance analysis. \n- **-h:** A switch to suppress the information header in the output file. \n- **-w:** A switch to suppress non-fatal warning messages. \n- **-ospec:** Produces output fields according to a specification string, allowing you to trace a ray's path and properties (e.g., `-ot` to trace, `-op` for intersection point, `-on` for normal). \n- **-n nproc:** Executes in parallel on `nproc` local processes to speed up calculation. \n- **-x res, -y res:** Sets the x and y resolution, which helps structure the output and is useful when creating image files from `rtrace` data. "
},
{
"topic": "Radiance Program: rpict (Detailed Options)",
"content": "`rpict` generates a 2D image from a scene octree. In addition to ambient parameters, its output is primarily controlled by view parameters:\n- **-vt[v|l|c|h|a|s]:** Sets the view type (e.g., `v` for perspective, `h` for hemispherical fisheye).\n- **-vp x y z:** Sets the View Point (camera location).\n- **-vd xd yd zd:** Sets the View Direction vector.\n- **-vu xu yu zu:** Sets the View Up vector, defining vertical orientation.\n- **-vh val / -vv val:** Sets the horizontal/vertical field of view in degrees (or width/height for parallel views).\n- **-x res / -y res:** Sets the horizontal/vertical resolution in pixels.\n- **-i:** A boolean switch to compute irradiance for each pixel instead of radiance."
},
{
"topic": "Full 3-Phase Method Matrix Generation Script",
"content": "This script generates the Daylight and View matrices, which is the most computationally intensive step of the 3-Phase Method and only needs to be run once for a given building geometry. High-quality ambient parameters are essential as they affect all subsequent results. \n\n**Filename:** `run_3ph_matrix_generation.sh` \n**Location:** `07_scripts/` \n```bash\n#!/bin/bash\n# --- Configuration ---\nPROJECT_NAME=\"office_3ph\"\n# Use high-quality parameters for matrix generation.\nAB=7\nAD=4096\nAS=2048\nAR=1024\nAA=0.1\n\n# --- File & Directory Setup ---\nGEOM_DIR=\"../01_geometry\"\nMAT_DIR=\"../02_materials\"\nOCT_DIR=\"../06_octrees\"\nRESULTS_DIR=\"../08_results\"\nmkdir -p $OCT_DIR $RESULTS_DIR\n\n# 1. Create Exterior Octree (for Daylight Matrix)\n# Contains only exterior geometry and windows with a placeholder material.\necho \"1. Creating EXTERIOR octree...\"\nEXT_OCTREE=\"${OCT_DIR}/${PROJECT_NAME}_exterior.oct\"\noconv -f ${MAT_DIR}/exterior_materials.mat ${GEOM_DIR}/exterior_geometry.rad > $EXT_OCTREE\n\n# 2. Generate Daylight Matrix (Sky -> Window Exterior)\necho \"2. Generating Daylight Matrix...\"\nDAYLIGHT_MTX=\"${RESULTS_DIR}/daylight.mtx\"\n# rcontrib calculates contribution from sky modifiers, binned into 145 Reinhart patches.\nrcontrib -I+ -w -ab $AB -ad $AD -as $AS -ar $AR -aa $AA \\\n -f reinhart.cal -b tbin -bn 145 -m sky_glow \\\n -c 10000 \\\n $EXT_OCTREE < <(oconv -f -i $EXT_OCTREE ${GEOM_DIR}/windows.rad | xform -m window_surface) > $DAYLIGHT_MTX\nif [ $? -ne 0 ]; then echo \"Error generating Daylight Matrix. Exiting.\"; exit 1; fi\n\n# 3. Create Interior Octree (for View Matrix)\n# Contains only interior geometry. The window is the sole light source.\necho \"3. Creating INTERIOR octree...\"\nINT_OCTREE=\"${OCT_DIR}/${PROJECT_NAME}_interior.oct\"\noconv -f ${MAT_DIR}/interior_materials.mat ${GEOM_DIR}/interior_geometry.rad > $INT_OCTREE\n\n# 4. Generate View Matrix (Window Interior -> Sensors)\necho \"4. Generating View Matrix...\"\nVIEW_MTX=\"${RESULTS_DIR}/view.mtx\"\nPOINTS_FILE=\"${RESULTS_DIR}/grid.pts\" # Assumes this exists\n# Trace from sensor points back to the window, binning results by the Klems basis.\nrcontrib -I+ -w -ab $AB -ad $AD -as $AS -ar $AR -aa $AA \\\n -f klems_int.cal -b kbin -bn 145 -m window_material \\\n $INT_OCTREE < $POINTS_FILE > $VIEW_MTX\nif [ $? -ne 0 ]; then echo \"Error generating View Matrix. Exiting.\"; exit 1; fi\n\necho \"---\"\necho \"Matrix generation complete.\"\necho \"Daylight Matrix: ${DAYLIGHT_MTX}\"\necho \"View Matrix: ${VIEW_MTX}\"\necho \"---\"\n```"
},
{
"topic": "Full 3-Phase Method Annual Calculation Script",
"content": "This script performs the final, rapid calculation for a 3-Phase Method annual simulation. It takes the pre-calculated matrices, a weather file, and a window BSDF file to generate a year's worth of illuminance data. The key advantage is that you can test different window systems by simply swapping the BSDF file and re-running this fast script. \n\n**Filename:** `run_3ph_annual.sh` \n**Location:** `07_scripts/` \n```bash\n#!/bin/bash\n# --- Configuration ---\nPROJECT_NAME=\"office_3ph\"\n# Provide a path to an EnergyPlus Weather (EPW) file.\nWEATHER_FILE=\"/path/to/your/USA_CA_Los-Angeles.Intl.AP.722950_TMY3.epw\"\n\n# --- File & Directory Setup ---\nBSDF_DIR=\"../05_bsdf\"\nRESULTS_DIR=\"../08_results\"\n\n# 1. Generate Sky Matrix from Weather File\necho \"1. Generating sky matrix from EPW file...\"\nSKY_MTX=\"${RESULTS_DIR}/sky.smx\"\n# epw2wea converts EPW to WEA format, then gendaymtx creates the annual sky matrix.\nepw2wea $WEATHER_FILE | gendaymtx -m 1 > $SKY_MTX\nif [ $? -ne 0 ]; then echo \"Error generating Sky Matrix. Exiting.\"; exit 1; fi\n\n# 2. Run dctimestep to get annual results\necho \"2. Running dctimestep for annual simulation...\"\nDAYLIGHT_MTX=\"${RESULTS_DIR}/daylight.mtx\"\nVIEW_MTX=\"${RESULTS_DIR}/view.mtx\"\n# This is the modular part: swap this XML file to test a different window.\nBSDF_FILE=\"${BSDF_DIR}/clear_glass.xml\"\nANNUAL_RESULTS=\"${RESULTS_DIR}/${PROJECT_NAME}.ill\"\n\n# dctimestep performs the final matrix multiplication for all 8760 hours.\ndctimestep $VIEW_MTX $BSDF_FILE $DAYLIGHT_MTX $SKY_MTX > $ANNUAL_RESULTS\nif [ $? -ne 0 ]; then echo \"Error during dctimestep. Exiting.\"; exit 1; fi\n\necho \"---\"\necho \"Annual simulation complete.\"\necho \"Annual illuminance results saved to: ${ANNUAL_RESULTS}\"\necho \"You can now run the post-processing script on this file.\"\necho \"---\"\n```"
},
{
"topic": "Detailed 5-Phase Method Workflow Commands",
"content": "The 5-Phase Method provides high accuracy for direct sun by correcting a standard 3-Phase result. The core equation is `I_5ph = I_3ph - I_ds-3ph + I_ds-5ph`. This involves calculating three separate time-series of illuminance and combining them. \n\n**Part 1: Calculate Standard 3-Phase Term (`I_3ph`)**\n1. **Generate V, D, S, and T matrices:** Follow the standard 3-Phase method. Use a Klems basis BSDF for the T matrix (e.g., `bsdf/fullwindow_klems.xml`). \n2. **Run `dctimestep`:**\n ```bash\n dctimestep -n 8760 -if matrices/viewmatrix.vmx bsdf/fullwindow_klems.xml \\\n matrices/daylightmatrix.dmx matrices/OakLand.smx | \\\n rcollate -h -oc 1 > data/i_3ph.txt\n ```\n \n\n**Part 2: Calculate Inaccurate Direct 3-Phase Term (`I_ds-3ph`)**\n1. [**Create 'black' octree:** Make all non-glazing surfaces non-reflective to isolate direct paths. \n ```bash\n xform -m black objects/testroom_Swall.rad objects/testroom.rad ... | \\\n oconv materials/testroom.mat - ... > octs/model_allblack.oct\n ```\n \n2. **Generate Direct View Matrix (`Vd`):** Use the black octree with `-ab 1`. \n ```bash\n rcontrib -I+ -ab 1 ... -m viewsurf octs/model_allblack.oct < data/photocells.pts > matrices/viewmatrix_direct.vmx\n ```\n \n3. **Generate Direct Daylight Matrix (`Dd`):** Use the black octree with `-ab 0`. \n ```bash\n genklemsamp ... | rcontrib -c 1000 -ab 0 ... -m sky_glow octs/model_allblack.oct > matrices/daylightmatrix_direct.dmx\n ```\n \n4. **Generate Direct Sun-Only Sky Matrix (`Sds`):** Use `gendaymtx` with the `-d` flag. \n ```bash\n gendaymtx -of -d skies/OakLand.wea > matrices/OakLand_direct.smx\n ```\n \n5. **Run `dctimestep`:**\n ```bash\n dctimestep -n 8760 -if matrices/viewmatrix_direct.vmx bsdf/fullwindow_klems.xml \\\n matrices/daylightmatrix_direct.dmx matrices/OakLand_direct.smx | \\\n rcollate -h -oc 1 > data/i_ds3ph.txt\n ```\n \n\n**Part 3: Calculate Accurate Direct 5-Phase Term (`I_ds-5ph`)**\n1. **Generate `suns.rad` file:** Create a scene file with many (e.g., 5185) sun sources. \n ```bash\n echo \"void light solar 0 0 3 1e6 1e6 1e6\" > skies/suns.rad\n cnt 5185 | rcalc -e MF:6 -f reinsrc.cal -e Rbin=recno \\\n -o 'solar source sun${Rbin} 0 0 4 ${Dx} ${Dy} ${Dz} 0.533' >> skies/suns.rad\n ```\n \n2. **Generate Tensor Tree BSDF:** Create a high-resolution BSDF (e.g., `bsdf/fullwindow_t45.xml`) using `genBSDF`. \n3. **Create suns octree:** Combine the black geometry, suns file, and the fenestration geometry using the high-resolution BSDF proxy. \n ```bash\n xform -m black ... | oconv materials/testroom.mat - ... objects/glazing_bsdf.rad skies/suns.rad > octs/model_suns.oct\n ```\n \n4. **Generate Sun Coefficient Matrix (`Cds`):** Use `rcontrib` to relate sun positions to sensors via the high-res BSDF. \n ```bash\n rcontrib -I -ab 1 -ad 65536 -dc 1 -dt 0 -dj 0 ... -m solar \\\n octs/model_suns.oct < data/photocells.pts > matrices/directsun.dsmx\n ```\n \n5. **Generate 5-Phase Sun Matrix (`Ssun`):** Use `gendaymtx` with the `-5` flag. \n ```bash\n gendaymtx -5 -d -m 6 -of skies/OakLand.wea > matrices/OakLand_direct_m6.smx\n ```\n \n6. **Run `dctimestep`:**\n ```bash\n dctimestep -n 8760 -if matrices/directsun.dsmx matrices/OakLand_direct_m6.smx | \\\n rcollate -h -oc 1 > data/i_ds5ph.txt\n ```\n \n\n**Part 4: Combine Final Results**\n1. **Use `rlam` and `rcalc`:** Paste the three data files together and perform the final calculation, then convert to lux. \n ```bash\n rlam data/i_3ph.txt data/i_ds3ph.txt data/i_ds5ph.txt | \\\n rcalc -e 'r=$1-$4+$7; g=$2-$5+$8; b=$3-$6+$9' \\\n -e '$1=179*(.265*r+.670*g+.065*b)' | \\\n rcollate -h -fa1 -ic 8760 -t > results/illum.txt\n ```\n "
},
{
"topic": "Radiance Program Deep Dive: rcontrib",
"content": "`rcontrib` is a core Radiance program that computes ray coefficients for objects identified by their modifiers. It is essential for matrix-based daylighting methods. \n\n**Key Functionality:**\n- Traces rays from an input source (e.g., sensor points) and tallies their contributions from specified light sources or sky patches (modifiers). \n- The output can be a contribution value (if `-V+` is used) or a coefficient that must be multiplied by the source's radiance (`-V-`, the default for daylight coefficients). \n\n**Important Settings:**\n- **`-n nprocs`**: Runs the calculation in parallel on `nprocs` processes to speed up computation. \n- **`-o ospec`**: Defines the output destination. Can be a file or a command pipe. `%s` is replaced by the modifier name and `%d` by the bin number. \n- **`-m mod`**: Specifies a modifier name (e.g., `sky_glow`) for which to compute contributions. Can be repeated. \n- **`-M file`**: Reads a list of modifier names from a file. \n- **`-b binv`**: Defines a 'bin number' expression, allowing for finer resolution, such as dividing a sky dome into patches. \n- **`-bn nbins`**: Specifies the total number of bins in advance, which is critical for correctly formatted output. \n- **`-f source`**: Reads definitions and expressions (e.g., for binning) from a source file, like `reinhart.cal` or `klems_int.cal`. \n- **`-c count`**: Accumulates and averages contributions over `count` input rays. A value of 0 produces a single record summing all input, useful for reverse sampling. \n- **`rtrace options`**: Accepts most standard `rtrace` options to control the quality of the ray-tracing (e.g., `-ab`, `-ad`, `-aa`, `-I+` for irradiance). "
},
{
"topic": "Radiance Program Deep Dive: rmtxop",
"content": "`rmtxop` loads and performs operations on matrix files. It is a critical utility for combining results in multi-phase simulations and for converting data formats. \n\n**Key Operations:**\n- **Concatenation (`.`):** Standard matrix multiplication. \n- **Addition (`+`):** Element-wise addition of two matrices. \n- **Element-wise Multiplication (`*`):** Multiplies corresponding elements of two matrices. \n- **Element-wise Division (`/`):** Divides elements of the first matrix by the second. \n\n**Important Settings:**\n- **`-v`**: Verbose mode, announces each operation. \n- **`-f[afdc]`**: Sets the output format: `a` for ASCII, `f` for float, `d` for double, `c` for RGBE color. \n- **`-t`**: Transposes the matrix, swapping rows and columns. Can be applied to inputs or the final result. \n- **`-s sf`**: Applies a scalar factor `sf` to the matrix elements. \n- **`-c c1 c2 ...`**: Transforms element values using coefficients. For example, `-c 47.4 119.9 11.6` converts a 3-component RGB irradiance matrix to a 1-component illuminance (lux) matrix. "
},
{
"topic": "Radiance Philosophy: Visualization vs. Simulation",
"content": "Radiance is a lighting visualization and simulation tool, not just a photorealistic renderer. Its primary goal is to generate images where calculated light levels quantitatively match actual physical conditions, making it a research and engineering instrument for predicting visible radiation distribution with verifiable accuracy. The core unit is spectral radiance (W⋅sr−1⋅m−2), from which all other photometric metrics like illuminance (lux) can be derived. The validity of a simulation depends entirely on the accuracy of its inputs, following the principle of 'garbage in, garbage out'."
},
{
"topic": "How Radiance Defines Light Sources",
"content": "In Radiance, light is an attribute of a surface, not an independent entity. There are no disembodied 'point lights'. To create a light source, you must first define a geometric object (e.g., a polygon or sphere) and then assign it a material property that makes it self-luminous. The object itself becomes the light source."
},
{
"topic": "Radiance Ray-Tracing Algorithm",
"content": "Radiance uses a light-backwards ray-tracing algorithm. Instead of tracing rays forward from light sources, it traces rays backward from the viewpoint (a virtual camera or measurement point). These rays bounce off surfaces based on their defined properties. When a ray path terminates at a light-emitting surface, its radiance contribution is calculated and added to the total value for the initial pixel or point. This process simulates both direct and indirect (diffuse interreflection) illumination."
},
{
"topic": "Radiance Scene File (.rad) Structure",
"content": "A .rad file is a human-readable plain text file that describes a 3D environment, including geometry, materials, and light sources. It supports four basic statement types:\n- Comments: Lines beginning with '#' are ignored.\n- Primitives: Core definitions for surfaces (polygons, spheres) and modifiers (materials, textures).\n- Aliases: Associates a new name with a previously defined primitive.\n- External Commands: Lines beginning with '!' are executed by the system shell, allowing for procedural geometry, file inclusion, and complex scene construction."
},
{
"topic": "Radiance Universal Primitive Syntax",
"content": "Every primitive in Radiance (materials, surfaces, etc.) follows a universal syntax:\n\nmodifier type identifier\nN S1 S2... SN\nI I1 I2... II\nM R1 R2... RM\n\n- modifier: The name of a previously defined primitive (like a material) that modifies the current one. Use 'void' for base materials.\n- type: A keyword specifying the primitive type (e.g., polygon, plastic, light).\n- identifier: A unique, user-defined name for the new primitive.\n- Argument Blocks: The next three lines contain string (N), integer (I), and real/floating-point (M) arguments, each preceded by a count of the arguments on that line."
},
{
"topic": "Two-Step Principle of Creating a Light Source",
"content": "Adding an artificial light source in Radiance is a two-step procedure:\n1. Define a Light Material: Create a material primitive using a light-emitting type (e.g., 'light', 'spotlight'). This defines the light's color and intensity and gives it a unique name.\n2. Apply the Material to Geometry: Create a geometric primitive (e.g., a polygon or sphere) and use the name of the light material from Step 1 as its modifier. This transforms the geometric object into a luminaire."
},
{
"topic": "Example: Creating a Spherical Light Source",
"content": "This example shows the two-step process for creating a spherical light source:\n\n```\n# Step 1: Define the light-emitting material.\n# The modifier is \"void\", type is \"light\", identifier is \"bright\".\nvoid light bright\n0\n0\n3 100 100 100 # R G B (Radiance in W/sr/m^2)\n\n# Step 2: Define geometry and apply the material.\n# The modifier is \"bright\", the material defined above.\n# The type is \"sphere\", the identifier is \"fixture\".\nbright sphere fixture\n0\n0\n4 2 1 1.5 0.125 # x_cen y_cen z_cen radius\n```"
},
{
"topic": "Native Light Source Primitive: light",
"content": "The 'light' primitive is the most fundamental light-emitting material. It models a surface as a perfect, uniform, diffuse emitter (Lambertian distribution), radiating light equally in all directions. It is ideal for bare lamps or simple luminous panels.\n\nSyntax:\nvoid light light_identifier\n0\n0\n3 Red_emission Green_emission Blue_emission\n\nThe three real arguments define the spectral radiance in W⋅sr−1⋅m−2 for the R, G, and B channels, controlling both color and intensity."
},
{
"topic": "Native Light Source Primitive: spotlight",
"content": "The 'spotlight' primitive models luminaires with directed output, like downlights or track lights. It defines color, intensity, direction, and angular spread.\n\nSyntax:\nvoid spotlight spotlight_identifier\n0\n0\n7 Red Green Blue cone_angle dx dy dz\n\n- Red, Green, Blue: Radiance in W⋅sr−1⋅m−2.\n- cone_angle: Full angular width of the emission cone in degrees (0-360).\n- dx, dy, dz: A 3D vector defining the beam's orientation."
},
{
"topic": "spotlight: Direction Vector and Focal Length",
"content": "The direction vector (dx dy dz) in a 'spotlight' primitive serves a dual purpose. Its orientation aims the light, but its magnitude (length) defines an effective focal length, simulating how a real lens or reflector collimates light. This changes the light falloff from the standard 1/r² to something closer to 1/(r+e)², where 'e' is the vector's magnitude. To simply aim the spotlight without this focusing effect, you must use a normalized direction vector (a vector with a length of 1.0), such as (0 0 -1) to aim straight down."
},
{
"topic": "Native Light Source Primitive: glow",
"content": "The 'glow' primitive is for self-luminous surfaces where the contribution to scene illumination can be precisely controlled or eliminated, making it an essential optimization tool. It is ideal for sources that must be visible but have negligible photometric impact, like indicator LEDs or exit signs.\n\nSyntax:\nvoid glow glow_identifier\n0\n0\n4 Red Green Blue max_radius"
},
{
"topic": "glow: The max_radius Parameter",
"content": "The 'max_radius' parameter in a 'glow' material controls its participation in the lighting calculation:\n- If max_radius > 0: The surface acts as a light source, but only for objects within this specified radius.\n- If max_radius = 0 (default): The surface is visible and contributes to indirect (ambient) calculations, but never casts direct shadows.\n- If max_radius < 0: The surface is purely cosmetic. It is visible but completely excluded from all lighting calculations (direct and indirect). This is the most efficient option for things like indicator lights."
},
{
"topic": "Native Light Source Primitive: illum",
"content": "The 'illum' primitive is for modeling secondary light sources, like luminaire diffusers or windows. Its key feature is that it acts as a light source for calculations but adopts the appearance of a different, specified material when viewed directly. This provides a computationally efficient way to model things like translucent diffusers without modeling the lamp inside.\n\nSyntax:\nalternate_material illum illum_identifier\n0\n0\n3 Red Green Blue"
},
{
"topic": "illum: Modeling Luminaire Diffusers",
"content": "The expert workflow for modeling a luminaire with a diffuser uses the 'illum' primitive. Instead of modeling the fixture box and internal lamp, you only model the visible diffuser polygon. The process is:\n1. Define a standard material (e.g., 'trans' or 'plastic') that describes the visual appearance of the diffuser.\n2. Define an 'illum' material. Use the name of the appearance material from step 1 as its modifier. Set the RGB values to the desired light output of the fixture.\n3. Apply this 'illum' material to the diffuser polygon. This is more efficient because for the rest of the scene, the diffuser itself is the light source, but when viewed by the camera, it appears as the correct translucent material."
},
{
"topic": "Summary of Light-Emitting Material Primitives",
"content": "- light: General purpose diffuse emitter (bare bulb, luminous panel). Provides uniform, Lambertian emission.\n- spotlight: Directional luminaires (downlight, projector). Emits light within a defined cone; direction vector magnitude acts as a focal length.\n- glow: Computationally inexpensive sources (LEDs, screens). Contribution to scene illumination is controlled by `max_radius`, allowing for purely cosmetic sources.\n- illum: Secondary sources with a custom appearance (luminaire diffuser, luminous ceiling). Acts as a light source for calculations but appears as a different `alternate_material` when viewed directly."
},
{
"topic": "Incorporating Photometric Data with ies2rad",
"content": "Professional lighting design uses photometric data from manufacturers, typically in IES LM-63 format (.ies files). Radiance uses the 'ies2rad' command-line utility to translate this data into a Radiance scene description. It generates a .rad file containing the luminaire geometry and an 'illum' material, and a .dat file containing the interpolated photometric data that the 'illum' material references."
},
{
"topic": "Key ies2rad Command-Line Options",
"content": "- -o outname: Sets the root name for the output files.\n- -d units: Defines output dimensions ('m' for meters, 'f' for feet, etc.). Default is meters.\n- -m factor: Multiplies output by a factor. Used for applying a Light Loss Factor (LLF).\n- -c r g b: Sets a custom color. Used with -t default.\n- -t lamp: Specifies a lamp type to look up in lamp.tab. Using '-t default' forces the use of the -c color.\n- -p prefdir: Places output files into a subdirectory."
},
{
"topic": "Workflow: Using an IES File",
"content": "1. Acquire an .ies file from a manufacturer.\n2. Execute ies2rad in the terminal: `ies2rad downlight.ies`. This creates `downlight.rad` and `downlight.dat`.\n3. Integrate into your master scene file using the `!xform` command to place and orient the luminaire. Example: `!xform -t 1.5 2.0 2.8 -rx -90 downlight.rad`. This modular approach allows for easy placement of multiple instances."
},
{
"topic": "Photometric Data Best Practices: Units",
"content": "A mismatch between the units specified in the ies2rad command (-d flag) and the units used to model the main scene is one of the most common and catastrophic sources of error. If a scene is modeled in feet, but ies2rad is run with its default meter output, all lighting levels will be incorrect. It is imperative to ensure consistency."
},
{
"topic": "Photometric Data Best Practices: Color",
"content": "IES files do not contain spectral color information. For color consistency, the most robust practice is to override ies2rad's color inference. By using the `-t default` option along with `-c 1 1 1`, you can specify a color-balanced white light. Color temperature and chromaticity can then be adjusted globally in post-processing with the `pfilt` utility."
},
{
"topic": "Geometric Primitives for Light Sources",
"content": "A light-emitting material can be applied as a modifier to any standard geometric primitive to create a light source of a specific shape:\n- polygon: For flat, polygonal sources like troffers or linear fixtures.\n- sphere: For omnidirectional sources like bare lamps.\n- cylinder: For modeling linear fluorescent or LED tubes.\n- ring: For modeling the circular aperture of a recessed downlight."
},
{
"topic": "Geometric Transformations with xform",
"content": "`xform` is Radiance's utility for geometric transformations. Key options include:\n- -t x y z: Translate (Move).\n- -rx degrees: Rotate around the X-axis.\n- -ry degrees: Rotate around the Y-axis.\n- -rz degrees: Rotate around the Z-axis.\n- -s factor: Uniformly scale the object."
},
{
"topic": "xform: Order of Operations",
"content": "The order of transformation operations in `xform` is critical and non-commutative; they are applied sequentially. A common source of errors is incorrect ordering. The general rule of thumb is to perform scaling and rotation operations first, while the object is at the origin, and then perform the final translation to place it in the scene. For example, `!xform -rx 45 -t 5 0 0 object.rad` (rotate then translate) produces a different result than `!xform -t 5 0 0 -rx 45 object.rad` (translate then rotate)."
},
{
"topic": "Creating Arrays of Luminaires with xform",
"content": "`xform` can create arrays of objects efficiently using the `-a` (array) and `-i` (iterate) options.\n- `-a N`: Creates N copies of the input object. It works with the transform that immediately follows it, applying the transform cumulatively to each copy (0 times for the first, 1 time for the second, etc.).\n- `-i N`: Repeats the following transformation N times. It is often used to apply a global transformation to an entire array."
},
{
"topic": "Best Practices for Scene File Management",
"content": "For complex projects, it is best practice to use a modular file organization rather than a single monolithic .rad file. A typical project might be structured with separate files for materials (materials.rad), light definitions (lights.rad), and geometry (room_geom.rad). These components are then assembled in a master scene file using `!xform` and other commands. This approach makes scenes easier to manage, debug, and reuse."
},
{
"topic": "Compiling a Scene with oconv",
"content": "`oconv` is the Radiance scene compiler. It reads the textual .rad descriptions and builds a single binary file with a .oct extension. This octree is a spatial data structure that organizes the scene's geometry to make the ray-tracing process computationally feasible. Without this compilation step, rendering would be impossibly slow."
},
{
"topic": "oconv: The Importance of Input File Order",
"content": "A frequent source of errors is providing input files to `oconv` in the wrong order. A fundamental rule of Radiance is that a modifier must be defined before it is referenced. This means a file containing material definitions (e.g., materials.rad) must always be listed on the command line *before* any file containing geometry that uses those materials (e.g., room_geom.rad).\n- Correct: `oconv materials.rad room_geom.rad > scene.oct`\n- Incorrect: `oconv room_geom.rad materials.rad > scene.oct` (will cause an 'undefined modifier' error)."
},
{
"topic": "Rendering an Image with rpict",
"content": "`rpict` is the primary batch-mode rendering engine in Radiance. It takes a compiled .oct file and a set of parameters defining the view and calculation quality, and produces a high-dynamic-range (HDR) image. Key view parameters include:\n- -vp x y z: View point (camera location).\n- -vd dx dy dz: View direction (where the camera is pointing).\n- -vu ux uy uz: View up vector (defines 'up').\n- -vh angle / -vv angle: Horizontal and vertical field of view in degrees."
},
{
"topic": "Troubleshooting: Noise and Splotches",
"content": "The most common artifact in Radiance renderings is noise or splotchy patterns in indirectly lit areas. This is a direct result of insufficient sampling in the ambient calculation. The engine has not sent out enough rays to get a stable average of the incoming light. The solution is to increase the quality of the ambient calculation by raising the values of `-ad` (ambient divisions) and `-as` (ambient super-samples), which provides more samples to smooth out the result at the cost of longer render times."
},
{
"topic": "Troubleshooting: Caustics and Specular Noise ('Fireflies')",
"content": "Standard backward ray-tracing is inefficient at resolving focused specular reflections, like caustics from sunlight through glass or off a curved metal surface. Trying to solve this with `rpict` alone is often futile and results in extreme noise or 'fireflies'. For these cases, Radiance provides advanced tools like `mkillum` (a pre-calculation step for complex sources) or a full photon mapping extension, which is often the only viable method for cleanly rendering such scenes."
},
{
"topic": "Radiance Engine in Modern GUI Tools",
"content": "Many modern tools like ClimateStudio, Ladybug/Honeybee, and OpenStudio use Radiance as their simulation engine. These applications act as sophisticated wrappers, automatically generating .rad files and executing command-line programs like `oconv` and `rpict` behind the scenes. An understanding of the underlying Radiance principles is invaluable for troubleshooting unexpected results or extending the capabilities of these GUI-based tools."
},
{
"topic": "Material: plastic",
"content": "The 'plastic' material is for surfaces with uncolored specular highlights. It is defined by its RGB reflectance, its fraction of specularity, and its roughness value. Roughness is the RMS slope of surface facets, where 0 is perfectly smooth. Specularity fractions above 0.1 and roughness values above 0.2 are not very realistic.\n\nSyntax:\nvoid plastic id\n0\n0\n5 red green blue spec rough"
},
{
"topic": "Material: metal",
"content": "The 'metal' material is similar to plastic, but its specular highlights are modified by the material color. The specularity of metals is usually 0.9 or greater, and roughness values above 0.2 are uncommon.\n\nSyntax:\nvoid metal id\n0\n0\n5 red green blue spec rough"
},
{
"topic": "Material: trans",
"content": "'Trans' is a translucent material, similar to plastic but with added transmission properties. Transmissivity is the fraction of light that travels through the material. Transmitted specular is the fraction of transmitted light that is not diffusely scattered. Translucent objects are considered infinitely thin.\n\nSyntax:\nvoid trans id\n0\n0\n7 red green blue spec rough trans tspec"
},
{
"topic": "Material: glass",
"content": "The 'glass' material is optimized for thin glass surfaces (refractive index defaults to 1.52). It avoids modeling internal reflections by using a single surface. The primary specification is the transmissivity at normal incidence. To compute transmissivity (tn) from the more commonly measured transmittance (Tn), use the formula:\ntn = (sqrt(0.8402528435 + 0.0072522239*Tn*Tn) - 0.9166530661) / (0.0036261119*Tn)\n\nSyntax:\nvoid glass id\n0\n0\n3 rtn gtn btn"
},
{
"topic": "Material: mirror",
"content": "'Mirror' is for planar surfaces that produce virtual source reflections. It should be used sparingly as it can be computationally expensive. It is only supported for flat surfaces like polygons and rings. The arguments are the RGB reflectance values (0-1). An optional string argument can specify an alternate material for non-source rays, similar to 'illum'."
},
{
"topic": "Material: BSDF",
"content": "The 'BSDF' material type is used for complex fenestration systems. It references an XML file containing the Bidirectional Scattering Distribution Function data. The arguments include the thickness of the BSDF surface, the XML file path, and up, forward, and right-hand vectors.\n\nSyntax:\nvoid BSDF id\n6+ up_x up_y up_z fwd_x fwd_y fwd_z file.xml transform\n0\nN real_args..."
},
{
"topic": "Material: antimatter",
"content": "'Antimatter' is a material that can 'subtract' volumes from other volumes. A ray passing into an antimatter object becomes blind to all the specified modifiers. It does not work properly with the 'trans' material, and multiple antimatter surfaces should be disjoint. The viewpoint must be outside all concerned volumes for a correct rendering."
},
{
"topic": "Material: mist",
"content": "'Mist' is a virtual material used to delineate a volume of participating atmosphere, making light beams visible (e.g., from a spotlight). It can define an extinction coefficient, scattering albedo, and scattering eccentricity. It is often used to surround a beam from a spotlight or to model clouds."
},
{
"topic": "Application Workflow: Project & Scene Setup",
"content": "The user workflow begins with the left toolbar panels:\n1. Project Setup: Define project name, location (map or EPW file), and Radiance path.\n2. Dimensions: Set room width, length, height, and orientation.\n3. Apertures & Shading: Select walls in the 3D view to add windows and shading devices.\n4. Artificial Lighting & Materials: Configure surface properties and add light sources.\n5. Sensor Grid: Define points in space for simulation calculations."
},
{
"topic": "Application Workflow: Simulation and Execution",
"content": "After scene setup, the user configures the simulation using the right sidebar:\n1. Recipe Selection: Add simulation 'recipes' like 'Illuminance Map' or 'Annual Daylight'.\n2. Parameter Tuning: Configure settings for each recipe in its floating panel.\n3. Package Generation: The application gathers all data and generates a complete Radiance project folder with geometry (.rad), materials, and run scripts (.sh/.bat).\n4. Execution: In the Electron app, a 'Run Simulation' button executes the script. In a browser, the user downloads the package and runs it manually."
},
{
"topic": "Application Workflow: Results and Analysis",
"content": "The final stage involves analyzing the simulation output:\n1. Load Results: The user loads a result file (.ill, .hdr, .dgp) into the Analysis sidebar.\n2. Data Processing: A background web worker parses the file to prevent UI freezing, and the Results Manager calculates metrics (sDA, ASE, etc.).\n3. Visualization: Results are displayed as a false-color map on the 3D sensor grid and in specialized dashboards like the Annual Metrics Dashboard or HDR Image Viewer."
},
{
"topic": "Application Architecture: UI Layer (ui.js)",
"content": "`ui.js` is the central hub for user interaction. It caches DOM elements, manages all event listeners (sliders, buttons), controls the state of floating windows, updates UI labels, handles 3D scene interactions (wall/sensor clicks), and orchestrates the loading of result files and display of dashboards."
},
{
"topic": "Application Architecture: 3D Visualization Layer (scene.js, geometry.js)",
"content": "`scene.js` manages the Three.js environment, including the scene, cameras, renderer, and navigation controls. It contains the main `animate()` loop. `geometry.js` is responsible for creating and updating all 3D objects (room, windows, shading, sensor grids) based on parameters from the UI layer."
},
{
"topic": "Application Architecture: State & Persistence (project.js)",
"content": "The `Project` class in `project.js` is the single source of truth for the application's state. It gathers all settings into a comprehensive JSON object for saving, applies settings from a loaded project file, manages file system access, and orchestrates the generation of the final simulation package."
},
{
"topic": "Application Architecture: Scripting Layer (scriptGenerator.js)",
"content": "`scriptGenerator.js` is the core translation engine. It takes the consolidated project data object and generates the text content for all Radiance-compatible files, including geometry files (.rad), material files, and executable run scripts for different simulation recipes."
},
{
"topic": "Application Architecture: Data Analysis Layer (resultsManager.js)",
"content": "`resultsManager.js` is the engine for post-simulation analysis. It receives result files, offloads parsing to a web worker, stores all data (allowing for A/B comparison), calculates statistics and climate-based metrics (sDA, ASE, UDI), and provides methods for the UI to retrieve data for visualization."
},
{
"topic": "Recommended Project Directory Structure",
"content": "A well-organized project directory is critical for managing complexity. A recommended structure includes separate folders for different file types:\n- 01_geometry/: .rad files for scene geometry\n- 02_materials/: .mat or .rad files for materials\n- 04_skies/: .rad files for skies and .epw files\n- 06_octrees/: Compiled .oct files\n- 07_scripts/: BASH and Python scripts to run simulations\n- 08_results/: Raw numerical output (.ill, .dgp, .pts, etc.)\n- 09_images/: Final rendered images (.hdr, .png)"
},
{
"topic": "Core Calculation Parameter: -ab (Ambient Bounces)",
"content": "The `-ab` parameter specifies the maximum number of diffuse inter-reflections a ray will undergo. It controls the 'depth' of the indirect lighting simulation. A value of `-ab 0` disables indirect calculation. For most analyses, a value between 3 and 5 is a good balance of accuracy and speed. Higher values (6-7) are needed for complex geometries. A high `-ab` value is ineffective unless the ray weight limit (`-lw`) is set to a very small value."
},
{
"topic": "Core Calculation Parameter: -ad (Ambient Divisions)",
"content": "The `-ad` parameter sets the number of sample rays sent to probe the hemisphere for indirect illuminance. It is the primary control for resolving detail in indirect lighting. An insufficient `-ad` value is the most common cause of 'splotchy' or 'blotchy' artifacts in renderings. The first step in troubleshooting these artifacts is to increase the `-ad` value, often by doubling it."
},
{
"topic": "Core Calculation Parameter: -as (Ambient Super-samples)",
"content": "The `-as` parameter defines the number of additional samples used to refine the initial ambient divisions in areas where high variance is detected. After setting a reasonable base value for `-ad`, increasing `-as` can efficiently clean up remaining noise without the high cost of universally increasing `-ad`. A good starting point is to set `-as` to half the value of `-ad`."
},
{
"topic": "Core Calculation Parameter: -aa (Ambient Accuracy)",
"content": "The `-aa` parameter controls the allowable error for interpolation by the irradiance cache. It specifically manages *interpolation* error, not sampling error. Attempting to fix blotchy artifacts (an `-ad` problem) by lowering `-aa` is incorrect and will drastically increase computation time. A correct use for `-aa` is to resolve artifacts like smooth but incorrect gradients or light 'bleeding' around corners."
},
{
"topic": "Core Calculation Parameter: -dj (Direct Jittering)",
"content": "The `-dj` parameter introduces randomness to shadow rays for area light sources. A value of 0 produces sharp, unrealistic hard-edged shadows. A positive value (e.g., `-dj 0.7`) distributes shadow rays across the source, correctly simulating soft-edged shadows (penumbras). For direct sun analysis with `rcontrib`, it is often better to use `-dj 0` to ensure the ray is always sent to the center of the solar disc for consistency."
},
{
"topic": "Recommended Ambient Parameter Quality Presets",
"content": "- Draft/Preview: -ab 2 -ad 256 -as 128 -aa 0.25 (Fast, expects artifacts)\n- Standard/Good: -ab 4 -ad 1024 -as 512 -aa 0.2 (Balanced, good default)\n- High-Fidelity: -ab 7 -ad 4096 -as 2048 -aa 0.15 (For publication or complex scenes, slow)\n- Reference: -aa 0.0 (Disables interpolation, extremely slow, for research)"
},
{
"topic": "Point-in-Time Workflow: Grid-Based Illuminance (rtrace)",
"content": "This workflow calculates illuminance (lux) on a grid of sensor points. It uses the `rtrace` program with a sensor points file (.pts). Each line in the .pts file defines a sensor's location and orientation (X Y Z Vx Vy Vz). The `-I` switch is used to compute irradiance. The raw RGB output from `rtrace` is then converted to a single lux value using `rcalc` with the expression `'$1=179*($1*0.265+$2*0.670+$3*0.065)'`."
},
{
"topic": "Point-in-Time Workflow: Daylight Factor (DF)",
"content": "Daylight Factor (DF) is the ratio of interior illuminance to the available unobstructed exterior horizontal illuminance under a standard CIE Overcast Sky. The workflow involves using `gensky` with the `-c` flag for an overcast sky and the `-B` flag to set a reference horizontal irradiance (e.g., 55.866 W/m² to correspond to 10,000 lux). `rtrace` is used to find the interior illuminance, which is then divided by the reference value to get the DF percentage."
},
{
"topic": "Point-in-Time Workflow: Daylight Glare Probability (DGP)",
"content": "DGP analysis is a two-step process to assess visual discomfort. First, `rpict` is used to generate a high-quality 180° hemispherical fisheye HDR image (`-vth -vh 180 -vv 180`). Second, the `evalglare` program processes this image to calculate the DGP value. High-quality ambient parameters are essential for the `rpict` rendering, as an inaccurate background luminance will produce an incorrect DGP value."
},
{
"topic": "DGP Interpretation Scale",
"content": "The Daylight Glare Probability (DGP) value represents the fraction of people likely to be disturbed by glare. The scale is interpreted as follows:\n- DGP < 0.35: Imperceptible glare (Good)\n- 0.35 ≤ DGP < 0.40: Perceptible glare (Acceptable)\n- 0.40 ≤ DGP < 0.45: Disturbing glare (Poor)\n- DGP ≥ 0.45: Intolerable glare (Unacceptable)"
},
{
"topic": "Annual Simulation: Daylight Coefficient (DC) Method",
"content": "The Daylight Coefficient (DC) method is the foundation for annual simulations. It pre-calculates the relationship between a set of discrete sky patches and interior sensor points, storing this relationship in a Daylight Coefficient matrix (DC). The illuminance for any given sky condition can then be found with a simple matrix multiplication: E = DC * S, where S is the sky luminance vector. `rcontrib` is the primary tool for generating the DC matrix. The main limitation is inflexibility; if the glazing changes, the entire time-consuming calculation must be redone."
},
{
"topic": "Annual Simulation: Three-Phase Method (3PM)",
"content": "The Three-Phase Method (3PM) solves the inflexibility of the DC method by decoupling the light path into three matrices: V (View Matrix: window interior to sensor), T (Transmission Matrix: through the window, i.e., a BSDF file), and D (Daylight Matrix: sky to window exterior). The final illuminance is calculated by I = V * T * D * S. The great advantage is that different window systems (T matrices) can be tested rapidly without recalculating the V and D matrices, which are the most computationally intensive parts."
},
{
"topic": "Annual Simulation: Five-Phase Method (5PM)",
"content": "The Five-Phase Method (5PM) is the most accurate method for annual simulations where direct sunlight is critical (e.g., for calculating Annual Sunlight Exposure, ASE). It refines the 3PM by correcting for the 'smearing' of the sun's contribution across a large sky patch. It works by calculating the total 3PM result, subtracting the inaccurate direct-sun portion from the 3PM, and adding back a new, high-fidelity direct-sun portion calculated with a more accurate method. The equation is: I_5PM = I_3PM_total - I_3PM_direct + I_5PM_direct."
},
{
"topic": "Annual Metrics: sDA, UDI, and ASE",
"content": "After an annual simulation produces a raw .ill file, a post-processing script is used to calculate standard metrics:\n- sDA (Spatial Daylight Autonomy): A measure of sufficient daylight (e.g., % of area receiving at least 300 lux for 50% of occupied hours).\n- UDI (Useful Daylight Illuminance): Percentage of time a point is within a useful illuminance range (e.g., 100-2000 lux).\n- ASE (Annual Sunlight Exposure): A measure of excessive sunlight (% of area receiving at least 1000 lux of direct sun for 250 hours). ASE should be calculated using the 5-Phase Method."
},
{
"topic": "Limitations of Tristimulus (RGB) Simulation for Non-Visual Effects",
"content": "Standard RGB simulation is effective for visual rendering but discards significant spectral information. This is a problem for analyzing non-visual effects of light on human physiology, such as circadian rhythm synchronization, which is mediated by intrinsically photosensitive Retinal Ganglion Cells (ipRGCs). These cells contain melanopsin, which has a peak sensitivity in the blue region of the spectrum (~460-490 nm), different from the peak visual sensitivity (~555 nm). Therefore, a standard simulation cannot accurately predict these biological effects."
},
{
"topic": "Spectral Analysis (9-Channel): N-Channel Methodology",
"content": "The 9-channel spectral methodology overcomes the limitations of Radiance's 3-channel engine by running the simulation multiple times. The visible spectrum (380-780 nm) is partitioned into 'N' bins. The simulation is run N/3 times, with Radiance's R, G, and B channels repurposed in each run to represent three consecutive spectral bins. The results are then aggregated to reconstruct a full N-channel spectral result. This methodology uses a 9-channel approach, requiring 3 simulation runs."
},
{
"topic": "Spectral Analysis (9-Channel): Wavelength Bins",
"content": "The 9-channel simulation uses the following wavelength bins:\n- Channel 1: 380-424 nm\n- Channel 2: 425-454 nm\n- Channel 3: 455-479 nm\n- Channel 4: 480-504 nm\n- Channel 5: 505-529 nm\n- Channel 6: 530-559 nm\n- Channel 7: 560-599 nm\n- Channel 8: 600-644 nm\n- Channel 9: 645-780 nm"
},
{
"topic": "Spectral Analysis (9-Channel): Pre-Processing Spectral Data",
"content": "To prepare for a 9-channel spectral simulation, continuous spectral data (like an SPD for a light source or an SRD for a material) must be converted into a single representative value for each of the 9 channels. This is done by calculating the arithmetic mean of all spectral data points that fall within the defined wavelength range for each bin. This process results in a nine-element vector representing the binned spectral properties."
},
{
"topic": "Spectral Analysis (9-Channel): Two-Pass Method for Sky/Sun Generation",
"content": "To create a spectrally accurate yet energetically consistent sky model, Ray Modeler uses a 'two-pass' method with the `gendaylit` program. \nPass 1: `gendaylit` is run normally to get the correct baseline radiometric output (radiance) of a standard white sun.\nPass 2: A scaling coefficient is calculated to match the brightness of the custom binned solar spectrum to the baseline sun's brightness. `gendaylit` is then run again, but its output is programmatically modified (using `sed`) to apply the scaled binned colors to the sun and sky primitives."
},
{
"topic": "Spectral Analysis (9-Channel): Post-Processing and Metric Calculation",
"content": "The final stage transforms the raw 9-channel simulation output into meaningful metrics. The data from the three separate simulation runs is aggregated. Then, final metrics are calculated via a weighted sum, where the 9-channel spectral irradiance vector is multiplied by a vector of pre-calculated weighting coefficients specific to the desired metric (e.g., photopic, melanopic, neuropic)."
},
{
"topic": "Spectral Analysis (9-Channel): Weighting Coefficients for Metrics",
"content": "To calculate final metrics from the 9-channel spectral irradiance, the following weighting coefficients are used in a weighted sum:\n- Photopic Weights (V(λ)): [0.0003, 0.0232, 0.1465, 0.3644, 0.7386, 0.9859, 0.8654, 0.3804, 0.0535]\n- Melanopic Weights (S_mel(λ)): [0.0335, 0.4021, 0.7932, 0.8876, 0.6548, 0.3923, 0.1256, 0.0177, 0.0010]\n- Neuropic Weights (Neuropsin): [0.7259, 0.2312, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]"
},
{
"topic": "Three-Phase Method: Core Concept",
"content": "The Three-Phase Method is a powerful technique for analyzing complex fenestration systems. It calculates matrices representing each phase of light transport:\nD (Daylight Matrix): From the sky to the window exterior.\nT (Transmission Matrix): Through the window system (a BSDF file).\nV (View Matrix): From the window interior to the analysis points.\nS (Sky Matrix): The sky's luminance distribution.\nThe final illuminance is calculated by multiplying these matrices: i = V * T * D * S."
},
{
"topic": "Three-Phase Method: Sky Generation (Phase 1)",
"content": "This phase defines the luminous environment. For a single point in time, `gensky` is piped to `genskyvec` to create a sky vector (.skv). For an entire year, `epw2wea` converts a weather file to .wea format, which is then used by `gendaymtx` to generate an annual sky matrix (.smx) containing 8760 hourly sky vectors."
},
{
"topic": "Three-Phase Method: Transmission Matrix / BSDF (Phase 2)",
"content": "The Transmission Matrix (T) describes how light passes through the fenestration system. It is a Bidirectional Scattering Distribution Function (BSDF), typically generated as an .xml file using software like LBNL WINDOW. Inside the software, the user defines the glazing layers and shading systems and sets the angular basis to 'W6 standard basis' (Klems 145-patch basis) to generate the file."
},
{
"topic": "Three-Phase Method: Daylight Matrix (Phase 3)",
"content": "The Daylight Matrix (D) relates sky patches to incident light directions on the window exterior. It is generated using `rcontrib`. First, an octree of the building's exterior and any obstructions is created. Then, `genklemsamp` generates sampling rays from the window surface, which are piped to `rcontrib` to calculate the contribution coefficients from the sky patches, resulting in a .dmx file."
},
{
"topic": "Three-Phase Method: View Matrix (Phase 4)",
"content": "The View Matrix (V) characterizes how light leaving the window's interior surface contributes to sensor points. An octree of the room's interior is created where the window is modeled as a 'glow' light source. `rcontrib` is then used to trace rays from the sensor points (.pts file) back to this glowing window surface. The results are binned according to the Klems basis to match the BSDF, creating a .vmx file."
},
{
"topic": "Three-Phase Method: Final Calculation (Phase 5)",
"content": "The final results are calculated by multiplying the matrices using the `dctimestep` program. The command takes the V, T, D, and S matrices as input in that order. For an annual simulation, the `-n 8760` flag is used along with the annual sky matrix (.smx) to produce an annual results file (e.g., .ill)."
},
{
"topic": "Radiance Calculation Strategy: Backward Ray-Tracing",
"content": "The Radiance lighting simulation suite is a physically-based, backward ray-tracing engine renowned for its scientific accuracy. The term 'backward' refers to its computational strategy: instead of tracing millions of rays forward from light sources in the hope that some will enter the virtual camera, Radiance traces rays backward from each pixel of the virtual camera into the scene to determine what is visible. When a ray intersects a surface, the software calculates the light arriving at that point from all other sources in the environment. This approach is orders of magnitude more efficient for generating images and calculating values at specific points. Achieving accuracy is contingent upon a sophisticated understanding and correct application of its numerous calculation parameters."
},
{
"topic": "The Ambient Calculation and Irradiance Cache",
"content": "The majority of light within an architectural space arrives at a given point after reflecting off other surfaces. This indirect illumination is computationally intensive. Radiance employs a sophisticated algorithm known as the irradiance cache to manage this complexity efficiently. This cache is a form of adaptive sampling for global illumination. Instead of calculating the full hemispherical illumination at every single point, it computes it at select locations and then intelligently interpolates these values for nearby points, storing the results in an ambient file (.amb). The parameters that govern this process represent the most critical trade-offs between simulation speed and physical accuracy."
},
{
"topic": "Core Calculation Parameter: -ar (Ambient Resolution)",
"content": "The `-ar` parameter sets the density of the irradiance cache, effectively defining the maximum resolution for the indirect calculation relative to the overall scene size. It works in concert with `-aa`. The ambient resolution is divided by the scene's bounding box diagonal to determine the maximum density of cached values. This means the same `-ar` value will behave differently in a small room versus a large open-plan office. A very low `-aa` value (high accuracy) is of little use if `-ar` is also low, as the system will not have enough resolution to store the detailed ambient values it is being forced to calculate."
},
{
"topic": "Core Calculation Parameter: -ds (Direct Sampling Ratio)",
"content": "The `-ds` parameter controls the adaptive subdivision of large area light sources. It ensures that surfaces very close to a large source are sampled with sufficient detail to avoid artifacts, at a modest computational cost."
},
{
"topic": "Core Calculation Parameter: -dt (Direct Thresholding)",
"content": "The `-dt` parameter is an optimization that halts shadow testing for light sources whose potential contribution to a point falls below a specified fraction. In a scene with hundreds of lights, `-dt` allows Radiance to estimate the contribution of the farthest, least significant lights instead of tracing a shadow ray for every single one, saving time."
},
{
"topic": "Core Calculation Parameter: -dc (Direct Certainty)",
"content": "A value of 1 for the `-dc` parameter guarantees that all shadow lines resulting in a contrast change greater than the `-dt` value will be calculated explicitly. For high-accuracy simulations, especially those involving direct sunlight, it is standard practice to set `-dt 0` and `-dc 1`. This combination disables statistical approximation and forces a full, brute-force calculation for all light sources, ensuring maximum accuracy at the cost of longer simulation times."
},
{
"topic": "Full Point-in-Time Illuminance Workflow (rtrace)",
"content": "This workflow calculates illuminance (lux) on a grid of sensor points using the `rtrace` program. First, create a sensor points file (.pts) where each line defines a sensor's location and orientation (X Y Z Vx Vy Vz). For a horizontal work plane, the orientation vector is `0 0 1`. The core of the workflow is a single command pipeline that pipes the points file into `rtrace` and then pipes the `rtrace` output into `rcalc` for conversion to lux.\n\nExample shell script (`run_point_illuminance.sh`):\n```bash\n#!/bin/bash\n# --- Simulation Configuration ---\nPROJECT_NAME=\"office_test\"\nLATITUDE=34.05\nLONGITUDE=-118.24\nMERIDIAN=-120\nMONTH=6\nDAY=21\nTIME=14.5\n# Ambient Parameters (Standard Quality)\nAB=4\nAD=1024\nAS=512\nAR=512\nAA=0.2\n\n# --- File & Directory Setup ---\nGEOM_DIR=\"../01_geometry\"\nMAT_DIR=\"../02_materials\"\nSKY_DIR=\"../04_skies\"\nOCT_DIR=\"../06_octrees\"\nRESULTS_DIR=\"../08_results\"\n\nmkdir -p $SKY_DIR $OCT_DIR $RESULTS_DIR\n\n# 1. Generate Sky Description\nSKY_FILE=\"${SKY_DIR}/${PROJECT_NAME}_${MONTH}_${DAY}_${TIME}.rad\"\ngensky $MONTH $DAY $TIME -a $LATITUDE -o $LONGITUDE -m $MERIDIAN > $SKY_FILE\n\n# 2. Create Scene Octree\nOCTREE_FILE=\"${OCT_DIR}/${PROJECT_NAME}.oct\"\noconv ${MAT_DIR}/*.mat ${GEOM_DIR}/*.rad ${SKY_FILE} > $OCTREE_FILE\n\n# 3. Generate Analysis Grid (if it doesn't exist)\nPOINTS_FILE=\"${RESULTS_DIR}/grid.pts\"\nif [ ! -f \"$POINTS_FILE\" ]; then\n gengrid 10 10 5 5 0.85 > $POINTS_FILE\nfi\n\n# 4. Run Illuminance Calculation\nRESULTS_FILE=\"${RESULTS_DIR}/${PROJECT_NAME}_illuminance.txt\"\nrtrace -I -h -w -ab $AB -ad $AD -as $AS -ar $AR -aa $AA $OCTREE_FILE < $POINTS_FILE | \\\nrcalc -e '$1=179*($1*0.265+$2*0.670+$3*0.065)' > $RESULTS_FILE\n\necho \"Simulation complete. Results in ${RESULTS_FILE}\"\n```"
},
{
"topic": "Full Point-in-Time DGP Workflow (rpict & evalglare)",
"content": "Daylight Glare Probability (DGP) analysis is a two-step process. First, `rpict` is used to generate a high-quality 180° hemispherical fisheye HDR image (`-vth -vh 180 -vv 180`). Second, the `evalglare` program processes this image to calculate the DGP value. High-quality ambient parameters are essential for the `rpict` rendering. The view is defined in a separate .vf file.\n\nExample view file (`glare_view.vf`):\n`rvu -vth -vp 2.5 1.5 1.2 -vd 0 1 0 -vu 0 0 1 -vh 180 -vv 180`\n\nExample shell script (`run_dgp_analysis.sh`):\n```bash\n#!/bin/bash\n# --- Simulation Configuration ---\nPROJECT_NAME=\"office_test\"\nLATITUDE=34.05\nLONGITUDE=-118.24\nMERIDIAN=-120\nMONTH=6\nDAY=21\nTIME=14.5\n# Ambient Parameters (High Quality is ESSENTIAL)\nAB=6\nAD=2048\nAS=1024\nAR=512\nAA=0.15\n\n# --- File & Directory Setup ---\nGEOM_DIR=\"../01_geometry\"\nMAT_DIR=\"../02_materials\"\nSKY_DIR=\"../04_skies\"\nOCT_DIR=\"../06_octrees\"\nVIEW_DIR=\"../03_views\"\nRESULTS_DIR=\"../08_results\"\nIMG_DIR=\"../09_images/hdr\"\nmkdir -p $SKY_DIR $OCT_DIR $RESULTS_DIR $IMG_DIR\n\n# 1. Generate Sky\nSKY_FILE=\"${SKY_DIR}/${PROJECT_NAME}_${MONTH}_${DAY}_${TIME}.rad\"\ngensky $MONTH $DAY $TIME -a $LATITUDE -o $LONGITUDE -m $MERIDIAN > $SKY_FILE\n\n# 2. Create Octree\nOCTREE_FILE=\"${OCT_DIR}/${PROJECT_NAME}.oct\"\noconv ${MAT_DIR}/*.mat ${GEOM_DIR}/*.rad ${SKY_FILE} > $OCTREE_FILE\n\n# 3. Render Fisheye Image\nVIEW_FILE=\"${VIEW_DIR}/glare_view.vf\"\nHDR_IMAGE=\"${IMG_DIR}/${PROJECT_NAME}_glare.hdr\"\nrpict -vf $VIEW_FILE -x 1500 -y 1500 \\\n -ab $AB -ad $AD -as $AS -ar $AR -aa $AA \\\n $OCTREE_FILE > $HDR_IMAGE\n\n# 4. Run evalglare\nGLARE_RESULTS=\"${RESULTS_DIR}/${PROJECT_NAME}_dgp.txt\"\nGLARE_CHECK_IMG=\"${IMG_DIR}/${PROJECT_NAME}_glare_check.hdr\"\nevalglare -d -c $GLARE_CHECK_IMG $HDR_IMAGE > $GLARE_RESULTS\n\necho \"Glare analysis complete. Results in ${GLARE_RESULTS}\"\n```"
},
{
"topic": "Post-Processing Annual Metrics with Python",
"content": "After running an annual simulation (e.g., with the Three-Phase Method), the raw .ill file contains 8760 illuminance values for every point. This data can be processed into meaningful metrics like sDA, UDI, and ASE using a Python script with the numpy and pandas libraries.\n\nExample script (`post_process_annual.py`):\n```python\nimport numpy as np\nimport pandas as pd\nimport argparse\nimport os\n\ndef calculate_metrics(illuminance_file: str, output_dir: str, num_points: int):\n try:\n data = np.fromfile(illuminance_file, dtype=np.float32)\n annual_illuminance = data.reshape(8760, num_points)\n except Exception as e:\n print(f\"Error reading file: {e}\")\n return\n\n # Occupancy: Weekdays, 8 AM to 6 PM (17:00)\n time_index = pd.to_datetime(pd.date_range(start='2023-01-01', periods=8760, freq='h'))\n occupied_mask = (time_index.hour >= 8) & (time_index.hour <= 17) & (time_index.dayofweek < 5)\n occupied_illuminance = annual_illuminance[occupied_mask, :]\n\n # sDA (300 lux, 50% of hours)\n sDA_points = np.sum(occupied_illuminance >= 300, axis=0) / occupied_illuminance.shape[0]\n sDA = np.sum(sDA_points >= 0.5) / num_points * 100\n\n # ASE (1000 lux, 250 hours) - requires 5-Phase method for accuracy\n ASE_points = np.sum(occupied_illuminance >= 1000, axis=0)\n ASE = np.sum(ASE_points >= 250) / num_points * 100\n\n # UDI\n udi_f = np.mean(occupied_illuminance < 100, axis=0) * 100\n udi_s = np.mean((occupied_illuminance >= 100) & (occupied_illuminance < 500), axis=0) * 100\n udi_a = np.mean((occupied_illuminance >= 500) & (occupied_illuminance < 2000), axis=0) * 100\n udi_e = np.mean(occupied_illuminance >= 2000, axis=0) * 100\n\n # Save results\n summary = {'sDA_300_50%': [f\"{sDA:.2f}%\"], 'ASE_1000_250h': [f\"{ASE:.2f}%\"]}\n summary_df = pd.DataFrame(summary)\n summary_path = os.path.join(output_dir, \"annual_metrics_summary.csv\")\n summary_df.to_csv(summary_path, index=False)\n print(f\"Summary results saved to {summary_path}\")\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"illuminance_file\", type=str)\n parser.add_argument(\"--points\", type=int, required=True)\n parser.add_argument(\"--outdir\", type=str, default=\"../08_results\")\n args = parser.parse_args()\n calculate_metrics(args.illuminance_file, args.outdir, args.points)\n```"
},
{
"topic": "Troubleshooting Common Simulation Issues",
"content": "Common simulation problems and their solutions:\n- **Light leaks at corners:** Caused by coincident surfaces. Ensure geometry is well-constructed with no gaps.\n- **Large, splotchy, or blotchy patches:** The `-ad` (Ambient Divisions) parameter is too low. Solution: Double the value of `-ad` and re-render. Do not try to fix this by lowering `-aa`.\n- **Smooth shadows with blocky boundaries:** The `-aa` (Ambient Accuracy) is too high or `-ar` (Ambient Resolution) is too low, causing poor interpolation. Solution: Decrease `-aa` and/or increase `-ar`.\n- **Scene appears too dark far from windows:** Insufficient light propagation. The `-ab` value is too low, or the `-lw` (limit weight) value is too high. Solution: Increase `-ab` to 5 or higher and decrease `-lw` to 1e-5 or lower.\n- **Incorrect DGP results:** Could be multiple causes: 1) Input image was not a 180° fisheye view. 2) Rendering quality was too low, giving inaccurate background luminance. 3) Wrong threshold method in `evalglare`. Solution: Verify `rpict` command used `-vth -vh 180 -vv 180`, re-render with High-Fidelity settings, and use the `-t` option in `evalglare`."
},
{
"topic": "Radiance Program: dctimestep",
"content": "`dctimestep` computes annual simulation results by multiplying pre-calculated matrices. It typically takes a View matrix, a Transmission matrix (BSDF), a Daylight matrix, and a Sky matrix as input. Key options:\n- `-n nsteps`: Specifies the number of time steps (e.g., 8760 for an annual simulation).\n- `-o ospec`: Specifies an output file or a pattern for multiple output files (e.g., for generating an image per time step)."
},
{
"topic": "Radiance Program: epw2wea",
"content": "`epw2wea` is a utility that transforms an EnergyPlus weather data file (.epw) into the DAYSIM weather file format (.wea). This converted format is then suitable for use with the `gendaymtx` program to create annual sky matrices."
},
{
"topic": "Radiance Program: evalglare",
"content": "`evalglare` evaluates glare sources within a 180-degree fisheye HDR image to calculate metrics like Daylight Glare Probability (DGP). Key options:\n- `-d`: Produces detailed output, listing properties of each detected glare source.\n- `-c fname`: Creates a 'check file,' which is a copy of the input image with detected glare sources highlighted in color for verification.\n- `-t xpos ypos angle`: Defines a task area on the image. This is the recommended method for determining the glare source threshold, which is based on the average luminance within this task area."
},
{
"topic": "Radiance Program: genBSDF",
"content": "`genBSDF` computes a bidirectional scattering distribution function (BSDF) from a Radiance scene description of a fenestration system. The output is an XML file conforming to the LBNL Window 6 standard. Key options:\n- `-c Nsamp`: Specifies the number of samples per incident direction (default 2000).\n- `-n Nproc`: Specifies the number of simultaneous processes to run.\n- `-t4 Nlog2`: Computes a non-uniform BSDF represented as a rank 4 tensor tree, suitable for high-accuracy direct sun calculations in the 5-Phase Method."
},
{
"topic": "Radiance Program: gendaymtx",
"content": "`gendaymtx` generates an annual Perez sky matrix (.smx) from a weather file (.wea). The output matrix contains luminance values for each sky patch for every hour of the year. Key options:\n- `-m N`: Increases sky resolution using Reinhart subdivision (e.g., `-m 1` for 146 patches, `-m 4` for 2306 patches).\n- `-d`: Produces a sun-only matrix with no sky contributions.\n- `-s`: Excludes the direct solar component.\n- `-5`: A special option used in the 5-Phase Method to generate a high-resolution direct sun matrix."
},
{
"topic": "Radiance Program: gensky",
"content": "`gensky` generates a Radiance scene description for the CIE standard sky distribution for a specific month, day, and time. Key options:\n- `-c`: Generates a cloudy (overcast) sky.\n- `+s`: Generates a sunny sky with the sun.\n- `-s`: Generates a sunny sky without the sun.\n- `-a lat -o lon -m mer`: Specifies site latitude, longitude, and standard meridian for accurate sun position.\n- `-B irrad`: Sets the zenith brightness based on a specified horizontal diffuse irradiance (in W/m²). Used in Daylight Factor workflows."
},
{
"topic": "Radiance Program: pcomb",
"content": "`pcomb` is used to combine Radiance pictures of equal size. It can perform linear combinations or more complex pixel-by-pixel operations defined by an expression. It is used in the image-based 5-Phase Method to combine the results from the different calculation phases using an expression like `-e 'ro=ri(1)-ri(2)+ri(3);...'`."
},
{
"topic": "Radiance Program: rcontrib",
"content": "`rcontrib` is a core program used to compute contribution coefficients, forming the basis of matrix-based methods. It traces rays from sensors and bins the results based on which source modifier (e.g., a sky patch) the ray terminates on. Key options:\n- `-I+`: Specifies that irradiance contributions should be calculated.\n- `-f file.cal`: A function file that defines how to map ray directions to bin numbers.\n- `-b var -bn N`: Specifies the bin variable and the total number of bins.\n- `-m modifier`: The base name of the modifier for which to calculate coefficients."
},
{
"topic": "Radiance Program: rfluxmtx",
"content": "`rfluxmtx` is a utility that acts as a wrapper for `rcontrib` to simplify the process of creating flux transfer matrices, such as the View (V) and Daylight (D) matrices in the Three-Phase Method. It samples rays uniformly over a sender surface and records their arrival at receiver surfaces."
},
{
"topic": "Radiance Program: rmtxop",
"content": "`rmtxop` performs matrix operations on files. It is used in annual simulation workflows to convert the RGB irradiance output from `dctimestep` into a single lux value. It can also be used to add and subtract matrices, which is essential for assembling the final result in the 5-Phase Method."
},
{
"topic": "Radiance Program: vwrays",
"content": "`vwrays` computes the ray origin and direction for each pixel of a specified view. Its output is typically piped directly into another program like `rtrace` or `rcontrib`. It is a key component in generating image-based View Matrices for the Three-Phase Method, where it generates the initial rays for a camera view that are then traced back to the window surface by `rcontrib`."
},
{
"topic": "Core Parameter Deep Dive: -ab (Ambient Bounces)",
"content": "The `-ab` parameter specifies the maximum number of diffuse inter-reflections a ray will undergo. It controls the 'depth' of the simulation. A value of `-ab 0` disables the indirect calculation entirely, useful for isolating direct solar contribution or for very fast previews. For most analyses, a value between 3 and 5 is a good balance of accuracy and speed. Higher values (6-7) are necessary for complex geometries like deep rooms or spaces with light shelves, where light must follow a tortuous path. A high `-ab` value is ineffective unless the ray weight limit (`-lw`) is set to a very small value (e.g., 1e-6) and the reflection limit (`-lr`) is also increased, otherwise rays will terminate prematurely."
},
{
"topic": "Core Parameter Deep Dive: -ad (Ambient Divisions)",
"content": "The `-ad` parameter sets the number of sample rays sent to probe the hemisphere for indirect illuminance and is the primary control for resolving detail in the first-bounce indirect lighting. An insufficient `-ad` value is the most common cause of 'splotchy' or 'blotchy' artifacts, which are a clear sign of undersampling the hemispherical environment. The scale of these splotches is much larger than a single pixel, indicating a fundamental issue with the ambient calculation. The first and most effective step in troubleshooting these artifacts is to increase the `-ad` value, often by doubling it."
},
{
"topic": "Core Parameter Deep Dive: -as (Ambient Super-samples)",
"content": "The `-as` parameter defines the number of additional samples used to refine the initial ambient divisions in areas where high variance is detected. It is a secondary, more targeted refinement. If the initial `-ad` samples show high variation (e.g., one hits a dark wall, the next a bright window), Radiance sends out `-as` extra samples to get a more accurate average]. After setting a reasonable base value for `-ad`, increasing `-as` can efficiently clean up remaining noise without the high cost of universally increasing `-ad`. A good starting point is to set `-as` to half the value of `-ad`."
},
{
"topic": "Core Parameter Deep Dive: -aa (Ambient Accuracy)",
"content": "The `-aa` parameter controls the allowable error for the interpolation performed by the irradiance cache. It specifically manages *interpolation* error, not sampling error. Attempting to fix blotchy artifacts (an `-ad` problem) by lowering `-aa` is incorrect and will drastically increase computation time. The correct use for `-aa` is to resolve artifacts that appear as smooth but incorrect gradients or light 'bleeding' around corners. A special value of `-aa 0` disables interpolation entirely, which is computationally prohibitive and reserved for generating reference results."
},
{
"topic": "Core Parameter Deep Dive: -dj (Direct Jittering)",
"content": "The `-dj` parameter introduces a random element to shadow rays for area light sources. A value of 0 produces sharp, unrealistic hard-edged shadows. A positive value (e.g., `-dj 0.7`) distributes shadow rays across the source, correctly simulating soft-edged shadows (penumbras). For direct sun analysis with `rcontrib`, it is often better to use `-dj 0` to ensure the ray is always sent to the center of the solar disc for maximum consistency."
},
{
"topic": "rpict View Types (-vt)",
"content": "Radiance supports several camera projection models using the `-vt` option:\n- **v (Perspective):** Standard rectilinear projection for realistic architectural visualization. \n- **l (Parallel):** Orthographic projection with no perspective, used for elevations, plans, and axonometric views. \n- **c (Cylindrical Panorama):** Creates 360° panoramic images. \n- **h (Hemispherical Fisheye):** Equidistant projection of a 180° hemisphere. Required for `evalglare` analysis. \n- **a (Angular Fisheye):** Distance from center is proportional to view angle. Also suitable for glare analysis. \n- **s (Planisphere):** Stereographic projection that preserves angles, used for sun-path diagrams."
},
{
"topic": "Daylight Factor (DF) Workflow Steps",
"content": "The Daylight Factor (DF) workflow calculates interior illuminance under a standard CIE Overcast Sky and normalizes the results. The steps are:\n1. **Create the Sky:** Use `gensky` with the `-c` flag for an overcast sky and the `-B` flag to set a reference horizontal irradiance. To get 10,000 lux, the command is `!gensky -c -B 55.866 > sky.rad` (since 10000 lux / 179 lm/W ≈ 55.866 W/m²). \n2. **Create Octree:** Combine the sky, geometry, and materials with `oconv`. \n3. **Calculate Interior Illuminance:** Use the standard `rtrace` workflow with the generated octree and a points file. A minimum of `-ab 3` is recommended for overcast conditions. \n4. **Calculate DF:** Use `rcalc` to process the raw irradiance. The expression converts the result to illuminance, divides by the 10,000 lux reference, and multiplies by 100 to get a percentage. \nExample rcalc command: `cat interior_irradiance.dat | rcalc -e '$1=100 * (179*($1*0.265+$2*0.670+$3*0.065)) / 10000' > results_df.txt`"
},
{
"topic": "Three-Phase Method (3PM) Matrix Definitions",
"content": "The Three-Phase Method (3PM) decouples the annual simulation light path into four distinct matrices, allowing for modular and rapid re-calculation. The governing equation is `I = V * T * D * S`. The matrices are:\n- **S (Sky Matrix):** A matrix of sky patch luminances for every time step in a year, generated from a climate file using `gendaymtx`. \n- **D (Daylight Matrix):** Describes light transport from the sky patches to the exterior surface of the fenestration. Calculated with `rcontrib`. \n- **T (Transmission Matrix):** Describes the optical behavior of the fenestration system itself. This is a Bidirectional Scattering Distribution Function (BSDF), typically an XML file generated by `genBSDF` or LBNL WINDOW. \n- **V (View Matrix):** Describes light transport from the interior surface of the fenestration to the final sensor points. Calculated with `rcontrib`."
},
{
"topic": "Five-Phase Method (5PM) Correction Logic",
"content": "The Five-Phase Method (5PM) refines the 3PM by performing a high-accuracy calculation for the direct sun component and using it to correct the base resultThis is critical for calculating Annual Sunlight Exposure (ASE) or analyzing light-redirecting systemsThe logic is to calculate three separate illuminance time-series and combine them.\nThe final equation is:\n`I_5PM = I_3PM_total - I_3PM_direct + I_5PM_direct`\nWhere:\n- `I_3PM_total` is the result from a standard 3-Phase simulation. \n- `I_3PM_direct` is the inaccurate direct-sun-only portion calculated using the 3PM. \n- `I_5PM_direct` is the new, high-fidelity direct-sun-only portion calculated with a more accurate method."
},
{
"topic": "Five-Phase Method: Advanced Matrices (Vd, Dd, Cds)",
"content": "The 5-Phase method introduces new matrices to isolate and accurately calculate the direct sun component:\n- **Vd and Dd (Direct-only View and Daylight Matrices):** These are generated using `rcontrib` with `-ab 0` (or `-ab 1`) and a special 'black' octree where all non-source surfaces are perfect absorbers. This ensures only the direct, un-reflected light paths are calculated for the subtraction step. \n- **Cds (Direct Sun Coefficient Matrix):** This is a new high-fidelity matrix that directly relates the sun's position to the interior sensors, bypassing the coarse sky patch discretization of the 3PM. It is calculated using `rcontrib` with an octree that contains many explicit sun sources (`suns.rad`) and a high-resolution tensor tree BSDF for the window. "
},
{
"topic": "Radiance Program: rtrace (Detailed Options)",
"content": "`rtrace` traces rays from standard input through a scene octree. Its behavior is controlled by numerous options, many of which are shared with `rpict`. Key options unique to or commonly used with `rtrace` include:\n- **-I (Uppercase i):** A boolean switch to compute irradiance instead of radiance, interpreting input as a measurement point and surface normal. This is essential for grid-based illuminance analysis. \n- **-h:** A switch to suppress the information header in the output file. \n- **-w:** A switch to suppress non-fatal warning messages. \n- **-ospec:** Produces output fields according to a specification string, allowing you to trace a ray's path and properties (e.g., `-ot` to trace, `-op` for intersection point, `-on` for normal). \n- **-n nproc:** Executes in parallel on `nproc` local processes to speed up calculation. \n- **-x res, -y res:** Sets the x and y resolution, which helps structure the output and is useful when creating image files from `rtrace` data. "
},
{
"topic": "Radiance Program: rpict (Detailed Options)",
"content": "`rpict` generates a 2D image from a scene octree. In addition to ambient parameters, its output is primarily controlled by view parameters:\n- **-vt[v|l|c|h|a|s]:** Sets the view type (e.g., `v` for perspective, `h` for hemispherical fisheye).\n- **-vp x y z:** Sets the View Point (camera location).\n- **-vd xd yd zd:** Sets the View Direction vector.\n- **-vu xu yu zu:** Sets the View Up vector, defining vertical orientation.\n- **-vh val / -vv val:** Sets the horizontal/vertical field of view in degrees (or width/height for parallel views).\n- **-x res / -y res:** Sets the horizontal/vertical resolution in pixels.\n- **-i:** A boolean switch to compute irradiance for each pixel instead of radiance."
},
{
"topic": "Full 3-Phase Method Matrix Generation Script",
"content": "This script generates the Daylight and View matrices, which is the most computationally intensive step of the 3-Phase Method and only needs to be run once for a given building geometry. High-quality ambient parameters are essential as they affect all subsequent results. \n\n**Filename:** `run_3ph_matrix_generation.sh` \n**Location:** `07_scripts/` \n```bash\n#!/bin/bash\n# --- Configuration ---\nPROJECT_NAME=\"office_3ph\"\n# Use high-quality parameters for matrix generation.\nAB=7\nAD=4096\nAS=2048\nAR=1024\nAA=0.1\n\n# --- File & Directory Setup ---\nGEOM_DIR=\"../01_geometry\"\nMAT_DIR=\"../02_materials\"\nOCT_DIR=\"../06_octrees\"\nRESULTS_DIR=\"../08_results\"\nmkdir -p $OCT_DIR $RESULTS_DIR\n\n# 1. Create Exterior Octree (for Daylight Matrix)\n# Contains only exterior geometry and windows with a placeholder material.\necho \"1. Creating EXTERIOR octree...\"\nEXT_OCTREE=\"${OCT_DIR}/${PROJECT_NAME}_exterior.oct\"\noconv -f ${MAT_DIR}/exterior_materials.mat ${GEOM_DIR}/exterior_geometry.rad > $EXT_OCTREE\n\n# 2. Generate Daylight Matrix (Sky -> Window Exterior)\necho \"2. Generating Daylight Matrix...\"\nDAYLIGHT_MTX=\"${RESULTS_DIR}/daylight.mtx\"\n# rcontrib calculates contribution from sky modifiers, binned into 145 Reinhart patches.\nrcontrib -I+ -w -ab $AB -ad $AD -as $AS -ar $AR -aa $AA \\\n -f reinhart.cal -b tbin -bn 145 -m sky_glow \\\n -c 10000 \\\n $EXT_OCTREE < <(oconv -f -i $EXT_OCTREE ${GEOM_DIR}/windows.rad | xform -m window_surface) > $DAYLIGHT_MTX\nif [ $? -ne 0 ]; then echo \"Error generating Daylight Matrix. Exiting.\"; exit 1; fi\n\n# 3. Create Interior Octree (for View Matrix)\n# Contains only interior geometry. The window is the sole light source.\necho \"3. Creating INTERIOR octree...\"\nINT_OCTREE=\"${OCT_DIR}/${PROJECT_NAME}_interior.oct\"\noconv -f ${MAT_DIR}/interior_materials.mat ${GEOM_DIR}/interior_geometry.rad > $INT_OCTREE\n\n# 4. Generate View Matrix (Window Interior -> Sensors)\necho \"4. Generating View Matrix...\"\nVIEW_MTX=\"${RESULTS_DIR}/view.mtx\"\nPOINTS_FILE=\"${RESULTS_DIR}/grid.pts\" # Assumes this exists\n# Trace from sensor points back to the window, binning results by the Klems basis.\nrcontrib -I+ -w -ab $AB -ad $AD -as $AS -ar $AR -aa $AA \\\n -f klems_int.cal -b kbin -bn 145 -m window_material \\\n $INT_OCTREE < $POINTS_FILE > $VIEW_MTX\nif [ $? -ne 0 ]; then echo \"Error generating View Matrix. Exiting.\"; exit 1; fi\n\necho \"---\"\necho \"Matrix generation complete.\"\necho \"Daylight Matrix: ${DAYLIGHT_MTX}\"\necho \"View Matrix: ${VIEW_MTX}\"\necho \"---\"\n```"
},
{
"topic": "Full 3-Phase Method Annual Calculation Script",
"content": "This script performs the final, rapid calculation for a 3-Phase Method annual simulation. It takes the pre-calculated matrices, a weather file, and a window BSDF file to generate a year's worth of illuminance data. The key advantage is that you can test different window systems by simply swapping the BSDF file and re-running this fast script. \n\n**Filename:** `run_3ph_annual.sh` \n**Location:** `07_scripts/` \n```bash\n#!/bin/bash\n# --- Configuration ---\nPROJECT_NAME=\"office_3ph\"\n# Provide a path to an EnergyPlus Weather (EPW) file.\nWEATHER_FILE=\"/path/to/your/USA_CA_Los-Angeles.Intl.AP.722950_TMY3.epw\"\n\n# --- File & Directory Setup ---\nBSDF_DIR=\"../05_bsdf\"\nRESULTS_DIR=\"../08_results\"\n\n# 1. Generate Sky Matrix from Weather File\necho \"1. Generating sky matrix from EPW file...\"\nSKY_MTX=\"${RESULTS_DIR}/sky.smx\"\n# epw2wea converts EPW to WEA format, then gendaymtx creates the annual sky matrix.\nepw2wea $WEATHER_FILE | gendaymtx -m 1 > $SKY_MTX\nif [ $? -ne 0 ]; then echo \"Error generating Sky Matrix. Exiting.\"; exit 1; fi\n\n# 2. Run dctimestep to get annual results\necho \"2. Running dctimestep for annual simulation...\"\nDAYLIGHT_MTX=\"${RESULTS_DIR}/daylight.mtx\"\nVIEW_MTX=\"${RESULTS_DIR}/view.mtx\"\n# This is the modular part: swap this XML file to test a different window.\nBSDF_FILE=\"${BSDF_DIR}/clear_glass.xml\"\nANNUAL_RESULTS=\"${RESULTS_DIR}/${PROJECT_NAME}.ill\"\n\n# dctimestep performs the final matrix multiplication for all 8760 hours.\ndctimestep $VIEW_MTX $BSDF_FILE $DAYLIGHT_MTX $SKY_MTX > $ANNUAL_RESULTS\nif [ $? -ne 0 ]; then echo \"Error during dctimestep. Exiting.\"; exit 1; fi\n\necho \"---\"\necho \"Annual simulation complete.\"\necho \"Annual illuminance results saved to: ${ANNUAL_RESULTS}\"\necho \"You can now run the post-processing script on this file.\"\necho \"---\"\n```"
},
{
"topic": "Detailed 5-Phase Method Workflow Commands",
"content": "The 5-Phase Method provides high accuracy for direct sun by correcting a standard 3-Phase result. The core equation is `I_5ph = I_3ph - I_ds-3ph + I_ds-5ph`. This involves calculating three separate time-series of illuminance and combining them. \n\n**Part 1: Calculate Standard 3-Phase Term (`I_3ph`)**\n1. **Generate V, D, S, and T matrices:** Follow the standard 3-Phase method. Use a Klems basis BSDF for the T matrix (e.g., `bsdf/fullwindow_klems.xml`). \n2. **Run `dctimestep`:**\n ```bash\n dctimestep -n 8760 -if matrices/viewmatrix.vmx bsdf/fullwindow_klems.xml \\\n matrices/daylightmatrix.dmx matrices/OakLand.smx | \\\n rcollate -h -oc 1 > data/i_3ph.txt\n ```\n \n\n**Part 2: Calculate Inaccurate Direct 3-Phase Term (`I_ds-3ph`)**\n1. [**Create 'black' octree:** Make all non-glazing surfaces non-reflective to isolate direct paths. \n ```bash\n xform -m black objects/testroom_Swall.rad objects/testroom.rad ... | \\\n oconv materials/testroom.mat - ... > octs/model_allblack.oct\n ```\n \n2. **Generate Direct View Matrix (`Vd`):** Use the black octree with `-ab 1`. \n ```bash\n rcontrib -I+ -ab 1 ... -m viewsurf octs/model_allblack.oct < data/photocells.pts > matrices/viewmatrix_direct.vmx\n ```\n \n3. **Generate Direct Daylight Matrix (`Dd`):** Use the black octree with `-ab 0`. \n ```bash\n genklemsamp ... | rcontrib -c 1000 -ab 0 ... -m sky_glow octs/model_allblack.oct > matrices/daylightmatrix_direct.dmx\n ```\n \n4. **Generate Direct Sun-Only Sky Matrix (`Sds`):** Use `gendaymtx` with the `-d` flag. \n ```bash\n gendaymtx -of -d skies/OakLand.wea > matrices/OakLand_direct.smx\n ```\n \n5. **Run `dctimestep`:**\n ```bash\n dctimestep -n 8760 -if matrices/viewmatrix_direct.vmx bsdf/fullwindow_klems.xml \\\n matrices/daylightmatrix_direct.dmx matrices/OakLand_direct.smx | \\\n rcollate -h -oc 1 > data/i_ds3ph.txt\n ```\n \n\n**Part 3: Calculate Accurate Direct 5-Phase Term (`I_ds-5ph`)**\n1. **Generate `suns.rad` file:** Create a scene file with many (e.g., 5185) sun sources. \n ```bash\n echo \"void light solar 0 0 3 1e6 1e6 1e6\" > skies/suns.rad\n cnt 5185 | rcalc -e MF:6 -f reinsrc.cal -e Rbin=recno \\\n -o 'solar source sun${Rbin} 0 0 4 ${Dx} ${Dy} ${Dz} 0.533' >> skies/suns.rad\n ```\n \n2. **Generate Tensor Tree BSDF:** Create a high-resolution BSDF (e.g., `bsdf/fullwindow_t45.xml`) using `genBSDF`. \n3. **Create suns octree:** Combine the black geometry, suns file, and the fenestration geometry using the high-resolution BSDF proxy. \n ```bash\n xform -m black ... | oconv materials/testroom.mat - ... objects/glazing_bsdf.rad skies/suns.rad > octs/model_suns.oct\n ```\n \n4. **Generate Sun Coefficient Matrix (`Cds`):** Use `rcontrib` to relate sun positions to sensors via the high-res BSDF. \n ```bash\n rcontrib -I -ab 1 -ad 65536 -dc 1 -dt 0 -dj 0 ... -m solar \\\n octs/model_suns.oct < data/photocells.pts > matrices/directsun.dsmx\n ```\n \n5. **Generate 5-Phase Sun Matrix (`Ssun`):** Use `gendaymtx` with the `-5` flag. \n ```bash\n gendaymtx -5 -d -m 6 -of skies/OakLand.wea > matrices/OakLand_direct_m6.smx\n ```\n \n6. **Run `dctimestep`:**\n ```bash\n dctimestep -n 8760 -if matrices/directsun.dsmx matrices/OakLand_direct_m6.smx | \\\n rcollate -h -oc 1 > data/i_ds5ph.txt\n ```\n \n\n**Part 4: Combine Final Results**\n1. **Use `rlam` and `rcalc`:** Paste the three data files together and perform the final calculation, then convert to lux. \n ```bash\n rlam data/i_3ph.txt data/i_ds3ph.txt data/i_ds5ph.txt | \\\n rcalc -e 'r=$1-$4+$7; g=$2-$5+$8; b=$3-$6+$9' \\\n -e '$1=179*(.265*r+.670*g+.065*b)' | \\\n rcollate -h -fa1 -ic 8760 -t > results/illum.txt\n ```\n "
},
{
"topic": "Radiance Program Deep Dive: rcontrib",
"content": "`rcontrib` is a core Radiance program that computes ray coefficients for objects identified by their modifiers. It is essential for matrix-based daylighting methods. \n\n**Key Functionality:**\n- Traces rays from an input source (e.g., sensor points) and tallies their contributions from specified light sources or sky patches (modifiers). \n- The output can be a contribution value (if `-V+` is used) or a coefficient that must be multiplied by the source's radiance (`-V-`, the default for daylight coefficients). \n\n**Important Settings:**\n- **`-n nprocs`**: Runs the calculation in parallel on `nprocs` processes to speed up computation. \n- **`-o ospec`**: Defines the output destination. Can be a file or a command pipe. `%s` is replaced by the modifier name and `%d` by the bin number. \n- **`-m mod`**: Specifies a modifier name (e.g., `sky_glow`) for which to compute contributions. Can be repeated. \n- **`-M file`**: Reads a list of modifier names from a file. \n- **`-b binv`**: Defines a 'bin number' expression, allowing for finer resolution, such as dividing a sky dome into patches. \n- **`-bn nbins`**: Specifies the total number of bins in advance, which is critical for correctly formatted output. \n- **`-f source`**: Reads definitions and expressions (e.g., for binning) from a source file, like `reinhart.cal` or `klems_int.cal`. \n- **`-c count`**: Accumulates and averages contributions over `count` input rays. A value of 0 produces a single record summing all input, useful for reverse sampling. \n- **`rtrace options`**: Accepts most standard `rtrace` options to control the quality of the ray-tracing (e.g., `-ab`, `-ad`, `-aa`, `-I+` for irradiance). "
},
{
"topic": "Radiance Program Deep Dive: rmtxop",
"content": "`rmtxop` loads and performs operations on matrix files. It is a critical utility for combining results in multi-phase simulations and for converting data formats. \n\n**Key Operations:**\n- **Concatenation (`.`):** Standard matrix multiplication. \n- **Addition (`+`):** Element-wise addition of two matrices. \n- **Element-wise Multiplication (`*`):** Multiplies corresponding elements of two matrices. \n- **Element-wise Division (`/`):** Divides elements of the first matrix by the second. \n\n**Important Settings:**\n- **`-v`**: Verbose mode, announces each operation. \n- **`-f[afdc]`**: Sets the output format: `a` for ASCII, `f` for float, `d` for double, `c` for RGBE color. \n- **`-t`**: Transposes the matrix, swapping rows and columns. Can be applied to inputs or the final result. \n- **`-s sf`**: Applies a scalar factor `sf` to the matrix elements. \n- **`-c c1 c2 ...`**: Transforms element values using coefficients. For example, `-c 47.4 119.9 11.6` converts a 3-component RGB irradiance matrix to a 1-component illuminance (lux) matrix. "
},
{
"topic": "Five-Phase Method: Core Concept and Equation",
"content": "The five-phase method extends the three-phase method to provide higher accuracy by treating the direct solar component more precisely, which is particularly important for spaces with complex fenestration systems (CFS). The core equation combines three calculated terms: a standard three-phase result, a subtraction of the inaccurate direct sun component from that result, and the addition of a new, highly accurate direct sun component. The equation is: I_5ph = I_3ph - I_ds-3ph + I_ds-5ph."
},
{
"topic": "Five-Phase Method: Prerequisites",
"content": "To perform a five-phase simulation, you need a working Radiance installation, a Radiance model of the space (geometry and materials), a photocell points file (.pts) for sensor locations, an EPW weather file for the location, and several supporting calculation files. These support files include `klems_int.cal` for Klems basis sampling, `reinhart.cal` for sky/sun discretization, and `reinsrc.cal` for generating sun sources."
},
{
"topic": "Five-Phase Method Step 1: Model Adjustments and BSDF Generation",
"content": "Before matrix calculations, the model must be prepared. This involves creating special Radiance surfaces for the simulation: `viewmtxsurf.rad` (a glow surface on the window's interior face), `daymtxsurf.rad` (a surface on the exterior face), and `glazing_bsdf.rad` (a proxy surface that will use the high-resolution BSDF). A 'black' plastic material must also be added to the main materials file for use in later steps. The method requires two BSDFs: a high-resolution tensor tree BSDF (e.g., for the accurate sun calculation) and a standard Klems basis BSDF (for the three-phase components). Both are generated using the `genBSDF` program."
},
{
"topic": "Five-Phase Method Step 2: Calculating I_3ph (Standard Three-Phase)",
"content": "This step calculates the standard three-phase daylight result. First, an octree (`model_3ph.oct`) is created containing the room geometry, context, and the special matrix surfaces. Then, the required matrices are generated: the View Matrix (V) with `rcontrib`, the Daylight Matrix (D) using `genklemsamp` piped to `rcontrib`, and the annual Sky Matrix (S) using `epw2wea` and `gendaymtx`. Finally, these matrices are combined with the Klems basis BSDF (T) using `dctimestep` to produce the annual illuminance result `i_3ph.txt`."
},
{
"topic": "Five-Phase Method Step 3: Calculating I_ds-3ph (Isolating 3-Phase Direct Sun)",
"content": "This step isolates the direct solar contribution as calculated by the standard three-phase method, which will be subtracted from the total. A special octree (`model_allblack.oct`) is created where all scene materials are turned to black to prevent inter-reflections. Using this black octree, a direct-only View Matrix (Vd) is calculated with `rcontrib -ab 1`, and a direct-only Daylight Matrix (Dd) is calculated with `rcontrib -ab 0`. A direct-sun-only Sky Matrix (Sds) is created with `gendaymtx -d`. These are combined with the Klems BSDF using `dctimestep` to produce `i_ds3ph.txt`."
},
{
"topic": "Five-Phase Method Step 4: Calculating I_ds-5ph (Accurate Direct Sun)",
"content": "This step calculates the direct solar contribution with high accuracy. A Radiance file with many sun sources (`suns.rad`) is generated. A new 'black' octree (`model_suns.oct`) is created that includes the suns file and the fenestration geometry using the high-resolution tensor tree BSDF. A Direct Sun Coefficient Matrix (Cds) is calculated with `rcontrib` using this octree, relating the sun sources to the sensors. A special 5-phase direct sun matrix (Ssun) is created using `gendaymtx -5`. These two matrices are combined using `dctimestep` to produce the accurate direct sun result `i_ds5ph.txt`."
},
{
"topic": "Five-Phase Method Step 5: Combining Components for Final Result",
"content": "The final five-phase illuminance result is assembled from the three intermediate files. The `rlam` command is used to paste the records from `i_3ph.txt`, `i_ds3ph.txt`, and `i_ds5ph.txt` side-by-side. This output is piped to `rcalc`, which performs the core calculation `(I_3ph - I_ds-3ph + I_ds-5ph)` for each RGB channel and then converts the final RGB value into a single photopic illuminance value (lux). A final `rcollate` command formats the data into a usable table, typically with hours as rows and sensors as columns."
},
{
"topic": "Radiance Philosophy: Visualization vs. Simulation",
"content": "Radiance is a lighting visualization and simulation tool, not just a photorealistic renderer. Its primary goal is to generate images where calculated light levels quantitatively match actual physical conditions, making it a research and engineering instrument for predicting visible radiation distribution with verifiable accuracy. The core unit is spectral radiance (W⋅sr−1⋅m−2), from which all other photometric metrics like illuminance (lux) can be derived. The validity of a simulation depends entirely on the accuracy of its inputs, following the principle of 'garbage in, garbage out'."
},
{
"topic": "How Radiance Defines Light Sources",
"content": "In Radiance, light is an attribute of a surface, not an independent entity. There are no disembodied 'point lights'. To create a light source, you must first define a geometric object (e.g., a polygon or sphere) and then assign it a material property that makes it self-luminous. The object itself becomes the light source."
},
{
"topic": "Radiance Ray-Tracing Algorithm",
"content": "Radiance uses a light-backwards ray-tracing algorithm. Instead of tracing rays forward from light sources, it traces rays backward from the viewpoint (a virtual camera or measurement point). These rays bounce off surfaces based on their defined properties. When a ray path terminates at a light-emitting surface, its radiance contribution is calculated and added to the total value for the initial pixel or point. This process simulates both direct and indirect (diffuse interreflection) illumination."
},
{
"topic": "Radiance Scene File (.rad) Structure",
"content": "A .rad file is a human-readable plain text file that describes a 3D environment, including geometry, materials, and light sources. It supports four basic statement types:\n- Comments: Lines beginning with '#' are ignored.\n- Primitives: Core definitions for surfaces (polygons, spheres) and modifiers (materials, textures).\n- Aliases: Associates a new name with a previously defined primitive.\n- External Commands: Lines beginning with '!' are executed by the system shell, allowing for procedural geometry, file inclusion, and complex scene construction."
},
{
"topic": "Radiance Universal Primitive Syntax",
"content": "Every primitive in Radiance (materials, surfaces, etc.) follows a universal syntax:\n\nmodifier type identifier\nN S1 S2... SN\nI I1 I2... II\nM R1 R2... RM\n\n- modifier: The name of a previously defined primitive (like a material) that modifies the current one. Use 'void' for base materials.\n- type: A keyword specifying the primitive type (e.g., polygon, plastic, light).\n- identifier: A unique, user-defined name for the new primitive.\n- Argument Blocks: The next three lines contain string (N), integer (I), and real/floating-point (M) arguments, each preceded by a count of the arguments on that line."
},
{
"topic": "Two-Step Principle of Creating a Light Source",
"content": "Adding an artificial light source in Radiance is a two-step procedure:\n1. Define a Light Material: Create a material primitive using a light-emitting type (e.g., 'light', 'spotlight'). This defines the light's color and intensity and gives it a unique name.\n2. Apply the Material to Geometry: Create a geometric primitive (e.g., a polygon or sphere) and use the name of the light material from Step 1 as its modifier. This transforms the geometric object into a luminaire."
},
{
"topic": "Example: Creating a Spherical Light Source",
"content": "This example shows the two-step process for creating a spherical light source:\n\n```\n# Step 1: Define the light-emitting material.\n# The modifier is \"void\", type is \"light\", identifier is \"bright\".\nvoid light bright\n0\n0\n3 100 100 100 # R G B (Radiance in W/sr/m^2)\n\n# Step 2: Define geometry and apply the material.\n# The modifier is \"bright\", the material defined above.\n# The type is \"sphere\", the identifier is \"fixture\".\nbright sphere fixture\n0\n0\n4 2 1 1.5 0.125 # x_cen y_cen z_cen radius\n```"
},
{
"topic": "Native Light Source Primitive: light",
"content": "The 'light' primitive is the most fundamental light-emitting material. It models a surface as a perfect, uniform, diffuse emitter (Lambertian distribution), radiating light equally in all directions. It is ideal for bare lamps or simple luminous panels.\n\nSyntax:\nvoid light light_identifier\n0\n0\n3 Red_emission Green_emission Blue_emission\n\nThe three real arguments define the spectral radiance in W⋅sr−1⋅m−2 for the R, G, and B channels, controlling both color and intensity."
},