File size: 36,682 Bytes
e78e1d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82c9ec6
e78e1d4
 
cdfca12
 
e78e1d4
cdfca12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e78e1d4
 
cdfca12
 
e78e1d4
 
cdfca12
 
 
 
 
 
 
 
 
e78e1d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82c9ec6
e78e1d4
 
82c9ec6
e78e1d4
 
82c9ec6
e78e1d4
 
82c9ec6
e78e1d4
 
82c9ec6
e78e1d4
 
 
 
 
 
 
 
 
 
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
"""
sections.py
===========

All Streamlit UI page/section functions for the Building Acoustics Analysis
Tool.  No functional changes have been introduced.
"""
from __future__ import annotations

# ── third-party ────────────────────────────────────────────────────────────
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import streamlit as st

# ── local imports ───────────────────────────────────────────────────────────
from config import FREQUENCIES, MAJOR_TABS, TOTAL_DOTS
from helpers import (
    slugify,
    standardise_freq_cols,
    validate_numeric,
    read_upload,
    calc_abs_area,
    plot_rt_band,
    plot_bn_band,
    articulation_index,
)

# ────────────────────────────────────────────────────────────────────────────
# Navigation helpers (used by several sections)
# ────────────────────────────────────────────────────────────────────────────
def nav_to(tab: str) -> None:
    """Switch the major tab in session-state."""
    st.session_state.major_tab = tab


def nav_buttons() -> None:
    """Render ← / β†’ buttons with explicit section names."""
    idx = MAJOR_TABS.index(st.session_state.major_tab)
    c1, _, c3 = st.columns([2, 6, 2])
    if idx > 0:
        c1.button(f"← {MAJOR_TABS[idx-1]}", on_click=nav_to,
                  args=(MAJOR_TABS[idx-1],))
    if idx < len(MAJOR_TABS) - 1:
        c3.button(f"{MAJOR_TABS[idx+1]} β†’", on_click=nav_to,
                  args=(MAJOR_TABS[idx+1],))

