motulator_gradnet#

Training of gradient networks (GradNets) for the magnetic models of motulator.

GradNets model the current and flux linkage maps of synchronous machines, including spatial harmonics, learned from measured or finite-element data [1]. A GradNet is the gradient of a scalar state function, the magnetic energy or co-energy, so the map is a conservative vector field by construction [2], and the monotonicity of the flux-linkage–current map is also ensured. The networks are defined and trained with PyTorch (GradNet, train_gradnet). A trained network is saved as the numpy function motulator.drive.gradnet.GradNetFunction, which the magnetic maps of motulator (e.g., motulator.drive.gradnet.FluxMap) evaluate without PyTorch. The trained maps are compared with the data using the plotting and error functions.

References

Classes#

AlgebraicSigmoid

Sigmoid-type activation function with one learnable parameter.

GradNet

Modular and monotone gradient network.

PNormGradient

p-norm gradient activation function.

PlotOptions

Options for plotting functions.

Softmax

Softmax activation function.

Squareplus

Rectifier-type activation function with one learnable parameter.

Functions#

get_training_data(dataset_path, base[, subsample, ...])

Get the training and validation data used by the model.

plot_output_vs_angle(fixed_value, theta_m_range, map_fcn)

Plot torque or flux linkage as a function of angle at a fixed input.

plot_surface_vs_current_and_angle(current_range, ...)

Plot selected output component vs selected input component over angle.

print_current_map_errors_meas(current_map, data[, base])

Print error metrics for a measured current map.

print_flux_map_errors_meas(flux_map, data[, base])

Print error metrics for a measured flux map.

to_function(model)

Convert a trained model to the numpy function of motulator.

train_gradnet(dataset_path, base[, is_flux_map, k, ...])

Train and save the GradNet model.

Package Contents#

class motulator_gradnet.AlgebraicSigmoid(beta_log0=-3.0)[source]#

Bases: torch.nn.Module

Sigmoid-type activation function with one learnable parameter.

Parameters:

beta_log0 (float)

class motulator_gradnet.GradNet(in_dim=2, mu_dim=2, num_modules=1, embed_dim=12, activation=Softmax, mu_log0=1.0, psi_base=1.0, i_base=1.0)[source]#

Bases: torch.nn.Module

Modular and monotone gradient network.

Parameters:
  • in_dim (int, optional) – Input dimension, defaults to 2.

  • mu_dim (int, optional) – Dimension of the linear term, defaults to 2.

  • num_modules (int, optional) – Number of GradNet modules, defaults to 1.

  • embed_dim (int, optional) – Embedding dimension for the GradNet modules, defaults to 12.

  • activation (Callable[[], nn.Module], optional) – Activation factory used by GradNet modules, defaults to Softmax.

  • mu_log0 (float, optional) – Initial value for the linear term coefficients in log-domain, defaults to 1.0.

  • psi_base (float, optional) – Base value of the flux linkage (Vs), defaults to 1.0. The network operates in per-unit quantities. The base values are stored in the model and used by the maps of motulator (e.g., ~motulator.drive.gradnet.CurrentMap) to convert between SI units and per-unit quantities.

  • i_base (float, optional) – Base value of the current (A), defaults to 1.0.

class motulator_gradnet.PNormGradient(dim=-1, p=8, beta_log0=0.0, freeze_beta=False)[source]#

Bases: torch.nn.Module

p-norm gradient activation function.

Defined as the gradient of S(z) = (1 + sum((beta*z_n)**p))**(1/p)/beta, where p is a positive even integer. This potential function corresponds to a smooth p-norm, which is convex, thus guaranteeing monotonicity.

Parameters:
class motulator_gradnet.PlotOptions[source]#

Options for plotting functions.

Parameters:
  • base (BaseValues | None, optional) – Base values for per-unit conversion. If None, SI values are used.

  • lims (dict[str, tuple[float, float]] | None, optional) – Axis limits as {‘x’: (xmin, xmax), ‘y’: (ymin, ymax)}.

  • ticks (dict[str, list[float]] | None, optional) – Axis ticks as {‘x’: [x1, x2, …], ‘y’: [y1, y2, …]}.

  • surface_cmap (str, optional) – Colormap for the surface plot, defaults to “viridis”.

  • latex (bool, optional) – Use LaTeX fonts if True, defaults to False.

  • save_path (str | Path | None, optional) – Path to save the figure. If None, the figure is not saved.

  • savefig_kwargs (Dict[str, Any], optional) – Additional keyword arguments passed to plt.savefig().

  • loci_levels_source ({"ticks", "val", "trn"}, optional) – Source for constant-loci levels in plot_surface_vs_current_and_angle() when plotting over current and angle. If “ticks”, uses ticks[“x”]/ticks[“y”] (with lims/fallback defaults). If “val” or “trn”, uses unique x/y values present in the corresponding point cloud slice.

class motulator_gradnet.Softmax(dim=-1, beta_log0=2.0, freeze_beta=False)[source]#

Bases: torch.nn.Module

Softmax activation function.

Parameters:
class motulator_gradnet.Squareplus(beta_log0=-2.0)[source]#

Bases: torch.nn.Module

Rectifier-type activation function with one learnable parameter.

Parameters:

beta_log0 (float)

motulator_gradnet.get_training_data(dataset_path, base, subsample=1, other_keys=None)[source]#

Get the training and validation data used by the model.

This function re-instantiates the dataset with the same parameters to reproduce the training set. Validation data is the set difference (complement).

Parameters:
  • dataset_path (str) – Path to the npz file containing the dataset.

  • base (BaseValues) – Base values of the target machine. They are only needed to re-instantiate the dataset; the returned data are not normalized.

  • subsample (int, optional) – Subsampling rate used in the training, defaults to 1 (no subsampling).

  • other_keys (list[str] | None, optional) – Additional fields of the npz file to be returned after the flux linkage and current, defaults to None (no additional fields).

