The user wants a program for "automated capacity planning". This is a very broad request. Capacity planning can apply to server infrastructure, cloud resources, manufacturing, staff scheduling, etc.
Given the context of programming requests usually involving software/infrastructure, I will assume the user likely means server/cloud resource capacity planning (e.g., predicting when you'll run out of CPU, memory, or storage based on current trends).
Goal: Write a program that automates capacity planning.
Components needed:
- Input Data: Needs historical metrics (timestamps and usage values).
- Analysis/Trend Detection: Needs a way to calculate the rate of growth (linear regression is the simplest and most standard starting point).
- Prediction: Extrapolate the trend to find when a threshold (capacity limit) is reached.
- Output: Report or alert stating when the resource will run out.
Approach:
I'll create a Python script. Python is the standard for data analysis.
- Libraries:
pandas for data handling, numpy for math/calculation, sklearn (scikit-learn) for linear regression, matplotlib (optional, but good for visualization).
- Scenario: Predicting Disk Space usage.
- Steps:
- Generate or load mock data (usage over time).
- Fit a Linear Regression model to the data.
- Project the line forward.
- Calculate the intersection point with the maximum capacity.
- Output the result.
Refinement:
Writing a full-blown enterprise solution is too much for a single code block. I should provide a conceptual framework implemented as a robust script. I will focus on a generic "Time-To-Exhaustion" calculator.
- Class Structure: Create a
CapacityPlanner class.
- Input: A list of (date, value) tuples.
- Method:
predict_saturation(limit).
- Logic: Convert dates to ordinal numbers (integers) to make regression easy. Fit the line y=mx+c. Solve for limit=mx+c⇒x=(limit−c)/m. Convert x back to a date.
Edge Cases:
- What if usage is flat? (Slope m is close to 0).
- What if usage is decreasing? (Slope m is negative).
- The program should handle these gracefully.
Drafting the Code (Mental or scratchpad):
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
def predict_exhaustion(dates, usage, capacity_limit):
# Convert dates to numbers
X = np.array([d.toordinal() for d in dates]).reshape(-1, 1)
y = np.array(usage)
model = LinearRegression()
model.fit(X, y)
# Calculate intersection
slope = model.coef_[0]
intercept = model.intercept_
if slope <= 0:
return "Never" # Or decreasing
days_until_full = (capacity_limit - intercept) / slope
# ... conversion logic
Adding Visualization:
A text output is boring. I should add a plotting feature using matplotlib to show the historical data and the trend line.
Final Plan:
- Introduction: Acknowledge that real-world capacity planning involves complex variables, but a programmatic approach usually starts with Time Series Forecasting.
- The Solution: A Python script using
sklearn for linear regression.
- Code Structure:
- Generate realistic-looking synthetic data (storage usage trending upward).
- Use Linear Regression to find the trend.
- Extrapolate to find the "Saturation Date".
- Plot the result.
- Explanation: Explain how it works and how to extend it (e.g., using ARIMA or Prophet instead of Linear Regression).
Let's write the actual code. I will make it modular so the user can swap out the data source.
- Self-Correction during coding: Standard Linear Regression is sensitive to outliers. For a simple example, it's fine, but I should add a comment about it.
- Data Generation: Make the data have some noise, but a clear trend, so the regression looks good.
Code Snippet Layout:
- Import dependencies.
CapacityPlanner class.
load_data function (mocked).
main execution block.
Let's refine the "Automated" part. Automation usually implies running this on a schedule. I will simulate the "run" aspect but focus on the logic.
The Prompt Specifics: "Write a program".
I will provide a complete, runnable Python script.
Step-by-step implementation details:
- Use
pandas for date management.
- Use
scikit-learn for the model.
- Use
matplotlib for the graph.
- Logic:
- Days=(Capacity−Intercept)/Sl
Let's go.
Capacity planning is a broad field, but it most commonly refers to IT Infrastructure Capacity Planning (predicting when servers, storage, or network bandwidth will run out).
Below is a complete, runnable Python program that automates this process. It treats capacity planning as a Time Series Forecasting problem using Linear Regression.
The Approach
- Input: Historical metrics (e.g., daily disk usage or CPU load).
- Model: Linear Regression (to find the trend line).
- Prediction: Calculate the specific date the trend line crosses the maximum capacity.
- Alerting: Classifies the urgency (OK, Warning, Critical).
- Visualization: Generates a graph showing historical data vs. predicted exhaustion.
The Python Program
You will need pandas, numpy, sklearn, and matplotlib installed (pip install pandas numpy scikit-learn matplotlib).
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from datetime import datetime, timedelta
import sys
class CapacityPlanner:
def __init__(self, resource_name, max_capacity, warning_threshold_percent=0.80):
"""
Initialize the planner.
:param resource_name: Name of the resource (e.g., 'Database Storage')
:param max_capacity: The maximum logical limit (e.g., 1000 GB)
:param warning_threshold_percent: When to trigger a warning (default 80%)
"""
self.resource_name = resource_name
self.max_capacity = max_capacity
self.warning_threshold = max_capacity * warning_threshold_percent
self.model = LinearRegression()
def load_data(self, dates, usage_values):
"""Load historical data."""
self.data = pd.DataFrame({'date': dates, 'usage': usage_values})
self.data['date'] = pd.to_datetime(self.data['date'])
# Sort by date to ensure proper time series analysis
self.data = self.data.sort_values('date').reset_index(drop=True)
# Convert dates to ordinal numbers (days) for regression math
# We calculate days relative to the first date in the dataset
self.start_date = self.data['date'].min()
self.data['days_offset'] = (self.data['date'] - self.start_date).dt.days
def train_and_predict(self):
"""Train the model and calculate exhaustion date."""
X = self.data['days_offset'].values.reshape(-1, 1)
y = self.data['usage'].values
# 1. Train the model
self.model.fit(X, y)
# Extract trend stats
self.slope = self.model.coef_[0] # Growth per day
self.intercept = self.model.intercept_
# 2. Calculate Current Status
self.current_usage = y[-1]
self.current_percent = (self.current_usage / self.max_capacity) * 100
# 3. Predict Exhaustion Date
# Linear equation: y = mx + b -> x = (y - b) / m
if self.slope <= 0:
# Usage is flat or decreasing
self.exhaustion_date = None
self.days_remaining = float('inf')
else:
days_to_full = (self.max_capacity - self.intercept) / self.slope
self.exhaustion_date = self.start_date + timedelta(days=days_to_full)
self.days_remaining = (self.exhaustion_date - datetime.now()).days
def generate_report(self):
"""Print a text report to console."""
print("-" * 60)
print(f"CAPACITY PLANNING REPORT: {self.resource_name}")
print("-" * 60)
print(f"Max Capacity : {self.max_capacity:,.2f} GB")
print(f"Current Usage : {self.current_usage:,.2f} GB ({self.current_percent:.1f}%)")
print(f"Growth Rate : {self.slope:,.2f} GB/day")
if self.exhaustion_date:
print(f"Estimated Full : {self.exhaustion_date.strftime('%Y-%m-%d')}")
print(f"Days Remaining : {self.days_remaining}")
else:
print("Status : Usage stable or decreasing. No exhaustion predicted.")
# Decision Logic / Alerting
status = "🟢 OK"
if self.current_percent >= 95 or (self.days_remaining < 14 and self.days_remaining > 0):
status = "🔴 CRITICAL: Immediate action required."
elif self.current_percent >= 80 or (self.days_remaining < 60 and self.days_remaining > 0):
status = "🟡 WARNING: Plan procurement soon."
print(f"Action Status : {status}")
print("-" * 60)
def plot_forecast(self, days_into_future=365):
"""Visualize the data and the forecast."""
# Create future dates for plotting the line
last_date = self.data['date'].max()
future_dates = [last_date + timedelta(days=x) for x in range(1, days_into_future)]
all_dates = list(self.data['date']) + future_dates
# Calculate predicted values for all dates
offsets = [(d - self.start_date).days for d in all_dates]
predictions = self.model.predict(np.array(offsets).reshape(-1, 1))
plt.figure(figsize=(10, 6))
# Plot Historical Data
plt.scatter(self.data['date'], self.data['usage'], color='blue', label='Historical Usage')
# Plot Trend Line
plt.plot(all_dates, predictions, color='orange', linestyle='--', label='Forecast Trend')
# Plot Capacity Limits
plt.axhline(y=self.max_capacity, color='red', linestyle='-', label='Max Capacity')
plt.axhline(y=self.warning_threshold, color='yellow', linestyle=':', label='Warning Threshold (80%)')
# Formatting
plt.title(f"Capacity Forecast: {self.resource_name}")
plt.xlabel("Date")
plt.ylabel("Usage (GB)")
plt.legend()
plt.grid(True)
# Save and show
filename = f"capacity_plan_{self.resource_name.replace(' ', '_')}.png"
plt.savefig(filename)
print(f"Graph saved to: {filename}")
# plt.show() # Uncomment to pop up the window
# ==========================================
# MOCK DATA GENERATOR (To simulate a scenario)
# ==========================================
def generate_mock_data():
# Simulate 6 months of data growing steadily
start_date = datetime(2023, 1, 1)
dates = [start_date + timedelta(days=x) for x in range(180)]
# Usage grows from 200GB to roughly 600GB over 6 months
# Adding some random noise
usage = [200 + (i * 2.2) + np.random.randint(-10, 10) for i in range(180)]
return dates, usage
# ==========================================
# MAIN EXECUTION
# ==========================================
if __name__ == "__main__":
# 1. Get Data (In real life, load from SQL, Prometheus, Cloud Watch, etc.)
dates, usage = generate_mock_data()
# 2. Initialize Planner (Resource Name, Max Capacity, Warning Level)
planner = CapacityPlanner("Primary Database Storage", max_capacity=1200)
# 3. Load and Process
planner.load_data(dates, usage)
planner.train_and_predict()
# 4. Output
planner.generate_report()
planner.plot_forecast()
How it Works
- Data Ingestion (
load_data): It converts dates into numerical "days from start" because machine learning models handle numbers better than date objects.
- Linear Regression (
train_and_predict): It draws a straight line through your messy data points. It calculates the slope (how fast you are growing per day).
- Extrapolation: It solves the math problem: "If this line continues straight, when does it hit the ceiling?"
- Decision Logic: It automates the decision-making process. It doesn't just give you a number; it tells you if you are
OK, in WARNING state (80% full or < 60 days left), or CRITICAL (95% full or < 14 days left).
How to adapt this to the Real World
In a production environment, you would replace the generate_mock_data() function with a connector to your actual data source.
Example AWS CloudWatch adaptation:
import boto3
def get_real_data():
client = boto3.client('cloudwatch')
response = client.get_metric_statistics(
Namespace='AWS/RDS',
MetricName='FreeStorageSpace',
Dimensions=[{'Name': 'DBInstanceIdentifier', 'Value': 'my-db'}],
StartTime=datetime.utcnow() - timedelta(days=90),
EndTime=datetime.utcnow(),
Period=86400, # Daily
Statistics=['Average']
)
# Parse the response into lists of dates and values
# (Implementation details depend on specific API response structure)
pass