Example #1
0
 def test_01(self):
     expected = KS001()
     expected.add_key_value(0, "a", 5)
     string = "|a=5|"
     actual = KS001.parse_str(string)
     self.assertEqual(actual, expected)
     self.assertEqual(expected.dump_str(), string)
Example #2
0
 def test_05(self):
     expected = KS001()
     expected.identifier = "hello"
     expected.add_key_value(0, "a|", 5)
     string = "hello|a||=5|"
     actual = KS001.parse_str(string)
     self.assertEqual(actual, expected)
     self.assertEqual(expected.dump_str(), string)
Example #3
0
 def test_11(self):
     expected = KS001()
     expected.add_key_value("d1", "a", 5)
     expected.add_key_value("d1", "b", 8)
     expected.add_key_value("d2", "foo", "ciao")
     string = "|d1:a=5_b=8|d2:foo=ciao|"
     actual = KS001.parse_str(string)
     self.assertEqual(actual, expected)
Example #4
0
 def test_09(self):
     expected = KS001()
     expected.identifier = "hello"
     expected.add_key_value("d:1", "a", 5)
     expected.add_key_value("d:1", "b", 8)
     string = "hello|d::1:a=5_b=8|"
     actual = KS001.parse_str(string)
     self.assertEqual(actual, expected)
     self.assertEqual(expected.dump_str(), string)
Example #5
0
 def test_10(self):
     expected = KS001()
     expected.identifier = "hello"
     expected.add_key_value("d1", "a", 5)
     expected.add_key_value("d1", "b", 8)
     expected.add_key_value("d2", "foo", "ciao")
     string = "hello|d1:a=5_b=8|d2:foo=ciao|"
     actual = KS001.parse_str(string)
     self.assertEqual(actual, expected)
     self.assertEqual(expected.dump_str(), string)
Example #6
0
    def test_contains_03(self):
        a = KS001()
        a.add_key_value(0, "a", 3)

        b = KS001()
        b.add_key_value(1, "a", 3)
        b.add_key_value(1, "b", 4)

        self.assertEqual(a in b, True)
        self.assertEqual(b in a, False)
Example #7
0
    def test_add_02(self):
        a = KS001()
        a.add_key_value(0, "a", 3)
        a.add_key_value(0, "b", 5)

        b = KS001()
        b.add_key_value("other", "c", 8)
        b.add_key_value("other", "d", 9)

        self.assertEqual(len(a + b), 2)
        self.assertEqual((a + b).dump_str(), "|a=3_b=5|other:c=8_d=9|")
Example #8
0
    def test_14(self):
        expected = KS001()
        expected.add_value_alias("ciao", "c")
        expected.add_key_value("d1", "a", 5)
        expected.add_key_value("d1", "b", 8)
        expected.add_empty_dictionary("d2")

        string = "|d1:a=5_b=8|d2:|"
        actual = KS001.parse_str(string, value_alias=expected.value_aliases)
        self.assertEqual(actual, expected)
        self.assertEqual(expected.dump_str(), string)
Example #9
0
    def test_12(self):
        expected = KS001()
        expected.add_key_alias("foo", "f")
        expected.add_key_value("d1", "a", 5)
        expected.add_key_value("d1", "b", 8)
        expected.add_key_value("d2", "foo", "ciao")

        string = "|d1:a=5_b=8|d2:f=ciao|"
        actual = KS001.parse_str(string, key_alias=expected.key_aliases)
        self.assertEqual(actual, expected)
        self.assertEqual(expected.dump_str(), string)
