pymoo icon indicating copy to clipboard operation
pymoo copied to clipboard

Use RunningMetric and save the graph in a PNG file

Open ghost opened this issue 2 years ago • 1 comments

I'm trying to print the RunningMetric, as described here in the documentation.

However my code run on a remote server, with no graphical interface. So I'd like to save the graph to a file.

But I can't find the way to do this.


For other visualizations, I could do :

plot = Radar(...)
plot.add(...)
plot.save("x.png")

But not for RunningMetric...

Any idea how to do that ?

ghost avatar Jul 21 '22 04:07 ghost

As a workaround, I'm defining myself the logic for saving an image :

import matplotlib.pyplot as plt
import numpy as np

from pymoo.util.running_metric import RunningMetric


class RunningMetric2(RunningMetric):

    def save(self, filename="running.png"):
        metric = self.term.get_metric()
        metrics = self.term.metrics
        tau = len(metrics)
        _delta_f = metric["delta_f"]
        _delta_ideal = [m['delta_ideal'] > 0.005 for m in metrics]
        _delta_nadir = [m['delta_nadir'] > 0.005 for m in metrics]

        fig, ax = plt.subplots()

        for k, f in self.hist:
            ax.plot(np.arange(len(f)) + 1, f, label="t=%s" % (k+1), alpha=0.6, linewidth=3)
        ax.plot(np.arange(len(_delta_f)) + 1, _delta_f, label="t=%s (*)" % (tau+1), alpha=0.9, linewidth=3)

        for k in range(len(_delta_ideal)):
            if _delta_ideal[k] or _delta_nadir[k]:
                ax.plot([k+1, k+1], [0, _delta_f[k]], color="black", linewidth=0.5, alpha=0.5)
                ax.plot([k+1], [_delta_f[k]], "o", color="black", alpha=0.5, markersize=2)

        ax.set_yscale("symlog")
        ax.legend()

        ax.set_xlabel("Generation")
        ax.set_ylabel("$\Delta \, f$", rotation=0)

        plt.savefig(filename)

I will not close this issue now, as I believe this should be included in the library, but feel free to close if you think otherwise !

ghost avatar Jul 21 '22 05:07 ghost