# ────────────────────────────────────────────────────────────────────────────
# Individual sections (exact logic preserved)
# ────────────────────────────────────────────────────────────────────────────
def section_instructions() -> None:
    st.title("πŸ”Š Building Acoustics Analysis Tool")

    with st.expander("App Information", expanded=False):
        st.write("""
            - Welcome to the Building Acoustics Analysis Tool.
            - This app was developed to help Deakin University Construction Management students complete a building acoustics assignment in SRT757 Building Systems and Environment.
            - This app is intended for a retrofitting task and assumes that you have measured the current reverberation of the room to be assessed.
            - The app helps to analyze and modify room reverberation times to fall within standard ranges using the Sabine equation.
            - This app is intended for educational purposes only and should not be used for professional purposes.
            """)

    # Example DataFrames
    df_current_reverberation_times = pd.DataFrame({
        '125': [0.8], '250': [0.7], '500': [0.6],
        '1000': [0.5], '2000': [0.4], '4000': [0.3]
    })

    df_existing_materials = pd.DataFrame({
        'Material Name': ['Carpet', 'Curtain'],
        'Area_No': [50, 30],
        '125': [0.1, 0.2], '250': [0.15, 0.25], '500': [0.2, 0.3],
        '1000': [0.3, 0.35], '2000': [0.4, 0.45], '4000': [0.5, 0.55]
    })

    df_new_materials = pd.DataFrame({
        'Material Name': ['Acoustic Panel', 'Foam'],
        'Area_No': [40, 20],
        '125': [0.3, 0.25], '250': [0.35, 0.3], '500': [0.4, 0.35],
        '1000': [0.45, 0.4], '2000': [0.5, 0.45], '4000': [0.6, 0.55]
    })

    df_sound_pressure_levels = pd.DataFrame({
        'Location': ['Location 1', 'Location 2'],
        '125': [60, 62], '250': [58, 59], '500': [55, 56],
        '1000': [52, 53], '2000': [50, 51], '4000': [48, 49]
    })

    st.write("## Instructions")

    st.markdown("""
    Welcome to the **Building Acoustics Analysis Tool**. This educational application supports students in analyzing and improving room acoustics by addressing:
    - **Reverberation Time (RT60)**
    - **Background Noise**
    - **Speech Intelligibility (Articulation Index)**

    The tool is structured around Sabine's theory and common acoustic assessment standards, using six standard frequencies (125 Hz, 250 Hz, 500 Hz, 1000 Hz, 2000 Hz, and 4000 Hz). It is designed to help users diagnose and treat acoustic deficiencies by uploading and modifying material and noise-related inputs.

    ⚠️ **Note:** This tool is intended for educational purposes and should not be used for professional certification or compliance without additional verification.

    ### Reverberation Time (RT60)
    RT60 represents the time required for a sound to decay by 60 dB after the source stops. An optimal RT60 enhances clarity and acoustic comfort:
    - **Short RT60**: Suitable for classrooms, meeting rooms, and lecture halls.
    - **Longer RT60**: More acceptable in concert halls and religious buildings.

    #### RT60 Calculation – Sabine’s Equation
    **RT60 = (0.16 Γ— V) / A**

    Where:
    - `V` = Room volume (mΒ³)
    - `A` = Total absorption (mΒ² Sabins)

    **Example**:
    If a 100 mΒ³ room has total absorption of 10 mΒ²:
    **RT60 = (0.16 Γ— 100) / 10 = 1.60 seconds**

    ### Background Noise
    Background noise refers to ambient sound levels in a room, typically measured in **dBA**. Excessive background noise can mask speech and reduce communication effectiveness, even in acoustically treated rooms.

    The app allows users to enter measured **background noise levels** for one or more locations and compare them with recommended standard ranges. You can visualize these using bar plots and identify areas needing improvement.

    - **Sources**: HVAC systems, outside traffic, or adjacent room activities.
    - **Goal**: Maintain noise levels within acceptable limits (as defined by relevant standards).

    ### Speech Intelligibility
    Speech intelligibility is the measure of how clearly speech can be understood within a room. This tool uses the **Articulation Index (AI)** method:
    - Based on β€œDots Above a Curve” from sound pressure level data
    - User inputs number of audible speech "dots" above noise thresholds
    - AI is computed and interpreted (None, Fair, Good, Excellent)

    Higher AI scores suggest better speech transmission. This measure is particularly important in educational, healthcare, and public spaces.

    ### App Functionality
    The app guides users through six key stages:
    1. **Initial Data Entry** – Upload baseline acoustic data (RT60, materials, background noise, SPL).
    2. **Initial Compliance Checks** – Review current RT60, noise levels, and speech intelligibility.
    3. **Desired RT60** – Define preferred RT60 per frequency to guide treatment.
    4. **Acoustic Treatment** – Add new materials to adjust absorption.
    5. **Final Compliance Checks** – Evaluate impact on RT60, noise, and intelligibility.
    6. **FAQ / Help** – Access help content and export a summary report.

    ### Formatting Input Data

    ⚠️ **Use CSV or Excel, following the formats shown below without.**

    #### Current Reverberation Times
    - **Format**: One row, column headers = frequencies
    """)
    st.write(df_current_reverberation_times)

    st.markdown("""
    #### Existing Materials – Absorption Coefficients and Areas
    - **Format**: Material name, surface area, absorption coefficients
    """)
    st.write(df_existing_materials)

    st.markdown("""
    #### New Materials – Absorption Coefficients and Areas
    - **Format**: Same structure as existing materials
    """)
    st.write(df_new_materials)

    st.markdown("""
    #### Sound Pressure Levels (SPL)
    - **Format**: Location name in first column; SPLs at frequencies as columns
    """)
    st.write(df_sound_pressure_levels)

    st.markdown("""
    ### Navigation Summary

    - **Instructions** – You are here. Read all information before starting.
    - **Initial Data Entry** – Upload all your acoustic data. Room volume, RT60, background noise, and SPLs are required.
    - **Initial Compliance Checks** – Visualize current RT60, compare background noise with limits, and assess initial speech intelligibility.
    - **Desired RT60** – Define target reverberation levels per frequency. This guides treatment planning.
    - **Acoustic Treatment** – Upload and experiment with new materials to modify absorption and reduce noise.
    - **Final Compliance Checks** – Review the combined impact of old and new materials on RT60, noise, and speech clarity.

    ### General Tips
    - Keep filenames and headings clean and consistent.
    - Use the six standard frequencies.
    - Adjust materials iteratively to achieve compliance.
    - Download your report after completing all sections.

    For further clarification or examples, please consult the FAQ tab or contact your instructor.
    """)
    st.info("After reviewing the instructions, proceed to the **Initial Data Entry** tab.")

    nav_buttons()


