Esempio n. 1
0
    def plot_progress(tech, T):
        P_tech = T[T['tech'] == tech]['progress']
        P_tech = [P for P in P_tech if len(P.shape) > 0]
        nDists = np.concatenate([P['new_dist'].astype(float) for P in P_tech])
        oDists = np.concatenate([P['old_dist'].astype(float) for P in P_tech])
        dDists = oDists - nDists

        fig, ax = plotting.subplots(1,
                                    2,
                                    figsize_adjust=(1.0, 0.5),
                                    constrained_layout=True)
        ax[0].hist(nDists, bins=args.hist_bins, **tech_style(tech))
        ax[0].axvline(x=0, lw=1, color='black')
        ax[0].set_ylabel(r'\#steps where new distance is $d$')
        ax[0].set_xlabel(r'Distance ($d$ — ' + tech + r')')
        ax[1].hist(dDists, bins=args.hist_bins, **tech_style(tech))
        ax[1].axvline(x=0, lw=1, color='black')
        ax[1].set_ylabel(r'\#steps where progress is $\delta$')
        ax[1].set_xlabel(r'Progress ($\delta$ — ' + tech + r')')
        plotting.show(fig,
                      outdir=outdir,
                      basefilename=filename(tech + '-dist-n-progress'),
                      w_pad=0.06)
def freeyaw():
    """
    Selected time series of free yaw response cases
    """

    fpath = 'data/calibrated/DataFrame'
    fdir = 'figures/freeyaw'

    fname1 = '0405_run_277_9.0ms_dc1_flexies_freeyaw_highrpm.h5'
    fname2 = '0410_run_330_9ms_dc1_samoerai_freeyaw_highrpm.h5'

    flex = pd.read_hdf(os.path.join(fpath, fname1), 'table')
    samo = pd.read_hdf(os.path.join(fpath, fname2), 'table')

    fname = '277-vs-330-9ms-rpm'
    fig, axes = plotting.subplots(nrows=1, ncols=1, figsize=(5,2), dpi=120)
    axes = axes.flatten()

    duration = 15

    ax = axes[0]
    t0 = 48
    i0 = int(t0*129024/63.0)
    i1 = i0 + int(duration*129024/63.0)
    ax.plot(flex.time[i0:i1]-t0, flex.rpm[i0:i1], 'b-', label='straight blade')
    t0 = 49.6
    i0 = int(t0*69000/69.0)
    i1 = i0 + int(duration*69000/69.)
    ax.plot(samo.time[i0:i1]-t0, samo.rpm[i0:i1], 'r-', label='swept blade', alpha=0.7)

    for ax in axes:
        leg = ax.legend(loc='best', borderaxespad=0)
        leg.get_frame().set_alpha(0.6)
        ax.grid(True)

    ax.set_xlabel('time [s]')
    ax.set_ylabel('RPM')
    ax.set_xlim([0, 15])

    fig.tight_layout()
    fig.subplots_adjust(top=0.92)
#    fig.suptitle('windspeed 9 m/s')
    print('saving: %s' % os.path.join(fdir, fname))
    fig.savefig(os.path.join(fdir, fname + '.png'))
    fig.savefig(os.path.join(fdir, fname + '.eps'))


    # =========================================================================
    fname = '277-vs-330-9ms-yaw'
    fig, axes = plotting.subplots(nrows=1, ncols=1, figsize=(5,2), dpi=120)
    axes = axes.flatten()

    duration = 15

    ax = axes[0]
    t0 = 48
    i0 = int(t0*129024/63.0)
    i1 = i0 + int(duration*129024/63.0)
    ax.plot(flex.time[i0:i1]-t0, flex.yaw_angle[i0:i1], 'b-',
            label='straight blade')
    t0 = 49.6
    i0 = int(t0*69000/69.0)
    i1 = i0 + int(duration*69000/69.)
    ax.plot(samo.time[i0:i1]-t0, samo.yaw_angle[i0:i1], 'r-',
            label='swept blade', alpha=0.7)

    for ax in axes:
        leg = ax.legend(loc='best', borderaxespad=0)
        leg.get_frame().set_alpha(0.6)
        ax.grid(True)

    ax.set_xlabel('time [s]')
    ax.set_ylabel('yaw angle [deg]')
    ax.set_xlim([0, 15])

    fig.tight_layout()
    fig.subplots_adjust(top=0.92)
