tyre / app.py
SHELLAPANDIANGANHUNGING's picture
Update app.py
c7fd793 verified
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import folium
from streamlit_folium import st_folium
from sklearn.linear_model import LinearRegression
import os
# ================= CONFIG =================
st.set_page_config(
page_title="Michelin Mining Tyre Analytics",
page_icon="",
layout="wide",
initial_sidebar_state="expanded"
)
# ================= CUSTOM CSS
st.markdown("""
<style>
/* ================= ROOT & COLORS ================= */
:root {
--michelin-blue: #003A8F;
--surface: #FFFFFF;
--surface-alt: #F9FAFB;
--text-dark: #1F2D3D;
--text-muted: #6C757D;
--border: #E9ECEF;
--shadow-sm: 0 2px 6px rgba(0,0,0,0.04);
--shadow: 0 6px 16px rgba(0,0,0,0.06);
--accent-yellow: #FFD100;
--filter-bg: #F5F7FA;
}
/* ================= GLOBAL TYPOGRAPHY & ALIGNMENT ================= */
.stApp {
background-color: var(--surface);
font-family: 'Segoe UI', system-ui, sans-serif;
color: var(--text-dark);
}
/* Force center alignment for ALL headings */
h1, h2, h3, h4, h5, h6,
.stMarkdown, .stText, p, div[data-testid="stMarkdownContainer"],
label, .stSelectbox label, .stMultiselect label, .stCheckbox label {
text-align: center !important;
}
/* Fix bullet/number list centering */
.stMarkdown ul, .stMarkdown ol {
text-align: left !important;
margin-left: auto;
margin-right: auto;
max-width: 800px;
}
/* ================= SIDEBAR (Power BI Style) ================= */
[data-testid="stSidebar"] {
background: var(--filter-bg) !important;
color: var(--text-dark);
padding: 20px 12px;
}
[data-testid="stSidebar"] h3 {
color: var(--michelin-blue);
font-weight: 700;
margin-bottom: 12px;
}
/* Power BI-style dropdowns */
[data-testid="stSelectbox"] div[data-baseweb="select"],
[data-testid="stMultiselect"] div[data-baseweb="select"] {
background-color: white !important;
border-radius: 8px !important;
border: 1px solid var(--border) !important;
box-shadow: var(--shadow-sm);
padding: 6px 10px !important;
min-height: 40px !important;
}
[data-testid="stSelectbox"] div[data-baseweb="select"] > div,
[data-testid="stMultiselect"] div[data-baseweb="select"] > div {
color: var(--text-dark) !important;
font-weight: 500;
}
/* Remove red tags from multiselect */
[data-testid="stMultiselect"] div[data-baseweb="select"] .stMultiSelectTag {
display: none !important;
}
/* Submit button */
[data-testid="stSidebar"] .stButton > button {
width: 100%;
background: var(--accent-yellow);
color: var(--michelin-blue);
font-weight: 700;
border-radius: 10px;
padding: 12px 0;
margin-top: 16px;
box-shadow: var(--shadow);
border: none;
font-size: 1.05rem;
}
[data-testid="stSidebar"] .stButton > button:hover {
background: #FFC107;
transform: translateY(-1px);
box-shadow: 0 8px 16px rgba(0,0,0,0.12);
}
/* ================= HEADER ================= */
.main-header h1 {
font-size: 2.4rem;
margin-bottom: 6px;
font-weight: 800;
color: var(--michelin-blue);
}
.main-header p {
font-size: 1.15rem;
color: var(--text-muted);
margin-top: 0;
}
/* ================= OBJECTIVE TITLE (NO BACKGROUND BOX) ================= */
.objective-title {
text-align: center !important;
font-size: 1.6rem;
font-weight: 800;
color: var(--michelin-blue);
margin: 40px 0 24px 0;
}
/* ================= INSIGHT LLM-STYLE (Like Screenshot) ================= */
.insight-box {
background: var(--surface-alt);
border: 1px solid var(--border);
border-radius: 12px;
padding: 20px;
box-shadow: var(--shadow-sm);
margin: 20px 0 30px 0;
position: relative;
display: flex;
align-items: flex-start;
gap: 12px;
}
.insight-box .content {
flex: 1;
font-size: 1.05rem;
line-height: 1.65;
color: var(--text-dark);
text-align: left;
}
.insight-box .tag {
position: absolute;
top: 12px;
right: 16px;
background: var(--michelin-blue);
color: white;
font-size: 0.85rem;
font-weight: 700;
padding: 6px 12px;
border-radius: 8px;
letter-spacing: 0.5px;
}
/* ================= PLOTLY ================= */
.plotly-graph-div {
border-radius: 12px;
overflow: hidden;
box-shadow: var(--shadow-sm);
border: 1px solid var(--border);
}
/* ================= FOOTER ================= */
.footer {
text-align: center;
font-size: 0.9rem;
color: var(--text-muted);
margin-top: 50px;
padding: 20px 0;
border-top: 1px solid var(--border);
}
/* ================= STREAMLIT TWEAKS ================= */
div.block-container {
padding-top: 2rem;
}
section[data-testid="stSidebar"] {
width: 280px !important;
min-width: 280px !important;
}
</style>
""", unsafe_allow_html=True)
# ================= LOAD DATA =================
@st.cache_data
def load_data():
try:
df = pd.read_excel("df_final.xlsx", sheet_name="Sheet1")
except FileNotFoundError:
st.error("❌ File `df_final.xlsx` not found. Please ensure it's in the same directory.")
st.stop()
# Fix encoding (e.g., '°C' β†’ 'Β°C')
df.columns = df.columns.str.replace("Γ‚", "")
for col in df.select_dtypes(include='object').columns:
df[col] = df[col].astype(str).str.replace("Γ‚", "")
# Parse datetime
df['Time'] = pd.to_datetime(df['Time'], errors='coerce')
df = df.dropna(subset=['Time'])
df['hour'] = df['Time'].dt.hour
# Alarm flag
df['is_alarm'] = (~df['Alarm Status'].str.contains('No Alarm', na=False)).astype(int)
# Dynamic risk score
p = df['Pressure (psi)']
p_red_high = df['Red High Press (psi)']
p_amber_high = df['Amber High Press (psi)']
t = df['Temperature (Β°C)']
t_red = df['Absolute Red Temp (Β°C)']
t_amber = df['Absolute Amber Temp (Β°C)']
p_norm = np.clip((p - p_amber_high) / (p_red_high - p_amber_high), 0, 1)
t_norm = np.clip((t - t_amber) / (t_red - t_amber), 0, 1)
df['risk_score'] = 0.6 * p_norm + 0.4 * t_norm
def get_risk_label(score):
if score >= 0.8: return 'Very High Risk'
elif score >= 0.6: return 'High Risk'
elif score >= 0.3: return 'Moderate Risk'
else: return 'Slight Risk'
df['Risk Level'] = df['risk_score'].apply(get_risk_label)
# Add Position Group
df['Position Group'] = df['Position'].apply(lambda x: 'Front' if x in [1, 2] else 'Rear')
return df
df = load_data()
col1, col2, col3 = st.columns([1.5, 6, 1.5]) # Increased side column width
with col1:
st.markdown("""
<div style="display:flex; align-items:center; justify-content:center; height:100%; padding:5px;">
<img src="https://huggingface.co/spaces/bukittechnology/tyre/resolve/main/btech2.png"
style="max-width:120px; height:auto; object-fit:contain;">
</div>
""", unsafe_allow_html=True)
with col2:
st.markdown("""
<div style="text-align:center; font-family:Arial, sans-serif; padding:2px 0;">
<h1 style="color:#154D9C; font-weight:bold; margin:0; line-height:1.3;">
Tyre Pressure Monitoring System (TPMS) Analytics<br>for Mining Equipments
</h1>
<p style="font-size:12px; color:#7d7d7d; margin:8px 0 0 0;">
Daily trend insights derived from 13–16 December 2023 data
</p>
</div>
""", unsafe_allow_html=True)
with col3:
st.markdown("""
<div style="display:flex; align-items:center; justify-content:center; height:100%; padding:5px;">
<img src="https://huggingface.co/spaces/bukittechnology/tyre/resolve/main/logo.png"
style="max-width:120px; height:auto; object-fit:contain;">
</div>
""", unsafe_allow_html=True)
# ================= SIDEBAR FILTERS =================
with st.sidebar:
st.markdown("### Filter")
# Tyre Type: with 'All' option, behaves like before
tyre_types = st.selectbox(
"Tyre Type", options=['All'] + sorted(df['Tyre Type'].dropna().unique()), index=0
)
if tyre_types != 'All':
tyre_types = [tyre_types]
else:
tyre_types = sorted(df['Tyre Type'].dropna().unique())
# Date: behaves like Tyre Type β€” show 'All' by default
date_options = sorted(df['date'].astype(str).unique())
dates_selected = st.selectbox(
"Date", options=['All'] + date_options, index=0
)
if dates_selected != 'All':
dates = [dates_selected]
else:
dates = date_options
# Zone: behaves like Tyre Type β€” show 'All' by default
zone_options = sorted(df['Zone'].dropna().unique())
zones_selected = st.selectbox(
"Zone", options=['All'] + zone_options, index=0
)
if zones_selected != 'All':
zones = [zones_selected]
else:
zones = zone_options
# Position: behaves like Tyre Type β€” show 'All' by default
pos_options = sorted(df['Position'].astype(int).dropna().unique())
positions_selected = st.selectbox(
"Position", options=['All'] + pos_options, index=0
)
if positions_selected != 'All':
positions = [positions_selected]
else:
positions = pos_options
# Alarm Status: behaves like Tyre Type β€” show 'All' by default
alarm_options = ["No Alarm", "Red High Pressure"]
alarms_selected = st.selectbox(
"Alarm Status", options=['All'] + alarm_options, index=0
)
if alarms_selected != 'All':
alarms = [alarms_selected]
else:
alarms = alarm_options
# Jam: Slider jam (00:00–23:00)
jam_range = st.slider(
"Jam",
min_value=0,
max_value=23,
value=(0, 23), # Default: semua jam
format="%02d:00"
)
submit = st.button("Submit")
# Apply filters
if submit:
dff = df.copy()
if dates: dff = dff[dff['date'].astype(str).isin(dates)]
if zones: dff = dff[dff['Zone'].isin(zones)]
if positions: dff = dff[dff['Position'].astype(int).isin(positions)]
if tyre_types: dff = dff[dff['Tyre Type'].isin(tyre_types)]
if alarms: dff = dff[dff['Alarm Status'].isin(alarms)]
# Tambahkan filter jam
dff = dff[dff['hour'].between(jam_range[0], jam_range[1], inclusive='both')]
else:
dff = df
dff = dff.copy()
dff['Position'] = pd.Categorical(dff['Position'], categories=[1, 2, 3, 4], ordered=True)
# Optional: Use descriptive labels (if desired)
position_labels = {
1: '1: Front 1',
2: '2: Front 2',
3: '3: Rear 3',
4: '4: Rear 4'
}
# Or keep as just '1', '2'... if minimal
# position_labels = {1: '1', 2: '2', 3: '3', 4: '4'}
dff['Position_Label'] = dff['Position'].map(position_labels)
st.markdown('<h3 class="objective-title">OBJECTIVE 1: Pressure & Temperature Trends β€” How Do Front and Rear Tyres Distribute?</h3>', unsafe_allow_html=True)
col2, col1 = st.columns(2)
# Define consistent color mapping
color_map = {1: '#003DA5', 2: '#7FA6E8', 3: '#3F7F73', 4: '#8EC3B7'}
category_order = [1, 2, 3, 4]
with col1:
st.markdown('<h5 style="text-align:center; margin-top: 0;">Pressure Distribution per Tyre Position</h5>', unsafe_allow_html=True)
fig1 = px.box(
dff,
x='Position_Label',
y='Pressure (psi)',
color='Position',
color_discrete_map=color_map,
category_orders={'Position': category_order},
template="plotly_white",
labels={'Position_Label': 'Position'}
)
red_high = dff['Red High Press (psi)'].min()
amber_high = dff['Amber High Press (psi)'].min()
# fig1.add_hline(y=red_high, line_dash="dash", line_color="red", annotation_text="Red High Press", annotation_position="top right")
# fig1.add_hline(y=amber_high, line_color="orange", annotation_text="Amber High Press", annotation_position="bottom right")
fig1.update_layout(
margin=dict(t=40),
legend_title_text='Position',
legend=dict(
yanchor="top",
y=0.99,
xanchor="left",
x=1.02 # Place legend outside plot to avoid overlap
)
)
st.plotly_chart(fig1, use_container_width=True)
with col2:
st.markdown('<h5 style="text-align:center; margin-top: 0;">Temperature Distribution per Tyre Position</h5>', unsafe_allow_html=True)
fig2 = px.box(
dff,
x='Position_Label',
y='Temperature (Β°C)',
color='Position',
color_discrete_map=color_map,
category_orders={'Position': category_order},
template="plotly_white",
labels={'Position_Label': 'Position'}
)
red_temp = dff['Absolute Red Temp (Β°C)'].min()
amber_temp = dff['Absolute Amber Temp (Β°C)'].min()
# fig2.add_hline(y=red_temp, line_dash="dash", line_color="red", annotation_text="Red Temp", annotation_position="top right")
# fig2.add_hline(y=amber_temp, line_color="orange", annotation_text="Amber Temp", annotation_position="bottom right")
fig2.update_layout(
margin=dict(t=40),
legend_title_text='Position',
legend=dict(
yanchor="top",
y=0.99,
xanchor="left",
x=1.02
)
)
st.plotly_chart(fig2, use_container_width=True)
# Insight 1 β€” Fisika & Mekanikal
front_pressure_avg = dff[dff['Position'].isin([1, 2])]['Pressure (psi)'].mean()
rear_pressure_avg = dff[dff['Position'].isin([3, 4])]['Pressure (psi)'].mean()
front_temp_avg = dff[dff['Position'].isin([1, 2])]['Temperature (Β°C)'].mean()
rear_temp_avg = dff[dff['Position'].isin([3, 4])]['Temperature (Β°C)'].mean()
# Fisika: Tekanan rendah β†’ deformasi besar β†’ hysteresis β†’ panas lebih banyak
# Mekanikal: Ban depan tanggung beban pengereman & kemudi β†’ stres lebih tinggi
if front_pressure_avg < rear_pressure_avg and front_temp_avg > rear_temp_avg:
insight_text = f"""
Rear tyres have higher pressure because they have higher specifications (10.00 R20 vs 11.00 R20)
"""
elif front_pressure_avg > rear_pressure_avg and front_temp_avg < rear_temp_avg:
insight_text = f"""
Front tyres: Higher pressure ({front_pressure_avg:.1f} psi) reduces deformation, lower heat ({front_temp_avg:.1f}Β°C), less mechanical stress. Rear tyres: Lower pressure ({rear_pressure_avg:.1f} psi) increases deformation, higher heat ({rear_temp_avg:.1f}Β°C) potential overloading or misalignment.
"""
else:
insight_text = f"""
Front tyres: Pressure {front_pressure_avg:.1f} psi, temperature {front_temp_avg:.1f}Β°C β†’ stable under current load/pressure balance. Rear tyres: Pressure {rear_pressure_avg:.1f} psi, temperature {rear_temp_avg:.1f}Β°C β†’ balanced operation.
"""
st.markdown(f"""
<div class="insight-box">
<div class="content">
{insight_text.strip()}
</div>
</div>
""", unsafe_allow_html=True)
####obejctic=ve 2
st.markdown("""
<h3 class="objective-title">OBJECTIVE 2: Shift and Tyre Position - How Are Alarms Concentrated Across Shifts and Tyres?</h3>
""", unsafe_allow_html=True)
# Filter semua data (termasuk alarm normal)
alarm_data = dff.copy()
# Buat 2 baris Γ— 4 kolom
col1, col2, col3, col4 = st.columns(4)
col5, col6, col7, col8 = st.columns(4)
# Fungsi helper untuk membuat radial chart per posisi dan shift
def create_radial_chart(pos_data, title, shift_hours, shift_type):
if pos_data.empty:
return None
# Kelompokkan jam dan status
hourly_status_counts = pos_data.groupby(['hour', 'Alarm Status']).size().unstack(fill_value=0)
# Klasifikasi berdasarkan kata kunci
hourly_normal = hourly_status_counts.get('No Alarm', pd.Series(0, index=shift_hours)).reindex(shift_hours, fill_value=0)
hourly_amber = hourly_status_counts.filter(regex='Amber').sum(axis=1).reindex(shift_hours, fill_value=0) # Semua yang mengandung "Amber"
hourly_red = hourly_status_counts.filter(regex='Red').sum(axis=1).reindex(shift_hours, fill_value=0) # Semua yang mengandung "Red"
# Total per jam
total_per_hour = hourly_normal + hourly_amber + hourly_red
# Sudut: sesuaikan agar jam 12 di bawah (180Β°), jam 6 di kanan (90Β°), jam 3 di atas (0Β°), jam 9 di kiri (270Β°)
if shift_type == 'pagi':
# Shift Pagi (06:00–18:00) β†’ 0Β° = 03:00, 90Β° = 06:00, 180Β° = 12:00, 270Β° = 18:00
theta = [(h - 3) * 30 for h in shift_hours] # 12 jam * 30Β° = 360Β°
tickvals = [0, 90, 180, 270]
ticktext = ["15:00", "06:00/18:00", "09:00", "12:00"]
else: # Shift Sore (18:00–06:00) β€” TAPI ikuti aturan jam seperti pagi
# Shift Sore (18:00–06:00) β†’ 0Β° = 21:00, 90Β° = 00:00, 180Β° = 06:00, 270Β° = 12:00
# Tapi karena ingin ikut aturan pagi, kita mapping jam agar 0Β° = 03:00, 90Β° = 06:00, 180Β° = 12:00, 270Β° = 18:00
# Maka kita gunakan jam pagi (06:00–18:00) sebagai referensi jam, tapi data diambil dari sore (18:00–06:00)
# Kita mapping: 18->06, 19->07, ..., 23->11, 00->12, 01->13, ..., 05->17
# Maka: theta = [(mapped_h - 3) * 30] where mapped_h = h + 12 if h < 6 else h - 12
theta = [(h - 3) * 30 for h in shift_hours]# 12 jam * 30Β° = 360Β°
tickvals = [0, 90, 180, 270]
ticktext = ["03:00", "18:00/06:00", "21:00", "00:00"]
fig = go.Figure()
# Tambahkan trace untuk masing-masing kategori dengan hovertemplate custom
fig.add_trace(go.Barpolar(
r=hourly_normal.values,
theta=theta,
name='Normal',
marker_color='#2E7D32', # Hijau
opacity=0.8,
hovertemplate='<b>Hour:</b> %{customdata}:00<br><b>Count:</b> %{r}<br><b>Status:</b> Normal<extra></extra>',
customdata=shift_hours
))
fig.add_trace(go.Barpolar(
r=hourly_amber.values,
theta=theta,
name='Amber',
marker_color='#FFBF00', # Kuning
opacity=0.8,
hovertemplate='<b>Hour:</b> %{customdata}:00<br><b>Count:</b> %{r}<br><b>Status:</b> Amber<extra></extra>',
customdata=shift_hours
))
fig.add_trace(go.Barpolar(
r=hourly_red.values,
theta=theta,
name='Red',
marker_color='#D32F2F', # Merah
opacity=0.8,
hovertemplate='<b>Hour:</b> %{customdata}:00<br><b>Count:</b> %{r}<br><b>Status:</b> Red<extra></extra>',
customdata=shift_hours
))
fig.update_layout(
polar=dict(
angularaxis=dict(
direction="clockwise",
period=len(shift_hours),
rotation=0,
tickvals=tickvals,
ticktext=ticktext,
tickfont=dict(size=12)
),
radialaxis=dict(
visible=True,
range=[0, max(total_per_hour.max() * 1.1, 1)]
)
),
showlegend=False,
margin=dict(t=30, b=20, l=20, r=20),
height=250,
title_text=title,
title_x=0.5
)
return fig
# =============== ROW 1: Position 1 & 2 (Pagi & Sore) ===============
with col1:
# Position 1 Pagi (06:00–18:00)
st.markdown('<div style="text-align:center; font-weight:bold; margin-bottom: 8px;">Position 1 (06:00–18:00)</div>', unsafe_allow_html=True)
pos1_data = alarm_data[alarm_data['Position'] == 1].copy()
pos1_data = pos1_data[pos1_data['hour'].between(6, 17, inclusive='both')]
fig1 = create_radial_chart(pos1_data, "", list(range(6, 18)), 'pagi')
if fig1 is not None:
st.plotly_chart(fig1, use_container_width=True)
else:
st.warning("No data for Position 1 (06:00–18:00)")
with col2:
# Position 1 Sore (18:00–06:00) β€” TAPI ikuti aturan jam seperti pagi
st.markdown('<div style="text-align:center; font-weight:bold; margin-bottom: 8px;">Position 1 (18:00–06:00)</div>', unsafe_allow_html=True)
pos1_data = alarm_data[alarm_data['Position'] == 1].copy()
pos1_data = pos1_data[~pos1_data['hour'].between(6, 17, inclusive='both')]
fig2 = create_radial_chart(pos1_data, "", list(range(18, 24)) + list(range(0, 6)), 'sore')
if fig2 is not None:
st.plotly_chart(fig2, use_container_width=True)
else:
st.warning("No data for Position 1 (18:00–06:00)")
with col3:
# Position 2 Pagi (06:00–18:00)
st.markdown('<div style="text-align:center; font-weight:bold; margin-bottom: 8px;">Position 2 (06:00–18:00)</div>', unsafe_allow_html=True)
pos2_data = alarm_data[alarm_data['Position'] == 2].copy()
pos2_data = pos2_data[pos2_data['hour'].between(6, 17, inclusive='both')]
fig3 = create_radial_chart(pos2_data, "", list(range(6, 18)), 'pagi')
if fig3 is not None:
st.plotly_chart(fig3, use_container_width=True)
else:
st.warning("No data for Position 2 (06:00–18:00)")
with col4:
# Position 2 Sore (18:00–06:00) β€” TAPI ikuti aturan jam seperti pagi
st.markdown('<div style="text-align:center; font-weight:bold; margin-bottom: 8px;">Position 2 (18:00–06:00)</div>', unsafe_allow_html=True)
pos2_data = alarm_data[alarm_data['Position'] == 2].copy()
pos2_data = pos2_data[~pos2_data['hour'].between(6, 17, inclusive='both')]
fig4 = create_radial_chart(pos2_data, "", list(range(18, 24)) + list(range(0, 6)), 'sore')
if fig4 is not None:
st.plotly_chart(fig4, use_container_width=True)
else:
st.warning("No data for Position 2 (18:00–06:00)")
# =============== ROW 2: Position 3 & 4 (Pagi & Sore) ===============
with col5:
# Position 3 Pagi (06:00–18:00)
st.markdown('<div style="text-align:center; font-weight:bold; margin-bottom: 8px;">Position 3 (06:00–18:00)</div>', unsafe_allow_html=True)
pos3_data = alarm_data[alarm_data['Position'] == 3].copy()
pos3_data = pos3_data[pos3_data['hour'].between(6, 17, inclusive='both')]
fig5 = create_radial_chart(pos3_data, "", list(range(6, 18)), 'pagi')
if fig5 is not None:
st.plotly_chart(fig5, use_container_width=True)
else:
st.warning("No data for Position 3 (06:00–18:00)")
with col6:
# Position 3 Sore (18:00–06:00) β€” TAPI ikuti aturan jam seperti pagi
st.markdown('<div style="text-align:center; font-weight:bold; margin-bottom: 8px;">Position 3 (18:00–06:00)</div>', unsafe_allow_html=True)
pos3_data = alarm_data[alarm_data['Position'] == 3].copy()
pos3_data = pos3_data[~pos3_data['hour'].between(6, 17, inclusive='both')]
fig6 = create_radial_chart(pos3_data, "", list(range(18, 24)) + list(range(0, 6)), 'sore')
if fig6 is not None:
st.plotly_chart(fig6, use_container_width=True)
else:
st.warning("No data for Position 3 (18:00–06:00)")
with col7:
# Position 4 Pagi (06:00–18:00)
st.markdown('<div style="text-align:center; font-weight:bold; margin-bottom: 8px;">Position 4 (06:00–18:00)</div>', unsafe_allow_html=True)
pos4_data = alarm_data[alarm_data['Position'] == 4].copy()
pos4_data = pos4_data[pos4_data['hour'].between(6, 17, inclusive='both')]
fig7 = create_radial_chart(pos4_data, "", list(range(6, 18)), 'pagi')
if fig7 is not None:
st.plotly_chart(fig7, use_container_width=True)
else:
st.warning("No data for Position 4 (06:00–18:00)")
with col8:
# Position 4 Sore (18:00–06:00) β€” TAPI ikuti aturan jam seperti pagi
st.markdown('<div style="text-align:center; font-weight:bold; margin-bottom: 8px;">Position 4 (18:00–06:00)</div>', unsafe_allow_html=True)
pos4_data = alarm_data[alarm_data['Position'] == 4].copy()
pos4_data = pos4_data[~pos4_data['hour'].between(6, 17, inclusive='both')]
fig8 = create_radial_chart(pos4_data, "", list(range(18, 24)) + list(range(0, 6)), 'sore')
if fig8 is not None:
st.plotly_chart(fig8, use_container_width=True)
else:
st.warning("No data for Position 4 (18:00–06:00)")
def generate_objective2_insights(df: pd.DataFrame) -> str:
"""
Generate dynamic, line-by-line insight for Objective 2.
Input: filtered DataFrame (e.g., by site/year/hour β€” already applied upstream)
Output: formatted string with <br> for newline (left-aligned, clean)
"""
# Filter hanya Red & Amber alarms
alarm_df = df[df['alarm_severity'].isin(['Red', 'Amber'])].copy()
if alarm_df.empty:
return "β€’ No Red or Amber alarms in selected period."
# === 1. Total counts ===
total_red = alarm_df[alarm_df['alarm_severity'] == 'Red'].shape[0]
total_amber = alarm_df[alarm_df['alarm_severity'] == 'Amber'].shape[0]
total_combined = total_red + total_amber
# === 2. Dominant period (custom bins) ===
def get_period(hour):
if 12 <= hour < 18:
return '12:00–18:00'
elif 18 <= hour < 24 or hour == 0: # include 00:00 as part of night
return '18:00–00:00'
else:
return 'Other'
alarm_df['period'] = alarm_df['hour'].apply(get_period)
period_counts = alarm_df['period'].value_counts()
dominant_period = period_counts.idxmax()
dominant_pct = period_counts.max() / total_combined * 100
# Second-dominant
if len(period_counts) > 1:
second_period = period_counts.index[1]
second_pct = period_counts.iloc[1] / total_combined * 100
else:
second_period = 'β€”'
second_pct = 0.0
# === 3. Peak per Position + Period + Severity ===
# We'll find peak hour within each (Position, period, severity) group
peaks = []
for pos in [1, 2, 3, 4]:
for period in ['12:00–18:00', '18:00–00:00']:
for sev in ['Red', 'Amber']:
subset = alarm_df[
(alarm_df['Position'] == pos) &
(alarm_df['period'] == period) &
(alarm_df['alarm_severity'] == sev)
]
if not subset.empty:
peak_hour = subset['hour'].mode().iloc[0] # most frequent hour
peak_count = (subset['hour'] == peak_hour).sum()
# Format hour to 00:00 (0 β†’ 00:00, 23 β†’ 23:00, but 0 in 18–00 group = 00:00)
display_hour = f"{int(peak_hour):02d}:00"
peaks.append((pos, period, sev, display_hour, peak_count))
# Build insight lines
lines = [
f"β€’ Dominant period for Red/Amber: {dominant_period} β€” {dominant_pct:.2f}%",
f"β€’ Second-dominant period: {second_period} β€” {second_pct:.2f}%"
]
# Add peak lines (only top patterns β€” limit to meaningful ones)
for pos, period, sev, hr, cnt in sorted(peaks, key=lambda x: (-x[4], x[0], x[1])):
if cnt >= 10: # only show peaks with β‰₯10 occurrences (avoid noise)
lines.append(f"β€’ Position {pos}, {period}: Peak {sev} alarm at {hr} ({cnt:,} occurrences)")
return "<br>".join(lines)
# === RENDER INSIGHT BOX ===
# =============== INSIGHT 2 (Ringkas & Fokus ke Red & Amber) ===============
# =============== INSIGHT 3 (Rata kiri, sesuai preferensi Aning) ===============
# β€”β€”β€”β€”β€” Validasi data β€”β€”β€”β€”β€”
required_cols = {'Alarm Status', 'hour', 'Position'}
if not required_cols.issubset(alarm_data.columns) or alarm_data.empty:
insight_lines = [
"β€’ No alarm data available for Red or Amber analysis.",
"β€’ Ensure dataset includes 'Alarm Status', 'hour', and 'Position' columns."
]
else:
# Filter Red & Amber β€” case-insensitive, robust terhadap NaN
mask_red = alarm_data['Alarm Status'].str.contains(r'\bRed\b', case=False, na=False)
mask_amber = alarm_data['Alarm Status'].str.contains(r'\bAmber\b', case=False, na=False)
red_amber_data = alarm_data[mask_red | mask_amber].copy()
if red_amber_data.empty:
insight_lines = ["β€’ No Red or Amber alarms detected in the dataset."]
else:
insight_lines = []
# Tambahkan flag
red_amber_data['is_red'] = mask_red.loc[red_amber_data.index]
red_amber_data['is_amber'] = mask_amber.loc[red_amber_data.index]
# Loop tiap posisi roda (1–4)
for pos in [1, 2, 3, 4]:
pos_data = red_amber_data[red_amber_data['Position'] == pos]
if pos_data.empty:
continue
# Band 1: 12:00–18:00 (siang/sore)
band1 = pos_data[(pos_data['hour'] >= 12) & (pos_data['hour'] <= 17)]
# Band 2: 18:00–00:00 (sore/malam/dini hari)
band2 = pos_data[(pos_data['hour'] >= 18) | (pos_data['hour'] <= 5)]
# β€” Band 1 β€”
if not band1.empty:
red_sub = band1[band1['is_red']]
if not red_sub.empty:
h_peak = int(red_sub['hour'].value_counts().idxmax())
c_peak = int(red_sub['hour'].value_counts().max())
insight_lines.append(f"β€’ Position {pos}, 06:00–18:00 (Day Shift): Peak Red alarm at {h_peak:02d}:00 ({c_peak} occurrences).")
amber_sub = band1[band1['is_amber']]
if not amber_sub.empty:
h_peak = int(amber_sub['hour'].value_counts().idxmax())
c_peak = int(amber_sub['hour'].value_counts().max())
insight_lines.append(f"β€’ Position {pos}, 06:00–18:00 (Day Shift): Peak Amber alarm at {h_peak:02d}:00 ({c_peak} occurrences).")
# β€” Band 2 β€”
if not band2.empty:
red_sub = band2[band2['is_red']]
if not red_sub.empty:
h_peak = int(red_sub['hour'].value_counts().idxmax())
c_peak = int(red_sub['hour'].value_counts().max())
insight_lines.append(f"β€’ Position {pos}, 18:00–06:00 (Night Shift): Peak Red alarm at {h_peak:02d}:00 ({c_peak} occurrences).")
amber_sub = band2[band2['is_amber']]
if not amber_sub.empty:
h_peak = int(amber_sub['hour'].value_counts().idxmax())
c_peak = int(amber_sub['hour'].value_counts().max())
insight_lines.append(f"β€’ Position {pos}, 18:00–06:00 (Night Shift): Peak Amber alarm at {h_peak:02d}:00 ({c_peak} occurrences).")
# Jika tidak ada alarm di posisi 1–4
if not insight_lines:
insight_lines = ["β€’ Red and Amber alarms occur outside standard wheel positions (1–4)."]
# β€”β€”β€”β€”β€” Tambahkan insight naratif (sesuai contoh Anda) β€”β€”β€”β€”β€”
has_front_red = not red_amber_data[(red_amber_data['Position'].isin([1, 2])) & (red_amber_data['is_red'])].empty
has_rear_amber = not red_amber_data[(red_amber_data['Position'].isin([3, 4])) & (red_amber_data['is_amber'])].empty
if has_front_red or has_rear_amber:
insight_lines.extend([
"β€’ The front tyre pressure is closed to upper threshold before equipment is being operated. It is shown by small number of red alarms in the early day shift and increase as being operated. Furthermore, during 04:00–06:00, red alarm decrease and it is likely due to operational slowdown.",
"β€’ In contrast, for rear tyres, notifications often indicate pressure below the lower threshold. As a result, amber alarms frequently occur early in the shift and return to normal as the tyres warm up during operation."
])
# Gabungkan jadi satu string, tiap baris baru β†’ \n
insight_text = "\n".join(insight_lines)
# β€”β€”β€”β€”β€” TAMPILKAN (RATA KIRI) β€”β€”β€”β€”β€”
st.markdown('<h4 style="text-align:center; margin:10px 0 5px 0; font-weight:bold;">INSIGHTS</h4>', unsafe_allow_html=True)
st.markdown(f"""
<div class="insight-box">
<div class="content" style="
text-align: left;
white-space: pre-line;
font-family: 'Segoe UI', sans-serif;
line-height: 1.6;
font-size: 0.95em;
">
{insight_text}
</div>
</div>
""", unsafe_allow_html=True)
### OBJECTICVE 3
# ================= OBJECTIVE 3 =================
st.markdown('<h3 class="objective-title">OBJECTIVE 3: Correlation β€” How Does Heat Influence Pressure and Which Tyres Trigger Red Alarms?</h3>', unsafe_allow_html=True)
# Prepare data
front_df = dff[dff['Position'].isin([1, 2])].copy()
rear_df = dff[dff['Position'].isin([3, 4])].copy()
col1, col2 = st.columns(2)
# =============== COL 1: Front β€” Temp β†’ Pressure ===============
with col1:
st.markdown('<h5 style="text-align:center; margin-top: 0;">Front Tyres: Temperature β†’ Pressure</h5>', unsafe_allow_html=True)
if not front_df.empty:
front_df['Category'] = front_df.apply(
lambda row: "Normal Front Tyre" if row['Alarm Status'] == 'No Alarm'
else "Amber Pressure Front Tyre" if 'Amber' in str(row['Alarm Status'])
else "Red Pressure Front Tyre", axis=1
)
categories = ["Normal Front Tyre", "Amber Pressure Front Tyre", "Red Pressure Front Tyre"]
front_df['Category'] = pd.Categorical(front_df['Category'], categories=categories, ordered=True)
valid = front_df.dropna(subset=['Temperature (Β°C)', 'Pressure (psi)'])
if len(valid) > 1:
X = valid[['Temperature (Β°C)']].values
y = valid['Pressure (psi)'].values
model = LinearRegression().fit(X, y)
x_line = np.linspace(X.min(), X.max(), 100).reshape(-1, 1)
y_line = model.predict(x_line)
corr = np.corrcoef(valid['Temperature (Β°C)'], valid['Pressure (psi)'])[0, 1]
fig = px.scatter(
valid,
x='Temperature (Β°C)',
y='Pressure (psi)',
color='Category',
color_discrete_map={
"Normal Front Tyre": "#2E7D32",
"Amber Pressure Front Tyre": "#FFBF00",
"Red Pressure Front Tyre": "#D32F2F"
},
category_orders={'Category': categories},
template="plotly_white"
)
fig.update_traces(
hovertemplate="<b>%{customdata[0]}</b><br>Temp: %{x:.1f}Β°C<br>Pressure: %{y:.1f} psi<extra></extra>",
customdata=valid[['Category']].values,
marker=dict(size=6)
)
fig.add_trace(go.Scatter(
x=x_line.flatten(), y=y_line,
mode='lines', name='Trend Line',
line=dict(color='#1976D2', dash='dot', width=2)
))
# Confidence band
y_pred = model.predict(X)
std_err = np.std(y - y_pred)
y_upper = y_line + 1.96 * std_err
y_lower = y_line - 1.96 * std_err
fig.add_trace(go.Scatter(
x=np.concatenate([x_line.flatten(), x_line.flatten()[::-1]]),
y=np.concatenate([y_upper, y_lower[::-1]]),
fill='toself',
fillcolor='rgba(211, 47, 47, 0.1)',
line=dict(color='rgba(255,255,255,0)'),
showlegend=False
))
fig.update_layout(
margin=dict(t=40),
annotations=[dict(x=0.95, y=0.95, xref="paper", yref="paper",
text=f"r = {corr:.2f}", showarrow=False,
bgcolor="white", bordercolor="black", borderwidth=1)],
legend_title_text='Status'
)
st.plotly_chart(fig, use_container_width=True)
else:
st.warning("Insufficient front tyre data.")
else:
st.warning("No front tyre data.")
# =============== COL 2: Front β€” Pressure vs Temp/Speed Ratio ===============
with col2:
st.markdown('<h5 style="text-align:center; margin-top: 0;">Front Tyres: Pressure vs Temp/Speed Ratio</h5>', unsafe_allow_html=True)
if not front_df.empty:
# Filter kecepatan > 0
front_speed_ok = front_df[front_df['Speed (km/h)'] > 0].copy()
if not front_speed_ok.empty:
front_speed_ok['temp_speed_ratio'] = front_speed_ok['Temperature (Β°C)'] / front_speed_ok['Speed (km/h)']
front_speed_ok['Category'] = front_speed_ok.apply(
lambda row: "Normal Front Tyre" if row['Alarm Status'] == 'No Alarm'
else "Amber Pressure Front Tyre" if 'Amber' in str(row['Alarm Status'])
else "Red Pressure Front Tyre", axis=1
)
categories = ["Normal Front Tyre", "Amber Pressure Front Tyre", "Red Pressure Front Tyre"]
front_speed_ok['Category'] = pd.Categorical(front_speed_ok['Category'], categories=categories, ordered=True)
valid = front_speed_ok.dropna(subset=['temp_speed_ratio', 'Pressure (psi)'])
if not valid.empty:
fig = px.scatter(
valid,
x='temp_speed_ratio',
y='Pressure (psi)',
color='Category',
color_discrete_map={
"Normal Front Tyre": "#2E7D32",
"Amber Pressure Front Tyre": "#FFBF00",
"Red Pressure Front Tyre": "#D32F2F"
},
category_orders={'Category': categories},
template="plotly_white",
labels={'temp_speed_ratio': 'Temp / Speed (Β°CΒ·h/km)'}
)
fig.update_traces(
hovertemplate="<b>%{customdata[0]}</b><br>T/S: %{x:.2f}<br>Pressure: %{y:.1f} psi<extra></extra>",
customdata=valid[['Category']].values,
marker=dict(size=6)
)
fig.update_layout(margin=dict(t=40), legend_title_text='Status')
st.plotly_chart(fig, use_container_width=True)
else:
st.warning("No valid front temp/speed data.")
else:
st.warning("No front data with Speed > 0.")
else:
st.warning("No front tyre data.")
# =============== COL 3 & 4: Rear Tyres ===============
col3, col4 = st.columns(2)
# =============== COL 3: Rear β€” Temp β†’ Pressure ===============
with col3:
st.markdown('<h5 style="text-align:center; margin-top: 0;">Rear Tyres: Temperature β†’ Pressure</h5>', unsafe_allow_html=True)
if not rear_df.empty:
rear_df['Category'] = rear_df.apply(
lambda row: "Normal Rear Tyre" if row['Alarm Status'] == 'No Alarm'
else "Amber Pressure Rear Tyre" if 'Amber' in str(row['Alarm Status'])
else "Red Pressure Rear Tyre", axis=1
)
categories = ["Normal Rear Tyre", "Amber Pressure Rear Tyre", "Red Pressure Rear Tyre"]
rear_df['Category'] = pd.Categorical(rear_df['Category'], categories=categories, ordered=True)
valid = rear_df.dropna(subset=['Temperature (Β°C)', 'Pressure (psi)'])
if len(valid) > 1:
X = valid[['Temperature (Β°C)']].values
y = valid['Pressure (psi)'].values
model = LinearRegression().fit(X, y)
x_line = np.linspace(X.min(), X.max(), 100).reshape(-1, 1)
y_line = model.predict(x_line)
corr = np.corrcoef(valid['Temperature (Β°C)'], valid['Pressure (psi)'])[0, 1]
fig = px.scatter(
valid,
x='Temperature (Β°C)',
y='Pressure (psi)',
color='Category',
color_discrete_map={
"Normal Rear Tyre": "#2E7D32",
"Amber Pressure Rear Tyre": "#FFBF00",
"Red Pressure Rear Tyre": "#D32F2F"
},
category_orders={'Category': categories},
template="plotly_white"
)
fig.update_traces(
hovertemplate="<b>%{customdata[0]}</b><br>Temp: %{x:.1f}Β°C<br>Pressure: %{y:.1f} psi<extra></extra>",
customdata=valid[['Category']].values,
marker=dict(size=6)
)
fig.add_trace(go.Scatter(
x=x_line.flatten(), y=y_line,
mode='lines', name='Trend Line',
line=dict(color='#1976D2', dash='dot', width=2)
))
y_pred = model.predict(X)
std_err = np.std(y - y_pred)
y_upper = y_line + 1.96 * std_err
y_lower = y_line - 1.96 * std_err
fig.add_trace(go.Scatter(
x=np.concatenate([x_line.flatten(), x_line.flatten()[::-1]]),
y=np.concatenate([y_upper, y_lower[::-1]]),
fill='toself',
fillcolor='rgba(211, 47, 47, 0.1)',
line=dict(color='rgba(255,255,255,0)'),
showlegend=False
))
fig.update_layout(
margin=dict(t=40),
annotations=[dict(x=0.95, y=0.95, xref="paper", yref="paper",
text=f"r = {corr:.2f}", showarrow=False,
bgcolor="white", bordercolor="black", borderwidth=1)],
legend_title_text='Status'
)
st.plotly_chart(fig, use_container_width=True)
else:
st.warning("Insufficient rear tyre data.")
else:
st.warning("No rear tyre data.")
# =============== COL 4: Rear β€” Pressure vs Temp/Speed Ratio ===============
with col4:
st.markdown('<h5 style="text-align:center; margin-top: 0;">Rear Tyres: Pressure vs Temp/Speed Ratio</h5>', unsafe_allow_html=True)
if not rear_df.empty:
rear_speed_ok = rear_df[rear_df['Speed (km/h)'] > 0].copy()
if not rear_speed_ok.empty:
rear_speed_ok['temp_speed_ratio'] = rear_speed_ok['Temperature (Β°C)'] / rear_speed_ok['Speed (km/h)']
rear_speed_ok['Category'] = rear_speed_ok.apply(
lambda row: "Normal Rear Tyre" if row['Alarm Status'] == 'No Alarm'
else "Amber Pressure Rear Tyre" if 'Amber' in str(row['Alarm Status'])
else "Red Pressure Rear Tyre", axis=1
)
categories = ["Normal Rear Tyre", "Amber Pressure Rear Tyre", "Red Pressure Rear Tyre"]
rear_speed_ok['Category'] = pd.Categorical(rear_speed_ok['Category'], categories=categories, ordered=True)
valid = rear_speed_ok.dropna(subset=['temp_speed_ratio', 'Pressure (psi)'])
if not valid.empty:
fig = px.scatter(
valid,
x='temp_speed_ratio',
y='Pressure (psi)',
color='Category',
color_discrete_map={
"Normal Rear Tyre": "#2E7D32",
"Amber Pressure Rear Tyre": "#FFBF00",
"Red Pressure Rear Tyre": "#D32F2F"
},
category_orders={'Category': categories},
template="plotly_white",
labels={'temp_speed_ratio': 'Temp / Speed (Β°CΒ·h/km)'}
)
fig.update_traces(
hovertemplate="<b>%{customdata[0]}</b><br>T/S: %{x:.2f}<br>Pressure: %{y:.1f} psi<extra></extra>",
customdata=valid[['Category']].values,
marker=dict(size=6)
)
fig.update_layout(margin=dict(t=40), legend_title_text='Status')
st.plotly_chart(fig, use_container_width=True)
else:
st.warning("No valid rear temp/speed data.")
else:
st.warning("No rear data with Speed > 0.")
else:
st.warning("No rear tyre data.")
# =============== INSIGHT 3 ===============
def safe_corr(a, b):
a, b = np.array(a), np.array(b)
mask = ~(np.isnan(a) | np.isnan(b))
if mask.sum() < 2:
return 0.0
c = np.corrcoef(a[mask], b[mask])[0, 1]
return c if np.isfinite(c) else 0.0
corr_p_t_front = safe_corr(front_df['Temperature (Β°C)'], front_df['Pressure (psi)'])
corr_p_t_rear = safe_corr(rear_df['Temperature (Β°C)'], rear_df['Pressure (psi)'])
corr_t_s_front = safe_corr(front_df['Temperature (Β°C)'], front_df['Speed (km/h)'])
corr_t_s_rear = safe_corr(rear_df['Temperature (Β°C)'], rear_df['Speed (km/h)'])
insight_lines = [
f"‒ Front tyres show stronger temp→pressure correlation (r = {corr_p_t_front:.2f}) than rear (r = {corr_p_t_rear:.2f}).",
f"β€’ Temperature–speed correlation to pressure is weak.",
f"β€’ This suggests heat buildup is driven more by load/friction than speed alone.",
f"β€’ Front tyre alarms concentrate in high-temp, high-pressure quadrants β€” enabling early intervention.",
f"β€’ Rear tyre alarms concentrate in low-temperature, low-pressure quadrants β€” enabling early warning"
]
insight_text = "\n".join(insight_lines)
st.markdown(f"""
<div class="insight-box">
<div class="content" style="text-align:left; white-space:pre-line;">
{insight_text}
</div>
</div>
""", unsafe_allow_html=True)
# ================= OBJECTIVE 4 =================
st.markdown('<h3 class="objective-title">OBJECTIVE 4: Spatial Risk Mapping β€” Where Do Red Pressure Alarms Occur Most Frequently?</h3>', unsafe_allow_html=True)
# st.markdown('<h5 style="text-align:center; margin-top: 0;">Tyre Alarms Distribution by Location</h5>', unsafe_allow_html=True)
valid_gps = dff.dropna(subset=['Latitude_y', 'Longitude_y'])
if valid_gps.empty:
st.warning("No valid GNSS coordinates for selected filters.")
else:
center_lat = valid_gps['Latitude_y'].mean()
center_lon = valid_gps['Longitude_y'].mean()
m = folium.Map(
location=[center_lat, center_lon],
zoom_start=16,
tiles='CartoDB positron',
width='100%',
height='520px'
)
# === Normalisasi suhu untuk scaling ukuran (lebih halus & kecil)
temp_min = valid_gps['Temperature (Β°C)'].min()
temp_max = valid_gps['Temperature (Β°C)'].max()
temp_range = temp_max - temp_min if temp_max > temp_min else 1
for _, r in valid_gps.iterrows():
# Warna: Red untuk Red High Pressure, hijau untuk lainnya (termasuk Amber/No Alarm)
if r['Alarm Status'] == 'Red High Pressure':
color = '#D32F2F' # Red 700
elif 'Amber' in str(r['Alarm Status']):
color = '#FFA726' # Amber ~ Orange 500
else:
color = '#2E7D32' # Green 700
# πŸ”» Ukuran bubble DIPERKECIL:
# - radius dasar = 1.5
# - tambahan maks = 4.0 (bukan 12)
# - formula lebih smooth: 1.5 + 4.0 * normalized_temp
normalized_temp = (r['Temperature (Β°C)'] - temp_min) / (temp_range + 1e-6)
radius = 1.5 + 4.0 * normalized_temp # βœ… JAUH LEBIH KECIL
# Popup
popup_html = f"""
<div style="font-family:Segoe UI; font-size:13px; line-height:1.4">
<b>SN:</b> {r['TyreSN']} | Pos: {int(r['Position'])}<br>
<b>Zone:</b> {r['Zone']}<br>
<b>Press:</b> {r['Pressure (psi)']:.1f} psi<br>
<b>Temp:</b> {r['Temperature (Β°C)']:.1f} Β°C<br>
<b>Speed:</b> {r['Speed (km/h)']:.1f} km/h<br>
<b>Alarm:</b> {r['Alarm Status']}
</div>
"""
folium.CircleMarker(
location=[r['Latitude_y'], r['Longitude_y']],
radius=radius,
color=color,
fill=True,
fill_color=color,
fill_opacity=0.72,
weight=1,
popup=folium.Popup(popup_html, max_width=250)
).add_to(m)
# Legend (update to include Amber)
legend_html = '''
<div style="
position: fixed;
bottom: 60px; right: 20px;
background: white;
border: 1px solid #E9ECEF;
border-radius: 10px;
box-shadow: 0 4px 12px rgba(0,0,0,0.08);
padding: 12px;
font-family: Segoe UI;
font-size: 13px;
z-index: 9999;
">
<b>Legend</b><br>
<span style="color:#2E7D32">●</span> Normal<br>
<span style="color:#FFA726">●</span> Amber Pressure<br>
<span style="color:#D32F2F">●</span> Red Pressure<br>
<i>Size ∝ Temperature<br>(1.5–5.5 px radius)</i>
</div>
'''
m.get_root().html.add_child(folium.Element(legend_html))
st_folium(m, width='100%', height=520, returned_objects=[])
# =============== INSIGHT 4 (Diperbaiki: angka 2 desimal, rata kiri, bullet-ready) ===============
if not valid_gps.empty:
alarm_gps = valid_gps[valid_gps['is_alarm'] == 1]
if not alarm_gps.empty:
# Top zone
zone_counts = alarm_gps['Zone'].value_counts()
top_zone = zone_counts.index[0]
top_zone_count = zone_counts.iloc[0]
total_alarms = len(alarm_gps)
zone_pct = (top_zone_count / total_alarms) * 100
# Front vs Rear
front_alarms = alarm_gps[alarm_gps['Position'].isin([1, 2])].shape[0]
rear_alarms = alarm_gps[alarm_gps['Position'].isin([3, 4])].shape[0]
front_pct = (front_alarms / total_alarms) * 100 if total_alarms > 0 else 0
insight_lines = [
f"β€’ Zone {top_zone} is the highest-risk area, contributing {top_zone_count} alarms ({zone_pct:.1f}% of total).",
f"β€’ Front tyres (Pos 1–2) generate {front_alarms} alarms ({front_pct:.1f}% of total alarm), indicating higher operational stress.",
f"β€’ {rear_alarms} alarms occur on rear tyres (Pos 3–4), representing {100 - front_pct:.1f}% of total alarm distribution."
]
insight_text = "\n".join(insight_lines)
else:
insight_text = "β€’ No alarms detected in the selected filter period."
else:
insight_text = "β€’ No valid GNSS data available for spatial analysis."
st.markdown(f"""
<div class="insight-box">
<div class="content" style="text-align:left; white-space:pre-line;">
{insight_text}
</div>
</div>
""", unsafe_allow_html=True)
# ================= OBJECTIVE 5 =================
# ================= OBJECTIVE 6 =================
st.markdown('<h3 class="objective-title">OBJECTIVE 6: Health Index Trends β€” How Does Tyre Health (Pressure & Temperature) Change Over Time by Position?</h3>', unsafe_allow_html=True)
# --- Buat data dummy jika file tidak ada ---
hi_raw = pd.DataFrame({
'Month': [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6],
'Position': [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
'HI_final': [
0.94751783, 0.981636598, 0.994359063, 0.990125387,
0.957691585, 0.97341454, 0.999259138, 0.994866508,
0.988009819, 0.997282609, 0.999844077, 1.0,
0.937885802, 0.968831878, 0.99572543, 0.99767257,
0.913787453, 0.946695458, 0.995078542, 0.999891732,
0.916053922, 0.937581169, 0.995727718, 0.999833558
]
})
# Tambahkan tahun ke kolom Month agar bisa di-parse
hi_raw['Month'] = pd.to_datetime(hi_raw['Month'].apply(lambda x: f"{int(x):02d}/2023"), format="%m/%Y")
st.success("")
# Jika berhasil baca, proses
required_cols = ['Month', 'Position', 'HI_final']
missing = [c for c in required_cols if c not in hi_raw.columns]
if missing:
st.error(f"❌ Missing required columns: {', '.join(missing)}")
else:
try:
hi_plot = hi_raw[required_cols].copy()
# Position β†’ integer
hi_plot['Position'] = pd.to_numeric(hi_plot['Position'], errors='coerce')
hi_plot = hi_plot.dropna(subset=['Position'])
hi_plot['Position'] = hi_plot['Position'].astype(int)
# Filter HI valid (0–100) β€” ubah ke skala 0–100 jika perlu
# hi_plot['HI_final'] *= 100 # Jika data dalam skala 0–1, aktifkan ini
if hi_plot.empty:
st.warning("⚠️ No valid Health Index records after cleaning.")
else:
hi_plot = hi_plot.sort_values(['Position', 'Month'])
# Line chart
fig = px.line(
hi_plot,
x='Month',
y='HI_final',
color='Position',
line_shape='linear',
title='',
labels={
'HI_final': 'Health Index',
'Month': 'Month',
'Position': 'Tyre Position'
},
color_discrete_map={
1: '#003DA5', # Dark Blue
2: '#7FA6E8', # Light Blue
3: '#FFB300', # Gold
4: '#FFE082' # Light Yellow
},
markers=True
)
# Hover & layout
fig.update_traces(
hovertemplate="<b>Position %{fullData.name}</b><br>Month: %{x|%b %Y}<br>HI: %{y:.2f}<extra></extra>",
line=dict(width=2.5)
)
fig.update_layout(
xaxis_title='Month',
yaxis_title='PT Health Index',
legend_title_text='Position',
hovermode='x unified',
margin=dict(t=40, b=40, l=60, r=40),
template="plotly_white"
)
# Tambahkan threshold HI = 0.8 (jika data dalam skala 0–1)
# fig.add_hline(
# y=0.8,
# line_dash="dot",
# line_color="red",
# annotation_text="",
# annotation_position="top right"
# )
st.plotly_chart(fig, use_container_width=True)
# === INSIGHT ===
avg_hi = hi_plot['HI_final'].mean()
front_hi = hi_plot[hi_plot['Position'].isin([1, 2])]['HI_final'].mean()
rear_hi = hi_plot[hi_plot['Position'].isin([3, 4])]['HI_final'].mean()
pos_avg = hi_plot.groupby('Position')['HI_final'].mean()
worst_pos = pos_avg.idxmin()
worst_hi = pos_avg.min()
insight_lines = [
f"β€’ The minimum PT HI for Tyre 1 in Mei was recorded at 0.91.",
f"β€’ The minimum PT HI for Tyre 2 in June was recorded at 0.93.",
f"β€’ The minimum PT HI for Tyre 3 in January was recorded at 1.00.",
f"β€’ The minimum PT HI for Tyre 4 in January was recorded at 1.00.",
f"β€’ Tyre 1 and Tyre 2 show a declining health index trend and should be prioritized for inspection."
]
insight_text = "\n".join(insight_lines)
st.markdown(f"""
<div class="insight-box">
<div class="content" style="text-align:left; white-space:pre-line;">
{insight_text}
</div>
</div>
""", unsafe_allow_html=True)
except Exception as e:
st.error(f"❌ Error processing Health Index {e}")
# ================= OBJECTIVE 6 =================
import streamlit as st
import pandas as pd
import numpy as np
# ⚠️ ASSUMPTION: `dff` exists in scope.
# Jika 'Alarm Type' tidak ada di kolom, kita fallback ke mode aman (empty alarms)
# β€” sesuai permintaan: *hard code, jgn pakai def*
st.markdown('<h3 class="objective-title">OBJECTIVE 6: Insights & Mitigation β€” How Can Red Pressure Alarms Be Reduced?</h3>', unsafe_allow_html=True)
# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” DATA PREP (HARD-CODED, NO DEF) β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
# # Cek apakah kolom 'Alarm Type' ada
# has_alarm_type = 'Alarm Type' in dff.columns
# # Front tyre stats β€” fallback ke "β€”" jika NaN/empty/error
# try:
# front_pressure_avg = dff[dff['Position'].isin([1, 2])]['Pressure (psi)'].mean()
# front_temp_avg = dff[dff['Position'].isin([1, 2])]['Temperature (Β°C)'].mean()
# except Exception:
# front_pressure_avg = np.nan
# front_temp_avg = np.nan
# front_pressure_avg_str = f"{front_pressure_avg:.1f}" if pd.notna(front_pressure_avg) else "β€”"
# front_temp_avg_str = f"{front_temp_avg:.1f}" if pd.notna(front_temp_avg) else "β€”"
# # Alarm filtering β€” hanya Red & Amber, jika 'Alarm Type' tidak ada β†’ anggap 0 alarm
# if has_alarm_type:
# alarm_mask = dff['Alarm Type'].isin(['Red', 'Amber'])
# alarm_df = dff[alarm_mask].copy()
# else:
# alarm_df = dff.iloc[0:0] # empty DataFrame
# hourly_counts = alarm_df['hour'].value_counts().reindex(range(24), fill_value=0) if 'hour' in alarm_df.columns else pd.Series([0]*24, index=range(24))
# total_alarms = hourly_counts.sum()
# dominant_hour = None
# dominant_percentage = 0.0
# if total_alarms > 0 and not hourly_counts.empty:
# dominant_hour = int(hourly_counts.idxmax())
# dominant_percentage = (hourly_counts[dominant_hour] / total_alarms) * 100
# # Zone alarm stats
# if 'Zone' in alarm_df.columns and not alarm_df.empty:
# zone_counts = alarm_df['Zone'].value_counts()
# if not zone_counts.empty:
# top_zone = str(zone_counts.index[0])
# top_zone_percentage = (zone_counts.iloc[0] / total_alarms) * 100 if total_alarms > 0 else 0.0
# else:
# top_zone = "β€”"
# top_zone_percentage = 0.0
# else:
# top_zone = "β€”"
# top_zone_percentage = 0.0
# # Korelasi β€” aman tanpa fungsi
# corr_pressure_temp_front = 0.0
# corr_speed_temp_rear = 0.0
# try:
# front_df = dff[dff['Position'].isin([1, 2])]
# rear_df = dff[dff['Position'].isin([3, 4])]
# # Pressure–temp (front)
# x1, y1 = front_df['Pressure (psi)'], front_df['Temperature (Β°C)']
# valid1 = x1.notna() & y1.notna()
# if valid1.sum() >= 2:
# c1 = np.corrcoef(x1[valid1], y1[valid1])[0, 1]
# corr_pressure_temp_front = c1 if np.isfinite(c1) else 0.0
# # Speed–temp (rear)
# x2, y2 = rear_df['Speed (km/h)'], rear_df['Temperature (Β°C)']
# valid2 = x2.notna() & y2.notna()
# if valid2.sum() >= 2:
# c2 = np.corrcoef(x2[valid2], y2[valid2])[0, 1]
# corr_speed_temp_rear = c2 if np.isfinite(c2) else 0.0
# except Exception:
# pass # tetap 0.0 jika error
# # Format Β±0.xx, hindari -0.00
# corr_pressure_temp_front_str = f"{corr_pressure_temp_front:+.2f}".replace("-0.00", "0.00")
# corr_speed_temp_rear_str = f"{corr_speed_temp_rear:+.2f}".replace("-0.00", "0.00")
# # Position 1 alarm count
# pos1_alarm_count = alarm_df[alarm_df['Position'] == 1].shape[0] if 'Position' in alarm_df.columns else 0
# # β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” INSIGHTS β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
# insight_lines = []
# # 1. Front tyre avg
# line1 = f"1. Front tyres (Pos 1 & 2): avg pressure {front_pressure_avg_str} psi, avg temperature {front_temp_avg_str}Β°C."
# if pd.notna(front_pressure_avg) and front_pressure_avg > 115:
# line1 += " Exceeds ideal inflation range (100–110 psi), indicating over-pressure risk."
# insight_lines.append(line1)
# # 2. Dominant hour
# if dominant_hour is not None:
# insight_lines.append(
# f"2. Peak Red/Amber alarm concentration at {dominant_hour:02d}:00 ({dominant_percentage:.1f}% of total)."
# )
# else:
# insight_lines.append("2. No statistically dominant hourly alarm peak.")
# # 3. Correlations
# insight_lines.append(
# f"3. Front pressure–temperature correlation: r = {corr_pressure_temp_front_str}; "
# f"Rear speed–temperature correlation: r = {corr_speed_temp_rear_str}."
# )
# # 4. Top zone
# if top_zone != "β€”" and top_zone_percentage >= 10.0:
# insight_lines.append(
# f"4. Zone {top_zone} accounts for {top_zone_percentage:.1f}% of alarms β€” highest-risk location."
# )
# else:
# insight_lines.append("4. Alarm distribution appears relatively uniform across zones.")
# # 5. Position 1 alarms
# if pos1_alarm_count > 0:
# insight_lines.append(
# f"5. Position 1 recorded {pos1_alarm_count} Red/Amber alarms β€” highest of any wheel position."
# )
# insight_text = "<br>".join(insight_lines)
# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” SUMMARY (HARD-CODED) β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
summary_text = """\
1. Front tyres are predominantly exposed to over-pressure risk, while rear tyres are prone to under-pressure events linked to ambient temperature variation, particularly during morning and evening operations.<br>
2. Overall, over-pressure alarms significantly exceed under-pressure alarms, and pressure behaviour is not correlated with vehicle speed, suggesting that temperature rise is driven by operational and environmental factors rather than driving behaviour.\
"""
# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” RECOMMENDATION (HARD-CODED, BUSINESS-READY) β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
recommendation_text = """\
1. Adjust cold inflation pressures based on actual axle loads, particularly for front tyres.<br>
2. Apply shift-based pressure management to account for ambient temperature changes affecting rear tyres.<br>
3. Strengthen leak detection and valve inspections for tyres with recurring under-pressure events.<br>
4. Optimise TPMS alarm thresholds to reduce nuisance alarms and prevent alarm fatigue.<br>
5. Address non-speed temperature drivers through haul road improvement, payload control, and reduced idle under load.<br>
6. Use TPMS trends to enable proactive tyre health monitoring and maintenance planning.\
"""
# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” RENDER β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
# st.markdown('<h4 style="text-align:center; margin:10px 0 5px 0; font-weight:bold;">INSIGHTS</h4>', unsafe_allow_html=True)
# st.markdown(f"""
# <div class="insight-box">
# <div class="content" style="text-align:left;">
# {insight_text}
# </div>
# </div>
# """, unsafe_allow_html=True)
st.markdown('<h4 style="text-align:center; margin:15px 0 5px 0; font-weight:bold;">SUMMARY</h4>', unsafe_allow_html=True)
st.markdown(f"""
<div class="insight-box">
<div class="content" style="text-align:left;">
{summary_text}
</div>
</div>
""", unsafe_allow_html=True)
st.markdown('<h4 style="text-align:center; margin:15px 0 5px 0; font-weight:bold;">RECOMMENDATION & RISK MITIGATION</h4>', unsafe_allow_html=True)
st.markdown(f"""
<div class="insight-box">
<div class="content" style="text-align:left;">
{recommendation_text}
</div>
</div>
""", unsafe_allow_html=True)
st.markdown("""
<div style="
text-align: center;
padding: 12px 0 40px 0;
margin-top: 20px;
margin-bottom: 40px;
font-family: Arial, sans-serif;
border: none !important;
">
<span style="font-size: 10px; color: #7d7d7d;">
&copy; 2025 Bukit Teknologi Digital. All rights reserved.
</span>
</div>
""", unsafe_allow_html=True)