Returns:

((train_psi, train_i, …), (val_psi, val_i, …)), where the arrays are flattened and in the units of the npz file.

Return type:

tuple

motulator_gradnet.plot_output_vs_angle(fixed_value, theta_m_range, map_fcn, output='tau_m', input_type='i_s_dq', val_data=None, trn_data=None, opts=None)[source]#

Plot torque or flux linkage as a function of angle at a fixed input.

Parameters:
  • fixed_value (complex) – Fixed complex input value (e.g., i_s_dq or psi_s_dq).

  • theta_m_range (np.ndarray) – Electrical rotor angle range (rad).

  • map_fcn (Callable) – Flux or current map function with harmonics.

  • output ({"psi_d", "psi_q", "tau_m"}, optional) – Output quantity to plot, defaults to “tau_m”.

  • input_type ({"i_s_dq", "psi_s_dq"}, optional) – Type of the fixed input value, defaults to “i_s_dq”.

  • val_data (tuple, optional) – Validation data tuple containing (psi_s_dq, i_s_dq, theta_m, tau_m).

  • trn_data (tuple, optional) – Training data tuple containing (psi_s_dq, i_s_dq, theta_m, tau_m).

  • opts (PlotOptions, optional) – Plotting options.

Return type:

None

motulator_gradnet.plot_surface_vs_current_and_angle(current_range, fixed_value, theta_m_range, map_fcn, input='i_q', output='tau_m', val_data=None, trn_data=None, opts=None)[source]#

Plot selected output component vs selected input component over angle.

Parameters:
  • current_range (np.ndarray) – Range of input values to vary.

  • fixed_value (float) – Fixed input value for the other axis.

  • theta_m_range (np.ndarray) – Electrical rotor angle range (rad).

  • map_fcn (Callable) – Flux or current map function with harmonics.

  • input ({"i_d", "i_q", "psi_d", "psi_q"}, optional) – Input axis to vary, defaults to “i_q”.

  • output ({"psi_d", "psi_q", "tau_m", "i_d", "i_q"}, optional) – Output quantity to plot, defaults to “tau_m”.

  • val_data (tuple, optional) – Validation data tuple containing (psi_s_dq, i_s_dq, theta_m, tau_m).

  • trn_data (tuple, optional) – Training data tuple containing (psi_s_dq, i_s_dq, theta_m, tau_m).

  • opts (PlotOptions, optional) – Plotting options.

Return type:

None

motulator_gradnet.print_current_map_errors_meas(current_map, data, base=None)[source]#

Print error metrics for a measured current map.

Parameters:

base (motulator.drive.utils.BaseValues | None)

Return type:

None

motulator_gradnet.print_flux_map_errors_meas(flux_map, data, base=None)[source]#

Print error metrics for a measured flux map.

Parameters:

base (motulator.drive.utils.BaseValues | None)

Return type:

None

motulator_gradnet.to_function(model)[source]#

Convert a trained model to the numpy function of motulator.

The modules of the model must have the same activation, one of ACTIVATIONS applied along the last axis (the default), with the same exponent p. The function is evaluated in double precision. It is saved to an npz file by its method save and loaded by motulator.drive.gradnet.load_gradnet.

Parameters:

model (GradNet) – Trained model.

Returns:

The model as a numpy function.

Return type:

GradNetFunction

motulator_gradnet.train_gradnet(dataset_path, base, is_flux_map=False, k=None, num_modules=1, embed_dim=12, batch_size=128, epochs=2000, lr=0.001, save_model_path=None, subsample=1, activation=None, device=None, *, i_low=0.0, weight_low=1.0)[source]#

Train and save the GradNet model.

Parameters:
  • dataset_path (str | Path) – Path to the training data file (npz format).

  • base (BaseValues) – Base values of the target machine. The training data are normalized with the base current and flux linkage, which are also stored in the model.

  • is_flux_map (bool, optional) – Whether the model is a flux map or current map, defaults to False.

  • k (int | None, optional) – Spatial harmonics order. If None, no harmonics are used, defaults to None.

  • num_modules (int, optional) – Number of GradNet modules, defaults to 1.

  • embed_dim (int, optional) – Embedding dimension for the GradNet modules, defaults to 12.

  • batch_size (int, optional) – Batch size for training, defaults to 128.

  • epochs (int, optional) – Number of training epochs, defaults to 2000.

  • lr (float, optional) – Learning rate for the optimizer, defaults to 1e-3.

  • save_model_path (str | Path | None, optional) – Path to save the trained model as an npz file (see to_function). If None, saves to model.npz in current directory.

  • subsample (int, optional) – Subsampling factor for the training data, defaults to 1 (uses all data).

  • activation (Callable[[], torch.nn.Module] | None, optional) – Activation function factory, defaults to PNormGradient. The trained model is saved as a numpy function, which supports the activations in ACTIVATIONS.

  • device (torch.device | None, optional) – Device to use for training. If None, automatically selects CUDA if available, otherwise CPU.

  • i_low (float, optional) – Current limit (A, peak value) defining the low-current region, defaults to 0.

  • weight_low (float, optional) – Loss weight of the data points whose current magnitude is below i_low, defaults to 1 (unweighted loss). The low-current region is determined by the current of the data point for both flux and current maps. A weight above 1 improves the accuracy at low currents, where a uniform data grid gives only a few points. The weights are normalized with their mean over the training set, so the loss of each batch is an unbiased estimate of the weighted loss of the whole set, which corresponds to repeating those points weight_low times in the dataset, except that the number of steps per epoch is unchanged.

Return type:

None