Example #10
0
    def save_image(self,
                   image_name: KS001,
                   folder: str = None,
                   colon: str = ':',
                   pipe: str = '|',
                   underscore: str = '_',
                   equal: str = '=') -> Any:
        """

        :param image_filename_no_extension:
        :param folder:
        :param save_raw_data: True if you want to save the data of the subplots. To do something, you are required
        to save the subplots as well!
        :return:
        """

        multi_image = image_name.clone()
        multi_image.add_key_value(place=self._dictonary_to_add_information,
                                  key="mode",
                                  value="multi")

        # Create 2x2 sub plots
        mat_gs = gridspec.GridSpec(2, 2)
        mat_fig = plt.figure()

        if self.subtitle is not None:
            real_title = f"{self.title.text}\n{self.subtitle.text}"
        else:
            real_title = f"{self.title.text}"

        total_plots = len(self._plots)
        legend_columns = 3
        legend_rows = np.math.ceil(total_plots / legend_columns)
        ydelta_per_row = 0.05
        title_y = 1 + legend_rows * ydelta_per_row  # each row gives 0.05 of highness

        mat_fig.suptitle(real_title, y=title_y)

        mat_ax1 = mat_fig.add_subplot(mat_gs[0, 0])  # row 0, col 0
        mat_ax2 = mat_fig.add_subplot(mat_gs[0, 1])  # row 0, col 1
        mat_ax3 = mat_fig.add_subplot(mat_gs[1, 0])
        mat_ax4 = mat_fig.add_subplot(mat_gs[1, 1])
        mat_axs = [mat_ax1, mat_ax2, mat_ax3, mat_ax4]

        mat_fig.tight_layout(pad=2, w_pad=2, h_pad=2)
        mat_fig.subplots_adjust(top=0.88)
        # fig.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25, wspace=0.35)

        xaxis_base = self.xaxis.label.text
        yaxis_base = self.yaxis.label.text

        for i, (cumornot, logornot) in enumerate(
                itertools.product([False, True], [False, True])):
            xperks = []
            yperks = []
            sub_image: KS001 = multi_image.clone()

            if cumornot:
                xperks.append('cumulative')
            else:
                xperks.append('linear')

            if logornot:
                yperks.append('log10')
            else:
                yperks.append('identity')

            sub_image.add_key_value(place=self._dictonary_to_add_information,
                                    key="cumulativex",
                                    value=cumornot)
            sub_image.add_key_value(place=self._dictonary_to_add_information,
                                    key="logy",
                                    value=logornot)

            self.xaxis.cumulative = cumornot
            self.xaxis.log10 = False
            self.xaxis.label.text = "{} ({})".format(xaxis_base,
                                                     ','.join(xperks))

            self.yaxis.cumulative = False
            self.yaxis.log10 = logornot
            self.yaxis.label.text = "{} ({})".format(yaxis_base,
                                                     ','.join(yperks))

            plot_figure = MatplotLibPlot2DGraph(xaxis=self.xaxis,
                                                yaxis=self.yaxis,
                                                title=DefaultText(""),
                                                subtitle=None,
                                                use_provided_fig=mat_axs[i])
            plot_figure.legend.visible = False

            for p in self.plots():
                plot_figure.add_plot(p)

            labels, lines = plot_figure.save_image(image_name=sub_image,
                                                   folder=folder,
                                                   colon=colon,
                                                   pipe=pipe,
                                                   underscore=underscore,
                                                   equal=equal)

            if i == 0:
                # print legend
                delta_title = ydelta_per_row if self.subtitle is None else (
                    2 * ydelta_per_row)
                mat_fig.legend(lines,
                               labels,
                               bbox_to_anchor=(0.0, title_y - delta_title),
                               loc='upper left',
                               ncol=legend_columns,
                               borderaxespad=0,
                               frameon=False)

            if self._create_subfigure_images:
                single_image = image_name.clone()
                single_image.add_key_value(
                    place=self._dictonary_to_add_information,
                    key="cumulativex",
                    value=cumornot)
                single_image.add_key_value(
                    place=self._dictonary_to_add_information,
                    key="logy",
                    value=logornot)

                self.xaxis.label.text = xaxis_base
                self.yaxis.label.text = yaxis_base

                single_figure = MatplotLibPlot2DGraph(
                    xaxis=self.xaxis,
                    yaxis=self.yaxis,
                    title=self.title,
                    subtitle=self.subtitle,
                )
                for p in plot_figure.plots():
                    single_figure.add_plot(p)

                single_figure.save_image(image_name=single_image,
                                         folder=folder,
                                         colon=colon,
                                         pipe=pipe,
                                         underscore=underscore,
                                         equal=equal)
