Skip to content

Commit

Permalink
Function to merge lines that end in ampersand
Browse files Browse the repository at this point in the history
  • Loading branch information
jank324 committed Sep 4, 2023
1 parent d1910b3 commit 523cfe9
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
25 changes: 25 additions & 0 deletions cheetah/bmad.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os
import re
from copy import deepcopy
from pathlib import Path


Expand Down Expand Up @@ -49,3 +50,27 @@ def read_clean_lines(lattice_file_path: Path) -> list[str]:
replaced_lines = [line.strip() for line in replaced_lines]

return replaced_lines


def merge_ampersand_continued_lines(lines: list[str]) -> list[str]:
"""
Merge lines ending with an ampersand with the following line.
:param lines: List of lines to merge.
:return: List of lines with ampersand-continued lines merged.
"""
merged_lines = deepcopy(lines)
for i in range(len(merged_lines) - 1):
if merged_lines[i] is not None and merged_lines[i].endswith("&"):
num_added_lines = 1
while merged_lines[i].endswith("&"):
merged_lines[i] = (
merged_lines[i][:-1] + merged_lines[i + num_added_lines]
)
merged_lines[i + num_added_lines] = None
num_added_lines += 1

# Prune None lines
merged_lines = [line for line in merged_lines if line is not None]

return merged_lines
22 changes: 22 additions & 0 deletions test_bmad.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"source": [
"import os\n",
"import re\n",
"from copy import deepcopy\n",
"from pathlib import Path\n",
"\n",
"import cheetah.bmad"
Expand Down Expand Up @@ -123,6 +124,27 @@
"lines[:20]"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(14409, 14405)"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"merged_lines = cheetah.bmad.merge_ampersand_continued_lines(lines)\n",
"len(lines), len(merged_lines)"
]
},
{
"cell_type": "code",
"execution_count": 50,
Expand Down

0 comments on commit 523cfe9

Please sign in to comment.