Skip to content

Commit 65389e7

Browse files
committed
yes
1 parent 29d6cd1 commit 65389e7

5 files changed

Lines changed: 55 additions & 7 deletions

File tree

freight_project/backend/app.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@ def run_sim():
3232
def init_sim(
3333
num_trucks: int = Query(50, description="Number of trucks"),
3434
num_loads: int = Query(20, description="Number of loads"),
35-
min_pop: int = Query(100000, description="Minimum city population")
35+
min_pop: int = Query(100000, description="Minimum city population"),
36+
enable_finance: bool = Query(True, description="Enable profit/expense tracking")
3637
):
3738
global sim
3839
# Create a new FreightSim instance
@@ -58,7 +59,10 @@ def get_status():
5859
"lat": truck["lat"], # current latitude
5960
"lon": truck["lng"], # current longitude
6061
"status": truck["status"], # Idle or Assigned
61-
"assigned_load": truck["assigned_load"]
62+
"assigned_load": truck["assigned_load"],
63+
"profit": truck["profit"], # total profit earned
64+
"expense": truck["expense"], # total expense incurred
65+
"net_profit": truck["profit"] - truck["expense"] # net profit
6266
})
6367

6468
# Build load status list
@@ -71,7 +75,7 @@ def get_status():
7175
"origin": origin["city"],
7276
"destination": dest["city"],
7377
"weight": load["weight"],
74-
"value": load["value"], # profit/priority metric
78+
"value": load["rate_per_ton"], # profit/priority metric
7579
"assigned_truck": load["assigned_truck"],
7680
"dest_latitude": dest["lat"],
7781
"dest_longitude": dest["lng"]

freight_project/backend/freight_trading.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from math import radians, cos, sin, asin, sqrt
55

66
class FreightSim:
7-
def __init__(self, csv_path="uscities.csv", num_trucks=50, min_pop=50000):
7+
def __init__(self, csv_path="uscities.csv", num_trucks=50, min_pop=50000, enable_finance=False):
88
# Load all US cities from the CSV file
99
self.cities = pd.read_csv(csv_path)
1010

@@ -13,13 +13,18 @@ def __init__(self, csv_path="uscities.csv", num_trucks=50, min_pop=50000):
1313

1414
# Create a fleet of trucks
1515
self.num_trucks = num_trucks
16+
17+
# Finance tracking flag
18+
self.enable_finance = enable_finance
19+
1620
self.trucks = pd.DataFrame({
1721
'truck_id': [f"T{i+1}" for i in range(num_trucks)], # Truck names T1, T2, ...
1822
'city_idx': np.random.choice(self.cities.index, num_trucks), # Start trucks in random cities
1923
'capacity': np.random.randint(10, 30, num_trucks), # Each truck can carry 10–30 tons
2024
'status': ['Idle'] * num_trucks, # Idle = waiting for a job
2125
'assigned_load': [None] * num_trucks, # No load assigned yet
22-
'profit': [0] * num_trucks # Track revenue earned
26+
'profit': [0] * num_trucks, # Track revenue earned
27+
'expense': [0]*num_trucks
2328
})
2429

2530
# Add city details to each truck so we know where it is
@@ -141,6 +146,19 @@ def update_trucks(self):
141146
revenue = load['weight'] * load['rate_per_ton']
142147
self.trucks.at[idx, 'profit'] += revenue
143148

149+
if self.enable_finance:
150+
# For simplicity, assume a fixed expense per mile
151+
origin = self.cities.iloc[load['origin_idx']]
152+
distance = self.haversine(origin['lat'], origin['lng'], dest['lat'], dest['lng'])
153+
expense_per_mile = 2.0 # $2 per mile
154+
expense = distance * expense_per_mile
155+
self.trucks.at[idx, 'expense'] += expense
156+
157+
# If finance tracking is enabled, show net profit
158+
net_profit = revenue - self.trucks.at[idx, 'expense'] if self.enable_finance else revenue
159+
print(f"✅ Truck {truck['truck_id']} delivered Load {load['load_id']} at {dest['city']}, {dest['state_name']} | Earned: ${revenue} | Net: ${net_profit}")
160+
161+
144162
print(f"✅ Truck {truck['truck_id']} delivered Load {load['load_id']} at {dest['city']}, {dest['state_name']} | Earned: ${revenue}")
145163

146164
# Remove load (delivered)

freight_project/cli/main.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from backend.freight_trading import FreightSim
22

33
def main():
4-
print("Freight Route Trading Simulator")
4+
print("🚚 Freight Route Trading Simulator (with Finance Tracking)")
55

66
# Ask user for input values
77
num_trucks = int(input("Enter number of trucks: "))
@@ -24,5 +24,18 @@ def main():
2424
print(f"\n--- Simulation Step {step+1} ---")
2525
sim.update_trucks()
2626

27+
# print financial summary
28+
total_revenue = sim.total_revenue()
29+
total_expense = sim.total_expense()
30+
net_profit = total_revenue - total_expense
31+
32+
print(f"💰 Revenue: ${total_revenue:.2f} | Expenses: ${total_expense:.2f} | Net Profit: ${net_profit:.2f}")
33+
34+
print("\n✅ Simulation complete!")
35+
print("Final Truck Profits:")
36+
for _, truck in sim.trucks.iterrows():
37+
print(f"Truck {truck['truck_id']}: Profit = ${truck['profit']:.2f}")
38+
39+
2740
if __name__ == "__main__":
2841
main()

freight_project/frontend/index.html

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ <h1>Freight Simulation Dashboard</h1>
2020
<label>Minimum Population:</label>
2121
<input id="minPop" type="number" value="100000" />
2222

23+
<label>
24+
<input id="enableFinance" type="checkbox" /> Enable Finance Tracking
25+
</label>
26+
2327
<button onclick="startSimulation()">Start Simulation</button>
2428
<button onclick="createLoad()">Create Random Load</button>
2529
</div>

freight_project/frontend/script.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,14 @@ async function refresh() {
1111

1212
// --- Update or create truck markers ---
1313
data.trucks.forEach(truck => {
14+
const popupContent = `
15+
<b>${truck.truck_id}</b><br>
16+
Status: ${truck.status}<br>
17+
Assigned Load: ${truck.assigned_load || "None"}<br>
18+
Profit: $${truck.profit.toFixed(2)}<br>
19+
Expense: $${truck.expense.toFixed(2)}<br>
20+
Net Profit: $${truck.net_profit.toFixed(2)}
21+
`;
1422
if (truckMarkers[truck.truck_id]) {
1523
truckMarkers[truck.truck_id].setLatLng([truck.lat, truck.lon]);
1624
truckMarkers[truck.truck_id].bindPopup(`${truck.truck_id} - ${truck.status}`);
@@ -57,8 +65,9 @@ async function startSimulation() {
5765
const numTrucks = document.getElementById("numTrucks").value;
5866
const numLoads = document.getElementById("numLoads").value;
5967
const minPop = document.getElementById("minPop").value;
68+
const enableFinance = document.getElementById("enableFinance").checked;
6069

61-
await fetch(`http://127.0.0.1:8000/init?num_trucks=${numTrucks}&num_loads=${numLoads}&min_pop=${minPop}`);
70+
await fetch(`http://127.0.0.1:8000/init?num_trucks=${numTrucks}&num_loads=${numLoads}&min_pop=${minPop}&enable_finance=${enableFinance}`);
6271
alert("Simulation started!");
6372
}
6473

0 commit comments

Comments
 (0)