Peano
Loading...
Searching...
No Matches
Project.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
3
4import filecmp
5import gc
6import os
7import re
8import shutil
9import sys
10import subprocess
11import multiprocessing
12import tempfile
13
18
19# Bound directly (not via the peano4.api.output.* attribute chain) because this
20# name is used in a default parameter value below, which is evaluated while
21# peano4.api itself is still being imported - the peano4.api attribute chain
22# is not yet fully wired up at that point.
23from .output import Overwrite
24from .Logger import Logger
25
26class Project (object):
27 """!
28
29 Represents a Peano 4 project.
30
31 namespace Sequence of strings representing the (nested) namespace. Pass in
32 [ "examples", "algebraicmg" ] for example if you wanna write a solver that
33 is embedded into the namespace examples::algebraicmg.
34
35
36 ## Global project properties
37
38 If you want to alter some global constants, you should manipulate
39 the constants attribute. It will eventually feed into the generated
40 file Constants.h. See peano4.api.output.Constants for further info.
41
42 """
43
44 def __init__(self, namespace, project_name, directory = ".", subdirectory = "", executable = ""):
45 """!
46 project_name Simple string.
47 """
48 if sys.version_info.major < 3:
49 print( "Warning: should be invoked through python3, i.e. with newer Python version" )
50
51 if subdirectory and not os.path.exists(subdirectory):
52 os.mkdir(subdirectory)
53
54 self.rootnamespace = namespace.copy()
55 self.namespace = namespace
56 self.namespaces = []
59 self.project_name = project_name
60 self.directory = directory
61 self.temporary_directory = tempfile.mkdtemp()
62 self._subdirectory = subdirectory
63 self.temporary_subdirectory = tempfile.mkdtemp()
64 if subdirectory:
65 self.namespace += [ subdirectory ]
66 if self.namespace:
67 if not self.namespace in self.namespaces:
68 self.namespaces.append(self.namespace)
69 if not self.subdirectory in self.subdirectories:
70 self.subdirectories.append(self.subdirectory)
71 self.temporary_subdirectories.append(tempfile.mkdtemp())
72
73 #
74 # Create default output model, i.e. those parts that have to be there
75 # always
76 #
78
79 #
80 # Empty model by default
81 #
83
85
87
88 self.is_generated = False
89 self.is_built = False
91
93 self.subconstants = []
94
95 if executable:
96 self.output.makefile.set_executable_name(executable)
97
98 self.is_extended = False
99
100
101 def __str__(self):
102 return "(#steps=" + str(self.solversteps) + ",model=" + str(self.datamodel) + ")"
103
104 def set_fenv_handler(self, args):
105 self.main.d[ "FENV_ARGS" ] = args
106
107 def cleanup(self):
108 """!
109 This routine has to be called after you've generated your code.
110 """
111 self.output.clear()
112 self.datamodel.clear()
113 self.solversteps.clear()
114
116
117 self.is_generated = False
118 self.is_built = False
119
121 self.subconstants = []
122
123 def generate(self,
124 overwrite=Overwrite.Default,
125 throw_away_data_after_generation=False):
126 """!
127 Generate all code. If you add stuff to your project after a
128 build, you have to (re-)generate the code. If you compile only
129 once, you don't have to invoke this routine explicitly. It is
130 lazily called by the other project routines - the latest before
131 you run the code.
132
133 It is important that I reset the output after each generate
134 call before you change parameter settings and call generate
135 again. To do so, invoke cleanup(). If you forget this, two
136 subsequent generate calls enrich the output twice.
137
138 throw_away_data_after_generation: Bool
139 The Peano 4 memory footprint can become quite substantial
140 effectively reducing the translation capabilities (as compilers
141 tend to require a lot of memory, too). So pass in True if you
142 want the script to throw away the data structures (and run a
143 garbage collection) after all files have been generated. Please
144 note that it invalidates both this object (and maybe another
145 object that you've used to generate the present one - such as
146 ExaHyPE). It really strips everything down to the stuff you
147 absolutely need to translate and run the code.
148 """
149 Logger().new_section("Generate code")
150 self.is_generated = True
151 self.is_built = False
152
153 # The constants and the output below write straight into self.directory,
154 # which only exists already if a solver has created it.
155 os.makedirs(self.directory, exist_ok=True)
156
157 self.output.readme.add_package_description( self.constants.readme_entry() )
158
159 self.datamodel.construct_output(self.output)
160 self.solversteps.construct_output(self.output)
161
162 self.main.construct_output(self.output,self.project_name + "-main")
163 if self.subconstants:
164 for i in range(len(self.subconstants)):
165 self.subconstants[i].generate(overwrite, self.temporary_directory, self.temporary_subdirectories[i])
166 else:
167 self.constants.generate(overwrite, self.temporary_directory)
168
169 # Generate the README last, so it is genuinely the final artefact: its
170 # "is ready" message (see peano4.api.output.Readme) is meant to be the
171 # last thing this routine reports before Logger's own atexit-triggered
172 # close() takes over.
174 #self.output.generate(overwrite, self.directory, self.subdirectories)
175
176 # Check whether any of the code generated into a temporary directory is
177 # different from the code that already exists in the corresponding subdirectory.
178 # If so, copy the generated code into the subdirectory. This is intended
179 # to avoid unnecessary recompilation of unchanged code.
181 self.subdirectories.append(self.subdirectory)
182 for temporary_subdirectory, subdirectory in zip(self.temporary_subdirectories, self.subdirectories):
183 for root, dirs, files in os.walk(temporary_subdirectory):
184 for file in files:
185 temporary_file_path = os.path.join(root, file)
186 relative_path = os.path.relpath(temporary_file_path, temporary_subdirectory)
187 target_file_path = os.path.join(self.directory, subdirectory, relative_path)
188 # Check if the target file exists and is different from the temporary file
189 if not os.path.exists(target_file_path) or not filecmp.cmp(temporary_file_path, target_file_path):
190 # Create the target directory if it doesn't exist
191 os.makedirs(os.path.dirname(target_file_path), exist_ok=True)
192 # Copy the temporary file to the target location
193 shutil.copy(temporary_file_path, target_file_path)
194 #last_point_location = target_file_path.find('.')
195 #while target_file_path.find('.', last_point_location + 1) >= 0:
196 # last_point_location = target_file_path.find('.', last_point_location + 1)
197 #file_prefix = target_file_path[0:target_file_path.find('.', last_point_location) - 1]
198 #if os.path.isfile(file_prefix + ".o"):
199 # os.remove(file_prefix + ".o")
200 # Logger().log(f"Deleted {file_prefix}.o")
201
202 Logger().log(f"Updated {target_file_path} from {temporary_file_path}")
203 for root, dirs, files in os.walk(self.temporary_directory):
204 for file in files:
205 temporary_file_path = os.path.join(root, file)
206 relative_path = os.path.relpath(temporary_file_path, self.temporary_directory)
207 target_file_path = os.path.join(self.directory, self.directory, relative_path)
208 # Check if the target file exists and is different from the temporary file
209 if not os.path.exists(target_file_path) or not filecmp.cmp(temporary_file_path, target_file_path):
210 # Create the target directory if it doesn't exist
211 os.makedirs(os.path.dirname(target_file_path), exist_ok=True)
212 # Copy the temporary file to the target location
213 shutil.copy(temporary_file_path, target_file_path)
214 Logger().log(f"Updated {target_file_path} from {temporary_file_path}")
215
216 if throw_away_data_after_generation:
217 self.datamodel = None
218 self.solversteps = None
219 self.output = None
220 gc.collect()
221 print("threw away all data and ran garbage collection")
222
223 def build(self,
224 make=True,
225 make_clean_first=True,
226 throw_away_data_after_build=False,
227 number_of_parallel_builds=-1):
228 """!
229 Invokes the underlying make build mechanism on the project.
230
231 number_of_parallel_builds: int
232 This is mapped onto make -jnumber_of_parallel_builds, i.e., it
233 determines how many parallel make instances the code spawns.
234 Usually, a lot of the generated code is quite lengthy. Therefore
235 compile time can be high. If you pass something smaller or equal
236 to zero, it will use the core count as guideline how to compile.
237
238 throw_away_data_after_build: Bool
239 see generate()
240 """
241 if number_of_parallel_builds <= 0:
242 number_of_parallel_builds = multiprocessing.cpu_count()
243
244 if not self.is_generated:
245 self.generate()
246
247 if make:
248 if make_clean_first:
249 print("clean up project ... in {}".format(self.directory))
250 try:
251 if make_clean_first:
252 subprocess.check_call(["make", "clean"], cwd=self.directory)
253 self.is_built = False
254 print("clean complete")
255 except Exception as e:
256 print("clean failed (" + str(e) + ") - continue anyway")
257
258 if not self.is_built:
259 print("start to compile with concurrency level of " + str(number_of_parallel_builds) + " ...")
260 try:
261 process = subprocess.run(["make", "-j"+str(number_of_parallel_builds)], cwd=self.directory, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
262 # Extract warnings and errors from error message
263 error_message = process.stderr.decode().strip()
264 warnings = re.findall(r"(?i)warning:.*", error_message)
265 errors = re.findall(r"(?i)error:.*", error_message)
266 # Print warnings into the terminal
267 if warnings:
268 print("\nWarnings ({}):".format(len(warnings)))
269 print("\n".join(warnings))
270 if errors:
271 print("\nErrors ({}):".format(len(errors)))
272 error_message = "\n".join(errors)
273 # Check the return code for linker errors
274 # Raise exception with errors
275 if process.returncode != 0:
276 linker_error_message = process.stderr.decode().strip() + "\n" + error_message
277 raise Exception(linker_error_message)
278 print("compile completed successfully")
279 self.is_built = True
280 self.build_was_successful = True
281 except Exception as e:
282 self.is_built = True
283 self.build_was_successful = False
284 print(str(e))
285 print("compile was not successful")
286 sys.exit(1)
287 else:
288 print("cannot build as code generation has not been successful")
289
290 if throw_away_data_after_build:
291 self.cleanup()
292 self.datamodel = None
293 self.solversteps = None
294 self.output = None
295 gc.collect()
296 print("threw away all data and ran garbage collection")
297
298 def run(self, executable, args=[], prefix=None, pipefile=None, rebuild_if_required=True):
299 """!
300 Runs the code. args should be a list of strings or the empty list.
301 prefix is an array, too. A typical invocation looks alike
302 project.run( ["16.0", "32.0"], ["/opt/mpi/mpirun", "-n", "1"] )
303 The operation returns True if the run had been successful
304
305 pipefile: string or None
306 """
307 success = False
308 if rebuild_if_required and not self.is_built and not self.build_was_successful:
309 self.build()
310
311 if not rebuild_if_required or (self.is_built and self.build_was_successful):
312 print( "run executable " + str(executable))
313
314 invocation = []
315 if prefix!=None:
316 invocation += prefix
317 invocation += ["./" + executable]
318 invocation += args
319
320 try:
321 result = None
322 if pipefile==None:
323 result = subprocess.run( invocation, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
324 else:
325 result = subprocess.run( invocation, stdout=open( pipefile, "w" ), stderr=subprocess.PIPE )
326 if result.returncode==0:
327 if pipefile==None:
328 print( result.stdout.decode("utf-8") )
329 if result.stderr!=None:
330 print( result.stderr.decode("utf-8") )
331 print( "run completed without error code, but check for warnings and numerical assertions/errors" )
332 else:
333 print( result.stderr.decode("utf-8") )
334 print( "run failed" )
335 success = True
336 except Exception as e:
337 print( "run of application was not successful: " + str(e) )
338 print( "invocation: " + str(invocation) )
339 else:
340 print( "cannot run as code compilation has not been successful" )
341 return success
342
343
345 subproject: 'Project',
346 master = False): #, subnamespace: str #def merge
347 """!
348 Adds a new Peano4 project into this Peano 4 project
349 """
350 """
351 assert(
352 lhs.namespace == rhs.namespace
353 ), "namespaces of the projects being merged don't match"
354
355 assert(
356 lhs.directory == rhs.directory
357 ), "directories of the projects being merged don't match"
358
359 assert(
360 lhs.output.makefile.d["CXX"] == lhs.output.makefile.d["CXX"]
361 ), "CXX compilers of the projects being merged don't match"
362
363 assert(
364 lhs.output.makefile.d["FC"] == lhs.output.makefile.d["FC"]
365 ), "FC compilers of the projects being merged don't match"
366
367 assert(
368 lhs.output.makefile.d["DIM"] == lhs.output.makefile.d["DIM"]
369 ), "dimensions of the projects being merged don't match"
370
371 assert(
372 lhs.output.makefile.d["MODE"] == lhs.output.makefile.d["MODE"]
373 ), "compile modes of the projects being merged don't match"
374 """
375 # assert(
376 # lhs._domain_offset == rhs._domain_offset and
377 # lhs._domain_size == rhs._domain_size and
378 # lhs._dimensions == rhs._dimensions and
379 # lhs._plotter_precision == rhs._plotter_precision
380 # ), "global simulation parameters of the projects being merged don't match"
381
382 # an internal utility function to merge two dictionaries
383 # def _merge(lhs_dict: dict, rhs_dict: dict) -> dict:
384 # dict_merged = lhs_dict.copy()
385 # for key,value in rhs_dict.items():
386 # if key in dict_merged:
387 # dict_merged[key] += value
388 # else:
389 # dict_merged[key] = value
390 # return dict_merged
391
392 assert(subproject._subdirectory != ""), "subdirectory of a subproject mustn't be empty"
393
394 self.namespace = subproject.namespace
395 self.namespaces.append(subproject.namespace)
396 self.datamodel.namespace = subproject.datamodel.namespace
397 self.datamodel._subdirectory = subproject.datamodel._subdirectory
398 if not subproject.subdirectory in self.subdirectories:
399 self.subdirectories.append(subproject.subdirectory)
400 self.temporary_subdirectories.append(tempfile.mkdtemp())
401 if not self.datamodel.namespace in self.datamodel.namespaces:
402 self.datamodel.namespaces.append(self.datamodel.namespace)
403 if not self.datamodel.subdirectory in self.datamodel.subdirectories:
404 self.datamodel.subdirectories.append(self.datamodel.subdirectory)
405
406
407 #
408 # merge all DaStGen2 and ParticleSet attributes of datamodel
409 #
410 for data in subproject.datamodel.cell_data:
411 self.datamodel.add_cell(data)
412 for data in subproject.datamodel.face_data:
413 self.datamodel.add_face(data)
414 for particle in subproject.datamodel.vertex_data:
415 self.datamodel.add_vertex(particle)
416 for particle in subproject.datamodel.global_data:
417 self.datamodel.add_global(particle)
418
419 #
420 # merge all steps of solversteps
421 #
422
423 # make the steps currently contained in the Peano4 project aware of the incoming subproject's data
424 for step in self.solversteps._steps:
425 added_step = subproject.solversteps._steps[0]
426 step.cell_data.extend(added_step.cell_data)
427 step.face_data.extend(added_step.face_data)
428 step.vertex_data.extend(added_step.vertex_data)
429
430 # make the incoming subproject's steps aware of the Peano4 project data
431 if len(self.solversteps._steps):
432 for added_step in subproject.solversteps._steps:
433 step = self.solversteps._steps[0]
434 added_step.cell_data.clear()
435 added_step.cell_data.extend(step.cell_data)
436 added_step.face_data.clear()
437 added_step.face_data.extend(step.face_data)
438 added_step.vertex_data.clear()
439 added_step.vertex_data.extend(step.vertex_data)
440
441 # finally append the incoming subproject's steps to the Peano4 project's steps
442 for step in subproject.solversteps._steps:
443 self.solversteps._steps.append(step)
444
445 #
446 # merge all keys and strings of output.makefile
447 #
448
449 # ... for compilers
450 if (self.output.makefile.d["CXX"]):
451 assert (
452 self.output.makefile.d["CXX"] == subproject.output.makefile.d["CXX"]
453 ), "the CXX compiler of the subproject being added doesn't match the one of the main project"
454 else:
455 self.output.makefile.d["CXX"] = subproject.output.makefile.d["CXX"]
456
457 if (self.output.makefile.d["FC"]):
458 assert (
459 self.output.makefile.d["FC"] == subproject.output.makefile.d["FC"]
460 ), "the FC compiler of the subproject being added doesn't match the one of the main project"
461 else:
462 self.output.makefile.d["FC"] = subproject.output.makefile.d["FC"]
463
464 for flag in subproject.output.makefile.d["CXXFLAGS"].split():
465 self.output.makefile.add_CXX_flag(flag)
466
467 for flag in subproject.output.makefile.d["FCFLAGS"].split():
468 self.output.makefile.add_Fortran_flag(flag)
469
470 for flag in subproject.output.makefile.d["LDFLAGS"].split():
471 self.output.makefile.add_linker_flag(flag)
472
473 self.output.makefile.d["LIBS"] += subproject.output.makefile.d["LIBS"]
474 self.output.makefile.d["GENERATED_INCLUDE_DIRS"] |= subproject.output.makefile.d["GENERATED_INCLUDE_DIRS"]
475 self.output.makefile.d["MODE"] = subproject.output.makefile.d["MODE"]
476
477 for module in subproject.output.makefile.d["FORTRAN_MODULES"]:
478 self.output.makefile.add_Fortran_module(module)
479
480 assert (
481 self.output.makefile.d["EXECUTABLENAME"]
482 ), "the name of the main project is empty"
483 if not self.output.makefile.d["DIM"]:
484 self.output.makefile.set_dimension(subproject.output.makefile.d["DIM"])
485 else:
486 assert (
487 self.output.makefile.d["DIM"] == subproject.output.makefile.d["DIM"]
488 ), "the dimensions of the added subproject doesn't match the current one of the main project"
489
490 # ... for filepaths
491 for filename in subproject.output.makefile.hfiles:
492 self.output.makefile.add_h_file(filename, False)
493 for filename in subproject.output.makefile.cppfiles:
494 self.output.makefile.add_cpp_file(filename, False)
495 for filename in subproject.output.makefile.fortranfiles:
496 self.output.makefile.add_Fortran_file(filename, False)
497
498 for filename in subproject.output.makefile.generated_hfiles:
499 self.output.makefile.add_h_file(filename, True)
500 for filename in subproject.output.makefile.generated_cppfiles:
501 self.output.makefile.add_cpp_file(filename, True)
502 for filename in subproject.output.makefile.generated_fortranfiles:
503 self.output.makefile.add_Fortran_file(filename, True)
504
505 #
506 # merge all strings and artefacts of readme
507 #
508 for i in subproject.output.readme._entries:
509 self.output.readme.add_entry(i)
510
511 for i in subproject.output.readme._package_descriptions:
512 self.output.readme.add_package_description(i)
513
514 for i in subproject.output.readme._entries:
515 self.output.readme.add_entry(i)
516
517 for i in subproject.output.artefacts:
518 self.output.add(i)
519
520 #
521 # the last added subproject becomes the master project (which will provide the template for the main file)
522 #
523 if not self.is_extended:
524 self.main = subproject.main
525 self.rootnamespace = subproject.rootnamespace
526 self._subdirectory = subproject._subdirectory
527 self.is_extended = True
528 self.main.merge(subproject.main)
529
530 # self.main.project = self
531 # self.main.overwrite = subproject.main.overwrite
532 # self.main.d.update(subproject.main.d)
533
534 #
535 # merge all constants
536 #
537 self.subconstants.append(subproject.constants)
538
539
540 @property
541 def subdirectory(self):
542 subdirectory = self._subdirectory
543 if subdirectory:
544 subdirectory += "/"
545 return subdirectory
#define assert(...)
Definition LinuxAMD.h:28
Singleton logger for the Peano 4 Python API.
Definition Logger.py:37
Represents a Peano 4 project.
Definition Project.py:26
run(self, executable, args=[], prefix=None, pipefile=None, rebuild_if_required=True)
Runs the code.
Definition Project.py:298
build(self, make=True, make_clean_first=True, throw_away_data_after_build=False, number_of_parallel_builds=-1)
Invokes the underlying make build mechanism on the project.
Definition Project.py:227
set_fenv_handler(self, args)
Definition Project.py:104
generate(self, overwrite=Overwrite.Default, throw_away_data_after_generation=False)
Generate all code.
Definition Project.py:125
__init__(self, namespace, project_name, directory=".", subdirectory="", executable="")
project_name Simple string.
Definition Project.py:44
cleanup(self)
This routine has to be called after you've generated your code.
Definition Project.py:107
add_subproject(self, 'Project' subproject, master=False)
Adds a new Peano4 project into this Peano 4 project.
Definition Project.py:346
Representative of generated Constants.h holding all user-defined constants.
Definition Constants.py:10
Represents the total output generated from the Peano4 data model plus all the operations on it.
Definition Output.py:7
The default sequence sketches what Peano does if there's no main.
All operations within Peano 4 model.
Definition Steps.py:6
The Python-side model of "what happens during one mesh sweep".
Definition __init__.py:1