GitsSaikat commited on
Commit
8e9b78d
·
0 Parent(s):

first commit

Browse files
Pavement.jpg ADDED
app.py ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+
3
+ import streamlit as st
4
+ import pandas as pd
5
+ import numpy as np
6
+ from typing import Dict
7
+ from PIL import Image
8
+ import matplotlib.pyplot as plt
9
+
10
+ from src.models import TrafficData, ClimateData, SubgradeProperties, MaterialProperties, Pavement
11
+ from src.performance import design_new_pavement
12
+ from src.lcca import perform_LCCA
13
+ from src.reporting import generate_report, export_report_to_pdf
14
+ from src.design import design_pavement_structure
15
+ from src.utils.helpers import read_excel, save_pdf
16
+ from src.utils.logger import setup_logger
17
+
18
+ logger = setup_logger(__name__)
19
+
20
+ st.set_page_config(page_title="ME Pavement Design Tool", layout="wide")
21
+
22
+ st.title("🛣️ Mechanistic-Empirical Pavement Design Tool for Highways and Airports")
23
+
24
+ image = Image.open('Pavement.jpg')
25
+
26
+ # Display the image at the top of the sidebar
27
+ st.sidebar.image(image, use_container_width=True)
28
+
29
+ # Sidebar for Navigation
30
+ st.sidebar.title("Navigation")
31
+ app_mode = st.sidebar.selectbox("Choose the app mode",
32
+ ["Home", "Input Data", "Design Pavement", "Run Simulation", "View Results", "Generate Report"])
33
+
34
+ # Initialize session state
35
+ if 'simulation_results' not in st.session_state:
36
+ st.session_state.simulation_results = {}
37
+ if 'lcc' not in st.session_state:
38
+ st.session_state.lcc = 0.0
39
+ if 'maintenance_costs' not in st.session_state:
40
+ st.session_state.maintenance_costs = {}
41
+ if 'lcc_over_time' not in st.session_state:
42
+ st.session_state.lcc_over_time = {}
43
+ if 'pavement_design' not in st.session_state:
44
+ st.session_state.pavement_design = {}
45
+
46
+ # Home Page
47
+ if app_mode == "Home":
48
+ st.markdown("""
49
+ ## Welcome to the Mechanistic-Empirical Pavement Design Tool
50
+
51
+ This tool allows you to design new pavements and evaluate their performance based on traffic, material, and environmental data. Follow the navigation steps on the sidebar to input data, design pavement structures, run simulations, view results, and generate comprehensive reports.
52
+ """)
53
+
54
+ # Input Data Page
55
+ elif app_mode == "Input Data":
56
+ st.header("Input Data")
57
+
58
+ st.markdown("""
59
+ ### 📋 Dataset Format Instructions
60
+
61
+ Please ensure that your Excel file contains the following sheets with the specified columns like the example dataset.
62
+
63
+ **Example Dataset**:
64
+
65
+ - **Traffic Sheet**:
66
+
67
+ | Axle_Loads | Traffic_Growth_Rate | Analysis_Period |
68
+ |------------|---------------------|------------------|
69
+ | 80 | 2.0 | 20 |
70
+ | 100 | | |
71
+ | 120 | | |
72
+
73
+ - **Climate Sheet**:
74
+
75
+ | Average_Temperature | Temperature_Variation | Rainfall |
76
+ |---------------------|-----------------------|----------|
77
+ | 15 | 10 | 500 |
78
+
79
+ - **Subgrade Sheet**:
80
+
81
+ | Modulus | CBR |
82
+ |---------|-----|
83
+ | 3000 | 10 |
84
+
85
+ - **Materials Sheet**:
86
+
87
+ | Asphalt_Modulus | Concrete_Strength | Thermal_Coeff |
88
+ |-----------------|--------------------|---------------|
89
+ | 3000 | 30 | 0.0001 |
90
+ """)
91
+
92
+ st.subheader("Upload Input Data Excel File")
93
+ uploaded_file = st.file_uploader("Choose an Excel file with required data", type=["xlsx"])
94
+
95
+ if uploaded_file:
96
+ try:
97
+ data_sheets = read_excel(uploaded_file)
98
+ # Assuming sheets named 'Traffic', 'Climate', 'Subgrade', 'Materials'
99
+ traffic_df = data_sheets.get('Traffic') or data_sheets.get('Sheet1') # Fallback to first sheet
100
+ climate_df = data_sheets.get('Climate') or data_sheets.get('Sheet2')
101
+ subgrade_df = data_sheets.get('Subgrade') or data_sheets.get('Sheet3')
102
+ materials_df = data_sheets.get('Materials') or data_sheets.get('Sheet4')
103
+
104
+ # Create data model instances
105
+ traffic_data = TrafficData.from_dataframe(traffic_df)
106
+ climate_data = ClimateData.from_dataframe(climate_df)
107
+ subgrade_props = SubgradeProperties.from_dataframe(subgrade_df)
108
+ material_props = MaterialProperties.from_dataframe(materials_df)
109
+
110
+ # Store in session state
111
+ st.session_state.traffic_data = traffic_data
112
+ st.session_state.climate_data = climate_data
113
+ st.session_state.subgrade_props = subgrade_props
114
+ st.session_state.material_props = material_props
115
+
116
+ st.success("Data loaded successfully from the uploaded Excel file.")
117
+ except Exception as e:
118
+ st.error(f"Failed to load data: {e}")
119
+
120
+ st.markdown("""
121
+ ### Alternatively, Enter Data Manually
122
+ """)
123
+
124
+ with st.form("manual_data_form"):
125
+ st.subheader("Traffic Data")
126
+ axle_loads = st.text_input("Axle Loads (comma-separated in kN)", value="80, 100, 120")
127
+ traffic_growth_rate = st.number_input("Traffic Growth Rate (% per annum)", min_value=0.0, max_value=100.0, value=2.0, step=0.1)
128
+ analysis_period = st.number_input("Analysis Period (Years)", min_value=1, max_value=100, value=20, step=1)
129
+
130
+ st.subheader("Climate Data")
131
+ average_temperature = st.number_input("Average Temperature (°C)", value=15.0)
132
+ temperature_variation = st.number_input("Temperature Variation (°C)", value=10.0)
133
+ rainfall = st.number_input("Annual Rainfall (mm)", value=500.0)
134
+
135
+ st.subheader("Subgrade Properties")
136
+ modulus = st.number_input("Modulus of Subgrade Reaction (kPa/m)", value=3000.0)
137
+ CBR = st.number_input("California Bearing Ratio (CBR %)", value=10.0)
138
+
139
+ st.subheader("Material Properties")
140
+ asphalt_modulus = st.number_input("Asphalt Modulus (MPa)", value=3000.0)
141
+ concrete_strength = st.number_input("Concrete Strength (MPa)", value=30.0)
142
+ thermal_coeff = st.number_input("Thermal Coefficient (°C^-1)", value=0.0001)
143
+
144
+ submitted = st.form_submit_button("Submit Data")
145
+ if submitted:
146
+ try:
147
+ axle_loads_list = [float(load.strip()) for load in axle_loads.split(",")]
148
+ traffic_data = TrafficData(axle_loads=axle_loads_list,
149
+ traffic_growth_rate=traffic_growth_rate / 100,
150
+ analysis_period=int(analysis_period))
151
+ climate_data = ClimateData(average_temperature=average_temperature,
152
+ temperature_variation=temperature_variation,
153
+ rainfall=rainfall)
154
+ subgrade_props = SubgradeProperties(modulus=modulus, CBR=CBR)
155
+ material_props = MaterialProperties(asphalt_modulus=asphalt_modulus,
156
+ concrete_strength=concrete_strength,
157
+ thermal_coeff=thermal_coeff)
158
+
159
+ # Store in session state
160
+ st.session_state.traffic_data = traffic_data
161
+ st.session_state.climate_data = climate_data
162
+ st.session_state.subgrade_props = subgrade_props
163
+ st.session_state.material_props = material_props
164
+
165
+ st.success("Data entered successfully.")
166
+ except Exception as e:
167
+ st.error(f"Error in data entry: {e}")
168
+
169
+
170
+ # Design Pavement Page
171
+ elif app_mode == "Design Pavement":
172
+ st.header("Design Pavement Structure")
173
+
174
+ if ('traffic_data' in st.session_state and
175
+ 'climate_data' in st.session_state and
176
+ 'subgrade_props' in st.session_state and
177
+ 'material_props' in st.session_state):
178
+
179
+ st.subheader("Define Pavement Layers")
180
+ with st.form("pavement_design_form"):
181
+ # User inputs the number of pavement layers
182
+ num_layers = st.number_input(
183
+ "Number of Pavement Layers",
184
+ min_value=1,
185
+ max_value=10,
186
+ value=3,
187
+ step=1,
188
+ help="Specify the total number of pavement layers you wish to design."
189
+ )
190
+
191
+ layers = []
192
+ st.markdown("### Define Each Layer")
193
+ for i in range(1, int(num_layers) + 1):
194
+ st.markdown(f"**Layer {i}**")
195
+
196
+ # Select layer type
197
+ layer_type = st.selectbox(
198
+ f"Layer {i} Type",
199
+ options=["Asphalt", "Concrete", "Base", "Sub-base"],
200
+ key=f"layer_type_{i}",
201
+ help="Select the material type for this pavement layer."
202
+ )
203
+
204
+ # Input layer thickness
205
+ thickness = st.number_input(
206
+ f"Layer {i} Thickness (mm)",
207
+ min_value=1.0,
208
+ max_value=1000.0,
209
+ value=100.0,
210
+ step=1.0,
211
+ key=f"layer_thickness_{i}",
212
+ help="Enter the thickness of this layer in millimeters."
213
+ )
214
+
215
+ layers.append((layer_type, thickness)) # Store as tuple
216
+
217
+ st.markdown("### Define Cost per Layer Type")
218
+ st.write("Enter the cost per millimeter for each layer type. These costs will be used to calculate the total estimated cost of the pavement.")
219
+
220
+ # Input costs for each layer type
221
+ asphalt_cost = st.number_input(
222
+ "Asphalt Cost per mm ($)",
223
+ min_value=0.0,
224
+ value=50.0,
225
+ step=1.0,
226
+ help="Enter the cost per millimeter for Asphalt layers."
227
+ )
228
+ concrete_cost = st.number_input(
229
+ "Concrete Cost per mm ($)",
230
+ min_value=0.0,
231
+ value=80.0,
232
+ step=1.0,
233
+ help="Enter the cost per millimeter for Concrete layers."
234
+ )
235
+ base_cost = st.number_input(
236
+ "Base Cost per mm ($)",
237
+ min_value=0.0,
238
+ value=40.0,
239
+ step=1.0,
240
+ help="Enter the cost per millimeter for Base layers."
241
+ )
242
+ subbase_cost = st.number_input(
243
+ "Sub-base Cost per mm ($)",
244
+ min_value=0.0,
245
+ value=30.0,
246
+ step=1.0,
247
+ help="Enter the cost per millimeter for Sub-base layers."
248
+ )
249
+
250
+ # Submit button to define pavement structure
251
+ submitted = st.form_submit_button("Define Pavement Structure")
252
+ if submitted:
253
+ try:
254
+ # Create a dictionary for layer costs based on user input
255
+ layer_costs = {
256
+ "Asphalt": asphalt_cost,
257
+ "Concrete": concrete_cost,
258
+ "Base": base_cost,
259
+ "Sub-base": subbase_cost
260
+ }
261
+
262
+ # Store pavement design and layer costs in session state
263
+ st.session_state.pavement_design = layers
264
+ st.session_state.layer_costs = layer_costs
265
+ st.success("Pavement structure defined successfully.")
266
+ except Exception as e:
267
+ st.error(f"Error in pavement design: {e}")
268
+
269
+ if 'pavement_design' in st.session_state and 'layer_costs' in st.session_state:
270
+ st.subheader("Pavement Design Summary")
271
+ design_summary = st.session_state.pavement_design
272
+ layer_costs = st.session_state.layer_costs
273
+
274
+ # Perform Calculations Based on User Input
275
+ total_thickness = sum([thickness for _, thickness in design_summary])
276
+ total_cost = sum([layer_costs.get(layer_type, 0) * thickness for layer_type, thickness in design_summary])
277
+
278
+ # Predict Distresses (Simplified Example Formulas)
279
+ fatigue_cracking = total_thickness * 0.05 # Placeholder formula
280
+ rutting = total_thickness * 0.03
281
+ thermal_cracking = total_thickness * 0.02
282
+
283
+ # Display Calculation Results
284
+ st.write(f"**Total Pavement Thickness:** {total_thickness} mm")
285
+ st.write(f"**Estimated Total Cost:** ${total_cost:,.2f}")
286
+ st.write(f"**Predicted Fatigue Cracking:** {fatigue_cracking:.2f} cracks")
287
+ st.write(f"**Predicted Rutting:** {rutting:.2f} mm")
288
+ st.write(f"**Predicted Thermal Cracking:** {thermal_cracking:.2f} cracks")
289
+
290
+ st.subheader("Detailed Pavement Layers")
291
+ design_df = pd.DataFrame(design_summary, columns=["Layer Type", "Thickness (mm)"])
292
+ st.table(design_df)
293
+
294
+ # Optional: Visual Representation of Pavement Layers
295
+ st.markdown("### Pavement Structure Visualization")
296
+ fig, ax = plt.subplots(figsize=(6, 3))
297
+ current_y = 0
298
+ for layer_type, thickness in design_summary:
299
+ ax.barh(1, thickness, left=current_y, height=0.5, label=layer_type)
300
+ current_y += thickness
301
+ ax.set_xlabel("Thickness (mm)")
302
+ ax.set_yticks([])
303
+ ax.legend()
304
+ st.pyplot(fig)
305
+
306
+
307
+ # Run Simulation Page
308
+ elif app_mode == "Run Simulation":
309
+ st.header("Run Simulation")
310
+
311
+ if 'pavement_design' in st.session_state and 'traffic_data' in st.session_state and 'climate_data' in st.session_state and \
312
+ 'subgrade_props' in st.session_state and 'material_props' in st.session_state:
313
+
314
+ st.subheader("Simulation Parameters")
315
+ with st.form("simulation_parameters_form"):
316
+ initial_cost = st.number_input("Initial Construction Cost ($)", min_value=0.0, value=1000000.0, step=1000.0)
317
+ maintenance_costs_input = st.text_area("Maintenance Costs (Year:Cost, separated by commas)",
318
+ value="5:100000, 10:150000, 15:200000, 20:250000")
319
+ discount_rate = st.number_input("Discount Rate (% per annum)", min_value=0.0, max_value=100.0, value=3.0, step=0.1)
320
+ analysis_period = st.number_input("Lifecycle Analysis Period (Years)", min_value=1, max_value=100, value=20, step=1)
321
+
322
+ submitted = st.form_submit_button("Run Simulation")
323
+ if submitted:
324
+ try:
325
+ # Parse maintenance costs
326
+ maintenance_costs = {}
327
+ for item in maintenance_costs_input.split(","):
328
+ if ':' in item:
329
+ year, cost = item.strip().split(":")
330
+ maintenance_costs[int(year)] = float(cost)
331
+ else:
332
+ st.warning(f"Ignoring invalid maintenance cost entry: '{item}'")
333
+
334
+ # Retrieve data from session state
335
+ pavement_design = st.session_state.pavement_design
336
+ traffic_data = st.session_state.traffic_data
337
+ climate_data = st.session_state.climate_data
338
+ subgrade_props = st.session_state.subgrade_props
339
+ material_props = st.session_state.material_props
340
+
341
+ # Run simulation
342
+ simulation_results = design_new_pavement(pavement_design, traffic_data, climate_data, subgrade_props, material_props)
343
+ st.session_state.simulation_results = simulation_results
344
+
345
+ # Perform LCCA
346
+ lcc = perform_LCCA(initial_cost, maintenance_costs, discount_rate / 100, analysis_period)
347
+ st.session_state.lcc = lcc
348
+ st.session_state.maintenance_costs = maintenance_costs
349
+
350
+ # Calculate LCCA over time for visualization
351
+ lcc_over_time = []
352
+ cumulative_lcc = initial_cost
353
+ for year in range(1, analysis_period + 1):
354
+ maintenance_cost = maintenance_costs.get(year, 0)
355
+ discounted_cost = maintenance_cost / ((1 + discount_rate / 100) ** year)
356
+ cumulative_lcc += discounted_cost
357
+ lcc_over_time.append(cumulative_lcc)
358
+ st.session_state.lcc_over_time = lcc_over_time
359
+
360
+ st.success("Simulation and LCCA completed successfully.")
361
+
362
+ except Exception as e:
363
+ st.error(f"Error during simulation: {e}")
364
+ else:
365
+ st.warning("Please input the necessary data in the 'Input Data' and 'Design Pavement' sections before running simulations.")
366
+
367
+ # View Results Page
368
+ elif app_mode == "View Results":
369
+ st.header("Simulation Results")
370
+
371
+ if 'simulation_results' in st.session_state and st.session_state.simulation_results:
372
+ simulation_results = st.session_state.simulation_results
373
+ lcc = st.session_state.lcc
374
+ maintenance_costs = st.session_state.maintenance_costs
375
+ lcc_over_time = st.session_state.lcc_over_time
376
+
377
+ st.subheader("Pavement Performance Predictions")
378
+ df_results = pd.DataFrame(list(simulation_results.items()), columns=["Distress Type", "Value"])
379
+ st.table(df_results)
380
+
381
+ st.subheader("Lifecycle Cost Analysis (LCCA)")
382
+ st.write(f"**Total Lifecycle Cost:** ${lcc:,.2f}")
383
+
384
+ # Visualization 1: Pie Chart of Distress Types
385
+ st.subheader("Distribution of Pavement Distresses")
386
+ pie_chart_data = df_results.set_index('Distress Type')
387
+ st.pyplot(pie_chart_data.plot.pie(y='Value', autopct='%1.1f%%', figsize=(6, 6)).figure)
388
+
389
+ # Visualization 2: Bar Chart of Distress Types
390
+ st.subheader("Pavement Distresses Overview")
391
+ st.bar_chart(df_results.set_index('Distress Type'))
392
+
393
+ # Visualization 3: Line Chart of Lifecycle Cost Over Time
394
+ if lcc_over_time:
395
+ st.subheader("Lifecycle Cost Over Time")
396
+ years = list(range(1, len(lcc_over_time) + 1))
397
+ cost_data = pd.DataFrame({
398
+ 'Year': years,
399
+ 'Cumulative LCC': lcc_over_time
400
+ })
401
+ st.line_chart(cost_data.set_index('Year'))
402
+
403
+ # Detailed Breakdown Table
404
+ st.subheader("Maintenance Costs Over Time")
405
+ maintenance_df = pd.DataFrame({
406
+ 'Year': list(maintenance_costs.keys()),
407
+ 'Maintenance Cost ($)': list(maintenance_costs.values())
408
+ }).sort_values('Year')
409
+ st.table(maintenance_df)
410
+
411
+ # Visualization 4: Line Chart of Cumulative LCCA
412
+ st.subheader("Cumulative Lifecycle Cost Analysis")
413
+ st.line_chart(cost_data.set_index('Year'))
414
+
415
+ # Visualization 5: Comparison of Initial Cost vs LCCA
416
+ st.subheader("Initial Cost vs Total Lifecycle Cost")
417
+ initial_cost = st.session_state.get('initial_cost', 0)
418
+ comparison_df = pd.DataFrame({
419
+ 'Cost Type': ['Initial Construction Cost', 'Total Lifecycle Cost'],
420
+ 'Amount ($)': [initial_cost, lcc]
421
+ })
422
+ st.bar_chart(comparison_df.set_index('Cost Type'))
423
+
424
+ # Additional Visualization: Pie Chart of Maintenance Cost Distribution
425
+ if maintenance_costs:
426
+ st.subheader("Maintenance Cost Distribution")
427
+ maintenance_df_pie = pd.DataFrame({
428
+ 'Year': list(maintenance_costs.keys()),
429
+ 'Maintenance Cost ($)': list(maintenance_costs.values())
430
+ }).sort_values('Year')
431
+ st.pyplot(maintenance_df_pie.plot.pie(y='Maintenance Cost ($)', labels=maintenance_df_pie['Year'], autopct='%1.1f%%', figsize=(6,6)).figure)
432
+
433
+ # Pavement Design Results
434
+ if 'pavement_design' in st.session_state and st.session_state.pavement_design:
435
+ st.subheader("Pavement Design Results")
436
+ pavement_design = st.session_state.pavement_design
437
+ design_df = pd.DataFrame(pavement_design, columns=["Layer Type", "Thickness (mm)"])
438
+ st.table(design_df)
439
+
440
+ else:
441
+ st.warning("No simulation results to display. Please run a simulation first.")
442
+
443
+ # Generate Report Page
444
+ elif app_mode == "Generate Report":
445
+ st.header("Generate Report")
446
+
447
+ if 'simulation_results' in st.session_state and st.session_state.simulation_results and \
448
+ 'lcc' in st.session_state and st.session_state.lcc > 0 and \
449
+ 'maintenance_costs' in st.session_state and st.session_state.maintenance_costs:
450
+ simulation_results = st.session_state.simulation_results
451
+ lcc = st.session_state.lcc
452
+ maintenance_costs = st.session_state.maintenance_costs
453
+ lcc_over_time = st.session_state.lcc_over_time
454
+
455
+ st.subheader("Review Results Before Report Generation")
456
+ df_results = pd.DataFrame(list(simulation_results.items()), columns=["Distress Type", "Value"])
457
+ st.table(df_results)
458
+ st.write(f"**Lifecycle Cost Analysis (LCCA):** ${lcc:,.2f}")
459
+
460
+ st.subheader("Maintenance Costs Breakdown")
461
+ maintenance_df = pd.DataFrame({
462
+ 'Year': list(maintenance_costs.keys()),
463
+ 'Maintenance Cost ($)': list(maintenance_costs.values())
464
+ }).sort_values('Year')
465
+ st.table(maintenance_df)
466
+
467
+ st.subheader("Lifecycle Cost Over Time")
468
+ if lcc_over_time:
469
+ years = list(range(1, len(lcc_over_time) + 1))
470
+ cost_data = pd.DataFrame({
471
+ 'Year': years,
472
+ 'Cumulative LCC': lcc_over_time
473
+ })
474
+ st.line_chart(cost_data.set_index('Year'))
475
+
476
+ generate_report_btn = st.button("Generate and Download Report")
477
+ if generate_report_btn:
478
+ try:
479
+ report_content = generate_report(simulation_results, lcc)
480
+ report_path = "pavement_design_report.pdf"
481
+ export_report_to_pdf(report_content, report_path)
482
+ with open(report_path, "rb") as pdf_file:
483
+ PDFbyte = pdf_file.read()
484
+ st.download_button(label="Download Report as PDF", data=PDFbyte, file_name="pavement_design_report.pdf", mime='application/octet-stream')
485
+ st.success("Report generated and ready for download.")
486
+ except Exception as e:
487
+ st.error(f"Failed to generate report: {e}")
488
+ else:
489
+ st.warning("No simulation results available. Please run a simulation first.")
me_pavement_design.log ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 2024-12-22 12:01:33,543 - src.performance - INFO - Total Fatigue Damage: 0.004472024810545181
2
+ 2024-12-22 12:01:33,544 - src.performance - INFO - Total Rutting: 1.2148684899458864 mm
3
+ 2024-12-22 12:01:33,546 - src.performance - INFO - Thermal Cracking Index: 0.001
4
+ 2024-12-22 12:01:33,546 - src.performance - INFO - Pavement design simulation completed.
5
+ 2024-12-22 12:01:33,546 - src.lcca - INFO - Starting Life-Cycle Cost Analysis (LCCA).
6
+ 2024-12-22 12:01:33,547 - src.lcca - INFO - Initial Cost: $1,000,000.00
7
+ 2024-12-22 12:01:33,547 - src.lcca - INFO - Total Lifecycle Cost (LCCA): $1,464,666.29
8
+ 2024-12-22 12:09:07,879 - src.performance - INFO - Total Fatigue Damage: 0.01724620834913378
9
+ 2024-12-22 12:09:07,879 - src.performance - INFO - Total Rutting: 2.0822954143592756 mm
10
+ 2024-12-22 12:09:07,880 - src.performance - INFO - Thermal Cracking Index: 0.001
11
+ 2024-12-22 12:09:07,880 - src.performance - INFO - Pavement design simulation completed.
12
+ 2024-12-22 12:09:07,881 - src.lcca - INFO - Starting Life-Cycle Cost Analysis (LCCA).
13
+ 2024-12-22 12:09:07,881 - src.lcca - INFO - Initial Cost: $1,000,000.00
14
+ 2024-12-22 12:09:07,882 - src.lcca - INFO - Total Lifecycle Cost (LCCA): $1,464,666.29
15
+ 2024-12-22 12:38:41,947 - src.performance - INFO - Total Fatigue Damage: 0.004472024810545181
16
+ 2024-12-22 12:38:41,950 - src.performance - INFO - Total Rutting: 1.2148684899458864 mm
17
+ 2024-12-22 12:38:41,950 - src.performance - INFO - Thermal Cracking Index: 0.001
18
+ 2024-12-22 12:38:41,950 - src.performance - INFO - Pavement design simulation completed.
19
+ 2024-12-22 12:38:41,950 - src.lcca - INFO - Starting Life-Cycle Cost Analysis (LCCA).
20
+ 2024-12-22 12:38:41,951 - src.lcca - INFO - Initial Cost: $1,000,000.00
21
+ 2024-12-22 12:38:41,951 - src.lcca - INFO - Total Lifecycle Cost (LCCA): $1,464,666.29
22
+ 2024-12-22 13:01:04,873 - src.performance - INFO - Total Fatigue Damage: 0.004472024810545181
23
+ 2024-12-22 13:01:04,875 - src.performance - INFO - Total Rutting: 1.2148684899458864 mm
24
+ 2024-12-22 13:01:04,877 - src.performance - INFO - Thermal Cracking Index: 0.001
25
+ 2024-12-22 13:01:04,877 - src.performance - INFO - Pavement design simulation completed.
26
+ 2024-12-22 13:01:04,877 - src.lcca - INFO - Starting Life-Cycle Cost Analysis (LCCA).
27
+ 2024-12-22 13:01:04,878 - src.lcca - INFO - Initial Cost: $1,000,000.00
28
+ 2024-12-22 13:01:04,878 - src.lcca - INFO - Total Lifecycle Cost (LCCA): $1,464,666.29
29
+ 2024-12-22 13:01:35,819 - src.reporting - INFO - Report generated successfully.
30
+ 2024-12-22 13:01:35,820 - src.reporting - ERROR - ReportLab is not installed. Please install it using 'pip install reportlab'
31
+ 2024-12-22 13:02:54,979 - src.performance - INFO - Total Fatigue Damage: 0.004472024810545181
32
+ 2024-12-22 13:02:54,982 - src.performance - INFO - Total Rutting: 1.2148684899458864 mm
33
+ 2024-12-22 13:02:54,982 - src.performance - INFO - Thermal Cracking Index: 0.001
34
+ 2024-12-22 13:02:54,982 - src.performance - INFO - Pavement design simulation completed.
35
+ 2024-12-22 13:02:54,983 - src.lcca - INFO - Starting Life-Cycle Cost Analysis (LCCA).
36
+ 2024-12-22 13:02:54,983 - src.lcca - INFO - Initial Cost: $1,000,000.00
37
+ 2024-12-22 13:02:54,983 - src.lcca - INFO - Total Lifecycle Cost (LCCA): $1,464,666.29
38
+ 2024-12-22 13:03:14,347 - src.reporting - INFO - Report generated successfully.
39
+ 2024-12-22 13:03:14,371 - src.reporting - INFO - Report exported to PDF at pavement_design_report.pdf
40
+ 2024-12-22 13:11:53,158 - src.performance - INFO - Total Fatigue Damage: 0.004472024810545181
41
+ 2024-12-22 13:11:53,161 - src.performance - INFO - Total Rutting: 1.2148684899458864 mm
42
+ 2024-12-22 13:11:53,161 - src.performance - INFO - Thermal Cracking Index: 0.001
43
+ 2024-12-22 13:11:53,161 - src.performance - INFO - Pavement design simulation completed.
44
+ 2024-12-22 13:11:53,162 - src.lcca - INFO - Starting Life-Cycle Cost Analysis (LCCA).
45
+ 2024-12-22 13:11:53,162 - src.lcca - INFO - Initial Cost: $1,000,000.00
46
+ 2024-12-22 13:11:53,162 - src.lcca - INFO - Total Lifecycle Cost (LCCA): $1,464,666.29
47
+ 2024-12-22 13:12:17,973 - src.reporting - INFO - Report generated successfully.
48
+ 2024-12-22 13:12:17,995 - src.reporting - INFO - Report exported to PDF at pavement_design_report.pdf
49
+ 2024-12-22 13:37:33,916 - src.performance - INFO - Total Fatigue Damage: 0.004472024810545181
50
+ 2024-12-22 13:37:33,917 - src.performance - INFO - Total Rutting: 1.2148684899458864 mm
51
+ 2024-12-22 13:37:33,918 - src.performance - INFO - Thermal Cracking Index: 0.001
52
+ 2024-12-22 13:37:33,919 - src.performance - INFO - Pavement design simulation completed.
53
+ 2024-12-22 13:37:33,920 - src.lcca - INFO - Starting Life-Cycle Cost Analysis (LCCA).
54
+ 2024-12-22 13:37:33,920 - src.lcca - INFO - Initial Cost: $1,000,000.00
55
+ 2024-12-22 13:37:33,920 - src.lcca - INFO - Total Lifecycle Cost (LCCA): $1,464,666.29
56
+ 2024-12-22 13:47:26,229 - src.performance - INFO - Total Fatigue Damage: 0.004472024810545181
57
+ 2024-12-22 13:47:26,230 - src.performance - INFO - Total Rutting: 1.2148684899458864 mm
58
+ 2024-12-22 13:47:26,230 - src.performance - INFO - Thermal Cracking Index: 0.001
59
+ 2024-12-22 13:47:26,231 - src.performance - INFO - Pavement design simulation completed.
60
+ 2024-12-22 13:47:26,231 - src.lcca - INFO - Starting Life-Cycle Cost Analysis (LCCA).
61
+ 2024-12-22 13:47:26,232 - src.lcca - INFO - Initial Cost: $1,000,000.00
62
+ 2024-12-22 13:47:26,232 - src.lcca - INFO - Total Lifecycle Cost (LCCA): $1,464,666.29
63
+ 2024-12-22 14:01:58,282 - src.performance - INFO - Total Fatigue Damage: 0.004472024810545181
64
+ 2024-12-22 14:01:58,284 - src.performance - INFO - Total Rutting: 1.2148684899458864 mm
65
+ 2024-12-22 14:01:58,284 - src.performance - INFO - Thermal Cracking Index: 0.001
66
+ 2024-12-22 14:01:58,284 - src.performance - INFO - Pavement design simulation completed.
67
+ 2024-12-22 14:01:58,285 - src.lcca - INFO - Starting Life-Cycle Cost Analysis (LCCA).
68
+ 2024-12-22 14:01:58,285 - src.lcca - INFO - Initial Cost: $1,000,000.00
69
+ 2024-12-22 14:01:58,285 - src.lcca - INFO - Total Lifecycle Cost (LCCA): $1,464,666.29
70
+ 2024-12-22 14:02:55,470 - src.reporting - INFO - Report generated successfully.
71
+ 2024-12-22 14:02:55,493 - src.reporting - INFO - Report exported to PDF at pavement_design_report.pdf
72
+ 2024-12-22 14:04:45,178 - src.performance - INFO - Total Fatigue Damage: 0.004472024810545181
73
+ 2024-12-22 14:04:45,179 - src.performance - INFO - Total Rutting: 1.2148684899458864 mm
74
+ 2024-12-22 14:04:45,180 - src.performance - INFO - Thermal Cracking Index: 0.001
75
+ 2024-12-22 14:04:45,180 - src.performance - INFO - Pavement design simulation completed.
76
+ 2024-12-22 14:04:45,181 - src.lcca - INFO - Starting Life-Cycle Cost Analysis (LCCA).
77
+ 2024-12-22 14:04:45,181 - src.lcca - INFO - Initial Cost: $1,000,000.00
78
+ 2024-12-22 14:04:45,182 - src.lcca - INFO - Total Lifecycle Cost (LCCA): $1,464,666.29
79
+ 2024-12-22 14:15:49,886 - src.performance - INFO - Total Fatigue Damage: 0.004472024810545181
80
+ 2024-12-22 14:15:49,887 - src.performance - INFO - Total Rutting: 1.2148684899458864 mm
81
+ 2024-12-22 14:15:49,887 - src.performance - INFO - Thermal Cracking Index: 0.001
82
+ 2024-12-22 14:15:49,887 - src.performance - INFO - Pavement design simulation completed.
83
+ 2024-12-22 14:15:49,889 - src.lcca - INFO - Starting Life-Cycle Cost Analysis (LCCA).
84
+ 2024-12-22 14:15:49,890 - src.lcca - INFO - Initial Cost: $1,000,000.00
85
+ 2024-12-22 14:15:49,891 - src.lcca - INFO - Total Lifecycle Cost (LCCA): $1,464,666.29
86
+ 2024-12-22 14:30:46,841 - src.performance - INFO - Total Fatigue Damage: 0.004472024810545181
87
+ 2024-12-22 14:30:46,843 - src.performance - INFO - Total Rutting: 1.2148684899458864 mm
88
+ 2024-12-22 14:30:46,843 - src.performance - INFO - Thermal Cracking Index: 0.001
89
+ 2024-12-22 14:30:46,843 - src.performance - INFO - Pavement design simulation completed.
90
+ 2024-12-22 14:30:46,845 - src.lcca - INFO - Starting Life-Cycle Cost Analysis (LCCA).
91
+ 2024-12-22 14:30:46,845 - src.lcca - INFO - Initial Cost: $1,000,000.00
92
+ 2024-12-22 14:30:46,845 - src.lcca - INFO - Total Lifecycle Cost (LCCA): $1,464,666.29
93
+ 2024-12-22 14:49:36,575 - src.performance - INFO - Total Fatigue Damage: 0.004472024810545181
94
+ 2024-12-22 14:49:36,576 - src.performance - INFO - Total Rutting: 1.2148684899458864 mm
95
+ 2024-12-22 14:49:36,577 - src.performance - INFO - Thermal Cracking Index: 0.001
96
+ 2024-12-22 14:49:36,577 - src.performance - INFO - Pavement design simulation completed.
97
+ 2024-12-22 14:49:36,577 - src.lcca - INFO - Starting Life-Cycle Cost Analysis (LCCA).
98
+ 2024-12-22 14:49:36,577 - src.lcca - INFO - Initial Cost: $1,000,000.00
99
+ 2024-12-22 14:49:36,578 - src.lcca - INFO - Total Lifecycle Cost (LCCA): $1,464,666.29
pavement_design_report.pdf ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ %PDF-1.3
2
+ %���� ReportLab Generated PDF document http://www.reportlab.com
3
+ 1 0 obj
4
+ <<
5
+ /F1 2 0 R
6
+ >>
7
+ endobj
8
+ 2 0 obj
9
+ <<
10
+ /BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font
11
+ >>
12
+ endobj
13
+ 3 0 obj
14
+ <<
15
+ /Contents 7 0 R /MediaBox [ 0 0 612 792 ] /Parent 6 0 R /Resources <<
16
+ /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
17
+ >> /Rotate 0 /Trans <<
18
+
19
+ >>
20
+ /Type /Page
21
+ >>
22
+ endobj
23
+ 4 0 obj
24
+ <<
25
+ /PageMode /UseNone /Pages 6 0 R /Type /Catalog
26
+ >>
27
+ endobj
28
+ 5 0 obj
29
+ <<
30
+ /Author (anonymous) /CreationDate (D:20241222140255+00'00') /Creator (ReportLab PDF Library - www.reportlab.com) /Keywords () /ModDate (D:20241222140255+00'00') /Producer (ReportLab PDF Library - www.reportlab.com)
31
+ /Subject (unspecified) /Title (untitled) /Trapped /False
32
+ >>
33
+ endobj
34
+ 6 0 obj
35
+ <<
36
+ /Count 1 /Kids [ 3 0 R ] /Type /Pages
37
+ >>
38
+ endobj
39
+ 7 0 obj
40
+ <<
41
+ /Filter [ /ASCII85Decode /FlateDecode ] /Length 385
42
+ >>
43
+ stream
44
+ Gat$s9l%X#%))C:kcdE9g+3_:7KY_o=aTG,'H_\l>d`,EO3DbOrV,n=)NkO6Q&WW.H[=])%+;XfHV+b:`8PUQJ7ZM,_"&`U^4mpU`B<HP\aHU2=kmlV06-oAng"Y>5]X<_2*$gd_+&gH7MF\t4WOuJZ*l8YJA2-"L%43REM9i5Y58FZ_)a0,7+aKSP71u]00>l\^X9ku,1*S\W18t<A<%t38Xef9*FRWTd,nJoZ$bEiq$Eh/qF+rZ@,*U[:nFM@rN-U70LD<nH.\,.<OLIRXr`qa&2f5[9=SEZ]Z@!>;'ahB0L03/</lsiPl8^t^A,5<GpSFe4G6gVpsDnp'^D:-dSW8"!a^SA-#6\_-f$3@m<`C>7KoFV`T,9rd2.J,Z#p~>endstream
45
+ endobj
46
+ xref
47
+ 0 8
48
+ 0000000000 65535 f
49
+ 0000000073 00000 n
50
+ 0000000104 00000 n
51
+ 0000000211 00000 n
52
+ 0000000404 00000 n
53
+ 0000000472 00000 n
54
+ 0000000768 00000 n
55
+ 0000000827 00000 n
56
+ trailer
57
+ <<
58
+ /ID
59
+ [<0765494f4f6e22fe0b5d4856b52b1ee6><0765494f4f6e22fe0b5d4856b52b1ee6>]
60
+ % ReportLab generated PDF document -- digest (http://www.reportlab.com)
61
+
62
+ /Info 5 0 R
63
+ /Root 4 0 R
64
+ /Size 8
65
+ >>
66
+ startxref
67
+ 1302
68
+ %%EOF
src/__pycache__/design.cpython-312.pyc ADDED
Binary file (847 Bytes). View file
 
src/__pycache__/lcca.cpython-312.pyc ADDED
Binary file (2.33 kB). View file
 
src/__pycache__/models.cpython-312.pyc ADDED
Binary file (11.5 kB). View file
 
src/__pycache__/performance.cpython-312.pyc ADDED
Binary file (4.98 kB). View file
 
src/__pycache__/reporting.cpython-312.pyc ADDED
Binary file (3.28 kB). View file
 
src/__pycache__/utils.cpython-312.pyc ADDED
Binary file (2.55 kB). View file
 
src/design.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # src/design.py
2
+
3
+ from typing import List, Tuple
4
+
5
+ def design_pavement_structure(layers: List[Tuple[str, float]]) -> List[Tuple[str, float]]:
6
+ """
7
+ Process the defined pavement layers and structure.
8
+
9
+ :param layers: List of tuples containing layer type and thickness.
10
+ :return: List of tuples representing the pavement design.
11
+ """
12
+ try:
13
+ pavement_design = layers # In this simple case, just return the layers as is
14
+ return pavement_design
15
+ except Exception as e:
16
+ raise ValueError(f"Error in pavement structure design: {e}")
src/lcca.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # src/lcca.py
2
+
3
+ import logging
4
+ from typing import Dict
5
+
6
+ from src.utils.logger import setup_logger
7
+
8
+ logger = setup_logger(__name__)
9
+
10
+
11
+ def calculate_LCCA(initial_cost: float, maintenance_costs: Dict[int, float], discount_rate: float, analysis_period: int) -> float:
12
+ """
13
+ Calculate the Life-Cycle Cost Analysis (LCCA) for the pavement.
14
+
15
+ :param initial_cost: Initial construction cost.
16
+ :param maintenance_costs: Maintenance costs with year as key.
17
+ :param discount_rate: Annual discount rate (decimal, e.g., 0.03 for 3%).
18
+ :param analysis_period: Number of years to analyze.
19
+ :return: Present value of total lifecycle costs.
20
+ """
21
+ lcc = initial_cost
22
+ logger.info(f"Initial Cost: ${initial_cost:,.2f}")
23
+ for year in range(1, analysis_period + 1):
24
+ maintenance_cost = maintenance_costs.get(year, 0)
25
+ discounted_cost = maintenance_cost / ((1 + discount_rate) ** year)
26
+ lcc += discounted_cost
27
+ if maintenance_cost > 0:
28
+ logger.debug(f"Year {year}: Maintenance Cost ${maintenance_cost:,.2f}, Discounted Cost ${discounted_cost:,.2f}")
29
+ logger.info(f"Total Lifecycle Cost (LCCA): ${lcc:,.2f}")
30
+ return lcc
31
+
32
+
33
+ def perform_LCCA(initial_cost: float, maintenance_costs: Dict[int, float], discount_rate: float, analysis_period: int) -> float:
34
+ """
35
+ Wrapper function to perform LCCA.
36
+
37
+ :param initial_cost: Initial construction cost.
38
+ :param maintenance_costs: Maintenance costs with year as key.
39
+ :param discount_rate: Annual discount rate.
40
+ :param analysis_period: Number of years to analyze.
41
+ :return: Present value of total lifecycle costs.
42
+ """
43
+ logger.info("Starting Life-Cycle Cost Analysis (LCCA).")
44
+ return calculate_LCCA(initial_cost, maintenance_costs, discount_rate, analysis_period)
src/models.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # src/models.py
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+ from typing import List, Dict
6
+ import logging
7
+
8
+ from src.utils.logger import setup_logger
9
+
10
+ logger = setup_logger(__name__)
11
+
12
+
13
+ class TrafficData:
14
+ def __init__(self, axle_loads: List[float], traffic_growth_rate: float, analysis_period: int):
15
+ """
16
+ Initialize TrafficData with axle loads, growth rate, and analysis period.
17
+
18
+ :param axle_loads: List of axle loads in kN.
19
+ :param traffic_growth_rate: Annual traffic growth rate (decimal, e.g., 0.02 for 2%).
20
+ :param analysis_period: Number of years for analysis.
21
+ """
22
+ self.axle_loads = axle_loads
23
+ self.traffic_growth_rate = traffic_growth_rate
24
+ self.analysis_period = analysis_period
25
+
26
+ def get_total_axle_loads(self) -> List[List[float]]:
27
+ """
28
+ Project total axle loads over the analysis period considering growth rate.
29
+
30
+ :return: A list of lists, each sublist represents axle loads for a year.
31
+ """
32
+ total_loads = []
33
+ for year in range(self.analysis_period):
34
+ growth_factor = (1 + self.traffic_growth_rate) ** year
35
+ projected_loads = [load * growth_factor for load in self.axle_loads]
36
+ total_loads.append(projected_loads)
37
+ logger.debug(f"Year {year + 1}: {projected_loads}")
38
+ return total_loads
39
+
40
+ @staticmethod
41
+ def from_dataframe(df: pd.DataFrame) -> 'TrafficData':
42
+ """
43
+ Create TrafficData instance from a pandas DataFrame.
44
+
45
+ :param df: DataFrame with columns 'Axle_Loads', 'Traffic_Growth_Rate', 'Analysis_Period'.
46
+ :return: TrafficData instance.
47
+ """
48
+ try:
49
+ axle_loads = df['Axle_Loads'].dropna().tolist()
50
+ traffic_growth_rate = float(df['Traffic_Growth_Rate'].iloc[0])
51
+ analysis_period = int(df['Analysis_Period'].iloc[0])
52
+ logger.info("TrafficData loaded successfully from DataFrame.")
53
+ return TrafficData(axle_loads, traffic_growth_rate, analysis_period)
54
+ except Exception as e:
55
+ logger.error(f"Error creating TrafficData from DataFrame: {e}")
56
+ raise ValueError(f"Invalid Traffic Data: {e}")
57
+
58
+
59
+ class ClimateData:
60
+ def __init__(self, average_temperature: float, temperature_variation: float, rainfall: float):
61
+ """
62
+ Initialize ClimateData with average temperature, temperature variation, and rainfall.
63
+
64
+ :param average_temperature: Average temperature in °C.
65
+ :param temperature_variation: Temperature variation in °C.
66
+ :param rainfall: Annual rainfall in mm.
67
+ """
68
+ self.average_temperature = average_temperature
69
+ self.temperature_variation = temperature_variation
70
+ self.rainfall = rainfall
71
+
72
+ @staticmethod
73
+ def from_dataframe(df: pd.DataFrame) -> 'ClimateData':
74
+ """
75
+ Create ClimateData instance from a pandas DataFrame.
76
+
77
+ :param df: DataFrame with columns 'Average_Temperature', 'Temperature_Variation', 'Rainfall'.
78
+ :return: ClimateData instance.
79
+ """
80
+ try:
81
+ average_temperature = float(df['Average_Temperature'].iloc[0])
82
+ temperature_variation = float(df['Temperature_Variation'].iloc[0])
83
+ rainfall = float(df['Rainfall'].iloc[0])
84
+ logger.info("ClimateData loaded successfully from DataFrame.")
85
+ return ClimateData(average_temperature, temperature_variation, rainfall)
86
+ except Exception as e:
87
+ logger.error(f"Error creating ClimateData from DataFrame: {e}")
88
+ raise ValueError(f"Invalid Climate Data: {e}")
89
+
90
+
91
+ class SubgradeProperties:
92
+ def __init__(self, modulus: float, CBR: float):
93
+ """
94
+ Initialize SubgradeProperties with modulus and California Bearing Ratio (CBR).
95
+
96
+ :param modulus: Modulus of subgrade reaction in kPa/m.
97
+ :param CBR: California Bearing Ratio in %.
98
+ """
99
+ self.modulus = modulus
100
+ self.CBR = CBR
101
+
102
+ @staticmethod
103
+ def from_dataframe(df: pd.DataFrame) -> 'SubgradeProperties':
104
+ """
105
+ Create SubgradeProperties instance from a pandas DataFrame.
106
+
107
+ :param df: DataFrame with columns 'Modulus', 'CBR'.
108
+ :return: SubgradeProperties instance.
109
+ """
110
+ try:
111
+ modulus = float(df['Modulus'].iloc[0])
112
+ CBR = float(df['CBR'].iloc[0])
113
+ logger.info("SubgradeProperties loaded successfully from DataFrame.")
114
+ return SubgradeProperties(modulus, CBR)
115
+ except Exception as e:
116
+ logger.error(f"Error creating SubgradeProperties from DataFrame: {e}")
117
+ raise ValueError(f"Invalid Subgrade Properties Data: {e}")
118
+
119
+
120
+ class MaterialProperties:
121
+ def __init__(self, asphalt_modulus: float, concrete_strength: float, thermal_coeff: float):
122
+ """
123
+ Initialize MaterialProperties with asphalt modulus, concrete strength, and thermal coefficient.
124
+
125
+ :param asphalt_modulus: Asphalt modulus in MPa.
126
+ :param concrete_strength: Concrete strength in MPa.
127
+ :param thermal_coeff: Thermal coefficient (°C^-1).
128
+ """
129
+ self.asphalt_modulus = asphalt_modulus
130
+ self.concrete_strength = concrete_strength
131
+ self.thermal_coeff = thermal_coeff
132
+
133
+ @staticmethod
134
+ def from_dataframe(df: pd.DataFrame) -> 'MaterialProperties':
135
+ """
136
+ Create MaterialProperties instance from a pandas DataFrame.
137
+
138
+ :param df: DataFrame with columns 'Asphalt_Modulus', 'Concrete_Strength', 'Thermal_Coeff'.
139
+ :return: MaterialProperties instance.
140
+ """
141
+ try:
142
+ asphalt_modulus = float(df['Asphalt_Modulus'].iloc[0])
143
+ concrete_strength = float(df['Concrete_Strength'].iloc[0])
144
+ thermal_coeff = float(df['Thermal_Coeff'].iloc[0])
145
+ logger.info("MaterialProperties loaded successfully from DataFrame.")
146
+ return MaterialProperties(asphalt_modulus, concrete_strength, thermal_coeff)
147
+ except Exception as e:
148
+ logger.error(f"Error creating MaterialProperties from DataFrame: {e}")
149
+ raise ValueError(f"Invalid Material Properties Data: {e}")
150
+
151
+
152
+ class Pavement:
153
+ def __init__(self, layers: List[float], pavement_type: str = 'Flexible'):
154
+ """
155
+ Initialize Pavement structure.
156
+
157
+ :param layers: List of layer thicknesses in mm.
158
+ :param pavement_type: Type of pavement ('Flexible', 'Rigid', 'Composite').
159
+ """
160
+ self.layers = layers
161
+ self.pavement_type = pavement_type
162
+
163
+ def add_layer(self, thickness: float):
164
+ """
165
+ Add a new layer to the pavement structure.
166
+
167
+ :param thickness: Thickness of the new layer in mm.
168
+ """
169
+ self.layers.append(thickness)
170
+ logger.debug(f"Added layer: {thickness} mm. Total layers: {self.layers}")
171
+
172
+ def remove_layer(self, index: int):
173
+ """
174
+ Remove a layer from the pavement structure by index.
175
+
176
+ :param index: Index of the layer to remove.
177
+ """
178
+ if 0 <= index < len(self.layers):
179
+ removed = self.layers.pop(index)
180
+ logger.debug(f"Removed layer at index {index}: {removed} mm. Remaining layers: {self.layers}")
181
+ else:
182
+ logger.warning(f"Attempted to remove non-existent layer at index {index}.")
183
+
184
+ def set_pavement_type(self, pavement_type: str):
185
+ """
186
+ Set the type of pavement.
187
+
188
+ :param pavement_type: Type of pavement ('Flexible', 'Rigid', 'Composite').
189
+ """
190
+ if pavement_type in ['Flexible', 'Rigid', 'Composite']:
191
+ self.pavement_type = pavement_type
192
+ logger.debug(f"Pavement type set to {pavement_type}.")
193
+ else:
194
+ logger.error(f"Invalid pavement type: {pavement_type}. Must be 'Flexible', 'Rigid', or 'Composite'.")
195
+ raise ValueError("Invalid pavement type. Choose from 'Flexible', 'Rigid', or 'Composite'.")
src/performance.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # src/performance.py
2
+
3
+ import logging
4
+ from typing import Dict
5
+
6
+ from src.models import Pavement, TrafficData, ClimateData, SubgradeProperties, MaterialProperties
7
+ from src.utils.logger import setup_logger
8
+
9
+ logger = setup_logger(__name__)
10
+
11
+
12
+ def predict_fatigue_cracking(pavement: Pavement, traffic_data: TrafficData, material_props: MaterialProperties) -> float:
13
+ """
14
+ Predict fatigue cracking based on axle loads and material properties.
15
+
16
+ :param pavement: Pavement structure.
17
+ :param traffic_data: Traffic data.
18
+ :param material_props: Material properties.
19
+ :return: Total fatigue damage.
20
+ """
21
+ total_damage = 0
22
+ axle_loads = traffic_data.get_total_axle_loads()
23
+ for year, loads in enumerate(axle_loads):
24
+ for load in loads:
25
+ damage = (load / material_props.asphalt_modulus) ** 3 # Simplified relationship
26
+ total_damage += damage
27
+ logger.debug(f"Year {year + 1}, Load {load} kN: Damage {damage}")
28
+ logger.info(f"Total Fatigue Damage: {total_damage}")
29
+ return total_damage
30
+
31
+
32
+ def predict_rutting(pavement: Pavement, traffic_data: TrafficData, climate_data: ClimateData, subgrade_props: SubgradeProperties) -> float:
33
+ """
34
+ Predict rutting based on axle loads, climate data, and subgrade properties.
35
+
36
+ :param pavement: Pavement structure.
37
+ :param traffic_data: Traffic data.
38
+ :param climate_data: Climate data.
39
+ :param subgrade_props: Subgrade properties.
40
+ :return: Total rutting depth.
41
+ """
42
+ total_rut = 0
43
+ axle_loads = traffic_data.get_total_axle_loads()
44
+ for year, loads in enumerate(axle_loads):
45
+ for load in loads:
46
+ rut = (load / subgrade_props.modulus) * (climate_data.rainfall / 1000) # Simplified relationship
47
+ total_rut += rut
48
+ logger.debug(f"Year {year + 1}, Load {load} kN: Rut {rut} mm")
49
+ logger.info(f"Total Rutting: {total_rut} mm")
50
+ return total_rut
51
+
52
+
53
+ def predict_thermal_cracking(pavement: Pavement, climate_data: ClimateData, material_props: MaterialProperties) -> float:
54
+ """
55
+ Predict thermal cracking based on temperature variation and material properties.
56
+
57
+ :param pavement: Pavement structure.
58
+ :param climate_data: Climate data.
59
+ :param material_props: Material properties.
60
+ :return: Thermal cracking index.
61
+ """
62
+ thermal_crack = material_props.thermal_coeff * climate_data.temperature_variation
63
+ logger.info(f"Thermal Cracking Index: {thermal_crack}")
64
+ return thermal_crack
65
+
66
+
67
+ def design_new_pavement(pavement: Pavement, traffic_data: TrafficData, climate_data: ClimateData,
68
+ subgrade_props: SubgradeProperties, material_props: MaterialProperties) -> Dict[str, float]:
69
+ """
70
+ Design a new pavement by predicting various distresses.
71
+
72
+ :param pavement: Pavement structure.
73
+ :param traffic_data: Traffic data.
74
+ :param climate_data: Climate data.
75
+ :param subgrade_props: Subgrade properties.
76
+ :param material_props: Material properties.
77
+ :return: Dictionary with predicted distresses.
78
+ """
79
+ fatigue = predict_fatigue_cracking(pavement, traffic_data, material_props)
80
+ rutting = predict_rutting(pavement, traffic_data, climate_data, subgrade_props)
81
+ thermal = predict_thermal_cracking(pavement, climate_data, material_props)
82
+ logger.info("Pavement design simulation completed.")
83
+ return {
84
+ 'Fatigue Cracking': fatigue,
85
+ 'Rutting': rutting,
86
+ 'Thermal Cracking': thermal
87
+ }
88
+
89
+
90
+ def evaluate_performance(pavement: Pavement, traffic_data: TrafficData, climate_data: ClimateData,
91
+ subgrade_props: SubgradeProperties, material_props: MaterialProperties) -> Dict[str, float]:
92
+ """
93
+ Evaluate pavement performance, currently mirrors design_new_pavement.
94
+
95
+ :param pavement: Pavement structure.
96
+ :param traffic_data: Traffic data.
97
+ :param climate_data: Climate data.
98
+ :param subgrade_props: Subgrade properties.
99
+ :param material_props: Material properties.
100
+ :return: Dictionary with predicted distresses.
101
+ """
102
+ logger.info("Evaluating pavement performance.")
103
+ return design_new_pavement(pavement, traffic_data, climate_data, subgrade_props, material_props)
src/reporting.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # src/reporting.py
2
+
3
+ from typing import Dict
4
+ import logging
5
+
6
+ from src.utils.logger import setup_logger
7
+ from src.utils.helpers import save_pdf
8
+
9
+ logger = setup_logger(__name__)
10
+
11
+
12
+ def generate_report(simulation_results: Dict[str, float], lcc: float) -> str:
13
+ """
14
+ Generate a textual report based on simulation results and LCCA.
15
+
16
+ :param simulation_results: Dictionary containing simulation results.
17
+ :param lcc: Lifecycle Cost Analysis result.
18
+ :return: Formatted report content as a string.
19
+ """
20
+ report = "Mechanistic-Empirical Pavement Design Report\n"
21
+ report += "="*50 + "\n\n"
22
+
23
+ report += "Pavement Performance Predictions:\n"
24
+ report += "-"*30 + "\n"
25
+ for key, value in simulation_results.items():
26
+ report += f"{key}: {value:.4f}\n"
27
+
28
+ report += f"\nLifecycle Cost Analysis (LCCA):\n"
29
+ report += "-"*30 + "\n"
30
+ report += f"Total Lifecycle Cost: ${lcc:,.2f}\n"
31
+
32
+ report += "\nConclusion:\n"
33
+ report += "The pavement design meets the required performance criteria based on the simulation results.\n"
34
+
35
+ logger.info("Report generated successfully.")
36
+ return report
37
+
38
+
39
+ def export_report_to_pdf(report_content: str, file_path: str):
40
+ """
41
+ Export the report content to a PDF file.
42
+
43
+ :param report_content: The content of the report as a string.
44
+ :param file_path: The path where the PDF will be saved.
45
+ """
46
+ try:
47
+ from reportlab.lib.pagesizes import letter
48
+ from reportlab.pdfgen import canvas
49
+ from reportlab.lib.units import inch
50
+
51
+ c = canvas.Canvas(file_path, pagesize=letter)
52
+ width, height = letter
53
+ textobject = c.beginText()
54
+ textobject.setTextOrigin(inch, height - inch)
55
+ textobject.setFont("Helvetica", 12)
56
+
57
+ for line in report_content.split('\n'):
58
+ textobject.textLine(line)
59
+ c.drawText(textobject)
60
+ c.showPage()
61
+ c.save()
62
+ logger.info(f"Report exported to PDF at {file_path}")
63
+ except ImportError:
64
+ logger.error("ReportLab is not installed. Please install it using 'pip install reportlab'")
65
+ raise
66
+ except Exception as e:
67
+ logger.error(f"Failed to export report to PDF: {e}")
68
+ raise
src/utils/__pycache__/helpers.cpython-312.pyc ADDED
Binary file (2.56 kB). View file
 
src/utils/__pycache__/logger.cpython-312.pyc ADDED
Binary file (1.5 kB). View file
 
src/utils/helpers.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # src/utils/helpers.py
2
+
3
+ import pandas as pd
4
+ import logging
5
+ from src.utils.logger import setup_logger
6
+
7
+ logger = setup_logger(__name__)
8
+
9
+
10
+ def read_excel(file_path: str) -> pd.DataFrame:
11
+ """
12
+ Reads an Excel file and returns a pandas DataFrame.
13
+
14
+ :param file_path: Path to the Excel file.
15
+ :return: pandas DataFrame.
16
+ """
17
+ try:
18
+ df = pd.read_excel(file_path, sheet_name=None) # Read all sheets
19
+ logger.info(f"Excel file '{file_path}' read successfully.")
20
+ return df
21
+ except Exception as e:
22
+ logger.error(f"Error reading Excel file '{file_path}': {e}")
23
+ raise IOError(f"Error reading Excel file: {e}")
24
+
25
+
26
+ def save_pdf(file_path: str, content: str):
27
+ """
28
+ Saves content to a PDF file using ReportLab.
29
+
30
+ :param file_path: Path to save the PDF.
31
+ :param content: Content to write into the PDF.
32
+ """
33
+ try:
34
+ from reportlab.lib.pagesizes import letter
35
+ from reportlab.pdfgen import canvas
36
+
37
+ c = canvas.Canvas(file_path, pagesize=letter)
38
+ width, height = letter
39
+ textobject = c.beginText(50, height - 50)
40
+ textobject.setFont("Helvetica", 12)
41
+
42
+ for line in content.split('\n'):
43
+ textobject.textLine(line)
44
+ c.drawText(textobject)
45
+ c.showPage()
46
+ c.save()
47
+ logger.info(f"PDF saved successfully at {file_path}.")
48
+ except ImportError:
49
+ logger.error("ReportLab library is not installed.")
50
+ raise
51
+ except Exception as e:
52
+ logger.error(f"Failed to save PDF: {e}")
53
+ raise
src/utils/logger.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # src/utils/logger.py
2
+
3
+ import logging
4
+ import os
5
+
6
+ def setup_logger(name: str, log_file: str = 'me_pavement_design.log', level: int = logging.INFO) -> logging.Logger:
7
+ """
8
+ Sets up a logger with the specified name and log file.
9
+
10
+ :param name: Name of the logger.
11
+ :param log_file: File where logs will be saved.
12
+ :param level: Logging level.
13
+ :return: Configured logger.
14
+ """
15
+ logger = logging.getLogger(name)
16
+ logger.setLevel(level)
17
+
18
+ # Avoid adding multiple handlers to the logger
19
+ if not logger.handlers:
20
+ # Create handlers
21
+ fh = logging.FileHandler(log_file)
22
+ fh.setLevel(level)
23
+ ch = logging.StreamHandler()
24
+ ch.setLevel(level)
25
+
26
+ # Create formatter and add it to handlers
27
+ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
28
+ fh.setFormatter(formatter)
29
+ ch.setFormatter(formatter)
30
+
31
+ # Add handlers to the logger
32
+ logger.addHandler(fh)
33
+ logger.addHandler(ch)
34
+
35
+ return logger