# ---------------------------------------------------------------------------
def section_initial_data() -> None:
    st.title("πŸ”Š Building Acoustics Analysis Tool")

    with st.expander("App Information", expanded=False):
        st.write("""
            - This app is intended for educational purposes only and should not be used for professional purposes.
        """)
    
    st.header("πŸ“₯ Initial Data Entry")
    t_rt, t_bn, t_si = st.tabs(
        ["Reverberation Time", "Background Noise", "Speech Intelligibility"])

    # ── RT60 + materials ───────────────────────────────────────────────────
    with t_rt:

        st.write('''The primary objective here is to provide all the initial input data needed to 
        start RT60 analysis. See the 'Instructions' on the left for formatting information.''')

        c1, c2 = st.columns(2)
        u_rt = c1.file_uploader("Current RT60 data (CSV/XLSX)", type=["csv", "xlsx"])
        if u_rt:
            df = standardise_freq_cols(read_upload(u_rt))
            st.session_state.df_current_rt = df if validate_numeric(df) else None

        u_mat = c2.file_uploader("Existing materials (CSV/XLSX)",
                                 type=["csv", "xlsx"])
        if u_mat:
            dfm = standardise_freq_cols(read_upload(u_mat))
            st.session_state.df_existing_mat = (
                dfm if validate_numeric(dfm.iloc[:, 2:]) else None
            )

        st.session_state.room_volume = st.number_input(
            "Room volume [mΒ³]",
            value=st.session_state.room_volume,
            min_value=0.0,
            step=0.1,
        )

        # warnings
        if st.session_state.df_current_rt is None:
            st.warning("⚠️ Upload *Current RT60* data.")
        if st.session_state.df_existing_mat is None:
            st.warning("⚠️ Upload *Existing Materials* data.")
        if st.session_state.room_volume == 0:
            st.warning("⚠️ Enter a non-zero room volume.")

        if st.session_state.df_current_rt is not None:
            st.dataframe(st.session_state.df_current_rt, use_container_width=True)
        if st.session_state.df_existing_mat is not None:
            st.dataframe(st.session_state.df_existing_mat, use_container_width=True)

    # ── Background noise ───────────────────────────────────────────────────
    with t_bn:

        # ------------------------------------------------------------------
        # One‑time session‑level initialisation (runs only for a new session)
        # ------------------------------------------------------------------
        if "df_background_noise" not in st.session_state:
            st.session_state.df_background_noise = pd.DataFrame(
                columns=["Location", "dBA"]
            )
        if "bn_input_loc" not in st.session_state:
            st.session_state.bn_input_loc = ""
        if "bn_input_val" not in st.session_state:
            st.session_state.bn_input_val = 0.0
    
        st.write(
            """The primary objective here is to provide the initial input data needed to
            start background noise analysis. See the 'Instructions' on the left for
            formatting information."""
        )
    
        c1, c2, c3 = st.columns([3, 2, 1])
        st.session_state.bn_input_loc = c1.text_input(
            "Location", st.session_state.bn_input_loc
        )
        st.session_state.bn_input_val = c2.number_input(
            "dBA", value=st.session_state.bn_input_val, min_value=0.0, step=0.1
        )
    
        if c3.button("Add / Update"):
            loc = st.session_state.bn_input_loc.strip()
            if loc:
                # work on an isolated copy to avoid cross‑session persistence
                df = st.session_state.df_background_noise.copy()
    
                if loc in df["Location"].values:
                    df.loc[df["Location"] == loc, "dBA"] = st.session_state.bn_input_val
                else:
                    df.loc[len(df)] = [loc, st.session_state.bn_input_val]
    
                # store the modified copy back into session_state
                st.session_state.df_background_noise = df
    
        if st.session_state.df_background_noise.empty:
            st.warning("⚠️ Enter at least one background‑noise measurement.")
    
        st.dataframe(
            st.session_state.df_background_noise, use_container_width=True
        )

    # ── SPL upload ─────────────────────────────────────────────────────────
    with t_si:

        st.write('''The primary objective here is to provide the initial input data needed to 
        start speech intelligibility analysis. See the 'Instructions' on the left for 
        formatting information''')
        
        u = st.file_uploader("Current sound pressure level data (CSV/XLSX)", type=["csv", "xlsx"])
        if u:
            df = standardise_freq_cols(read_upload(u, header=0, index_col=0))
            df.columns = [int(c) for c in df.columns]
            st.session_state.df_spl = (
                df if set(df.columns) >= set(FREQUENCIES) else None
            )
            # reset AI dicts on new upload
            st.session_state.dots_init_dict, st.session_state.ai_init_dict = {}, {}
            st.session_state.dots_final_dict, st.session_state.ai_final_dict = {}, {}

        if st.session_state.df_spl is None:
            st.warning("⚠️ Upload *SPL* data with columns 125–4000 Hz.")
        else:
            st.dataframe(st.session_state.df_spl, use_container_width=True)

    nav_buttons()


