pyfemtet.opt package

Subpackages

Submodules

Module contents

class pyfemtet.opt.FEMOpt(fem=None, opt=None)[source]

Bases: object

A class to manage finite element method (FEM) optimization using a specified optimizer and FEM interface.

opt

The optimizer instance to be used for optimization.

Type:

AbstractOptimizer

monitor_info

Dictionary to store monitoring information such as host and port.

Type:

dict[str, str | int | None]

Parameters:
  • fem (AbstractFEMInterface, optional) – An instance of a FEM interface. Defaults to None, in which case a FemtetInterface is used.

  • opt (AbstractOptimizer, optional) – An optimizer instance. Defaults to None, in which case OptunaOptimizer is used.

add_categorical_parameter(name, initial_value=None, choices=None, properties=None, *, pass_to_fem=True, fix=False)[source]
Parameters:
Return type:

None

add_constant_value(name, value, properties=None, *, pass_to_fem=True)[source]
Parameters:
add_constraint(name, fun, lower_bound=None, upper_bound=None, args=None, kwargs=None, strict=True, using_fem=None)[source]
Parameters:
add_expression(name, fun, properties=None, args=None, kwargs=None, *, pass_to_fem=True)[source]
Parameters:
Return type:

None

add_expression_string(name, expression_string, properties=None, *, pass_to_fem=True)[source]
Parameters:
  • name (str) –

  • expression_string (str) –

  • properties (dict[str, ...] | None) –

  • pass_to_fem (bool) –

Return type:

None

add_expression_sympy(name, sympy_expr, properties=None, *, pass_to_fem=True)[source]
Parameters:
  • name (str) –

  • sympy_expr (Expr) –

  • properties (dict[str, ...] | None) –

  • pass_to_fem (bool) –

Return type:

None

add_fem(fem)[source]
Parameters:

fem (AbstractFEMInterface) –

Return type:

OptimizationDataPerFEM

add_objective(name, fun, direction='minimize', args=None, kwargs=None)[source]
Parameters:
Return type:

None

add_objectives(names, fun, n_return, directions=None, args=None, kwargs=None)[source]
Parameters:
add_other_output(name, fun, args=None, kwargs=None)[source]
Parameters:
add_parameter(name, initial_value=None, lower_bound=None, upper_bound=None, step=None, properties=None, *, pass_to_fem=True, fix=False)[source]
Parameters:
  • name (str) –

  • initial_value (float | None) –

  • lower_bound (float | None) –

  • upper_bound (float | None) –

  • step (float | None) –

  • properties (dict[str, ...] | None) –

  • pass_to_fem (bool) –

  • fix (bool) –

Return type:

None

add_sub_fidelity_model(name, sub_fidelity_model, fidelity)[source]
Parameters:
add_trial(parameters)[source]
Parameters:

parameters (dict[str, str | Real]) –

opt: AbstractOptimizer
optimize(n_trials=None, n_parallel=1, timeout=None, wait_setup=True, confirm_before_exit=True, history_path=None, with_monitor=True, scheduler_address=None, seed=None)[source]
Parameters:
  • n_trials (int | None) –

  • n_parallel (int) –

  • timeout (float | None) –

  • wait_setup (bool) –

  • confirm_before_exit (bool) –

  • history_path (str | None) –

  • with_monitor (bool) –

  • scheduler_address (str | None) –

  • seed (int | None) –

set_monitor_host(host=None, port=None)[source]

Sets the host IP address and the port of the process monitor.

Parameters:
  • host (str) – The hostname or IP address of the monitor server.

  • port (int, optional) – The port number of the monitor server. If None, 8080 will be used. Defaults to None.

Tip

Specifying host 0.0.0.0 allows viewing monitor from all computers on the local network.

If no hostname is specified, the monitor server will be hosted on localhost.

We can access process monitor by accessing `localhost:8080` on our browser by default.

set_random_seed(seed)[source]
Parameters:

seed (int) –

set_termination_condition(func)[source]
Parameters:

func (Callable[[History], bool] | None) –

class pyfemtet.opt.FemtetInterface(femprj_path=None, model_name=None, connect_method='auto', save_pdt='all', strictly_pid_specify=True, allow_without_project=False, open_result_with_gui=True, always_open_copy=False, parametric_output_indexes_use_as_objective=None)[source]

Bases: COMInterface

Control Femtet from optimizer.

Parameters:
  • femprj_path (str, optional) – The path to the project file. If not specified, get it from connected Femtet.

  • model_name (str, optional) – The name of the model. If not specified, get it from connected Femtet or the first model when Femtet open the project file.

  • connect_method (str, optional) – The connection method. Default is ‘auto’. Other valid values are ‘new’ or ‘existing’.

  • save_pdt (str, optional) – The type to save result file. Valid values are ‘all’, ‘none’ or ‘optimal’. Default is ‘all’.

  • strictly_pid_specify (bool, optional) – Whether to strictly specify the PID in Femtet connection. Default is True.

  • allow_without_project (bool, optional) – Whether to allow without a project. Default is False.

  • open_result_with_gui (bool, optional) – Whether to open the result with GUI. Default is True.

  • parametric_output_indexes_use_as_objective (dict[int, str or float], optional) –

    A list of parametric output indexes and its direction to use as the objective function. If not specified, it will be None and no parametric outputs are used as objectives.

    Note

    Indexes start at 0, but the parametric analysis output settings in the Femtet dialog box indicate setting numbers starting at 1.

    Warning

    Setting this argument deletes the parametric analysis swept table set in the femprj file. If you do not want to delete the swept table, make a copy of the original file.

