energy-logistics
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseEnergy Logistics
能源物流
You are an expert in energy logistics and supply chain management. Your goal is to help optimize the complex logistics of oil, gas, and energy resources from extraction to end-users, balancing cost, safety, reliability, and environmental constraints.
你是能源物流和供应链管理领域的专家,目标是帮助优化石油、天然气及能源资源从开采到终端用户的复杂物流流程,平衡成本、安全、可靠性和环境约束。
Initial Assessment
初步评估
Before optimizing energy logistics, understand:
-
Energy Resource Type
- What energy commodities? (crude oil, natural gas, LNG, refined products)
- Production volumes and flow rates?
- Geographic sources? (wells, fields, terminals)
- Destination markets and end-users?
-
Infrastructure & Assets
- Existing transportation modes? (pipelines, tankers, rail, trucks)
- Storage facilities? (tanks, terminals, caverns)
- Processing facilities? (refineries, terminals, depots)
- Asset capacities and utilization rates?
-
Operational Context
- Supply contract structures? (long-term, spot market)
- Regulatory requirements? (safety, environmental, permits)
- Quality specifications and blending requirements?
- Seasonal demand patterns?
-
Challenges & Objectives
- Primary goals? (cost reduction, reliability, safety)
- Current bottlenecks or constraints?
- Risk factors? (price volatility, geopolitical, weather)
- Environmental or sustainability targets?
在优化能源物流之前,需要先明确以下信息:
-
能源资源类型
- 涉及哪些能源商品?(原油、天然气、LNG、成品油)
- 产量和流速是多少?
- 地理来源是哪里?(油井、油气田、终端站)
- 目标市场和终端用户是哪些?
-
基础设施与资产
- 现有运输方式有哪些?(管道、油轮、铁路、卡车)
- 存储设施有哪些?(储罐、终端站、地下洞穴)
- 加工设施有哪些?(炼油厂、终端站、油库)
- 资产容量和利用率是多少?
-
运营背景
- 供应合同结构是怎样的?(长期合同、现货市场)
- 监管要求有哪些?(安全、环保、许可)
- 质量规格和调和要求是什么?
- 季节性需求模式是怎样的?
-
挑战与目标
- 核心目标是什么?(降本、可靠性、安全)
- 当前的瓶颈或约束是什么?
- 风险因素有哪些?(价格波动、地缘政治、天气)
- 环境或可持续发展目标是什么?
Energy Logistics Framework
能源物流框架
Supply Chain Structure
供应链结构
Upstream (Production):
- Well sites and production facilities
- Gathering systems (local pipelines)
- Initial processing (separation, treatment)
- Production scheduling optimization
Midstream (Transportation & Storage):
- Pipeline networks (transmission)
- Marine transportation (tankers, barges)
- Rail and truck logistics
- Storage terminals and hubs
- Inventory management
Downstream (Distribution):
- Refineries and processing plants
- Distribution terminals
- Retail delivery (gas stations, heating oil)
- End-user delivery
上游(生产):
- 井场和生产设施
- 集输系统(本地管道)
- 初步加工(分离、处理)
- 生产调度优化
中游(运输与存储):
- 管道网络(输送)
- 海运(油轮、驳船)
- 铁路和卡车物流
- 存储终端和枢纽
- 库存管理
下游(配送):
- 炼油厂和加工厂
- 配送终端
- 零售配送(加油站、取暖油)
- 终端用户配送
Transportation Modes
运输方式
Pipeline Transportation
管道运输
Advantages:
- Highest capacity (continuous flow)
- Lowest cost per unit for large volumes
- Most reliable and safe
- Minimal environmental impact
Optimization Considerations:
python
import numpy as np
from scipy.optimize import linprog
def optimize_pipeline_flow(pipeline_network, supply, demand, capacities, costs):
"""
Optimize flow through pipeline network
Parameters:
- pipeline_network: dict of {(source, destination): pipeline_id}
- supply: dict of {source: available_volume}
- demand: dict of {destination: required_volume}
- capacities: dict of {pipeline_id: max_flow_rate}
- costs: dict of {pipeline_id: cost_per_barrel}
"""
from pulp import *
# Create problem
prob = LpProblem("Pipeline_Flow", LpMinimize)
# Decision variables: flow through each pipeline
flows = {}
for (src, dest), pipe_id in pipeline_network.items():
flows[pipe_id] = LpVariable(
f"Flow_{src}_to_{dest}",
lowBound=0,
upBound=capacities[pipe_id]
)
# Objective: minimize transportation cost
prob += lpSum([costs[pipe] * flows[pipe]
for pipe in flows])
# Constraints: supply limits
for source, max_supply in supply.items():
outbound = [flows[pipe_id]
for (src, dest), pipe_id in pipeline_network.items()
if src == source]
if outbound:
prob += lpSum(outbound) <= max_supply
# Constraints: demand satisfaction
for destination, required in demand.items():
inbound = [flows[pipe_id]
for (src, dest), pipe_id in pipeline_network.items()
if dest == destination]
if inbound:
prob += lpSum(inbound) >= required
# Solve
prob.solve(PULP_CBC_CMD(msg=0))
return {
'status': LpStatus[prob.status],
'total_cost': value(prob.objective),
'flows': {pipe: flows[pipe].varValue for pipe in flows}
}优势:
- 运力最高(连续流动)
- 大批量运输单位成本最低
- 最可靠、最安全
- 环境影响最小
优化注意事项:
python
import numpy as np
from scipy.optimize import linprog
def optimize_pipeline_flow(pipeline_network, supply, demand, capacities, costs):
"""
Optimize flow through pipeline network
Parameters:
- pipeline_network: dict of {(source, destination): pipeline_id}
- supply: dict of {source: available_volume}
- demand: dict of {destination: required_volume}
- capacities: dict of {pipeline_id: max_flow_rate}
- costs: dict of {pipeline_id: cost_per_barrel}
"""
from pulp import *
# Create problem
prob = LpProblem("Pipeline_Flow", LpMinimize)
# Decision variables: flow through each pipeline
flows = {}
for (src, dest), pipe_id in pipeline_network.items():
flows[pipe_id] = LpVariable(
f"Flow_{src}_to_{dest}",
lowBound=0,
upBound=capacities[pipe_id]
)
# Objective: minimize transportation cost
prob += lpSum([costs[pipe] * flows[pipe]
for pipe in flows])
# Constraints: supply limits
for source, max_supply in supply.items():
outbound = [flows[pipe_id]
for (src, dest), pipe_id in pipeline_network.items()
if src == source]
if outbound:
prob += lpSum(outbound) <= max_supply
# Constraints: demand satisfaction
for destination, required in demand.items():
inbound = [flows[pipe_id]
for (src, dest), pipe_id in pipeline_network.items()
if dest == destination]
if inbound:
prob += lpSum(inbound) >= required
# Solve
prob.solve(PULP_CBC_CMD(msg=0))
return {
'status': LpStatus[prob.status],
'total_cost': value(prob.objective),
'flows': {pipe: flows[pipe].varValue for pipe in flows}
}Example usage
Example usage
network = {
('Field_A', 'Terminal_1'): 'Pipe_1',
('Field_B', 'Terminal_1'): 'Pipe_2',
('Terminal_1', 'Refinery_1'): 'Pipe_3',
('Terminal_1', 'Refinery_2'): 'Pipe_4'
}
supply = {
'Field_A': 100000, # barrels/day
'Field_B': 150000
}
demand = {
'Refinery_1': 120000,
'Refinery_2': 80000
}
capacities = {
'Pipe_1': 110000,
'Pipe_2': 160000,
'Pipe_3': 130000,
'Pipe_4': 90000
}
costs = {
'Pipe_1': 0.50, # $/barrel
'Pipe_2': 0.45,
'Pipe_3': 0.60,
'Pipe_4': 0.55
}
result = optimize_pipeline_flow(network, supply, demand, capacities, costs)
print(f"Optimal daily cost: ${result['total_cost']:,.2f}")
**Batching & Scheduling:**
- Sequential batching (different products)
- Contamination management
- Batch tracking and quality control
```python
def batch_schedule_pipeline(batches, pipeline_capacity, transit_times):
"""
Schedule multiple product batches through pipeline
Parameters:
- batches: list of {product, volume, source, destination, priority}
- pipeline_capacity: barrels/hour
- transit_times: dict of {(source, destination): hours}
"""
from collections import deque
schedule = []
current_time = 0
# Sort by priority and volume
sorted_batches = sorted(batches,
key=lambda x: (x['priority'], -x['volume']))
for batch in sorted_batches:
# Calculate transit time
transit = transit_times.get(
(batch['source'], batch['destination']), 24
)
# Calculate pump time
pump_time = batch['volume'] / pipeline_capacity
# Schedule
schedule.append({
'batch_id': batch['product'],
'start_time': current_time,
'pump_hours': pump_time,
'arrival_time': current_time + pump_time + transit,
'volume': batch['volume']
})
current_time += pump_time
return schedulenetwork = {
('Field_A', 'Terminal_1'): 'Pipe_1',
('Field_B', 'Terminal_1'): 'Pipe_2',
('Terminal_1', 'Refinery_1'): 'Pipe_3',
('Terminal_1', 'Refinery_2'): 'Pipe_4'
}
supply = {
'Field_A': 100000, # barrels/day
'Field_B': 150000
}
demand = {
'Refinery_1': 120000,
'Refinery_2': 80000
}
capacities = {
'Pipe_1': 110000,
'Pipe_2': 160000,
'Pipe_3': 130000,
'Pipe_4': 90000
}
costs = {
'Pipe_1': 0.50, # $/barrel
'Pipe_2': 0.45,
'Pipe_3': 0.60,
'Pipe_4': 0.55
}
result = optimize_pipeline_flow(network, supply, demand, capacities, costs)
print(f"Optimal daily cost: ${result['total_cost']:,.2f}")
**批次与调度:**
- 连续批次运输(不同产品)
- 污染管理
- 批次追踪和质量控制
```python
def batch_schedule_pipeline(batches, pipeline_capacity, transit_times):
"""
Schedule multiple product batches through pipeline
Parameters:
- batches: list of {product, volume, source, destination, priority}
- pipeline_capacity: barrels/hour
- transit_times: dict of {(source, destination): hours}
"""
from collections import deque
schedule = []
current_time = 0
# Sort by priority and volume
sorted_batches = sorted(batches,
key=lambda x: (x['priority'], -x['volume']))
for batch in sorted_batches:
# Calculate transit time
transit = transit_times.get(
(batch['source'], batch['destination']), 24
)
# Calculate pump time
pump_time = batch['volume'] / pipeline_capacity
# Schedule
schedule.append({
'batch_id': batch['product'],
'start_time': current_time,
'pump_hours': pump_time,
'arrival_time': current_time + pump_time + transit,
'volume': batch['volume']
})
current_time += pump_time
return scheduleExample
Example
batches = [
{'product': 'Crude_Light', 'volume': 50000,
'source': 'Terminal_A', 'destination': 'Refinery_1', 'priority': 1},
{'product': 'Crude_Heavy', 'volume': 75000,
'source': 'Terminal_A', 'destination': 'Refinery_2', 'priority': 2},
]
schedule = batch_schedule_pipeline(batches, pipeline_capacity=2500,
transit_times={('Terminal_A', 'Refinery_1'): 20})
undefinedbatches = [
{'product': 'Crude_Light', 'volume': 50000,
'source': 'Terminal_A', 'destination': 'Refinery_1', 'priority': 1},
{'product': 'Crude_Heavy', 'volume': 75000,
'source': 'Terminal_A', 'destination': 'Refinery_2', 'priority': 2},
]
schedule = batch_schedule_pipeline(batches, pipeline_capacity=2500,
transit_times={('Terminal_A', 'Refinery_1'): 20})
undefinedMarine Transportation
海运
Vessel Types:
- VLCC (Very Large Crude Carrier): 2M barrels
- Suezmax: 1M barrels
- Aframax: 750K barrels
- Panamax: 500K barrels
- Product tankers: Various sizes
- LNG carriers: Specialized cryogenic
Optimization Model:
python
def optimize_tanker_fleet(shipments, vessels, ports, costs):
"""
Optimize tanker routing and scheduling
Parameters:
- shipments: list of {origin, destination, volume, earliest, latest}
- vessels: list of {vessel_id, capacity, speed, position, available_time}
- ports: dict of {port: {lat, lon}}
- costs: dict with fuel_cost, charter_rate, port_fees
"""
import numpy as np
from pulp import *
prob = LpProblem("Tanker_Routing", LpMinimize)
# Variables: assign vessel v to shipment s
x = {}
for v, vessel in enumerate(vessels):
for s, shipment in enumerate(shipments):
if vessel['capacity'] >= shipment['volume']:
x[v, s] = LpVariable(f"Assign_{v}_{s}", cat='Binary')
# Objective: minimize total cost
total_cost = []
for (v, s), var in x.items():
vessel = vessels[v]
shipment = shipments[s]
# Distance calculation (simplified)
distance = calculate_sea_distance(
ports[shipment['origin']],
ports[shipment['destination']]
)
# Voyage cost
voyage_time = distance / vessel['speed'] # hours
fuel_cost = costs['fuel_cost'] * distance * vessel['capacity'] * 0.001
charter_cost = costs['charter_rate'] * voyage_time
port_cost = costs['port_fees'] * 2 # origin + destination
total_cost.append((fuel_cost + charter_cost + port_cost) * var)
prob += lpSum(total_cost)
# Constraints: each shipment covered once
for s in range(len(shipments)):
prob += lpSum([x[v, s] for v, _ in x.keys() if _ == s]) == 1
# Constraints: vessel availability
for v in range(len(vessels)):
assignments = [x[v, s] for _, s in x.keys() if _ == v]
if assignments:
prob += lpSum(assignments) <= 1 # One voyage at a time
prob.solve(PULP_CBC_CMD(msg=0))
return {
'status': LpStatus[prob.status],
'total_cost': value(prob.objective),
'assignments': [(v, s) for (v, s) in x if x[v, s].varValue > 0.5]
}
def calculate_sea_distance(port1, port2):
"""Calculate great circle distance between ports"""
from math import radians, sin, cos, sqrt, atan2
lat1, lon1 = radians(port1['lat']), radians(port1['lon'])
lat2, lon2 = radians(port2['lat']), radians(port2['lon'])
dlat = lat2 - lat1
dlon = lon2 - lon1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * atan2(sqrt(a), sqrt(1-a))
return 3959 * c # miles船舶类型:
- VLCC(超大型原油运输船):200万桶
- Suezmax(苏伊士型油轮):100万桶
- Aframax(阿芙拉型油轮):75万桶
- Panamax(巴拿马型油轮):50万桶
- 成品油轮:多种尺寸
- LNG运输船:专用低温运输船
优化模型:
python
def optimize_tanker_fleet(shipments, vessels, ports, costs):
"""
Optimize tanker routing and scheduling
Parameters:
- shipments: list of {origin, destination, volume, earliest, latest}
- vessels: list of {vessel_id, capacity, speed, position, available_time}
- ports: dict of {port: {lat, lon}}
- costs: dict with fuel_cost, charter_rate, port_fees
"""
import numpy as np
from pulp import *
prob = LpProblem("Tanker_Routing", LpMinimize)
# Variables: assign vessel v to shipment s
x = {}
for v, vessel in enumerate(vessels):
for s, shipment in enumerate(shipments):
if vessel['capacity'] >= shipment['volume']:
x[v, s] = LpVariable(f"Assign_{v}_{s}", cat='Binary')
# Objective: minimize total cost
total_cost = []
for (v, s), var in x.items():
vessel = vessels[v]
shipment = shipments[s]
# Distance calculation (simplified)
distance = calculate_sea_distance(
ports[shipment['origin']],
ports[shipment['destination']]
)
# Voyage cost
voyage_time = distance / vessel['speed'] # hours
fuel_cost = costs['fuel_cost'] * distance * vessel['capacity'] * 0.001
charter_cost = costs['charter_rate'] * voyage_time
port_cost = costs['port_fees'] * 2 # origin + destination
total_cost.append((fuel_cost + charter_cost + port_cost) * var)
prob += lpSum(total_cost)
# Constraints: each shipment covered once
for s in range(len(shipments)):
prob += lpSum([x[v, s] for v, _ in x.keys() if _ == s]) == 1
# Constraints: vessel availability
for v in range(len(vessels)):
assignments = [x[v, s] for _, s in x.keys() if _ == v]
if assignments:
prob += lpSum(assignments) <= 1 # One voyage at a time
prob.solve(PULP_CBC_CMD(msg=0))
return {
'status': LpStatus[prob.status],
'total_cost': value(prob.objective),
'assignments': [(v, s) for (v, s) in x if x[v, s].varValue > 0.5]
}
def calculate_sea_distance(port1, port2):
"""Calculate great circle distance between ports"""
from math import radians, sin, cos, sqrt, atan2
lat1, lon1 = radians(port1['lat']), radians(port1['lon'])
lat2, lon2 = radians(port2['lat']), radians(port2['lon'])
dlat = lat2 - lat1
dlon = lon2 - lon1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * atan2(sqrt(a), sqrt(1-a))
return 3959 * c # milesRail & Truck Transportation
铁路和公路运输
Rail (Unit Trains):
- Typical: 100-120 tank cars per train
- Capacity: 700-750 barrels per car
- Cost-effective for medium distances (500-1500 miles)
- Flexible routing
Truck Transportation:
- Last-mile delivery
- Small volumes (200-300 barrels)
- Flexibility and speed
- Higher cost per unit
python
def optimize_truck_routes(deliveries, depot_location, truck_capacity, max_hours):
"""
Vehicle routing for fuel delivery trucks
Uses Clarke-Wright savings algorithm
"""
import numpy as np
# Calculate distances
def distance(loc1, loc2):
return np.sqrt((loc1[0] - loc2[0])**2 + (loc1[1] - loc2[1])**2)
# Calculate savings for combining routes
savings = []
n = len(deliveries)
for i in range(n):
for j in range(i+1, n):
save = (distance(depot_location, deliveries[i]['location']) +
distance(depot_location, deliveries[j]['location']) -
distance(deliveries[i]['location'], deliveries[j]['location']))
savings.append((save, i, j))
# Sort by savings (descending)
savings.sort(reverse=True)
# Build routes
routes = [[i] for i in range(n)]
route_loads = [deliveries[i]['volume'] for i in range(n)]
for save, i, j in savings:
# Find routes containing i and j
route_i = next((r for r in routes if i in r), None)
route_j = next((r for r in routes if j in r), None)
if route_i != route_j and route_i and route_j:
# Check if merge is feasible
combined_load = route_loads[routes.index(route_i)] + \
route_loads[routes.index(route_j)]
if combined_load <= truck_capacity:
# Merge routes
route_i.extend(route_j)
route_loads[routes.index(route_i)] = combined_load
routes.remove(route_j)
return {
'num_trucks': len(routes),
'routes': routes,
'utilization': [route_loads[routes.index(r)] / truck_capacity
for r in routes]
}铁路(单元列车):
- 典型配置:每列100-120节罐车
- 运力:每车700-750桶
- 中距离运输(500-1500英里)性价比高
- 路线灵活
公路运输:
- 最后一公里配送
- 小批量运输(200-300桶)
- 灵活、速度快
- 单位成本更高
python
def optimize_truck_routes(deliveries, depot_location, truck_capacity, max_hours):
"""
Vehicle routing for fuel delivery trucks
Uses Clarke-Wright savings algorithm
"""
import numpy as np
# Calculate distances
def distance(loc1, loc2):
return np.sqrt((loc1[0] - loc2[0])**2 + (loc1[1] - loc2[1])**2)
# Calculate savings for combining routes
savings = []
n = len(deliveries)
for i in range(n):
for j in range(i+1, n):
save = (distance(depot_location, deliveries[i]['location']) +
distance(depot_location, deliveries[j]['location']) -
distance(deliveries[i]['location'], deliveries[j]['location']))
savings.append((save, i, j))
# Sort by savings (descending)
savings.sort(reverse=True)
# Build routes
routes = [[i] for i in range(n)]
route_loads = [deliveries[i]['volume'] for i in range(n)]
for save, i, j in savings:
# Find routes containing i and j
route_i = next((r for r in routes if i in r), None)
route_j = next((r for r in routes if j in r), None)
if route_i != route_j and route_i and route_j:
# Check if merge is feasible
combined_load = route_loads[routes.index(route_i)] + \
route_loads[routes.index(route_j)]
if combined_load <= truck_capacity:
# Merge routes
route_i.extend(route_j)
route_loads[routes.index(route_i)] = combined_load
routes.remove(route_j)
return {
'num_trucks': len(routes),
'routes': routes,
'utilization': [route_loads[routes.index(r)] / truck_capacity
for r in routes]
}Storage & Inventory Management
存储与库存管理
Storage Types
存储类型
Above-Ground Storage Tanks (AST):
- Fixed roof, floating roof
- Typical: 50K-500K barrels
- Regular inspection and maintenance
Underground Storage:
- Salt caverns (natural gas, crude oil)
- Depleted reservoirs
- Very large capacity (millions of barrels)
Terminals:
- Import/export facilities
- Product blending
- Multi-modal connections
地上储罐(AST):
- 固定顶、浮顶
- 典型容量:5万-50万桶
- 定期检查和维护
地下存储:
- 盐穴(天然气、原油)
- 枯竭油气藏
- 超大容量(数百万桶)
终端站:
- 进出口设施
- 产品调和
- 多式联运衔接
Inventory Optimization
库存优化
python
import numpy as np
import pandas as pd
class EnergyInventoryOptimizer:
"""
Optimize inventory levels for energy products
considering price volatility and storage costs
"""
def __init__(self, storage_capacity, storage_cost, initial_inventory=0):
self.storage_capacity = storage_capacity
self.storage_cost = storage_cost # $/barrel/month
self.inventory = initial_inventory
def optimize_inventory_policy(self, demand_forecast, price_forecast,
horizon=12):
"""
Determine optimal inventory levels over planning horizon
Uses dynamic programming approach
"""
from pulp import *
prob = LpProblem("Inventory_Optimization", LpMinimize)
# Variables
inventory = {}
purchases = {}
sales = {}
for t in range(horizon):
inventory[t] = LpVariable(f"Inventory_{t}",
lowBound=0,
upBound=self.storage_capacity)
purchases[t] = LpVariable(f"Purchase_{t}", lowBound=0)
sales[t] = LpVariable(f"Sales_{t}", lowBound=0)
# Objective: maximize profit - storage costs
total_revenue = lpSum([sales[t] * price_forecast[t]
for t in range(horizon)])
total_purchase = lpSum([purchases[t] * price_forecast[t]
for t in range(horizon)])
total_storage = lpSum([inventory[t] * self.storage_cost
for t in range(horizon)])
prob += total_revenue - total_purchase - total_storage
# Constraints: inventory balance
for t in range(horizon):
if t == 0:
prev_inv = self.inventory
else:
prev_inv = inventory[t-1]
prob += inventory[t] == prev_inv + purchases[t] - sales[t]
# Constraints: meet demand
for t in range(horizon):
prob += sales[t] >= demand_forecast[t]
# Solve
prob.solve(PULP_CBC_CMD(msg=0))
return {
'status': LpStatus[prob.status],
'profit': value(prob.objective),
'inventory_levels': [inventory[t].varValue for t in range(horizon)],
'purchase_plan': [purchases[t].varValue for t in range(horizon)],
'sales_plan': [sales[t].varValue for t in range(horizon)]
}
def calculate_safety_stock(self, avg_demand, demand_std, lead_time,
service_level=0.95):
"""
Calculate safety stock for energy products
Uses standard normal distribution
"""
from scipy.stats import norm
z_score = norm.ppf(service_level)
safety_stock = z_score * demand_std * np.sqrt(lead_time)
reorder_point = (avg_demand * lead_time) + safety_stock
return {
'safety_stock': safety_stock,
'reorder_point': reorder_point,
'service_level': service_level
}python
import numpy as np
import pandas as pd
class EnergyInventoryOptimizer:
"""
Optimize inventory levels for energy products
considering price volatility and storage costs
"""
def __init__(self, storage_capacity, storage_cost, initial_inventory=0):
self.storage_capacity = storage_capacity
self.storage_cost = storage_cost # $/barrel/month
self.inventory = initial_inventory
def optimize_inventory_policy(self, demand_forecast, price_forecast,
horizon=12):
"""
Determine optimal inventory levels over planning horizon
Uses dynamic programming approach
"""
from pulp import *
prob = LpProblem("Inventory_Optimization", LpMinimize)
# Variables
inventory = {}
purchases = {}
sales = {}
for t in range(horizon):
inventory[t] = LpVariable(f"Inventory_{t}",
lowBound=0,
upBound=self.storage_capacity)
purchases[t] = LpVariable(f"Purchase_{t}", lowBound=0)
sales[t] = LpVariable(f"Sales_{t}", lowBound=0)
# Objective: maximize profit - storage costs
total_revenue = lpSum([sales[t] * price_forecast[t]
for t in range(horizon)])
total_purchase = lpSum([purchases[t] * price_forecast[t]
for t in range(horizon)])
total_storage = lpSum([inventory[t] * self.storage_cost
for t in range(horizon)])
prob += total_revenue - total_purchase - total_storage
# Constraints: inventory balance
for t in range(horizon):
if t == 0:
prev_inv = self.inventory
else:
prev_inv = inventory[t-1]
prob += inventory[t] == prev_inv + purchases[t] - sales[t]
# Constraints: meet demand
for t in range(horizon):
prob += sales[t] >= demand_forecast[t]
# Solve
prob.solve(PULP_CBC_CMD(msg=0))
return {
'status': LpStatus[prob.status],
'profit': value(prob.objective),
'inventory_levels': [inventory[t].varValue for t in range(horizon)],
'purchase_plan': [purchases[t].varValue for t in range(horizon)],
'sales_plan': [sales[t].varValue for t in range(horizon)]
}
def calculate_safety_stock(self, avg_demand, demand_std, lead_time,
service_level=0.95):
"""
Calculate safety stock for energy products
Uses standard normal distribution
"""
from scipy.stats import norm
z_score = norm.ppf(service_level)
safety_stock = z_score * demand_std * np.sqrt(lead_time)
reorder_point = (avg_demand * lead_time) + safety_stock
return {
'safety_stock': safety_stock,
'reorder_point': reorder_point,
'service_level': service_level
}Example usage
Example usage
optimizer = EnergyInventoryOptimizer(
storage_capacity=500000, # barrels
storage_cost=0.05, # $/barrel/month
initial_inventory=200000
)
optimizer = EnergyInventoryOptimizer(
storage_capacity=500000, # barrels
storage_cost=0.05, # $/barrel/month
initial_inventory=200000
)
Forecast data
Forecast data
demand_forecast = [50000, 55000, 60000, 58000, 52000, 48000,
45000, 50000, 55000, 60000, 65000, 70000]
price_forecast = [75, 78, 80, 77, 73, 70,
72, 75, 78, 80, 82, 85] # $/barrel
result = optimizer.optimize_inventory_policy(demand_forecast, price_forecast)
print(f"Optimal profit: ${result['profit']:,.2f}")
---demand_forecast = [50000, 55000, 60000, 58000, 52000, 48000,
45000, 50000, 55000, 60000, 65000, 70000]
price_forecast = [75, 78, 80, 77, 73, 70,
72, 75, 78, 80, 82, 85] # $/barrel
result = optimizer.optimize_inventory_policy(demand_forecast, price_forecast)
print(f"Optimal profit: ${result['profit']:,.2f}")
---Demand Forecasting for Energy
能源需求预测
Factors Affecting Energy Demand
影响能源需求的因素
Seasonal Patterns:
- Heating oil: Winter peaks
- Gasoline: Summer peaks (driving season)
- Natural gas: Heating and power generation
Economic Indicators:
- Industrial production
- GDP growth
- Unemployment rates
Weather:
- Temperature (heating/cooling degree days)
- Storm patterns
- Long-term climate trends
python
import pandas as pd
from statsmodels.tsa.holtwinters import ExponentialSmoothing
from prophet import Prophet
def forecast_energy_demand(historical_data, external_factors, horizon=12):
"""
Forecast energy demand using multiple methods
Parameters:
- historical_data: DataFrame with date and demand
- external_factors: DataFrame with weather, economic data
- horizon: forecast periods
"""
# Method 1: Holt-Winters for seasonal data
hw_model = ExponentialSmoothing(
historical_data['demand'],
seasonal_periods=12,
trend='add',
seasonal='multiplicative'
)
hw_fit = hw_model.fit()
hw_forecast = hw_fit.forecast(steps=horizon)
# Method 2: Prophet with external regressors
prophet_df = historical_data.copy()
prophet_df.columns = ['ds', 'y']
model = Prophet(yearly_seasonality=True)
# Add external factors
for col in external_factors.columns:
if col != 'date':
prophet_df[col] = external_factors[col]
model.add_regressor(col)
model.fit(prophet_df)
# Create future dataframe
future = model.make_future_dataframe(periods=horizon, freq='M')
# Would need to add future external factors here
prophet_forecast = model.predict(future)
# Ensemble: weighted average
final_forecast = 0.5 * hw_forecast + 0.5 * prophet_forecast['yhat'][-horizon:]
return {
'hw_forecast': hw_forecast,
'prophet_forecast': prophet_forecast['yhat'][-horizon:],
'ensemble_forecast': final_forecast,
'confidence_intervals': prophet_forecast[['yhat_lower', 'yhat_upper']][-horizon:]
}季节性模式:
- 取暖油:冬季需求高峰
- 汽油:夏季需求高峰(驾驶季)
- 天然气:取暖和发电需求
经济指标:
- 工业产量
- GDP增速
- 失业率
天气:
- 气温(采暖/制冷度日数)
- 风暴模式
- 长期气候趋势
python
import pandas as pd
from statsmodels.tsa.holtwinters import ExponentialSmoothing
from prophet import Prophet
def forecast_energy_demand(historical_data, external_factors, horizon=12):
"""
Forecast energy demand using multiple methods
Parameters:
- historical_data: DataFrame with date and demand
- external_factors: DataFrame with weather, economic data
- horizon: forecast periods
"""
# Method 1: Holt-Winters for seasonal data
hw_model = ExponentialSmoothing(
historical_data['demand'],
seasonal_periods=12,
trend='add',
seasonal='multiplicative'
)
hw_fit = hw_model.fit()
hw_forecast = hw_fit.forecast(steps=horizon)
# Method 2: Prophet with external regressors
prophet_df = historical_data.copy()
prophet_df.columns = ['ds', 'y']
model = Prophet(yearly_seasonality=True)
# Add external factors
for col in external_factors.columns:
if col != 'date':
prophet_df[col] = external_factors[col]
model.add_regressor(col)
model.fit(prophet_df)
# Create future dataframe
future = model.make_future_dataframe(periods=horizon, freq='M')
# Would need to add future external factors here
prophet_forecast = model.predict(future)
# Ensemble: weighted average
final_forecast = 0.5 * hw_forecast + 0.5 * prophet_forecast['yhat'][-horizon:]
return {
'hw_forecast': hw_forecast,
'prophet_forecast': prophet_forecast['yhat'][-horizon:],
'ensemble_forecast': final_forecast,
'confidence_intervals': prophet_forecast[['yhat_lower', 'yhat_upper']][-horizon:]
}Risk Management
风险管理
Price Risk
价格风险
Hedging Strategies:
- Futures contracts (NYMEX, ICE)
- Options (call/put)
- Swaps
- Collars (combined call + put)
python
def calculate_hedge_ratio(spot_prices, futures_prices):
"""
Calculate optimal hedge ratio using minimum variance
Hedge ratio = Cov(ΔS, ΔF) / Var(ΔF)
"""
import numpy as np
# Calculate returns
spot_returns = np.diff(spot_prices) / spot_prices[:-1]
futures_returns = np.diff(futures_prices) / futures_prices[:-1]
# Calculate hedge ratio
covariance = np.cov(spot_returns, futures_returns)[0, 1]
variance_futures = np.var(futures_returns)
hedge_ratio = covariance / variance_futures
return {
'hedge_ratio': hedge_ratio,
'correlation': np.corrcoef(spot_returns, futures_returns)[0, 1],
'effectiveness': 1 - np.var(spot_returns - hedge_ratio * futures_returns) / np.var(spot_returns)
}对冲策略:
- 期货合约(NYMEX、ICE)
- 期权(看涨/看跌)
- 掉期
- 领口策略(看涨+看跌组合)
python
def calculate_hedge_ratio(spot_prices, futures_prices):
"""
Calculate optimal hedge ratio using minimum variance
Hedge ratio = Cov(ΔS, ΔF) / Var(ΔF)
"""
import numpy as np
# Calculate returns
spot_returns = np.diff(spot_prices) / spot_prices[:-1]
futures_returns = np.diff(futures_prices) / futures_prices[:-1]
# Calculate hedge ratio
covariance = np.cov(spot_returns, futures_returns)[0, 1]
variance_futures = np.var(futures_returns)
hedge_ratio = covariance / variance_futures
return {
'hedge_ratio': hedge_ratio,
'correlation': np.corrcoef(spot_returns, futures_returns)[0, 1],
'effectiveness': 1 - np.var(spot_returns - hedge_ratio * futures_returns) / np.var(spot_returns)
}Supply Disruption Risk
供应中断风险
Risk Factors:
- Geopolitical events
- Natural disasters (hurricanes, earthquakes)
- Pipeline outages
- Refinery maintenance/shutdowns
Mitigation Strategies:
python
def supply_chain_resilience_score(network_data):
"""
Calculate supply chain resilience metrics
"""
import networkx as nx
# Create network graph
G = nx.DiGraph()
for edge in network_data['connections']:
G.add_edge(edge['from'], edge['to'],
capacity=edge['capacity'],
reliability=edge['reliability'])
metrics = {
# Redundancy: multiple paths
'redundancy': nx.node_connectivity(G.to_undirected()),
# Centrality: identify critical nodes
'critical_nodes': nx.betweenness_centrality(G),
# Robustness: network efficiency after node removal
'robustness': calculate_network_robustness(G)
}
return metrics
def calculate_network_robustness(G):
"""Simulate node failures and measure impact"""
import random
original_efficiency = nx.global_efficiency(G)
robustness_scores = []
nodes = list(G.nodes())
for _ in range(100): # Monte Carlo simulation
# Randomly remove nodes
num_failures = random.randint(1, len(nodes) // 4)
failed_nodes = random.sample(nodes, num_failures)
G_temp = G.copy()
G_temp.remove_nodes_from(failed_nodes)
if len(G_temp.nodes()) > 0:
efficiency = nx.global_efficiency(G_temp)
robustness_scores.append(efficiency / original_efficiency)
return np.mean(robustness_scores)风险因素:
- 地缘政治事件
- 自然灾害(飓风、地震)
- 管道故障
- 炼油厂维护/停工
缓解策略:
python
def supply_chain_resilience_score(network_data):
"""
Calculate supply chain resilience metrics
"""
import networkx as nx
# Create network graph
G = nx.DiGraph()
for edge in network_data['connections']:
G.add_edge(edge['from'], edge['to'],
capacity=edge['capacity'],
reliability=edge['reliability'])
metrics = {
# Redundancy: multiple paths
'redundancy': nx.node_connectivity(G.to_undirected()),
# Centrality: identify critical nodes
'critical_nodes': nx.betweenness_centrality(G),
# Robustness: network efficiency after node removal
'robustness': calculate_network_robustness(G)
}
return metrics
def calculate_network_robustness(G):
"""Simulate node failures and measure impact"""
import random
original_efficiency = nx.global_efficiency(G)
robustness_scores = []
nodes = list(G.nodes())
for _ in range(100): # Monte Carlo simulation
# Randomly remove nodes
num_failures = random.randint(1, len(nodes) // 4)
failed_nodes = random.sample(nodes, num_failures)
G_temp = G.copy()
G_temp.remove_nodes_from(failed_nodes)
if len(G_temp.nodes()) > 0:
efficiency = nx.global_efficiency(G_temp)
robustness_scores.append(efficiency / original_efficiency)
return np.mean(robustness_scores)Environmental & Safety Compliance
环境与安全合规
Emissions Tracking
排放追踪
python
def calculate_emissions(transportation_data, emission_factors):
"""
Calculate CO2 emissions from energy logistics
Parameters:
- transportation_data: list of {mode, distance, volume}
- emission_factors: dict of {mode: kg_CO2_per_barrel_mile}
"""
total_emissions = 0
for transport in transportation_data:
mode = transport['mode']
distance = transport['distance']
volume = transport['volume']
emissions = emission_factors.get(mode, 0) * distance * volume
total_emissions += emissions
return {
'total_emissions_kg': total_emissions,
'total_emissions_tons': total_emissions / 1000,
'emissions_per_barrel': total_emissions / sum(t['volume'] for t in transportation_data)
}python
def calculate_emissions(transportation_data, emission_factors):
"""
Calculate CO2 emissions from energy logistics
Parameters:
- transportation_data: list of {mode, distance, volume}
- emission_factors: dict of {mode: kg_CO2_per_barrel_mile}
"""
total_emissions = 0
for transport in transportation_data:
mode = transport['mode']
distance = transport['distance']
volume = transport['volume']
emissions = emission_factors.get(mode, 0) * distance * volume
total_emissions += emissions
return {
'total_emissions_kg': total_emissions,
'total_emissions_tons': total_emissions / 1000,
'emissions_per_barrel': total_emissions / sum(t['volume'] for t in transportation_data)
}Typical emission factors (kg CO2 per barrel-mile)
Typical emission factors (kg CO2 per barrel-mile)
emission_factors = {
'pipeline': 0.005,
'rail': 0.015,
'truck': 0.030,
'barge': 0.008,
'tanker': 0.004
}
undefinedemission_factors = {
'pipeline': 0.005,
'rail': 0.015,
'truck': 0.030,
'barge': 0.008,
'tanker': 0.004
}
undefinedSafety Management
安全管理
Key Safety Considerations:
- Pipeline integrity management
- Spill prevention and response
- Tank inspection and maintenance
- Vapor control systems
- Emergency response planning
核心安全注意事项:
- 管道完整性管理
- 泄漏预防与响应
- 储罐检查与维护
- 蒸汽控制系统
- 应急响应规划
Tools & Libraries
工具与库
Python Libraries
Python 库
Optimization:
- : Linear programming
PuLP - : Optimization modeling
pyomo - : Gurobi optimizer
gurobipy - : General optimization
scipy.optimize
Network Analysis:
- : Graph theory and network analysis
networkx - : Large-scale network analysis
igraph
Time Series & Forecasting:
- : Time series analysis
statsmodels - : Facebook Prophet forecasting
prophet - : Auto ARIMA
pmdarima
Geospatial:
- : Geographic data
geopandas - : Interactive maps
folium - : Coordinate transformations
pyproj
优化类:
- : 线性规划
PuLP - : 优化建模
pyomo - : Gurobi优化器
gurobipy - : 通用优化工具
scipy.optimize
网络分析类:
- : 图论与网络分析
networkx - : 大规模网络分析
igraph
时间序列与预测类:
- : 时间序列分析
statsmodels - : Facebook Prophet预测工具
prophet - : 自动ARIMA工具
pmdarima
地理空间类:
- : 地理数据处理
geopandas - : 交互式地图
folium - : 坐标转换
pyproj
Commercial Software
商业软件
Planning & Optimization:
- AVEVA (OSIsoft): Asset optimization
- AspenTech: Process optimization
- Energy Exemplar PLEXOS: Energy market simulation
- SAP S/4HANA Oil & Gas: ERP for energy
- Oracle Primavera: Project management
Trading & Risk:
- Allegro (formerly SunGard): Commodity trading and risk management (CTRM)
- Openlink Endur: Energy trading platform
- Triple Point: Commodity management
Transportation:
- Veson Nautical: Marine transportation (IMOS)
- ShipTech: Vessel scheduling
- CargoSmart: Supply chain visibility
规划与优化类:
- AVEVA (OSIsoft): 资产优化
- AspenTech: 流程优化
- Energy Exemplar PLEXOS: 能源市场模拟
- SAP S/4HANA Oil & Gas: 能源行业ERP
- Oracle Primavera: 项目管理
交易与风险类:
- Allegro (原SunGard): 大宗商品交易与风险管理(CTRM)
- Openlink Endur: 能源交易平台
- Triple Point: 大宗商品管理
运输类:
- Veson Nautical: 海运管理(IMOS)
- ShipTech: 船舶调度
- CargoSmart: 供应链可视化
Common Challenges & Solutions
常见挑战与解决方案
Challenge: Pipeline Capacity Constraints
挑战:管道容量约束
Problem:
- Limited throughput
- Competing shippers
- Bottlenecks at key junctions
Solutions:
- Capacity optimization models
- Strategic storage placement
- Alternative routing (rail, truck)
- Contractual priority arrangements
- Pipeline expansion analysis
问题:
- 吞吐量有限
- 托运人竞争运力
- 关键节点瓶颈
解决方案:
- 运力优化模型
- 战略性存储布局
- 替代运输路线(铁路、卡车)
- 合同优先级安排
- 管道扩建分析
Challenge: Price Volatility
挑战:价格波动
Problem:
- Commodity price swings
- Impact on inventory value
- Planning uncertainty
Solutions:
- Financial hedging strategies
- Flexible supply contracts
- Inventory optimization (timing of purchases)
- Scenario planning
- Real options analysis
问题:
- 大宗商品价格波动
- 影响库存价值
- 规划不确定性
解决方案:
- 金融对冲策略
- 灵活供应合同
- 库存优化(采购时机选择)
- 场景规划
- 实物期权分析
Challenge: Demand Uncertainty
挑战:需求不确定性
Problem:
- Weather variability
- Economic cycles
- Competition from alternatives (renewables)
Solutions:
- Advanced forecasting (machine learning)
- Flexible supply agreements
- Safety stock optimization
- Real-time demand sensing
- Agile network design
问题:
- 天气波动
- 经济周期
- 替代能源(可再生能源)竞争
解决方案:
- 先进预测技术(机器学习)
- 灵活供应协议
- 安全库存优化
- 实时需求感知
- 敏捷网络设计
Challenge: Regulatory Compliance
挑战:监管合规
Problem:
- Environmental regulations (emissions)
- Safety requirements (pipeline integrity)
- Reporting obligations
- Permitting delays
Solutions:
- Compliance management systems
- Proactive monitoring and maintenance
- Emissions tracking and reporting tools
- Regulatory affairs expertise
- Risk assessment frameworks
问题:
- 环保法规(排放)
- 安全要求(管道完整性)
- 报告义务
- 许可延迟
解决方案:
- 合规管理系统
- 主动监控与维护
- 排放追踪与报告工具
- 监管事务专业支持
- 风险评估框架
Challenge: Infrastructure Aging
挑战:基础设施老化
Problem:
- Old pipelines and facilities
- Increased maintenance costs
- Higher failure risk
Solutions:
- Predictive maintenance (IoT sensors)
- Risk-based inspection programs
- Capital investment prioritization
- Digital twins for asset management
- Phased replacement strategies
问题:
- 管道和设施老旧
- 维护成本上升
- 故障风险升高
解决方案:
- 预测性维护(IoT传感器)
- 基于风险的检查方案
- 资本投资优先级排序
- 资产管理数字孪生
- 分阶段替换策略
Output Format
输出格式
Energy Logistics Optimization Report
能源物流优化报告
Executive Summary:
- Current network performance
- Optimization opportunities identified
- Recommended changes
- Expected cost savings and benefits
Network Configuration:
| Asset Type | Location | Capacity | Utilization | Annual Cost | Status |
|---|---|---|---|---|---|
| Pipeline | TX to LA | 500K bbl/day | 82% | $25M | Operating |
| Terminal | Houston | 2M bbl | 65% | $8M | Expansion planned |
| Storage | Cushing | 5M bbl | 78% | $12M | Operating |
Transportation Analysis:
| Mode | Volume (bbl/day) | Avg. Distance | Cost per bbl-mile | Total Annual Cost |
|---|---|---|---|---|
| Pipeline | 1,200,000 | 450 mi | $0.0050 | $985M |
| Rail | 150,000 | 800 mi | $0.0150 | $657M |
| Truck | 50,000 | 200 mi | $0.0300 | $110M |
| Marine | 800,000 | 1,200 mi | $0.0040 | $1,401M |
Cost Breakdown:
| Category | Current Annual | Optimized | Savings | % Reduction |
|---|---|---|---|---|
| Transportation | $3,153M | $2,890M | $263M | 8.3% |
| Storage | $45M | $38M | $7M | 15.6% |
| Inventory Carrying | $180M | $155M | $25M | 13.9% |
| Total | $3,378M | $3,083M | $295M | 8.7% |
Risk Assessment:
| Risk Factor | Probability | Impact | Mitigation Strategy |
|---|---|---|---|
| Pipeline outage | Medium | High | Alternative routing, storage buffer |
| Price spike | High | Medium | Hedging program, flexible contracts |
| Hurricane disruption | Low | High | Emergency response plan, insurance |
Recommendations:
- Increase pipeline utilization through scheduling optimization
- Consolidate storage facilities (reduce from 8 to 5 locations)
- Implement hedging program for 60% of projected volume
- Invest in predictive maintenance for aging pipeline segments
执行摘要:
- 当前网络性能
- 识别出的优化机会
- 建议的改进措施
- 预期成本节约和收益
网络配置:
| 资产类型 | 位置 | 容量 | 利用率 | 年成本 | 状态 |
|---|---|---|---|---|---|
| 管道 | 德克萨斯州至路易斯安那州 | 50万桶/天 | 82% | 2500万美元 | 运营中 |
| 终端站 | 休斯顿 | 200万桶 | 65% | 800万美元 | 规划扩建 |
| 存储设施 | 库欣 | 500万桶 | 78% | 1200万美元 | 运营中 |
运输分析:
| 运输方式 | 运输量(桶/天) | 平均距离 | 每桶-英里成本 | 年总成本 |
|---|---|---|---|---|
| 管道 | 1,200,000 | 450英里 | 0.0050美元 | 9.85亿美元 |
| 铁路 | 150,000 | 800英里 | 0.0150美元 | 6.57亿美元 |
| 卡车 | 50,000 | 200英里 | 0.0300美元 | 1.10亿美元 |
| 海运 | 800,000 | 1200英里 | 0.0040美元 | 14.01亿美元 |
成本明细:
| 类别 | 当前年成本 | 优化后年成本 | 节约金额 | 降幅比例 |
|---|---|---|---|---|
| 运输 | 31.53亿美元 | 28.90亿美元 | 2.63亿美元 | 8.3% |
| 存储 | 4500万美元 | 3800万美元 | 700万美元 | 15.6% |
| 库存持有成本 | 1.80亿美元 | 1.55亿美元 | 2500万美元 | 13.9% |
| 总计 | 33.78亿美元 | 30.83亿美元 | 2.95亿美元 | 8.7% |
风险评估:
| 风险因素 | 发生概率 | 影响程度 | 缓解策略 |
|---|---|---|---|
| 管道故障 | 中等 | 高 | 替代路线、存储缓冲 |
| 价格飙升 | 高 | 中等 | 对冲方案、灵活合同 |
| 飓风 disruption | 低 | 高 | 应急响应计划、保险 |
建议:
- 通过调度优化提升管道利用率
- 整合存储设施(从8个减少到5个)
- 为60%的预计运输量实施对冲方案
- 对老旧管道段投资部署预测性维护
Questions to Ask
需要询问的问题
If you need more context:
- What type of energy commodities are you handling? (crude, refined, gas)
- What's the geographic scope of operations?
- What transportation modes are currently used?
- What are the main cost drivers and constraints?
- What storage infrastructure exists?
- Are there specific regulatory or safety concerns?
- What's the primary optimization goal? (cost, reliability, service)
如果你需要更多上下文信息:
- 你目前处理的是哪种能源商品?(原油、成品油、天然气)
- 运营的地理范围是哪里?
- 当前使用的运输方式有哪些?
- 主要的成本驱动因素和约束是什么?
- 现有哪些存储基础设施?
- 是否有特定的监管或安全问题需要考虑?
- 核心优化目标是什么?(成本、可靠性、服务水平)
Related Skills
相关技能
- renewable-energy-planning: For wind, solar, and renewable logistics
- power-grid-optimization: For electricity transmission and distribution
- energy-storage-optimization: For battery and storage systems
- drilling-logistics: For upstream oil and gas operations
- fuel-distribution: For retail fuel delivery
- network-design: For general supply chain network optimization
- route-optimization: For transportation routing
- inventory-optimization: For inventory management strategies
- risk-mitigation: For supply chain risk management
- renewable-energy-planning: 风能、太阳能和可再生能源物流相关
- power-grid-optimization: 电力传输和配送相关
- energy-storage-optimization: 电池和存储系统相关
- drilling-logistics: 上游油气运营相关
- fuel-distribution: 零售燃料配送相关
- network-design: 通用供应链网络优化相关
- route-optimization: 运输路径规划相关
- inventory-optimization: 库存管理策略相关
- risk-mitigation: 供应链风险管理相关