# ---------------------------------------------------------------------------
def section_initial_checks() -> None:
    st.title("πŸ”Š Building Acoustics Analysis Tool")

    with st.expander("App Information", expanded=False):
        st.write("""
            - This app is intended for educational purposes only and should not be used for professional purposes.
        """)
    
    st.header("βœ… Initial Compliance Checks")
    st.write("""The purpose of initial complaince checks to verify if the acoustic properties
    of the space complies with standards. If the space complies, acoustic treatment may not
    be required. """)
    t_rt, t_bn, t_si = st.tabs(
        ["Reverberation Time", "Background Noise", "Speech Intelligibility"])

    # early global warnings
    if (st.session_state.df_current_rt is None or
            st.session_state.df_existing_mat is None):
        st.warning("⚠️ Current RT60 and/or Materials data missing "
                   "(see *Initial Data Entry*).")
    if st.session_state.df_background_noise.empty:
        st.warning("⚠️ Background-noise data missing "
                   "(see *Initial Data Entry*).")
    if st.session_state.df_spl is None:
        st.warning("⚠️ Sound pressure level (SPL) data missing (see *Initial Data Entry*).")

    # ── RT60 check ─────────────────────────────────────────────────────────
    with t_rt:
        st.write("""Privide the min and max standard RT60 for your space type to complete 
        initial RT60 compliance check.""")
        c1, c2 = st.columns(2)
        st.session_state.rt_min = c1.number_input(
            "Min standard RT60 [s]", value=st.session_state.rt_min, min_value=0.0, step=0.01)
        st.session_state.rt_max = c2.number_input(
            "Max standard RT60 [s]", value=st.session_state.rt_max, min_value=0.0, step=0.01)

        if st.session_state.rt_max <= st.session_state.rt_min:
            st.warning("⚠️ Max RT60 must be greater than Min RT60.")

        if st.session_state.df_existing_mat is not None:
            @st.cache_data(show_spinner=False)
            def _abs(df):
                acc = {f: 0.0 for f in FREQUENCIES}
                for _, r in df.iterrows():
                    area = r[1]
                    for f, coeff in zip(FREQUENCIES, r[2:]):
                        acc[f] += coeff * area
                return acc

            st.markdown("""###### Sound absorption based initial matrials""")
            st.session_state.current_absorption = _abs(
                st.session_state.df_existing_mat)
            st.dataframe(pd.DataFrame([st.session_state.current_absorption]),
                         use_container_width=True)

        if (st.session_state.df_current_rt is not None and
                st.session_state.rt_max > st.session_state.rt_min):
            y_cur = [float(st.session_state.df_current_rt.iloc[0][f])
                     for f in FREQUENCIES]
            fig = plot_rt_band(
                y_cur,
                [st.session_state.rt_min]*6,
                [st.session_state.rt_max]*6,
                "Initial RT60 vs Standard RT60 Range",
            )
            st.plotly_chart(fig, use_container_width=True)
            st.session_state.fig_rt_initial = fig

    # ── Background noise check ─────────────────────────────────────────────
    with t_bn:
        st.write("""Provide the min and max standard background noise for your space type to
        complete complaince check.""")
        c1, c2 = st.columns(2)
        st.session_state.bn_min = c1.number_input(
            "Min standard background noise [dBA]", value=st.session_state.bn_min, min_value=0.0, step=0.1)
        st.session_state.bn_max = c2.number_input(
            "Max standard background noise [dBA]", value=st.session_state.bn_max, min_value=0.0, step=0.1)

        if st.session_state.bn_max <= st.session_state.bn_min:
            st.warning("⚠️ Max background noise must be greater than Min background noise.")

        df = st.session_state.df_background_noise
        if (not df.empty and st.session_state.bn_max > st.session_state.bn_min):
            fig = plot_bn_band(
                df["Location"], df["dBA"],
                st.session_state.bn_min, st.session_state.bn_max,
                "Initial Background Noise vs Standard Background Noise Range",
            )
            st.plotly_chart(fig, use_container_width=True)
            st.session_state.fig_bn_initial = fig

    # ── Speech-intelligibility check ───────────────────────────────────────
    with t_si:
        col_text, col_img = st.columns([3,2])
        with col_text:
            st.write("""Manually plot the sound pressure values below on the dots graph 
            (see Fig 1) and count the dots above the line for 
            articluation index calculation below. You must plot a dot graph for each 
            location in the sound pressure levels table below.""")

            if st.session_state.df_spl is not None:
                st.markdown("###### current sound pressure levels")
                st.dataframe(st.session_state.df_spl, use_container_width=True)

        with col_img:
            st.image("dots_graph2.jpg", caption="Fig 1: Dots graph",
             use_column_width=False)

        if st.session_state.df_spl is not None:
            # st.markdown("###### current sound pressure levels")
            # st.dataframe(st.session_state.df_spl, use_container_width=True)
            ai_rows = []
            st.markdown("###### Articulation Index (AI) calculation")
            for loc in st.session_state.df_spl.index:
                key = slugify(f"dots_init_{loc}")
                default = st.session_state.dots_init_dict.get(loc, 0)
                dots = st.number_input(
                    f"Dots above ({loc})", 0, TOTAL_DOTS,
                    step=1, value=default, key=key)
                st.session_state.dots_init_dict[loc] = dots
                ai, interp = articulation_index(dots) if dots else (None, "")
                st.session_state.ai_init_dict[loc] = (ai, interp)
                ai_rows.append({
                    "Location": loc,
                    "Articulation Index (AI)": f"{ai:.2f}" if ai is not None else "",
                    "Interpretation": interp,
                })
            st.dataframe(pd.DataFrame(ai_rows), use_container_width=True)

    nav_buttons()

# ---------------------------------------------------------------------------
def section_acoustic_treatment() -> None:
    st.title("πŸ”Š Building Acoustics Analysis Tool")

    with st.expander("App Information", expanded=False):
        st.write("""
            - This app is intended for educational purposes only and should not be used for professional purposes.
        """)
    
    st.header("πŸ›  Acoustic Treatment")
    tab_desired, tab_mat = st.tabs(["Desired RT60", "New Materials"])

    # ── Desired RT60 entry ─────────────────────────────────────────────────
    with tab_desired:

        st.write('''At this point in the analysis, you would need to define your desired RT60, 
        which would be used to calculate the desired sound absorption needed to achieve the 
        desired RT60. Compare the total frequency values in the table below to the calculated current
        room sound absorption on the Initial RT60 Compliance Check tab to inform your selection 
        of new materials in the next step of the analysis''')

        if st.session_state.rt_max == 0:
            st.warning("⚠️ Define RT60 standard range in *Initial Compliance Checks* first.")

        st.info("Enter the desired RT60 for each frequency.")
        desired = {}
        for freq in FREQUENCIES:
            default = float(
                st.session_state.desired_rt_df[
                    st.session_state.desired_rt_df["Frequency"] == freq
                ]["Desired RT60"].values[0]
            )
            val = st.number_input(
                f"{freq} Hz", min_value=0.01, step=0.01,
                value=default, key=f"des_rt_{freq}")
            desired[freq] = val

        st.session_state.desired_rt_df["Desired RT60"] = (
            st.session_state.desired_rt_df["Frequency"].map(desired)
        )

        within = all(
            st.session_state.rt_min <= v <= st.session_state.rt_max
            for v in desired.values()
        )
        if within:
            df_abs = pd.DataFrame([{
                f: calc_abs_area(st.session_state.room_volume, v)
                for f, v in desired.items()
            }], index=["Required absorption"])
            st.markdown("###### Sound absorption based on Desired RT60")
            st.dataframe(df_abs, use_container_width=True)
        else:
            st.error("Each Desired RT60 must lie within the standard range.")

        if st.session_state.room_volume == 0:
            st.warning("⚠️ Enter a non-zero room volume (see *Initial Data Entry*).")

    # ── New materials ──────────────────────────────────────────────────────
    with tab_mat:

        st.write("""The desired sound absorption calculated on the Desired RT60 tab is the target
        sound absorption you are aiming to achieve. You now have to start working towards achieving
        the target absorptions. Based on the differences between the desired sound absorptions 
        (see Desired RT60 tab) and the calculated current room sound absorptions 
        (see Initial RT60 Compliance Check tab), you would need to introduce new materials to either
        increase or decrease sound absorption for some frequencies. Note that sound absorption 
        coefficients of a material are not the same for all frequencies. Therefore, you need to 
        strategically select your materials. You may need to repeat the material selection process
        several times to ensure that the room passes the final RT60 compliance check. 
        Your project brief may place limitations on the number of structural changes 
        (like changing the wall or concrete floor) you are allowed to make. For a retrofit project, 
        you can change non-structural elements like carpet and ceiling tiles. Additionally, you 
        can introduce new materials like curtains.
        """)

        
        u = st.file_uploader("New materials data (CSV/XLSX)", type=["csv", "xlsx"])
        if u:
            st.session_state.df_new_mat = standardise_freq_cols(read_upload(u))

        if st.session_state.df_new_mat is None:
            st.warning("⚠️ Upload or add at least one new material.")
        else:
            st.info("""You can add or delete rows and modify the values in the table below. 
            Changes will be applied and will instantly impact sound absorption
            and Final Compliance Checks.""")
            
            df_edit = st.data_editor(
                st.session_state.df_new_mat, num_rows="dynamic",
                use_container_width=True, key="edit_newmat")
            st.session_state.df_new_mat = df_edit

            new_abs = {f: 0.0 for f in FREQUENCIES}
            for _, r in df_edit.iterrows():
                area = r[1]
                for f, coeff in zip(FREQUENCIES, r[2:]):
                    new_abs[f] += coeff * area
            st.session_state.new_absorption = new_abs
            st.markdown("###### Sound absorption based on new materials")
            st.dataframe(pd.DataFrame([new_abs], index=["New absorption"]),
                         use_container_width=True)

    nav_buttons()


