Ejemplo n.º 1
0
def plot_glab_position(dfCrd: pd.DataFrame,
                       scale: float,
                       logger: logging.Logger,
                       showplot: bool = False):
    """
    plot_glab_position plots the position difference wrt to Nominal a priori position
    """
    cFuncName = colored(os.path.basename(__file__),
                        'yellow') + ' - ' + colored(
                            sys._getframe().f_code.co_name, 'green')

    logger.info('{func:s}: plotting position offset'.format(func=cFuncName))

    # set up the plot
    plt.style.use('ggplot')

    # get info for the plot titles
    plot_title, proc_options, rx_geod = amc.get_title_info(logger=logger)

    # subplots
    fig, ax = plt.subplots(nrows=4, ncols=1, sharex=True, figsize=(16.0, 12.0))

    fig.suptitle('{title:s}'.format(title=plot_title), **glc.title_font)

    # plot annotations
    ax[0].annotate('{conf:s}'.format(conf=amc.dRTK['glab_out']),
                   xy=(0, 1),
                   xycoords='axes fraction',
                   xytext=(0, 0),
                   textcoords='offset pixels',
                   horizontalalignment='left',
                   verticalalignment='bottom',
                   weight='ultrabold',
                   fontsize='small')

    ax[0].annotate(proc_options,
                   xy=(1, 1),
                   xycoords='axes fraction',
                   xytext=(0, 0),
                   textcoords='offset pixels',
                   horizontalalignment='right',
                   verticalalignment='bottom',
                   weight='ultrabold',
                   fontsize='small')

    # copyright this
    ax[-1].annotate(r'$\copyright$ Alain Muls ([email protected])',
                    xy=(1, 0),
                    xycoords='axes fraction',
                    xytext=(0, -50),
                    textcoords='offset pixels',
                    horizontalalignment='right',
                    verticalalignment='bottom',
                    weight='ultrabold',
                    fontsize='x-small')

    # plot the ENU difference xwrt nominal initial position and display the standard deviation, xDOP
    for i, (crd, sdCrd) in enumerate(
            zip(glc.dgLab['OUTPUT']['dENU'], glc.dgLab['OUTPUT']['sdENU'])):
        # select the axis to use for this coordinate
        axis = ax[i]

        # get the statistics for this coordinate
        crd_stats = amc.dRTK['dgLABng']['stats']['crd'][crd]

        # color for markers and alpha colors for error bars
        rgb = mpcolors.colorConverter.to_rgb(glc.enu_colors[i])
        rgb_error = amutils.make_rgb_transparent(rgb, (1, 1, 1), 0.4)

        # plot coordinate differences and error bars
        axis.errorbar(x=dfCrd['DT'].values,
                      y=dfCrd[crd],
                      yerr=dfCrd[sdCrd],
                      linestyle='none',
                      fmt='.',
                      ecolor=rgb_error,
                      capthick=1,
                      markersize=1,
                      color=glc.enu_colors[i])

        # set dimensions of y-axis (double for UP scale)
        if crd == 'dU0':
            axis.set_ylim(
                [crd_stats['wavg'] - scale * 2, crd_stats['wavg'] + scale * 2])
        else:
            axis.set_ylim(
                [crd_stats['wavg'] - scale, crd_stats['wavg'] + scale])

        axis.set_ylabel('{crd:s} [m]'.format(crd=crd, fontsize='large'),
                        color=glc.enu_colors[i],
                        weight='ultrabold')

        # annotate each subplot with its reference position
        stat_str = '\n'.join(
            (r'gLab={:.3f} ($\pm${:.3f})'.format(crd_stats['kf'],
                                                 crd_stats['sdkf']), r'',
             r'WAvg={:.3f} ($\pm${:.3f})'.format(crd_stats['wavg'],
                                                 crd_stats['sdwavg']), r'',
             r'Range=[{:.2f}..{:.2f}]'.format(crd_stats['max'],
                                              crd_stats['min'])))
        # place a text box in upper left in axes coords
        axis.text(1.01,
                  0.95,
                  stat_str,
                  transform=axis.transAxes,
                  fontsize='small',
                  verticalalignment='top',
                  color=glc.enu_colors[i],
                  weight='strong')

        # annotatetxt = markerAnnotation(crd, sdCrd)
        # axis.annotate(annotatetxt, xy=(1, 1), xycoords='axes fraction', xytext=(0, 0), textcoords='offset pixels', horizontalalignment='right', verticalalignment='bottom', weight='ultrabold', fontsize='large')

        # title of sub-plot
        # axis.set_title('{crd:s} offset'.format(crd=str.capitalize(crd), fontsize='large'))
        axis.set_xlabel('')

    # last subplot: number of satellites & PDOP
    # plot #SVs on left axis
    axis = ax[-1]
    axis.set_ylim([0, 24])
    axis.set_ylabel('#SVs [-]',
                    fontsize='large',
                    color='grey',
                    weight='ultrabold')
    # axis.set_xlabel('Time [sec]', fontsize='large')

    # plot the number of SVs and color as function of the GNSSs used
    for (i_gnss, gnss, gnss_color) in zip([1, 1, 2], ['GAL', 'GPS', ''],
                                          ['blue', 'red', 'grey']):
        if i_gnss == 2:
            axis.fill_between(dfCrd['DT'].values,
                              0,
                              dfCrd['#SVs'],
                              where=(dfCrd['#GNSSs'] == i_gnss),
                              alpha=0.25,
                              linestyle='-',
                              linewidth=2,
                              color=gnss_color,
                              interpolate=False)
        else:
            axis.fill_between(dfCrd['DT'].values,
                              0,
                              dfCrd['#SVs'],
                              where=((dfCrd['#GNSSs'] == i_gnss) &
                                     (gnss == dfCrd['GNSSs'])),
                              alpha=0.25,
                              linestyle='-',
                              linewidth=2,
                              color=gnss_color,
                              interpolate=False)

    # plot PDOP on second y-axis
    axis_right = axis.twinx()

    axis_right.set_ylim([0, 10])
    axis_right.set_ylabel('PDOP [-]',
                          fontsize='large',
                          color='darkorchid',
                          weight='ultrabold')

    # plot PDOP value
    axis_right.plot(dfCrd['DT'],
                    dfCrd['PDOP'],
                    linestyle='',
                    marker='.',
                    markersize=1,
                    color='darkorchid',
                    label='PDOP')

    # set limits for the x-axis
    axis.set_xlim([dfCrd['DT'].iloc[0], dfCrd['DT'].iloc[-1]])

    # create the ticks for the time axis
    dtFormat = plot_utils.determine_datetime_ticks(startDT=dfCrd['DT'].iloc[0],
                                                   endDT=dfCrd['DT'].iloc[-1])
    if dtFormat['minutes']:
        axis.xaxis.set_major_locator(
            dates.MinuteLocator(byminute=range(10, 60, 10), interval=1))
    else:
        axis.xaxis.set_major_locator(
            dates.HourLocator(interval=dtFormat['hourInterval']))  # every

    axis.xaxis.set_minor_locator(dates.DayLocator(interval=1))  # every day
    axis.xaxis.set_minor_formatter(dates.DateFormatter('\n%d-%m-%Y'))
    axis.xaxis.set_major_formatter(
        dates.DateFormatter('%H:%M'))  # hours and minutes

    axis.xaxis.set_tick_params(rotation=0)
    for tick in axis.xaxis.get_major_ticks():
        tick.label1.set_horizontalalignment('center')

    # save the plot in subdir png of GNSSSystem
    dir_png = os.path.join(amc.dRTK['dir_root'],
                           amc.dRTK['dgLABng']['dir_glab'], 'png')
    png_filename = os.path.join(
        dir_png,
        '{out:s}-ENU.png'.format(out=amc.dRTK['glab_out'].replace('.', '-')))
    amutils.mkdir_p(dir_png)
    fig.savefig(png_filename, dpi=fig.dpi)

    logger.info('{func:s}: created plot {plot:s}'.format(func=cFuncName,
                                                         plot=colored(
                                                             png_filename,
                                                             'green')))

    if showplot:
        plt.show(block=True)
    else:
        plt.close(fig)

    return
