Skip to content

Commit eefa8be

Browse files
author
matasovt
committed
Notebook results
1 parent 40ee842 commit eefa8be

8 files changed

Lines changed: 659 additions & 446 deletions

File tree

‎current_setpoints/data/machines.py‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -153,10 +153,6 @@ def __init__(
153153

154154
self.machine_name = machine_name
155155
self.flux_values = flux_values
156-
# TODO: zeptat se Lukase (podle jeho kodu)
157-
# self.mat_A = (self.n_phases * self.n_ppairs / 4) * (
158-
# self.mat_crossc @ self.L_stat + self.L_stat @ self.mat_crossc.T
159-
# )
160156

161157
dim = self.n_phases - 1
162158
dummy_vec_curr_dq = np.zeros(dim)

‎current_setpoints/optimization/grid.py‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,7 @@ def get_correction_grid(
227227
neural_model: torch.nn.Module,
228228
scaler: Any,
229229
device: torch.device,
230+
machine: BaseMachine,
230231
) -> Dict[str, Any]:
231232
"""
232233
Computes the correction grid by predicting torque using the neural model
@@ -237,9 +238,7 @@ def get_correction_grid(
237238
neural_model: Trained PyTorch neural network for torque prediction.
238239
scaler: The scaler used to normalize inputs for the neural model.
239240
device: CPU or CUDA device.
240-
241-
Returns:
242-
Dict: A copy of the baseline grid, appended with the 'grid_torq_neural' matrix.
241+
machine: The machine instance to fetch dynamic B_tensors.
243242
"""
244243
print("Computing Phase-Agnostic ML Correction Grid...")
245244

@@ -248,7 +247,6 @@ def get_correction_grid(
248247
}
249248

250249
dim, n_torq, n_omega = dict_grid_corr["curr_dq_grid"].shape
251-
252250
grid_torq_neural = np.full((n_torq, n_omega), np.nan)
253251

254252
omega_2d = np.tile(dict_grid_corr["vec_omega"], (n_torq, 1))
@@ -263,12 +261,18 @@ def get_correction_grid(
263261
curr_valid = curr_flat[:, valid_mask]
264262

265263
X_in = np.vstack([omega_valid, curr_valid]).T
266-
267264
X_scaled = scaler.transform(X_in)
268265
X_tensor = torch.from_numpy(X_scaled).float().to(device)
269266

267+
b_vecs = []
268+
for i in range(len(omega_valid)):
269+
machine.update_state(omega=omega_valid[i], vec_curr_dq=curr_valid[:, i])
270+
b_vecs.append(machine.vec_b)
271+
272+
B_tensor = torch.from_numpy(np.array(b_vecs)).float().to(device).unsqueeze(-1)
273+
270274
with torch.no_grad():
271-
preds = neural_model(X_tensor).cpu().numpy().flatten()
275+
preds = neural_model(X_tensor, B_tensor).cpu().numpy().flatten()
272276

273277
torq_neural_flat = np.full(n_torq * n_omega, np.nan)
274278
torq_neural_flat[valid_mask] = preds

‎current_setpoints/optimization/optimizer.py‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,16 +37,23 @@ def _get_base_constraints(self, transform: Any) -> List[Dict[str, Any]]:
3737
Returns:
3838
List[Dict]: Scipy-compatible constraint definitions.
3939
"""
40+
41+
def safe_current_constraint(vec_curr_dq):
42+
self.model.machine.update_state(transform.omega, vec_curr_dq)
43+
return current_constraint(vec_curr_dq, self.model.machine, transform)
44+
45+
def safe_voltage_constraint(vec_curr_dq):
46+
self.model.machine.update_state(transform.omega, vec_curr_dq)
47+
return voltage_constraint(vec_curr_dq, self.model.machine, transform)
48+
4049
return [
4150
{
4251
"type": "ineq",
43-
"fun": current_constraint,
44-
"args": (self.model.machine, transform),
52+
"fun": safe_current_constraint,
4553
},
4654
{
4755
"type": "ineq",
48-
"fun": voltage_constraint,
49-
"args": (self.model.machine, transform),
56+
"fun": safe_voltage_constraint,
5057
},
5158
]
5259

‎current_setpoints/utils/plotting.py‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,12 @@
88
from .plot_config import PlotConfig
99

1010

11-
def plot_grid_segments(data_obj: Any, machine: Optional[BaseMachine] = None) -> None:
11+
def plot_grid_segments(
12+
data_obj: Any,
13+
title: str = "Segments Overview",
14+
machine: Optional[BaseMachine] = None,
15+
override_torq_2d: Optional[np.ndarray] = None,
16+
) -> None:
1217
"""
1318
Plots the motor operating regions.
1419
Expects data_obj to be the MachineData instance generated by grid_to_data.
@@ -18,15 +23,19 @@ def plot_grid_segments(data_obj: Any, machine: Optional[BaseMachine] = None) ->
1823

1924
with plt.rc_context(PlotConfig.get_rc_params()):
2025
fig, ax = plt.subplots(figsize=(8, 6))
21-
ax.set_title("Segments Overview")
26+
ax.set_title(title)
2227

2328
omega_rpm = data_obj.omega
2429
vec_torq = data_obj.torq
2530

2631
ax.set_xlabel("Speed [r/min]")
2732
ax.set_ylabel("Torque [Nm]")
2833

29-
omega_2d, torq_2d = np.meshgrid(omega_rpm, vec_torq)
34+
omega_2d, default_torq_2d = np.meshgrid(omega_rpm, vec_torq)
35+
36+
# Use the override array if provided, otherwise default to commanded torque
37+
torq_2d = override_torq_2d if override_torq_2d is not None else default_torq_2d
38+
3039
modes_valid = data_obj.segments
3140

3241
valid_mask = ~np.isnan(modes_valid)
@@ -188,7 +197,9 @@ def plot_residual_torque_error(dict_grid: Dict[str, Any], machine: BaseMachine)
188197

189198

190199
def plot_current_trajectories_split(
191-
dict_grid_base: Dict[str, Any], dict_grid_recalc: Dict[str, Any], machine: BaseMachine
200+
dict_grid_base: Dict[str, Any],
201+
dict_grid_recalc: Dict[str, Any],
202+
machine: BaseMachine,
192203
) -> None:
193204
colors_map = PlotConfig.get_colors()
194205
labels_map = PlotConfig.get_labels()
@@ -253,7 +264,9 @@ def plot_grid_onto_ax(ax, dict_grid, d_idx, q_idx):
253264

254265

255266
def plot_joule_losses_reduction(
256-
dict_grid_base: Dict[str, Any], dict_grid_recalc: Dict[str, Any], machine: BaseMachine
267+
dict_grid_base: Dict[str, Any],
268+
dict_grid_recalc: Dict[str, Any],
269+
machine: BaseMachine,
257270
) -> None:
258271
omega_rpm = dict_grid_recalc["vec_omega"] * dict_grid_recalc.get(
259272
"const_mech_speed", 30 / (np.pi * machine.n_ppairs)

‎notebooks/main.ipynb‎

Lines changed: 225 additions & 37 deletions
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)