Python API¶
latform can also be used as a Python library for parsing, formatting, and analyzing Bmad lattice files programmatically.
Parsing¶
parse¶
Parse a Bmad lattice string into a list of statements.
import latform
statements = latform.parse("""
parameter[particle] = electron
Q1: quadrupole, L=0.5, k1=1.2
D1: drift, L=2.0
FODO: line = (Q1, D1)
use, FODO
""")
for st in statements:
print(type(st).__name__, st)
parse_file¶
Parse a single .bmad file from disk.
statements = latform.parse_file("my_lattice.bmad")
parse_file_recursive¶
Parse a lattice file and all files it references via call statements.
Returns a Files object containing parsed statements organized by filename.
files = latform.parse_file_recursive("my_lattice.bmad")
# Iterate over all files and their statements
for filename, statements in files.by_filename.items():
print(f"{filename}: {len(statements)} statements")
# Access the call graph
for caller, callees in files.filename_calls.items():
for callee in callees:
print(f"{caller} -> {callee}")
Formatting¶
format_statements¶
Format parsed statements back to a Bmad string using FormatOptions.
from latform.output import format_statements
from latform.types import FormatOptions
statements = latform.parse_file("my_lattice.bmad")
options = FormatOptions(
line_length=100,
name_case="upper",
kind_case="lower",
)
formatted = format_statements(statements, options)
print(formatted)
format_file¶
A convenience function that parses and formats a file in one step.
from latform.output import format_file
from latform.types import FormatOptions
formatted = format_file("my_lattice.bmad", FormatOptions())
FormatOptions¶
All formatting behavior is controlled through the FormatOptions dataclass.
The defaults match the latform CLI defaults:
from latform.types import FormatOptions
options = FormatOptions(
line_length=100, # target line length
max_line_length=130, # force multiline above this (default: 130% of line_length)
compact=False, # if True, no blank lines between statement types
indent_size=2, # spaces per indent level
indent_char=" ", # indentation character
comment_col=40, # column for inline comment alignment
name_case="upper", # element names: "upper", "lower", "same"
attribute_case="lower", # attribute names: "upper", "lower", "same"
kind_case="lower", # element types/keywords: "upper", "lower", "same"
builtin_case="lower", # builtin functions: "upper", "lower", "same"
section_break_character="-", # character for section break lines
section_break_width=None, # width of section breaks (None = line_length)
trailing_comma=False, # trailing comma in multiline blocks
renames={}, # element rename mapping {"old": "new"}
flatten_call=False, # inline call statements
flatten_inline=False, # inline call:: arguments
strip_comments=False, # remove all comments
newline_at_eof=True, # ensure trailing newline
)
Statement Types¶
Parsed statements are instances of these classes from latform.statements:
| Class | Description | Example |
|---|---|---|
Element |
Element definition | Q1: quadrupole, L=0.5 |
Line |
Beamline definition | FODO: line = (Q1, D1) |
Constant |
Constant assignment | K1_VAL = 1.5 |
Parameter |
Bracketed parameter | parameter[particle] = electron |
Simple |
Keyword statement | use, FODO or call, file=sub.bmad |
Assignment |
General assignment | Q1[k1] = 0.5 |
Empty |
Empty/whitespace-only |
Working with Files¶
The Files class manages recursive parsing. MemoryFiles is a subclass
that starts from a string rather than a file on disk.
from latform.parser import Files, MemoryFiles
# From disk
files = Files(main=pathlib.Path("my_lattice.bmad"))
files.parse(recurse=True)
files.annotate()
# From a string
files = MemoryFiles.from_contents(
contents="Q1: quadrupole, L=0.5\n",
root_path="/path/to/lattice_dir/virtual.bmad",
)
files.parse()
files.annotate()
Diffing¶
Compare two parsed lattice files programmatically.
from latform.parser import Files
from latform.diff import calculate_diff
files1 = Files(main=pathlib.Path("old_lattice.bmad"))
files1.parse()
files1.annotate()
files2 = Files(main=pathlib.Path("new_lattice.bmad"))
files2.parse()
files2.annotate()
diff = calculate_diff(files1, files2)
for p in diff.params_added:
print(f"Added parameter: {p.name} = {p.new_value}")
for name, details in diff.eles_changed.items():
print(f"Changed element: {name}")
for attr, old, new in details.attrs_changed:
print(f" {attr}: {old} -> {new}")
API Reference¶
latform ¶
latform.output ¶
¶
¶
latform.output.format_statements ¶
format_statements(statements, options)
Format a statement and return the code string
Source code in latform/output.py
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 | |
latform.types ¶
¶
latform.types.Block
dataclass
¶
Block(opener=None, closer=None, items=list())
¶
to_token(include_opener=True)
Convert this Block to a single Token with merged location information.
Source code in latform/types.py
409 410 411 412 413 | |
latform.types.OutputLine
dataclass
¶
OutputLine(indent=0, parts=list(), comment=None)
A single line of output with indentation and an optional comment.
latform.types.Seq
dataclass
¶
Seq(opener=None, closer=None, items=list(), delimiter=SPACE)
Ordered sequence of mixed items: * Attribute (a named value, i.e., a name=value pair) * Expression (may be a single token) * Seq (a nested sequence)
¶
to_call_name()
Convert Seq to a single Token.
Source code in latform/types.py
177 178 179 180 181 182 183 184 | |
to_text(opts=None)
Convert Seq to its full output representation.
Source code in latform/types.py
205 206 207 208 209 210 211 212 | |
to_token(include_opener=True)
Convert Seq to a single Token.
Source code in latform/types.py
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | |
¶
latform.parser ¶
¶
latform.parser.Files
dataclass
¶
Files(main, stack=list(), by_filename=dict(), local_file_to_source_filename=dict(), filename_calls=dict())
Represents a collection of parsed files starting from a main entry point.
¶
property
¶call_graph_edges
Return a list of (caller, callee) string edges for visualization.
¶
annotate()
Resolve named items across all parsed files.
Source code in latform/parser.py
510 511 512 513 514 515 516 517 | |
get_named_items()
Aggregate named items from all files.
Source code in latform/parser.py
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 | |
parse(recurse=True)
Parse the main file and optionally its dependencies recursively.
Source code in latform/parser.py
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 | |
reformat(options)
Reformat all files in the collection.
Source code in latform/parser.py
562 563 564 565 566 567 568 569 570 571 572 573 574 575 | |
latform.parser.MemoryFiles
dataclass
¶
MemoryFiles(main, stack=list(), by_filename=dict(), local_file_to_source_filename=dict(), filename_calls=dict(), initial_contents='', _formatted_contents=None)
Bases: Files
Files alternative that starts parsing from a string in memory rather than a
file on disk. Recursion will look to the filesystem relative to
root_path.
¶
property
¶formatted_contents
Get the formatted result of the initial memory contents.
¶
classmethod
¶from_contents(contents, root_path)
Create a MemoryFiles instance from a string.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in latform/parser.py
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 | |
¶
latform.diff ¶
latform-diff - compare two lattice files.
¶
latform.diff.ElementDiffDetails
dataclass
¶
ElementDiffDetails(type_change=None, attrs_added=list(), attrs_removed=list(), attrs_changed=list())
Holds specific differences for a single element.
| Attributes: |
|
|---|
latform.diff.LatticeDiff
dataclass
¶
LatticeDiff(params_added=list(), params_removed=list(), params_changed=list(), eles_added=list(), eles_removed=list(), eles_changed=dict(), eles_renamed=list())
Aggregates all differences between two lattice definitions.
| Attributes: |
|
|---|
latform.diff.ParameterChange
dataclass
¶
ParameterChange(target, name, old_value, new_value)
Represents a change in a single parameter (target, name).
¶
latform.diff.calculate_diff ¶
calculate_diff(files1, files2)
Compute differences between two file sets and return a dataclass.
| Parameters: |
|---|
| Returns: |
|
|---|
Source code in latform/diff.py
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 | |
latform.diff.print_diff ¶
print_diff(diff, console)
Render the diff using Rich tables.
Source code in latform/diff.py
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 | |