Ejemplo n.º 2
0
def plotUTMOffset(dRtk: dict, dfPos: pd.DataFrame, dfCrd: pd.DataFrame, dCrdLim: dict, logger: logging.Logger, showplot: bool = False):
    """
    plotUTMOffset plots the offset NEU wrt to reference point

    """
    cFuncName = colored(os.path.basename(__file__), 'yellow') + ' - ' + colored(sys._getframe().f_code.co_name, 'green')

    # select colors for E, N, U coordinate difference
    colors = []
    colors.append([51 / 256., 204 / 256., 51 / 256.])
    colors.append([51 / 256., 51 / 256., 255 / 256.])
    colors.append([255 / 256., 51 / 256., 51 / 256.])

    # what to plot
    crds2Plot = ['UTM.E', 'UTM.N', 'ellH', 'ns']
    stdDev2Plot = ['sde', 'sdn', 'sdu']
    annotateList = ['east', 'north', 'ellh', '#SV']

    # find gaps in the data by comparing to mean value of difference in time
    dfPos['tDiff'] = dfPos['DT'].diff(1)
    dtMean = dfPos['tDiff'].mean()

    # look for it using location indexing
    dfPos.loc[dfPos['tDiff'] > dtMean, 'ns'] = np.nan

    amc.logDataframeInfo(df=dfPos, dfName='dfPos', callerName=cFuncName, logger=logger)

    # set up the plot
    plt.style.use('ggplot')

    # subplots
    fig, ax = plt.subplots(nrows=len(crds2Plot), ncols=1, sharex=True, figsize=(20.0, 16.0))
    fig.suptitle('{syst:s} - {posf:s} - {date:s}'.format(posf=dRtk['info']['rtkPosFile'], syst=dRtk['syst'], date=dRtk['Time']['date']))

    # make title for plot
    ax[0].annotate('{syst:s} - {date:s}'.format(syst=dRtk['syst'], date=dfPos['DT'].iloc[0].strftime('%d %b %Y')), xy=(0, 1), xycoords='axes fraction', xytext=(0, 0), textcoords='offset pixels', horizontalalignment='left', verticalalignment='bottom', weight='strong', fontsize='large')

    # copyright this
    ax[-1].annotate(r'$\copyright$ Alain Muls ([email protected])', xy=(1, 1), xycoords='axes fraction', xytext=(0, 0), textcoords='offset pixels', horizontalalignment='right', verticalalignment='bottom', weight='strong', fontsize='large')

    # subplots for coordinates display delta NEU
    for i, crd in enumerate(crds2Plot[:3]):
        axis = ax[i]

        # color for markers and alpha colors for error bars
        rgb = mpcolors.colorConverter.to_rgb(colors[i])
        rgb_new = amutils.make_rgb_transparent(rgb, (1, 1, 1), 0.3)

        # plot coordinate differences and error bars
        axis.errorbar(x=dfPos['DT'], y=dfCrd[crd], yerr=dfPos[stdDev2Plot[i]], linestyle='None', fmt='o', ecolor=rgb_new, capthick=1, markersize=1, color=colors[i])

        # set dimensions of y-axis
        axis.set_ylim([dCrdLim['min'], dCrdLim['max']])
        axis.set_ylabel('{crd:s} [m]'.format(crd=crd, fontsize='large'), color=colors[i])

        # # annotate each subplot with its reference position
        # if [dRtk['marker']['UTM.E'], dRtk['marker']['UTM.N'], dRtk['marker']['ellH']] == [np.NaN, np.NaN, np.NaN]:
        #     # use the mean UTM/ellH position for the reference point
        #     crdRef = dRtk['WAvg'][crd]
        #     crdSD = dRtk['WAvg'][stdDev2Plot[i]]
        #     annotatetxt = r'Mean: {refcrd:.3f}m ($\pm${stddev:.2f}m)'.format(refcrd=crdRef, stddev=crdSD)
        # else:
        #     # we have a reference point
        #     crdRef = dRtk['marker'][crd]
        #     crdOffset = dRtk['marker'][crd] - dRtk['WAvg'][crd]
        #     crdSD = dRtk['WAvg'][stdDev2Plot[i]]
        #     annotatetxt = r'Ref: {crd:s} = {refcrd:.3f}m ({offset:.3f}m $\pm${stddev:.2f}m)'.format(crd=crd, refcrd=crdRef, stddev=crdSD, offset=crdOffset)

        annotatetxt = markerAnnotation(crd, stdDev2Plot[i])

        # put annotation text
        axis.annotate(annotatetxt, xy=(1, 1), xycoords='axes fraction', xytext=(0, 0), textcoords='offset pixels', horizontalalignment='right', verticalalignment='bottom', weight='strong', fontsize='large')

        # title of sub-plot
        axis.set_title('{crd:s} offset'.format(crd=str.capitalize(annotateList[i]), fontsize='large'))

    # last subplot: number of satellites & PDOP
    for _, crd in enumerate(crds2Plot[3:4]):
        # plot #SVs on left axis
        axis = ax[-1]
        axis.set_ylim([0, 24])
        axis.set_ylabel('#SVs [-]', fontsize='large', color='grey')
        # axis.set_xlabel('Time [sec]', fontsize='large')

        axis.fill_between(dfPos['DT'], 0, dfPos['ns'], alpha=0.5, linestyle='-', linewidth=3, color='grey', label='#SVs', interpolate=False)
        # plot PDOP on second y-axis
        axRight = axis.twinx()

        axRight.set_ylim([0, 15])
        axRight.set_ylabel('PDOP [-]', fontsize='large', color='darkorchid')

        # plot PDOP value
        axRight.plot(dfPos['DT'], dfPos['PDOP'], linestyle='-', marker='.', markersize=1, color='darkorchid', label='PDOP')

        # set title
        axis.set_title('Visible satellites & PDOP', fontsize='large')

        # create the ticks for the time axis
        dtFormat = plot_utils.determine_datetime_ticks(startDT=dfPos['DT'].iloc[0], endDT=dfPos['DT'].iloc[-1])

        if dtFormat['minutes']:
            axis.xaxis.set_major_locator(dates.MinuteLocator(byminute=range[1, 60, 5], interval=1))
        else:
            axis.xaxis.set_major_locator(dates.HourLocator(interval=dtFormat['hourInterval']))   # every 4 hours
        axis.xaxis.set_major_formatter(dates.DateFormatter('%H:%M'))  # hours and minutes

        axis.xaxis.set_minor_locator(dates.DayLocator(interval=1))    # every day
        axis.xaxis.set_minor_formatter(dates.DateFormatter('\n%d-%m-%Y'))

        axis.xaxis.set_tick_params(rotation=0)
        for tick in axis.xaxis.get_major_ticks():
            # tick.tick1line.set_markersize(0)
            # tick.tick2line.set_markersize(0)
            tick.label1.set_horizontalalignment('center')

    # save the plot in subdir png of GNSSSystem
    amutils.mkdir_p(os.path.join(dRtk['info']['dir'], 'png'))
    pngName = os.path.join(dRtk['info']['dir'], 'png', os.path.splitext(dRtk['info']['rtkPosFile'])[0] + '-ENU.png')
    fig.savefig(pngName, dpi=fig.dpi)

    logger.info('{func:s}: created plot {plot:s}'.format(func=cFuncName, plot=colored(pngName, 'green')))

    if showplot:
        plt.show(block=True)
    else:
        plt.close(fig)

    return