#    fig.suptitle('windspeed 9 m/s')
    print('saving: %s' % os.path.join(fdir, fname))
    fig.savefig(os.path.join(fdir, fname + '.png'))
    fig.savefig(os.path.join(fdir, fname + '.eps'))
def plot_windbluepower_st_540():
    """Plot the data and add some other constant resistance values to it.
    """

    q_rmax, p_rmax, rpm_rmax, emax = torque_power_at_ohm(28)
    q_rmin, p_rmin, rpm_rmin, emin = torque_power_at_ohm(11)

    # headers:
    # Run #,W [rpm],Rsetting [ohm],Voltage [V],Current [A],tau_input [N-m]
    # P_output [W],Eff [-]
    fname = "data/model/generator-windbluepower-st-540.csv"
    df = pd.read_csv(fname, sep=",")
    rad = df["W [rpm]"].values * np.pi / 30.0
    rpm = df["W [rpm]"].values
    Qc = df["tau_input [N-m]"]
    R = df["Rsetting [ohm]"]
    eff = df["Eff [-]"] * 100.0
    # the torque-rpm grid
    xi = np.linspace(rpm.min(), rpm.max(), 200)
    yi = np.linspace(Qc.min(), Qc.max(), 200)
    cmap = mpl.cm.get_cmap("jet", 8)

    # -------------------------------------------------------------------------
    # iso-lines: dump load resistance value in Ohm
    # grid the data
    zi = mpl.mlab.griddata(rpm, Qc, R, xi, yi, interp="linear")
    # consider switching to: matplotlib.tri.Triangulation or
    # matplotlib.tri.TriInterpolator, see: matplotlib.org/api/tri_api.html
    fig, axes = plotting.subplots(nrows=1, ncols=1, figsize=(4, 2), dpi=120)
    ax = axes.flatten()[0]
    cnt = ax.contour(xi, yi, zi, 8, colors=None, cmap=cmap)  # , vmax=35, vmin=0)
    ax.clabel(cnt, inline=1, fontsize=10, fmt="%1.0f")
    ax.set_xlabel("rotor speed [rpm]")
    ax.set_ylabel("input torque [Nm]")
    ax.grid()
    #    clb = fig.colorbar(cnt)
    #    clb.set_label('color bar label')
    #    leg = ax.legend(loc='best', labelspacing=0, columnspacing=0)
    #    leg.get_frame().set_alpha(0.6)
    fig.tight_layout()
    fig.savefig("figures/generator-st-540-contour.png")
    fig.savefig("figures/generator-st-540-contour.eps")
    # -------------------------------------------------------------------------

    # -------------------------------------------------------------------------
    # iso-lines: efficiency
    # grid the data
    zi = mpl.mlab.griddata(rpm, Qc, eff, xi, yi, interp="linear")
    # consider switching to: matplotlib.tri.Triangulation or
    # matplotlib.tri.TriInterpolator, see: matplotlib.org/api/tri_api.html
    fig, axes = plotting.subplots(nrows=1, ncols=1, figsize=(4, 2), dpi=120)
    ax = axes.flatten()[0]
    cnt = ax.contour(xi, yi, zi, 8, colors=None, cmap=cmap)  # , vmax=35, vmin=0)
    ax.clabel(cnt, inline=1, fontsize=10, fmt="%1.0f")
    ax.set_xlabel("rotor speed [rpm]")
    ax.set_ylabel("input torque [Nm]")
    ax.grid()
    fig.tight_layout()
    fig.savefig("figures/generator-st-540-contour-eff.png")
    fig.savefig("figures/generator-st-540-contour-eff.eps")
    # -------------------------------------------------------------------------

    # -------------------------------------------------------------------------
    fig, axes = plotting.subplots(nrows=1, ncols=1, figsize=(5, 3), dpi=120)
    ax = axes.flatten()[0]

    #    plt.figure()
    #    plt.contour(xi, yi, zi,6, colors='k') #, vmax=35, vmin=0)

    N = len(range(5, 30, 1))
    # select a color map
    cmap = mpl.cm.get_cmap("jet", N)  # hot
    # convert to array
    cmap_arr = cmap(np.arange(N))
    # and now you have each color as an RGB tuple as
    #    for i in cmap_arr:
    #        coltuple = tuple(i[0:3])

    for r, color in zip(range(5, 30, 1), cmap_arr):
        c = tuple(color[0:3])
        q_, p_, rpm_, eff_ = torque_power_at_ohm(r)
        ax.plot(rpm_, q_, ls="-", alpha=0.6, color=c, marker="+")

    #    plt.plot(rpm_rmax, q_rmax, 'r-', label='R=28 (dc0)')
    #    plt.plot(rpm_rmin, q_rmin, 'b-', label='R=11 (dc1)')
    #    plt.legend(loc='best')
    ax.set_xlabel("rotor speed [rpm]")
    ax.set_xlabel("input torque [Nm]")
    ax.grid()
    #    leg = ax.legend(loc='best', labelspacing=0, columnspacing=0)
    #    leg.get_frame().set_alpha(0.6)
    fig.tight_layout()
    fig.savefig("figures/generator-st-540.png")
    fig.savefig("figures/generator-st-540.eps")
