• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

transentis / bptk_py / 18773402293

22 Oct 2025 07:27AM UTC coverage: 86.514% (-3.6%) from 90.141%
18773402293

push

github

olivergrasl
remove global

6242 of 7215 relevant lines covered (86.51%)

0.87 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

98.44
/BPTK_Py/visualizations/visualize.py
1
#                                                       /`-
2
# _                                  _   _             /####`-
3
# | |                                | | (_)           /########`-
4
# | |_ _ __ __ _ _ __  ___  ___ _ __ | |_ _ ___       /###########`-
5
# | __| '__/ _` | '_ \/ __|/ _ \ '_ \| __| / __|   ____ -###########/
6
# | |_| | | (_| | | | \__ \  __/ | | | |_| \__ \  |    | `-#######/
7
# \__|_|  \__,_|_| |_|___/\___|_| |_|\__|_|___/  |____|    `- # /
8
#
9
# Copyright (c) 2018 transentis labs GmbH
10
# MIT License
11

12

13

14
import statistics
1✔
15
import pandas as pd
1✔
16

17

18
class visualizer():
1✔
19
    """
20
    Class for building plots from dataframes. Includes capabilities to produce time series data.
21
    Can also only modify dataframes to generate time series and return the modified dataframe
22
    """
23

24
    def __init__(self,config=None):
1✔
25
        self.config = config
1✔
26

27
    def plot(self, df, return_df, visualize_from_period, visualize_to_period, stacked, kind, title, alpha, x_label,
1✔
28
             y_label, start_date="1/1/2018", freq="D", series_names={},format="plot"):
29
        """
30
        Plot method. Creates plots from dataframes
31
        :param df: DataFrame input
32
        :param return_df: Flag. If true return a dataFrame and do not plot (default: False)
33
        :param visualize_from_period: visualize from a specific t (default: 0)
34
        :param visualize_to_period:  visualize until a specific t (default: model's stoptime)
35
        :param stacked: If True, use stacked series (default: False)
36
        :param kind: 'area' or 'line' plot (ldefault: area)
37
        :param title: Title of plot
38
        :param alpha: Alpha of series (default: see config!)
39
        :param x_label: x_label of plot
40
        :param y_label: y_label of plot
41
        :param start_date: Start date for time series
42
        :param freq: Frequency setting for time series
43
        :param series_names: series renaming patterns
44
        :return: depends on format flag: either just a plot, which formally returns nothing, or Matplotlib axes, or a dataframe
45
        """
46

47
        if not kind:
1✔
48
            kind=self.config.configuration["kind"]
1✔
49

50
        if not stacked:
1✔
51
            stacked = self.config.configuration["stacked"]
1✔
52

53
        if not alpha:
1✔
54
            alpha = self.config.configuration["alpha"]
1✔
55

56
        if not start_date == "":
1✔
57
            df.index = pd.date_range(start_date, periods=len(df), freq=freq)
1✔
58

59
        series_names_keys = series_names.keys()
1✔
60

61
        if len(series_names) > 0:
1✔
62

63

64
            new_columns = {}
1✔
65
            for column in df.columns:
1✔
66
                for series_names_key in series_names_keys:
1✔
67
                    if series_names_key in column:
1✔
68
                        new_column = column.replace(series_names_key, series_names[series_names_key])
1✔
69
                        new_columns[column] = new_column
1✔
70

71
            df.rename(columns=new_columns, inplace=True)
1✔
72

73
        ## If user did not set return_df=True, plot the simulation results (default behavior)
74
        if not (return_df or format=="df"):
1✔
75

76
            ### Get the plot object
77
            if visualize_to_period == 0:
1✔
78

79
                ax = df.iloc[visualize_from_period:].plot(kind=kind, stacked=stacked,
1✔
80
                                                          figsize=self.config.configuration["figsize"],
81
                                                          title=title,
82
                                                          alpha=alpha, color=self.config.configuration["colors"],
83
                                                          lw=self.config.configuration["linewidth"])
84

85
            elif visualize_from_period == visualize_to_period:
1✔
86
                print("[INFO] No data to plot for period t={} to t={}".format(str(visualize_from_period),
1✔
87
                                                                              str(visualize_to_period)))
88
                return None
1✔
89

90
            else:
91
                if visualize_to_period + 1 > len(df):
1✔
92
                    visualize_to_period = len(df)
1✔
93

94
                ax = df.iloc[visualize_from_period:visualize_to_period].plot(kind=kind, stacked=stacked,
1✔
95
                                                                             figsize=self.config.configuration["figsize"],
96
                                                                             title=title,
97
                                                                             alpha=alpha,
98
                                                                             color=self.config.configuration["colors"],
99
                                                                             lw=self.config.configuration["linewidth"])
100
                ### Set axes labels and set the formats
101
            if (len(x_label) > 0):
1✔
102
                ax.set_xlabel(x_label)
1✔
103

104
                # Set the y-axis label
105
            if (len(y_label) > 0):
1✔
106
                ax.set_ylabel(y_label)
1✔
107

108
            for ymaj in ax.yaxis.get_majorticklocs():
1✔
109
                ax.axhline(y=ymaj, ls='-', alpha=0.05, color=(34.1 / 100, 32.9 / 100, 34.1 / 100))
1✔
110

111
            self.update_plot_formats(ax)
1✔
112

113
            if format=="axes":
1✔
114
                return ax
×
115
            else:
116
                return
1✔
117

118
        ### If user wanted a dataframe instead, here it is!
119
        elif return_df or format=="df":
1✔
120
            if visualize_to_period == 0:
1✔
121
                return df.iloc[visualize_from_period:]
1✔
122
            elif visualize_from_period == visualize_to_period:
1✔
123
                print("[INFO] No data for period t={} to t={}".format(str(visualize_from_period + 1),
1✔
124
                                                                      str(visualize_to_period + 1)))
125
                return None
1✔
126
            else:
127
                return df.iloc[visualize_from_period:visualize_to_period]
1✔
128

129

130

131
    def update_plot_formats(self, ax):
1✔
132
        """
133
        Configure the plot formats for the labels. Generates the formatting for y labels
134
        :param ax:
135
        :return:
136
        """
137
        ylabels_mean = statistics.mean(ax.get_yticks())
1✔
138

139

140
        # Override the format based on the mean values
141

142
        import matplotlib.ticker as ticker
1✔
143

144
        def label_format(x,pos):
1✔
145
            if ylabels_mean <= 2.0 and ylabels_mean >= -2.0:
1✔
146
                label = format(x, ',.2f')
1✔
147

148
            elif ylabels_mean <= 10.0 and ylabels_mean >= -10.0:
1✔
149
                label = format(x, ',.1f')
1✔
150

151
            else:
152
                label = format(x, ',.0f')
1✔
153

154
            return label
1✔
155

156

157
        ax.yaxis.set_major_formatter(ticker.FuncFormatter(func=label_format))
1✔
158

159
        ## Quick fix for incompatibility of scientific notation and ticklabels
160
        try:
1✔
161
            ax.ticklabel_format(style='plain')
1✔
162
        except:
1✔
163
            pass
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc