Peano
Loading...
Searching...
No Matches
Makefile.py
Go to the documentation of this file.
1# This file is part of the Peano project. For conditions of distribution and
2# use, please see the copyright notice at www.peano-framework.org
3import os
4import re
5import sys
6import subprocess
7import jinja2
8
9from .Helper import write_file
10
11from .CompileMode import CompileMode
12
13
14class Makefile(object):
15 """Represents the created Makefile of a Peano 4 project"""
16
17 default_overwrite = True
18
19 def __init__(self):
20 self.clear()
21
22 @property
23 def readme_entry(self):
24 result_template = jinja2.Template(
25 """
26## Makefile settings
27
28~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
29CXX = {{CXX}}
30CXXFLAGS = {{CXXFLAGS}}
31FC = {{FC}}
32FCFLAGS = {{FCFLAGS}}
33LDFLAGS = {{LDFLAGS}}
34LIBS = {{LIBS}}
35DIM = {{DIM}}
36CONFIGUREPATH = {{CONFIGUREPATH}}
37EXECUTABLENAME = {{EXECUTABLENAME}}
38FORTRAN_MODULES = {{FORTRAN_MODULES}}
39MODE = {{MODE}}
40~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
41
42## Compiler version
43
44~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
45{{VERSION}}
46~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
47
48"""
49 )
50 try:
51 version_string = subprocess.run(
52 [self.d["CXX"], "--version"], stdout=subprocess.PIPE
53 )
54 except Exception:
55 version_string = subprocess.run(
56 ["echo", "Unknown"], shell=True, stdout=subprocess.PIPE
57 )
58 self.d["VERSION"] = version_string.stdout.decode("utf-8")
59 return result_template.render(**self.d) + self.configure_call
60
61 @property
63 return jinja2.Template(
64 """
65{% if Parallel %}
66
67### MPI parallelisation
68
69Peano's distributed memory parallelisation is based upon plain space-filling
70curves which are used first to split the cells among the ranks, and, after
71that, to split the cells into chunks and deploy them onto cores (if shared
72memory is used). There is no particularly novel contribution/paper on this
73aspect of the code. The paper that is (algorithmically) most interesting is
74an old EuroPar publication:
75
76 @InProceedings{Bungartz:2006:Parallelisation,
77 author={Bungartz, Hans-Joachim and Mehl, Miriam and Weinzierl, Tobias},
78 editor={Nagel, Wolfgang E. and Walter, Wolfgang V. and Lehner, Wolfgang},
79 title={A Parallel Adaptive Cartesian PDE Solver Using Space--Filling Curves},
80 booktitle={Euro-Par 2006 Parallel Processing},
81 year={2006},
82 publisher={Springer Berlin Heidelberg},
83 address={Berlin, Heidelberg},
84 pages={1064--1074},
85 abstract={In this paper, we present a parallel multigrid PDE solver working on adaptive hierarchical cartesian grids. The presentation is restricted to the linear elliptic operator of second order, but extensions are possible and have already been realised as prototypes. Within the solver the handling of the vertices and the degrees of freedom associated to them is implemented solely using stacks and iterates of a Peano space--filling curve. Thus, due to the structuredness of the grid, two administrative bits per vertex are sufficient to store both geometry and grid refinement information. The implementation and parallel extension, using a space--filling curve to obtain a load balanced domain decomposition, will be formalised. In view of the fact that we are using a multigrid solver of linear complexity {\\$}{\\backslash}mathcal{\\{}O{\\}}(n){\\$}, it has to be ensured that communication cost and, hence, the parallel algorithm's overall complexity do not exceed this linear behaviour.},
86 isbn={978-3-540-37784-9}
87 }
88
89{% endif %}
90{% if SharedOMP %}
91
92### OpenMP parallelisation
93
94Peano 4 run uses a wrapper around OpenMP to obtain a high task efficiency.
95The wrapper can be read as user-level threading implemented on top of OpenMP's
96tasking mechanism. It is described in
97
98 @article{Schulz:2021:Tasking,
99 title = {Task inefficiency patterns for a wave equation solver},
100 journal = {IWOMP},"
101 year = {2021},
102 author = {Holger Schulz and Gonzalo Brito Gadeschi and Oleksandr Rudyy and Tobias Weinzierl},
103 }
104
105{% endif %}
106
107{% if SharedOMP %}
108
109Peano relies on a mixture of classic domain decomposition and task-based
110parallelism. The domain decomposition provides the baseline performance,
111and the tasking adds the big flexibility and scalability gain on top. The
112key publication discussing the overall idea and algorithmic ingredients is
113the SISC paper
114
115 @article{Charrier:2020:Enclave,
116 author = {Charrier, Dominic Etienne and Hazelwood, Benjamin and Weinzierl, Tobias},
117 title = {Enclave Tasking for DG Methods on Dynamically Adaptive Meshes},
118 journal = {SIAM Journal on Scientific Computing},
119 volume = {42},
120 number = {3},
121 pages = {C69-C96},
122 year = {2020},
123 doi = {10.1137/19M1276194},
124 URL = {https://doi.org/10.1137/19M1276194},
125 eprint = {https://doi.org/10.1137/19M1276194}
126 }
127
128{% endif %}
129
130"""
131 ).render(**self.d)
132
134 return self.d["EXECUTABLENAME"]
135
136 def clear(self):
138 self.d = {}
139 self.d["CXX"] = ""
140 self.d["CXXFLAGS"] = ""
141 self.d["FC"] = ""
142 self.d["FCFLAGS"] = ""
143 self.d["LDFLAGS"] = ""
144 self.d["LIBS"] = "-lomp"
145 self.d["DIM"] = "2"
146 self.d["CONFIGUREPATH"] = "."
147 self.d["EXECUTABLENAME"] = ""
148 self.d["CMAKE_BUILD_DIR"] = ""
149 self.d["FORTRAN_MODULES"] = []
150 self.d["APP_SUBDIRECTORIES"] = []
151 self.set_mode(CompileMode.DEBUG)
152 self.clear_files()
153
154 def set_executable_name(self, fname):
155 self.d["EXECUTABLENAME"] = fname
156
157 def clear_files(self):
158 self.hfiles = []
159 self.cppfiles = []
160 self.mlir_dict = {}
161 self.fortranfiles = []
165
166 def set_dimension(self, dimension):
167 self.d["DIM"] = str(dimension)
168
170 """
171 Returns the directory where the ./configure script is located
172 """
173 return self.d["CONFIGUREPATH"]
174
176 """
177 Returns the directory where the ./configure script is located
178 """
179 return self.get_configure_path() + "/src"
180
181 def add_header_search_path(self, path):
182 """
183 Add the header search path to both the C++ and the Fortran
184 call command.
185 """
186 self.d["CXXFLAGS"] += " -I" + path
187 self.d["FCFLAGS"] += " -I" + path
188
189 def add_library(self, library_name, library_path=""):
190 """
191 If you want to link against a library from Peano, feel free to use
192 get_Peano4_source_directory() and hand in a concatenation of this
193 path plus a subpath. Otherwise, specify the absolute path where to
194 search for. By default, Peano's src directory is in the search
195 path.
196
197 A popular invocation including one of Peano's toolboxes is
198
199 project.output.makefile.add_library("ToolboxFiniteElements2d_trace", project.output.makefile.get_source_path() + "/toolbox/finiteelements")
200 """
201 if library_path != "":
202 self.d["LIBS"] = "-L" + library_path + " " + self.d["LIBS"]
203 self.d["LIBS"] += library_name + " "
204
205 def set_mode(self, mode):
206 """
207 mode should be of type CompileMode. Pass in
208
209 peano4.api.output.CompileMode.DEBUG
210
211 for example. Debug is the default.
212 """
213 if mode == CompileMode.DEBUG:
214 self.d["MODE"] = "DEBUG"
215 elif mode == CompileMode.ASSERTS:
216 self.d["MODE"] = "ASSERTS"
217 elif mode == CompileMode.STATS:
218 self.d["MODE"] = "STATS"
219 elif mode == CompileMode.TRACE:
220 self.d["MODE"] = "TRACE"
221 elif mode == CompileMode.RELEASE:
222 self.d["MODE"] = "RELEASE"
223 else:
224 assert False
225
226 def set_CXX_compiler(self, value):
227 self.d["CXX"] = value
228
229 def set_CXX_flags(self, value):
230 self.d["CXXFLAGS"] = value
231
232 def add_CXX_flag(self, value, force=False):
233 if value in self.d["CXXFLAGS"] and not force:
234 print(
235 "CXXFLAG "
236 + value
237 + " is already in list of flags. Ignored as force attribute is not set"
238 )
239 else:
240 self.d["CXXFLAGS"] += " " + value
241
242 def set_Fortran_compiler(self, value):
243 self.d["FC"] = value
244
245 def set_Fortran_flags(self, value):
246 self.d["FCFLAGS"] = value
247
248 def add_Fortran_flag(self, value, force=False):
249 if value in self.d["FCFLAGS"] and not force:
250 print(
251 "FCFLAGS "
252 + value
253 + " is already in list of flags. Ignored as force attribute is not set"
254 )
255 else:
256 self.d["FCFLAGS"] += " " + value
257
258 def add_linker_flag(self, value):
259 self.d["LDFLAGS"] += " " + value
260
261 def set_linker_flags(self, value):
262 self.d["LDFLAGS"] = value + " "
263
264 def parse_configure_script_outcome(self, directory):
265 """
266 directory should point to the directory which holds the ./configure script.
267 It furthermore has to be invoked after configure has passed successfully.
268 This script does not accept relative paths. We then search for the subdirectory
269 src and parse the Makefile there.
270 """
271 if 'PEANO_SRC_ROOT_DIR' in os.environ:
272 directory = os.environ['PEANO_SRC_ROOT_DIR']
273
274 self.d["CONFIGUREPATH"] = directory
275
276 if 'PEANO_CMAKE_BUILD_DIR' in os.environ: # If this environment flag has been set, favour CMake
277 self.d["CMAKE_BUILD_DIR"] = os.environ['PEANO_CMAKE_BUILD_DIR']
278 else: # If not, and an Automake configuration is present, favour this instead
279 try:
280 input_file = directory + "/config.log"
281 input = open(input_file, "r")
282 self.configure_call = ""
283 print("parse configure outcome " + input_file + " to extract configure settings")
284 MakefileDefined = [
285 "Parallel",
286 "SharedOMP",
287 "SharedSYCL",
288 "SharedCPP",
289 ]
290
291 for line in input:
292 if "./configure" in line and self.configure_call == "":
293 print("found the configure call info " + line)
294 self.configure_call = line.strip()
295 for define in MakefileDefined:
296 if re.search("#define " + define, line):
297 self.d[define] = "1"
298
299 input_file = directory + "/src/Makefile"
300 input = open(input_file, "r")
301 print("parse configure outcome " + input_file + " to extract compile settings")
302 MakefileConstants = [
303 "CXXFLAGS_PEANO_2D_RELEASE",
304 "CXXFLAGS_PEANO_2D_STATS",
305 "CXXFLAGS_PEANO_2D_ASSERTS",
306 "CXXFLAGS_PEANO_2D_TRACE",
307 "CXXFLAGS_PEANO_2D_DEBUG",
308 "CXXFLAGS_PEANO_3D_RELEASE",
309 "CXXFLAGS_PEANO_3D_STATS",
310 "CXXFLAGS_PEANO_3D_ASSERTS",
311 "CXXFLAGS_PEANO_3D_TRACE",
312 "CXXFLAGS_PEANO_3D_DEBUG",
313 "LDFLAGS_PEANO_RELEASE",
314 "LDFLAGS_PEANO_STATS",
315 "LDFLAGS_PEANO_ASSERTS",
316 "LDFLAGS_PEANO_TRACE",
317 "LDFLAGS_PEANO_DEBUG",
318 "LDADD_PEANO_2D_RELEASE",
319 "LDADD_PEANO_2D_STATS",
320 "LDADD_PEANO_2D_ASSERTS",
321 "LDADD_PEANO_2D_TRACE",
322 "LDADD_PEANO_2D_DEBUG",
323 "LDADD_PEANO_3D_RELEASE",
324 "LDADD_PEANO_3D_STATS",
325 "LDADD_PEANO_3D_ASSERTS",
326 "LDADD_PEANO_3D_TRACE",
327 "LDADD_PEANO_3D_DEBUG",
328 "CXX",
329 "FC",
330 "CXXFLAGS",
331 "LDFLAGS",
332 "LIBS",
333 "GPU_VENDOR",
334 "GPU_ARCH"
335 ]
336
337 for line in input:
338 for constant in MakefileConstants:
339 if re.search(constant + " *=", line) and line.startswith(constant):
340 try:
341 flags = line.split("=", 1)[1].strip()
342 #print("add " + constant + "=" + flags)
343 self.d[constant] = flags
344 except:
345 print("Error in " + line + " for token " + constant)
346 return
347 except IOError:
348 self.d["CMAKE_BUILD_DIR"] = next((path for path in (os.path.join(directory, subdir) for subdir in os.listdir(directory)) if os.path.isfile(os.path.join(path, "PeanoTargets.cmake"))), "")
349 pass # If there is no Automake configuration we try CMake as last attempt
350
351 if self.d["CMAKE_BUILD_DIR"] != "":
352 cmake_cache_file = self.d["CMAKE_BUILD_DIR"] + "/CMakeCache.txt"
353 if os.path.isfile(cmake_cache_file):
354 with open(cmake_cache_file, 'r') as input:
355 for line in input:
356 key_value = line.split("=", 1)
357 if len(key_value) == 2:
358 key, value = key_value
359 key = key.split(":")[0].strip()
360 if key == "CMAKE_CXX_COMPILER":
361 self.d["CXX"] = value.strip()
362 if key == "CMAKE_Fortran_COMPILER":
363 self.d["FC"] = value.strip()
364 else: # Nothing has been configured so far
365 raise Exception("""
366 Error: if you call parse_configure_script_outcome(), please hand over directory where
367 ./configure had been called. You passed """ + directory
368 )
369
370 def add_h_file(self, filename, generated=False):
371 """
372 Add a new header filename.
373 This is actually not needed for compilation,
374 but is useful to have for IDEs where the header files can be displayed
375 in the project.
376
377 filename: String
378 Filename of a C/C++ header file. They usually should have the .h/.hpp extension.
379 generated: Bool
380 Use this flag for generated files which can be tracked
381 by the cleaning routines 'distclean' or 'maintainer-clean' of the Makefile.
382 """
383 if generated:
384 if (
385 self.generated_hfiles.count(filename) == 0
386 and self.hfiles.count(filename) == 0
387 ):
388 self.generated_hfiles.append(filename)
389 else:
390 if self.hfiles.count(filename) == 0:
391 self.hfiles.append(filename)
392 if self.generated_hfiles.count(filename) > 0:
393 self.generated_hfiles.remove(filename)
394
395 def remove_h_file(self, filename):
396 if filename in self.generated_hfiles:
397 self.generated_hfiles.remove(filename)
398 if filename in self.hfiles:
399 self.hfiles.remove(filename)
400
401 def add_cpp_file(self, filename, generated=False):
402 """
403 Add a new cpp filename. This is basically a set implementation, i.e., you can
404 add files multiple times, but they are not inserted multiple times. This
405 is important, as the steps add the cpp files. Multiple steps can hold the
406 same action, so this action would be created multiple times.
407
408 All the standard Peano 4 routines rely on this function to add their
409 generated files to the build environment. Nothing stops you however to
410 add more files yourself.
411
412 filename: String
413 Filename of a C++ file. They usually should have the .cpp/.cxx extension.
414 generated: Bool
415 Use this flag for generated files which can be tracked
416 by the cleaning routines 'distclean' or 'maintainer-clean' of the Makefile.
417 """
418 if generated:
419 # Non-generated file takes precedence over generated files.
420 # We only add a generated file if has not been added yet as a non-generated file instead.
421 if (
422 self.generated_cppfiles.count(filename) == 0
423 and self.cppfiles.count(filename) == 0
424 ):
425 self.generated_cppfiles.append(filename)
426 else:
427 # If a file is a non-generated file we definitely want to add it.
428 if self.cppfiles.count(filename) == 0:
429 self.cppfiles.append(filename)
430 # We ensure that we only add a .cpp file once.
431 # Otherwise we would get duplicated symbols errors.
432 # But we never delete a non-generated file.
433 if self.generated_cppfiles.count(filename) > 0:
434 self.generated_cppfiles.remove(filename)
435
436 def remove_cpp_file(self, filename):
437 if filename in self.generated_cppfiles:
438 self.generated_cppfiles.remove(filename)
439 if filename in self.cppfiles:
440 self.cppfiles.remove(filename)
441
442 def add_mlir_file(self, filename, pipeline):
443 """
444 Add a new mlir filename. It gets added to a dictionary where the associated value
445 is the pipeline that should be applied to the file.
446
447 filename: String
448 Filename of an MLIR file. They have the .mlir extension.
449 pipeline: String
450 MLIR pipeline that should be applied to the file.
451 generated: Bool
452 Use this flag for generated files which can be tracked
453 by the cleaning routines 'distclean' or 'maintainer-clean' of the Makefile.
454 """
455 mlir_prefix = filename.rsplit(".", 1)[0]
456 self.mlir_dict[mlir_prefix] = pipeline
457
458 def remove_mlir_file(self, filename):
459 mlir_prefix = filename.rsplit(".", 1)[0]
460 if mlir_prefix in self.mlir_dict:
461 del self.mlir_dict[mlir_prefix]
462
463 def add_Fortran_file(self, filename, generated=False):
464 """
465 Add a new Fortran file.
466
467 All the standard Peano 4 routines rely on this function to add their
468 generated files to the build environment. Nothing stops you however to
469 add more files yourself. Don't add a file multiple times. This might
470 break the compiler.
471
472 Fortran is really picky about the translation order. So you have to add
473 the stuff in the right order. Otherwise, Fortran might complain. This is
474 your responsibility.
475
476 If your file defines a module, please do not use this routine, but use
477 add_Fortran_module() instead.
478
479 filename: String
480 Filename of a Fortran file. They usually should have the .f90 extension.
481 generated: Bool
482 Use this flag for generated files which can be tracked
483 by the cleaning routines 'distclean' or 'maintainer-clean' of the Makefile.
484 """
485 if generated:
486 if (
487 self.generated_fortranfiles.count(filename) == 0
488 and self.fortranfiles.count(filename) == 0
489 ):
490 self.generated_fortranfiles.append(filename)
491 else:
492 if self.fortranfiles.count(filename) == 0:
493 self.fortranfiles.append(filename)
494 if self.generated_fortranfiles.count(filename) > 0:
495 self.generated_fortranfiles.remove(filename)
496
497 def remove_Fortran_file(self, filename):
498 if filename in self.generated_fortranfiles:
499 self.generated_fortranfiles.remove(filename)
500 if filename in self.fortranfiles:
501 self.fortranfiles.remove(filename)
502
503 def add_Fortran_module(self, module_file, force=False):
504 """
505 Add a Fortran module
506
507 module_file: String
508 Filename of a Fortran source code file which hosts a module. It should
509 have the extension .f90 or similar.
510
511 force: Boolean
512 Enforce that Fortran module is added even though it might already be in
513 the list.
514 """
515 if not module_file.endswith(".f90"):
516 print(
517 "Warning: Fortran module file does not have extension .f90 ("
518 + module_file
519 + ") and translation thus might fail"
520 )
521 if module_file in self.d["FORTRAN_MODULES"] and not force:
522 print(
523 """Fortran module file
524"""
525 + module_file
526 + """
527is already in module file list. Did not add it once more. You can overwrite
528this default behaviour via the force attribute in add_Fortran_module(). If
529you create multiple Peano 4 makefiles in a row (as you change parameters, e.g.)
530then this message can typically be ignored.
531"""
532 )
533 elif module_file in self.d["FORTRAN_MODULES"] and force:
534 print(
535 "Fortran module file "
536 + module_file
537 + " is already in module file list but force flag is set. Add it"
538 )
539 self.d["FORTRAN_MODULES"].append(module_file)
540 else:
541 self.d["FORTRAN_MODULES"].append(module_file)
542
543 def add_Fortran_modules(self, module_files):
544 for i in module_files:
545 self.add_Fortran_module(i)
546
547 def generate(self, overwrite, directory, subdirectories=[]):
548 """
549 Generates build files and other project-related files based on templates.
550
551 :param overwrite: Specifies whether existing files should be overwritten.
552 :type overwrite: bool
553 :param directory: The directory where the generated files will be placed.
554 :type directory: str
555 """
556 self.d["H_HEADERS"] = self.hfiles
557 self.d["CXX_SOURCES"] = self.cppfiles
558 self.d["FORTRAN_SOURCES"] = self.fortranfiles
559 self.d["GENERATED_H_HEADERS"] = self.generated_hfiles
560 self.d["GENERATED_CXX_SOURCES"] = self.generated_cppfiles
561 self.d["GENERATED_FORTRAN_SOURCES"] = self.generated_fortranfiles
562 if subdirectories:
563 for subdirectory in subdirectories:
564 self.d["APP_SUBDIRECTORIES"].append(subdirectory)
565
566 #self.d["MLIR_PREFIXES"] = mlir_prefixes
567 self.d["MLIR_DICT"] = self.mlir_dict
568 self.d["MLIR_OBJS"] = " ".join([f"{prefix}_mlir.o" for prefix in self.mlir_dict.keys()])
569
570 # Encapsulate file generation as a function
571 def generate_output_file(input_file_path, output_file_path):
572 if write_file(overwrite, self.default_overwrite, output_file_path):
573 print("write " + output_file_path)
574 template_loader = jinja2.FileSystemLoader(searchpath=os.path.split(input_file_path)[0])
575 templateEnv = jinja2.Environment(loader=template_loader)
576 template = templateEnv.get_template(os.path.split(input_file_path)[1])
577 with open(output_file_path, "w") as output:
578 output.write(template.render(self.d))
579
580 file_dir = os.path.dirname(os.path.realpath(__file__))
581
582 generate_output_file(os.path.join(file_dir, "Gitignore.template"), os.path.join(directory, ".gitignore"))
583
584 if self.d["CMAKE_BUILD_DIR"] != "":
585 generate_output_file(os.path.join(file_dir, "CMakeLists.txt.template"), os.path.join(directory, "CMakeLists.txt"))
586 # Shortcut to the CMake build. Used to mirror Autotools.
587 generate_output_file(os.path.join(file_dir, "Makefile.cmake.template"), os.path.join(directory, "Makefile"))
588 else:
589 generate_output_file(os.path.join(file_dir, "Makefile.template"), os.path.join(directory, "Makefile"))
Represents the created Makefile of a Peano 4 project.
Definition Makefile.py:14
get_configure_path(self)
Returns the directory where the .
Definition Makefile.py:169
add_CXX_flag(self, value, force=False)
Definition Makefile.py:232
add_Fortran_module(self, module_file, force=False)
Add a Fortran module.
Definition Makefile.py:503
add_Fortran_file(self, filename, generated=False)
Add a new Fortran file.
Definition Makefile.py:463
add_Fortran_modules(self, module_files)
Definition Makefile.py:543
get_source_path(self)
Returns the directory where the .
Definition Makefile.py:175
add_Fortran_flag(self, value, force=False)
Definition Makefile.py:248
parse_configure_script_outcome(self, directory)
directory should point to the directory which holds the .
Definition Makefile.py:264
add_library(self, library_name, library_path="")
If you want to link against a library from Peano, feel free to use get_Peano4_source_directory() and ...
Definition Makefile.py:189
add_cpp_file(self, filename, generated=False)
Add a new cpp filename.
Definition Makefile.py:401
add_header_search_path(self, path)
Add the header search path to both the C++ and the Fortran call command.
Definition Makefile.py:181
add_mlir_file(self, filename, pipeline)
Add a new mlir filename.
Definition Makefile.py:442
generate(self, overwrite, directory, subdirectories=[])
Generates build files and other project-related files based on templates.
Definition Makefile.py:547
add_h_file(self, filename, generated=False)
Add a new header filename.
Definition Makefile.py:370
set_mode(self, mode)
mode should be of type CompileMode.
Definition Makefile.py:205