sadickam commited on
Commit
5192a72
·
verified ·
1 Parent(s): eac20f2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +855 -823
app.py CHANGED
@@ -1,823 +1,855 @@
1
- import streamlit as st
2
- import pandas as pd
3
- import plotly.graph_objects as go
4
- from fpdf import FPDF
5
- import tempfile
6
- import kaleido
7
- import numpy as np
8
-
9
- # Set page configuration
10
- st.set_page_config(
11
- #page_title="Building Acoustics Analysis Tool",
12
- page_icon="🏫",
13
- initial_sidebar_state="expanded"
14
- )
15
-
16
- # Title and instructional information
17
- st.title("🔊:blue[Building Acoustics Analysis (RT60)]")
18
-
19
- with st.expander("App Information", expanded=False):
20
- st.write("""
21
- - Welcome to the Building Acoustics Analysis Tool.
22
- - This app was developed to help Deakin University Construction Management students complete building acoustics a assignment in SRT757 Building Systems and Environment.
23
- - This app is intended for a retrofitting task and assumes that you have measured the current reverberation of the room to be assessed.
24
- - The app helps to analyze and modify room reverberation times to fall within standard ranges using Sabine equation.
25
-
26
- - This app is for educational purposes and not intended for professional use.
27
- """)
28
-
29
- default_values = {
30
- 'current_tab': "Instructions",
31
- 'current_rt': {},
32
- 'frequencies': [],
33
- 'existing_materials': [],
34
- 'volume': 0.0,
35
- 'desired_rt': {},
36
- 'new_materials': [],
37
- 'df_current_rt': None,
38
- 'df_existing_materials': None,
39
- 'df_new_materials': None,
40
- 'min_rt_val': 0.0,
41
- 'max_rt_val': 0.0,
42
- 'new_absorption': {},
43
- 'fig1': None,
44
- 'fig2': None, # Ensure fig2 is initialized
45
- 'df_sound_pressure': None,
46
- 'noise_reduction': None,
47
- 'df_current_absorption': None,
48
- 'df_new_absorption': None
49
- }
50
-
51
- for key, value in default_values.items():
52
- if key not in st.session_state:
53
- st.session_state[key] = value
54
-
55
-
56
- # Helper functions
57
- def calculate_absorption_area(volume, reverberation_time):
58
- return 0.161 * volume / reverberation_time if reverberation_time else float('inf')
59
-
60
- def generate_pdf(volume, current_rt, existing_materials, min_rt, max_rt, desired_rt, new_materials, fig1, fig2, df_sound_pressure, updated_df):
61
- from fpdf import FPDF
62
- import tempfile
63
- import kaleido
64
-
65
- pdf = FPDF()
66
- pdf.add_page()
67
- pdf.set_font("Arial", size=12)
68
- pdf.cell(200, 10, txt="Room Acoustics Analysis Report", ln=True, align="C")
69
- pdf.cell(200, 10, txt=f"Room Volume: {volume:.2f} m³", ln=True)
70
-
71
- pdf.cell(200, 10, txt="Current Reverberation Times (s):", ln=True)
72
- for freq, rt in current_rt.items():
73
- pdf.cell(200, 10, txt=f"{freq} Hz: {rt:.2f}", ln=True)
74
-
75
- pdf.cell(200, 10, txt="Existing Materials and Absorption Coefficients:", ln=True)
76
- for material in existing_materials:
77
- pdf.cell(200, 10, txt=f"Material: {material['name']}, Area: {material['area']:.2f} m²", ln=True)
78
- for freq, coeff in material['coefficients'].items():
79
- pdf.cell(200, 10, txt=f"{freq} Hz: {coeff:.2f}", ln=True)
80
-
81
- pdf.cell(200, 10, txt="Standard Reverberation Time Range (s):", ln=True)
82
- for freq in min_rt.keys():
83
- pdf.cell(200, 10, txt=f"{freq} Hz: {min_rt[freq]:.2f} - {max_rt[freq]:.2f}", ln=True)
84
-
85
- pdf.cell(200, 10, txt="Desired Reverberation Times (s):", ln=True)
86
- for freq, rt in desired_rt.items():
87
- pdf.cell(200, 10, txt=f"{freq} Hz: {rt:.2f}", ln=True)
88
-
89
- pdf.cell(200, 10, txt="New Materials and Absorption Coefficients:", ln=True)
90
- for material in new_materials:
91
- pdf.cell(200, 10, txt=f"Material: {material['name']}, Area: {material['area']:.2f} m²", ln=True)
92
- for freq, coeff in material['coefficients'].items():
93
- pdf.cell(200, 10, txt=f"{freq} Hz: {coeff:.2f}", ln=True)
94
-
95
- # Save the figures as temporary files and add to the PDF
96
- for fig, tmpfile in [(fig1, "fig1.png"), (fig2, "fig2.png")]:
97
- with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmpfile:
98
- fig.write_image(tmpfile.name, engine='kaleido')
99
- pdf.image(tmpfile.name, x=10, y=None, w=180)
100
-
101
- # Add sound pressure levels data
102
- pdf.add_page()
103
- pdf.cell(200, 10, txt="Current Sound Pressure Levels (dB):", ln=True)
104
- for index, row in df_sound_pressure.iterrows():
105
- pdf.cell(200, 10, txt=f"{index}:", ln=True)
106
- for col in df_sound_pressure.columns:
107
- pdf.cell(200, 10, txt=f"{col} Hz: {row[col]:.2f}", ln=True)
108
-
109
- # Add updated sound pressure levels data
110
- pdf.cell(200, 10, txt="Updated Sound Pressure Levels (dB):", ln=True)
111
- for index, row in updated_df.iterrows():
112
- pdf.cell(200, 10, txt=f"{index}:", ln=True)
113
- for col in updated_df.columns:
114
- pdf.cell(200, 10, txt=f"{col} Hz: {row[col]:.2f}", ln=True)
115
-
116
- return pdf.output(dest='S').encode('latin1')
117
-
118
-
119
- def read_uploaded_file(uploaded_file, header=0, index_col=None):
120
- try:
121
- if uploaded_file.name.endswith('.csv'):
122
- return pd.read_csv(uploaded_file, header=header, index_col=index_col)
123
- elif uploaded_file.name.endswith('.xlsx'):
124
- return pd.read_excel(uploaded_file, header=header, index_col=index_col)
125
- except Exception as e:
126
- st.error(f"Error reading file {uploaded_file.name}: {e}")
127
-
128
- # Layout customizations
129
- hide_menu_style = """
130
- <style>
131
- #MainMenu {visibility: hidden;}
132
- footer {visibility: hidden;}
133
- </style>
134
- """
135
- st.markdown(hide_menu_style, unsafe_allow_html=True)
136
-
137
- # Sidebar with navigation
138
- def switch_tab(tab_name):
139
- st.session_state.current_tab = tab_name
140
-
141
- with st.sidebar:
142
- for tab in ["Instructions", "Initial Data Entry", "Initial RT60 Compliance Check", "Desired RT60",
143
- "Acoustic Treatment", "Final RT60 Compliance Check", "Intelligibility Noise Reduction"]:
144
- st.button(tab, on_click=switch_tab, args=(tab,))
145
-
146
- # # Display content based on selected tab in the main window
147
- # st.title("Building Acoustics Analysis Tool")
148
- # st.header(st.session_state.current_tab)
149
-
150
- def display_instructions():
151
- import pandas as pd
152
-
153
- # Example DataFrames for input data
154
- df_current_reverberation_times = pd.DataFrame({
155
- '125': [0.8],
156
- '250': [0.7],
157
- '500': [0.6],
158
- '1000': [0.5],
159
- '2000': [0.4],
160
- '4000': [0.3]
161
- })
162
-
163
- df_existing_materials = pd.DataFrame({
164
- 'Material Name': ['Carpet', 'Curtain'],
165
- 'Area_No': [50, 30],
166
- '125Hz': [0.1, 0.2],
167
- '250Hz': [0.15, 0.25],
168
- '500Hz': [0.2, 0.3],
169
- '1KHz': [0.3, 0.35],
170
- '2KHz': [0.4, 0.45],
171
- '4KHz': [0.5, 0.55]
172
- })
173
-
174
- df_new_materials = pd.DataFrame({
175
- 'Material Name': ['Acoustic Panel', 'Foam'],
176
- 'Area_No': [40, 20],
177
- '125Hz': [0.3, 0.25],
178
- '250Hz': [0.35, 0.3],
179
- '500Hz': [0.4, 0.35],
180
- '1KHz': [0.45, 0.4],
181
- '2KHz': [0.5, 0.45],
182
- '4KHz': [0.6, 0.55]
183
- })
184
-
185
- df_sound_pressure_levels = pd.DataFrame({
186
- 'Location': ['Location 1', 'Location 2'],
187
- '125': [60, 62],
188
- '250': [58, 59],
189
- '500': [55, 56],
190
- '1000': [52, 53],
191
- '2000': [50, 51],
192
- '4000': [48, 49]
193
- })
194
-
195
- st.write('## Instructions')
196
-
197
- instructions = """
198
-
199
- ## Introduction
200
-
201
- Welcome to the Building Acoustics Analysis Tool. This application is designed to help you analyze the resolve
202
- reverberation time (RT60) issues and calculate noise reduction for resolving speech intelligibility of a room. The
203
- analysis leverages Sabine's equation for reverberation time analysis, which is crucial in determining the acoustic
204
- characteristics of a space.
205
-
206
- Please note that the app focuses on specific frequencies: 125 Hz, 250 Hz, 500 Hz, 1000 Hz, 2000 Hz, and 4000 Hz.
207
- These frequencies are standard in acoustics analysis and will be the basis for all calculations and visualizations.
208
-
209
- If you need to analyze multiple rooms, you will need to repeat the analysis for each room individually. This tool
210
- assumes you have measured RT60 values for one location within the room and sound pressure levels for one or more
211
- locations within the room.
212
-
213
- This app is for educational purposes and not intended for professional use.
214
-
215
- ## App Functionality
216
-
217
- The Building Acoustics Analysis Tool provides the following functionalities:
218
-
219
- 1. **Initial Data Entry**: Upload and review initial acoustic data, including current reverberation times and existing materials.
220
- 2. **Initial RT60 Compliance Check**: Compare current RT60 values against standard ranges to determine compliance.
221
- 3. **Desired RT60**: Set desired RT60 values and calculate the required sound absorption to achieve these values.
222
- 4. **Acoustic Treatment**: Introduce new materials and calculate their impact on the room's acoustics.
223
- 5. **Final RT60 Compliance Check**: Verify that the new RT60 values are within the desired range after acoustic treatment.
224
- 6. **Intelligibility Noise Reduction**: Analyze noise reduction and its impact on sound pressure levels in the room.
225
-
226
- ## Instructions for Formatting Input Data
227
-
228
- Please note that the number 0, 1, 2, .... in the first column of the examples below are similar to the default
229
- Excel line numbers. Therefore, DO NOT number the first columns of your data files.
230
-
231
- ### Current Reverberation Times
232
-
233
- - **File Format**: `current_reverberation_times.csv` or `current_reverberation_times.xlsx`
234
- - **Data Format**: The first row should contain the frequency values as column headings, and the second row should contain the reverberation times corresponding to each frequency.
235
-
236
- **Example:**
237
-
238
- """
239
-
240
- st.markdown(instructions)
241
- st.write(df_current_reverberation_times)
242
-
243
- instructions = """
244
- ### Existing Materials Absorption Coefficients and Areas
245
-
246
- - **File Format**: `existing_materials.csv` or `existing_materials.xlsx`
247
- - **Data Format**: The first column should contain the material names, the second column should contain the surface areas of the materials (in square meters), and the subsequent columns should contain absorption coefficients for different frequencies.
248
-
249
- **Example:**
250
-
251
- """
252
-
253
- st.markdown(instructions)
254
- st.write(df_existing_materials)
255
-
256
- instructions = """
257
- ### New Materials Absorption Coefficients and Areas
258
-
259
- - **File Format**: `new_materials.csv` or `new_materials.xlsx`
260
- - **Data Format**: The first column should contain the material names, the second column should contain the surface areas of the materials (in square meters), and the subsequent columns should contain absorption coefficients for different frequencies.
261
-
262
- **Example:**
263
-
264
- """
265
-
266
- st.markdown(instructions)
267
- st.write(df_new_materials)
268
-
269
- instructions = """
270
- ### Current Sound Pressure Levels
271
-
272
- - **File Format**: `sound_pressure_levels.csv` or `sound_pressure_levels.xlsx`
273
- - **Data Format**: The first column should contain the names of the locations where sound pressure was measured, and the subsequent columns should contain sound pressure levels for different frequencies.
274
-
275
- **Example:**
276
-
277
- """
278
-
279
- st.markdown(instructions)
280
- st.write(df_sound_pressure_levels)
281
-
282
- instructions = """
283
- ## What Happens on Each Tab
284
-
285
- ### Instructions
286
-
287
- This tab provides detailed instructions on how to format your input data files and general information about using the app.
288
-
289
- ### Initial Data Entry
290
-
291
- Upload and review your initial acoustic data, including current reverberation times and existing materials data.
292
- Ensure all input data has been provided correctly before proceeding.
293
-
294
- ### Initial RT60 Compliance Check
295
-
296
- Compare your current RT60 values against standard ranges to determine if they are within acceptable limits.
297
- If the values are not within the standard range, you will need to apply acoustic treatment.
298
-
299
- ### Desired RT60
300
-
301
- Set your desired RT60 values for each frequency. The app will calculate the required sound absorption needed to
302
- achieve these values.
303
-
304
- ### Acoustic Treatment
305
-
306
- Introduce new materials and see their impact on the room's acoustics. Adjust the new materials data to try and
307
- achieve the desired RT60 values.
308
-
309
- ### Final RT60 Compliance Check
310
-
311
- Verify that the new RT60 values after acoustic treatment are within the desired range. If they are not, you may
312
- need to adjust your materials and try again.
313
-
314
- ### Intelligibility Noise Reduction
315
-
316
- Upload sound pressure levels and analyze the noise reduction achieved by the acoustic treatment. The app will
317
- calculate updated sound pressure levels based on the noise reduction.
318
-
319
- ## General Tips
320
-
321
- - **File Formats**: Ensure your input files are in CSV or Excel format.
322
- - **Consistent Naming**: Keep column headings consistent and spelled correctly.
323
- - **No Extra Data**: Avoid including any extra rows or columns outside of the specified format.
324
- - **Check for Errors**: Verify there are no typographical errors in the column headings.
325
- - **Repeat for Multiple Rooms**: If you need to analyze multiple rooms, repeat the process for each room individually.
326
- - **Save Your Work**: Regularly download the PDF report after completing your analysis.
327
-
328
- By following these instructions, you will be able to use the Building Acoustics Analysis Tool effectively and
329
- obtain accurate acoustic analysis for your room. If you encounter any issues, refer to these instructions or
330
- seek further assistance.
331
- """
332
- st.markdown(instructions)
333
-
334
- st.info("After reading the instructions, get your input data ready and proceed to the next step.")
335
-
336
- def display_initial_data_entry():
337
- st.write('''## Initial Data Entry''')
338
-
339
- st.write('''The primary objective here is to provide all the initial input data needed to start RT60 analysis.
340
- See the 'Instructions' on the left for formatting information''')
341
-
342
- st.write("#### Upload current reverberation times")
343
- current_rt_file = st.file_uploader("Upload CSV or Excel file for current reverberation times", type=['csv', 'xlsx'],
344
- help='Go to Instructions on the sidebar for formatting information.')
345
-
346
- if current_rt_file:
347
- st.session_state.df_current_rt = read_uploaded_file(current_rt_file, header=0, index_col=None)
348
- if st.session_state.df_current_rt is not None:
349
- st.session_state.frequencies = st.session_state.df_current_rt.columns.tolist()
350
- st.session_state.current_rt = dict(
351
- zip(st.session_state.frequencies, st.session_state.df_current_rt.iloc[0].tolist()))
352
- st.write("Current reverberation times:")
353
- st.dataframe(st.session_state.df_current_rt, use_container_width=True)
354
-
355
- elif st.session_state.df_current_rt is not None:
356
- st.write("Current reverberation times:")
357
- st.dataframe(st.session_state.df_current_rt, use_container_width=True)
358
-
359
- st.write("#### Upload existing materials data")
360
- existing_materials_file = st.file_uploader("Upload CSV or Excel file for existing materials", type=['csv', 'xlsx'],
361
- help='Go to Instructions on the sidebar for formatting information.')
362
-
363
- if existing_materials_file:
364
- st.session_state.df_existing_materials = read_uploaded_file(existing_materials_file, header=0, index_col=None)
365
- if st.session_state.df_existing_materials is not None:
366
- st.write("Existing Materials Data:")
367
- st.dataframe(st.session_state.df_existing_materials, use_container_width=True)
368
- st.session_state.existing_materials = []
369
- for _, row in st.session_state.df_existing_materials.iterrows():
370
- material = {
371
- 'name': row[0],
372
- 'area': row[1],
373
- 'coefficients': dict(zip(st.session_state.frequencies, row[2:].tolist()))
374
- }
375
- st.session_state.existing_materials.append(material)
376
- elif st.session_state.df_existing_materials is not None:
377
- st.write("Existing Materials Data:")
378
- st.dataframe(st.session_state.df_existing_materials, use_container_width=True)
379
-
380
- st.write("#### Enter total room volume")
381
- st.session_state.volume = float(st.number_input("Room Volume (m³):", min_value=0.0, step=0.01, format="%.2f",
382
- key="room_volume", value=st.session_state.volume,
383
- help='The calculated total volume of the room'))
384
-
385
- if st.session_state.df_current_rt is not None and st.session_state.df_existing_materials is not None and st.session_state.volume > 0:
386
- st.success("All input data has been successfully processed. Proceed to the next analysis step.")
387
- else:
388
- st.warning("Please ensure all input data has been provided correctly before proceeding.")
389
-
390
- def display_initial_rt60_compliance_check():
391
- st.write('''## Initial RT60 Compliance Check''')
392
-
393
- st.write('''The aim of initial compliance check is to compare the current RT60 values to the
394
- standard RT60 range. For the purpose of this tool, compliance is achieved if RT60 values for all frequencies are
395
- within the standard range. The graph at the bottom of this page would assist you in verifying compliance.
396
- If at least one frequency is not in the range, you would need to apply some acoustic treatment. See the
397
- "Acoustic Treatment" tab.''')
398
-
399
- st.write("#### Define standard reverberation time range")
400
- st.session_state.min_rt_val = float(
401
- st.number_input("Minimum Standard RT60 (s) for all frequencies:", min_value=0.0, step=0.01,
402
- format="%.2f", key="min_rt", value=st.session_state.min_rt_val,
403
- help='The minimum recommended RT60 in the applicable standard for your space type'))
404
- st.session_state.max_rt_val = float(
405
- st.number_input("Maximum Standard RT60 (s) for all frequencies:", min_value=0.0, step=0.01,
406
- format="%.2f", key="max_rt", value=st.session_state.max_rt_val,
407
- help='The maximum recommended RT60 in the applicable standard for your space type'))
408
- min_rt = {freq: st.session_state.min_rt_val for freq in st.session_state.frequencies}
409
- max_rt = {freq: st.session_state.max_rt_val for freq in st.session_state.frequencies}
410
-
411
- if st.session_state.current_rt and st.session_state.existing_materials:
412
- st.write("#### Calculated current room sound absorption")
413
- st.write('''The sound absorptions in the table below are calculated based on the absorption coefficients and areas
414
- of the existing materials in the room. You will compare total frequency values in this table to
415
- the desired sound absorption on the Desired RT60 to inform your selection of new materials''')
416
- current_absorption = {freq: 0 for freq in st.session_state.frequencies}
417
- absorption_data = []
418
- for material in st.session_state.existing_materials:
419
- material_absorption = {'Material': material['name']}
420
- for freq in st.session_state.frequencies:
421
- absorption_value = material['coefficients'][freq] * material['area']
422
- material_absorption[freq] = absorption_value
423
- current_absorption[freq] += absorption_value
424
- absorption_data.append(material_absorption)
425
-
426
- total_absorption = {'Material': 'Total Absorption'}
427
- for freq in st.session_state.frequencies:
428
- total_absorption[freq] = current_absorption[freq]
429
- absorption_data.append(total_absorption)
430
-
431
- df_current_absorption = pd.DataFrame(absorption_data)
432
- st.dataframe(df_current_absorption, use_container_width=True)
433
- st.session_state.df_current_absorption = df_current_absorption.copy() # Save a copy of current absorption data
434
-
435
- # Graph of Current RT vs. Standard Range
436
- fig1 = go.Figure()
437
- fig1.add_trace(go.Scatter(x=st.session_state.frequencies,
438
- y=[st.session_state.current_rt[freq] for freq in st.session_state.frequencies],
439
- mode='lines+markers',
440
- name='Current RT'))
441
- fig1.add_trace(
442
- go.Scatter(x=st.session_state.frequencies, y=[min_rt[freq] for freq in st.session_state.frequencies],
443
- mode='lines', name='Min Standard RT',
444
- line=dict(dash='dash')))
445
- fig1.add_trace(
446
- go.Scatter(x=st.session_state.frequencies, y=[max_rt[freq] for freq in st.session_state.frequencies],
447
- mode='lines', name='Max Standard RT',
448
- line=dict(dash='dash')))
449
- fig1.add_trace(
450
- go.Scatter(x=st.session_state.frequencies, y=[min_rt[freq] for freq in st.session_state.frequencies],
451
- fill='tonexty', mode='none',
452
- fillcolor='rgba(0,100,80,0.2)', showlegend=False))
453
- fig1.update_layout(title='Current RT vs. Standard Range', xaxis_title='Frequency (Hz)',
454
- yaxis_title='Reverberation Time (s)')
455
- st.plotly_chart(fig1)
456
- st.session_state.fig1 = fig1
457
-
458
- compliant = all(min_rt[freq] <= st.session_state.current_rt[freq] for freq in st.session_state.frequencies)
459
- compliant = compliant and all(
460
- st.session_state.current_rt[freq] <= max_rt[freq] for freq in st.session_state.frequencies)
461
-
462
- if compliant:
463
- st.success("All RT60 values are within the standard range. Proceed to the next step.")
464
- else:
465
- st.warning(
466
- "Some RT60 values are outside the standard range. You need to apply acoustic treatment in the next step.")
467
- else:
468
- st.warning("Please provide the current reverberation times and existing materials data before proceeding.")
469
-
470
- def display_desired_rt60():
471
- st.write('''## Desired RT60''')
472
-
473
- st.write('''At this point in the analysis, you would need to define your desired RT60, which would be used to
474
- calculate the desired sound absorption needed to achieve the desired RT60. Compare total frequency values
475
- in the table below to the calculated current room sound absorption on the Initial RT60 Compliance Check tab
476
- to inform your selection of new materials in the next step of the analysis''')
477
-
478
- if st.session_state.frequencies and st.session_state.min_rt_val and st.session_state.max_rt_val:
479
- st.write("#### Set desired reverberation time")
480
- min_rt = {freq: st.session_state.min_rt_val for freq in st.session_state.frequencies}
481
- max_rt = {freq: st.session_state.max_rt_val for freq in st.session_state.frequencies}
482
- valid_rt = True
483
- for freq in st.session_state.frequencies:
484
- st.session_state.desired_rt[freq] = st.number_input(f"Desired RT at {freq} Hz (s):", min_value=0.01,
485
- step=0.01,
486
- format="%.2f", key=f"desired_rt_{freq}",
487
- value=st.session_state.desired_rt.get(freq, 0.01),
488
- help='''The RT60 value you wish to achieve. This value must
489
- be within the range of the standard RT60 for your space and
490
- can be the same or different for each frequency''')
491
- if not (min_rt[freq] <= st.session_state.desired_rt[freq] <= max_rt[freq]):
492
- valid_rt = False
493
-
494
- st.write("##### Desired sound absorption based on desired RT60")
495
- desired_absorption_area = {
496
- freq: calculate_absorption_area(st.session_state.volume, st.session_state.desired_rt[freq]) for freq in
497
- st.session_state.frequencies}
498
- df_desired_absorption = pd.DataFrame([desired_absorption_area], columns=st.session_state.frequencies,
499
- index=['Desired Absorption Area'])
500
- st.dataframe(df_desired_absorption, use_container_width=True)
501
-
502
- if valid_rt and all(st.session_state.desired_rt[freq] > 0 for freq in st.session_state.frequencies):
503
- st.success("Desired RT60 values have been set correctly. Proceed to the next tab for acoustic treatment.")
504
- elif not valid_rt:
505
- st.error("Some desired RT60 values are not within the standard range. Please adjust the values.")
506
- else:
507
- st.warning("Desired RT60 values cannot be zero. Please provide valid values.")
508
- else:
509
- st.warning("Please complete the previous steps before proceeding to set the desired RT60 values.")
510
-
511
- def display_acoustic_treatment():
512
- st.write("""## Acoustic Treatment""")
513
-
514
- st.write("""The desired sound absorption calculated on the Desired RT60 tab is the target sound absorption
515
- you are aiming to achieve. You now have to start working towards achieving the target absorptions. Based on the
516
- differences between the desired sound absorptions (see Desired RT60 tab) and the calculated current room
517
- sound absorptions (see Initial RT60 Compliance Check tab), you would need to introduce new materials to either
518
- increase or decrease sound absorption for some frequencies. Note that sound absorption coefficients of a material
519
- is not the same for all frequencies. Therefore, you need to strategically select your materials. You may need
520
- to repeat the material selection process several times to ensure that the room passes the final RT60 compliance check.
521
- Your project brief may place limitations on the number of structural changes (like changing the wall or
522
- concrete floor) you are allowed to make. For a retrofit project, you can change non-structural elements
523
- like carpet and ceiling tiles. Additionally, you can introduce new materials like curtains.
524
- """)
525
-
526
- st.write("#### Upload new materials data")
527
- new_materials_file = st.file_uploader("Upload CSV or Excel file for new materials", type=['csv', 'xlsx'],
528
- help='Go to Instructions on the sidebar for formatting information.')
529
-
530
- if new_materials_file:
531
- st.session_state.df_new_materials = read_uploaded_file(new_materials_file, header=0, index_col=None)
532
- if st.session_state.df_new_materials is not None:
533
- st.write("New materials data:")
534
- st.dataframe(st.session_state.df_new_materials, use_container_width=True)
535
-
536
- st.session_state.new_materials = []
537
- for _, row in st.session_state.df_new_materials.iterrows():
538
- material = {
539
- 'name': row[0],
540
- 'area': row[1],
541
- 'coefficients': dict(zip(st.session_state.frequencies, row[2:].tolist()))
542
- }
543
- st.session_state.new_materials.append(material)
544
- elif st.session_state.df_new_materials is not None:
545
- st.write("New materials data:")
546
- st.dataframe(st.session_state.df_new_materials, use_container_width=True)
547
-
548
- if st.session_state.df_new_materials is not None:
549
- st.write("#### Edit new materials data")
550
- st.info(
551
- "You can add or delete rows and modify the values in the table below. Changes will be applied when sound absorption is updated based on new materials.")
552
- edited_df = st.data_editor(st.session_state.df_new_materials, num_rows="dynamic")
553
- st.session_state.df_new_materials = edited_df
554
-
555
- st.session_state.new_materials = []
556
- for _, row in st.session_state.df_new_materials.iterrows():
557
- material = {
558
- 'name': row[0],
559
- 'area': row[1],
560
- 'coefficients': dict(zip(st.session_state.frequencies, row[2:].tolist()))
561
- }
562
- st.session_state.new_materials.append(material)
563
-
564
- if st.session_state.new_materials and st.session_state.frequencies:
565
- st.session_state.new_absorption = {freq: 0 for freq in st.session_state.frequencies}
566
- absorption_data = []
567
- for material in st.session_state.new_materials:
568
- material_absorption = {'Material': material['name']}
569
- for freq in st.session_state.frequencies:
570
- absorption_value = material['coefficients'][freq] * material['area']
571
- material_absorption[freq] = absorption_value
572
- st.session_state.new_absorption[freq] += absorption_value
573
- absorption_data.append(material_absorption)
574
-
575
- total_absorption = {'Material': 'Total Absorption'}
576
- for freq in st.session_state.frequencies:
577
- total_absorption[freq] = st.session_state.new_absorption[freq]
578
- absorption_data.append(total_absorption)
579
-
580
- df_new_absorption = pd.DataFrame(absorption_data)
581
- st.write("#### Calculated sound absorption based on new materials")
582
- st.write('''The total sound absorption for each frequency must be equal to or very close to the desired sound absorption
583
- (see Desired RT60 tab) to increase your chances of achieving the desired RT60.''')
584
- st.dataframe(df_new_absorption, use_container_width=True)
585
- st.session_state.df_new_absorption = df_new_absorption.copy() # Save a copy of new absorption data
586
-
587
- st.success("New materials data has been processed. Proceed to the final RT60 compliance check.")
588
- else:
589
- st.warning("Please upload new materials data before proceeding.")
590
-
591
- def display_final_rt60_compliance_check():
592
- st.write("""## Final RT60 Compliance Check""")
593
- st.write("""This is the last step in the RT60 analysis. To pass the final compliance check, the new RT60 for each
594
- frequency must be within the standard RT60 range. If compliance fails, you need to go back to the Acoustic Treatment
595
- stage to revise your materials. Update your new materials spreadsheet and upload on the Acoustic Treatment tab.
596
- """)
597
-
598
- if st.session_state.new_absorption and st.session_state.frequencies:
599
- min_rt = {freq: st.session_state.min_rt_val for freq in st.session_state.frequencies}
600
- max_rt = {freq: st.session_state.max_rt_val for freq in st.session_state.frequencies}
601
- st.write("#### Calculated new reverberation times")
602
- new_rt = {freq: calculate_absorption_area(st.session_state.volume, st.session_state.new_absorption[freq]) for
603
- freq in st.session_state.frequencies}
604
- df_new_rt = pd.DataFrame([new_rt], columns=st.session_state.frequencies, index=['New Reverberation Time'])
605
- st.dataframe(df_new_rt, use_container_width=True)
606
-
607
- # Graph of Current and New RT vs. Standard Range
608
- fig2 = go.Figure()
609
- fig2.add_trace(go.Scatter(x=st.session_state.frequencies,
610
- y=[st.session_state.current_rt[freq] for freq in st.session_state.frequencies],
611
- mode='lines+markers',
612
- name='Current RT'))
613
- fig2.add_trace(
614
- go.Scatter(x=st.session_state.frequencies, y=[new_rt[freq] for freq in st.session_state.frequencies],
615
- mode='lines+markers', name='New RT'))
616
- fig2.add_trace(
617
- go.Scatter(x=st.session_state.frequencies, y=[min_rt[freq] for freq in st.session_state.frequencies],
618
- mode='lines', name='Min Standard RT',
619
- line=dict(dash='dash')))
620
- fig2.add_trace(
621
- go.Scatter(x=st.session_state.frequencies, y=[max_rt[freq] for freq in st.session_state.frequencies],
622
- mode='lines', name='Max Standard RT',
623
- line=dict(dash='dash')))
624
- fig2.add_trace(
625
- go.Scatter(x=st.session_state.frequencies, y=[min_rt[freq] for freq in st.session_state.frequencies],
626
- fill='tonexty', mode='none',
627
- fillcolor='rgba(0,100,80,0.2)', showlegend=False))
628
- fig2.update_layout(title='Current RT60 and New RT60 vs. Standard Range', xaxis_title='Frequency (Hz)',
629
- yaxis_title='Reverberation Time (s)')
630
- st.plotly_chart(fig2)
631
- st.session_state.fig2 = fig2 # Save fig2 in session state
632
-
633
- st.success(
634
- "After reflecting on the results, decide what to do next based on the expected outcome specified in your project brief.")
635
- else:
636
- st.warning("Please complete the previous steps before proceeding to the final RT60 compliance check.")
637
-
638
-
639
- def display_intelligibility_noise_reduction():
640
- st.write('''## Intelligibility Noise Reduction''')
641
-
642
- st.write('''On this tab, you will calculate noise reduction using existing and new materials sound absorption
643
- coefficients and surface areas that were provided for reverberation time analysis. The relevant data
644
- have copied to this tab for ease of reference. Note that you can update the new materials data by adding new rows
645
- or deleting existing rows. Your can also directly edit the current new materials data information. All updates
646
- will lead to updating relevant processes on this tab. Note that changes made to the new materials data
647
- on this tab will also update the new materials data for reverberation time given that the analysis is for the
648
- same room''')
649
-
650
- st.write("#### Upload current sound pressure levels")
651
- st.warning("##### Upload current sound pressure level data to complete the analysis on this tab")
652
- sound_pressure_file = st.file_uploader("Upload CSV or Excel file for current sound pressure levels",
653
- type=['csv', 'xlsx'],
654
- help='The file should have columns for frequencies 125, 250, 500, 1000, 2000, and 4000, and the first column should contain the names of the locations where sound pressure was measured.')
655
-
656
- if sound_pressure_file:
657
- st.session_state.df_sound_pressure = read_uploaded_file(sound_pressure_file, header=0, index_col=0)
658
- if st.session_state.df_sound_pressure is not None:
659
- st.session_state.df_sound_pressure.columns = [int(col) for col in
660
- st.session_state.df_sound_pressure.columns]
661
- st.session_state.frequencies = [125, 250, 500, 1000, 2000, 4000]
662
- st.write("Current Sound Pressure Levels:")
663
- st.dataframe(st.session_state.df_sound_pressure, use_container_width=True)
664
-
665
- elif st.session_state.df_sound_pressure is not None:
666
- st.write("Current Sound Pressure Levels:")
667
- st.dataframe(st.session_state.df_sound_pressure, use_container_width=True)
668
-
669
- st.write("#### Calculated current room sound absorption")
670
- st.info('''The data below is a duplicate of the current room sound absorption calculated for reverberation time
671
- analysis. It is provided here as a reminder of the existing materials in the room and their calculated sound
672
- absorptions.''')
673
- if st.session_state.df_current_absorption is not None:
674
- st.dataframe(st.session_state.df_current_absorption, use_container_width=True)
675
- else:
676
- st.write("No data available for current room sound absorption. Please complete the previous steps.")
677
-
678
- st.write("#### Editable new materials data")
679
- st.info('''The editable table below is a duplicate of the new materials data from reverberation time
680
- analysis. You can edit this table by adding new rows, deleting existing rows, or directly editing any
681
- information in the table. Click check box on the left to delete a row. Hover over the table and click + at the
682
- top or bottom to add new rows. Note that any changes made here will automatically update all the calculations
683
- on this tab and also update the new materials data for reverberation time and other reverberation time
684
- calculations that are connected to that data.''')
685
-
686
- if st.session_state.df_new_materials is not None:
687
- edited_df = st.data_editor(st.session_state.df_new_materials, num_rows="dynamic")
688
- st.session_state.df_new_materials = edited_df
689
-
690
- st.session_state.new_materials = []
691
- for _, row in st.session_state.df_new_materials.iterrows():
692
- material = {
693
- 'name': row[0],
694
- 'area': row[1],
695
- 'coefficients': dict(zip(st.session_state.frequencies, row[2:].tolist()))
696
- }
697
- st.session_state.new_materials.append(material)
698
-
699
- st.session_state.new_absorption = {freq: 0 for freq in st.session_state.frequencies}
700
- absorption_data = []
701
- for material in st.session_state.new_materials:
702
- material_absorption = {'Material': material['name']}
703
- for freq in st.session_state.frequencies:
704
- absorption_value = material['coefficients'][freq] * material['area']
705
- material_absorption[freq] = absorption_value
706
- st.session_state.new_absorption[freq] += absorption_value
707
- absorption_data.append(material_absorption)
708
-
709
- total_absorption = {'Material': 'Total Absorption'}
710
- for freq in st.session_state.frequencies:
711
- total_absorption[freq] = st.session_state.new_absorption[freq]
712
- absorption_data.append(total_absorption)
713
-
714
- df_new_absorption = pd.DataFrame(absorption_data)
715
- st.write("#### Calculated sound absorption based on new materials")
716
- st.info('''The table below presents sound absorption calculated based on the information in the
717
- Editable new materials data above''')
718
- st.dataframe(df_new_absorption, use_container_width=True)
719
- st.session_state.df_new_absorption = df_new_absorption.copy() # Save a copy of new absorption data
720
- else:
721
- st.write("No data available for new materials. Please upload new materials data.")
722
-
723
- st.write("#### Calculated Noise Reduction")
724
- if st.session_state.df_current_absorption is not None and st.session_state.df_new_absorption is not None:
725
- current_total_absorption = st.session_state.df_current_absorption.loc[:,
726
- st.session_state.frequencies].sum().sum()
727
- new_total_absorption = st.session_state.df_new_absorption.loc[:, st.session_state.frequencies].sum().sum()
728
- if current_total_absorption > 0:
729
- noise_reduction = 10 * np.log10(new_total_absorption / current_total_absorption)
730
- st.session_state.noise_reduction = noise_reduction
731
- st.write(f"##### Noise Reduction: {noise_reduction:.2f} dB")
732
- st.info('''The above noise reduction value is calculated total sound absorption for existing and new
733
- material above. The noise reduction formula is shown below:
734
- NR = 10 * Log10(new materials total absorption/existing materials total absorption)
735
-
736
- The above formula is the same as 10 * Log10(S alpha after/S alpha before''')
737
- else:
738
- st.error("Current total absorption is zero, which is not possible. Please check your data.")
739
- else:
740
- st.write("No data available to calculate noise reduction. Please complete the previous steps.")
741
-
742
- if st.session_state.df_sound_pressure is not None and 'noise_reduction' in st.session_state:
743
- st.write("#### Updated Sound Pressure Levels")
744
- st.info('''The values in the table below have been updated to account for the calculated noise reduction.
745
- Note that these are logarithm deductions given that sound pressure level is in decibels. Plot the
746
- updated sound pressure levels on your speech intelligibility Dot chart.''')
747
- updated_df = st.session_state.df_sound_pressure.copy()
748
-
749
- # Ensure all values are numeric and fill NaN with 0
750
- updated_df = updated_df.apply(pd.to_numeric, errors='coerce').fillna(0)
751
-
752
- # Subtract noise reduction from each sound pressure level using log subtraction
753
- for col in updated_df.columns:
754
- updated_df[col] = updated_df[col].apply(
755
- lambda x: 10 ** (x / 10) - 10 ** (st.session_state.noise_reduction / 10))
756
- updated_df[col] = updated_df[col].apply(lambda x: 10 * np.log10(x) if x > 0 else 0)
757
-
758
- st.write("Updated Sound Pressure Levels:")
759
- st.dataframe(updated_df, use_container_width=True)
760
-
761
- # PDF Download Button
762
- st.write("""
763
- **IMPORTANT NOTE ABOUT PDF REPORT:** The purpose of the PDF report is to provide you detailed record of all
764
- your input data and the graphs generated. Graphs in PDF report are of low resolutions. Hence, remember to download
765
- individual graphs and tables to include in your report. Hover your mouse over a graph and several icons would
766
- appear at the top right corner of the graph, click the first icon to download the graph. Repeat the same process
767
- to download tables.
768
- """)
769
- if st.button("Download PDF Report"):
770
- pdf = generate_pdf(
771
- st.session_state.volume,
772
- st.session_state.current_rt,
773
- st.session_state.existing_materials,
774
- {freq: st.session_state.min_rt_val for freq in st.session_state.frequencies},
775
- {freq: st.session_state.max_rt_val for freq in st.session_state.frequencies},
776
- st.session_state.desired_rt,
777
- st.session_state.new_materials,
778
- st.session_state.fig1,
779
- st.session_state.fig2,
780
- st.session_state.df_sound_pressure,
781
- updated_df
782
- )
783
- st.download_button(label="Download PDF", data=pdf, file_name="Room_Acoustics_Report.pdf",
784
- mime="application/pdf")
785
-
786
- # Main content display based on the current tab
787
- if st.session_state.current_tab == "Instructions":
788
- display_instructions()
789
- elif st.session_state.current_tab == "Initial Data Entry":
790
- display_initial_data_entry()
791
- elif st.session_state.current_tab == "Initial RT60 Compliance Check":
792
- display_initial_rt60_compliance_check()
793
- elif st.session_state.current_tab == "Desired RT60":
794
- display_desired_rt60()
795
- elif st.session_state.current_tab == "Acoustic Treatment":
796
- display_acoustic_treatment()
797
- elif st.session_state.current_tab == "Final RT60 Compliance Check":
798
- display_final_rt60_compliance_check()
799
- elif st.session_state.current_tab == "Intelligibility Noise Reduction":
800
- display_intelligibility_noise_reduction()
801
-
802
- # Navigation buttons
803
- tab_order = [
804
- "Instructions",
805
- "Initial Data Entry",
806
- "Initial RT60 Compliance Check",
807
- "Desired RT60",
808
- "Acoustic Treatment",
809
- "Final RT60 Compliance Check",
810
- "Intelligibility Noise Reduction"
811
- ]
812
-
813
- current_index = tab_order.index(st.session_state.current_tab)
814
-
815
- col1, col2, col3 = st.columns(3)
816
- if current_index > 0:
817
- col1.button("Previous", on_click=switch_tab, args=(tab_order[current_index - 1],))
818
- if current_index < len(tab_order) - 1:
819
- col3.button("Next", on_click=switch_tab, args=(tab_order[current_index + 1],))
820
-
821
- # Footer
822
- st.write("---")
823
- st.write("Developed by Dr Abdul-Manan Sadick, Deakin University, Australia, 2024.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import plotly.graph_objects as go
4
+ from fpdf import FPDF
5
+ import tempfile
6
+ import kaleido
7
+ import numpy as np
8
+
9
+ # Set page configuration
10
+ st.set_page_config(
11
+ page_icon="🏫",
12
+ initial_sidebar_state="expanded"
13
+ )
14
+
15
+ # Title and instructional information
16
+ st.title("🔊:blue[Building Acoustics Analysis (RT60)]")
17
+
18
+ with st.expander("App Information", expanded=False):
19
+ st.write("""
20
+ - Welcome to the Building Acoustics Analysis Tool.
21
+ - This app was developed to help Deakin University Construction Management students complete a building acoustics assignment in SRT757 Building Systems and Environment.
22
+ - This app is intended for a retrofitting task and assumes that you have measured the current reverberation of the room to be assessed.
23
+ - The app helps to analyze and modify room reverberation times to fall within standard ranges using the Sabine equation.
24
+ - This app is for educational purposes and not intended for professional use.
25
+ """)
26
+
27
+ default_values = {
28
+ 'current_tab': "Instructions",
29
+ 'current_rt': {},
30
+ 'frequencies': [],
31
+ 'existing_materials': [],
32
+ 'volume': 0.0,
33
+ 'desired_rt': {},
34
+ 'new_materials': [],
35
+ 'df_current_rt': None,
36
+ 'df_existing_materials': None,
37
+ 'df_new_materials': None,
38
+ 'min_rt_val': 0.0,
39
+ 'max_rt_val': 0.0,
40
+ 'new_absorption': {},
41
+ 'fig1': None,
42
+ 'fig2': None,
43
+ 'df_sound_pressure': None,
44
+ 'noise_reduction': None,
45
+ 'df_current_absorption': None,
46
+ 'df_new_absorption': None
47
+ }
48
+
49
+ for key, value in default_values.items():
50
+ if key not in st.session_state:
51
+ st.session_state[key] = value
52
+
53
+ # Helper functions
54
+ def standardize_frequencies(df):
55
+ """Standardize frequency column names to numerical values."""
56
+ column_mapping = {
57
+ '125Hz': '125', '250Hz': '250', '500Hz': '500', '1000Hz': '1000', '1KHz': '1000', '2KHz': '2000', '4KHz': '4000'
58
+ }
59
+ # Apply the mapping and ensure columns are treated as strings
60
+ df.columns = [column_mapping.get(col, col) for col in df.columns]
61
+ df.columns = df.columns.astype(str)
62
+ # Replace and try to convert to numeric
63
+ new_columns = pd.to_numeric(df.columns.str.replace(' Hz', '').str.replace('KHz', '000'), errors='coerce')
64
+ # Create a list to hold the final column names
65
+ final_columns = []
66
+ for original, new in zip(df.columns, new_columns):
67
+ # Use original column name if conversion failed
68
+ if pd.isna(new):
69
+ final_columns.append(original)
70
+ else:
71
+ final_columns.append(new)
72
+ df.columns = final_columns
73
+ return df
74
+
75
+ def validate_data(df):
76
+ """Basic validation of the uploaded data."""
77
+ if df.empty:
78
+ return False
79
+ # Check for numeric data in all columns except the first (which can be material names, etc.)
80
+ if not all(df.iloc[:, 1:].applymap(np.isreal).all()):
81
+ return False
82
+ # Check for non-negative values in numeric columns
83
+ if (df.iloc[:, 1:] < 0).any().any():
84
+ return False
85
+ return True
86
+
87
+ def calculate_absorption_area(volume, reverberation_time):
88
+ return 0.16 * volume / reverberation_time if reverberation_time else float('inf')
89
+
90
+ def generate_pdf(volume, current_rt, existing_materials, min_rt, max_rt, desired_rt, new_materials, fig1, fig2, df_sound_pressure, updated_df):
91
+ pdf = FPDF()
92
+ pdf.add_page()
93
+ pdf.set_font("Arial", size=12)
94
+ pdf.cell(200, 10, txt="Room Acoustics Analysis Report", ln=True, align="C")
95
+ pdf.cell(200, 10, txt=f"Room Volume: {volume:.2f} m³", ln=True)
96
+
97
+ # Summary and Recommendations
98
+ pdf.cell(200, 10, txt="Summary and Recommendations:", ln=True)
99
+ compliance_issues = [freq for freq in current_rt.keys() if not (min_rt[freq] <= current_rt[freq] <= max_rt[freq])]
100
+ if compliance_issues:
101
+ pdf.cell(200, 10, txt="Non-compliant frequencies found:", ln=True)
102
+ for freq in compliance_issues:
103
+ pdf.cell(200, 10, txt=f"{freq} Hz: {current_rt[freq]:.2f} s (out of standard range)", ln=True)
104
+ pdf.cell(200, 10, txt="Recommendation: Consider adding or modifying materials to bring RT60 within standard ranges.", ln=True)
105
+ else:
106
+ pdf.cell(200, 10, txt="All frequencies are within the standard RT60 range.", ln=True)
107
+ pdf.cell(200, 10, txt="No additional acoustic treatment is necessary.", ln=True)
108
+
109
+ pdf.cell(200, 10, txt="Current Reverberation Times (s):", ln=True)
110
+ for freq, rt in current_rt.items():
111
+ pdf.cell(200, 10, txt=f"{freq} Hz: {rt:.2f}", ln=True)
112
+
113
+ pdf.cell(200, 10, txt="Existing Materials and Absorption Coefficients:", ln=True)
114
+ for material in existing_materials:
115
+ pdf.cell(200, 10, txt=f"Material: {material['name']}, Area: {material['area']:.2f} m²", ln=True)
116
+ for freq, coeff in material['coefficients'].items():
117
+ pdf.cell(200, 10, txt=f"{freq} Hz: {coeff:.2f}", ln=True)
118
+
119
+ pdf.cell(200, 10, txt="Standard Reverberation Time Range (s):", ln=True)
120
+ for freq in min_rt.keys():
121
+ pdf.cell(200, 10, txt=f"{freq} Hz: {min_rt[freq]:.2f} - {max_rt[freq]:.2f}", ln=True)
122
+
123
+ pdf.cell(200, 10, txt="Desired Reverberation Times (s):", ln=True)
124
+ for freq, rt in desired_rt.items():
125
+ pdf.cell(200, 10, txt=f"{freq} Hz: {rt:.2f}", ln=True)
126
+
127
+ pdf.cell(200, 10, txt="New Materials and Absorption Coefficients:", ln=True)
128
+ for material in new_materials:
129
+ pdf.cell(200, 10, txt=f"Material: {material['name']}, Area: {material['area']:.2f} m²", ln=True)
130
+ for freq, coeff in material['coefficients'].items():
131
+ pdf.cell(200, 10, txt=f"{freq} Hz: {coeff:.2f}", ln=True)
132
+
133
+ # Save the figures as temporary files and add to the PDF
134
+ for fig, tmpfile in [(fig1, "fig1.png"), (fig2, "fig2.png")]:
135
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmpfile:
136
+ fig.write_image(tmpfile.name, engine='kaleido')
137
+ pdf.image(tmpfile.name, x=10, y=None, w=180)
138
+
139
+ # Add sound pressure levels data
140
+ pdf.add_page()
141
+ pdf.cell(200, 10, txt="Current Sound Pressure Levels (dB):", ln=True)
142
+ for index, row in df_sound_pressure.iterrows():
143
+ pdf.cell(200, 10, txt=f"{index}:", ln=True)
144
+ for col in df_sound_pressure.columns:
145
+ pdf.cell(200, 10, txt=f"{col} Hz: {row[col]:.2f}", ln=True)
146
+
147
+ # Add updated sound pressure levels data
148
+ pdf.cell(200, 10, txt="Updated Sound Pressure Levels (dB):", ln=True)
149
+ for index, row in updated_df.iterrows():
150
+ pdf.cell(200, 10, txt=f"{index}:", ln=True)
151
+ for col in updated_df.columns:
152
+ pdf.cell(200, 10, txt=f"{col} Hz: {row[col]:.2f}", ln=True)
153
+
154
+ return pdf.output(dest='S').encode('latin1')
155
+
156
+ def read_uploaded_file(uploaded_file, header=0, index_col=None):
157
+ try:
158
+ if uploaded_file.name.endswith('.csv'):
159
+ return pd.read_csv(uploaded_file, header=header, index_col=index_col)
160
+ elif uploaded_file.name.endswith('.xlsx'):
161
+ return pd.read_excel(uploaded_file, header=header, index_col=index_col)
162
+ except Exception as e:
163
+ st.error(f"Error reading file {uploaded_file.name}: {e}")
164
+
165
+ # Layout customizations
166
+ hide_menu_style = """
167
+ <style>
168
+ #MainMenu {visibility: hidden;}
169
+ footer {visibility: hidden;}
170
+ </style>
171
+ """
172
+ st.markdown(hide_menu_style, unsafe_allow_html=True)
173
+
174
+ # Sidebar with navigation
175
+ def switch_tab(tab_name):
176
+ st.session_state.current_tab = tab_name
177
+
178
+ with st.sidebar:
179
+ for tab in ["Instructions", "Initial Data Entry", "Initial RT60 Compliance Check", "Desired RT60",
180
+ "Acoustic Treatment", "Final RT60 Compliance Check", "Intelligibility Noise Reduction", "FAQ / Help"]:
181
+ st.button(tab, on_click=switch_tab, args=(tab,))
182
+
183
+ # Display content based on selected tab in the main window
184
+ def display_instructions():
185
+ import pandas as pd
186
+
187
+ # Example DataFrames for input data
188
+ df_current_reverberation_times = pd.DataFrame({
189
+ '125': [0.8],
190
+ '250': [0.7],
191
+ '500': [0.6],
192
+ '1000': [0.5],
193
+ '2000': [0.4],
194
+ '4000': [0.3]
195
+ })
196
+
197
+ df_existing_materials = pd.DataFrame({
198
+ 'Material Name': ['Carpet', 'Curtain'],
199
+ 'Area_No': [50, 30],
200
+ '125': [0.1, 0.2],
201
+ '250': [0.15, 0.25],
202
+ '500': [0.2, 0.3],
203
+ '1000': [0.3, 0.35],
204
+ '2000': [0.4, 0.45],
205
+ '4000': [0.5, 0.55]
206
+ })
207
+
208
+ df_new_materials = pd.DataFrame({
209
+ 'Material Name': ['Acoustic Panel', 'Foam'],
210
+ 'Area_No': [40, 20],
211
+ '125': [0.3, 0.25],
212
+ '250': [0.35, 0.3],
213
+ '500': [0.4, 0.35],
214
+ '1000': [0.45, 0.4],
215
+ '2000': [0.5, 0.45],
216
+ '4000': [0.6, 0.55]
217
+ })
218
+
219
+ df_sound_pressure_levels = pd.DataFrame({
220
+ 'Location': ['Location 1', 'Location 2'],
221
+ '125': [60, 62],
222
+ '250': [58, 59],
223
+ '500': [55, 56],
224
+ '1000': [52, 53],
225
+ '2000': [50, 51],
226
+ '4000': [48, 49]
227
+ })
228
+
229
+ st.write('## Instructions')
230
+
231
+ instructions = """
232
+
233
+ ## Introduction
234
+ Welcome to the Building Acoustics Analysis Tool. This application is designed to assist you in analyzing and resolving
235
+ reverberation time (RT60) issues and calculating noise reduction for improving speech intelligibility in a room. The
236
+ analysis leverages Sabine's equation for reverberation time analysis, which is crucial in determining the acoustic
237
+ characteristics of a space.
238
+ Please note that the app focuses on specific frequencies: 125 Hz, 250 Hz, 500 Hz, 1000 Hz, 2000 Hz, and 4000 Hz.
239
+ These frequencies are standard in acoustics analysis and will be the basis for all calculations and visualizations.
240
+ This app is intended for educational purposes and is not suitable for professional use.
241
+ ## What is RT60?
242
+ RT60, or reverberation time, is the time it takes for the sound level to decay by 60 decibels after the sound source has stopped. It is a key parameter in room acoustics, influencing speech intelligibility, music clarity, and overall acoustic comfort. Short RT60 values are desired in spaces like classrooms or offices where clarity of speech is essential, while longer RT60 values might be acceptable in concert halls where richer sound is preferred.
243
+ ### Example of RT60 Calculation Using Sabine's Equation
244
+ Sabine's equation is used to calculate the RT60:
245
+ **RT60 = (0.16 * V) / A**
246
+ Where:
247
+ - **V** is the volume of the room in cubic meters (m³).
248
+ - **A** is the total sound absorption of the room, which depends on the surface areas and absorption coefficients of the materials present.
249
+ For example, if a room has a volume of 100 m³ and contains materials with a total absorption area of 10 m², the RT60 can be calculated as:
250
+ **RT60 = (0.16 * 100) / 10 = 1.60 seconds**
251
+ ## App Functionality
252
+ The Building Acoustics Analysis Tool provides the following functionalities:
253
+ 1. **Initial Data Entry**: Upload and review initial acoustic data, including current reverberation times and existing materials.
254
+ 2. **Initial RT60 Compliance Check**: Compare current RT60 values against standard ranges to determine compliance.
255
+ 3. **Desired RT60**: Set desired RT60 values and calculate the required sound absorption to achieve these values.
256
+ 4. **Acoustic Treatment**: Introduce new materials and calculate their impact on the room's acoustics.
257
+ 5. **Final RT60 Compliance Check**: Verify that the new RT60 values are within the desired range after acoustic treatment.
258
+ 6. **Intelligibility Noise Reduction**: Analyze noise reduction and its impact on sound pressure levels in the room.
259
+ ## Instructions for Formatting Input Data
260
+ Please note that the number 0, 1, 2, .... in the first column of the examples below are similar to the default
261
+ Excel line numbers. Therefore, DO NOT number the first columns of your data files.
262
+ ### Current Reverberation Times
263
+ - **File Format**: CSV or Excel
264
+ - **Data Format**: The first row should contain the frequency values as column headings, and the second row should contain the reverberation times corresponding to each frequency.
265
+ **Example:**
266
+ """
267
+
268
+ st.markdown(instructions)
269
+ st.write(df_current_reverberation_times)
270
+
271
+ instructions = """
272
+ ### Existing Materials Absorption Coefficients and Areas
273
+ - **File Format**: CSV or Excel
274
+ - **Data Format**: The first column should contain the material names, the second column should contain the surface areas of the materials (in square meters), and the subsequent columns should contain absorption coefficients for different frequencies.
275
+ **Example:**
276
+ """
277
+
278
+ st.markdown(instructions)
279
+ st.write(df_existing_materials)
280
+
281
+ instructions = """
282
+ ### New Materials Absorption Coefficients and Areas
283
+ - **File Format**: CSV or Excel
284
+ - **Data Format**: The first column should contain the material names, the second column should contain the surface areas of the materials (in square meters), and the subsequent columns should contain absorption coefficients for different frequencies.
285
+ **Example:**
286
+ """
287
+
288
+ st.markdown(instructions)
289
+ st.write(df_new_materials)
290
+
291
+ instructions = """
292
+ ### Current Sound Pressure Levels
293
+ - **File Format**: CSV or Excel
294
+ - **Data Format**: The first column should contain the names of the locations where sound pressure was measured, and the subsequent columns should contain sound pressure levels for different frequencies.
295
+ **Example:**
296
+ """
297
+
298
+ st.markdown(instructions)
299
+ st.write(df_sound_pressure_levels)
300
+
301
+ instructions = """
302
+ ## What Happens on Each Tab
303
+ ### Instructions
304
+ This tab provides detailed instructions on how to format your input data files and general information about using the app.
305
+ ### Initial Data Entry
306
+ Upload and review your initial acoustic data, including current reverberation times and existing materials data.
307
+ Ensure all input data has been provided correctly before proceeding.
308
+ ### Initial RT60 Compliance Check
309
+ Compare your current RT60 values against standard ranges to determine if they are within acceptable limits.
310
+ If the values are not within the standard range, you will need to apply acoustic treatment.
311
+ ### Desired RT60
312
+ Set your desired RT60 values for each frequency. The app will calculate the required sound absorption needed to
313
+ achieve these values.
314
+ ### Acoustic Treatment
315
+ Introduce new materials and see their impact on the room's acoustics. Adjust the new materials data to try and
316
+ achieve the desired RT60 values.
317
+ ### Final RT60 Compliance Check
318
+ Verify that the new RT60 values after acoustic treatment are within the desired range. If they are not, you may
319
+ need to adjust your materials and try again.
320
+ ### Intelligibility Noise Reduction
321
+ Upload sound pressure levels and analyze the noise reduction achieved by the acoustic treatment. The app will
322
+ calculate updated sound pressure levels based on the noise reduction.
323
+ ## General Tips
324
+ - **File Formats**: Ensure your input files are in CSV or Excel format.
325
+ - **Consistent Naming**: Keep column headings consistent and spelled correctly.
326
+ - **No Extra Data**: Avoid including any extra rows or columns outside of the specified format.
327
+ - **Check for Errors**: Verify there are no typographical errors in the column headings.
328
+ - **Repeat for Multiple Rooms**: If you need to analyze multiple rooms, repeat the process for each room individually.
329
+ - **Save Your Work**: Regularly download the PDF report after completing your analysis.
330
+ By following these instructions, you will be able to use the Building Acoustics Analysis Tool effectively and
331
+ obtain accurate acoustic analysis for your room. If you encounter any issues, refer to these instructions or
332
+ seek further assistance.
333
+ """
334
+ st.markdown(instructions)
335
+
336
+ st.info("After reading the instructions, get your input data ready and proceed to the next step.")
337
+
338
+ def display_initial_data_entry():
339
+ st.write('''## Initial Data Entry''')
340
+
341
+ st.write('''The primary objective here is to provide all the initial input data needed to start RT60 analysis.
342
+ See the 'Instructions' on the left for formatting information''')
343
+
344
+ st.write("#### Upload current reverberation times")
345
+ current_rt_file = st.file_uploader("Upload CSV or Excel file for current reverberation times", type=['csv', 'xlsx'],
346
+ help='Go to Instructions on the sidebar for formatting information.')
347
+
348
+ if current_rt_file:
349
+ df_current_rt = read_uploaded_file(current_rt_file, header=0, index_col=None)
350
+ df_current_rt = standardize_frequencies(df_current_rt)
351
+ st.session_state.df_current_rt = df_current_rt
352
+ if st.session_state.df_current_rt is not None:
353
+ st.session_state.frequencies = st.session_state.df_current_rt.columns.tolist()
354
+ st.session_state.current_rt = dict(
355
+ zip(st.session_state.frequencies, st.session_state.df_current_rt.iloc[0].tolist()))
356
+ st.write("Current reverberation times:")
357
+ st.dataframe(st.session_state.df_current_rt, use_container_width=True)
358
+
359
+ elif st.session_state.df_current_rt is not None:
360
+ st.write("Current reverberation times:")
361
+ st.dataframe(st.session_state.df_current_rt, use_container_width=True)
362
+
363
+ st.write("#### Upload existing materials data")
364
+ existing_materials_file = st.file_uploader("Upload CSV or Excel file for existing materials", type=['csv', 'xlsx'],
365
+ help='Go to Instructions on the sidebar for formatting information.')
366
+
367
+ if existing_materials_file:
368
+ df_existing_materials = read_uploaded_file(existing_materials_file, header=0, index_col=None)
369
+ df_existing_materials = standardize_frequencies(df_existing_materials)
370
+ st.session_state.df_existing_materials = df_existing_materials
371
+ if st.session_state.df_existing_materials is not None:
372
+ st.write("Existing Materials Data:")
373
+ st.dataframe(st.session_state.df_existing_materials, use_container_width=True)
374
+ st.session_state.existing_materials = []
375
+ for _, row in st.session_state.df_existing_materials.iterrows():
376
+ material = {
377
+ 'name': row[0],
378
+ 'area': row[1],
379
+ 'coefficients': dict(zip(st.session_state.frequencies, row[2:].tolist()))
380
+ }
381
+ st.session_state.existing_materials.append(material)
382
+ elif st.session_state.df_existing_materials is not None:
383
+ st.write("Existing Materials Data:")
384
+ st.dataframe(st.session_state.df_existing_materials, use_container_width=True)
385
+
386
+ st.write("#### Enter total room volume")
387
+ st.session_state.volume = float(st.number_input("Room Volume (m³):", min_value=0.0, step=0.01, format="%.2f",
388
+ key="room_volume", value=st.session_state.volume,
389
+ help='The calculated total volume of the room'))
390
+
391
+ if st.session_state.df_current_rt is not None and st.session_state.df_existing_materials is not None and st.session_state.volume > 0:
392
+ st.success("All input data has been successfully processed. Proceed to the next analysis step.")
393
+ else:
394
+ st.warning("Please ensure all input data has been provided correctly before proceeding.")
395
+
396
+ def display_initial_rt60_compliance_check():
397
+ st.write('''## Initial RT60 Compliance Check''')
398
+
399
+ st.write('''The aim of initial compliance check is to compare the current RT60 values to the
400
+ standard RT60 range. For the purpose of this tool, compliance is achieved if RT60 values for all frequencies are
401
+ within the standard range. The graph at the bottom of this page would assist you in verifying compliance.
402
+ If at least one frequency is not in the range, you would need to apply some acoustic treatment. See the
403
+ "Acoustic Treatment" tab.''')
404
+
405
+ st.write("#### Define standard reverberation time range")
406
+ st.session_state.min_rt_val = float(
407
+ st.number_input("Minimum Standard RT60 (s) for all frequencies:", min_value=0.0, step=0.01,
408
+ format="%.2f", key="min_rt", value=st.session_state.min_rt_val,
409
+ help='The minimum recommended RT60 in the applicable standard for your space type'))
410
+ st.session_state.max_rt_val = float(
411
+ st.number_input("Maximum Standard RT60 (s) for all frequencies:", min_value=0.0, step=0.01,
412
+ format="%.2f", key="max_rt", value=st.session_state.max_rt_val,
413
+ help='The maximum recommended RT60 in the applicable standard for your space type'))
414
+ min_rt = {freq: st.session_state.min_rt_val for freq in st.session_state.frequencies}
415
+ max_rt = {freq: st.session_state.max_rt_val for freq in st.session_state.frequencies}
416
+
417
+ if st.session_state.current_rt and st.session_state.existing_materials:
418
+ st.write("#### Calculated current room sound absorption")
419
+ st.write('''The sound absorptions in the table below are calculated based on the absorption coefficients and areas
420
+ of the existing materials in the room. You will compare total frequency values in this table to
421
+ the desired sound absorption on the Desired RT60 to inform your selection of new materials''')
422
+ current_absorption = {freq: 0 for freq in st.session_state.frequencies}
423
+ absorption_data = []
424
+ for material in st.session_state.existing_materials:
425
+ material_absorption = {'Material': material['name']}
426
+ for freq in st.session_state.frequencies:
427
+ absorption_value = material['coefficients'][freq] * material['area']
428
+ material_absorption[freq] = absorption_value
429
+ current_absorption[freq] += absorption_value
430
+ absorption_data.append(material_absorption)
431
+
432
+ total_absorption = {'Material': 'Total Absorption'}
433
+ for freq in st.session_state.frequencies:
434
+ total_absorption[freq] = current_absorption[freq]
435
+ absorption_data.append(total_absorption)
436
+
437
+ df_current_absorption = pd.DataFrame(absorption_data)
438
+ st.dataframe(df_current_absorption, use_container_width=True)
439
+ st.session_state.df_current_absorption = df_current_absorption.copy() # Save a copy of current absorption data
440
+
441
+ # Graph of Current RT vs. Standard Range
442
+ fig1 = go.Figure()
443
+ fig1.add_trace(go.Scatter(x=st.session_state.frequencies,
444
+ y=[st.session_state.current_rt[freq] for freq in st.session_state.frequencies],
445
+ mode='lines+markers',
446
+ name='Current RT'))
447
+ fig1.add_trace(
448
+ go.Scatter(x=st.session_state.frequencies, y=[min_rt[freq] for freq in st.session_state.frequencies],
449
+ mode='lines', name='Min Standard RT',
450
+ line=dict(dash='dash')))
451
+ fig1.add_trace(
452
+ go.Scatter(x=st.session_state.frequencies, y=[max_rt[freq] for freq in st.session_state.frequencies],
453
+ mode='lines', name='Max Standard RT',
454
+ line=dict(dash='dash')))
455
+ fig1.add_trace(
456
+ go.Scatter(x=st.session_state.frequencies, y=[min_rt[freq] for freq in st.session_state.frequencies],
457
+ fill='tonexty', mode='none',
458
+ fillcolor='rgba(0,100,80,0.2)', showlegend=False))
459
+ fig1.update_layout(title='Current RT vs. Standard Range', xaxis_title='Frequency (Hz)',
460
+ yaxis_title='Reverberation Time (s)')
461
+ st.plotly_chart(fig1)
462
+ st.session_state.fig1 = fig1
463
+
464
+ compliant = all(min_rt[freq] <= st.session_state.current_rt[freq] for freq in st.session_state.frequencies)
465
+ compliant = compliant and all(
466
+ st.session_state.current_rt[freq] <= max_rt[freq] for freq in st.session_state.frequencies)
467
+
468
+ if compliant:
469
+ st.success("All RT60 values are within the standard range. Proceed to the next step.")
470
+ else:
471
+ st.warning(
472
+ "Some RT60 values are outside the standard range. You need to apply acoustic treatment in the next step.")
473
+ else:
474
+ st.warning("Please provide the current reverberation times and existing materials data before proceeding.")
475
+
476
+ def display_desired_rt60():
477
+ st.write('''## Desired RT60''')
478
+
479
+ st.write('''At this point in the analysis, you would need to define your desired RT60, which would be used to
480
+ calculate the desired sound absorption needed to achieve the desired RT60. Compare total frequency values
481
+ in the table below to the calculated current room sound absorption on the Initial RT60 Compliance Check tab
482
+ to inform your selection of new materials in the next step of the analysis''')
483
+
484
+ if st.session_state.frequencies and st.session_state.min_rt_val and st.session_state.max_rt_val:
485
+ st.write("#### Set desired reverberation time")
486
+ min_rt = {freq: st.session_state.min_rt_val for freq in st.session_state.frequencies}
487
+ max_rt = {freq: st.session_state.max_rt_val for freq in st.session_state.frequencies}
488
+ valid_rt = True
489
+ for freq in st.session_state.frequencies:
490
+ st.session_state.desired_rt[freq] = st.number_input(f"Desired RT at {freq} Hz (s):", min_value=0.01,
491
+ step=0.01,
492
+ format="%.2f", key=f"desired_rt_{freq}",
493
+ value=st.session_state.desired_rt.get(freq, 0.01),
494
+ help='''The RT60 value you wish to achieve. This value must
495
+ be within the range of the standard RT60 for your space and
496
+ can be the same or different for each frequency''')
497
+ if not (min_rt[freq] <= st.session_state.desired_rt[freq] <= max_rt[freq]):
498
+ valid_rt = False
499
+
500
+ st.write("##### Desired sound absorption based on desired RT60")
501
+ desired_absorption_area = {
502
+ freq: calculate_absorption_area(st.session_state.volume, st.session_state.desired_rt[freq]) for freq in
503
+ st.session_state.frequencies}
504
+ df_desired_absorption = pd.DataFrame([desired_absorption_area], columns=st.session_state.frequencies,
505
+ index=['Desired Absorption Area'])
506
+ st.dataframe(df_desired_absorption, use_container_width=True)
507
+
508
+ if valid_rt and all(st.session_state.desired_rt[freq] > 0 for freq in st.session_state.frequencies):
509
+ st.success("Desired RT60 values have been set correctly. Proceed to the next tab for acoustic treatment.")
510
+ elif not valid_rt:
511
+ st.error("Some desired RT60 values are not within the standard range. Please adjust the values.")
512
+ else:
513
+ st.warning("Desired RT60 values cannot be zero. Please provide valid values.")
514
+ else:
515
+ st.warning("Please complete the previous steps before proceeding to set the desired RT60 values.")
516
+
517
+ def display_acoustic_treatment():
518
+ st.write("""## Acoustic Treatment""")
519
+
520
+ st.write("""The desired sound absorption calculated on the Desired RT60 tab is the target sound absorption
521
+ you are aiming to achieve. You now have to start working towards achieving the target absorptions. Based on the
522
+ differences between the desired sound absorptions (see Desired RT60 tab) and the calculated current room
523
+ sound absorptions (see Initial RT60 Compliance Check tab), you would need to introduce new materials to either
524
+ increase or decrease sound absorption for some frequencies. Note that sound absorption coefficients of a material
525
+ is not the same for all frequencies. Therefore, you need to strategically select your materials. You may need
526
+ to repeat the material selection process several times to ensure that the room passes the final RT60 compliance check.
527
+ Your project brief may place limitations on the number of structural changes (like changing the wall or
528
+ concrete floor) you are allowed to make. For a retrofit project, you can change non-structural elements
529
+ like carpet and ceiling tiles. Additionally, you can introduce new materials like curtains.
530
+ """)
531
+
532
+ st.write("#### Upload new materials data")
533
+ new_materials_file = st.file_uploader("Upload CSV or Excel file for new materials", type=['csv', 'xlsx'],
534
+ help='Go to Instructions on the sidebar for formatting information.')
535
+
536
+ if new_materials_file:
537
+ df_new_materials = read_uploaded_file(new_materials_file, header=0, index_col=None)
538
+ df_new_materials = standardize_frequencies(df_new_materials)
539
+ st.session_state.df_new_materials = df_new_materials
540
+ if st.session_state.df_new_materials is not None:
541
+ st.write("New materials data:")
542
+ st.dataframe(st.session_state.df_new_materials, use_container_width=True)
543
+
544
+ st.session_state.new_materials = []
545
+ for _, row in st.session_state.df_new_materials.iterrows():
546
+ material = {
547
+ 'name': row[0],
548
+ 'area': row[1],
549
+ 'coefficients': dict(zip(st.session_state.frequencies, row[2:].tolist()))
550
+ }
551
+ st.session_state.new_materials.append(material)
552
+ elif st.session_state.df_new_materials is not None:
553
+ st.write("New materials data:")
554
+ st.dataframe(st.session_state.df_new_materials, use_container_width=True)
555
+
556
+ if st.session_state.df_new_materials is not None:
557
+ st.write("#### Edit new materials data")
558
+ st.info(
559
+ "You can add or delete rows and modify the values in the table below. Changes will be applied when sound absorption is updated based on new materials.")
560
+ edited_df = st.data_editor(st.session_state.df_new_materials, num_rows="dynamic")
561
+ st.session_state.df_new_materials = edited_df
562
+
563
+ st.session_state.new_materials = []
564
+ for _, row in st.session_state.df_new_materials.iterrows():
565
+ material = {
566
+ 'name': row[0],
567
+ 'area': row[1],
568
+ 'coefficients': dict(zip(st.session_state.frequencies, row[2:].tolist()))
569
+ }
570
+ st.session_state.new_materials.append(material)
571
+
572
+ if st.session_state.new_materials and st.session_state.frequencies:
573
+ st.session_state.new_absorption = {freq: 0 for freq in st.session_state.frequencies}
574
+ absorption_data = []
575
+ for material in st.session_state.new_materials:
576
+ material_absorption = {'Material': material['name']}
577
+ for freq in st.session_state.frequencies:
578
+ absorption_value = material['coefficients'][freq] * material['area']
579
+ material_absorption[freq] = absorption_value
580
+ st.session_state.new_absorption[freq] += absorption_value
581
+ absorption_data.append(material_absorption)
582
+
583
+ total_absorption = {'Material': 'Total Absorption'}
584
+ for freq in st.session_state.frequencies:
585
+ total_absorption[freq] = st.session_state.new_absorption[freq]
586
+ absorption_data.append(total_absorption)
587
+
588
+ df_new_absorption = pd.DataFrame(absorption_data)
589
+ st.write("#### Calculated sound absorption based on new materials")
590
+ st.write('''The total sound absorption for each frequency must be equal to or very close to the desired sound absorption
591
+ (see Desired RT60 tab) to increase your chances of achieving the desired RT60.''')
592
+ st.dataframe(df_new_absorption, use_container_width=True)
593
+ st.session_state.df_new_absorption = df_new_absorption.copy() # Save a copy of new absorption data
594
+
595
+ st.success("New materials data has been processed. Proceed to the final RT60 compliance check.")
596
+ else:
597
+ st.warning("Please upload new materials data before proceeding.")
598
+
599
+ def display_final_rt60_compliance_check():
600
+ st.write("""## Final RT60 Compliance Check""")
601
+ st.write("""This is the last step in the RT60 analysis. To pass the final compliance check, the new RT60 for each
602
+ frequency must be within the standard RT60 range. If compliance fails, you need to go back to the Acoustic Treatment
603
+ stage to revise your materials. Update your new materials spreadsheet and upload on the Acoustic Treatment tab.
604
+ """)
605
+
606
+ if st.session_state.new_absorption and st.session_state.frequencies:
607
+ min_rt = {freq: st.session_state.min_rt_val for freq in st.session_state.frequencies}
608
+ max_rt = {freq: st.session_state.max_rt_val for freq in st.session_state.frequencies}
609
+ st.write("#### Calculated new reverberation times")
610
+ new_rt = {freq: calculate_absorption_area(st.session_state.volume, st.session_state.new_absorption[freq]) for
611
+ freq in st.session_state.frequencies}
612
+ df_new_rt = pd.DataFrame([new_rt], columns=st.session_state.frequencies, index=['New Reverberation Time'])
613
+ st.dataframe(df_new_rt, use_container_width=True)
614
+
615
+ # Graph of Current and New RT vs. Standard Range
616
+ fig2 = go.Figure()
617
+ fig2.add_trace(go.Scatter(x=st.session_state.frequencies,
618
+ y=[st.session_state.current_rt[freq] for freq in st.session_state.frequencies],
619
+ mode='lines+markers',
620
+ name='Current RT'))
621
+ fig2.add_trace(
622
+ go.Scatter(x=st.session_state.frequencies, y=[new_rt[freq] for freq in st.session_state.frequencies],
623
+ mode='lines+markers', name='New RT'))
624
+ fig2.add_trace(
625
+ go.Scatter(x=st.session_state.frequencies, y=[min_rt[freq] for freq in st.session_state.frequencies],
626
+ mode='lines', name='Min Standard RT',
627
+ line=dict(dash='dash')))
628
+ fig2.add_trace(
629
+ go.Scatter(x=st.session_state.frequencies, y=[max_rt[freq] for freq in st.session_state.frequencies],
630
+ mode='lines', name='Max Standard RT',
631
+ line=dict(dash='dash')))
632
+ fig2.add_trace(
633
+ go.Scatter(x=st.session_state.frequencies, y=[min_rt[freq] for freq in st.session_state.frequencies],
634
+ fill='tonexty', mode='none',
635
+ fillcolor='rgba(0,100,80,0.2)', showlegend=False))
636
+ fig2.update_layout(title='Current RT60 and New RT60 vs. Standard Range', xaxis_title='Frequency (Hz)',
637
+ yaxis_title='Reverberation Time (s)')
638
+ st.plotly_chart(fig2)
639
+ st.session_state.fig2 = fig2 # Save fig2 in session state
640
+
641
+ st.success(
642
+ "After reflecting on the results, decide what to do next based on the expected outcome specified in your project brief.")
643
+ else:
644
+ st.warning("Please complete the previous steps before proceeding to the final RT60 compliance check.")
645
+
646
+ def display_intelligibility_noise_reduction():
647
+ st.write('''## Intelligibility Noise Reduction''')
648
+
649
+ st.write('''On this tab, you will calculate noise reduction using existing and new materials sound absorption
650
+ coefficients and surface areas that were provided for reverberation time analysis. The relevant data
651
+ have copied to this tab for ease of reference. Note that you can update the new materials data by adding new rows
652
+ or deleting existing rows. Your can also directly edit the current new materials data information. All updates
653
+ will lead to updating relevant processes on this tab. Note that changes made to the new materials data
654
+ on this tab will also update the new materials data for reverberation time given that the analysis is for the
655
+ same room''')
656
+
657
+ st.write("#### Upload current sound pressure levels")
658
+ st.warning("##### Upload current sound pressure level data to complete the analysis on this tab")
659
+ sound_pressure_file = st.file_uploader("Upload CSV or Excel file for current sound pressure levels",
660
+ type=['csv', 'xlsx'],
661
+ help='The file should have columns for frequencies 125, 250, 500, 1000, 2000, and 4000, and the first column should contain the names of the locations where sound pressure was measured.')
662
+
663
+ if sound_pressure_file:
664
+ df_sound_pressure = read_uploaded_file(sound_pressure_file, header=0, index_col=0)
665
+ df_sound_pressure = standardize_frequencies(df_sound_pressure)
666
+ st.session_state.df_sound_pressure = df_sound_pressure
667
+ if st.session_state.df_sound_pressure is not None:
668
+ st.session_state.df_sound_pressure.columns = [int(col) for col in
669
+ st.session_state.df_sound_pressure.columns]
670
+ st.session_state.frequencies = [125, 250, 500, 1000, 2000, 4000]
671
+ st.write("Current Sound Pressure Levels:")
672
+ st.dataframe(st.session_state.df_sound_pressure, use_container_width=True)
673
+
674
+ elif st.session_state.df_sound_pressure is not None:
675
+ st.write("Current Sound Pressure Levels:")
676
+ st.dataframe(st.session_state.df_sound_pressure, use_container_width=True)
677
+
678
+ st.write("#### Calculated current room sound absorption")
679
+ st.info('''The data below is a duplicate of the current room sound absorption calculated for reverberation time
680
+ analysis. It is provided here as a reminder of the existing materials in the room and their calculated sound
681
+ absorptions.''')
682
+ if st.session_state.df_current_absorption is not None:
683
+ st.dataframe(st.session_state.df_current_absorption, use_container_width=True)
684
+ else:
685
+ st.write("No data available for current room sound absorption. Please complete the previous steps.")
686
+
687
+ st.write("#### Editable new materials data")
688
+ st.info('''The editable table below is a duplicate of the new materials data from reverberation time
689
+ analysis. You can edit this table by adding new rows, deleting existing rows, or directly editing any
690
+ information in the table. Click check box on the left to delete a row. Hover over the table and click + at the
691
+ top or bottom to add new rows. Note that any changes made here will automatically update all the calculations
692
+ on this tab and also update the new materials data for reverberation time and other reverberation time
693
+ calculations that are connected to that data.''')
694
+
695
+ if st.session_state.df_new_materials is not None:
696
+ edited_df = st.data_editor(st.session_state.df_new_materials, num_rows="dynamic")
697
+ st.session_state.df_new_materials = edited_df
698
+
699
+ st.session_state.new_materials = []
700
+ for _, row in st.session_state.df_new_materials.iterrows():
701
+ material = {
702
+ 'name': row[0],
703
+ 'area': row[1],
704
+ 'coefficients': dict(zip(st.session_state.frequencies, row[2:].tolist()))
705
+ }
706
+ st.session_state.new_materials.append(material)
707
+
708
+ st.session_state.new_absorption = {freq: 0 for freq in st.session_state.frequencies}
709
+ absorption_data = []
710
+ for material in st.session_state.new_materials:
711
+ material_absorption = {'Material': material['name']}
712
+ for freq in st.session_state.frequencies:
713
+ absorption_value = material['coefficients'][freq] * material['area']
714
+ material_absorption[freq] = absorption_value
715
+ st.session_state.new_absorption[freq] += absorption_value
716
+ absorption_data.append(material_absorption)
717
+
718
+ total_absorption = {'Material': 'Total Absorption'}
719
+ for freq in st.session_state.frequencies:
720
+ total_absorption[freq] = st.session_state.new_absorption[freq]
721
+ absorption_data.append(total_absorption)
722
+
723
+ df_new_absorption = pd.DataFrame(absorption_data)
724
+ st.write("#### Calculated sound absorption based on new materials")
725
+ st.info('''The table below presents sound absorption calculated based on the information in the
726
+ Editable new materials data above''')
727
+ st.dataframe(df_new_absorption, use_container_width=True)
728
+ st.session_state.df_new_absorption = df_new_absorption.copy() # Save a copy of new absorption data
729
+ else:
730
+ st.write("No data available for new materials. Please upload new materials data.")
731
+
732
+ st.write("#### Calculated Noise Reduction")
733
+ if st.session_state.df_current_absorption is not None and st.session_state.df_new_absorption is not None:
734
+ current_total_absorption = st.session_state.df_current_absorption.loc[:,
735
+ st.session_state.frequencies].sum().sum()
736
+ new_total_absorption = st.session_state.df_new_absorption.loc[:, st.session_state.frequencies].sum().sum()
737
+ if current_total_absorption > 0:
738
+ noise_reduction = 10 * np.log10(new_total_absorption / current_total_absorption)
739
+ st.session_state.noise_reduction = noise_reduction
740
+ st.write(f"##### Noise Reduction: {noise_reduction:.4f} dB")
741
+ st.info('''The above noise reduction value is calculated based on total sound absorption for existing and new
742
+ material above. The noise reduction formula is NR = 10 * Log10 (S alpha after / S alpha before)
743
+ This formula calculates the reduction in pressure levels due to increased sound absorption.''')
744
+ else:
745
+ st.error("Current total absorption is zero, which is not possible. Please check your data.")
746
+ else:
747
+ st.write("No data available to calculate noise reduction. Please complete the previous steps.")
748
+
749
+ if st.session_state.df_sound_pressure is not None and 'noise_reduction' in st.session_state:
750
+ st.write("#### Updated Sound Pressure Levels")
751
+ st.info('''The values in the table below have been updated to account for the calculated noise reduction.
752
+ The noise reduction is subtracted directly from the original sound pressure levels without logarithmic conversion. Plot the
753
+ updated sound pressure levels on your speech intelligibility Dot chart.''')
754
+ updated_df = st.session_state.df_sound_pressure.copy()
755
+
756
+ # Ensure all values are numeric and fill NaN with 0
757
+ updated_df = updated_df.apply(pd.to_numeric, errors='coerce').fillna(0)
758
+
759
+ # Subtract noise reduction directly from each sound pressure level
760
+ updated_df = updated_df - st.session_state.noise_reduction
761
+
762
+ st.write("Updated Sound Pressure Levels:")
763
+ st.dataframe(updated_df, use_container_width=True)
764
+
765
+ # PDF Download Button
766
+ st.write("""
767
+ **IMPORTANT NOTE ABOUT PDF REPORT:** The purpose of the PDF report is to provide you detailed record of all
768
+ your input data and the graphs generated. Graphs in PDF report are of low resolutions. Hence, remember to download
769
+ individual graphs and tables to include in your report. Hover your mouse over a graph and several icons would
770
+ appear at the top right corner of the graph, click the first icon to download the graph. Repeat the same process
771
+ to download tables.
772
+ """)
773
+ if st.button("Download PDF Report"):
774
+ pdf = generate_pdf(
775
+ st.session_state.volume,
776
+ st.session_state.current_rt,
777
+ st.session_state.existing_materials,
778
+ {freq: st.session_state.min_rt_val for freq in st.session_state.frequencies},
779
+ {freq: st.session_state.max_rt_val for freq in st.session_state.frequencies},
780
+ st.session_state.desired_rt,
781
+ st.session_state.new_materials,
782
+ st.session_state.fig1,
783
+ st.session_state.fig2,
784
+ st.session_state.df_sound_pressure,
785
+ updated_df
786
+ )
787
+ st.download_button(label="Download PDF", data=pdf, file_name="Room_Acoustics_Report.pdf",
788
+ mime="application/pdf")
789
+
790
+ def display_faq_help():
791
+ st.write('''## FAQ / Help''')
792
+
793
+ faq_content = """
794
+ ### Frequently Asked Questions
795
+ **Q1: What should I do if the data upload fails?**
796
+ 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.
797
+ **Q2: How do I interpret the RT60 values?**
798
+ 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.
799
+ **Q3: Why is my calculated RT60 not within the standard range?**
800
+ 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.
801
+ **Q4: What should I do if the app does not accept my frequency columns?**
802
+ 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.
803
+ **Q5: How can I improve speech intelligibility in my room?**
804
+ 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.
805
+ **Q6: How can I save my analysis results?**
806
+ 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.
807
+ ### Troubleshooting Tips
808
+ - **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.
809
+ - **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.
810
+ - **App Performance**: If the app is running slowly, consider optimizing your data size and complexity. Large datasets or highly detailed input may impact performance.
811
+
812
+ """
813
+ st.markdown(faq_content)
814
+
815
+ # Main content display based on the current tab
816
+ if st.session_state.current_tab == "Instructions":
817
+ display_instructions()
818
+ elif st.session_state.current_tab == "Initial Data Entry":
819
+ display_initial_data_entry()
820
+ elif st.session_state.current_tab == "Initial RT60 Compliance Check":
821
+ display_initial_rt60_compliance_check()
822
+ elif st.session_state.current_tab == "Desired RT60":
823
+ display_desired_rt60()
824
+ elif st.session_state.current_tab == "Acoustic Treatment":
825
+ display_acoustic_treatment()
826
+ elif st.session_state.current_tab == "Final RT60 Compliance Check":
827
+ display_final_rt60_compliance_check()
828
+ elif st.session_state.current_tab == "Intelligibility Noise Reduction":
829
+ display_intelligibility_noise_reduction()
830
+ elif st.session_state.current_tab == "FAQ / Help":
831
+ display_faq_help()
832
+
833
+ # Navigation buttons
834
+ tab_order = [
835
+ "Instructions",
836
+ "Initial Data Entry",
837
+ "Initial RT60 Compliance Check",
838
+ "Desired RT60",
839
+ "Acoustic Treatment",
840
+ "Final RT60 Compliance Check",
841
+ "Intelligibility Noise Reduction",
842
+ "FAQ / Help"
843
+ ]
844
+
845
+ current_index = tab_order.index(st.session_state.current_tab)
846
+
847
+ col1, col2, col3 = st.columns(3)
848
+ if current_index > 0:
849
+ col1.button("Previous", on_click=switch_tab, args=(tab_order[current_index - 1],))
850
+ if current_index < len(tab_order) - 1:
851
+ col3.button("Next", on_click=switch_tab, args=(tab_order[current_index + 1],))
852
+
853
+ # Footer
854
+ st.write("---")
855
+ st.write("Developed by Dr Abdul-Manan Sadick, Deakin University, Australia, 2024.")