Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
trixi-framework
GitHub Repository: trixi-framework/Trixi.jl
Path: blob/main/utils/add_alloctest.py
2055 views
1
import argparse
2
3
def add_code_after_end(input_file, output_file, code_to_add):
4
with open(input_file, 'r') as f:
5
julia_code = f.read()
6
7
# Split the Julia code by "end" keywords
8
code_lines = julia_code.split("end")
9
10
# Initialize the modified code with the first part of the code
11
modified_code = code_lines[0]
12
13
# Loop through each "end" and add the code after it, excluding the last "end"
14
for i in range(1, len(code_lines) - 1):
15
# Check for consecutive "end" keywords
16
if code_lines[i].strip() == "":
17
continue
18
19
modified_code += f"{code_to_add}{code_lines[i]}"
20
21
# Add the last "end" without the code
22
modified_code += code_lines[-1]
23
24
with open(output_file, 'w') as f:
25
f.write(modified_code)
26
27
if __name__ == "__main__":
28
parser = argparse.ArgumentParser(description="Add code after 'end' keyword in a Julia source file.")
29
parser.add_argument("input_file", help="Input Julia source file")
30
31
args = parser.parse_args()
32
33
code_to_add = """ # Ensure that we do not have excessive memory allocations
34
# (e.g., from type instabilities)
35
let
36
t = sol.t[end]
37
u_ode = sol.u[end]
38
du_ode = similar(u_ode)
39
@test (@allocated Trixi.rhs!(du_ode, u_ode, semi, t)) < 1000
40
end
41
end"""
42
43
add_code_after_end(args.input_file, args.input_file, code_to_add)
44
45