I have a C++ code which creates an array at each time. (C++ is needed because of the speed - if the code was built directly in Python, it would take 8 days to execute.) The structure of the code looks something like:
const int StopTime = 10000;
int main(void){
int Time = 0;
while(Time<StopTime){
//Create a 2D array of dimensions 10x10 filled with integers
}
}
The final result shall be an animated gif figure, which would display the colormap plots of the 10000 arrays subsequently generated. I am quite familiar with Python's \matplotlib package, so I hope to save all of these 10000 arrays to some file which would then be imported to Python's code a plotted with \matplotlib. How could I do it? Or is there some C++ library to help without the need to export the arrays? The easier to understand and learn, the better. (I am much more confortable working with Python.)
I have already had a look on https://github.com/lava/matplotlib-cpp but I cannot even install it correctly.
Can someone more experienced help me please? Thank you so much!
PS: I am a beginner in both C++ and Python, and mathematician by training.
The quick and dirty approach to such a problem is often to generate python code from your primary program. Here your C++ program. For example, the string [0, 3, 5, 1]
is a valid python fragment defining an array of four values.
So, if you have your std::array<T,N>
or your T[N]
or std::vector<T>
with your data, you can serialise them fairly easily to something that can be used as input to the python interpreter:
template <typename Os, typename It>
void serialise(Os& os, It begin, It end) {
os << '[';
std::string sep;
for (auto it = begin; it != end; ++it) {
os << sep << *it;
sep = ", ";
}
os << " ]";
}
Which you can call with
std::cout << "data = ";
serialise(std::cout,std::begin(data),std::end(data));
std::cout << "\n";
You can easily abstract this for multi-dimensional data structures to print something like [ [1,2,3], [4,5,6] ]
.
You can then wrap your program into a small script (using bash, python, whatever) and have the output of your C++ program be prepended to your matplotlib python script, which then accesses the variable data
.
Consider the following a very rough sketch how you could do it with bash:
# generate data array
./main > run.py
# add actual python code that accesses data
cat matplot.tmpl.py >> run.py
# run generated python program
python3 run.py