Working site
This commit is contained in:
@@ -9,12 +9,21 @@ from app.models.auto import Auto_Delivery, Auto_Temp, Auto_Update, Tickets_Auto_
|
||||
# --- Constants for the Model ---
|
||||
# This is a baseline daily usage for homes that use oil for hot water.
|
||||
# A typical value is 0.5 to 1.0 gallons per day. Adjust as needed.
|
||||
HOT_WATER_DAILY_USAGE = Decimal('0.7')
|
||||
HOT_WATER_DAILY_USAGE = Decimal('1.0')
|
||||
|
||||
# This determines how quickly the K-Factor adjusts.
|
||||
# 0.7 means 70% weight is given to the historical factor and 30% to the new one.
|
||||
# This prevents wild swings from a single unusual delivery period.
|
||||
K_FACTOR_SMOOTHING_WEIGHT = Decimal('0.7')
|
||||
K_FACTOR_SMOOTHING_WEIGHT = Decimal('0.7')
|
||||
|
||||
TANK_MAX_FILLS = {
|
||||
275: 240,
|
||||
330: 280,
|
||||
500: 475,
|
||||
550: 500
|
||||
}
|
||||
|
||||
PARTIAL_DELIVERIES = [100, 125, 150, 200]
|
||||
|
||||
|
||||
class FuelEstimator:
|
||||
@@ -25,6 +34,37 @@ class FuelEstimator:
|
||||
"""Helper to fetch weather data for a specific date."""
|
||||
return self.session.query(Auto_Temp).filter(Auto_Temp.todays_date == target_date).first()
|
||||
|
||||
def _estimate_initial_house_factor(self, customer: Auto_Delivery) -> Decimal:
|
||||
"""
|
||||
Generic function to estimate initial house factor for customers with only one delivery.
|
||||
This can be improved with more sophisticated logic (e.g., averaging similar customers).
|
||||
"""
|
||||
# Default generic house factor: 0.12 gallons per degree day (average based on existing customer data)
|
||||
# This represents typical heating usage and can be adjusted based on future data analysis
|
||||
return Decimal('0.12')
|
||||
|
||||
def _verify_house_factor_correctness(self, customer: Auto_Delivery) -> bool:
|
||||
"""
|
||||
Verify and correct house_factor based on delivery history.
|
||||
Returns True if correction was made.
|
||||
"""
|
||||
# Count deliveries for this customer
|
||||
delivery_count = self.session.query(func.count(Tickets_Auto_Delivery.id)).filter(
|
||||
Tickets_Auto_Delivery.customer_id == customer.customer_id
|
||||
).scalar()
|
||||
|
||||
corrected = False
|
||||
|
||||
if delivery_count <= 1:
|
||||
# Customers with 0 or 1 delivery should have house_factor = 0.12 (initial average)
|
||||
if customer.house_factor != Decimal('0.12'):
|
||||
print(f"Correcting house_factor for customer {customer.customer_id} from {customer.house_factor} to 0.12 (1 or fewer deliveries)")
|
||||
customer.house_factor = Decimal('0.12')
|
||||
corrected = True
|
||||
# For customers with 2+ deliveries, keep their calculated factor (no correction needed)
|
||||
|
||||
return corrected
|
||||
|
||||
def run_daily_update(self):
|
||||
"""
|
||||
Main function to run once per day. It updates the estimated fuel level
|
||||
@@ -43,8 +83,8 @@ class FuelEstimator:
|
||||
print(f"Error: Weather data for {today} not found. Cannot run update.")
|
||||
return {"ok": False, "message": f"Weather data for {today} not found."}
|
||||
|
||||
# Degree days can't be negative for this calculation. If it's warm, HDD is 0.
|
||||
degree_day = Decimal(max(0, todays_weather.degree_day))
|
||||
# Degree days can't be negative for this calculation. If it's warm, HDD = 0.
|
||||
degree_day = Decimal(max(0, 65 - float(todays_weather.temp_avg)))
|
||||
|
||||
# 3. Get all active automatic customers
|
||||
auto_customers = self.session.query(Auto_Delivery).filter(
|
||||
@@ -54,19 +94,25 @@ class FuelEstimator:
|
||||
if not auto_customers:
|
||||
print("No active automatic delivery customers found.")
|
||||
return {"ok": True, "message": "No active customers to update."}
|
||||
|
||||
|
||||
print(f"Staging daily fuel update for {len(auto_customers)} customers...")
|
||||
|
||||
|
||||
corrections_made = 0
|
||||
|
||||
# 4. Loop through each customer and update their fuel level
|
||||
for customer in auto_customers:
|
||||
# Verify and correct house_factor if needed
|
||||
if self._verify_house_factor_correctness(customer):
|
||||
corrections_made += 1
|
||||
|
||||
heating_usage = customer.house_factor * degree_day
|
||||
|
||||
|
||||
hot_water_usage = Decimal('0.0')
|
||||
if customer.hot_water_summer == 1:
|
||||
hot_water_usage = HOT_WATER_DAILY_USAGE
|
||||
|
||||
|
||||
gallons_used_today = heating_usage + hot_water_usage
|
||||
|
||||
|
||||
customer.estimated_gallons_left_prev_day = customer.estimated_gallons_left
|
||||
new_estimated_gallons = customer.estimated_gallons_left - gallons_used_today
|
||||
customer.estimated_gallons_left = max(Decimal('0.0'), new_estimated_gallons)
|
||||
@@ -77,9 +123,13 @@ class FuelEstimator:
|
||||
# 5. Log that today's update is complete
|
||||
new_update_log = Auto_Update(last_updated=today)
|
||||
self.session.add(new_update_log)
|
||||
|
||||
|
||||
print("Daily update staged. Awaiting commit.")
|
||||
return {"ok": True, "message": f"Successfully staged updates for {len(auto_customers)} customers."}
|
||||
message = f"Successfully staged updates for {len(auto_customers)} customers."
|
||||
if corrections_made > 0:
|
||||
message += f" Corrected house factors for {corrections_made} customers."
|
||||
|
||||
return {"ok": True, "message": message}
|
||||
|
||||
def refine_factor_after_delivery(self, ticket: Tickets_Auto_Delivery):
|
||||
"""
|
||||
@@ -90,8 +140,13 @@ class FuelEstimator:
|
||||
Auto_Delivery.customer_id == ticket.customer_id
|
||||
).first()
|
||||
|
||||
if not customer or not customer.last_fill:
|
||||
print(f"Cannot refine K-Factor: Customer {ticket.customer_id} not found or has no previous fill date. Resetting tank only.")
|
||||
if not customer:
|
||||
print(f"Customer {ticket.customer_id} not found.")
|
||||
return
|
||||
|
||||
if not customer.last_fill:
|
||||
print(f"Setting initial K-Factor for new customer {ticket.customer_id} with only one delivery.")
|
||||
customer.house_factor = self._estimate_initial_house_factor(customer)
|
||||
self._update_tank_after_fill(customer, ticket)
|
||||
return
|
||||
|
||||
@@ -103,13 +158,12 @@ class FuelEstimator:
|
||||
self._update_tank_after_fill(customer, ticket)
|
||||
return
|
||||
|
||||
total_hdd_result = self.session.query(func.sum(Auto_Temp.degree_day)).filter(
|
||||
interval_temps = self.session.query(Auto_Temp).filter(
|
||||
Auto_Temp.todays_date > start_date,
|
||||
Auto_Temp.todays_date <= end_date,
|
||||
Auto_Temp.degree_day > 0
|
||||
).scalar()
|
||||
|
||||
total_hdd = Decimal(total_hdd_result or 0)
|
||||
Auto_Temp.todays_date <= end_date
|
||||
).all()
|
||||
total_degree_days = sum(max(0, 65 - float(temp.temp_avg)) for temp in interval_temps)
|
||||
total_hdd = Decimal(total_degree_days)
|
||||
|
||||
total_hot_water_usage = Decimal('0.0')
|
||||
if customer.hot_water_summer == 1:
|
||||
@@ -136,18 +190,28 @@ class FuelEstimator:
|
||||
print(f"K-Factor and tank status for Customer {customer.customer_id} staged for update.")
|
||||
|
||||
def _update_tank_after_fill(self, customer: Auto_Delivery, ticket: Tickets_Auto_Delivery):
|
||||
"""Helper to reset customer tank status after a fill-up."""
|
||||
"""Helper to update customer tank status after a fill-up or partial delivery."""
|
||||
customer.last_fill = ticket.fill_date
|
||||
customer.days_since_last_fill = 0
|
||||
|
||||
# A "fill-up" means the tank is full. This is critical for accuracy.
|
||||
|
||||
# Determine max fill capacity
|
||||
if customer.tank_size and Decimal(customer.tank_size) > 0:
|
||||
customer.estimated_gallons_left = Decimal(customer.tank_size)
|
||||
tank_size = float(Decimal(customer.tank_size))
|
||||
max_fill = TANK_MAX_FILLS.get(tank_size, tank_size)
|
||||
else:
|
||||
# Default to a common tank size if not specified, e.g., 275
|
||||
customer.estimated_gallons_left = Decimal('275.0')
|
||||
|
||||
# The previous day's value should match the new full value on a fill day.
|
||||
# Default to legal max for common tank size (275 gallons = 240)
|
||||
max_fill = 240.0
|
||||
|
||||
# Check if this is a partial delivery
|
||||
if float(ticket.gallons_delivered) in PARTIAL_DELIVERIES:
|
||||
# Partial delivery: add to current level, cap at max_fill
|
||||
customer.estimated_gallons_left += ticket.gallons_delivered
|
||||
customer.estimated_gallons_left = min(customer.estimated_gallons_left, Decimal(str(max_fill)))
|
||||
else:
|
||||
# Full delivery: set to max_fill
|
||||
customer.estimated_gallons_left = Decimal(str(max_fill))
|
||||
|
||||
# The previous day's value should match the new value on a fill day.
|
||||
customer.estimated_gallons_left_prev_day = customer.estimated_gallons_left
|
||||
customer.last_updated = date.today()
|
||||
customer.auto_status = 1 # Reactivate the customer
|
||||
customer.auto_status = 1 # Reactivate the customer
|
||||
|
||||
Reference in New Issue
Block a user