Example #11
0
    def save_image(
            self,
            image_name: KS001,
            folder: str = None,
            colon: str = ':',
            pipe: str = '|',
            underscore: str = '_',
            equal: str = '=') -> List[Tuple[str, KS001Str, DataTypeStr]]:
        image_filename_no_ext = image_name.dump_str(colon=colon,
                                                    pipe=pipe,
                                                    underscore=underscore,
                                                    equal=equal)
        logging.info(f"saving image {image_filename_no_ext}")

        if self.use_provided_fig is not None:
            mat_ax = self.use_provided_fig
        else:
            mat_fig = plt.figure()
            mat_ax = mat_fig.add_subplot(1, 1, 1)

        if self.subtitle is not None:
            mat_title = f"{self.title.text}\n{self.subtitle.text}"
        else:
            mat_title = f"{self.title.text}"

        total_plots = len(self._plots)
        legend_columns = 3
        legend_rows = np.math.ceil(total_plots / legend_columns)
        ydelta_per_row = 0.05
        title_y = 1 + legend_rows * ydelta_per_row  # each row gives 0.05
        delta_title = ydelta_per_row if self.subtitle is None else (
            2 * ydelta_per_row)

        if self.legend.visible:
            mat_ax.set_title(mat_title, pad=0, loc="center", y=title_y)
        else:
            mat_ax.set_title(mat_title, pad=0, loc="center")

        mat_ax.set_xlabel(self._xaxis.label.text,
                          fontdict={"size": self._xaxis.label.font_size})
        mat_ax.set_ylabel(self._yaxis.label.text,
                          fontdict={"size": self._yaxis.label.font_size})

        mat_ax.xaxis.set_major_formatter(
            MatPlotCompliantFormatter(self.xaxis.formatter))
        mat_ax.yaxis.set_major_formatter(
            MatPlotCompliantFormatter(self.yaxis.formatter))

        extension = "eps"
        image_abspath = os.path.abspath(
            os.path.join(folder, image_filename_no_ext)) + f".{extension}"

        lines = []
        labels = []

        # we need to generate markers and differentiate marker position by a small delta (otherwise if 2 curves overlap
        # you don't see nor the curve nor the marker.
        # marker_number represents the number of marker that has a curve
        # marker_delta represents how much
        markers = itertools.cycle(('^', '+', 'x', 'd', '*'))
        marker_size = itertools.cycle((2, 2, 2, 2, 2))
        marker_number = 10

        plots = list(self.plots())

        for i, p in enumerate(plots):
            if len(p) != len(self._xaxis):
                raise ValueError(
                    f"xaxis is long {len(self._xaxis)} but the function {p.label} we want to draw is long {len(p)} points! There is something very wrong!"
                )

            if self._xaxis.cumulative:
                actual_draw = np.cumsum(p)
            else:
                actual_draw = p

            marker_step = int(len(self.xaxis) / marker_number)
            if marker_step == 0:
                marker_step = 1

            if len(self.xaxis) >= len(plots):
                start_marker = i
            else:
                start_marker = 0

            line, = mat_ax.plot(
                list(self.xaxis.axis),
                list(actual_draw),
                label=p.label.text,
                linewidth=1,
                marker=next(markers),
                markevery=slice(start_marker, -1, marker_step),
                markersize=next(marker_size),
            )
            lines.append(line)
            labels.append(p.label.text)

            # if the curve has labels, we need to plot them
            if p.has_some_labels():
                for index, (x, (y, label)) in filter(
                        lambda ax: ax[0] in range(start_marker, len(p),
                                                  marker_step),
                        enumerate(zip(self.xaxis.axis,
                                      p.values_and_labels()))):
                    mat_ax.annotate(
                        label,
                        xy=(x, y),
                        xytext=(0, 10),
                        textcoords='offset points',
                        ha='right',
                        va='bottom',
                    )

        # x axis scale
        if self.xaxis.log10:
            mat_ax.set_xscale("log", basex=10)
        else:
            mat_ax.set_xscale("linear")

        # y axis scale
        if self.yaxis.log10:
            mat_ax.set_yscale("log", basey=10)
        else:
            mat_ax.set_yscale("linear")

        # grid
        if self.grid.visible:
            mat_ax.grid(True, axis='both')

        # legend
        if self.legend.visible:
            mat_ax.legend(lines,
                          labels,
                          bbox_to_anchor=(0.0, title_y - delta_title),
                          loc='upper left',
                          ncol=legend_columns,
                          borderaxespad=0,
                          frameon=False)

        logging.info(f"creating image {image_abspath}")
        plt.savefig(image_abspath, bbox_inches='tight', format=extension)

        return [(image_abspath, image_filename_no_ext, extension)]