API Reference

PyMAD-NG Module contents

class pymadng.MAD(mad_path: str | Path | None = None, py_name: str = 'py', raise_on_madng_error: bool = True, debug: bool = False, stdout: TextIO | str | Path | None = None, redirect_stderr: bool = False, num_temp_vars: int = 8, ipython_use_jedi: bool = False)

Bases: object

An object that allows communication with MAD-NG

py_name

A string indicating the name of the reference to python from MAD-NG, for communication from MAD-NG to Python.

__MAD_version__

A string indicating the version of MAD-NG being used. (Also accessible from pymadng.MAD().MAD.env.version)

__init__(mad_path: str | Path | None = None, py_name: str = 'py', raise_on_madng_error: bool = True, debug: bool = False, stdout: TextIO | str | Path | None = None, redirect_stderr: bool = False, num_temp_vars: int = 8, ipython_use_jedi: bool = False)

Initialise a MAD object for communication with MAD-NG.

This constructor starts the MAD subprocess, establishes communication pipes, and imports necessary MAD modules. The mad_path defaults to a bundled executable if not provided.

Parameters:
  • mad_path (str | Path, optional) – Path to the MAD executable.

  • py_name (str, optional) – Name used for MAD-to-Python communication.

  • raise_on_madng_error (bool, optional) – If True, raises errors from MAD-NG immediately.

  • debug (bool, optional) – If True, enables detailed debugging output.

  • stdout (TextIO | str | Path | None, optional) – Destination for MAD-NG’s standard output.

  • redirect_stderr (bool, optional) – If True, redirects stderr to stdout.

  • num_temp_vars (int, optional) – Maximum number of temporary variables to track.

  • ipython_use_jedi (bool, optional) – If True, allows IPython to use jedi for autocompletion.

close()

Close the MAD-NG process and clean up resources.

create_deferred_expression(**kwargs) MadLastRef

Create a deferred expression object in MAD-NG.

The keyword arguments represent deferred expressions using ‘:=’ syntax. Intended for assigning a temporary variable that holds a lazy-evaluated result.

Parameters:

**kwargs – Expression name-value pairs.

Returns:

A reference to the deferred expression.

Return type:

mad_high_level_last_ref

eval(expression: str) Any

Evaluate an expression in the MAD-NG environment.

Parameters:

expression (str) – The expression to evaluate.

Returns:

The result of the evaluated expression.

Return type:

Any

evaluate_in_madx_environment(value: str) None

Execute code in the native MAD-X environment.

Opens a MAD-X environment, sends the code, and then closes the environment.

Parameters:

input (str) – The MAD-X code to execute.

globals() list[str]

Retrieve a list of all global variable names in the MAD-NG environment.

Returns:

A list containing the names of global variables.

Return type:

list[str]

history() str

Retrieve the command history sent to MAD-NG.

Filters out internal error-handling commands.

Returns:

A newline-separated string of historical commands.

Return type:

str

load(module: str, *varnames: str)

Import classes or functions from a specific MAD-NG module.

If no specific names are provided, imports all available members from the module.

Parameters:
  • module (str) – The module name in MAD-NG.

  • *varnames (str) – Optional list of members to import.

loadfile(path: str | Path, *varnames: str)

Load and execute a .mad file in the MAD-NG environment.

If additional variable names are provided, assign each to the corresponding member of the loaded file.

Parameters:
  • path (str | Path) – File path for the .mad file.

  • *vars (str) – Optional names to bind to specific elements from the file.

protected_send(string: str) MAD

Send a command to MAD-NG with error protection.

Temporarily enables error handling so that any command errors in MAD-NG are caught and raised in Python.

Parameters:

string (str) – The MAD-NG command code to send.

Returns:

Self for method chaining.

Return type:

MAD

psend(string: str) MAD

Alias for protected_send

quote_strings(value: str | list[str]) str | list[str]

Surround the provided string or list of strings with single quotes.

Parameters:

value (str or list[str]) – The input string(s) to quote.

Returns:

The quoted string or list of quoted strings.

receive(varname: str | None = None) Any

Alias for the recv method.

Parameters:

varname (str, optional) – Name of the variable to receive.

Returns:

The received data.

recv(varname: str | None = None) Any

Retrieve data from the MAD-NG process.

Reads a data type identifier and then receives the corresponding value from MAD-NG.

Parameters:

varname (str, optional) – Variable name used for clarity when receiving references.

Returns:

The value received from MAD-NG.

recv_and_exec(context: dict = {}) dict

Receive a string from MAD-NG and execute it.

The provided execution context is updated with numpy (np) and the current MAD object.

Parameters:

context (dict, optional) – The environment for executing the received code.

Returns:

The updated execution environment.

Return type:

dict

recv_vars(*names: str, shallow_copy: bool = False) Any

Retrieve one or more variables from MAD-NG.

Parameters:
  • *names (str) – The names of the variables to be fetched from MAD-NG.

  • shallow_copy (bool, optional) – If True, returns a shallow copy of the variables.

Returns:

The retrieved variable value or a tuple of values if multiple names are provided.

send(data: Any) MAD

Send data to MAD-NG.

Accepts various types of data and serialises them for transfer to MAD-NG.

Parameters:

data (str/int/float/np.ndarray/bool/list/dict) – The information to send.

Returns:

Returns self to facilitate method chaining.

Return type:

MAD

send_cpx_tpsa(monos: np.ndarray, coefficients: np.ndarray)

Transmit complex TPSA data to MAD-NG.

Sends complex-valued monomials and coefficients for TPSA table construction.

Parameters:
  • monos (np.ndarray) – 2D array of monomials (unsigned bytes).

  • coefficients (np.ndarray) – Array of complex TPSA coefficients.

send_logrange(start: float, stop: float, size: int)

Send a logarithmic range to MAD-NG.

Generates and sends a logarithmic range equivalent to numpy.geomspace.

Parameters:
  • start (float) – The start value.

  • stop (float) – The stop value.

  • size (int) – The number of points in the range.

send_range(start: float, stop: float, size: int)

Send a linear range to MAD-NG.

Builds a range analogous to numpy.linspace and sends it based on the specified boundaries and size.

Parameters:
  • start (float) – The starting value of the range.

  • stop (float) – The ending value of the range (inclusive).

  • size (int) – The total number of elements in the range.

send_tpsa(monos: np.ndarray, coefficients: np.ndarray)

Transmit TPSA data for processing in MAD-NG.

Sends a two-dimensional array of monomials and the associated coefficient array.

Parameters:
  • monos (np.ndarray) – 2D array containing the monomials.

  • coefficients (np.ndarray) – Array of TPSA coefficients.

send_vars(**varnames: str | int | float | np.ndarray | bool | list)

Send multiple named variables to the MAD-NG process.

Each keyword pair becomes a variable in the MAD-NG environment.

Parameters:

**vars – Key-value pairs representing variable names and their values.

Useful functions for MAD References

pymadng.madp_classes.MadObject.convert_to_dataframe(self, columns: list | None = None, force_pandas: bool = False)

Converts the object to a pandas dataframe.

Parameters:
  • columns (list, optional) – List of columns to include in the dataframe. Defaults to None.

  • force_pandas (bool, optional) – If True, always use pandas.DataFrame. Defaults to False.

Returns:

The dataframe containing the object’s data.

Return type:

pandas.DataFrame or tfs.TfsDataFrame

pymadng.madp_classes.MadObject.to_df(self, columns: list | None = None, force_pandas: bool = False)

See convert_to_dataframe