# ---------------------------------------------------------------------------
def section_final_checks() -> None:
    st.title("πŸ”Š Building Acoustics Analysis Tool")

    with st.expander("App Information", expanded=False):
        st.write("""
            - This app is intended for educational purposes only and should not be used for professional purposes.
        """)
    
    st.header("🚦 Final Compliance Checks")
    t_rt, t_bn, t_si = st.tabs(
        ["Reverberation Time", "Background Noise", "Speech Intelligibility"])

    combined = {
        f: st.session_state.current_absorption.get(f, 0)
           + st.session_state.new_absorption.get(f, 0)
        for f in FREQUENCIES
    }

    
    # ── RT60 final check ───────────────────────────────────────────────────
    with t_rt:
        if st.session_state.room_volume == 0 or not st.session_state.new_absorption:
            st.warning("⚠️ Provide room volume and at least one new material, then run Acoustic Treatment.")
        else:
            # --------------------------------------------------------------
            # Use *only* the absorption contributed by the new materials
            # (st.session_state.new_absorption) for Sabine RT60 calculation
            # --------------------------------------------------------------
            new_rt = {
                f: (0.16 * st.session_state.room_volume / a) if a > 0 else float("inf")
                for f, a in st.session_state.new_absorption.items()
            }
    
            st.markdown("New RT60 values after acoustic treatment (based on new materials only)")
            st.dataframe(
                pd.DataFrame([new_rt], index=["New RT60"]), use_container_width=True
            )
    
            # Plot current vs standard band vs new RT60
            y_cur = (
                [float(st.session_state.df_current_rt.iloc[0][f]) for f in FREQUENCIES]
                if st.session_state.df_current_rt is not None
                else [None] * 6
            )
    
            fig = plot_rt_band(
                y_cur,
                [st.session_state.rt_min] * 6,
                [st.session_state.rt_max] * 6,
                "Final RT60 vs Standard Range",
            )
            fig.add_trace(
                go.Scatter(
                    x=FREQUENCIES,
                    y=[new_rt[f] for f in FREQUENCIES],
                    mode="lines+markers",
                    name="New",
                    marker_color="#d62728",
                )
            )
            st.plotly_chart(fig, use_container_width=True)
            st.session_state.fig_rt_final = fig

    # ── Background noise final check ───────────────────────────────────────
    with t_bn:
        st.write("""When you apply acoustic treatment to a room, the noise reduction 
        resulting from increased sound absorption will deacrease background noise.""")
        df = st.session_state.df_background_noise
        if df.empty or not combined:
            st.warning("⚠️ Provide background-noise data and run Acoustic Treatment.")
        else:
            before = sum(st.session_state.current_absorption.values())
            after = sum(combined.values())
            if before == 0:
                st.error("Existing absorption sum is zero.")
            else:
                nr = 10 * np.log10(after / before)
                st.metric("Noise Reduction", f"{nr:.2f} dB", 
                help="Noise reduction due to acoustic treatment" )
                df_new = df.copy()
                df_new["dBA"] = df_new["dBA"] - nr
                fig = plot_bn_band(
                    df_new["Location"], df_new["dBA"],
                    st.session_state.bn_min, st.session_state.bn_max,
                    "Final Background Noise vs Standard Range",
                )
                st.plotly_chart(fig, use_container_width=True)
                st.session_state.fig_bn_final = fig

    # ── AI final check ─────────────────────────────────────────────────────-
    with t_si:
        st.write("""When you apply acoustic treatment to a room, the noise reduction 
        resulting from increased sound absorption will deacrease the sound pressure
        levels used in calcuating AI""")
        if st.session_state.df_spl is None or not combined:
            st.warning("⚠️ Upload SPL data and run Acoustic Treatment first.")
        else:
            before = sum(st.session_state.current_absorption.values())
            after = sum(combined.values())
            nr_db = 10 * np.log10(after / before) if before else 0
            df_new_spl = st.session_state.df_spl - nr_db
            st.markdown("###### New sound pressure levels after acoustic treatment")
            st.write("""For each location in the table below, plot the new sound pressure
            levels on the dots graph, count dots above the line, and calculate AI below.""")
            st.dataframe(df_new_spl, use_container_width=True)

            st.markdown("Articulation Index (AI) calculation")
            ai_rows = []
            for loc in df_new_spl.index:
                key = slugify(f"dots_final_{loc}")
                default = st.session_state.dots_final_dict.get(loc, 0)
                dots = st.number_input(
                    f"Dots above ({loc})", 0, TOTAL_DOTS,
                    step=1, value=default, key=key)
                st.session_state.dots_final_dict[loc] = dots
                ai, interp = articulation_index(dots) if dots else (None, "")
                st.session_state.ai_final_dict[loc] = (ai, interp)
                ai_rows.append({
                    "Location": loc,
                    "AI": f"{ai:.2f}" if ai is not None else "",
                    "Interpretation": interp,
                })
            st.dataframe(pd.DataFrame(ai_rows), use_container_width=True)

    nav_buttons()


