Generate runnable code from a modelΒΆ
Code generation is the process of representing the CellML model in another language format. At the time of writing, two profiles are available: C (default) and Python. There are four steps to code generation:
Create a
Generatoritem and select the profile language. (The default profile is C).Pass a model to the generator for processing.
Retrieve the generated implementation code. This is the contents of the
*.cfile (if C is the profile) or*.pyif Python is selected.(optional) Retrieve the generated interface code. This is the contents of the
*.hfile, and is not required for the Python profile.
Generate code from a model
// Generate runnable code in other language formats for this model.
// Create a Generator instance. Note that by default this uses the C language profile.
auto generator = libcellml::Generator::create();
// Pass the generator the model for processing.
generator->setModel(analyser->model());
printIssues(generator);
// Retrieve and write the interface code (*.h) and implementation code (*.c) to files.
std::ofstream outFile("sineComparisonExample.h");
outFile << generator->interfaceCode();
outFile.close();
outFile.open("sineComparisonExample.c");
outFile << generator->implementationCode();
outFile.close();
// If required, change the generator profile to Python.
auto profile = libcellml::GeneratorProfile::create(libcellml::GeneratorProfile::Profile::PYTHON);
generator->setProfile(profile);
// Retrieve and write the implementation code (*.py) to a file.
outFile.open("sineComparisonExample.py");
outFile << generator->implementationCode();
outFile.close();
Full context: example_simulationToolDev.cpp
# Generate runnable code in other language formats for this model.
# Create a Generator instance. Note that by default this is the C language.
generator = Generator()
# Pass the generator the analysed model for processing.
generator.processModel(analyser.model())
print_issues_to_terminal(generator)
# Retrieve and write the interface code (*.h) and implementation code (*.cpp) to files.
write_file = open("sineComparisonExample.h", "w")
write_file.write(generator.interfaceCode())
write_file.close()
write_file = open("sineComparisonExample.cpp", "w")
write_file.write(generator.implementationCode())
write_file.close()
# If required, change the generator profile to Python and reprocess the model.
profile = GeneratorProfile(GeneratorProfile.Profile.PYTHON)
generator.setProfile(profile)
generator.processModel(model)
# Retrieve and write the implementation code (*.py) to a file.
write_file = open("sineComparisonExample.py", "w")
write_file.write(generator.implementationCode())
write_file.close()
Full context: example_simulationToolDev.py