LINC-BIT commited on
Commit
7cae457
·
verified ·
1 Parent(s): 37f5997

Upload 15 files

Browse files
code/long-term prediction/CNN.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pandas as pd
3
+ import torch
4
+ import torch.nn as nn
5
+ from torch.utils.data import DataLoader, Dataset
6
+ import numpy as np
7
+ from glob import glob
8
+
9
+ # 参数设置
10
+ DATA_DIR = "G:\\loading_benchmark\\bakFlightLoadData\\bakFlightLoadData" # 数据文件夹路径
11
+ AIRCRAFT_MODELS = ["A320", "B737", "A330", "A350", "B777", "B787"]
12
+ TRAIN_DAYS = 40
13
+ TEST_DAYS = 47
14
+
15
+ # 数据处理
16
+ def load_and_process_data(data_dir, aircraft_models):
17
+ all_files = sorted(glob(os.path.join(data_dir, "BAKFLGITH_LOADDATA*.csv")))
18
+ data_by_day = []
19
+
20
+ for file in all_files:
21
+ df = pd.read_csv(file, header=None, usecols=[0, 1, 3], names=["fid", "fleetId", "weight"],
22
+ encoding='ISO-8859-1')
23
+ daily_data = {}
24
+ for model in aircraft_models:
25
+ model_data = df[df["fleetId"].str.contains(model, na=False)]
26
+ if not model_data.empty:
27
+ daily_avg = model_data["weight"].mean() # 每天的平均载货重量
28
+ daily_data[model] = daily_avg
29
+ data_by_day.append(daily_data)
30
+
31
+ return data_by_day
32
+
33
+
34
+ def prepare_data(data_by_day, train_days, test_days):
35
+ """
36
+ 准备按机型的训练和测试数据,每天计算平均值,分为训练和测试集。
37
+ """
38
+ train_data = data_by_day[:train_days]
39
+ test_data = data_by_day[:train_days + test_days]
40
+
41
+ train_processed = {model: [] for model in AIRCRAFT_MODELS}
42
+ test_processed = {model: [] for model in AIRCRAFT_MODELS}
43
+
44
+ for daily_data in train_data:
45
+ for model in AIRCRAFT_MODELS:
46
+ if model in daily_data:
47
+ train_processed[model].append(daily_data[model])
48
+
49
+ for daily_data in test_data:
50
+ for model in AIRCRAFT_MODELS:
51
+ if model in daily_data:
52
+ test_processed[model].append(daily_data[model])
53
+
54
+ return train_processed, test_processed
55
+
56
+
57
+ # 自定义数据集
58
+ class AircraftDataset(Dataset):
59
+ def __init__(self, data):
60
+ self.data = data
61
+
62
+ def __len__(self):
63
+ return len(self.data)
64
+
65
+ def __getitem__(self, idx):
66
+ return torch.tensor([self.data[idx]], dtype=torch.float32)
67
+
68
+
69
+ # CNN 模型
70
+ class CNNSPredictor(nn.Module):
71
+ def __init__(self, input_size, output_size):
72
+ super(CNNSPredictor, self).__init__()
73
+ self.conv1 = nn.Conv1d(in_channels=1, out_channels=64, kernel_size=1, padding=1)
74
+ self.pool = nn.MaxPool1d(2)
75
+ self.dropout = nn.Dropout(p=0.01)
76
+ self.conv2 = nn.Conv1d(in_channels=64, out_channels=32, kernel_size=1, padding=1)
77
+ self.fc1 = nn.Linear(32, 64) # 全连接层,用于输出之前的隐藏层
78
+ self.fc2 = nn.Linear(64, output_size)
79
+
80
+ def forward(self, x):
81
+ # 输入 x 形状: [batch_size, 1, seq_len]
82
+ x = self.conv1(x)
83
+ x = self.pool(x)
84
+ x = self.dropout(x)
85
+ x = self.conv2(x)
86
+ x = self.pool(x)
87
+ x = self.dropout(x)
88
+ x = torch.flatten(x, 1) # 展平
89
+ x = self.fc1(x)
90
+ x = self.fc2(x)
91
+ return x
92
+
93
+
94
+ # 训练和测试函数
95
+ def train_model(train_loader, model, criterion, optimizer, epochs=50):
96
+ model.train()
97
+ for epoch in range(epochs):
98
+ total_loss = 0
99
+ for batch in train_loader:
100
+ optimizer.zero_grad()
101
+ batch = batch.unsqueeze(1) # [batch, 1, seq_len] 扩展维度,适应 Conv1d
102
+ predictions = model(batch)
103
+ loss = criterion(predictions, batch)
104
+ loss.backward()
105
+ optimizer.step()
106
+ total_loss += loss.item()
107
+ print(f"Epoch {epoch + 1}/{epochs}, Loss: {total_loss:.4f}")
108
+
109
+
110
+ def test_model(test_loader, model):
111
+ model.eval()
112
+ predictions = []
113
+ true_values = []
114
+ with torch.no_grad():
115
+ for batch in test_loader:
116
+ batch = batch.unsqueeze(1) # [batch_size, 1, seq_len]
117
+ preds = model(batch)
118
+ predictions.append(preds.squeeze().numpy())
119
+ true_values.append(batch.squeeze().numpy())
120
+
121
+ mae_list = []
122
+ mape_list = []
123
+ acc = 0
124
+ for i in range(len(true_values)):
125
+ mae = np.abs(predictions[i] - true_values[i]) # 平均绝对误差
126
+ mape = np.abs(predictions[i] - true_values[i])/true_values[i]
127
+ mae_list.append(mae)
128
+ mape_list.append(mape)
129
+ if mape * 100 < 7:
130
+ acc += 1
131
+ return true_values, predictions, mae_list, mape_list, acc / len(true_values)
132
+
133
+
134
+ # 主程序
135
+ if __name__ == "__main__":
136
+ # 加载数据
137
+ data_by_day = load_and_process_data(DATA_DIR, AIRCRAFT_MODELS)
138
+
139
+ # 按机型分开训练和测试
140
+ results = {}
141
+ for model in AIRCRAFT_MODELS:
142
+ print(f"Processing model: {model}")
143
+ fw = open(f'G:\\loading_benchmark\\result\\pred_{model}_cnn2', 'w')
144
+ # 准备训练和测试数据
145
+ train_processed, test_processed = prepare_data(data_by_day, TRAIN_DAYS, TEST_DAYS)
146
+ train_data = train_processed[model]
147
+ test_data = test_processed[model]
148
+
149
+ if not train_data or not test_data:
150
+ print(f"No data available for {model}")
151
+ continue
152
+
153
+ train_dataset = AircraftDataset(train_data)
154
+ test_dataset = AircraftDataset(test_data)
155
+ train_loader = DataLoader(train_dataset, batch_size=8, shuffle=True)
156
+ test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False)
157
+
158
+ # 定义模型和训练
159
+ input_size = 1 # 仅平均载货重量作为输入
160
+ output_size = 1 # 预测平均载货重量
161
+ model_instance = CNNSPredictor(input_size, output_size)
162
+
163
+ criterion = nn.MSELoss()
164
+ optimizer = torch.optim.Adam(model_instance.parameters(), lr=0.001)
165
+
166
+ # 训练模型
167
+ train_model(train_loader, model_instance, criterion, optimizer, epochs=600)
168
+
169
+ # 测试模型
170
+ true, predictions, mae, mse, acc = test_model(test_loader, model_instance)
171
+ for i in range(len(predictions)):
172
+ fw.write(f"{true[i]}\t{predictions[i]}\t{mae[i]}\t{mse[i]}\t{acc}\n")
173
+
174
+ # 输出结果
175
+ # for model, preds in results.items():
176
+ # print(f"Results for {model}:")
177
+ # print(preds)
code/long-term prediction/LSTM.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ import os
4
+ import pandas as pd
5
+ import torch
6
+ import torch.nn as nn
7
+ from torch.utils.data import DataLoader, Dataset
8
+ import numpy as np
9
+ from glob import glob
10
+ from einops import rearrange
11
+ # 参数设置
12
+ DATA_DIR = "G:\\loading_benchmark\\bakFlightLoadData\\bakFlightLoadData" # 数据文件夹路径
13
+ # AIRCRAFT_MODELS = ['A320-232D', 'A320-23B', 'A320-21B', 'A320-23A', 'A320-21A', 'A320-27B', 'A320-27C', 'A320-21D', 'A320-27A', 'A320-214S']
14
+ AIRCRAFT_MODELS = ["A320", "B737", "A330", "A350", "B777", "B787"]
15
+ # AIRCRAFT_MODELS = ["A320"]
16
+ TRAIN_DAYS = 40
17
+ TEST_DAYS = 47
18
+
19
+
20
+ # 数据处理
21
+ def load_and_process_data(data_dir, aircraft_models):
22
+ all_files = sorted(glob(os.path.join(data_dir, "BAKFLGITH_LOADDATA*.csv")))
23
+ data_by_day = []
24
+
25
+ for file in all_files:
26
+ df = pd.read_csv(file, header=None, usecols=[0, 1, 3], names=["fid", "fleetId", "weight"],
27
+ encoding='ISO-8859-1')
28
+ daily_data = {}
29
+ for model in aircraft_models:
30
+ model_data = df[df["fleetId"].str.contains(model, na=False)]
31
+ if not model_data.empty:
32
+ # model_data = model_data.groupby("fid")["weight"].transform('sum')
33
+ daily_avg = model_data["weight"].mean() # 每天的平均载货重量
34
+ # grouped_data = model_data.groupby("fid")["weight"].sum()
35
+ # # 计算该机型的平均载货重量(按航班ID的总重量平均)
36
+ # daily_avg = grouped_data.mean()
37
+ daily_data[model] = daily_avg
38
+ data_by_day.append(daily_data)
39
+
40
+ return data_by_day
41
+
42
+
43
+ def prepare_data(data_by_day, train_days, test_days):
44
+ """
45
+ 准备按机型的训练和测试数据,每天计算平均值,分为训练和测试集。
46
+ """
47
+ train_data = data_by_day[:train_days]
48
+ test_data = data_by_day[:train_days + test_days]
49
+
50
+ train_processed = {model: [] for model in AIRCRAFT_MODELS}
51
+ test_processed = {model: [] for model in AIRCRAFT_MODELS}
52
+
53
+ for daily_data in train_data:
54
+ for model in AIRCRAFT_MODELS:
55
+ if model in daily_data:
56
+ train_processed[model].append(daily_data[model])
57
+
58
+ for daily_data in test_data:
59
+ for model in AIRCRAFT_MODELS:
60
+ if model in daily_data:
61
+ test_processed[model].append(daily_data[model])
62
+
63
+ return train_processed, test_processed
64
+
65
+
66
+ # 自定义数据集
67
+ class AircraftDataset(Dataset):
68
+ def __init__(self, data):
69
+ self.data = data
70
+
71
+ def __len__(self):
72
+ return len(self.data)
73
+
74
+ def __getitem__(self, idx):
75
+ return torch.tensor([self.data[idx]], dtype=torch.float32)
76
+
77
+
78
+ # LSTM 模型
79
+ class LSTMPredictor(nn.Module):
80
+ def __init__(self, input_size, hidden_size, num_layers, output_size):
81
+ super(LSTMPredictor, self).__init__()
82
+ self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True,bidirectional=False)
83
+ self.dropout = nn.Dropout(p=0.05)
84
+ self.conv2 = nn.Conv1d(in_channels=64, out_channels=32, kernel_size=1, padding=1)
85
+ self.fc1 = nn.Linear(64,32) # 全连接层,用于输出之前的隐藏层
86
+ self.fc = nn.Linear(32, output_size)
87
+
88
+ def forward(self, x):
89
+ out, _ = self.lstm(x)
90
+
91
+ # out = self.dropout(out)
92
+ x = out
93
+ x = self.dropout(x)
94
+ x = self.fc1(x)
95
+ x = self.fc(x)
96
+ # out = self.fc(out[:, -1, :])
97
+ return x
98
+
99
+
100
+ # 训练和测试函数
101
+ def train_model(train_loader, model, criterion, optimizer, epochs=50):
102
+ model.train()
103
+ optimizer.zero_grad()
104
+ for epoch in range(epochs):
105
+ total_loss = 0
106
+ for batch in train_loader:
107
+ optimizer.zero_grad()
108
+ batch = batch.unsqueeze(1) # [batch, seq_len=1, features]
109
+ predictions = model(batch)
110
+ loss = criterion(predictions, batch)
111
+ loss.backward()
112
+ optimizer.step()
113
+ total_loss += loss.item()
114
+ print(f"Epoch {epoch + 1}/{epochs}, Loss: {total_loss:.4f}")
115
+
116
+
117
+ def test_model(test_loader, model):
118
+
119
+ predictions = []
120
+ true_values = []
121
+ with torch.no_grad():
122
+ for batch in test_loader:
123
+ batch = batch.unsqueeze(1) # [batch_size, seq_len=1, features]
124
+ preds = model(batch)
125
+ predictions.append(preds.squeeze().numpy())
126
+ true_values.append(batch.squeeze().numpy())
127
+
128
+
129
+ acc = 0
130
+ # 计算误差
131
+ mae_list = []
132
+ mape_list = []
133
+ for i in range(len(true_values)):
134
+ mae = np.abs(predictions[i] - true_values[i]) # 平均绝对误差
135
+ mape = np.abs(predictions[i] - true_values[i])/true_values[i]
136
+ mae_list.append(mae)
137
+ mape_list.append(mape)
138
+ if mape*100 < 7:
139
+ acc+=1
140
+ # print(f"Test MAE: {mae:.4f}, Test MSE: {mape:.4f}")
141
+ return true_values,predictions, mae_list, mape_list,acc/len(true_values)
142
+
143
+
144
+ # 主程序
145
+ if __name__ == "__main__":
146
+ # 加载数据
147
+ data_by_day = load_and_process_data(DATA_DIR, AIRCRAFT_MODELS)
148
+
149
+ # 按机型分开训练和测试
150
+ results = {}
151
+ for model in AIRCRAFT_MODELS:
152
+ print(f"Processing model: {model}")
153
+ fw = open('G:\\loading_benchmark\\result\\pred_'+model+'_lstm3', 'w')
154
+ # 准备训练和测试数据
155
+ train_processed, test_processed = prepare_data(data_by_day, TRAIN_DAYS, TEST_DAYS)
156
+ print(train_processed[model])
157
+ train_data = train_processed[model]
158
+ test_data = test_processed[model]
159
+
160
+ if not train_data or not test_data:
161
+ print(f"No data available for {model}")
162
+ continue
163
+ print(train_data)
164
+ train_dataset = AircraftDataset(train_data)
165
+ test_dataset = AircraftDataset(test_data)
166
+ train_loader = DataLoader(train_dataset, batch_size=8, shuffle=True)
167
+ test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False)
168
+
169
+ # 定义模型和训练
170
+ input_size = 1 # 仅平均载货重量作为输入
171
+ hidden_size = 64
172
+ num_layers = 2
173
+ output_size = 1 # 预测平均载货重量
174
+ model_instance = LSTMPredictor(input_size, hidden_size, num_layers, output_size)
175
+
176
+ criterion = nn.MSELoss()
177
+ optimizer = torch.optim.Adam(model_instance.parameters(), lr=0.001)
178
+
179
+ # 训练模型
180
+ train_model(train_loader, model_instance, criterion, optimizer, epochs=500)
181
+
182
+ # 测试模型
183
+ true,predictions,mae,mse,acc = test_model(test_loader, model_instance)
184
+ for i in range(len(predictions)):
185
+ fw.write(str(true[i])+"\t"+str(predictions[i])+"\t"+str(mae[i])+"\t"+str(mse[i])+"\t"+str(acc)+"\n")
186
+ # 输出结果
187
+ # for model, preds in results.items():
188
+ # print(f"Results for {model}:")
189
+ # print(preds)
code/long-term prediction/regression.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ import os
4
+ import pandas as pd
5
+ import torch
6
+ import torch.nn as nn
7
+ from torch.utils.data import DataLoader, Dataset
8
+ import numpy as np
9
+ from glob import glob
10
+
11
+ # 参数设置
12
+ DATA_DIR = "G:\\loading_benchmark\\bakFlightLoadData\\bakFlightLoadData" # 数据文件夹路径
13
+ AIRCRAFT_MODELS = ["A320", "B737", "A330", "A350", "B777", "B787"]
14
+ # AIRCRAFT_MODELS = ["A320"]
15
+ TRAIN_DAYS = 40
16
+ TEST_DAYS = 47
17
+
18
+
19
+ # 数据处理
20
+ def load_and_process_data(data_dir, aircraft_models):
21
+ all_files = sorted(glob(os.path.join(data_dir, "BAKFLGITH_LOADDATA*.csv")))
22
+ data_by_day = []
23
+
24
+ for file in all_files:
25
+ df = pd.read_csv(file, header=None, usecols=[0, 1, 3], names=["fid", "fleetId", "weight"],
26
+ encoding='ISO-8859-1')
27
+ daily_data = {}
28
+ for model in aircraft_models:
29
+ model_data = df[df["fleetId"].str.contains(model, na=False)]
30
+ if not model_data.empty:
31
+ daily_avg = model_data["weight"].mean() # 每天的平均载货重量
32
+ daily_data[model] = daily_avg
33
+ data_by_day.append(daily_data)
34
+
35
+ return data_by_day
36
+
37
+
38
+ def prepare_data(data_by_day, train_days, test_days):
39
+ """
40
+ 准备按机型的训练和测试数据,每天计算平均值,分为训练和测试集。
41
+ """
42
+ train_data = data_by_day[:train_days]
43
+ test_data = data_by_day[:train_days + test_days]
44
+
45
+ train_processed = {model: [] for model in AIRCRAFT_MODELS}
46
+ test_processed = {model: [] for model in AIRCRAFT_MODELS}
47
+
48
+ for daily_data in train_data:
49
+ for model in AIRCRAFT_MODELS:
50
+ if model in daily_data:
51
+ train_processed[model].append(daily_data[model])
52
+
53
+ for daily_data in test_data:
54
+ for model in AIRCRAFT_MODELS:
55
+ if model in daily_data:
56
+ test_processed[model].append(daily_data[model])
57
+
58
+ return train_processed, test_processed
59
+
60
+
61
+ # 自定义数据集
62
+ class AircraftDataset(Dataset):
63
+ def __init__(self, data):
64
+ self.data = data
65
+
66
+ def __len__(self):
67
+ return len(self.data)
68
+
69
+ def __getitem__(self, idx):
70
+ return torch.tensor([self.data[idx]], dtype=torch.float32)
71
+
72
+
73
+ # LSTM 模型
74
+ class LSTMPredictor(nn.Module):
75
+ def __init__(self, input_size, hidden_size, num_layers, output_size):
76
+ super(LSTMPredictor, self).__init__()
77
+ # self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True,bidirectional=True)
78
+ self.fc = nn.Linear(input_size, output_size)
79
+
80
+ def forward(self, x):
81
+ # out, _ = self.lstm(x)
82
+ out = self.fc(x)
83
+ return out
84
+
85
+
86
+ # 训练和测试函数
87
+ def train_model(train_loader, model, criterion, optimizer, epochs=50):
88
+ model.train()
89
+ epoch = 0
90
+ while True:
91
+ epoch +=1
92
+ total_loss = 0
93
+ for batch in train_loader:
94
+ optimizer.zero_grad()
95
+ batch = batch.unsqueeze(1) # [batch, seq_len=1, features]
96
+ predictions = model(batch)
97
+ loss = criterion(predictions, batch)
98
+ loss.backward()
99
+ optimizer.step()
100
+ total_loss += loss.item()
101
+ _,_,_,_,acc = test_model(train_loader, model,8)
102
+ if epoch % 50 == 0:
103
+ print(acc)
104
+ if acc > 0.50:
105
+ break
106
+ print(f"Epoch {epoch + 1}, Loss: {total_loss:.4f}")
107
+
108
+
109
+ def test_model(test_loader, model,batchsize):
110
+ model.eval()
111
+ predictions = []
112
+ true_values = []
113
+ with torch.no_grad():
114
+ for batch in test_loader:
115
+ batch = batch.unsqueeze(1) # [batch_size, seq_len=1, features]
116
+ preds = model(batch)
117
+ predictions.append(preds.squeeze().numpy())
118
+ true_values.append(batch.squeeze().numpy())
119
+
120
+
121
+ acc = 0
122
+ # 计算误差
123
+ mae_list = []
124
+ mape_list = []
125
+ for i in range(len(true_values)):
126
+ mae = np.abs(predictions[i] - true_values[i]) # 平均绝对误差
127
+ mape = np.abs(predictions[i] - true_values[i])/true_values[i]
128
+ mae_list.append(mae)
129
+ mape_list.append(mape)
130
+ if batchsize == 1:
131
+ if mape*100 < 7:
132
+ acc+=1
133
+ else:
134
+ for i in range(len(mape)):
135
+ if mape[i]*100 < 7:
136
+ acc+=1
137
+ # print(f"Test MAE: {mae:.4f}, Test MSE: {mape:.4f}")
138
+ return true_values,predictions, mae_list, mape_list,acc/(len(true_values)*batchsize)
139
+
140
+ # 主程序
141
+ if __name__ == "__main__":
142
+ # 加载数据
143
+ data_by_day = load_and_process_data(DATA_DIR, AIRCRAFT_MODELS)
144
+
145
+ # 按机型分开训练和测试
146
+ results = {}
147
+ for model in AIRCRAFT_MODELS:
148
+ print(f"Processing model: {model}")
149
+ fw = open('G:\\loading_benchmark\\result\\pred_'+model+'_reg1', 'w')
150
+ # 准备训练和测试数据
151
+ train_processed, test_processed = prepare_data(data_by_day, TRAIN_DAYS, TEST_DAYS)
152
+ train_data = train_processed[model]
153
+ test_data = test_processed[model]
154
+
155
+ if not train_data or not test_data:
156
+ print(f"No data available for {model}")
157
+ continue
158
+
159
+ train_dataset = AircraftDataset(train_data)
160
+ test_dataset = AircraftDataset(test_data)
161
+ train_loader = DataLoader(train_dataset, batch_size=8, shuffle=True)
162
+ test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False)
163
+
164
+ # 定义模型和训练
165
+ input_size = 1 # 仅平均载货重量作为输入
166
+ hidden_size = 64
167
+ num_layers = 2
168
+ output_size = 1 # 预测平均载货重量
169
+ model_instance = LSTMPredictor(input_size, hidden_size, num_layers, output_size)
170
+
171
+ criterion = nn.MSELoss()
172
+ optimizer = torch.optim.Adam(model_instance.parameters(), lr=0.001)
173
+
174
+ # 训练模型
175
+ train_model(train_loader, model_instance, criterion, optimizer, epochs=200)
176
+
177
+ # 测试模型
178
+ true,predictions,mae,mse,acc = test_model(test_loader, model_instance,1)
179
+ for i in range(len(predictions)):
180
+ fw.write(str(true[i])+"\t"+str(predictions[i])+"\t"+str(mae[i])+"\t"+str(mse[i])+"\t"+str(acc)+"\n")
181
+ # 输出结果
182
+ # for model, preds in results.items():
183
+ # print(f"Results for {model}:")
184
+ # print(preds)
code/optimization baselines/algorithm/COM.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.optimize import linprog
3
+
4
+
5
+ def cargo_load_planning_linear1(weights, cargo_names, cargo_types_dict, positions, cg_impact, cg_impact_2u, cg_impact_4u,
6
+ max_positions):
7
+ """
8
+ 使用整数线性规划方法计算货物装载方案,最小化重心的变化量。
9
+
10
+ 参数:
11
+ weights (list): 每个货物的质量列表。
12
+ cargo_names (list): 每个货物的名称。
13
+ cargo_types_dict (dict): 货物名称和占用的货位数量。
14
+ positions (list): 可用的货位编号。
15
+ cg_impact (list): 每个位置每kg货物对重心index的影响系数。
16
+ cg_impact_2u (list): 两个位置组合的重心影响系数。
17
+ cg_impact_4u (list): 四个位置组合的重心影响系数。
18
+ max_positions (int): 总货位的数量。
19
+
20
+ 返回:
21
+ result.x: 最优装载方案矩阵。
22
+ """
23
+ # 将货物类型映射为对应的占用单位数
24
+ cargo_types = [cargo_types_dict[name] for name in cargo_names]
25
+
26
+ num_cargos = len(weights) # 货物数量
27
+ num_positions = len(positions) # 可用货位数量
28
+
29
+ # 决策变量:xij (是否将货物i放置在位置j)
30
+ c = [] # 目标函数系数列表
31
+ for i in range(num_cargos):
32
+ for j in range(num_positions):
33
+ if cargo_types[i] == 1:
34
+ c.append(abs(weights[i] * cg_impact[j]))
35
+ elif cargo_types[i] == 2 and j % 2 == 0 and j < len(cg_impact_2u) * 2:
36
+ c.append(abs(weights[i] * cg_impact_2u[j // 2]))
37
+ elif cargo_types[i] == 4 and j % 4 == 0 and j < len(cg_impact_4u) * 4:
38
+ c.append(abs(weights[i] * cg_impact_4u[j // 4]))
39
+ else:
40
+ c.append(0) # 不适合的索引默认影响为0
41
+
42
+ # 决策变量约束:xij只能是0或1 (整型约束由 linprog 近似处理)
43
+ bounds = [(0, 1) for _ in range(num_cargos * num_positions)]
44
+
45
+ # 约束1:每个货物只能装载到一个位置
46
+ A_eq = []
47
+ b_eq = []
48
+ for i in range(num_cargos):
49
+ constraint = [0] * (num_cargos * num_positions)
50
+ for j in range(num_positions):
51
+ constraint[i * num_positions + j] = 1
52
+ A_eq.append(constraint)
53
+ b_eq.append(1)
54
+
55
+ # 约束2:每个位置只能装载一个货物
56
+ A_ub = []
57
+ b_ub = []
58
+ for j in range(num_positions): # 遍历所有位置
59
+ constraint = [0] * (num_cargos * num_positions)
60
+ for i in range(num_cargos): # 遍历所有货物
61
+ constraint[i * num_positions + j] = 1
62
+ A_ub.append(constraint)
63
+ b_ub.append(1) # 每个位置最多只能分配一个货物
64
+
65
+ # 约束3:占用多个位置的货物
66
+ for i, cargo_type in enumerate(cargo_types):
67
+ if cargo_type == 2: # 两个连续位置组合
68
+ for j in range(0, num_positions - 1, 2):
69
+ constraint = [0] * (num_cargos * num_positions)
70
+ constraint[i * num_positions + j] = 1
71
+ constraint[i * num_positions + j + 1] = 1
72
+ A_ub.append(constraint)
73
+ b_ub.append(1)
74
+ elif cargo_type == 4: # 上两个、下两个组合
75
+ for j in range(0, num_positions - 3, 4):
76
+ constraint = [0] * (num_cargos * num_positions)
77
+ constraint[i * num_positions + j] = 1
78
+ constraint[i * num_positions + j + 1] = 1
79
+ constraint[i * num_positions + j + 2] = 1
80
+ constraint[i * num_positions + j + 3] = 1
81
+ A_ub.append(constraint)
82
+ b_ub.append(1)
83
+
84
+ # 转换为numpy数组
85
+ A_eq = np.array(A_eq)
86
+ b_eq = np.array(b_eq)
87
+ A_ub = np.array(A_ub)
88
+ b_ub = np.array(b_ub)
89
+ c = np.array(c)
90
+
91
+ # 求解线性规划问题
92
+ result = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=bounds, method='highs')
93
+
94
+ if result.success:
95
+ # print("成功找到最优装载方案!")
96
+ solution = result.x.reshape((num_cargos, num_positions))
97
+ # print("装载方案矩阵:")
98
+ # print(solution)
99
+
100
+ # 计算最终重心变化
101
+ cg_change = 0
102
+ for i in range(num_cargos):
103
+ for j in range(num_positions):
104
+ if cargo_types[i] == 1:
105
+ cg_change += solution[i, j] * weights[i] * cg_impact[j]
106
+ elif cargo_types[i] == 2 and j % 2 == 0 and j < len(cg_impact_2u) * 2:
107
+ cg_change += solution[i, j] * weights[i] * cg_impact_2u[j // 2]
108
+ elif cargo_types[i] == 4 and j % 4 == 0 and j < len(cg_impact_4u) * 4:
109
+ cg_change += solution[i, j] * weights[i] * cg_impact_4u[j // 4]
110
+ # print(f"重心的变化量: {cg_change:.2f}")
111
+ return result,cg_change
112
+ # 输出实际分布
113
+ # print("货物实际分布:")
114
+ # for i in range(num_cargos):
115
+ # assigned_positions = []
116
+ # for j in range(num_positions):
117
+ # if solution[i, j] > 0.5: # 判断位置是否被分配
118
+ # assigned_positions.append(j)
119
+ # print(f"货物 {cargo_names[i]} (占 {cargo_types[i]} 单位): 放置位置 -> {assigned_positions}")
120
+ else:
121
+ result = []
122
+ return result,-1000000
123
+
124
+
125
+
126
+
127
+ # 示例输入
128
+ # def main():
129
+ # weights = [500, 800, 1200, 300, 700, 1000, 600, 900] # 每个货物的质量
130
+ # cargo_names = ['LD3', 'LD3', 'PLA', 'LD3', 'P6P', 'PLA', 'LD3', 'BULK'] # 货物名称
131
+ # cargo_types_dict = {"LD3": 1, "PLA": 2, "P6P": 4, "BULK": 1} # 货物占位关系
132
+ # positions = list(range(44)) # 44个货位编号
133
+ # cg_impact = [i * 0.1 for i in range(44)] # 每kg货物对重心index的影响系数 (单个位置)
134
+ # cg_impact_2u = [i * 0.08 for i in range(22)] # 两个位置组合的影响系数
135
+ # cg_impact_4u = [i * 0.05 for i in range(11)] # 四个位置组合的影响系数
136
+ # max_positions = 44 # 总货位数量
137
+ #
138
+ # result = cargo_load_planning(weights, cargo_names, cargo_types_dict, positions, cg_impact, cg_impact_2u,
139
+ # cg_impact_4u, max_positions)
140
+ #
141
+ #
142
+ # if __name__ == "__main__":
143
+ # main()
code/optimization baselines/algorithm/DMOPSO.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pyswarms as ps
3
+
4
+
5
+ def cargo_load_planning_pso_v2(weights, cargo_names, cargo_types_dict, positions, cg_impact, cg_impact_2u, cg_impact_4u,
6
+ max_positions, options=None, swarmsize=100, maxiter=100):
7
+ """
8
+ 使用二进制粒子群优化方法计算货物装载方案,最小化重心的变化量。
9
+
10
+ 参数:
11
+ weights (list): 每个货物的质量列表。
12
+ cargo_names (list): 每个货物的名称。
13
+ cargo_types_dict (dict): 货物名称和占用的货位数量。
14
+ positions (list): 可用的货位编号。
15
+ cg_impact (list): 每个位置每kg货物对重心index的影响系数。
16
+ cg_impact_2u (list): 两个位置组合的重心影响系数。
17
+ cg_impact_4u (list): 四个位置组合的重心影响系数。
18
+ max_positions (int): 总货位的数量。
19
+ options (dict, optional): PSO算法的配置选项。
20
+ swarmsize (int, optional): 粒子群大小。
21
+ maxiter (int, optional): 最大迭代次数。
22
+
23
+ 返回:
24
+ best_solution (np.array): 最优装载方案矩阵。
25
+ best_cg_change (float): 最优方案的重心变化量。
26
+ """
27
+ # 将货物类型映射为对应的占用单位数
28
+ cargo_types = [cargo_types_dict[name] for name in cargo_names]
29
+
30
+ num_cargos = len(weights) # 货物数量
31
+ num_positions = len(positions) # 可用货位数量
32
+ dimension = num_cargos * max_positions # 每个粒子的维度:货物数量 × 可用货位数量
33
+
34
+ # 如果未提供options,使用默认配置
35
+ if options is None:
36
+ options = {'c1': 0.5, 'c2': 0.3, 'w': 0.9}
37
+
38
+ # 定义适应度评估函数
39
+ def fitness_function(x):
40
+ """
41
+ 计算每个粒子的适应度值。
42
+
43
+ 参数:
44
+ x (numpy.ndarray): 粒子的位置数组,形状为 (n_particles, dimension)。
45
+
46
+ 返回:
47
+ numpy.ndarray: 每个粒子的适应度值。
48
+ """
49
+ fitness = np.zeros(x.shape[0])
50
+
51
+ for idx, particle in enumerate(x):
52
+ # 将连续位置映射为离散起始位置
53
+ start_positions = []
54
+ penalty = 0
55
+ cg_change = 0.0
56
+ occupied = np.zeros(num_positions, dtype=int)
57
+
58
+ for i in range(num_cargos):
59
+ cargo_type = cargo_types[i]
60
+ pos_continuous = particle[i * max_positions:(i + 1) * max_positions]
61
+
62
+ # 根据粒子位置值选择最佳货位
63
+ start_pos = np.argmax(pos_continuous)
64
+
65
+ # 检查边界
66
+ if start_pos < 0 or start_pos + cargo_type > num_positions:
67
+ penalty += 1000
68
+ continue
69
+
70
+ # 检查对齐
71
+ if cargo_type == 2 and start_pos % 2 != 0:
72
+ penalty += 1000
73
+ if cargo_type == 4 and start_pos % 4 != 0:
74
+ penalty += 1000
75
+
76
+ # 检查重叠
77
+ if np.any(occupied[start_pos:start_pos + cargo_type]):
78
+ penalty += 1000
79
+ else:
80
+ occupied[start_pos:start_pos + cargo_type] = 1
81
+
82
+ start_positions.append(start_pos)
83
+
84
+ # 计算重心变化量
85
+ if cargo_type == 1:
86
+ cg_change += weights[i] * cg_impact[start_pos]
87
+ elif cargo_type == 2:
88
+ cg_change += weights[i] * cg_impact_2u[start_pos // 2]
89
+ elif cargo_type == 4:
90
+ cg_change += weights[i] * cg_impact_4u[start_pos // 4]
91
+
92
+ fitness[idx] = cg_change + penalty
93
+
94
+ return fitness
95
+
96
+ # 设置PSO的边界
97
+ # 对于每个货物,起始位置的范围根据货物类型对齐
98
+ lower_bounds = []
99
+ upper_bounds = []
100
+ for i in range(num_cargos):
101
+ cargo_type = cargo_types[i]
102
+ lower_bounds.append([0] * max_positions)
103
+ upper_bounds.append([1] * max_positions)
104
+
105
+ bounds = (np.array(lower_bounds), np.array(upper_bounds))
106
+
107
+ # 初始化PSO优化器
108
+ optimizer = ps.single.GlobalBestPSO(n_particles=swarmsize, dimensions=dimension, options=options, bounds=bounds)
109
+
110
+ # 运行PSO优化
111
+ best_cost, best_pos = optimizer.optimize(fitness_function, iters=maxiter)
112
+
113
+ # 将最佳位置映射为离散装载方案
114
+ best_start_positions = []
115
+ penalty = 0
116
+ cg_change = 0.0
117
+ occupied = np.zeros(num_positions, dtype=int)
118
+
119
+ for i in range(num_cargos):
120
+ cargo_type = cargo_types[i]
121
+ pos_continuous = best_pos[i * max_positions:(i + 1) * max_positions]
122
+
123
+ # 根据粒子位置值选择最佳货位
124
+ start_pos = np.argmax(pos_continuous)
125
+
126
+ # 检查边界
127
+ if start_pos < 0 or start_pos + cargo_type > num_positions:
128
+ penalty += 1000
129
+ best_start_positions.append(start_pos)
130
+ continue
131
+
132
+ # 检查对齐
133
+ if cargo_type == 2 and start_pos % 2 != 0:
134
+ penalty += 1000
135
+ if cargo_type == 4 and start_pos % 4 != 0:
136
+ penalty += 1000
137
+
138
+ # 检查重叠
139
+ if np.any(occupied[start_pos:start_pos + cargo_type]):
140
+ penalty += 1000
141
+ else:
142
+ occupied[start_pos:start_pos + cargo_type] = 1
143
+
144
+ best_start_positions.append(start_pos)
145
+
146
+ # 计算重心变化量
147
+ if cargo_type == 1:
148
+ cg_change += abs(weights[i] * cg_impact[start_pos])
149
+ elif cargo_type == 2:
150
+ cg_change += abs(weights[i] * cg_impact_2u[start_pos // 2])
151
+ elif cargo_type == 4:
152
+ cg_change += abs(weights[i] * cg_impact_4u[start_pos // 4])
153
+
154
+ total_cg_change = cg_change + penalty
155
+
156
+ # 构建装载方案矩阵
157
+ best_xij = np.zeros((num_cargos, num_positions), dtype=int)
158
+ for i, start_pos in enumerate(best_start_positions):
159
+ cargo_type = cargo_types[i]
160
+ for k in range(cargo_type):
161
+ pos = start_pos + k
162
+ if pos < num_positions:
163
+ best_xij[i, pos] = 1
164
+
165
+ # 检查是否有严重惩罚,判断是否找到可行解
166
+ if total_cg_change >= -999999:
167
+ return best_xij, total_cg_change
168
+ else:
169
+ return [], -1000000
170
+
171
+
172
+ # 示例调用
173
+
code/optimization baselines/algorithm/GA-normal.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import random
3
+ from deap import base, creator, tools, algorithms
4
+
5
+
6
+ def cargo_load_planning_genetic(weights, cargo_names, cargo_types_dict, positions, cg_impact, cg_impact_2u, cg_impact_4u,
7
+ max_positions, population_size=100, generations=100, crossover_prob=0.7, mutation_prob=0.2):
8
+ """
9
+ 使用遗传算法计算货物装载方案,最小化重心的变化量。
10
+
11
+ 参数:
12
+ weights (list): 每个货物的质量列表。
13
+ cargo_names (list): 每个货物的名称。
14
+ cargo_types_dict (dict): 货物名称和占用的货位数量。
15
+ positions (list): 可用的货位编号。
16
+ cg_impact (list): 每个位置每kg货物对重心index的影响系数。
17
+ cg_impact_2u (list): 两个位置组合的重心影响系数。
18
+ cg_impact_4u (list): 四个位置组合的重心影响系数。
19
+ max_positions (int): 总货位的数量。
20
+ population_size (int): 遗传算法的种群大小。
21
+ generations (int): 遗传算法的代数。
22
+ crossover_prob (float): 交叉操作的概率。
23
+ mutation_prob (float): 变异操作的概率。
24
+
25
+ 返回:
26
+ best_solution (np.array): 最优装载方案矩阵。
27
+ best_cg_change (float): 最优方案的重心变化量。
28
+ """
29
+ try:
30
+ # 将货物类型映射为对应的占用单位数
31
+ cargo_types = [cargo_types_dict[name] for name in cargo_names]
32
+
33
+ num_cargos = len(weights) # 货物数量
34
+ num_positions = len(positions) # 可用货位数量
35
+
36
+ # 定义适应度函数(最小化重心变化量)
37
+ if not hasattr(creator, "FitnessMin"):
38
+ creator.create("FitnessMin", base.Fitness, weights=(-1.0,))
39
+ if not hasattr(creator, "Individual"):
40
+ creator.create("Individual", list, fitness=creator.FitnessMin)
41
+
42
+ toolbox = base.Toolbox()
43
+
44
+ # 个体初始化函数,确保货物类型为2和4时起始位置对齐
45
+ def init_individual():
46
+ individual = []
47
+ occupied = [False] * num_positions
48
+ for cargo_type in cargo_types:
49
+ if cargo_type == 1:
50
+ valid_positions = [j for j in range(num_positions) if not occupied[j]]
51
+ elif cargo_type == 2:
52
+ valid_positions = [j for j in range(0, num_positions - 1, 2) if not any(occupied[j + k] for k in range(cargo_type))]
53
+ elif cargo_type == 4:
54
+ valid_positions = [j for j in range(0, num_positions - 3, 4) if not any(occupied[j + k] for k in range(cargo_type))]
55
+ else:
56
+ valid_positions = []
57
+
58
+ if not valid_positions:
59
+ # 如果没有有效位置,随机选择一个符合类型对齐的起始位置
60
+ if cargo_type == 1:
61
+ start_pos = random.randint(0, num_positions - 1)
62
+ elif cargo_type == 2:
63
+ choices = [j for j in range(0, num_positions - 1, 2)]
64
+ if choices:
65
+ start_pos = random.choice(choices)
66
+ else:
67
+ start_pos = 0 # 默认位置
68
+ elif cargo_type == 4:
69
+ choices = [j for j in range(0, num_positions - 3, 4)]
70
+ if choices:
71
+ start_pos = random.choice(choices)
72
+ else:
73
+ start_pos = 0 # 默认位置
74
+ else:
75
+ start_pos = 0 # 默认位置
76
+ else:
77
+ start_pos = random.choice(valid_positions)
78
+
79
+ individual.append(start_pos)
80
+
81
+ # 标记占用的位置
82
+ for k in range(cargo_type):
83
+ pos = start_pos + k
84
+ if pos < num_positions:
85
+ occupied[pos] = True
86
+
87
+ return creator.Individual(individual)
88
+
89
+ toolbox.register("individual", init_individual)
90
+ toolbox.register("population", tools.initRepeat, list, toolbox.individual)
91
+
92
+ # 适应度评估函数
93
+ def evaluate(individual):
94
+ # 检查重叠和边界
95
+ occupied = [False] * num_positions
96
+ penalty = 0
97
+ cg_change = 0.0
98
+
99
+ for i, start_pos in enumerate(individual):
100
+ cargo_type = cargo_types[i]
101
+ weight = weights[i]
102
+
103
+ # 检查边界
104
+ if start_pos < 0 or start_pos + cargo_type > num_positions:
105
+ penalty += 10000 # 超出边界的严重惩罚
106
+ continue
107
+
108
+ # 检查重叠
109
+ overlap = False
110
+ for k in range(cargo_type):
111
+ pos = start_pos + k
112
+ if occupied[pos]:
113
+ penalty += 10000 # 重叠的严重惩罚
114
+ overlap = True
115
+ break
116
+ occupied[pos] = True
117
+ if overlap:
118
+ continue
119
+
120
+ # 计算重心变化量
121
+ if cargo_type == 1:
122
+ cg_change += abs(weight * cg_impact[start_pos])
123
+ elif cargo_type == 2:
124
+ if start_pos % 2 == 0 and (start_pos // 2) < len(cg_impact_2u):
125
+ cg_change += abs(weight * cg_impact_2u[start_pos // 2])
126
+ else:
127
+ penalty += 10000 # 不对齐的严重惩罚
128
+ elif cargo_type == 4:
129
+ if start_pos % 4 == 0 and (start_pos // 4) < len(cg_impact_4u):
130
+ cg_change += abs(weight * cg_impact_4u[start_pos // 4])
131
+ else:
132
+ penalty += 10000 # 不对齐的严重惩罚
133
+
134
+ return (cg_change + penalty,)
135
+
136
+ toolbox.register("evaluate", evaluate)
137
+ toolbox.register("mate", tools.cxTwoPoint)
138
+
139
+ # 自定义变异函数,确保变异后的起始位置对齐
140
+ def custom_mutate(individual, indpb):
141
+ for i in range(len(individual)):
142
+ if random.random() < indpb:
143
+ cargo_type = cargo_types[i]
144
+ try:
145
+ if cargo_type == 1:
146
+ new_pos = random.randint(0, num_positions - 1)
147
+ elif cargo_type == 2:
148
+ choices = [j for j in range(0, num_positions - 1, 2)]
149
+ if choices:
150
+ new_pos = random.choice(choices)
151
+ else:
152
+ new_pos = individual[i] # 如果没有可选位置,保持不变
153
+ elif cargo_type == 4:
154
+ choices = [j for j in range(0, num_positions - 3, 4)]
155
+ if choices:
156
+ new_pos = random.choice(choices)
157
+ else:
158
+ new_pos = individual[i] # 如果没有可选位置,保持不变
159
+ else:
160
+ new_pos = individual[i] # 保持不变
161
+ individual[i] = new_pos
162
+ except ValueError:
163
+ # 捕获可能的 ValueError 并直接返回当前个体
164
+ return individual,
165
+ return (individual,)
166
+
167
+ toolbox.register("mutate", custom_mutate, indpb=mutation_prob)
168
+ toolbox.register("select", tools.selTournament, tournsize=3)
169
+
170
+ # 初始化种群
171
+ population = toolbox.population(n=population_size)
172
+
173
+ # 运行遗传算法
174
+ try:
175
+ algorithms.eaSimple(population, toolbox, cxpb=crossover_prob, mutpb=1.0, ngen=generations,
176
+ verbose=False)
177
+ except ValueError as e:
178
+ print(f"遗传算法运行时出错: {e}")
179
+ return [], -1000000 # 返回空列表和一个负的重心变化量作为错误标志
180
+
181
+ # 选择最优个体
182
+ try:
183
+ best_individual = tools.selBest(population, 1)[0]
184
+ best_cg_change = evaluate(best_individual)[0]
185
+ except IndexError as e:
186
+ print(f"选择最优个体时出错: {e}")
187
+ return [], -1000000 # 返回空列表和一个负的重心变化量作为错误标志
188
+
189
+ # 构建装载方案矩阵
190
+ solution = np.zeros((num_cargos, num_positions))
191
+ for i, start_pos in enumerate(best_individual):
192
+ cargo_type = cargo_types[i]
193
+ for k in range(cargo_type):
194
+ pos = start_pos + k
195
+ if pos < num_positions:
196
+ solution[i, pos] = 1
197
+
198
+ return solution, best_cg_change
199
+ except:
200
+ return [],-1000000
201
+
202
+
203
+ # # 示例输入和调用
204
+ # def main():
205
+ # weights = [500, 800, 1200, 300, 700, 1000, 600, 900] # 每个货物的质量
206
+ # cargo_names = ['LD3', 'LD3', 'PLA', 'LD3', 'P6P', 'PLA', 'LD3', 'BULK'] # 货物名称
207
+ # cargo_types_dict = {"LD3": 1, "PLA": 2, "P6P": 4, "BULK": 1} # 货物占位关系
208
+ # positions = list(range(44)) # 44个货位编号
209
+ # cg_impact = [i * 0.1 for i in range(44)] # 每kg货物对重心index的影响系数 (单个位置)
210
+ # cg_impact_2u = [i * 0.08 for i in range(22)] # 两个位置组合的影响系数
211
+ # cg_impact_4u = [i * 0.05 for i in range(11)] # 四个位置组合的影响系数
212
+ # max_positions = 44 # 总货位数量
213
+ #
214
+ # solution, cg_change = cargo_load_planning_genetic(
215
+ # weights, cargo_names, cargo_types_dict, positions,
216
+ # cg_impact, cg_impact_2u, cg_impact_4u, max_positions,
217
+ # population_size=200, generations=200, crossover_prob=0.8, mutation_prob=0.2
218
+ # )
219
+ #
220
+ # if solution is not None and len(solution) > 0:
221
+ # print("成功找到最优装载方案!")
222
+ # print("装载方案矩阵:")
223
+ # print(solution)
224
+ # print(f"重心的变化量: {cg_change:.2f}")
225
+
226
+ # 输出实际分布
227
+ # for i in range(len(weights)):
228
+ # assigned_positions = []
229
+ # for j in range(len(positions)):
230
+ # if solution[i, j] > 0.5: # 判断位置是否被分配
231
+ # assigned_positions.append(j)
232
+ # print(f"货物 {cargo_names[i]} (占 {cargo_types_dict[cargo_names[i]]} 单位): 放置位置 -> {assigned_positions}")
233
+ # else:
234
+ # print("未找到可行的装载方案。")
235
+ #
236
+ #
237
+ # if __name__ == "__main__":
238
+ # main()
code/optimization baselines/algorithm/HGA.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import random
3
+ from deap import base, creator, tools, algorithms
4
+
5
+
6
+ def cargo_load_planning_genetic(weights, cargo_names, cargo_types_dict, positions, cg_impact, cg_impact_2u, cg_impact_4u,
7
+ max_positions, population_size=100, generations=100, crossover_prob=0.7, mutation_prob=0.2):
8
+ """
9
+ 使用改进版遗传算法计算货物装载方案,最小化重心的变化量。
10
+
11
+ 参数:
12
+ weights (list): 每个货物的质量列表。
13
+ cargo_names (list): 每个货物的名称。
14
+ cargo_types_dict (dict): 货物名称和占用的货位数量。
15
+ positions (list): 可用的货位编号。
16
+ cg_impact (list): 每个位置每kg货物对重心index的影响系数。
17
+ cg_impact_2u (list): 两个位置组合的重心影响系数。
18
+ cg_impact_4u (list): 四个位置组合的重心影响系数。
19
+ max_positions (int): 总货位的数量。
20
+ population_size (int): 遗传算法的种群大小。
21
+ generations (int): 遗传算法的代数。
22
+ crossover_prob (float): 交叉操作的概率。
23
+ mutation_prob (float): 变异操作的概率。
24
+
25
+ 返回:
26
+ best_solution (np.array): 最优装载方案矩阵。
27
+ best_cg_change (float): 最优方案的重心变化量。
28
+ """
29
+ try:
30
+ # 将货物类型映射为对应的占用单位数
31
+ cargo_types = [cargo_types_dict[name] for name in cargo_names]
32
+
33
+ num_cargos = len(weights) # 货物数量
34
+ num_positions = len(positions) # 可用货位数量
35
+
36
+ # 定义适应度函数(最小化重心变化量)
37
+ if not hasattr(creator, "FitnessMin"):
38
+ creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) # 目标是最小化
39
+ if not hasattr(creator, "Individual"):
40
+ creator.create("Individual", list, fitness=creator.FitnessMin)
41
+
42
+ toolbox = base.Toolbox()
43
+
44
+ # 个体初始化函数
45
+ def init_individual():
46
+ individual = []
47
+ occupied = [False] * num_positions
48
+ for cargo_type in cargo_types:
49
+ if cargo_type == 1:
50
+ valid_positions = [j for j in range(num_positions) if not occupied[j]]
51
+ elif cargo_type == 2:
52
+ valid_positions = [j for j in range(0, num_positions - 1, 2) if not any(occupied[j + k] for k in range(cargo_type))]
53
+ elif cargo_type == 4:
54
+ valid_positions = [j for j in range(0, num_positions - 3, 4) if not any(occupied[j + k] for k in range(cargo_type))]
55
+ else:
56
+ valid_positions = []
57
+
58
+ if not valid_positions:
59
+ # 如果没有有效位置,随机选择一个符合类型对齐的起始位置
60
+ if cargo_type == 1:
61
+ start_pos = random.randint(0, num_positions - 1)
62
+ elif cargo_type == 2:
63
+ choices = [j for j in range(0, num_positions - 1, 2)]
64
+ if choices:
65
+ start_pos = random.choice(choices)
66
+ else:
67
+ start_pos = 0 # 默认位置
68
+ elif cargo_type == 4:
69
+ choices = [j for j in range(0, num_positions - 3, 4)]
70
+ if choices:
71
+ start_pos = random.choice(choices)
72
+ else:
73
+ start_pos = 0 # 默认位置
74
+ else:
75
+ start_pos = 0 # 默认位置
76
+ else:
77
+ start_pos = random.choice(valid_positions)
78
+
79
+ individual.append(start_pos)
80
+
81
+ # 标记占用的位置
82
+ for k in range(cargo_type):
83
+ pos = start_pos + k
84
+ if pos < num_positions:
85
+ occupied[pos] = True
86
+
87
+ return creator.Individual(individual)
88
+
89
+ toolbox.register("individual", init_individual)
90
+ toolbox.register("population", tools.initRepeat, list, toolbox.individual)
91
+
92
+ # 适应度评估函数
93
+ def evaluate(individual):
94
+ # 检查重叠和边界
95
+ occupied = [False] * num_positions
96
+ penalty = 0
97
+ cg_change = 0.0
98
+
99
+ for i, start_pos in enumerate(individual):
100
+ cargo_type = cargo_types[i]
101
+ weight = weights[i]
102
+
103
+ # 检查边界
104
+ if start_pos < 0 or start_pos + cargo_type > num_positions:
105
+ penalty += 10000 # 超出边界的严重惩罚
106
+ continue
107
+
108
+ # 检查重叠
109
+ overlap = False
110
+ for k in range(cargo_type):
111
+ pos = start_pos + k
112
+ if occupied[pos]:
113
+ penalty += 10000 # 重叠的严重惩罚
114
+ overlap = True
115
+ break
116
+ occupied[pos] = True
117
+ if overlap:
118
+ continue
119
+
120
+ # 计算重心变化量
121
+ if cargo_type == 1:
122
+ cg_change += abs(weight * cg_impact[start_pos])
123
+ elif cargo_type == 2:
124
+ if start_pos % 2 == 0 and (start_pos // 2) < len(cg_impact_2u):
125
+ cg_change += abs(weight * cg_impact_2u[start_pos // 2])
126
+ else:
127
+ penalty += 10000 # 不对齐的严重惩罚
128
+ elif cargo_type == 4:
129
+ if start_pos % 4 == 0 and (start_pos // 4) < len(cg_impact_4u):
130
+ cg_change += abs(weight * cg_impact_4u[start_pos // 4])
131
+ else:
132
+ penalty += 10000 # 不对齐的严重惩罚
133
+
134
+ return (cg_change + penalty,)
135
+
136
+ toolbox.register("evaluate", evaluate)
137
+ toolbox.register("mate", tools.cxOnePoint) # 改为单点交叉
138
+ toolbox.register("mutate", tools.mutShuffleIndexes, indpb=mutation_prob) # 使用交换变异
139
+ toolbox.register("select", tools.selRoulette) # 轮盘赌选择
140
+
141
+ # 初始化种群
142
+ population = toolbox.population(n=population_size)
143
+
144
+ # 运行遗传算法
145
+ try:
146
+ algorithms.eaSimple(population, toolbox, cxpb=crossover_prob, mutpb=1.0, ngen=generations,
147
+ verbose=False)
148
+ except ValueError as e:
149
+ print(f"遗传算法运行时出错: {e}")
150
+ return [], -1000000 # 返回空列表和一个负的重心变化量作为错误标志
151
+
152
+ # 选择最优个体
153
+ try:
154
+ best_individual = tools.selBest(population, 1)[0]
155
+ best_cg_change = evaluate(best_individual)[0]
156
+ except IndexError as e:
157
+ print(f"选择最优个体时出错: {e}")
158
+ return [], -1000000 # 返回空列表和一个负的重心变化量作为错误标志
159
+
160
+ # 构建装载方案矩阵
161
+ solution = np.zeros((num_cargos, num_positions))
162
+ for i, start_pos in enumerate(best_individual):
163
+ cargo_type = cargo_types[i]
164
+ for k in range(cargo_type):
165
+ pos = start_pos + k
166
+ if pos < num_positions:
167
+ solution[i, pos] = 1
168
+
169
+ return solution, best_cg_change
170
+ except Exception as e:
171
+ print(f"发生错误: {e}")
172
+ return [], -1000000
173
+
174
+ #
175
+ # # 示例输入和调用
176
+ # def main():
177
+ # weights = [500, 800, 1200, 300, 700, 1000, 600, 900] # 每个货物的质量
178
+ # cargo_names = ['LD3', 'LD3
code/optimization baselines/algorithm/IOM.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.optimize import linprog
3
+
4
+
5
+ def cargo_load_planning_linear2(weights, cargo_names, cargo_types_dict, positions, cg_impact, cg_impact_2u, cg_impact_4u,
6
+ max_positions):
7
+ """
8
+ 使用整数线性规划方法计算货物装载方案,最小化重心的变化量。
9
+
10
+ 参数:
11
+ weights (list): 每个货物的质量列表。
12
+ cargo_names (list): 每个货物的名称。
13
+ cargo_types_dict (dict): 货物名称和占用的货位数量。
14
+ positions (list): 可用的货位编号。
15
+ cg_impact (list): 每个位置每kg货物对重心index的影响系数。
16
+ cg_impact_2u (list): 两个位置组合的重心影响系数。
17
+ cg_impact_4u (list): 四个位置组合的重心影响系数。
18
+ max_positions (int): 总货位的数量。
19
+
20
+ 返回:
21
+ result.x: 最优装载方案矩阵。
22
+ """
23
+ # 将货物类型映射为对应的占用单位数
24
+ cargo_types = [cargo_types_dict[name] for name in cargo_names]
25
+
26
+ num_cargos = len(weights) # 货物数量
27
+ num_positions = len(positions) # 可用货位数量
28
+
29
+ # 决策变量:xij (是否将货物i放置在位置j)
30
+ c = [] # 目标函数系数列表
31
+ for i in range(num_cargos):
32
+ for j in range(num_positions):
33
+ if cargo_types[i] == 1:
34
+ c.append(abs(weights[i] * cg_impact[j]))
35
+ elif cargo_types[i] == 2 and j % 2 == 0 and j < len(cg_impact_2u) * 2:
36
+ c.append(abs(weights[i] * cg_impact_2u[j // 2]))
37
+ elif cargo_types[i] == 4 and j % 4 == 0 and j < len(cg_impact_4u) * 4:
38
+ c.append(abs(weights[i] * cg_impact_4u[j // 4]))
39
+ else:
40
+ c.append(0) # 不适合的索引默认影响为0
41
+
42
+ # 决策变量约束:xij只能是0或1 (整型约束由 linprog 近似处理)
43
+ bounds = [(0, 1) for _ in range(num_cargos * num_positions)]
44
+
45
+ # 约束1:每个货物只能装载到一个位置
46
+ A_eq = []
47
+ b_eq = []
48
+ for i in range(num_cargos):
49
+ constraint = [0] * (num_cargos * num_positions)
50
+ for j in range(num_positions):
51
+ constraint[i * num_positions + j] = 1
52
+ A_eq.append(constraint)
53
+ b_eq.append(1)
54
+
55
+ # 约束2:每个位置只能装载一个货物
56
+ A_ub = []
57
+ b_ub = []
58
+ for j in range(num_positions): # 遍历所有位置
59
+ constraint = [0] * (num_cargos * num_positions)
60
+ for i in range(num_cargos): # 遍历所有货物
61
+ constraint[i * num_positions + j] = 1
62
+ A_ub.append(constraint)
63
+ b_ub.append(1) # 每个位置最多只能分配一个货物
64
+
65
+ # 约束3:占用多个位置的货物
66
+ for i, cargo_type in enumerate(cargo_types):
67
+ if cargo_type == 2: # 两个连续位置组合
68
+ for j in range(0, num_positions - 1, 2):
69
+ constraint = [0] * (num_cargos * num_positions)
70
+ constraint[i * num_positions + j] = 1
71
+ constraint[i * num_positions + j + 1] = 1
72
+ A_ub.append(constraint)
73
+ b_ub.append(1)
74
+ elif cargo_type == 4: # 上两个、下两个组合
75
+ for j in range(0, num_positions - 3, 4):
76
+ constraint = [0] * (num_cargos * num_positions)
77
+ constraint[i * num_positions + j] = 1
78
+ constraint[i * num_positions + j + 1] = 1
79
+ constraint[i * num_positions + j + 2] = 1
80
+ constraint[i * num_positions + j + 3] = 1
81
+ A_ub.append(constraint)
82
+ b_ub.append(1)
83
+
84
+ # 转换为numpy数组
85
+ A_eq = np.array(A_eq)
86
+ b_eq = np.array(b_eq)
87
+ A_ub = np.array(A_ub)
88
+ b_ub = np.array(b_ub)
89
+ c = np.array(c)
90
+
91
+ # 求解线性规划问题
92
+ result = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=bounds, method='highs-ds')
93
+
94
+ if result.success:
95
+ # print("成功找到最优装载方案!")
96
+ solution = result.x.reshape((num_cargos, num_positions))
97
+ # print("装载方案矩阵:")
98
+ # print(solution)
99
+
100
+ # 计算最终重心变化
101
+ cg_change = 0
102
+ for i in range(num_cargos):
103
+ for j in range(num_positions):
104
+ if cargo_types[i] == 1:
105
+ cg_change += solution[i, j] * weights[i] * cg_impact[j]
106
+ elif cargo_types[i] == 2 and j % 2 == 0 and j < len(cg_impact_2u) * 2:
107
+ cg_change += solution[i, j] * weights[i] * cg_impact_2u[j // 2]
108
+ elif cargo_types[i] == 4 and j % 4 == 0 and j < len(cg_impact_4u) * 4:
109
+ cg_change += solution[i, j] * weights[i] * cg_impact_4u[j // 4]
110
+ # print(f"重心的变化量: {cg_change:.2f}")
111
+ return result,cg_change
112
+ # 输出实际分布
113
+ # print("货物实际分布:")
114
+ # for i in range(num_cargos):
115
+ # assigned_positions = []
116
+ # for j in range(num_positions):
117
+ # if solution[i, j] > 0.5: # 判断位置是否被分配
118
+ # assigned_positions.append(j)
119
+ # print(f"货物 {cargo_names[i]} (占 {cargo_types[i]} 单位): 放置位置 -> {assigned_positions}")
120
+ else:
121
+ result = []
122
+ return result,-1000000
123
+
124
+
125
+
126
+
127
+ # 示例输入
128
+ # def main():
129
+ # weights = [500, 800, 1200, 300, 700, 1000, 600, 900] # 每个货物的质量
130
+ # cargo_names = ['LD3', 'LD3', 'PLA', 'LD3', 'P6P', 'PLA', 'LD3', 'BULK'] # 货物名称
131
+ # cargo_types_dict = {"LD3": 1, "PLA": 2, "P6P": 4, "BULK": 1} # 货物占位关系
132
+ # positions = list(range(44)) # 44个货位编号
133
+ # cg_impact = [i * 0.1 for i in range(44)] # 每kg货物对重心index的影响系数 (单个位置)
134
+ # cg_impact_2u = [i * 0.08 for i in range(22)] # 两个位置组合的影响系数
135
+ # cg_impact_4u = [i * 0.05 for i in range(11)] # 四个位置组合的影响系数
136
+ # max_positions = 44 # 总货位数量
137
+ #
138
+ # result = cargo_load_planning(weights, cargo_names, cargo_types_dict, positions, cg_impact, cg_impact_2u,
139
+ # cg_impact_4u, max_positions)
140
+ #
141
+ #
142
+ # if __name__ == "__main__":
143
+ # main()
code/optimization baselines/algorithm/MLIP-ACLPDD.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.optimize import linprog
3
+
4
+
5
+ def cargo_load_planning_linear3(weights, cargo_names, cargo_types_dict, positions, cg_impact, cg_impact_2u, cg_impact_4u,
6
+ max_positions):
7
+ """
8
+ 使用整数线性规划方法计算货物装载方案,最小化重心的变化量。
9
+
10
+ 参数:
11
+ weights (list): 每个货物的质量列表。
12
+ cargo_names (list): 每个货物的名称。
13
+ cargo_types_dict (dict): 货物名称和占用的货位数量。
14
+ positions (list): 可用的货位编号。
15
+ cg_impact (list): 每个位置每kg货物对重心index的影响系数。
16
+ cg_impact_2u (list): 两个位置组合的重心影响系数。
17
+ cg_impact_4u (list): 四个位置组合的重心影响系数。
18
+ max_positions (int): 总货位的数量。
19
+
20
+ 返回:
21
+ result.x: 最优装载方案矩阵。
22
+ """
23
+ # 将货物类型映射为对应的占用单位数
24
+ cargo_types = [cargo_types_dict[name] for name in cargo_names]
25
+
26
+ num_cargos = len(weights) # 货物数量
27
+ num_positions = len(positions) # 可用货位数量
28
+
29
+ # 决策变量:xij (是否将货物i放置在位置j)
30
+ c = [] # 目标函数系数列表
31
+ for i in range(num_cargos):
32
+ for j in range(num_positions):
33
+ if cargo_types[i] == 1:
34
+ c.append(abs(weights[i] * cg_impact[j]))
35
+ elif cargo_types[i] == 2 and j % 2 == 0 and j < len(cg_impact_2u) * 2:
36
+ c.append(abs(weights[i] * cg_impact_2u[j // 2]))
37
+ elif cargo_types[i] == 4 and j % 4 == 0 and j < len(cg_impact_4u) * 4:
38
+ c.append(abs(weights[i] * cg_impact_4u[j // 4]))
39
+ else:
40
+ c.append(0) # 不适合的索引默认影响为0
41
+
42
+ # 决策变量约束:xij只能是0或1 (整型约束由 linprog 近似处理)
43
+ bounds = [(0, 1) for _ in range(num_cargos * num_positions)]
44
+
45
+ # 约束1:每个货物只能装载到一个位置
46
+ A_eq = []
47
+ b_eq = []
48
+ for i in range(num_cargos):
49
+ constraint = [0] * (num_cargos * num_positions)
50
+ for j in range(num_positions):
51
+ constraint[i * num_positions + j] = 1
52
+ A_eq.append(constraint)
53
+ b_eq.append(1)
54
+
55
+ # 约束2:每个位置只能装载一个货物
56
+ A_ub = []
57
+ b_ub = []
58
+ for j in range(num_positions): # 遍历所有位置
59
+ constraint = [0] * (num_cargos * num_positions)
60
+ for i in range(num_cargos): # 遍历所有货物
61
+ constraint[i * num_positions + j] = 1
62
+ A_ub.append(constraint)
63
+ b_ub.append(1) # 每个位置最多只能分配一个货物
64
+
65
+ # 约束3:占用多个位置的货物
66
+ for i, cargo_type in enumerate(cargo_types):
67
+ if cargo_type == 2: # 两个连续位置组合
68
+ for j in range(0, num_positions - 1, 2):
69
+ constraint = [0] * (num_cargos * num_positions)
70
+ constraint[i * num_positions + j] = 1
71
+ constraint[i * num_positions + j + 1] = 1
72
+ A_ub.append(constraint)
73
+ b_ub.append(1)
74
+ elif cargo_type == 4: # 上两个、下两个组合
75
+ for j in range(0, num_positions - 3, 4):
76
+ constraint = [0] * (num_cargos * num_positions)
77
+ constraint[i * num_positions + j] = 1
78
+ constraint[i * num_positions + j + 1] = 1
79
+ constraint[i * num_positions + j + 2] = 1
80
+ constraint[i * num_positions + j + 3] = 1
81
+ A_ub.append(constraint)
82
+ b_ub.append(1)
83
+
84
+ # 转换为numpy数组
85
+ A_eq = np.array(A_eq)
86
+ b_eq = np.array(b_eq)
87
+ A_ub = np.array(A_ub)
88
+ b_ub = np.array(b_ub)
89
+ c = np.array(c)
90
+
91
+ # 求解线性规划问题
92
+ result = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=bounds, method='highs-ipm')
93
+
94
+ if result.success:
95
+ # print("成功找到最优装载方案!")
96
+ solution = result.x.reshape((num_cargos, num_positions))
97
+ # print("装载方案矩阵:")
98
+ # print(solution)
99
+
100
+ # 计算最终重心变化
101
+ cg_change = 0
102
+ for i in range(num_cargos):
103
+ for j in range(num_positions):
104
+ if cargo_types[i] == 1:
105
+ cg_change += solution[i, j] * weights[i] * cg_impact[j]
106
+ elif cargo_types[i] == 2 and j % 2 == 0 and j < len(cg_impact_2u) * 2:
107
+ cg_change += solution[i, j] * weights[i] * cg_impact_2u[j // 2]
108
+ elif cargo_types[i] == 4 and j % 4 == 0 and j < len(cg_impact_4u) * 4:
109
+ cg_change += solution[i, j] * weights[i] * cg_impact_4u[j // 4]
110
+ # print(f"重心的变化量: {cg_change:.2f}")
111
+ return result,cg_change
112
+ # 输出实际分布
113
+ # print("货物实际分布:")
114
+ # for i in range(num_cargos):
115
+ # assigned_positions = []
116
+ # for j in range(num_positions):
117
+ # if solution[i, j] > 0.5: # 判断位置是否被分配
118
+ # assigned_positions.append(j)
119
+ # print(f"货物 {cargo_names[i]} (占 {cargo_types[i]} 单位): 放置位置 -> {assigned_positions}")
120
+ else:
121
+ result = []
122
+ return result,-1000000
123
+
124
+
125
+
126
+
127
+ # 示例输入
128
+ # def main():
129
+ # weights = [500, 800, 1200, 300, 700, 1000, 600, 900] # 每个货物的质量
130
+ # cargo_names = ['LD3', 'LD3', 'PLA', 'LD3', 'P6P', 'PLA', 'LD3', 'BULK'] # 货物名称
131
+ # cargo_types_dict = {"LD3": 1, "PLA": 2, "P6P": 4, "BULK": 1} # 货物占位关系
132
+ # positions = list(range(44)) # 44个货位编号
133
+ # cg_impact = [i * 0.1 for i in range(44)] # 每kg货物对重心index的影响系数 (单个位置)
134
+ # cg_impact_2u = [i * 0.08 for i in range(22)] # 两个位置组合的影响系数
135
+ # cg_impact_4u = [i * 0.05 for i in range(11)] # 四个位置组合的影响系数
136
+ # max_positions = 44 # 总货位数量
137
+ #
138
+ # result = cargo_load_planning(weights, cargo_names, cargo_types_dict, positions, cg_impact, cg_impact_2u,
139
+ # cg_impact_4u, max_positions)
140
+ #
141
+ #
142
+ # if __name__ == "__main__":
143
+ # main()
code/optimization baselines/algorithm/MLIP-WBP.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pulp
3
+
4
+ def cargo_load_planning_mip1(weights, cargo_names, cargo_types_dict, positions, cg_impact, cg_impact_2u, cg_impact_4u,
5
+ max_positions):
6
+ """
7
+ 使用混合整数规划方法计算货物装载方案,最小化重心的变化量。
8
+
9
+ 参数:
10
+ weights (list): 每个货物的质量列表。
11
+ cargo_names (list): 每个货物的名称。
12
+ cargo_types_dict (dict): 货物名称和占用的货位数量。
13
+ positions (list): 可用的货位编号。
14
+ cg_impact (list): 每个位置每kg货物对重心index的影响系数。
15
+ cg_impact_2u (list): 两个位置组合的重心影响系数。
16
+ cg_impact_4u (list): 四个位置组合的重心影响系数。
17
+ max_positions (int): 总货位的数量。
18
+
19
+ 返回:
20
+ result (pulp.LpStatus): 求解状态。
21
+ cg_change (float): 最优解的重心变化量。
22
+ solution_matrix (np.ndarray): 最优装载方案矩阵。
23
+ """
24
+ # 将货物类型映射为对应的占用单位数
25
+ cargo_types = [cargo_types_dict[name] for name in cargo_names]
26
+
27
+ num_cargos = len(weights) # 货物数量
28
+ num_positions = len(positions) # 可用货位数量
29
+
30
+ # 创建优化问题实例
31
+ prob = pulp.LpProblem("Cargo_Load_Planning", pulp.LpMinimize)
32
+
33
+ # 创建决策变量 x_ij (是否将货物i放置在位置j)
34
+ # 使用字典键 (i,j) 来标识变量
35
+ x = pulp.LpVariable.dicts("x",
36
+ ((i, j) for i in range(num_cargos) for j in range(num_positions)),
37
+ cat='Binary')
38
+
39
+ # 定义目标函数:最小化重心的变化量
40
+ objective_terms = []
41
+ for i in range(num_cargos):
42
+ for j in range(num_positions):
43
+ if cargo_types[i] == 1:
44
+ impact = abs(weights[i] * cg_impact[j])
45
+ elif cargo_types[i] == 2 and j % 2 == 0 and j < len(cg_impact_2u) * 2:
46
+ impact = abs(weights[i] * cg_impact_2u[j // 2])
47
+ elif cargo_types[i] == 4 and j % 4 == 0 and j < len(cg_impact_4u) * 4:
48
+ impact = abs(weights[i] * cg_impact_4u[j // 4])
49
+ else:
50
+ impact = 0
51
+ objective_terms.append(impact * x[i, j])
52
+
53
+ prob += pulp.lpSum(objective_terms), "Total_CG_Change"
54
+
55
+ # 约束1:每个货物只能装载到一个位置
56
+ for i in range(num_cargos):
57
+ prob += pulp.lpSum([x[i, j] for j in range(num_positions)]) == 1, f"Cargo_{i}_Single_Position"
58
+
59
+ # 约束2:每个位置只能装载一个货物
60
+ for j in range(num_positions):
61
+ prob += pulp.lpSum([x[i, j] for i in range(num_cargos)]) <= 1, f"Position_{j}_Single_Cargo"
62
+
63
+ # 约束3:占用多个位置的货物
64
+ for i, cargo_type in enumerate(cargo_types):
65
+ if cargo_type == 2: # 两个连续位置组合
66
+ for j in range(0, num_positions - 1, 2):
67
+ prob += x[i, j] + x[i, j + 1] <= 1, f"Cargo_{i}_Type2_Position_{j}_{j+1}"
68
+ elif cargo_type == 4: # 四个连续位置组合
69
+ for j in range(0, num_positions - 3, 4):
70
+ prob += x[i, j] + x[i, j + 1] + x[i, j + 2] + x[i, j + 3] <= 1, f"Cargo_{i}_Type4_Position_{j}_{j+3}"
71
+
72
+ # 求解问题
73
+ solver = pulp.GLPK_CMD(msg=False) # 使用默认的CBC求解器,不显示求解过程
74
+ prob.solve(solver)
75
+
76
+ # 检查求解状态
77
+ if pulp.LpStatus[prob.status] == 'Optimal':
78
+ # 构建装载方案矩阵
79
+ solution = np.zeros((num_cargos, num_positions))
80
+ for i in range(num_cargos):
81
+ for j in range(num_positions):
82
+ var_value = pulp.value(x[i, j])
83
+ if var_value is not None and var_value > 0.5:
84
+ solution[i, j] = 1
85
+
86
+ # 计算最终重心变化
87
+ cg_change = 0.0
88
+ for i in range(num_cargos):
89
+ for j in range(num_positions):
90
+ if solution[i, j] == 1:
91
+ if cargo_types[i] == 1:
92
+ cg_change += weights[i] * cg_impact[j]
93
+ elif cargo_types[i] == 2 and j % 2 == 0 and j < len(cg_impact_2u) * 2:
94
+ cg_change += weights[i] * cg_impact_2u[j // 2]
95
+ elif cargo_types[i] == 4 and j % 4 == 0 and j < len(cg_impact_4u) * 4:
96
+ cg_change += weights[i] * cg_impact_4u[j // 4]
97
+
98
+ return pulp.LpStatus[prob.status], cg_change, solution
99
+ else:
100
+ # 若求解失败,则返回空结果和错误标志
101
+ return pulp.LpStatus[prob.status], -1000000, None
102
+
103
+ # 示例输入和调用
104
+ def main():
105
+ weights = [500, 800, 1200, 300, 700, 1000, 600, 900] # 每个货物的质量
106
+ cargo_names = ['LD3', 'LD3', 'PLA', 'LD3', 'P6P', 'PLA', 'LD3', 'BULK'] # 货物名称
107
+ cargo_types_dict = {"LD3": 1, "PLA": 2, "P6P": 4, "BULK": 1} # 货物占位关系
108
+ positions = list(range(44)) # 44个货位编号
109
+ cg_impact = [i * 0.1 for i in range(44)] # 每kg货物对重心index的影响系数 (单个位置)
110
+ cg_impact_2u = [i * 0.08 for i in range(22)] # 两个位置组合的影响系数
111
+ cg_impact_4u = [i * 0.05 for i in range(11)] # 四个位置组合的影响系数
112
+ max_positions = 44 # 总货位数量
113
+
114
+ status, cg_change, solution = cargo_load_planning_mip(
115
+ weights, cargo_names, cargo_types_dict, positions, cg_impact, cg_impact_2u, cg_impact_4u, max_positions
116
+ )
117
+
118
+ if status == 'Optimal':
119
+ print("成功找到最优装载方案!")
120
+ print("装载方案矩阵:")
121
+ print(solution)
122
+
123
+ print(f"重心的变化量: {cg_change:.2f}")
124
+
125
+ # 输出实际分布
126
+ for i in range(len(weights)):
127
+ assigned_positions = []
128
+ for j in range(len(positions)):
129
+ if solution[i, j] > 0.5: # 判断位置是否被分配
130
+ assigned_positions.append(j)
131
+ print(f"货物 {cargo_names[i]} (占 {cargo_types_dict[cargo_names[i]]} 单位): 放置位置 -> {assigned_positions}")
132
+ else:
133
+ print("未能找到可行解。")
134
+ print(f"求解状态: {status}")
135
+
136
+ if __name__ == "__main__":
137
+ main()
code/optimization baselines/algorithm/MLIP.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pulp
3
+
4
+ def cargo_load_planning_mip(weights, cargo_names, cargo_types_dict, positions, cg_impact, cg_impact_2u, cg_impact_4u,
5
+ max_positions):
6
+ """
7
+ 使用混合整数规划方法计算货物装载方案,最小化重心的变化量。
8
+
9
+ 参数:
10
+ weights (list): 每个货物的质量列表。
11
+ cargo_names (list): 每个货物的名称。
12
+ cargo_types_dict (dict): 货物名称和占用的货位数量。
13
+ positions (list): 可用的货位编号。
14
+ cg_impact (list): 每个位置每kg货物对重心index的影响系数。
15
+ cg_impact_2u (list): 两个位置组合的重心影响系数。
16
+ cg_impact_4u (list): 四个位置组合的重心影响系数。
17
+ max_positions (int): 总货位的数量。
18
+
19
+ 返回:
20
+ result (pulp.LpStatus): 求解状态。
21
+ cg_change (float): 最优解的重心变化量。
22
+ solution_matrix (np.ndarray): 最优装载方案矩阵。
23
+ """
24
+ # 将货物类型映射为对应的占用单位数
25
+ cargo_types = [cargo_types_dict[name] for name in cargo_names]
26
+
27
+ num_cargos = len(weights) # 货物数量
28
+ num_positions = len(positions) # 可用货位数量
29
+
30
+ # 创建优化问题实例
31
+ prob = pulp.LpProblem("Cargo_Load_Planning", pulp.LpMinimize)
32
+
33
+ # 创建决策变量 x_ij (是否将货物i放置在位置j)
34
+ # 使用字典键 (i,j) 来标识变量
35
+ x = pulp.LpVariable.dicts("x",
36
+ ((i, j) for i in range(num_cargos) for j in range(num_positions)),
37
+ cat='Binary')
38
+
39
+ # 定义目标函数:最小化重心的变化量
40
+ objective_terms = []
41
+ for i in range(num_cargos):
42
+ for j in range(num_positions):
43
+ if cargo_types[i] == 1:
44
+ impact = abs(weights[i] * cg_impact[j])
45
+ elif cargo_types[i] == 2 and j % 2 == 0 and j < len(cg_impact_2u) * 2:
46
+ impact = abs(weights[i] * cg_impact_2u[j // 2])
47
+ elif cargo_types[i] == 4 and j % 4 == 0 and j < len(cg_impact_4u) * 4:
48
+ impact = abs(weights[i] * cg_impact_4u[j // 4])
49
+ else:
50
+ impact = 0
51
+ objective_terms.append(impact * x[i, j])
52
+
53
+ prob += pulp.lpSum(objective_terms), "Total_CG_Change"
54
+
55
+ # 约束1:每个货物只能装载到一个位置
56
+ for i in range(num_cargos):
57
+ prob += pulp.lpSum([x[i, j] for j in range(num_positions)]) == 1, f"Cargo_{i}_Single_Position"
58
+
59
+ # 约束2:每个位置只能装载一个货物
60
+ for j in range(num_positions):
61
+ prob += pulp.lpSum([x[i, j] for i in range(num_cargos)]) <= 1, f"Position_{j}_Single_Cargo"
62
+
63
+ # 约束3:占用多个位置的货物
64
+ for i, cargo_type in enumerate(cargo_types):
65
+ if cargo_type == 2: # 两个连续位置组合
66
+ for j in range(0, num_positions - 1, 2):
67
+ prob += x[i, j] + x[i, j + 1] <= 1, f"Cargo_{i}_Type2_Position_{j}_{j+1}"
68
+ elif cargo_type == 4: # 四个连续位置组合
69
+ for j in range(0, num_positions - 3, 4):
70
+ prob += x[i, j] + x[i, j + 1] + x[i, j + 2] + x[i, j + 3] <= 1, f"Cargo_{i}_Type4_Position_{j}_{j+3}"
71
+
72
+ # 求解问题
73
+ solver = pulp.PULP_CBC_CMD(msg=False) # 使用默认的CBC求解器,不显示求解过程
74
+ prob.solve(solver)
75
+
76
+ # 检查求解状态
77
+ if pulp.LpStatus[prob.status] == 'Optimal':
78
+ # 构建装载方案矩阵
79
+ solution = np.zeros((num_cargos, num_positions))
80
+ for i in range(num_cargos):
81
+ for j in range(num_positions):
82
+ var_value = pulp.value(x[i, j])
83
+ if var_value is not None and var_value > 0.5:
84
+ solution[i, j] = 1
85
+
86
+ # 计算最终重心变化
87
+ cg_change = 0.0
88
+ for i in range(num_cargos):
89
+ for j in range(num_positions):
90
+ if solution[i, j] == 1:
91
+ if cargo_types[i] == 1:
92
+ cg_change += weights[i] * cg_impact[j]
93
+ elif cargo_types[i] == 2 and j % 2 == 0 and j < len(cg_impact_2u) * 2:
94
+ cg_change += weights[i] * cg_impact_2u[j // 2]
95
+ elif cargo_types[i] == 4 and j % 4 == 0 and j < len(cg_impact_4u) * 4:
96
+ cg_change += weights[i] * cg_impact_4u[j // 4]
97
+
98
+ return solution, cg_change
99
+ else:
100
+ # 若求解失败,则返回空结果和错误标志
101
+ return [], -1000000
102
+
103
+ # 示例输入和调用
104
+ # def main():
105
+ # weights = [500, 800, 1200, 300, 700, 1000, 600, 900] # 每个货物的质量
106
+ # cargo_names = ['LD3', 'LD3', 'PLA', 'LD3', 'P6P', 'PLA', 'LD3', 'BULK'] # 货物名称
107
+ # cargo_types_dict = {"LD3": 1, "PLA": 2, "P6P": 4, "BULK": 1} # 货物占位关系
108
+ # positions = list(range(44)) # 44个货位编号
109
+ # cg_impact = [i * 0.1 for i in range(44)] # 每kg货物对重心index的影响系数 (单个位置)
110
+ # cg_impact_2u = [i * 0.08 for i in range(22)] # 两个位置组合的影响系数
111
+ # cg_impact_4u = [i * 0.05 for i in range(11)] # 四个位置组合的影响系数
112
+ # max_positions = 44 # 总货位数量
113
+ #
114
+ # status, cg_change, solution = cargo_load_planning_mip(
115
+ # weights, cargo_names, cargo_types_dict, positions, cg_impact, cg_impact_2u, cg_impact_4u, max_positions
116
+ # )
117
+ #
118
+ # if status == 'Optimal':
119
+ # print("成功找到最优装载方案!")
120
+ # print("装载方案矩阵:")
121
+ # print(solution)
122
+ #
123
+ # print(f"重心的变化量: {cg_change:.2f}")
124
+ #
125
+ # # 输出实际分布
126
+ # for i in range(len(weights)):
127
+ # assigned_positions = []
128
+ # for j in range(len(positions)):
129
+ # if solution[i, j] > 0.5: # 判断位置是否被分配
130
+ # assigned_positions.append(j)
131
+ # print(f"货物 {cargo_names[i]} (占 {cargo_types_dict[cargo_names[i]]} 单位): 放置位置 -> {assigned_positions}")
132
+ # else:
133
+ # print("未能找到可行解。")
134
+ # print(f"求解状态: {status}")
135
+ #
136
+ # if __name__ == "__main__":
137
+ # main()
code/optimization baselines/algorithm/NL-CPLEX.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.optimize import linprog
3
+
4
+
5
+ def cargo_load_planning_nonlinear1(weights, cargo_names, cargo_types_dict, positions, cg_impact, cg_impact_2u, cg_impact_4u,
6
+ max_positions):
7
+ """
8
+ 使用整数线性规划方法计算货物装载方案,最小化重心的变化量。
9
+
10
+ 参数:
11
+ weights (list): 每个货物的质量列表。
12
+ cargo_names (list): 每个货物的名称。
13
+ cargo_types_dict (dict): 货物名称和占用的货位数量。
14
+ positions (list): 可用的货位编号。
15
+ cg_impact (list): 每个位置每kg货物对重心index的影响系数。
16
+ cg_impact_2u (list): 两个位置组合的重心影响系数。
17
+ cg_impact_4u (list): 四个位置组合的重心影响系数。
18
+ max_positions (int): 总货位的数量。
19
+
20
+ 返回:
21
+ result.x: 最优装载方案矩阵。
22
+ """
23
+ # 将货物类型映射为对应的占用单位数
24
+ cargo_types = [cargo_types_dict[name] for name in cargo_names]
25
+
26
+ num_cargos = len(weights) # 货物数量
27
+ num_positions = len(positions) # 可用货位数量
28
+
29
+ # 决策变量:xij (是否将货物i放置在位置j)
30
+ c = [] # 目标函数系数列表
31
+ for i in range(num_cargos):
32
+ for j in range(num_positions):
33
+ if cargo_types[i] == 1:
34
+ c.append((weights[i] * cg_impact[j])**2)
35
+ elif cargo_types[i] == 2 and j % 2 == 0 and j < len(cg_impact_2u) * 2:
36
+ c.append((weights[i] * cg_impact_2u[j // 2])**2)
37
+ elif cargo_types[i] == 4 and j % 4 == 0 and j < len(cg_impact_4u) * 4:
38
+ c.append((weights[i] * cg_impact_4u[j // 4])**2)
39
+ else:
40
+ c.append(0) # 不适合的索引默认影响为0
41
+
42
+ # 决策变量约束:xij只能是0或1 (整型约束由 linprog 近似处理)
43
+ bounds = [(0, 1) for _ in range(num_cargos * num_positions)]
44
+
45
+ # 约束1:每个货物只能装载到一个位置
46
+ A_eq = []
47
+ b_eq = []
48
+ for i in range(num_cargos):
49
+ constraint = [0] * (num_cargos * num_positions)
50
+ for j in range(num_positions):
51
+ constraint[i * num_positions + j] = 1
52
+ A_eq.append(constraint)
53
+ b_eq.append(1)
54
+
55
+ # 约束2:每个位置只能装载一个货物
56
+ A_ub = []
57
+ b_ub = []
58
+ for j in range(num_positions): # 遍历所有位置
59
+ constraint = [0] * (num_cargos * num_positions)
60
+ for i in range(num_cargos): # 遍历所有货物
61
+ constraint[i * num_positions + j] = 1
62
+ A_ub.append(constraint)
63
+ b_ub.append(1) # 每个位置最多只能分配一个货物
64
+
65
+ # 约束3:占用多个位置的货物
66
+ for i, cargo_type in enumerate(cargo_types):
67
+ if cargo_type == 2: # 两个连续位置组合
68
+ for j in range(0, num_positions - 1, 2):
69
+ constraint = [0] * (num_cargos * num_positions)
70
+ constraint[i * num_positions + j] = 1
71
+ constraint[i * num_positions + j + 1] = 1
72
+ A_ub.append(constraint)
73
+ b_ub.append(1)
74
+ elif cargo_type == 4: # 上两个、下两个组合
75
+ for j in range(0, num_positions - 3, 4):
76
+ constraint = [0] * (num_cargos * num_positions)
77
+ constraint[i * num_positions + j] = 1
78
+ constraint[i * num_positions + j + 1] = 1
79
+ constraint[i * num_positions + j + 2] = 1
80
+ constraint[i * num_positions + j + 3] = 1
81
+ A_ub.append(constraint)
82
+ b_ub.append(1)
83
+
84
+ # 转换为numpy数组
85
+ A_eq = np.array(A_eq)
86
+ b_eq = np.array(b_eq)
87
+ A_ub = np.array(A_ub)
88
+ b_ub = np.array(b_ub)
89
+ c = np.array(c)
90
+
91
+ # 求解线性规划问题
92
+ result = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=bounds, method='highs-ds')
93
+
94
+ if result.success:
95
+ # print("成功找到最优装载方案!")
96
+ solution = result.x.reshape((num_cargos, num_positions))
97
+ # print("装载方案矩阵:")
98
+ # print(solution)
99
+
100
+ # 计算最终重心变化
101
+ cg_change = 0
102
+ for i in range(num_cargos):
103
+ for j in range(num_positions):
104
+ if cargo_types[i] == 1:
105
+ cg_change += solution[i, j] * weights[i] * cg_impact[j]
106
+ elif cargo_types[i] == 2 and j % 2 == 0 and j < len(cg_impact_2u) * 2:
107
+ cg_change += solution[i, j] * weights[i] * cg_impact_2u[j // 2]
108
+ elif cargo_types[i] == 4 and j % 4 == 0 and j < len(cg_impact_4u) * 4:
109
+ cg_change += solution[i, j] * weights[i] * cg_impact_4u[j // 4]
110
+ # print(f"重心的变化量: {cg_change:.2f}")
111
+ return result,cg_change
112
+ # 输出实际分布
113
+ # print("货物实际分布:")
114
+ # for i in range(num_cargos):
115
+ # assigned_positions = []
116
+ # for j in range(num_positions):
117
+ # if solution[i, j] > 0.5: # 判断位置是否被分配
118
+ # assigned_positions.append(j)
119
+ # print(f"货物 {cargo_names[i]} (占 {cargo_types[i]} 单位): 放置位置 -> {assigned_positions}")
120
+ else:
121
+ result = []
122
+ return result,-1000000
123
+
124
+
125
+
126
+
127
+ # # 示例输入
128
+ # def main():
129
+ # weights = [500, 800, 1200, 300, 700, 1000, 600, 900] # 每个货物的质量
130
+ # cargo_names = ['LD3', 'LD3', 'PLA', 'LD3', 'P6P', 'PLA', 'LD3', 'BULK'] # 货物名称
131
+ # cargo_types_dict = {"LD3": 1, "PLA": 2, "P6P": 4, "BULK": 1} # 货物占位关系
132
+ # positions = list(range(44)) # 44个货位编号
133
+ # cg_impact = [i * 0.1 for i in range(44)] # 每kg货物对重心index的影响系数 (单个位置)
134
+ # cg_impact_2u = [i * 0.08 for i in range(22)] # 两个位置组合的影响系数
135
+ # cg_impact_4u = [i * 0.05 for i in range(11)] # 四个位置组合的影响系数
136
+ # max_positions = 44 # 总货位数量
137
+ #
138
+ # result = cargo_load_planning_nonlinear1(weights, cargo_names, cargo_types_dict, positions, cg_impact, cg_impact_2u,
139
+ # cg_impact_4u, max_positions)
140
+ #
141
+ #
142
+ # if __name__ == "__main__":
143
+ # main()
code/optimization baselines/algorithm/PSO-normal.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pyswarms as ps
3
+
4
+
5
+ def cargo_load_planning_pso(weights, cargo_names, cargo_types_dict, positions, cg_impact, cg_impact_2u, cg_impact_4u,
6
+ max_positions, options=None, swarmsize=100, maxiter=100):
7
+ """
8
+ 使用粒子群优化方法计算货物装载方案,最小化重心的变化量。
9
+
10
+ 参数:
11
+ weights (list): 每个货物的质量列表。
12
+ cargo_names (list): 每个货物的名称。
13
+ cargo_types_dict (dict): 货物名称和占用的货位数量。
14
+ positions (list): 可用的货位编号。
15
+ cg_impact (list): 每个位置每kg货物对重心index的影响系数。
16
+ cg_impact_2u (list): 两个位置组合的重心影响系数。
17
+ cg_impact_4u (list): 四个位置组合的重心影响系数。
18
+ max_positions (int): 总货位的数量。
19
+ options (dict, optional): PSO算法的配置选项。
20
+ swarmsize (int, optional): 粒子群大小。
21
+ maxiter (int, optional): 最大迭代次数。
22
+
23
+ 返回:
24
+ best_solution (np.array): 最优装载方案矩阵。
25
+ best_cg_change (float): 最优方案的重心变化量。
26
+ """
27
+ # 将货物类型映射为对应的占用单位数
28
+ cargo_types = [cargo_types_dict[name] for name in cargo_names]
29
+
30
+ num_cargos = len(weights) # 货物数量
31
+ num_positions = len(positions) # 可用货位数量
32
+ dimension = num_cargos # 每个粒子的维度对应每个货物的起始位置
33
+
34
+ # 如果未提供options,使用默认配置
35
+ if options is None:
36
+ options = {'c1': 0.5, 'c2': 0.3, 'w': 0.9}
37
+
38
+ # 定义适应度评估函数
39
+ def fitness_function(x):
40
+ """
41
+ 计算每个粒子的适应度值。
42
+
43
+ 参数:
44
+ x (numpy.ndarray): 粒子的位置数组,形状为 (n_particles, dimension)。
45
+
46
+ 返回:
47
+ numpy.ndarray: 每个粒子的适应度值。
48
+ """
49
+ fitness = np.zeros(x.shape[0])
50
+
51
+ for idx, particle in enumerate(x):
52
+ # 将连续位置映射为离散起始位置,根据货物类型对齐
53
+ start_positions = []
54
+ penalty = 0
55
+ cg_change = 0.0
56
+ occupied = np.zeros(num_positions, dtype=int)
57
+
58
+ for i in range(num_cargos):
59
+ cargo_type = cargo_types[i]
60
+ pos_continuous = particle[i]
61
+
62
+ # 根据货物类型对齐
63
+ if cargo_type == 1:
64
+ start_pos = int(np.round(pos_continuous)) % num_positions
65
+ elif cargo_type == 2:
66
+ start_pos = (int(np.round(pos_continuous)) // 2) * 2
67
+ if start_pos >= num_positions - 1:
68
+ start_pos = num_positions - 2
69
+ elif cargo_type == 4:
70
+ start_pos = (int(np.round(pos_continuous)) // 4) * 4
71
+ if start_pos >= num_positions - 3:
72
+ start_pos = num_positions - 4
73
+ else:
74
+ start_pos = 0 # 默认位置
75
+
76
+ # 检查边界
77
+ if start_pos < 0 or start_pos + cargo_type > num_positions:
78
+ penalty += 1000
79
+ continue
80
+
81
+ # 检查对齐
82
+ if cargo_type == 2 and start_pos % 2 != 0:
83
+ penalty += 1000
84
+ if cargo_type == 4 and start_pos % 4 != 0:
85
+ penalty += 1000
86
+
87
+ # 检查重叠
88
+ if np.any(occupied[start_pos:start_pos + cargo_type]):
89
+ penalty += 1000
90
+ else:
91
+ occupied[start_pos:start_pos + cargo_type] = 1
92
+
93
+ start_positions.append(start_pos)
94
+
95
+ # 计算重心变化量
96
+ if cargo_type == 1:
97
+ cg_change += weights[i] * cg_impact[start_pos]
98
+ elif cargo_type == 2:
99
+ cg_change += weights[i] * cg_impact_2u[start_pos // 2]
100
+ elif cargo_type == 4:
101
+ cg_change += weights[i] * cg_impact_4u[start_pos // 4]
102
+
103
+ fitness[idx] = cg_change + penalty
104
+
105
+ return fitness
106
+
107
+ # 设置PSO的边界
108
+ # 对于每个货物,起始位置的范围根据货物类型对齐
109
+ lower_bounds = []
110
+ upper_bounds = []
111
+ for i in range(num_cargos):
112
+ cargo_type = cargo_types[i]
113
+ if cargo_type == 1:
114
+ lower_bounds.append(0)
115
+ upper_bounds.append(num_positions - 1)
116
+ elif cargo_type == 2:
117
+ lower_bounds.append(0)
118
+ upper_bounds.append(num_positions - 2)
119
+ elif cargo_type == 4:
120
+ lower_bounds.append(0)
121
+ upper_bounds.append(num_positions - 4)
122
+ else:
123
+ lower_bounds.append(0)
124
+ upper_bounds.append(num_positions - 1)
125
+
126
+ bounds = (np.array(lower_bounds), np.array(upper_bounds))
127
+
128
+ # 初始化PSO优化器
129
+ optimizer = ps.single.GlobalBestPSO(n_particles=swarmsize, dimensions=dimension, options=options, bounds=bounds)
130
+
131
+ # 运行PSO优化
132
+ best_cost, best_pos = optimizer.optimize(fitness_function, iters=maxiter)
133
+
134
+ # 将最佳位置映射为离散装载方案
135
+ best_start_positions = []
136
+ penalty = 0
137
+ cg_change = 0.0
138
+ occupied = np.zeros(num_positions, dtype=int)
139
+
140
+ for i in range(num_cargos):
141
+ cargo_type = cargo_types[i]
142
+ pos_continuous = best_pos[i]
143
+
144
+ # 根据货物类型对齐
145
+ if cargo_type == 1:
146
+ start_pos = int(np.round(pos_continuous)) % num_positions
147
+ elif cargo_type == 2:
148
+ start_pos = (int(np.round(pos_continuous)) // 2) * 2
149
+ if start_pos >= num_positions - 1:
150
+ start_pos = num_positions - 2
151
+ elif cargo_type == 4:
152
+ start_pos = (int(np.round(pos_continuous)) // 4) * 4
153
+ if start_pos >= num_positions - 3:
154
+ start_pos = num_positions - 4
155
+ else:
156
+ start_pos = 0 # 默认位置
157
+
158
+ # 检查边界
159
+ if start_pos < 0 or start_pos + cargo_type > num_positions:
160
+ penalty += 1000
161
+ best_start_positions.append(start_pos)
162
+ continue
163
+
164
+ # 检查对齐
165
+ if cargo_type == 2 and start_pos % 2 != 0:
166
+ penalty += 1000
167
+ if cargo_type == 4 and start_pos % 4 != 0:
168
+ penalty += 1000
169
+
170
+ # 检查重叠
171
+ if np.any(occupied[start_pos:start_pos + cargo_type]):
172
+ penalty += 1000
173
+ else:
174
+ occupied[start_pos:start_pos + cargo_type] = 1
175
+
176
+ best_start_positions.append(start_pos)
177
+
178
+ # 计算重心变化量
179
+ if cargo_type == 1:
180
+ cg_change += abs(weights[i] * cg_impact[start_pos])
181
+ elif cargo_type == 2:
182
+ cg_change += abs(weights[i] * cg_impact_2u[start_pos // 2])
183
+ elif cargo_type == 4:
184
+ cg_change += abs(weights[i] * cg_impact_4u[start_pos // 4])
185
+
186
+ total_cg_change = cg_change + penalty
187
+
188
+ # 构建装载方案矩阵
189
+ best_xij = np.zeros((num_cargos, num_positions), dtype=int)
190
+ for i, start_pos in enumerate(best_start_positions):
191
+ cargo_type = cargo_types[i]
192
+ for k in range(cargo_type):
193
+ pos = start_pos + k
194
+ if pos < num_positions:
195
+ best_xij[i, pos] = 1
196
+
197
+ # 检查是否有严重惩罚,判断是否找到可行解
198
+ if total_cg_change >= -999999:
199
+ return best_xij, total_cg_change
200
+ else:
201
+ return [], -1000000
202
+
203
+ #
204
+ # # 示例输入和调用
205
+ # def main():
206
+ # weights = [500, 800, 1200, 300, 700, 1000, 600, 900] # 每个货物的质量
207
+ # cargo_names = ['LD3', 'LD3', 'PLA', 'LD3', 'P6P', 'PLA', 'LD3', 'BULK'] # 货物名称
208
+ # cargo_types_dict = {"LD3": 1, "PLA": 2, "P6P": 4, "BULK": 1} # 货物占位关系
209
+ # positions = list(range(44)) # 44个货位编号
210
+ # cg_impact = [i * 0.1 for i in range(44)] # 每kg货物对重心index的影响系数 (单个位置)
211
+ # cg_impact_2u = [i * 0.08 for i in range(22)] # 两个位置组合的影响系数
212
+ # cg_impact_4u = [i * 0.05 for i in range(11)] # 四个位置组合的影响系数
213
+ # max_positions = 44 # 总货位数量
214
+ #
215
+ # # 设置PSO参数(可选)
216
+ # options = {'c1': 0.5, 'c2': 0.3, 'w': 0.9}
217
+ #
218
+ # solution, cg_change = cargo_load_planning_pso(
219
+ # weights, cargo_names, cargo_types_dict, positions,
220
+ # cg_impact, cg_impact_2u, cg_impact_4u, max_positions,
221
+ # options=options, swarmsize=200, maxiter=200
222
+ # )
223
+ #
224
+ # if solution is not None and len(solution) > 0:
225
+ # print("成功找到最优装载方案!")
226
+ # print("装载方案矩阵:")
227
+ # print(solution)
228
+ # print(f"重心的变化量: {cg_change:.2f}")
229
+ #
230
+ # # 输出实际分布
231
+ # for i in range(len(weights)):
232
+ # assigned_positions = []
233
+ # for j in range(len(positions)):
234
+ # if solution[i, j] > 0.5: # 判断位置是否被分配
235
+ # assigned_positions.append(j)
236
+ # print(f"货物 {cargo_names[i]} (占 {cargo_types_dict[cargo_names[i]]} 单位): 放置位置 -> {assigned_positions}")
237
+ # else:
238
+ # print("未找到可行的装载方案。")
239
+ #
240
+ #
241
+ # if __name__ == "__main__":
242
+ # main()
code/optimization baselines/algorithm/RCH.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+
4
+ def cargo_load_planning_heuristic(weights, cargo_names, cargo_types_dict, positions,
5
+ cg_impact, cg_impact_2u, cg_impact_4u, max_positions,
6
+ max_iterations=1000):
7
+ """
8
+ 使用两阶段启发式算法计算货物装载方案,最小化重心的变化量。
9
+
10
+ 参数:
11
+ weights (list): 每个货物的质量列表。
12
+ cargo_names (list): 每个货物的名称。
13
+ cargo_types_dict (dict): 货物名称和占用的货位数量。
14
+ positions (list): 可用的货位编号。
15
+ cg_impact (list): 每个位置每kg货物对重心index的影响系数。
16
+ cg_impact_2u (list): 两个位置组合的重心影响系数。
17
+ cg_impact_4u (list): 四个位置组合的重心影响系数。
18
+ max_positions (int): 总货位的数量。
19
+ max_iterations (int): 优化阶段的最大迭代次数。
20
+
21
+ 返回:
22
+ solution (np.array): 最优装载方案矩阵。
23
+ total_cg_change (float): 最优方案的重心变化量。
24
+ """
25
+ # 将货物类型映射为对应的占用单位数
26
+ cargo_types = [cargo_types_dict[name] for name in cargo_names]
27
+
28
+ num_cargos = len(weights) # 货物数量
29
+ num_positions = len(positions) # 可用货位数量
30
+
31
+ # 初始化装载方案矩阵
32
+ solution = np.zeros((num_cargos, num_positions), dtype=int)
33
+
34
+ # 标记已占用的位置
35
+ occupied = np.zeros(num_positions, dtype=int)
36
+
37
+ # 按照货物类型(占用单位数降序)和重量降序排序货物
38
+ sorted_indices = sorted(range(num_cargos), key=lambda i: (-cargo_types[i], -weights[i]))
39
+
40
+ # 阶段1:初始装载方案生成
41
+ for i in sorted_indices:
42
+ cargo_type = cargo_types[i]
43
+ feasible_positions = []
44
+
45
+ # 根据货物类型确定可行的起始位置
46
+ if cargo_type == 1:
47
+ possible_starts = range(0, num_positions)
48
+ elif cargo_type == 2:
49
+ possible_starts = range(0, num_positions - 1, 2)
50
+ elif cargo_type == 4:
51
+ possible_starts = range(0, num_positions - 3, 4)
52
+ else:
53
+ possible_starts = []
54
+
55
+ for start in possible_starts:
56
+ # 检查是否超出边界
57
+ if start + cargo_type > num_positions:
58
+ continue
59
+ # 检查是否与已占用位置重叠
60
+ if np.any(occupied[start:start + cargo_type]):
61
+ continue
62
+ # 计算重心变化量
63
+ if cargo_type == 1:
64
+ cg = abs(weights[i] * cg_impact[start])
65
+ elif cargo_type == 2:
66
+ cg = abs(weights[i] * cg_impact_2u[start // 2])
67
+ elif cargo_type == 4:
68
+ cg = abs(weights[i] * cg_impact_4u[start // 4])
69
+ feasible_positions.append((start, cg))
70
+
71
+ # 如果有可行位置,选择使重心变化最小的位置
72
+ if feasible_positions:
73
+ best_start, best_cg = min(feasible_positions, key=lambda x: x[1])
74
+ solution[i, best_start:best_start + cargo_type] = 1
75
+ occupied[best_start:best_start + cargo_type] = 1
76
+ else:
77
+ # 如果没有可行位置,则尝试分配到任何未占用的位置(可能违反约束)
78
+ for start in range(0, num_positions - cargo_type + 1):
79
+ if np.all(occupied[start:start + cargo_type] == 0):
80
+ solution[i, start:start + cargo_type] = 1
81
+ occupied[start:start + cargo_type] = 1
82
+ break
83
+
84
+ # 计算初始重心变化量
85
+ total_cg_change = 0.0
86
+ for i in range(num_cargos):
87
+ cargo_type = cargo_types[i]
88
+ assigned_positions = np.where(solution[i] == 1)[0]
89
+ if len(assigned_positions) == 0:
90
+ continue
91
+ if cargo_type == 1:
92
+ total_cg_change += abs(weights[i] * cg_impact[assigned_positions[0]])
93
+ elif cargo_type == 2:
94
+ total_cg_change += abs(weights[i] * cg_impact_2u[assigned_positions[0] // 2])
95
+ elif cargo_type == 4:
96
+ total_cg_change += abs(weights[i] * cg_impact_4u[assigned_positions[0] // 4])
97
+
98
+ # 阶段2:装载方案优化
99
+ for _ in range(max_iterations):
100
+ improved = False
101
+ for i in range(num_cargos):
102
+ cargo_type = cargo_types[i]
103
+ current_positions = np.where(solution[i] == 1)[0]
104
+ if len(current_positions) == 0:
105
+ continue
106
+ current_start = current_positions[0]
107
+
108
+ # 根据货物类型确定可行的起始位置
109
+ if cargo_type == 1:
110
+ possible_starts = range(0, num_positions)
111
+ elif cargo_type == 2:
112
+ possible_starts = range(0, num_positions - 1, 2)
113
+ elif cargo_type == 4:
114
+ possible_starts = range(0, num_positions - 3, 4)
115
+ else:
116
+ possible_starts = []
117
+
118
+ best_start = current_start
119
+ best_cg = total_cg_change
120
+
121
+ for start in possible_starts:
122
+ if start == current_start:
123
+ continue
124
+ # 检查是否超出边界
125
+ if start + cargo_type > num_positions:
126
+ continue
127
+ # 检查是否与已占用位置重叠
128
+ if np.any(occupied[start:start + cargo_type]):
129
+ continue
130
+ # 计算重心变化量
131
+ if cargo_type == 1:
132
+ new_cg = abs(weights[i] * cg_impact[start])
133
+ elif cargo_type == 2:
134
+ new_cg = abs(weights[i] * cg_impact_2u[start // 2])
135
+ elif cargo_type == 4:
136
+ new_cg = abs(weights[i] * cg_impact_4u[start // 4])
137
+ else:
138
+ new_cg = 0
139
+
140
+ # 计算新的总重心变化量
141
+ temp_cg_change = total_cg_change - (
142
+ weights[i] * cg_impact[current_start] if cargo_type == 1 else
143
+ weights[i] * cg_impact_2u[current_start // 2] if cargo_type == 2 else
144
+ weights[i] * cg_impact_4u[current_start // 4] if cargo_type == 4 else 0
145
+ ) + new_cg
146
+
147
+ # 如果新的重心变化量更小,进行更新
148
+ if temp_cg_change < best_cg:
149
+ best_cg = temp_cg_change
150
+ best_start = start
151
+
152
+ # 如果找到了更好的位置,进行更新
153
+ if best_start != current_start:
154
+ # 释放当前占用的位置
155
+ occupied[current_start:current_start + cargo_type] = 0
156
+ solution[i, current_start:current_start + cargo_type] = 0
157
+
158
+ # 分配到新的位置
159
+ solution[i, best_start:best_start + cargo_type] = 1
160
+ occupied[best_start:best_start + cargo_type] = 1
161
+
162
+ # 更新总重心变化量
163
+ total_cg_change = best_cg
164
+ improved = True
165
+
166
+ if not improved:
167
+ break # 如果在一个完整的迭代中没有改进,结束优化
168
+
169
+ return solution, total_cg_change
170
+
171
+
172
+ # 示例输入和调用
173
+ def main():
174
+ weights = [500, 800, 1200, 300, 700, 1000, 600, 900] # 每个货物的质量
175
+ cargo_names = ['LD3', 'LD3', 'PLA', 'LD3', 'P6P', 'PLA', 'LD3', 'BULK'] # 货物名称
176
+ cargo_types_dict = {"LD3": 1, "PLA": 2, "P6P": 4, "BULK": 1} # 货物占位关系
177
+ positions = list(range(44)) # 44个货位编号
178
+ cg_impact = [i * 0.1 for i in range(44)] # 每kg货物对重心index的影响系数 (单个位置)
179
+ cg_impact_2u = [i * 0.08 for i in range(22)] # 两个位置组合的影响系数
180
+ cg_impact_4u = [i * 0.05 for i in range(11)] # 四个位置组合的影响系数
181
+ max_positions = 44 # 总货位数量
182
+
183
+ solution, cg_change = cargo_load_planning_heuristic(
184
+ weights, cargo_names, cargo_types_dict, positions,
185
+ cg_impact, cg_impact_2u, cg_impact_4u, max_positions,
186
+ max_iterations=1000
187
+ )
188
+
189
+ if solution is not None and solution.size > 0:
190
+ print("成功找到最优装载方案!")
191
+ print("装载方案矩阵:")
192
+ print(solution)
193
+ print(f"重心的变化量: {cg_change:.2f}")
194
+
195
+ # 输出实际分布
196
+ for i in range(len(weights)):
197
+ assigned_positions = []
198
+ for j in range(len(positions)):
199
+ if solution[i, j] > 0.5: # 判断位置是否被分配
200
+ assigned_positions.append(j)
201
+ print(f"货物 {cargo_names[i]} (占 {cargo_types_dict[cargo_names[i]]} 单位): 放置位置 -> {assigned_positions}")
202
+ else:
203
+ print("未找到可行的装载方案。")
204
+
205
+
206
+ if __name__ == "__main__":
207
+ main()
code/optimization baselines/algorithm/SDCCLPM.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.optimize import linprog
3
+
4
+
5
+ def cargo_load_planning_nonlinear2(weights, cargo_names, cargo_types_dict, positions, cg_impact, cg_impact_2u, cg_impact_4u,
6
+ max_positions):
7
+ """
8
+ 使用整数线性规划方法计算货物装载方案,最小化重心的变化量。
9
+
10
+ 参数:
11
+ weights (list): 每个货物的质量列表。
12
+ cargo_names (list): 每个货物的名称。
13
+ cargo_types_dict (dict): 货物名称和占用的货位数量。
14
+ positions (list): 可用的货位编号。
15
+ cg_impact (list): 每个位置每kg货物对重心index的影响系数。
16
+ cg_impact_2u (list): 两个位置组合的重心影响系数。
17
+ cg_impact_4u (list): 四个位置组合的重心影响系数。
18
+ max_positions (int): 总货位的数量。
19
+
20
+ 返回:
21
+ result.x: 最优装载方案矩阵。
22
+ """
23
+ # 将货物类型映射为对应的占用单位数
24
+ cargo_types = [cargo_types_dict[name] for name in cargo_names]
25
+
26
+ num_cargos = len(weights) # 货物数量
27
+ num_positions = len(positions) # 可用货位数量
28
+
29
+ # 决策变量:xij (是否将货物i放置在位置j)
30
+ c = [] # 目标函数系数列表
31
+ for i in range(num_cargos):
32
+ for j in range(num_positions):
33
+ if cargo_types[i] == 1:
34
+ c.append((weights[i] * cg_impact[j])**2)
35
+ elif cargo_types[i] == 2 and j % 2 == 0 and j < len(cg_impact_2u) * 2:
36
+ c.append((weights[i] * cg_impact_2u[j // 2])**2)
37
+ elif cargo_types[i] == 4 and j % 4 == 0 and j < len(cg_impact_4u) * 4:
38
+ c.append((weights[i] * cg_impact_4u[j // 4])**2)
39
+ else:
40
+ c.append(0) # 不适合的索引默认影响为0
41
+
42
+ # 决策变量约束:xij只能是0或1 (整型约束由 linprog 近似处理)
43
+ bounds = [(0, 1) for _ in range(num_cargos * num_positions)]
44
+
45
+ # 约束1:每个货物只能装载到一个位置
46
+ A_eq = []
47
+ b_eq = []
48
+ for i in range(num_cargos):
49
+ constraint = [0] * (num_cargos * num_positions)
50
+ for j in range(num_positions):
51
+ constraint[i * num_positions + j] = 1
52
+ A_eq.append(constraint)
53
+ b_eq.append(1)
54
+
55
+ # 约束2:每个位置只能装载一个货物
56
+ A_ub = []
57
+ b_ub = []
58
+ for j in range(num_positions): # 遍历所有位置
59
+ constraint = [0] * (num_cargos * num_positions)
60
+ for i in range(num_cargos): # 遍历所有货物
61
+ constraint[i * num_positions + j] = 1
62
+ A_ub.append(constraint)
63
+ b_ub.append(1) # 每个位置最多只能分配一个货物
64
+
65
+ # 约束3:占用多个位置的货物
66
+ for i, cargo_type in enumerate(cargo_types):
67
+ if cargo_type == 2: # 两个连续位置组合
68
+ for j in range(0, num_positions - 1, 2):
69
+ constraint = [0] * (num_cargos * num_positions)
70
+ constraint[i * num_positions + j] = 1
71
+ constraint[i * num_positions + j + 1] = 1
72
+ A_ub.append(constraint)
73
+ b_ub.append(1)
74
+ elif cargo_type == 4: # 上两个、下两个组合
75
+ for j in range(0, num_positions - 3, 4):
76
+ constraint = [0] * (num_cargos * num_positions)
77
+ constraint[i * num_positions + j] = 1
78
+ constraint[i * num_positions + j + 1] = 1
79
+ constraint[i * num_positions + j + 2] = 1
80
+ constraint[i * num_positions + j + 3] = 1
81
+ A_ub.append(constraint)
82
+ b_ub.append(1)
83
+
84
+ # 转换为numpy数组
85
+ A_eq = np.array(A_eq)
86
+ b_eq = np.array(b_eq)
87
+ A_ub = np.array(A_ub)
88
+ b_ub = np.array(b_ub)
89
+ c = np.array(c)
90
+
91
+ # 求解线性规划问题
92
+ result = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=bounds, method='highs')
93
+
94
+ if result.success:
95
+ # print("成功找到最优装载方案!")
96
+ solution = result.x.reshape((num_cargos, num_positions))
97
+ # print("装载方案矩阵:")
98
+ # print(solution)
99
+
100
+ # 计算最终重心变化
101
+ cg_change = 0
102
+ for i in range(num_cargos):
103
+ for j in range(num_positions):
104
+ if cargo_types[i] == 1:
105
+ cg_change += solution[i, j] * weights[i] * cg_impact[j]
106
+ elif cargo_types[i] == 2 and j % 2 == 0 and j < len(cg_impact_2u) * 2:
107
+ cg_change += solution[i, j] * weights[i] * cg_impact_2u[j // 2]
108
+ elif cargo_types[i] == 4 and j % 4 == 0 and j < len(cg_impact_4u) * 4:
109
+ cg_change += solution[i, j] * weights[i] * cg_impact_4u[j // 4]
110
+ # print(f"重心的变化量: {cg_change:.2f}")
111
+ return result,cg_change
112
+ # 输出实际分布
113
+ # print("货物实际分布:")
114
+ # for i in range(num_cargos):
115
+ # assigned_positions = []
116
+ # for j in range(num_positions):
117
+ # if solution[i, j] > 0.5: # 判断位置是否被分配
118
+ # assigned_positions.append(j)
119
+ # print(f"货物 {cargo_names[i]} (占 {cargo_types[i]} 单位): 放置位置 -> {assigned_positions}")
120
+ else:
121
+ result = []
122
+ return result,-1000000
123
+
124
+
125
+
126
+
127
+ # # 示例输入
128
+ # def main():
129
+ # weights = [500, 800, 1200, 300, 700, 1000, 600, 900] # 每个货物的质量
130
+ # cargo_names = ['LD3', 'LD3', 'PLA', 'LD3', 'P6P', 'PLA', 'LD3', 'BULK'] # 货物名称
131
+ # cargo_types_dict = {"LD3": 1, "PLA": 2, "P6P": 4, "BULK": 1} # 货物占位关系
132
+ # positions = list(range(44)) # 44个货位编号
133
+ # cg_impact = [i * 0.1 for i in range(44)] # 每kg货物对重心index的影响系数 (单个位置)
134
+ # cg_impact_2u = [i * 0.08 for i in range(22)] # 两个位置组合的影响系数
135
+ # cg_impact_4u = [i * 0.05 for i in range(11)] # 四个位置组合的影响系数
136
+ # max_positions = 44 # 总货位数量
137
+ #
138
+ # result = cargo_load_planning_nonlinear1(weights, cargo_names, cargo_types_dict, positions, cg_impact, cg_impact_2u,
139
+ # cg_impact_4u, max_positions)
140
+ #
141
+ #
142
+ # if __name__ == "__main__":
143
+ # main()