sadickam's picture
Update app.py
8c3a9e1 verified
import streamlit as st
import pandas as pd
import plotly.graph_objects as go
from fpdf import FPDF
import tempfile
import kaleido
import numpy as np
# Set page configuration
st.set_page_config(
page_icon="🏫",
initial_sidebar_state="expanded"
)
# Title and instructional information
st.title("🔊:blue[Building Acoustics Analysis (RT60)]")
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 for educational purposes and not intended for professional use.
""")
default_values = {
'current_tab': "Instructions",
'current_rt': {},
'frequencies': [],
'existing_materials': [],
'volume': 0.0,
'desired_rt': {},
'new_materials': [],
'df_current_rt': None,
'df_existing_materials': None,
'df_new_materials': None,
'min_rt_val': 0.0,
'max_rt_val': 0.0,
'new_absorption': {},
'fig1': None,
'fig2': None,
'df_sound_pressure': None,
'noise_reduction': None,
'df_current_absorption': None,
'df_new_absorption': None
}
for key, value in default_values.items():
if key not in st.session_state:
st.session_state[key] = value
# Helper functions
def standardize_frequencies(df):
"""Standardize frequency column names to numerical values."""
column_mapping = {
'125Hz': '125', '250Hz': '250', '500Hz': '500', '1000Hz': '1000', '1KHz': '1000', '2KHz': '2000', '4KHz': '4000'
}
# Apply the mapping and ensure columns are treated as strings
df.columns = [column_mapping.get(col, col) for col in df.columns]
df.columns = df.columns.astype(str)
# Replace and try to convert to numeric
new_columns = pd.to_numeric(df.columns.str.replace(' Hz', '').str.replace('KHz', '000'), errors='coerce')
# Create a list to hold the final column names
final_columns = []
for original, new in zip(df.columns, new_columns):
# Use original column name if conversion failed
if pd.isna(new):
final_columns.append(original)
else:
final_columns.append(new)
df.columns = final_columns
return df
def validate_data(df):
"""Basic validation of the uploaded data."""
if df.empty:
return False
# Check for numeric data in all columns except the first (which can be material names, etc.)
if not all(df.iloc[:, 1:].applymap(np.isreal).all()):
return False
# Check for non-negative values in numeric columns
if (df.iloc[:, 1:] < 0).any().any():
return False
return True
def calculate_absorption_area(volume, reverberation_time):
return 0.16 * volume / reverberation_time if reverberation_time else float('inf')
def generate_pdf(volume, current_rt, existing_materials, min_rt, max_rt, desired_rt, new_materials, fig1, fig2, df_sound_pressure, updated_df):
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.cell(200, 10, txt="Room Acoustics Analysis Report", ln=True, align="C")
pdf.cell(200, 10, txt=f"Room Volume: {volume:.2f} m³", ln=True)
# Summary and Recommendations
pdf.cell(200, 10, txt="Summary and Recommendations:", ln=True)
compliance_issues = [freq for freq in current_rt.keys() if not (min_rt[freq] <= current_rt[freq] <= max_rt[freq])]
if compliance_issues:
pdf.cell(200, 10, txt="Non-compliant frequencies found:", ln=True)
for freq in compliance_issues:
pdf.cell(200, 10, txt=f"{freq} Hz: {current_rt[freq]:.2f} s (out of standard range)", ln=True)
pdf.cell(200, 10, txt="Recommendation: Consider adding or modifying materials to bring RT60 within standard ranges.", ln=True)
else:
pdf.cell(200, 10, txt="All frequencies are within the standard RT60 range.", ln=True)
pdf.cell(200, 10, txt="No additional acoustic treatment is necessary.", ln=True)
pdf.cell(200, 10, txt="Current Reverberation Times (s):", ln=True)
for freq, rt in current_rt.items():
pdf.cell(200, 10, txt=f"{freq} Hz: {rt:.2f}", ln=True)
pdf.cell(200, 10, txt="Existing Materials and Absorption Coefficients:", ln=True)
for material in existing_materials:
pdf.cell(200, 10, txt=f"Material: {material['name']}, Area: {material['area']:.2f} m²", ln=True)
for freq, coeff in material['coefficients'].items():
pdf.cell(200, 10, txt=f"{freq} Hz: {coeff:.2f}", ln=True)
pdf.cell(200, 10, txt="Standard Reverberation Time Range (s):", ln=True)
for freq in min_rt.keys():
pdf.cell(200, 10, txt=f"{freq} Hz: {min_rt[freq]:.2f} - {max_rt[freq]:.2f}", ln=True)
pdf.cell(200, 10, txt="Desired Reverberation Times (s):", ln=True)
for freq, rt in desired_rt.items():
pdf.cell(200, 10, txt=f"{freq} Hz: {rt:.2f}", ln=True)
pdf.cell(200, 10, txt="New Materials and Absorption Coefficients:", ln=True)
for material in new_materials:
pdf.cell(200, 10, txt=f"Material: {material['name']}, Area: {material['area']:.2f} m²", ln=True)
for freq, coeff in material['coefficients'].items():
pdf.cell(200, 10, txt=f"{freq} Hz: {coeff:.2f}", ln=True)
# Save the figures as temporary files and add to the PDF
for fig, tmpfile in [(fig1, "fig1.png"), (fig2, "fig2.png")]:
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmpfile:
fig.write_image(tmpfile.name, engine='kaleido')
pdf.image(tmpfile.name, x=10, y=None, w=180)
# Add sound pressure levels data
pdf.add_page()
pdf.cell(200, 10, txt="Current Sound Pressure Levels (dB):", ln=True)
for index, row in df_sound_pressure.iterrows():
pdf.cell(200, 10, txt=f"{index}:", ln=True)
for col in df_sound_pressure.columns:
pdf.cell(200, 10, txt=f"{col} Hz: {row[col]:.2f}", ln=True)
# Add updated sound pressure levels data
pdf.cell(200, 10, txt="Updated Sound Pressure Levels (dB):", ln=True)
for index, row in updated_df.iterrows():
pdf.cell(200, 10, txt=f"{index}:", ln=True)
for col in updated_df.columns:
pdf.cell(200, 10, txt=f"{col} Hz: {row[col]:.2f}", ln=True)
return pdf.output(dest='S').encode('latin1')
def read_uploaded_file(uploaded_file, header=0, index_col=None):
try:
if uploaded_file.name.endswith('.csv'):
return pd.read_csv(uploaded_file, header=header, index_col=index_col)
elif uploaded_file.name.endswith('.xlsx'):
return pd.read_excel(uploaded_file, header=header, index_col=index_col)
except Exception as e:
st.error(f"Error reading file {uploaded_file.name}: {e}")
# Layout customizations
hide_menu_style = """
<style>
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
</style>
"""
st.markdown(hide_menu_style, unsafe_allow_html=True)
# Sidebar with navigation
def switch_tab(tab_name):
st.session_state.current_tab = tab_name
with st.sidebar:
for tab in ["Instructions", "Initial Data Entry", "Initial RT60 Compliance Check", "Desired RT60",
"Acoustic Treatment", "Final RT60 Compliance Check", "Intelligibility Noise Reduction", "FAQ / Help"]:
st.button(tab, on_click=switch_tab, args=(tab,))
# Display content based on selected tab in the main window
def display_instructions():
import pandas as pd
# Example DataFrames for input data
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')
instructions = """
## Introduction
Welcome to the Building Acoustics Analysis Tool. This application is designed to assist you in analyzing and resolving
reverberation time (RT60) issues and calculating noise reduction for improving speech intelligibility in a room. The
analysis leverages Sabine's equation for reverberation time analysis, which is crucial in determining the acoustic
characteristics of a space.
Please note that the app focuses on specific frequencies: 125 Hz, 250 Hz, 500 Hz, 1000 Hz, 2000 Hz, and 4000 Hz.
These frequencies are standard in acoustics analysis and will be the basis for all calculations and visualizations.
This app is intended for educational purposes and is not suitable for professional use.
## What is RT60?
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.
### Example of RT60 Calculation Using Sabine's Equation
Sabine's equation is used to calculate the RT60:
**RT60 = (0.16 * V) / A**
Where:
- **V** is the volume of the room in cubic meters (m³).
- **A** is the total sound absorption of the room, which depends on the surface areas and absorption coefficients of the materials present.
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:
**RT60 = (0.16 * 100) / 10 = 1.60 seconds**
## App Functionality
The Building Acoustics Analysis Tool provides the following functionalities:
1. **Initial Data Entry**: Upload and review initial acoustic data, including current reverberation times and existing materials.
2. **Initial RT60 Compliance Check**: Compare current RT60 values against standard ranges to determine compliance.
3. **Desired RT60**: Set desired RT60 values and calculate the required sound absorption to achieve these values.
4. **Acoustic Treatment**: Introduce new materials and calculate their impact on the room's acoustics.
5. **Final RT60 Compliance Check**: Verify that the new RT60 values are within the desired range after acoustic treatment.
6. **Intelligibility Noise Reduction**: Analyze noise reduction and its impact on sound pressure levels in the room.
## Instructions for Formatting Input Data
Please note that the number 0, 1, 2, .... in the first column of the examples below are similar to the default
Excel line numbers. Therefore, DO NOT number the first columns of your data files.
### Current Reverberation Times
- **File Format**: CSV or Excel
- **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.
**Example:**
"""
st.markdown(instructions)
st.write(df_current_reverberation_times)
instructions = """
### Existing Materials Absorption Coefficients and Areas
- **File Format**: CSV or Excel
- **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.
**Example:**
"""
st.markdown(instructions)
st.write(df_existing_materials)
instructions = """
### New Materials Absorption Coefficients and Areas
- **File Format**: CSV or Excel
- **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.
**Example:**
"""
st.markdown(instructions)
st.write(df_new_materials)
instructions = """
### Current Sound Pressure Levels
- **File Format**: CSV or Excel
- **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.
**Example:**
"""
st.markdown(instructions)
st.write(df_sound_pressure_levels)
instructions = """
## What Happens on Each Tab
### Instructions
This tab provides detailed instructions on how to format your input data files and general information about using the app.
### Initial Data Entry
Upload and review your initial acoustic data, including current reverberation times and existing materials data.
Ensure all input data has been provided correctly before proceeding.
### Initial RT60 Compliance Check
Compare your current RT60 values against standard ranges to determine if they are within acceptable limits.
If the values are not within the standard range, you will need to apply acoustic treatment.
### Desired RT60
Set your desired RT60 values for each frequency. The app will calculate the required sound absorption needed to
achieve these values.
### Acoustic Treatment
Introduce new materials and see their impact on the room's acoustics. Adjust the new materials data to try and
achieve the desired RT60 values.
### Final RT60 Compliance Check
Verify that the new RT60 values after acoustic treatment are within the desired range. If they are not, you may
need to adjust your materials and try again.
### Intelligibility Noise Reduction
Upload sound pressure levels and analyze the noise reduction achieved by the acoustic treatment. The app will
calculate updated sound pressure levels based on the noise reduction.
## General Tips
- **File Formats**: Ensure your input files are in CSV or Excel format.
- **Consistent Naming**: Keep column headings consistent and spelled correctly.
- **No Extra Data**: Avoid including any extra rows or columns outside of the specified format.
- **Check for Errors**: Verify there are no typographical errors in the column headings.
- **Repeat for Multiple Rooms**: If you need to analyze multiple rooms, repeat the process for each room individually.
- **Save Your Work**: Regularly download the PDF report after completing your analysis.
By following these instructions, you will be able to use the Building Acoustics Analysis Tool effectively and
obtain accurate acoustic analysis for your room. If you encounter any issues, refer to these instructions or
seek further assistance.
"""
st.markdown(instructions)
st.info("After reading the instructions, get your input data ready and proceed to the next step.")
def display_initial_data_entry():
st.write('''## Initial Data Entry''')
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''')
st.write("#### Upload current reverberation times")
current_rt_file = st.file_uploader("Upload CSV or Excel file for current reverberation times", type=['csv', 'xlsx'],
help='Go to Instructions on the sidebar for formatting information.')
if current_rt_file:
df_current_rt = read_uploaded_file(current_rt_file, header=0, index_col=None)
df_current_rt = standardize_frequencies(df_current_rt)
st.session_state.df_current_rt = df_current_rt
if st.session_state.df_current_rt is not None:
st.session_state.frequencies = st.session_state.df_current_rt.columns.tolist()
st.session_state.current_rt = dict(
zip(st.session_state.frequencies, st.session_state.df_current_rt.iloc[0].tolist()))
st.write("Current reverberation times:")
st.dataframe(st.session_state.df_current_rt, use_container_width=True)
elif st.session_state.df_current_rt is not None:
st.write("Current reverberation times:")
st.dataframe(st.session_state.df_current_rt, use_container_width=True)
st.write("#### Upload existing materials data")
existing_materials_file = st.file_uploader("Upload CSV or Excel file for existing materials", type=['csv', 'xlsx'],
help='Go to Instructions on the sidebar for formatting information.')
if existing_materials_file:
df_existing_materials = read_uploaded_file(existing_materials_file, header=0, index_col=None)
df_existing_materials = standardize_frequencies(df_existing_materials)
st.session_state.df_existing_materials = df_existing_materials
if st.session_state.df_existing_materials is not None:
st.write("Existing Materials Data:")
st.dataframe(st.session_state.df_existing_materials, use_container_width=True)
st.session_state.existing_materials = []
for _, row in st.session_state.df_existing_materials.iterrows():
material = {
'name': row[0],
'area': row[1],
'coefficients': dict(zip(st.session_state.frequencies, row[2:].tolist()))
}
st.session_state.existing_materials.append(material)
elif st.session_state.df_existing_materials is not None:
st.write("Existing Materials Data:")
st.dataframe(st.session_state.df_existing_materials, use_container_width=True)
st.write("#### Enter total room volume")
st.session_state.volume = float(st.number_input("Room Volume (m³):", min_value=0.0, step=0.01, format="%.2f",
key="room_volume", value=st.session_state.volume,
help='The calculated total volume of the room'))
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:
st.success("All input data has been successfully processed. Proceed to the next analysis step.")
else:
st.warning("Please ensure all input data has been provided correctly before proceeding.")
def display_initial_rt60_compliance_check():
st.write('''## Initial RT60 Compliance Check''')
st.write('''The aim of initial compliance check is to compare the current RT60 values to the
standard RT60 range. For the purpose of this tool, compliance is achieved if RT60 values for all frequencies are
within the standard range. The graph at the bottom of this page would assist you in verifying compliance.
If at least one frequency is not in the range, you would need to apply some acoustic treatment. See the
"Acoustic Treatment" tab.''')
st.write("#### Define standard reverberation time range")
st.session_state.min_rt_val = float(
st.number_input("Minimum Standard RT60 (s) for all frequencies:", min_value=0.0, step=0.01,
format="%.2f", key="min_rt", value=st.session_state.min_rt_val,
help='The minimum recommended RT60 in the applicable standard for your space type'))
st.session_state.max_rt_val = float(
st.number_input("Maximum Standard RT60 (s) for all frequencies:", min_value=0.0, step=0.01,
format="%.2f", key="max_rt", value=st.session_state.max_rt_val,
help='The maximum recommended RT60 in the applicable standard for your space type'))
min_rt = {freq: st.session_state.min_rt_val for freq in st.session_state.frequencies}
max_rt = {freq: st.session_state.max_rt_val for freq in st.session_state.frequencies}
if st.session_state.current_rt and st.session_state.existing_materials:
st.write("#### Calculated current room sound absorption")
st.write('''The sound absorptions in the table below are calculated based on the absorption coefficients and areas
of the existing materials in the room. You will compare total frequency values in this table to
the desired sound absorption on the Desired RT60 to inform your selection of new materials''')
current_absorption = {freq: 0 for freq in st.session_state.frequencies}
absorption_data = []
for material in st.session_state.existing_materials:
material_absorption = {'Material': material['name']}
for freq in st.session_state.frequencies:
absorption_value = material['coefficients'][freq] * material['area']
material_absorption[freq] = absorption_value
current_absorption[freq] += absorption_value
absorption_data.append(material_absorption)
total_absorption = {'Material': 'Total Absorption'}
for freq in st.session_state.frequencies:
total_absorption[freq] = current_absorption[freq]
absorption_data.append(total_absorption)
df_current_absorption = pd.DataFrame(absorption_data)
st.dataframe(df_current_absorption, use_container_width=True)
st.session_state.df_current_absorption = df_current_absorption.copy() # Save a copy of current absorption data
# Graph of Current RT vs. Standard Range
fig1 = go.Figure()
fig1.add_trace(go.Scatter(x=st.session_state.frequencies,
y=[st.session_state.current_rt[freq] for freq in st.session_state.frequencies],
mode='lines+markers',
name='Current RT'))
fig1.add_trace(
go.Scatter(x=st.session_state.frequencies, y=[min_rt[freq] for freq in st.session_state.frequencies],
mode='lines', name='Min Standard RT',
line=dict(dash='dash')))
fig1.add_trace(
go.Scatter(x=st.session_state.frequencies, y=[max_rt[freq] for freq in st.session_state.frequencies],
mode='lines', name='Max Standard RT',
line=dict(dash='dash')))
fig1.add_trace(
go.Scatter(x=st.session_state.frequencies, y=[min_rt[freq] for freq in st.session_state.frequencies],
fill='tonexty', mode='none',
fillcolor='rgba(0,100,80,0.2)', showlegend=False))
fig1.update_layout(title='Current RT vs. Standard Range', xaxis_title='Frequency (Hz)',
yaxis_title='Reverberation Time (s)')
st.plotly_chart(fig1)
st.session_state.fig1 = fig1
compliant = all(min_rt[freq] <= st.session_state.current_rt[freq] for freq in st.session_state.frequencies)
compliant = compliant and all(
st.session_state.current_rt[freq] <= max_rt[freq] for freq in st.session_state.frequencies)
if compliant:
st.success("All RT60 values are within the standard range. Proceed to the next step.")
else:
st.warning(
"Some RT60 values are outside the standard range. You need to apply acoustic treatment in the next step.")
else:
st.warning("Please provide the current reverberation times and existing materials data before proceeding.")
def display_desired_rt60():
st.write('''## Desired RT60''')
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 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.frequencies and st.session_state.min_rt_val and st.session_state.max_rt_val:
st.write("#### Set desired reverberation time")
min_rt = {freq: st.session_state.min_rt_val for freq in st.session_state.frequencies}
max_rt = {freq: st.session_state.max_rt_val for freq in st.session_state.frequencies}
valid_rt = True
for freq in st.session_state.frequencies:
st.session_state.desired_rt[freq] = st.number_input(f"Desired RT at {freq} Hz (s):", min_value=0.01,
step=0.01,
format="%.2f", key=f"desired_rt_{freq}",
value=st.session_state.desired_rt.get(freq, 0.01),
help='''The RT60 value you wish to achieve. This value must
be within the range of the standard RT60 for your space and
can be the same or different for each frequency''')
if not (min_rt[freq] <= st.session_state.desired_rt[freq] <= max_rt[freq]):
valid_rt = False
st.write("##### Desired sound absorption based on desired RT60")
desired_absorption_area = {
freq: calculate_absorption_area(st.session_state.volume, st.session_state.desired_rt[freq]) for freq in
st.session_state.frequencies}
df_desired_absorption = pd.DataFrame([desired_absorption_area], columns=st.session_state.frequencies,
index=['Desired Absorption Area'])
st.dataframe(df_desired_absorption, use_container_width=True)
if valid_rt and all(st.session_state.desired_rt[freq] > 0 for freq in st.session_state.frequencies):
st.success("Desired RT60 values have been set correctly. Proceed to the next tab for acoustic treatment.")
elif not valid_rt:
st.error("Some desired RT60 values are not within the standard range. Please adjust the values.")
else:
st.warning("Desired RT60 values cannot be zero. Please provide valid values.")
else:
st.warning("Please complete the previous steps before proceeding to set the desired RT60 values.")
def display_acoustic_treatment():
st.write("""## Acoustic Treatment""")
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
is 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.
""")
st.write("#### Upload new materials data")
new_materials_file = st.file_uploader("Upload CSV or Excel file for new materials", type=['csv', 'xlsx'],
help='Go to Instructions on the sidebar for formatting information.')
if new_materials_file:
df_new_materials = read_uploaded_file(new_materials_file, header=0, index_col=None)
df_new_materials = standardize_frequencies(df_new_materials)
st.session_state.df_new_materials = df_new_materials
if st.session_state.df_new_materials is not None:
st.write("New materials data:")
st.dataframe(st.session_state.df_new_materials, use_container_width=True)
st.session_state.new_materials = []
for _, row in st.session_state.df_new_materials.iterrows():
material = {
'name': row[0],
'area': row[1],
'coefficients': dict(zip(st.session_state.frequencies, row[2:].tolist()))
}
st.session_state.new_materials.append(material)
elif st.session_state.df_new_materials is not None:
st.write("New materials data:")
st.dataframe(st.session_state.df_new_materials, use_container_width=True)
if st.session_state.df_new_materials is not None:
st.write("#### Edit new materials data")
st.info(
"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.")
edited_df = st.data_editor(st.session_state.df_new_materials, num_rows="dynamic")
st.session_state.df_new_materials = edited_df
st.session_state.new_materials = []
for _, row in st.session_state.df_new_materials.iterrows():
material = {
'name': row[0],
'area': row[1],
'coefficients': dict(zip(st.session_state.frequencies, row[2:].tolist()))
}
st.session_state.new_materials.append(material)
if st.session_state.new_materials and st.session_state.frequencies:
st.session_state.new_absorption = {freq: 0 for freq in st.session_state.frequencies}
absorption_data = []
for material in st.session_state.new_materials:
material_absorption = {'Material': material['name']}
for freq in st.session_state.frequencies:
absorption_value = material['coefficients'][freq] * material['area']
material_absorption[freq] = absorption_value
st.session_state.new_absorption[freq] += absorption_value
absorption_data.append(material_absorption)
total_absorption = {'Material': 'Total Absorption'}
for freq in st.session_state.frequencies:
total_absorption[freq] = st.session_state.new_absorption[freq]
absorption_data.append(total_absorption)
df_new_absorption = pd.DataFrame(absorption_data)
st.write("#### Calculated sound absorption based on new materials")
st.write('''The total sound absorption for each frequency must be equal to or very close to the desired sound absorption
(see Desired RT60 tab) to increase your chances of achieving the desired RT60.''')
st.dataframe(df_new_absorption, use_container_width=True)
st.session_state.df_new_absorption = df_new_absorption.copy() # Save a copy of new absorption data
st.success("New materials data has been processed. Proceed to the final RT60 compliance check.")
else:
st.warning("Please upload new materials data before proceeding.")
def display_final_rt60_compliance_check():
st.write("""## Final RT60 Compliance Check""")
st.write("""This is the last step in the RT60 analysis. To pass the final compliance check, the new RT60 for each
frequency must be within the standard RT60 range. If compliance fails, you need to go back to the Acoustic Treatment
stage to revise your materials. Update your new materials spreadsheet and upload on the Acoustic Treatment tab.
""")
if st.session_state.new_absorption and st.session_state.frequencies:
min_rt = {freq: st.session_state.min_rt_val for freq in st.session_state.frequencies}
max_rt = {freq: st.session_state.max_rt_val for freq in st.session_state.frequencies}
st.write("#### Calculated new reverberation times")
new_rt = {freq: calculate_absorption_area(st.session_state.volume, st.session_state.new_absorption[freq]) for
freq in st.session_state.frequencies}
df_new_rt = pd.DataFrame([new_rt], columns=st.session_state.frequencies, index=['New Reverberation Time'])
st.dataframe(df_new_rt, use_container_width=True)
# Graph of Current and New RT vs. Standard Range
fig2 = go.Figure()
fig2.add_trace(go.Scatter(x=st.session_state.frequencies,
y=[st.session_state.current_rt[freq] for freq in st.session_state.frequencies],
mode='lines+markers',
name='Current RT'))
fig2.add_trace(
go.Scatter(x=st.session_state.frequencies, y=[new_rt[freq] for freq in st.session_state.frequencies],
mode='lines+markers', name='New RT'))
fig2.add_trace(
go.Scatter(x=st.session_state.frequencies, y=[min_rt[freq] for freq in st.session_state.frequencies],
mode='lines', name='Min Standard RT',
line=dict(dash='dash')))
fig2.add_trace(
go.Scatter(x=st.session_state.frequencies, y=[max_rt[freq] for freq in st.session_state.frequencies],
mode='lines', name='Max Standard RT',
line=dict(dash='dash')))
fig2.add_trace(
go.Scatter(x=st.session_state.frequencies, y=[min_rt[freq] for freq in st.session_state.frequencies],
fill='tonexty', mode='none',
fillcolor='rgba(0,100,80,0.2)', showlegend=False))
fig2.update_layout(title='Current RT60 and New RT60 vs. Standard Range', xaxis_title='Frequency (Hz)',
yaxis_title='Reverberation Time (s)')
st.plotly_chart(fig2)
st.session_state.fig2 = fig2 # Save fig2 in session state
st.success(
"After reflecting on the results, decide what to do next based on the expected outcome specified in your project brief.")
else:
st.warning("Please complete the previous steps before proceeding to the final RT60 compliance check.")
def display_intelligibility_noise_reduction():
st.write('''## Intelligibility Noise Reduction''')
st.write('''On this tab, you will calculate noise reduction using existing and new materials sound absorption
coefficients and surface areas that were provided for reverberation time analysis. The relevant data
have copied to this tab for ease of reference. Note that you can update the new materials data by adding new rows
or deleting existing rows. Your can also directly edit the current new materials data information. All updates
will lead to updating relevant processes on this tab. Note that changes made to the new materials data
on this tab will also update the new materials data for reverberation time given that the analysis is for the
same room''')
st.write("#### Upload current sound pressure levels")
st.warning("##### Upload current sound pressure level data to complete the analysis on this tab")
sound_pressure_file = st.file_uploader("Upload CSV or Excel file for current sound pressure levels",
type=['csv', 'xlsx'],
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.')
if sound_pressure_file:
df_sound_pressure = read_uploaded_file(sound_pressure_file, header=0, index_col=0)
df_sound_pressure = standardize_frequencies(df_sound_pressure)
st.session_state.df_sound_pressure = df_sound_pressure
if st.session_state.df_sound_pressure is not None:
st.session_state.df_sound_pressure.columns = [int(col) for col in
st.session_state.df_sound_pressure.columns]
st.session_state.frequencies = [125, 250, 500, 1000, 2000, 4000]
st.write("Current Sound Pressure Levels:")
st.dataframe(st.session_state.df_sound_pressure, use_container_width=True)
elif st.session_state.df_sound_pressure is not None:
st.write("Current Sound Pressure Levels:")
st.dataframe(st.session_state.df_sound_pressure, use_container_width=True)
st.write("#### Calculated current room sound absorption")
st.info('''The data below is a duplicate of the current room sound absorption calculated for reverberation time
analysis. It is provided here as a reminder of the existing materials in the room and their calculated sound
absorptions.''')
if st.session_state.df_current_absorption is not None:
st.dataframe(st.session_state.df_current_absorption, use_container_width=True)
else:
st.write("No data available for current room sound absorption. Please complete the previous steps.")
st.write("#### Editable new materials data")
st.info('''The editable table below is a duplicate of the new materials data from reverberation time
analysis. You can edit this table by adding new rows, deleting existing rows, or directly editing any
information in the table. Click check box on the left to delete a row. Hover over the table and click + at the
top or bottom to add new rows. Note that any changes made here will automatically update all the calculations
on this tab and also update the new materials data for reverberation time and other reverberation time
calculations that are connected to that data.''')
if st.session_state.df_new_materials is not None:
edited_df = st.data_editor(st.session_state.df_new_materials, num_rows="dynamic")
st.session_state.df_new_materials = edited_df
st.session_state.new_materials = []
for _, row in st.session_state.df_new_materials.iterrows():
material = {
'name': row[0],
'area': row[1],
'coefficients': dict(zip(st.session_state.frequencies, row[2:].tolist()))
}
st.session_state.new_materials.append(material)
st.session_state.new_absorption = {freq: 0 for freq in st.session_state.frequencies}
absorption_data = []
for material in st.session_state.new_materials:
material_absorption = {'Material': material['name']}
for freq in st.session_state.frequencies:
absorption_value = material['coefficients'][freq] * material['area']
material_absorption[freq] = absorption_value
st.session_state.new_absorption[freq] += absorption_value
absorption_data.append(material_absorption)
total_absorption = {'Material': 'Total Absorption'}
for freq in st.session_state.frequencies:
total_absorption[freq] = st.session_state.new_absorption[freq]
absorption_data.append(total_absorption)
df_new_absorption = pd.DataFrame(absorption_data)
st.write("#### Calculated sound absorption based on new materials")
st.info('''The table below presents sound absorption calculated based on the information in the
Editable new materials data above''')
st.dataframe(df_new_absorption, use_container_width=True)
st.session_state.df_new_absorption = df_new_absorption.copy() # Save a copy of new absorption data
else:
st.write("No data available for new materials. Please upload new materials data.")
st.write("#### Calculated Noise Reduction")
if st.session_state.df_current_absorption is not None and st.session_state.df_new_absorption is not None:
current_total_absorption = st.session_state.df_current_absorption.loc[:,
st.session_state.frequencies].sum().sum()
new_total_absorption = st.session_state.df_new_absorption.loc[:, st.session_state.frequencies].sum().sum()
if current_total_absorption > 0:
noise_reduction = 10 * np.log10(new_total_absorption / current_total_absorption)
st.session_state.noise_reduction = noise_reduction
st.write(f"##### Noise Reduction: {noise_reduction:.4f} dB")
st.info('''The above noise reduction value is calculated based on total sound absorption for existing and new
material above. The noise reduction formula is NR = 10 * Log10 (S alpha after / S alpha before)
This formula calculates the reduction in pressure levels due to increased sound absorption.''')
else:
st.error("Current total absorption is zero, which is not possible. Please check your data.")
else:
st.write("No data available to calculate noise reduction. Please complete the previous steps.")
if st.session_state.df_sound_pressure is not None and 'noise_reduction' in st.session_state:
st.write("#### Updated Sound Pressure Levels")
st.info('''The values in the table below have been updated to account for the calculated noise reduction.
The noise reduction is subtracted directly from the original sound pressure levels without logarithmic conversion. Plot the
updated sound pressure levels on your speech intelligibility Dot chart.''')
updated_df = st.session_state.df_sound_pressure.copy()
# Ensure all values are numeric and fill NaN with 0
updated_df = updated_df.apply(pd.to_numeric, errors='coerce').fillna(0)
# Subtract noise reduction directly from each sound pressure level
updated_df = updated_df - st.session_state.noise_reduction
st.write("Updated Sound Pressure Levels:")
st.dataframe(updated_df, use_container_width=True)
# PDF Download Button
st.write("""
**IMPORTANT NOTE ABOUT PDF REPORT:** The purpose of the PDF report is to provide you detailed record of all
your input data and the graphs generated. Graphs in PDF report are of low resolutions. Hence, remember to download
individual graphs and tables to include in your report. Hover your mouse over a graph and several icons would
appear at the top right corner of the graph, click the first icon to download the graph. Repeat the same process
to download tables.
""")
if st.button("Download PDF Report"):
pdf = generate_pdf(
st.session_state.volume,
st.session_state.current_rt,
st.session_state.existing_materials,
{freq: st.session_state.min_rt_val for freq in st.session_state.frequencies},
{freq: st.session_state.max_rt_val for freq in st.session_state.frequencies},
st.session_state.desired_rt,
st.session_state.new_materials,
st.session_state.fig1,
st.session_state.fig2,
st.session_state.df_sound_pressure,
updated_df
)
st.download_button(label="Download PDF", data=pdf, file_name="Room_Acoustics_Report.pdf",
mime="application/pdf")
def display_faq_help():
st.write('''## 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)
# Main content display based on the current tab
if st.session_state.current_tab == "Instructions":
display_instructions()
elif st.session_state.current_tab == "Initial Data Entry":
display_initial_data_entry()
elif st.session_state.current_tab == "Initial RT60 Compliance Check":
display_initial_rt60_compliance_check()
elif st.session_state.current_tab == "Desired RT60":
display_desired_rt60()
elif st.session_state.current_tab == "Acoustic Treatment":
display_acoustic_treatment()
elif st.session_state.current_tab == "Final RT60 Compliance Check":
display_final_rt60_compliance_check()
elif st.session_state.current_tab == "Intelligibility Noise Reduction":
display_intelligibility_noise_reduction()
elif st.session_state.current_tab == "FAQ / Help":
display_faq_help()
# Navigation buttons
tab_order = [
"Instructions",
"Initial Data Entry",
"Initial RT60 Compliance Check",
"Desired RT60",
"Acoustic Treatment",
"Final RT60 Compliance Check",
"Intelligibility Noise Reduction",
"FAQ / Help"
]
current_index = tab_order.index(st.session_state.current_tab)
col1, col2, col3 = st.columns(3)
if current_index > 0:
col1.button("Previous", on_click=switch_tab, args=(tab_order[current_index - 1],))
if current_index < len(tab_order) - 1:
col3.button("Next", on_click=switch_tab, args=(tab_order[current_index + 1],))
# Footer
st.write("---")
st.write("Project Team: Dr Abdul-Manan Sadick and Dr Majed Abu Seif, Deakin University, Australia, 2024.")