Ejemplo n.º 3
0
def plot_utm_ellh(dRtk: dict,
                  dfUTM: pd.DataFrame,
                  logger: logging.Logger,
                  showplot: bool = False):
    """
     plots the UTM coordinates

    """
    cFuncName = colored(os.path.basename(__file__),
                        'yellow') + ' - ' + colored(
                            sys._getframe().f_code.co_name, 'green')

    # select colors for position mode
    # colors = []
    # colors.append([51 / 256., 204 / 256., 51 / 256.])
    # colors.append([51 / 256., 51 / 256., 255 / 256.])
    # colors.append([255 / 256., 51 / 256., 51 / 256.])
    colors = [
        'tab:white', 'tab:green', 'tab:olive', 'tab:orange', 'tab:cyan',
        'tab:blue', 'tab:red', 'tab:pink', 'tab:purple', 'tab:brown'
    ]

    # what to plot
    crds2Plot = ['UTM.E', 'UTM.N', 'ellH', 'age']
    stdDev2Plot = ['sde', 'sdn', 'sdu']
    stdDevWAvg = ['sdUTM.E', 'sdUTM.N', 'sdellH']

    # set up the plot
    plt.style.use('ggplot')

    # subplots
    fig, ax = plt.subplots(nrows=len(crds2Plot),
                           ncols=1,
                           sharex=True,
                           figsize=(20.0, 16.0))

    # make title for plot
    ax[0].annotate(
        '{camp:s} - {date:s} - {marker:s} ({pos:s}, quality {mode:s})'.format(
            camp=dRtk['campaign'],
            date=dRtk['obsStart'].strftime('%d %b %Y'),
            marker=dRtk['marker'],
            pos=dRtk['posFile'],
            mode=dRtk['rtkqual'].upper()),
        xy=(0.5, 1),
        xycoords='axes fraction',
        xytext=(0, 0),
        textcoords='offset pixels',
        horizontalalignment='center',
        verticalalignment='bottom',
        weight='strong',
        fontsize='large')

    # copyright this
    ax[-1].annotate(r'$\copyright$ Alain Muls ([email protected])',
                    xy=(1, 1),
                    xycoords='axes fraction',
                    xytext=(0, 0),
                    textcoords='offset pixels',
                    horizontalalignment='right',
                    verticalalignment='bottom',
                    weight='strong',
                    fontsize='large')

    # determine the difference to weighted average or marker position of UTM (N,E), ellH to plot
    dfCrd = pd.DataFrame(columns=crds2Plot[:3])
    originCrds = [float(amc.dRTK['WAVG'][crd]) for crd in crds2Plot[:3]]
    dfCrd = dfUTM[crds2Plot[:3]].sub(originCrds, axis='columns')
    amutils.logHeadTailDataFrame(logger=logger,
                                 callerName=cFuncName,
                                 df=dfCrd,
                                 dfName='dfCrd')

    crdMax = max(dfCrd.max())
    crdMin = min(dfCrd.min())
    crdMax = int(crdMax + (1 if crdMax > 0 else -1))
    crdMin = int(crdMin + (1 if crdMin > 0 else -1))

    # plot the coordinates dN, dE, dU and ns
    for i, crd in enumerate(crds2Plot):
        if i < 3:  # subplots for coordinates display dN, dE, dU
            # plot over the different coordinate offsets using different colors

            # we plot offset to the weighted averga value
            # ax[i].plot(dfUTM['DT'], dCrd[crd], linestyle='', marker='.', markersize=2, color=colors[i], label=crd)
            # ax[i].fill_between(dfUTM['DT'], dCrd[crd]-dfUTM[stdDev2Plot[i]], dCrd[crd]+dfUTM[stdDev2Plot[i]], color=colors[i], alpha=0.15, interpolate=False)

            for key, value in rtkc.dRTKQual.items():
                # get the indices according to the position mode
                idx = dfUTM.index[dfUTM['Q'] == key]
                rgb = mpcolors.colorConverter.to_rgb(colors[key])
                rgb_new = amutils.make_rgb_transparent(rgb, (1, 1, 1), 0.3)

                # plot according to the color list if the length of the index is not 0
                if len(idx) > 0:
                    ax[i].errorbar(x=dfUTM.loc[idx]['DT'],
                                   y=dfCrd.loc[idx][crd],
                                   yerr=dfUTM.loc[idx][stdDev2Plot[i]],
                                   linestyle='None',
                                   fmt='o',
                                   ecolor=rgb_new,
                                   capthick=2,
                                   markersize=2,
                                   color=colors[key],
                                   label=value)

            # set dimensions of y-axis
            ax[i].set_ylim([crdMin, crdMax])
            ax[i].set_ylabel('{crd:s} [m]'.format(crd=crd, fontsize='large'))

            # lcoation of legend
            ax[i].legend(loc='best', markerscale=4)

            # annotate plot
            annotatetxt = r'WAvg: {crd:.3f}m $\pm$ {sdcrd:.3f}m'.format(
                crd=amc.dRTK['WAVG'][crds2Plot[i]],
                sdcrd=amc.dRTK['WAVG'][stdDevWAvg[i]])
            ax[i].annotate(annotatetxt,
                           xy=(1, 1),
                           xycoords='axes fraction',
                           xytext=(0, 0),
                           textcoords='offset pixels',
                           horizontalalignment='right',
                           verticalalignment='bottom',
                           fontweight='bold',
                           fontsize='large')

        else:  # last subplot: age of corrections & #SVs
            # plot #SVs on left axis
            # ax[i].set_ylim([0, 24])

            # plot AGE value
            ax[i].set_ylabel('Age [s]', fontsize='large', color='darkorchid')
            ax[i].set_xlabel('Time [sec]', fontsize='large')
            ax[i].plot(dfUTM['DT'],
                       dfUTM['age'],
                       linestyle='',
                       marker='x',
                       markersize=2,
                       color='darkorchid',
                       label='age')
            ax[i].set_title('#SVs & Age of correction',
                            fontsize='large',
                            fontweight='bold')

            # plot number of SV on second y-axis
            axRight = ax[i].twinx()

            axRight.set_ylim([0, 25])
            axRight.set_ylabel('#SVs [-]', fontsize='large', color='grey')

            ax[i].fill_between(dfUTM['DT'],
                               0,
                               dfUTM['ns'],
                               alpha=0.5,
                               linestyle='-',
                               linewidth=3,
                               color='grey',
                               label='#SVs',
                               interpolate=False)

            # create the ticks for the time axis
            dtFormat = plot_utils.determine_datetime_ticks(
                startDT=dfUTM['DT'].iloc[0], endDT=dfUTM['DT'].iloc[-1])

            if dtFormat['minutes']:
                if dfUTM.shape[0] > 300:
                    ax[i].xaxis.set_major_locator(
                        dates.MinuteLocator(byminute=range(1, 60, 10),
                                            interval=1))
                else:
                    ax[i].xaxis.set_major_locator(
                        dates.MinuteLocator(byminute=range(1, 60), interval=1))

            else:
                ax[i].xaxis.set_major_locator(
                    dates.HourLocator(
                        interval=dtFormat['hourInterval']))  # every 4 hours
            ax[i].xaxis.set_major_formatter(
                dates.DateFormatter('%H:%M'))  # hours and minutes

            ax[i].xaxis.set_minor_locator(
                dates.DayLocator(interval=1))  # every day
            ax[i].xaxis.set_minor_formatter(dates.DateFormatter('\n%d-%m-%Y'))

            ax[i].xaxis.set_tick_params(rotation=0)
            for tick in ax[i].xaxis.get_major_ticks():
                # tick.tick1line.set_markersize(0)
                # tick.tick2line.set_markersize(0)
                tick.label1.set_horizontalalignment('center')

    # save the plot in subdir png of GNSSSystem
    pngName = os.path.join(
        dRtk['posDir'],
        '{name:s}-ENU.png'.format(name=os.path.splitext(dRtk['posFile'])[0]))
    fig.savefig(pngName, dpi=fig.dpi)

    logger.info('{func:s}: created plot {plot:s}'.format(func=cFuncName,
                                                         plot=colored(
                                                             pngName,
                                                             'green')))

    if showplot:
        plt.show(block=True)
    else:
        plt.close(fig)

    return