Esempio n. 4
0
def plots(args):
    T = read_reports(args.dir)
    outdir = OutputDir(args.outputs, log=True)
    filename = lambda f: args.prefix + '-' + f if args.prefix is not None else f

    T = T[T['crit'] == args.criterion]
    T_init_tests = {
        n: T[T['init_tests'] == n]
        for n in np.unique(T['init_tests'])
    }

    for init_tests in T_init_tests:
        generated_tests = sum(run['report']['#tests'][-1] - init_tests
                              for run in T_init_tests[init_tests])
        n_runs = len(T_init_tests[init_tests])
        print(f'{generated_tests} tests generated for |X_0|={init_tests}'
              '(average = {} test{}/run).'.format(*s_(generated_tests * 1. /
                                                      n_runs)))

    def tech_style(tech):
        return dict(color='blue' if tech == 'pca' else 'red')

    # Progress/ICA

    def plot_progress(tech, T):
        P_tech = T[T['tech'] == tech]['progress']
        P_tech = [P for P in P_tech if len(P.shape) > 0]
        nDists = np.concatenate([P['new_dist'].astype(float) for P in P_tech])
        oDists = np.concatenate([P['old_dist'].astype(float) for P in P_tech])
        dDists = oDists - nDists

        fig, ax = plotting.subplots(1,
                                    2,
                                    figsize_adjust=(1.0, 0.5),
                                    constrained_layout=True)
        ax[0].hist(nDists, bins=args.hist_bins, **tech_style(tech))
        ax[0].axvline(x=0, lw=1, color='black')
        ax[0].set_ylabel(r'\#steps where new distance is $d$')
        ax[0].set_xlabel(r'Distance ($d$ — ' + tech + r')')
        ax[1].hist(dDists, bins=args.hist_bins, **tech_style(tech))
        ax[1].axvline(x=0, lw=1, color='black')
        ax[1].set_ylabel(r'\#steps where progress is $\delta$')
        ax[1].set_xlabel(r'Progress ($\delta$ — ' + tech + r')')
        plotting.show(fig,
                      outdir=outdir,
                      basefilename=filename(tech + '-dist-n-progress'),
                      w_pad=0.06)

    if not args.no_pca_progress:
        plot_progress('pca', T)

    # Progress/ICA

    if not args.no_ica_progress:
        plot_progress('ica', T)

    # Summary

    if not args.no_summary:

        def plot_style(report):
            return tech_style(report['tech'])

        def it_(ax):
            return ax if len(T_init_tests) > 1 else [ax]

        Nms = args.dnn_name  # r'\mathcal{N}_{\mathsf{ms}}'
        cov_label_ = lambda d, n, x: r'\mathrm{' + d + r'}(\mathcal{B}_{' + n + r', ' + x + '})'
        cov_label = lambda n, x: \
                    cov_label_ ('BFCov', n, x) if args.criterion == 'bfc' else \
                    cov_label_ ('BFdCov', n, x)

        fig, ax = plotting.subplots(3,
                                    len(T_init_tests),
                                    sharex='col',
                                    sharey='row',
                                    constrained_layout=True)
        for axi in it_(ax[-1]):
            # unshare x axes for the bottom row:
            g = axi.get_shared_x_axes()
            g.remove(axi)
            for a in g.get_siblings(axi):
                g.remove(a)

        for init_tests, axi in zip(T_init_tests, it_(ax[0])):
            for run in T_init_tests[init_tests]:
                axi.plot(run['report']['#tests'] - init_tests,
                         **plot_style(run))

        from matplotlib.ticker import StrMethodFormatter
        for init_tests, axi in zip(T_init_tests, it_(ax[1])):
            for run in T_init_tests[init_tests]:
                if len(run['report']) == 0:
                    continue
                axi.plot(
                    run['report']['coverage'] - run['report']['coverage'][0],
                    **plot_style(run))
            axi.yaxis.set_major_formatter(StrMethodFormatter('{x:2.1f}'))
            axi.yaxis.set_ticks(
                np.arange(0, np.amax(axi.get_yticks()), step=0.1))

        for init_tests, axi in zip(T_init_tests, it_(ax[2])):
            init_covs = [
                run['report']['coverage'][0]
                for run in T_init_tests[init_tests] if len(run['report']) > 0
            ]
            final_covs = [
                run['report']['coverage'][-1]
                for run in T_init_tests[init_tests] if len(run['report']) > 0
            ]
            bp = axi.boxplot(
                [init_covs, final_covs],
                positions=[0, 20],
                widths=6,
                # labels = [r'initial ($i=0$)', 'final'],
                flierprops=dict(marker='.', markersize=1),
                bootstrap=1000,
                manage_ticks=False)
            axi.yaxis.set_major_formatter(StrMethodFormatter('{x:2.1f}'))
            for box in bp['boxes']:
                box.set(linewidth=.5)
            for box in bp['caps']:
                box.set(linewidth=.5)
            plt.setp(axi.get_xticklabels(), visible=False)

        for init_tests, axi in zip(T_init_tests, it_(ax[1])):
            axi.xaxis.set_tick_params(which='both', labelbottom=True)

        # Set labels and column titles:
        for init_tests, axi in zip(T_init_tests, it_(ax[0])):
            axi.set_title(f'$|X_0| = {init_tests}$')
        for axi in it_(ax[-1]):
            axi.set_xlabel(r'iteration ($i$)')
        it_(ax[0])[0].set_ylabel(r'$|X_i| - |X_0|$')
        it_(ax[1])[0].set_ylabel(r'$' + cov_label(Nms, r'X_i') + '-' +
                                 cov_label(Nms, r'X_0') + '$')
        it_(ax[2])[0].set_ylabel(r'$' + cov_label(Nms, r'X_i') + '$')
        # it_(ax[-1])[(len (T_init_tests) - 1) // 2 + 1].set_xlabel (r'iteration ($i$)')
        plotting.show(fig,
                      basefilename=filename('summary-per-X0'),
                      outdir=outdir,
                      rect=(.01, 0, 1, 1))
    def get_steps(self, sigs, weights, cutoff_hz=1.0, order=2, window=4.0,
                  x_threshold=2.0, figname=None, min_step_window=2.0):
        """
        Parameters
        ----------

        sigs : list(ndarray(n), ndarray(n))
            List of signals (1D-arrays)
        """

        x = sigs[0]
        y = sigs[1]
        xf, xf_ds, xf_ds_dt, x_regress = self.conditioning(x, cutoff_hz=cutoff_hz,
                                                    order=order, window=window)
        xf_ds_regress = x_regress[:,0]
        yf, yf_ds, yf_ds_dt, y_regress = self.conditioning(y, cutoff_hz=cutoff_hz,
                                                    order=order, window=window)
        yf_ds_regress = y_regress[:,0]

        # select on the product of yf_ds_regress * xf_ds_regress,
        # both need to be steady!
        xw = weights[0]
        yw = weights[1]
        xy_ds = np.abs(xf_ds_regress*xw) + np.abs(yf_ds_regress*yw)

        xf_sel_mask, xf_sel_arg = self.select(xy_ds, x_threshold)

        step_ds_mask, steps_ds = self.steady_steps(xf_sel_mask,
                                                   step_lenght=min_step_window)
        # save steps in high-res sampling of the original signal
        steps = np.round(steps_ds * self.sps / self.freq_ds, 0).astype(np.int)
        np.savetxt(figname.replace('.png', '_steps.txt'), steps)