# ---------------------------------------------------------------------------
def section_faq() -> None:
    st.title("πŸ”Š Building Acoustics Analysis Tool")

    with st.expander("App Information", expanded=False):
        st.write("""
            - This app is intended for educational purposes only and should not be used for professional purposes.
        """)
    
    st.header("❓ FAQ / Help")
    faq_content = """
    ### Frequently Asked Questions
    **Q1: What should I do if the data upload fails?**
    Ensure your file is in the correct format (CSV or Excel). Check that the column headings are consistent with the expected format (e.g., `125`, `250`, `500`, `1000`, `2000`, `4000` or `125Hz`, `250Hz`, `500Hz`, `1KHz`, `2KHz`, `4KHz`). Remove any extra rows or columns that do not contain relevant data.
    
    **Q2: How do I interpret the RT60 values?**
    RT60 values represent the time it takes for the sound to decay by 60 dB in a room. Lower RT60 values indicate faster sound decay and are preferable for environments where speech intelligibility is important. Higher RT60 values might be suitable for spaces intended for musical performances.
    
    **Q3: Why is my calculated RT60 not within the standard range?**
    This may occur if the room's current materials are not adequately absorbing sound. You may need to introduce new materials with higher absorption coefficients or increase the surface area of existing materials.
    
    **Q4: What should I do if the app does not accept my frequency columns?**
    The app standardizes frequency columns to numerical values (e.g., `125`, `250`) regardless of their initial format (e.g., `125Hz`, `125 Hz`). Ensure that the frequency values in your uploaded file are correctly formatted and consistent.
    
    **Q5: How can I improve speech intelligibility in my room?**
    To improve speech intelligibility, aim for a lower RT60 across the relevant frequencies, particularly in the range of 500 Hz to 4000 Hz. This can be achieved by adding more sound-absorbing materials, such as acoustic panels or curtains.
    
    **Q6: How can I save my analysis results?**
    You can download the PDF report, which includes all the data and graphs from your analysis. Click the "Download PDF Report" button at the end of your analysis to save the report to your device.
    ### Troubleshooting Tips
    - **Data Upload Issues**: If you encounter issues uploading data, double-check the format and structure of your file. Ensure the first row contains column headings and the data is organized as per the examples provided.
    - **Unexpected Results**: If your analysis results seem incorrect, verify the accuracy of the input data, including the room volume and material properties. Incorrect input data can lead to erroneous calculations.
    - **App Performance**: If the app is running slowly, consider optimizing your data size and complexity. Large datasets or highly detailed input may impact performance.
    
    """
    st.markdown(faq_content)
    nav_buttons()