Warning

Even if you specify strictly_pid_specify=True on the constructor, the connection behavior is like strictly_pid_specify=False in parallel processing because of its large overhead. So you should close all Femtet processes before running FEMOpt.optimize() if n_parallel >= 2.

Tip

If you search for information about the method to connect python and Femtet, see connect_femtet().

close(timeout=15, force=True)[source]

Destructor.

May not quit Femtet. If you want to quit certainly, Please use quit() method.

com_members = {'Femtet': 'FemtetMacro.Femtet'}
connect_femtet(connect_method='auto', pid=None)[source]

Connects to a Femtet process.

Parameters:
  • connect_method (str, optional) – The connection method. Can be ‘new’, ‘existing’, or ‘auto’. Defaults to ‘auto’.

  • pid (int or None, optional) – The process ID of an existing Femtet process and wanted to connect.

Note

When connect_method is ‘new’, starts a new Femtet process and connects to it. pid will be ignored.

Note

When ‘existing’, connect to an existing Femtet process. However, if there are no Femtets to which it can connect (i.e. already connected to another Python or Excel process), it throws an exception.

Note

When set to ‘auto’, first tries ‘existing’, and if that fails, connects with ‘new’. If pid is specified and failed to connect, it will not try existing another Femtet process.

femtet_is_alive()[source]

Returns connected femtet process is existing or not.

Return type:

bool

load_objectives(*args, **kwargs)
property object_pass_to_fun

The object pass to the first argument of user-defined objective functions.

Returns:

COM object of Femtet.

Return type:

Femtet (CDispatch)

open(femprj_path, model_name=None)[source]

Open specific analysis model with connected Femtet.

Parameters:
  • femprj_path (str) –

  • model_name (str | None) –

Return type:

None

postprocess(*args, **kwargs)
preprocess(*args, **kwargs)
quit(timeout=15, force=True)[source]

Force to terminate connected Femtet.

reopen()[source]
solve(*args, **kwargs)
update(*args, **kwargs)
update_model(*args, **kwargs)
update_parameter(*args, **kwargs)
use_parametric_output_as_objective(number, direction='minimize')[source]

Use output setting of Femtet parametric analysis as an objective function.

Parameters:
  • number (int) – The index of output settings tab in parametric analysis dialog of Femtet. Starts at 1.

  • direction (str | float) – Objective direction. Valid input is one of ‘minimize’, ‘maximize’ or a specific value. Defaults to ‘minimize’.

Returns:

None

Return type:

None

class pyfemtet.opt.FemtetWithNXInterface(prt_path, femprj_path=None, model_name=None, connect_method='auto', save_pdt='all', strictly_pid_specify=True, allow_without_project=False, open_result_with_gui=True, parametric_output_indexes_use_as_objective=None, always_open_copy=False, export_curves=None, export_surfaces=None, export_solids=None, export_flattened_assembly=None)[source]

Bases: FemtetInterface, _NXInterface

Control Femtet and NX.

Using this class, you can import CAD files created in NX through the Parasolid format into a Femtet project. It allows you to pass design variables to NX, update the model, and perform analysis using the updated model in Femtet.

Parameters:
  • prt_path (str) – The path to .prt file containing the CAD data from which the import is made.

  • export_curves (bool or None, optional) – Defaults to None.

  • export_surfaces (bool or None, optional) – Defaults to None.

  • export_solids (bool or None, optional) – Defaults to None.

  • export_flattened_assembly (bool or None, optional) – Defaults to None.

  • femprj_path (str) –

  • model_name (str) –

  • connect_method (str) –

  • save_pdt (str) –

  • strictly_pid_specify (bool) –

  • allow_without_project (bool) –

  • open_result_with_gui (bool) –

  • parametric_output_indexes_use_as_objective (dict[int, str | float]) –

Notes

`export_*` arguments sets parasolid export setting of NX. If None, PyFemtet does not change the current setting of NX.

It is recommended not to change these values from the settings used when exporting the Parasolid that was imported into Femtet.

update_model()[source]
class pyfemtet.opt.FemtetWithSolidworksInterface(sldprt_path, femprj_path=None, model_name=None, connect_method='auto', save_pdt='all', strictly_pid_specify=True, allow_without_project=False, open_result_with_gui=True, parametric_output_indexes_use_as_objective=None, always_open_copy=False, close_solidworks_on_terminate=False, solidworks_visible=True)[source]

Bases: FemtetInterface, SolidworksInterface, AbstractFEMInterface

Interface class integrating Femtet and SolidWorks operations.

This class combines the capabilities of both Femtet and SolidWorks interfaces, allowing coordinated operation between simulation (Femtet) and CAD manipulation (SolidWorks).

Parameters:
  • sldprt_path (str) – Path to the SolidWorks part file (.sldprt).

  • femprj_path (str, optional) – Path to the Femtet project file (.femprj). Defaults to None.

  • model_name (str, optional) – Name of the model in the project. Defaults to None.

  • connect_method (str, optional) – Connection method for Femtet. Defaults to “auto”.

  • save_pdt (str, optional) – Specifies which data to save. Defaults to “all”.

  • strictly_pid_specify (bool, optional) – Whether to strictly specify parameter IDs. Defaults to True.

  • allow_without_project (bool, optional) – If True, allows operation without a project file. Defaults to False.

  • open_result_with_gui (bool, optional) – If True, open results with GUI. Defaults to True.

  • parametric_output_indexes_use_as_objective (dict[int, str | float], optional) – Indexes for parametric output used as objectives. Defaults to None.

  • always_open_copy (bool, optional) – If True, always open a copy of the project. Defaults to False.

  • close_solidworks_on_terminate (bool, optional) – If True, SolidWorks will close when this object is destroyed. Defaults to False.

  • solidworks_visible (bool, optional) – If True, SolidWorks will be started in visible mode. Defaults to True.

close(timeout=15, force=True)[source]

Destructor.

May not quit Femtet. If you want to quit certainly, Please use quit() method.

update_model()[source]

Update .sldprt

update_parameter(x, with_warning=False)[source]
Parameters:

x (dict[str, Variable]) –

Return type:

None

class pyfemtet.opt.OptunaOptimizer(sampler_class=None, sampler_kwargs=None)[source]

Bases: AbstractOptimizer

An optimizer class utilizing Optuna for hyperparameter optimization.

This class provides an interface to conduct optimization studies using Optuna. It manages the study lifecycle, sampler configuration, and trial execution.

study_name

Name of the Optuna study.

Type:

str

storage

Storage URL or object for the Optuna study.

Type:

str | optuna.storages.BaseStorage

storage_path

Path to the Optuna study storage.

Type:

str

current_trial

The current Optuna trial being evaluated.

Type:

optuna.trial.Trial | None

sampler_class

The class of the Optuna sampler to use.

Type:

type[optuna.samplers.BaseSampler]

sampler_kwargs

Keyword arguments to initialize the sampler.

Type:

dict

n_trials

Number of trials to run in the study.

Type:

int | None

timeout

Maximum time allowed for the optimization.

Type:

float | None

callbacks

List of callback functions to invoke during optimization.

Type:

list

Parameters:
  • sampler_class (type[optuna.samplers.BaseSampler], optional) – The sampler class for suggesting parameter values. Defaults to TPESampler if None.

  • sampler_kwargs (dict[str, ...], optional) – Dictionary of keyword arguments for the sampler. Defaults to an empty dictionary.

Raises:

None

Examples

>>> optimizer = OptunaOptimizer()
>>> optimizer.n_trials = 100
>>> optimizer.timeout = 600
>>> # Further configuration and usage...
add_categorical_parameter(name, initial_value, choices, properties=None, *, pass_to_fem=True, fix=False)[source]
Parameters:
Return type:

None

add_parameter(name, initial_value, lower_bound=None, upper_bound=None, step=None, properties=None, *, pass_to_fem=True, fix=False)[source]
Parameters:
  • name (str) –

  • initial_value (float) –

  • lower_bound (float | None) –

  • upper_bound (float | None) –

  • step (float | None) –

  • properties (dict[str, ...] | None) –

  • pass_to_fem (bool) –

  • fix (bool) –

Return type:

None

callbacks: list
current_trial: optuna.trial.Trial | None
n_trials: int | None
run()[source]
sampler_class: type[optuna.samplers.BaseSampler]
sampler_kwargs: dict
storage: str | optuna.storages.BaseStorage
storage_path: str
study_name = 'pyfemtet-study'
timeout: float | None
class pyfemtet.opt.ScipyOptimizer(method=None, tol=None)[source]

Bases: AbstractOptimizer

Optimizer class that utilizes SciPy optimization methods.

This class serves as a wrapper around SciPy’s optimization routines, allowing customization of the optimization method, tolerance, and options. It also provides mechanisms for handling constraints with enhancement and scaling.

method

The optimization method to use (e.g., ‘BFGS’, ‘Nelder-Mead’).

Type:

str

tol

Tolerance for termination.

Type:

float or None

options

Additional options to pass to the SciPy optimizer.

Type:

dict

constraint_enhancement

Small value added to enhance constraint handling.

Type:

float

constraint_scaling

Scaling factor applied to constraints.

Type:

float

Parameters:
  • method (str) – The optimization method to use (e.g., ‘BFGS’, ‘Nelder-Mead’).

  • tol (float or None) – Tolerance for termination.

add_sub_fidelity_model(name, sub_fidelity_model, fidelity)[source]
Parameters:
add_trial(parameters)[source]
Parameters:

parameters (dict[str, str | Real]) –

run()[source]