#        steps_ds_times = self.t_ds[steps_ds.flatten()]
#        steps = np.ndarray(steps_ds.shape) * np.nan
#        for k in range(steps.shape[0]):
#            t0 = self.t_ds[steps[k,0]]
#            t1 = self.t_ds[steps[k,1]]
#            steps[k,0] = np.abs(self.time - t0).argmin()
#            steps[k,0] = np.abs(self.time - t1).argmin()

        if figname is not None:
            print('start plotting...')
            fig, axes = plotting.subplots(nrows=3, ncols=1, figsize=(8,9),
                                          dpi=120)
            ax = axes[0,0]
            ax.set_title('original and filtered signals')
            ax.plot(self.time, x, 'r-', alpha=0.3)
            ax.plot(self.time, xf, 'r-')
            ax.grid()
            axr = ax.twinx()
            axr.plot(self.time, y, 'g-', alpha=0.3)
            axr.plot(self.time, yf, 'g-')

            ax = axes[1,0]
            ax.set_title('lin regr window: %1.02f sec' % window)
            t_mask = self.t_ds.copy()
            t_mask[~xf_sel_mask] = np.nan
            x_mask = xf_ds.copy()
            x_mask[~xf_sel_mask] = np.nan
            ax.plot(self.t_ds, xf_ds, 'r-', alpha=1.0, label='xf ds')
            ax.plot(self.t_ds, x_mask, 'k-+', alpha=0.7, label='xf select')
            ax.grid()
            axr = ax.twinx()
            axr.plot(self.t_ds, yf_ds, 'g-', alpha=0.8, label='yx ds')
            y_mask = yf_ds.copy()
            y_mask[~xf_sel_mask] = np.nan
            axr.plot(self.t_ds, y_mask, 'k-+', alpha=0.7, label='yf select')
            xmin = axr.get_ylim()[0]
            xmax = axr.get_ylim()[1]
            collection = region.span_where(self.t_ds, ymin=xmin, ymax=xmax,
                                           where=xf_sel_mask, facecolor='grey',
                                           alpha=0.4)
            axr.add_collection(collection)
            leg = plotting.one_legend(ax, axr, loc='best')
            leg.get_frame().set_alpha(0.5)

            ax = axes[2,0]
            rpl = (x_threshold, min_step_window)
            ax.set_title('threshold: %1.02f, min step window: %1.2f sec' % rpl)
            ax.plot(self.t_ds, np.abs(xf_ds_regress), 'r-',
                    label='xf lin regress', alpha=0.9)
            ax.plot(self.t_ds, np.abs(yf_ds_regress), 'g-',
                     label='yf lin regress', alpha=0.9)
            ax.plot(self.t_ds, np.abs(xy_ds), 'k-', label='xy*w', alpha=0.7)
            ax.axhline(y=x_threshold, linewidth=1, color='k', linestyle='--',
                       aa=False)
            ax.set_ylim([0,5])
            xmin = ax.get_ylim()[0]
            xmax = ax.get_ylim()[1]
            collection = region.span_where(self.t_ds, ymin=xmin, ymax=xmax,
                                           where=step_ds_mask, facecolor='grey',
                                           alpha=0.4)
            ax.add_collection(collection)
#            axr = ax.twinx()
#            axr.plot(self.t_ds, np.abs(yf_ds_regress), 'g-',
#                     label='yf lin regress', alpha=0.9)
#            ax, axr = plotting.match_yticks(ax, axr)
#            axr.set_ylim([0,5])
#            leg = plotting.one_legend(ax, axr, loc='best')
#            leg.get_frame().set_alpha(0.5)

            ax.grid()
            leg = ax.legend(loc='best')
            leg.get_frame().set_alpha(0.5)

            fig.tight_layout()
            fig.savefig(figname)
            print(figname)

        return steps