Skip to content

Commit 81f72af

Browse files
jgray-19Copilot
andauthored
Update documentation (#17)
* Update documentation * Update docs/source/debugging.md Co-authored-by: Copilot <[email protected]> * Update docs/source/architecture.md Co-authored-by: Copilot <[email protected]> * Fix incorrect repository name everywhere --------- Co-authored-by: Copilot <[email protected]>
1 parent 38570df commit 81f72af

33 files changed

+2280
-804
lines changed

CHANGELOG.md

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
0.7.0 (2024/12/05)
2+
3+
Rewrite documentation
4+
Update to MAD-NG 1.1.1
5+
Handle opening and closing of MAD-NG process more robustly
6+
7+
18
0.6.0 (2024/12/05)
29
Remove `debug` input variable functionality, now it is only a boolean, and dictates whether the debug information is printed to the console. \
310
Add `stdout` input to the `MAD` object, this allows the user to redirect the output of the MAD-NG process to a file. \
@@ -53,7 +60,7 @@ Set pymadng to now be in beta.
5360
Fix MADX issue
5461
Move binaries to the bin folder \
5562
Update MAD-NG binaries \
56-
Rename files to start with madp_... \
63+
Rename files to start with madp\_... \
5764
Completely refactor underlying process and remove reliance on mad objects, mad strings and `__last__`, now the process is completely self contained and can be separated into MAD-NG itself.
5865

5966
List of changes to PyMAD-NG
@@ -70,4 +77,4 @@ Update MAD-NG binaries
7077

7178
Update MAD-NG binaries \
7279
Fix bug with negative integer values \
73-
Initialise CHANGELOG
80+
Initialise CHANGELOG

README.md

Lines changed: 88 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,100 @@
1-
# pymadng
2-
Python interface to MAD-NG running as subprocess
1+
# PyMAD-NG
32

4-
Install using below, see [The Python Package Index (PyPi)](https://pypi.org/project/pymadng/);
3+
**Python interface to MAD-NG running as a subprocess**
54

6-
`pip install pymadng`
5+
[![PyPI version](https://img.shields.io/pypi/v/pymadng.svg)](https://pypi.org/project/pymadng/)
6+
[![Documentation Status](https://readthedocs.org/projects/pymadng/badge/?version=latest)](https://pymadng.readthedocs.io/en/latest/)
7+
[![License](https://img.shields.io/github/license/MethodicalAcceleratorDesign/MAD-NG.py)](https://github.com/MethodicalAcceleratorDesign/MAD-NG.py/blob/main/LICENSE)
78

8-
Familiarising yourself with pymadng
9-
===================================
9+
---
1010

11-
First, we recommend familiarising yourself with MAD-NG, documentation can be found [here](https://madx.web.cern.ch/releases/madng/html/).
11+
## 🚀 Installation
1212

13-
Then reading through the Low-Level Example Explained on the [pymadng documentation](https://pymadng.readthedocs.io/en/latest/) should be sufficient (alongside knowledge of MAD-NG), assuming you are not planning to use any "syntactic sugar". If you plan to use the available pythonic looking code, there are plenty of examples to look at.
13+
Install via pip from [PyPI](https://pypi.org/project/pymadng/):
1414

15-
In the documentation, [FODO Examples Explained](https://pymadng.readthedocs.io/en/latest/ex-fodo.html), is a chapter that goes into detail on what is happening on each line of the [FODO example](https://github.com/MethodicalAcceleratorDesign/MADpy/blob/main/examples/ex-fodo/ex-fodos.py), while [LHC Example](https://pymadng.readthedocs.io/en/latest/ex-lhc-couplingLocal.html) gives an example of loading the LHC and how to grab intermediate results from a match.
15+
```bash
16+
pip install pymadng
17+
```
1618

17-
The only other example that may be of use is the [ps-twiss](https://github.com/MethodicalAcceleratorDesign/MADpy/blob/main/examples/ex-ps-twiss/ps-twiss.py) example. This is an extremely simple example, extending the FODO example to perform a twiss on the PS sequence.
18-
If anything does not seem fully explained, initially check the [API Reference](https://pymadng.readthedocs.io/en/latest/pymadng.html#module-pymadng) and/or the [MAD-NG Documentation](https://mad.web.cern.ch/mad/releases/madng/html/), then feel free to open an [issue](https://github.com/MethodicalAcceleratorDesign/MADpy/issues) so improvements can be made.
19+
---
1920

20-
Documentation
21-
=============
21+
## 🧠 Getting Started
2222

23-
Documentation, including explanation of a couple of examples and the limitations of the API can be found [here](https://pymadng.readthedocs.io/en/latest/).
23+
Before diving into PyMAD-NG, we recommend you:
2424

25-
The API reference is also included in [this documentation](https://pymadng.readthedocs.io/en/latest/). You can also compile to documentation yourself by cloning the repository and running ``make html`` in the docs folder.
25+
1. Familiarise yourself with [MAD-NG](https://madx.web.cern.ch/releases/madng/html/) — understanding MAD-NG is essential.
26+
2. Read the [Quick Start Guide](https://pymadng.readthedocs.io/en/latest/) to see how to control MAD-NG from Python.
2627

27-
Getting the examples working
28-
============================
28+
### Explore Key Examples
2929

30-
You can run the example with `python3 EXAMPLE_NAME.py`
30+
- **[Low-Level Example Explained](https://pymadng.readthedocs.io/en/latest/)** – Learn the fundamentals line-by-line.
31+
- **[FODO Example Breakdown](https://pymadng.readthedocs.io/en/latest/ex-fodo.html)** – Annotated walkthrough of a FODO cell simulation.
32+
- **[LHC Matching Example](https://pymadng.readthedocs.io/en/latest/ex-lhc-couplingLocal.html)** – Real-world optics matching with intermediate feedback.
33+
- **[PS Twiss Example](https://github.com/MethodicalAcceleratorDesign/MAD-NG.py/blob/main/examples/ex-ps-twiss/ps-twiss.py)** – Minimal example applying `twiss()` to the Proton Synchrotron.
34+
35+
If anything seems unclear:
36+
- Refer to the [API Reference](https://pymadng.readthedocs.io/en/latest/pymadng.html#module-pymadng)
37+
- Check the [MAD-NG Docs](https://madx.web.cern.ch/releases/madng/html/)
38+
- Or open an [issue](https://github.com/MethodicalAcceleratorDesign/MAD-NG.py/issues)
39+
40+
---
41+
42+
## 📚 Documentation
43+
44+
Full documentation and example breakdowns are hosted at:
45+
[https://pymadng.readthedocs.io/en/latest/](https://pymadng.readthedocs.io/en/latest/)
46+
47+
To build locally:
48+
49+
```bash
50+
git clone https://github.com/MethodicalAcceleratorDesign/MAD-NG.py.git
51+
cd MAD-NG.py/docs
52+
make html
53+
```
54+
55+
---
56+
57+
## 🧪 Running Examples
58+
59+
Examples are stored in the `examples/` folder.
60+
Run any script with:
61+
62+
```bash
63+
python3 examples/ex-fodos.py
64+
```
65+
66+
You can also batch-run everything using:
67+
68+
```bash
69+
python3 runall.py
70+
```
71+
72+
---
73+
74+
## 💡 Features
75+
76+
- High-level Python interface to MAD-NG
77+
- Access to MAD-NG functions, sequences, optics, and tracking
78+
- Dynamic `send()` and `recv()` communication
79+
- Python-native handling of MAD tables and expressions
80+
- Optional integration with `pandas` and `tfs-pandas`
81+
82+
---
83+
84+
## 🤝 Contributing
85+
86+
We welcome contributions! See [`CONTRIBUTING.md`](docs/source/contributing.md) or the [Contributing Guide](https://pymadng.readthedocs.io/en/latest/contributing.html) in the docs.
87+
88+
Bug reports, feature requests, and pull requests are encouraged.
89+
90+
---
91+
92+
## 📜 License
93+
94+
PyMAD-NG is licensed under the [MIT License](https://github.com/MethodicalAcceleratorDesign/MAD-NG.py/blob/main/LICENSE).
95+
96+
---
97+
98+
## 🙌 Acknowledgements
99+
100+
Built on top of MAD-NG, developed at CERN. This interface aims to bring MAD's power to the Python ecosystem with minimal friction.

docs/source/advanced_features.md

Lines changed: 204 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
1+
```{eval-rst}
2+
.. currentmodule:: pymadng
3+
```
4+
5+
# Advanced Features in PyMAD-NG
6+
7+
This section covers some of the most powerful capabilities in PyMAD-NG. These features allow you to create scalable and complex accelerator workflows by combining the performance of MAD-NG with Python's expressiveness.
8+
9+
```{contents}
10+
:depth: 1
11+
:local:
12+
```
13+
14+
---
15+
16+
## Understanding `_last[]` Temporary Variables
17+
18+
In MAD-NG, when a command returns a value, it is not automatically captured unless explicitly assigned. PyMAD-NG handles this by assigning results to a set of reserved variables: `_last[1]`, `_last[2]`, etc.
19+
20+
These are managed internally by PyMAD-NG using a helper class {class}`madp_last.last_counter`, and accessed in Python via references. This allows expressions like:
21+
22+
```python
23+
result = mad.math.sqrt(2) + mad.math.log(10)
24+
```
25+
26+
Behind the scenes, each intermediate operation is stored in a new `_last[i]` reference, then combined. You can access or evaluate the result using `.eval()`:
27+
28+
```python
29+
print(result.eval())
30+
```
31+
32+
These temporary variables are recycled unless manually stored using:
33+
34+
```python
35+
mad["my_var"] = result
36+
```
37+
38+
This is particularly useful in expressions, multi-step computations, and avoiding naming clutter.
39+
40+
---
41+
42+
## Function and Object References in MAD-NG
43+
44+
In PyMAD-NG, accessing or calling any MAD-NG function or object returns a Python reference to that MAD-NG entity, rather than immediately executing or resolving it. This enables symbolic chaining and precise control over execution.
45+
46+
### Example:
47+
```python
48+
r = mad.math.exp(1)
49+
print(type(r)) # high_level_mad_ref
50+
print(r.eval()) # 2.718...
51+
```
52+
53+
You can delay evaluation until needed, allowing reuse:
54+
```python
55+
mad["result"] = mad.math.log(10) + mad.math.sin(1)
56+
```
57+
58+
This keeps Python responsive and lets MAD-NG do the heavy lifting.
59+
60+
---
61+
62+
## Real-Time Feedback with Python During Matching
63+
64+
MAD-NG supports callbacks and iterative evaluations, which can be tied into Python logic. One common use is during `match` procedures, where you want to receive intermediate updates.
65+
66+
### Example Workflow:
67+
In MAD:
68+
```lua
69+
function twiss_and_send()
70+
local tbl, flow = twiss {sequence=seq, method=4}
71+
py:send({tbl.s, tbl.beta11})
72+
return tbl, flow
73+
end
74+
```
75+
76+
In Python:
77+
```python
78+
mad.match(
79+
command=mad.twiss_and_send,
80+
variables=[...],
81+
equalities=[...],
82+
objective={"fmin": 1e-3},
83+
maxcall=100
84+
)
85+
86+
while True:
87+
data = mad.recv()
88+
if data is None:
89+
break
90+
update_plot(data)
91+
```
92+
93+
This is ideal for live visualization, feedback loops, or diagnostics during optimization.
94+
95+
---
96+
97+
## Using PyMAD-NG with Multiprocessing
98+
99+
Because PyMAD-NG communicates with MAD-NG via pipes (not shared memory), you can launch multiple independent MAD processes using `os.fork()` or `multiprocessing`.
100+
101+
### When to Use This:
102+
- Run parallel simulations or parameter scans
103+
- Avoid reloading large sequences repeatedly
104+
105+
### Example:
106+
```python
107+
import os
108+
if os.fork() == 0:
109+
mad = MAD()
110+
mad.send("... long running setup ...")
111+
os._exit(0)
112+
```
113+
114+
Each process maintains its own MAD instance and data pipeline.
115+
116+
---
117+
118+
## Loading and Using External MAD Files and Modules
119+
120+
MAD-X and MAD-NG models often consist of `.seq`, `.mad`, `.madx`, or `.str` files. You can load these via the high-level interface:
121+
122+
```python
123+
mad.MADX.load("'lhc.seq'", "'lhc.mad'")
124+
mad.load("MADX", "lhcb1")
125+
```
126+
127+
Or load additional MAD-NG modules:
128+
```python
129+
mad.load("MAD.gphys", "melmcol")
130+
```
131+
132+
This loads extended libraries for magnet properties, tracking models, or optics algorithms.
133+
134+
---
135+
136+
## Exporting Results for External Use
137+
138+
After running a Twiss or Survey, the results are stored in an `mtable`, which can be exported to a TFS file:
139+
140+
```python
141+
mad.tbl.write("'results.tfs'", mad.quote_strings(["s", "beta11", "mu1"]))
142+
```
143+
144+
You can read this file with `tfs-pandas` or use it as input to another tool.
145+
146+
---
147+
148+
## Combining with NumPy and Pandas
149+
150+
PyMAD-NG integrates cleanly with Python’s data ecosystem:
151+
152+
- Pass `numpy` arrays to MAD-NG using {func}`MAD.send`
153+
- Use {func}`.to_df` on MAD tables to get Pandas DataFrames
154+
- Use `tfs-pandas` for rich metadata support
155+
156+
### Example:
157+
```python
158+
import numpy as np
159+
mad.send("my_array = py:recv()")
160+
mad.send(np.linspace(0, 1, 100))
161+
```
162+
163+
This allows direct use of scientific computation tools in tandem with accelerator modeling.
164+
165+
---
166+
167+
## Managing Larger Workflows
168+
169+
PyMAD-NG supports:
170+
- Loading full files with `mad.loadfile("mysetup.mad")`
171+
- Organising expressions using Python variables
172+
- Retaining command history using:
173+
174+
```python
175+
print(mad.history())
176+
```
177+
178+
For clean resource management, always use context blocks:
179+
```python
180+
with MAD() as mad:
181+
mad.MADX.load("'lhc.seq'", "'lhc.mad'")
182+
```
183+
184+
This ensures the MAD process is correctly shut down when finished.
185+
186+
---
187+
188+
## Summary of Advanced Features
189+
190+
| Feature | Purpose |
191+
|---------------------------------|--------------------------------------------------|
192+
| `_last[]` Variables | Track intermediate return values symbolically |
193+
| Reference Objects | Access MAD-NG objects with delayed evaluation |
194+
| Matching Feedback | Monitor intermediate results during match |
195+
| Multiprocessing | Run multiple MAD-NG simulations in parallel |
196+
| File and Module Loading | Import sequences, optics files, and Lua modules |
197+
| Table Export | Write TFS files from MAD tables |
198+
| NumPy / Pandas Interoperability | Pass data between Python and MAD-NG seamlessly |
199+
| Project Structuring | Use {func}`MAD.loadfile`, {func}`MAD.history`, and `with` block |
200+
201+
These tools are designed to give you complete control over your simulations while staying fast and maintainable.
202+
203+
Next: head over to **Debugging & Troubleshooting** to diagnose and resolve common issues in real-world workflows.
204+

0 commit comments

Comments
 (0)