Parse and print CellML syntax¶
Parse from a CellML format file¶
The following code will read a file called sine_comparison.cellml and deserialise its contents into a Model instance.
Note that both the Parser class and its opposite number, the Printer class, deal with strings rather than files.
You’ll need to read the file into a string, and then use the string as input to the Parser item.
Parse a model from a CellML file
// Parse a CellML file into a model.
// Read the file containing the CellML model into a string.
std::string inFileName = "simulationExample.cellml";
std::ifstream inFile(inFileName);
std::stringstream inFileContents;
inFileContents << inFile.rdbuf();
std::cout << "Opening the CellML file" << std::endl;
// Create a libCellML Parser, and use it to parse the fileContents
// string and convert it into a CellML Model structure.
auto parser = libcellml::Parser::create();
auto model = parser->parseModel(inFileContents.str());
printIssues(parser);
Full context: example_simulationToolDev.cpp
# Parse the model from a CellML file.
# Create a libCellML Parser, and use it to parse the fileContents
# string and convert it into a CellML Model structure.
read_file = open("resources/simulationExample.cellml", "r")
parser = Parser()
model = parser.parseModel(read_file.read())
print_issues_to_terminal(parser)
Full context: example_simulationToolDev.py
Print a model to CellML format¶
The Printer class has the opposite functionality to the Parser class.
It accepts an existing ModelPtr and creates a string which can be written to a file.
As with the Parser and the Validator, the Printer also records a collection of Issue items which can be accessed as shown below.
// Create a Printer instance.
auto printer = libcellml::Printer::create();
// The output of the printModel function is a string representing the serialised input model.
std::string serialisedModelString = printer->printModel(model);
// Check the printer for issues.
assert(printer->issueCount() == 0);
// Write the serialised string to a file.
std::string outFileName = "my_printed_file.cellml";
std::ofstream outFile(outFileName);
outFile << serialisedModelString;
outFile.close();
from libcellml import Printer
# Create a Printer instance.
printer = Printer()
# The output of the printModel function is a string representing the serialised input model.
serialised_model = printer.printModel(model)
# Check the printer for issues.
assert(printer.issueCount() == 0)
# Write the string to a file.
write_file = open("my_printed_file.cellml", "w")
write_file.write(serialised_model)
write_file.close()
Details of any issues that the printer encounters and records can be retrieved as described on the Retrieve Issue items page.