forked from Urban-Meteorology-Reading/SUEWS
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathgenerate_datamodel_rst.py
More file actions
1998 lines (1718 loc) · 76.3 KB
/
generate_datamodel_rst.py
File metadata and controls
1998 lines (1718 loc) · 76.3 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
"""
SUEWS Data Model RST Generator.
This script generates reStructuredText (.rst) files for the SUEWS Pydantic data models.
It uses the doc_utils module to extract model documentation as JSON, then formats it as RST.
To run this script, navigate to the `docs/` directory and execute:
python generate_datamodel_rst.py
"""
import argparse
import json
from pathlib import Path
import sys
from typing import Any
# Try to import supy directly (if installed via make dev)
# Fall back to sys.path manipulation if not installed
PROJECT_ROOT = Path(__file__).resolve().parent.parent
try:
from supy.data_model.doc_utils import ModelDocExtractor
except ImportError:
# If supy is not installed, add src to path for development
SRC_PATH = PROJECT_ROOT / "src"
sys.path.insert(0, str(SRC_PATH))
from supy.data_model.doc_utils import ModelDocExtractor
class RSTGenerator:
"""Generate RST documentation from extracted model documentation."""
def __init__(self, doc_data: dict[str, Any]):
"""
Initialize the RST generator with extracted documentation data.
Args:
doc_data: Dictionary containing model documentation from ModelDocExtractor
"""
self.doc_data = doc_data
self.models = doc_data.get("models", {})
self.hierarchy = doc_data.get("hierarchy", {})
self.metadata = doc_data.get("metadata", {})
def generate_all_rst(
self, output_dir: Path, mode: str = "production", style: str = "collapsible"
) -> None:
"""
Generate RST files for all models.
Args:
output_dir: Directory to write RST files to
mode: "preview" or "production" mode
style: Style to use in production mode ("simple", "dropdown", "compact", "tabbed", "hybrid")
"""
output_dir.mkdir(parents=True, exist_ok=True)
# Generate RST for each model
for model_name, model_doc in self.models.items():
if model_doc.get("circular_ref"):
continue # Skip circular references
rst_content = self._format_model(model_name, model_doc)
rst_file = output_dir / f"{model_name.lower()}.rst"
with open(rst_file, "w", encoding="utf-8") as f:
f.write(rst_content)
print(f"Generated: {rst_file}")
# Define style generators mapping
style_generators = {
"simple": self._generate_index_simple,
"compact": self._generate_index_compact,
"dropdown": self._generate_index_dropdown,
"tabbed": self._generate_index_tabs,
"hybrid": self._generate_index_hybrid,
}
if mode == "preview":
# Preview mode: Generate navigation page with links to all styles
index_content = self._generate_preview_index()
index_file = output_dir / "index.rst"
with open(index_file, "w", encoding="utf-8") as f:
f.write(index_content)
print(f"Generated: {index_file} (preview navigation)")
# Generate all style variations
for style_name, generator_func in style_generators.items():
style_content = generator_func()
style_file = output_dir / f"index-{style_name}.rst"
with open(style_file, "w", encoding="utf-8") as f:
f.write(style_content)
print(f"Generated: {style_file}")
else:
# Production mode: Generate only the chosen style as main index
index_content = style_generators[style]()
index_file = output_dir / "index.rst"
with open(index_file, "w", encoding="utf-8") as f:
f.write(index_content)
print(f"Generated: {index_file} (production, style: {style})")
print(f"\nGenerated {len(self.models)} RST files + index in {output_dir}")
print(f"Total fields documented: {self.metadata.get('total_fields', 0)}")
def _format_model(self, model_name: str, model_doc: dict[str, Any]) -> str:
"""Format a single model as RST."""
lines = []
# Add meta tags
lines.extend(self._format_meta_tags(model_name, model_doc))
# Add reference label and index
lines.extend(self._format_reference_and_index(model_name))
# Add title
title = model_doc.get("title", model_name)
lines.append(title)
lines.append("=" * len(title))
lines.append("")
# Add description
description = model_doc.get("description", "")
if description:
lines.append(description)
lines.append("")
# Add parameters section
if model_doc.get("fields"):
lines.append("**Parameters:**")
lines.append("")
# Format each field
for field_doc in model_doc["fields"]:
lines.extend(self._format_field(field_doc, model_name))
lines.append("") # Blank line between fields
return "\n".join(lines)
@staticmethod
def _format_meta_tags(model_name: str, model_doc: dict[str, Any]) -> list[str]:
"""Format meta tags for SEO."""
title = model_doc.get("title", model_name)
return [
".. meta::",
f" :description: SUEWS YAML configuration for {title.lower()} parameters",
f" :keywords: SUEWS, YAML, {model_name.lower()}, parameters, configuration",
"",
]
@staticmethod
def _format_reference_and_index(model_name: str) -> list[str]:
"""Format reference label and index entries."""
return [
f".. _{model_name.lower()}:",
"",
".. index::",
f" single: {model_name} (YAML parameter)",
f" single: YAML; {model_name}",
"",
]
@staticmethod
def _add_field_index_entries(field_name: str, model_name: str) -> list[str]:
"""Add index entries for a field.
Args:
field_name: Name of the field
model_name: Name of the containing model
Returns
-------
List of RST lines for index entries
"""
lines = [
".. index::",
f" single: {field_name} (YAML parameter)",
f" single: {model_name}; {field_name}",
"",
]
# Add reference label for physics method fields with relationships
# These fields are cross-referenced in documentation describing physics
# method dependencies (e.g., "see netradiationmethod_" for SPARTACUS coupling)
# Note: diagmethod→rslmethod, localclimatemethod→rsllevel (legacy renames)
physics_anchor_fields = {
"netradiationmethod",
"emissionsmethod",
"storageheatmethod",
"ohmincqf",
"roughlenmommethod",
"roughlenheatmethod",
"stabilitymethod",
"rslmethod", # was diagmethod
"rsllevel", # was localclimatemethod
"gsmodel",
"snowuse",
"stebbsmethod",
"rcmethod",
}
if field_name in physics_anchor_fields:
lines.append(f".. _{field_name}:")
lines.append("")
return lines
@staticmethod
def _format_field_description(field_doc: dict[str, Any]) -> list[str]:
"""Format the description section of a field.
Args:
field_doc: Field documentation dictionary
Returns
-------
List of RST lines for the description
"""
lines = []
description = field_doc.get("description", "")
if description:
# Parse for method options if present
if field_doc.get("options") and "Options:" in description:
main_desc = description.split("Options:", 1)[0].strip()
lines.append(f" {main_desc}")
else:
lines.append(f" {description}")
lines.append("")
return lines
@staticmethod
def _format_ref_value_hint(
field_name: str, field_doc: dict[str, Any], type_info: dict[str, Any]
) -> list[str]:
"""Format YAML structure hint for RefValue types.
Args:
field_name: Name of the field
field_doc: Field documentation dictionary
type_info: Type information dictionary
Returns
-------
List of RST lines for RefValue hint
"""
if not type_info.get("is_ref_value"):
return []
lines = []
nested_model = field_doc.get("nested_model")
if nested_model:
lines.extend([
" In YAML, this is typically specified using a ``value`` key, e.g.: ",
f" ``{field_name}: {{value: ...}}``.",
" The structure of this ``value`` is detailed in the linked section below.",
"",
])
else:
type_str = field_doc.get("type", "...")
lines.extend([
" In YAML, this is typically specified using a ``value`` key, e.g.: ",
f" ``{field_name}: {{value: {type_str}}}``.",
"",
])
return lines
def _format_field_metadata(
self, field_doc: dict[str, Any], type_info: dict[str, Any], model_name: str = ""
) -> list[str]:
"""Format metadata sections (options, unit, default, constraints).
Args:
field_doc: Field documentation dictionary
type_info: Type information dictionary
model_name: Name of the containing model (for context)
Returns
-------
List of RST lines for metadata
"""
lines = []
# Add options if present
if field_doc.get("options"):
lines.append(" :Options:")
for opt in field_doc["options"]:
opt_str = self._format_option(opt)
lines.append(f" | {opt_str}")
lines.append("")
# Add unit (not for enum fields)
unit = field_doc.get("unit")
if unit and not field_doc.get("options"):
formatted_unit = self._format_unit(unit)
lines.append(f" :Unit: {formatted_unit}")
# Add default/sample value
default_label, default_value = self._format_default(field_doc, model_name)
if default_label is not None and default_value is not None:
lines.append(f" :{default_label}: {default_value}")
# Add default description if available
default_desc = field_doc.get("default_description")
if default_desc:
lines.append(f" :Default Description: {default_desc}")
# Add range description if available
range_desc = field_doc.get("range_description")
if range_desc:
lines.append(f" :Range Description: {range_desc}")
# Add reference field for RefValue types
if type_info.get("is_ref_value"):
lines.append(
" :Reference: Optional - provide DOI/citation in standard format"
)
# Add constraints
constraints = field_doc.get("constraints")
if constraints:
constraint_str = self._format_constraints(constraints)
if constraint_str:
lines.append(f" :Constraints: {constraint_str}")
# Add method relationships
relationships = field_doc.get("relationships")
if relationships:
lines.append("")
lines.append(" .. admonition:: Method Interactions")
lines.append(" :class: note")
lines.append("")
# Add note if present
note = relationships.get("note")
if note:
lines.append(f" {note}")
lines.append("")
# Add depends_on
depends = relationships.get("depends_on", [])
if depends:
refs = ", ".join(f":ref:`{d} <{d}>`" for d in depends)
lines.append(f" **Depends on:** {refs}")
lines.append("")
# Add provides_to
provides = relationships.get("provides_to", [])
if provides:
refs = ", ".join(f":ref:`{p} <{p}>`" for p in provides)
lines.append(f" **Provides to:** {refs}")
lines.append("")
return lines
def _format_field(self, field_doc: dict[str, Any], model_name: str) -> list[str]:
"""Format a single field as RST."""
lines = []
field_name = field_doc["name"]
type_info = field_doc.get("type_info", {})
# Add index entries
lines.extend(self._add_field_index_entries(field_name, model_name))
# Use yaml:option directive for YAML configuration options
lines.append(f".. yaml:option:: {field_name}")
lines.append("")
# Add description
lines.extend(self._format_field_description(field_doc))
# Handle RefValue types - add YAML structure hint
lines.extend(self._format_ref_value_hint(field_name, field_doc, type_info))
# Add metadata (options, unit, default, constraints)
lines.extend(self._format_field_metadata(field_doc, type_info, model_name))
# Add link to nested model documentation
nested_model = field_doc.get("nested_model")
if nested_model:
lines.append("")
lines.append(
self._format_nested_model_link(field_name, nested_model, type_info)
)
return lines
def _format_option(self, option: dict[str, Any]) -> str:
"""Format a single option."""
value = option["value"]
name = option["name"]
desc = option["description"]
# Apply formatting to description
desc = self._format_option_description(desc)
return f"``{value}`` ({name}) = {desc}"
@staticmethod
def _format_option_description(desc: str) -> str:
"""Format option description with markdown."""
replacements = [
("(recommended)", "**(recommended)**"),
("(not recommended)", "**(not recommended)**"),
("(experimental)", "**(experimental)**"),
]
for old, new in replacements:
if old in desc:
desc = desc.replace(old, new)
return desc
def _format_unit(self, unit: str) -> str:
"""Format units for RST display."""
if not unit:
return unit
# Convert to RST substitution format for proper rendering
unit = unit.replace("³", "^3").replace("²", "^2").replace("⁻", "^-")
# Handle division
if "/" in unit:
parts = unit.split("/")
if len(parts) == 2:
numerator = parts[0].strip()
denominator = parts[1].strip()
if "^" in denominator:
base, exp = denominator.split("^", 1)
denominator = f"{base}^-{exp}"
else:
denominator = f"{denominator}^-1"
numerator = self._process_unit_part(numerator)
denominator = self._process_unit_part(denominator)
return f"{numerator} {denominator}"
return self._process_unit_part(unit)
@staticmethod
def _process_unit_part(part: str) -> str:
"""Process a single unit part."""
known_patterns = [
"km^-1",
"mm^-1",
"m^-1",
"m^-2",
"m^-3",
"m^2",
"m^3",
"s^-1",
"kg^-1",
"K^-1",
"J^-1",
"W^-1",
"h^-1",
"day^-1",
"cap^-1",
"ha^-1",
"d^-1",
"d^-2",
]
if part in known_patterns:
return f"|{part}|"
# Handle compound units
words = part.split()
formatted = []
for word in words:
if word in known_patterns or (
"^" in word
and any(
word.startswith(b) for b in ["m", "s", "kg", "K", "W", "h", "d"]
)
):
formatted.append(f"|{word}|")
else:
formatted.append(word)
return " ".join(formatted)
@staticmethod
def _format_default(
field_doc: dict[str, Any], model_name: str = ""
) -> tuple[str, str]: # noqa: PLR0912
"""Format default value for display with consistent labeling.
Returns appropriate label-value pair based on field characteristics:
- Required fields: ("Status", "Required")
- Optional with defaults: ("Default", "value") or ("Example", "value")
- Optional without defaults: ("Default", "None (optional)")
- Nested models: (None, None) to skip display
Args:
field_doc: Field documentation dictionary
model_name: Name of the containing model (for context)
"""
nested_model = field_doc.get("nested_model")
# Skip nested models entirely - structure link is sufficient
if nested_model:
return None, None
# Get the field type to check if it's Optional
type_str = str(field_doc.get("type", ""))
is_optional = "Optional" in type_str or (
"Union[" in type_str and "None" in type_str
)
# Check for default value
default = field_doc.get("default")
# Check if this is PydanticUndefined - means it's required
if str(default) == "PydanticUndefined":
return "Status", "Required"
# Handle None defaults explicitly
if default is None:
# If the field is Optional (like Reference fields), show as optional
if is_optional:
return "Default", "None (optional)"
else:
# If not Optional but has None default, still show as optional
# (this handles cases where the model has default=None)
return "Default", "None (optional)"
# We have a non-None default value - format it
# Determine if this is a site/surface-specific model
# These models contain fields that vary by site or surface type
site_surface_models = {
"Site",
"SiteProperties",
"PavedProperties",
"BldgsProperties",
"EvetrProperties",
"DectrProperties",
"GrassProperties",
"BsoilProperties",
"WaterProperties",
}
is_site_specific = model_name in site_surface_models
# Format the value for display
if isinstance(default, (str, int, float, bool)):
if isinstance(default, str):
display_value = (
f"``'{default}'``" if default else "``''`` (empty string)"
)
else:
display_value = f"``{default}``"
elif isinstance(default, dict) and "value" in default:
# Enum default with name
display_value = f"``{default['value']}`` ({default.get('name', '')})"
elif isinstance(default, list):
# Format lists more readably
if len(default) <= 5:
display_value = f"``{default!r}``"
else:
# Truncate long lists
display_value = (
f"``[{default[0]!r}, {default[1]!r}, ..., {default[-1]!r}]``"
)
else:
# For complex defaults, try to represent them nicely
try:
display_value = f"``{json.dumps(default)}``"
except (TypeError, ValueError):
display_value = f"``{default}``"
# Choose appropriate label based on field type
if is_site_specific:
return "Example", display_value
else:
return "Default", display_value
@staticmethod
def _format_constraints(constraints: dict[str, Any]) -> str:
"""Format constraints for display."""
parts = []
# Numeric constraints
constraint_map = {
"gt": ">",
"ge": ">=",
"lt": "<",
"le": "<=",
"multiple_of": "Must be a multiple of",
"min_length": "Minimum length",
"max_length": "Maximum length",
"pattern": "Must match regex pattern",
}
for key, desc in constraint_map.items():
if key in constraints:
value = constraints[key]
parts.append(f"{desc}: ``{value!r}``")
# Allowed values
if "allowed_values" in constraints:
values = constraints["allowed_values"]
values_str = ", ".join(f"``{v!r}``" for v in values)
parts.append(f"Allowed values: {values_str}")
return "; ".join(parts)
@staticmethod
def _get_initial_state_message(
field_name: str, nested_model: str, nested_lower: str
) -> str:
"""Get message for initial state models."""
basic_states = {
"InitialStatePaved",
"InitialStateBldgs",
"InitialStateBsoil",
"InitialStateWater",
}
if nested_model in basic_states:
return (
f" For ``{field_name}``, one generic SurfaceInitialState object "
f"is used to specify initial conditions - "
f"see :doc:`surfaceinitialstate` for details."
)
return (
f" For ``{field_name}``, one vegetation-specific initial state "
f"with additional parameters is used - "
f"see :doc:`{nested_lower}` for details."
)
@staticmethod
def _format_nested_model_link(
field_name: str, nested_model: str, type_info: dict[str, Any]
) -> str:
"""Format link to nested model documentation."""
nested_lower = nested_model.lower()
# Build message based on type
message = ""
# Check type and build appropriate message
if type_info.get("is_ref_value"):
message = (
f" The structure for the ``value`` key of ``{field_name}`` "
f"is detailed in :doc:`{nested_lower}`."
)
elif type_info.get("is_list"):
if nested_model == "SurfaceInitialState":
message = (
f" For ``{field_name}``, a list of generic SurfaceInitialState "
f"objects is used to specify initial conditions for each layer - "
f"see :doc:`surfaceinitialstate` for details."
)
else:
message = (
f" Each item in the ``{field_name}`` list must conform to the "
f":doc:`{nested_lower}` structure."
)
elif type_info.get("is_dict"):
message = (
f" Each value in the ``{field_name}`` mapping must conform to the "
f":doc:`{nested_lower}` structure."
)
elif (
nested_model.startswith("InitialState") and nested_model != "InitialStates"
):
message = RSTGenerator._get_initial_state_message(
field_name, nested_model, nested_lower
)
else:
message = (
f" The ``{field_name}`` parameter group is defined by the "
f":doc:`{nested_lower}` structure."
)
return message
def _generate_index_dropdown(self) -> str:
"""Generate index.rst with collapsible dropdown sections (mixed approach)."""
lines = [
".. _yaml_config_reference:",
"",
"YAML Configuration Reference",
"============================",
"",
"This documentation follows the hierarchical structure of SUEWS YAML configuration files.",
"",
".. note::",
" Parameter groups with many fields are shown in collapsible dropdowns.",
" Click on the dropdown to expand and see the parameters.",
"",
]
# Build the hierarchical structure from the models
hierarchy = self._build_hierarchy()
# Choose display style (uncomment the one you want):
# Style 1: Simple nested list (all fields visible)
# self._generate_hierarchy_rst_simple(hierarchy, lines, level=0, max_level=5)
# Style 2: Mixed approach with collapsible sections for long groups (recommended)
self._generate_hierarchy_rst_collapsible(hierarchy, lines, level=0, max_level=5)
# Style 3: Aggressive collapse (most compact, everything >5 fields collapsed)
# self._generate_hierarchy_rst_aggressive_collapse(hierarchy, lines, level=0, max_level=5)
# Add toctree at the end with all documents (hidden)
lines.extend([
"",
".. toctree::",
" :hidden:",
" :maxdepth: 3",
"",
])
# Add all model files to toctree (excluding RefValue and Reference)
for model_name in sorted(self.models.keys()):
if model_name not in {"RefValue", "Reference"}:
lines.append(f" {model_name.lower()}")
return "\n".join(lines)
def _generate_index_simple(self) -> str:
"""Generate index.rst with simple nested list (all fields visible)."""
lines = [
".. _yaml_config_reference:",
"",
"YAML Configuration Reference (Simple Layout)",
"=============================================",
"",
"This documentation follows the hierarchical structure of SUEWS YAML configuration files.",
"",
]
# Build the hierarchical structure from the models
hierarchy = self._build_hierarchy()
# Simple nested list style
self._generate_hierarchy_rst_simple(hierarchy, lines, level=0, max_level=5)
# Add toctree at the end with all documents (hidden)
lines.extend([
"",
".. toctree::",
" :hidden:",
" :maxdepth: 3",
"",
])
# Add all model files to toctree (excluding RefValue and Reference)
for model_name in sorted(self.models.keys()):
if model_name not in {"RefValue", "Reference"}:
lines.append(f" {model_name.lower()}")
return "\n".join(lines)
def _generate_index_compact(self) -> str:
"""Generate index.rst with aggressive collapsing (most compact)."""
lines = [
".. _yaml_config_reference:",
"",
"YAML Configuration Reference (Compact Layout)",
"==============================================",
"",
"This documentation follows the hierarchical structure of SUEWS YAML configuration files.",
"",
]
# Build the hierarchical structure from the models
hierarchy = self._build_hierarchy()
# Aggressive collapse style
self._generate_hierarchy_rst_compact(hierarchy, lines, level=0, max_level=5)
# Add toctree at the end with all documents (hidden)
lines.extend([
"",
".. toctree::",
" :hidden:",
" :maxdepth: 3",
"",
])
# Add all model files to toctree (excluding RefValue and Reference)
for model_name in sorted(self.models.keys()):
if model_name not in {"RefValue", "Reference"}:
lines.append(f" {model_name.lower()}")
return "\n".join(lines)
def _generate_preview_index(self) -> str:
"""Generate preview navigation page with links to all style demos."""
lines = [
".. _yaml_config_reference_preview:",
"",
"YAML Configuration Reference - Style Preview",
"=============================================",
"",
"This preview page allows you to compare different documentation styles for the YAML configuration reference.",
"",
"Choose a style to preview:",
"",
".. grid:: 3",
" :gutter: 3",
"",
" .. grid-item-card:: Simple Layout",
" :link: index-simple",
" :link-type: doc",
"",
" All configuration fields visible in a nested list format.",
" Best for quick scanning and searching.",
"",
" .. grid-item-card:: Dropdown Layout",
" :link: index-dropdown",
" :link-type: doc",
"",
" Mixed approach with dropdown sections for long parameter groups.",
" Balances readability and compactness with interactive dropdowns.",
"",
" .. grid-item-card:: Compact Layout",
" :link: index-compact",
" :link-type: doc",
"",
" Aggressive collapsing for maximum compactness.",
" Everything with >5 fields is collapsed.",
"",
" .. grid-item-card:: Tabbed Layout",
" :link: index-tabbed",
" :link-type: doc",
"",
" Interactive tabbed interface for navigation.",
" Modern UI but requires JavaScript.",
"",
" .. grid-item-card:: Hybrid Layout",
" :link: index-hybrid",
" :link-type: doc",
"",
" **Recommended** - Tabs for major sections, dropdowns for details.",
" Best of both worlds: intuitive navigation with compact display.",
"",
".. note::",
" This is a preview mode. In production, only one style will be used.",
"",
".. toctree::",
" :hidden:",
" :maxdepth: 1",
"",
" index-simple",
" index-dropdown",
" index-compact",
" index-tabbed",
" index-hybrid",
"",
]
# Add all model files to hidden toctree
for model_name in sorted(self.models.keys()):
if model_name not in {"RefValue", "Reference"}:
lines.append(f" {model_name.lower()}")
return "\n".join(lines)
def _generate_index_tabs(self) -> str:
"""Generate index-tabs.rst with tabbed layout."""
lines = [
".. _yaml_config_reference_tabs:",
"",
"YAML Configuration Reference (Tabbed Layout)",
"=============================================",
"",
"This documentation follows the hierarchical structure of SUEWS YAML configuration files.",
"",
".. note::",
" Click on the tabs below to navigate through different configuration sections.",
"",
]
# Build the hierarchical structure from the models
hierarchy = self._build_hierarchy()
# Use the tabbed layout style
self._generate_hierarchy_rst_tabbed(hierarchy, lines, level=0, max_level=6)
# Add toctree at the end with all documents (hidden)
lines.extend([
"",
".. toctree::",
" :hidden:",
" :maxdepth: 3",
"",
])
# Add all model files to toctree (excluding RefValue and Reference)
for model_name in sorted(self.models.keys()):
if model_name not in {"RefValue", "Reference"}:
lines.append(f" {model_name.lower()}")
return "\n".join(lines)
def _generate_index_hybrid(self) -> str:
"""Generate index.rst with hybrid layout (tabs at top levels, dropdowns for deeper levels)."""
lines = [
".. _yaml_config_reference:",
"",
"YAML Configuration Reference",
"============================",
"",
"This documentation follows the hierarchical structure of SUEWS YAML configuration files.",
"",
".. note::",
" Navigate through configuration sections using the tabs below. ",
" Click on dropdowns to expand and see detailed parameters.",
"",
]
# Build the hierarchical structure from the models
hierarchy = self._build_hierarchy()
# Use the hybrid layout style - tabs for top 2 levels, dropdowns for rest
self._generate_hierarchy_rst_hybrid(
hierarchy, lines, level=0, tab_levels=3, max_level=6
)
# Add toctree at the end with all documents (hidden)
lines.extend([
"",
".. toctree::",
" :hidden:",
" :maxdepth: 3",
"",
])
# Add all model files to toctree (excluding RefValue and Reference)
for model_name in sorted(self.models.keys()):
if model_name not in {"RefValue", "Reference"}:
lines.append(f" {model_name.lower()}")
return "\n".join(lines)
def _build_hierarchy(self) -> dict:
"""Build hierarchical structure from model relationships."""
hierarchy = {}
# Start with SUEWSConfig as root
if "SUEWSConfig" in self.models:
# Get full model structure including simple fields
hierarchy["SUEWSConfig"] = self._get_model_children("SUEWSConfig", depth=0)
return hierarchy
def _get_model_children(self, model_name: str, depth: int = 0) -> dict:
"""Get children of a model based on its fields."""
if model_name not in self.models:
return {"title": model_name, "children": {}, "simple_fields": []}
model_data = self.models[model_name]
result = {
"title": model_data.get("title", model_name),
"model": model_name,
"children": {},
"simple_fields": [], # Add simple fields list
}
# Stop expanding at certain depth or for profile/utility types
profile_types = {"DayProfile", "HourlyProfile", "WeeklyProfile"}
utility_types = {"Reference", "RefValue"}
# Don't expand profile types or utility types or if we're too deep
if model_name in profile_types or model_name in utility_types or depth > 4:
return result
# Collect all fields - both nested models and simple fields
for field in model_data.get("fields", []):
field_name = field["name"]
nested_model = field.get("nested_model")
# Skip Reference and RefValue as they're utility types
if (
nested_model
and nested_model in self.models
and nested_model not in utility_types
):
# For profile types, just note the field name without expanding
if nested_model in profile_types:
# Add profile fields as simple fields instead
result["simple_fields"].append({
"name": field_name,
"type": nested_model,
"description": field.get("description", ""),
})
else:
# Use field name as key, get nested model structure
field_key = field_name
# For certain models with generic names, use field-specific titles
child_info = self._get_model_children(nested_model, depth + 1)