def plot_full_figure(time_sec=None):

    #loc_file = r'C:\Users\xavier.mouy\Documents\Reports_&_Papers\Papers\10-XAVarray_2020\results\mobile_array_copper\localizations_1m_5cm.nc'
    loc_file = r'C:\Users\xavier.mouy\Documents\Reports_&_Papers\Papers\10-XAVarray_2020\results\mobile_array_copper\localizations_2cm_3m.nc'
    loc_file_matlab = r'C:\Users\xavier.mouy\Documents\Reports_&_Papers\Papers\10-XAVarray_2020\results\mobile_array_copper\localizations_matlab_with_CI.csv'
    audio_file = r'C:\Users\xavier.mouy\Documents\Reports_&_Papers\Papers\10-XAVarray_2020\data\mobile_array\2019-09-14_HornbyIsland_Trident\671404070.190918222812.wav'
    video_file = r'C:\Users\xavier.mouy\Documents\Reports_&_Papers\Papers\10-XAVarray_2020\data\large_array\2019-09-15_HornbyIsland_AMAR_07-HI\3420_FishCam01_20190920T163627.613206Z_1600x1200_awb-auto_exp-night_fr-10_q-20_sh-0_b-50_c-0_i-400_sat-0.mp4'
    hp_config_file = r'C:\Users\xavier.mouy\Documents\Reports_&_Papers\Papers\10-XAVarray_2020\data\mobile_array\2019-09-14_HornbyIsland_Trident\hydrophones_config_HI-201909.csv'
    localization_config_file = r'C:\Users\xavier.mouy\Documents\Reports_&_Papers\Papers\10-XAVarray_2020\config_files\localization_config_mobile_array.yaml'
    t1_sec = 214  #216
    t2_sec = 224  #223

    filter_x = [-5, 5]
    filter_y = [-5, 5]
    filter_z = [-2, 5]
    filter_x_std = 6
    filter_y_std = 9
    filter_z_std = 6

    params = pd.DataFrame({
        'loc_color': ['black'],
        'loc_marker': ['o'],
        'loc_alpha': [1],
        'loc_size': [5],
        'uncertainty_color': ['black'],
        'uncertainty_style': ['-'],
        'uncertainty_alpha': [1],  #0.7
        'uncertainty_width': [0.2],  #0.2
        'x_min': [-1.5],
        'x_max': [1.5],
        'y_min': [-0.5],
        'y_max': [3],
        'z_min': [-1.5],
        'z_max': [1.5],
    })

    ## ###########################################################################
    localization_config = read_yaml(localization_config_file)
    hydrophones_config = pd.read_csv(hp_config_file)
    sound_speed_mps = localization_config['ENVIRONMENT']['sound_speed_mps']
    ref_channel = localization_config['TDOA']['ref_channel']
    hydrophone_pairs = defineReceiverPairs(len(hydrophones_config),
                                           ref_receiver=ref_channel)

    ## load localization results
    loc = Measurement()
    loc.from_netcdf(loc_file)
    loc_data = loc.data

    # used matlab CI
    loc_data = pd.read_csv(loc_file_matlab)

    # ## recalculate data errors
    # diff=[]
    # idx = 0
    # for idx in range(len(loc_data)):
    #     m = loc_data.loc[[idx],['x','y','z']]
    #     tdoa_m = predict_tdoa(m, sound_speed_mps, hydrophones_config, hydrophone_pairs)
    #     tdoa_measured = loc_data.loc[[idx],['tdoa_sec_1','tdoa_sec_2','tdoa_sec_3']].to_numpy()
    #     #diff_temp = (tdoa_m-tdoa_measured.T)**2
    #     if idx==0:
    #         diff = (tdoa_m-tdoa_measured.T)**2
    #     else:
    #         diff = np.vstack((diff,(tdoa_m-tdoa_measured.T)**2))

    # Q = len(loc_data)
    # #M = m.size # number of dimensions of the model (here: X, Y, and Z)
    # #N = len(tdoa_sec) # number of measurements
    # #error_std = np.sqrt((1/(Q*(N-M))) * (sum((tdoa_sec-tdoa_m)**2)))
    # tdoa_errors_std = np.sqrt( (1/Q)*(sum(diff)))

    # #tdoa_errors_std = calc_data_error(tdoa_sec, m, sound_speed_mps,hydrophones_config, hydrophone_pairs)
    # for idx in range(len(loc_data)):
    #     loc_errors_std = calc_loc_errors(tdoa_errors_std, loc_data.loc[[idx],['x','y','z']] , sound_speed_mps, hydrophones_config, hydrophone_pairs)
    #     print('m')

    # Filter
    loc_data = loc_data.dropna(subset=['x', 'y', 'z'])  # remove NaN
    loc_data = loc_data.loc[(loc_data['x'] >= min(filter_x))
                            & (loc_data['x'] <= max(filter_x)) &
                            (loc_data['y'] >= min(filter_y)) &
                            (loc_data['y'] <= max(filter_y)) &
                            (loc_data['z'] >= min(filter_z)) &
                            (loc_data['z'] <= max(filter_z)) &
                            (loc_data['x_std'] <= filter_x_std) &
                            (loc_data['y_std'] <= filter_y_std) &
                            (loc_data['z_std'] <= filter_z_std)]
    # Adjust detection times
    loc_data['time_min_offset'] = loc_data['time_min_offset'] - t1_sec
    loc_data['time_max_offset'] = loc_data['time_max_offset'] - t1_sec

    if time_sec != None:
        loc_data = loc_data.loc[(loc_data['time_max_offset'] <= time_sec)]
    else:
        print('Static')

    # update loc object
    loc.data = loc_data

    # plots
    # fig, ax = plt.subplots(figsize=(6, 1))
    # fig.subplots_adjust(bottom=0.5)
    # n_colors = t2_sec-t1_sec
    # cmap = mpl.cm.get_cmap('CMRmap', n_colors*2)
    # norm = mpl.colors.Normalize(vmin=0, vmax=n_colors)
    # ax_cmap = mpl.colorbar.ColorbarBase(ax, cmap=cmap,
    #                                 norm=norm,
    #                                 orientation='horizontal')
    # ax_cmap.set_label('Time (s)')

    # Plot spectrogram
    fig_final, ax_spectro = plot_spectrogram(audio_file,
                                             loc,
                                             t1_sec,
                                             t2_sec,
                                             geometry=(5, 1, 1))
    ax_spectro.set_title("")
    ax_spectro.get_xaxis().set_visible(False)
    n_colors = t2_sec - t1_sec
    cmap = mpl.cm.get_cmap('viridis', n_colors * 4)
    norm = mpl.colors.Normalize(vmin=0, vmax=n_colors)
    divider = make_axes_locatable(ax_spectro)
    cax = divider.append_axes('bottom', 0.1, pad=0.03)
    ax_cmap = mpl.colorbar.ColorbarBase(cax,
                                        cmap=cmap,
                                        norm=norm,
                                        orientation='horizontal')
    ax_cmap.set_label('Time (s)')

    if time_sec:
        SFreq_min, SFreq_max = ax_spectro.get_ylim()
        ax_spectro.plot([time_sec, time_sec], [SFreq_min, SFreq_max], 'r')

    # plot detection points on top of spectrogram
    #gs0 = fig_final.add_gridspec(60,1)
    ax_detec = fig_final.add_subplot(20, 1, 1)
    det_y = np.asarray(np.ones((1, len(loc_data['time_min_offset']))))[0]
    det_x = np.asarray(loc_data['time_min_offset'])
    ax_detec.scatter(det_x,
                     det_y,
                     c=loc_data['time_min_offset'],
                     cmap=cmap,
                     norm=norm,
                     s=12)
    ax_detec.set_xlim(ax_spectro.get_xlim())
    ax_detec.get_xaxis().set_visible(False)
    ax_detec.get_yaxis().set_visible(False)
    ax_detec.axis('off')

    # #pos =[left, bottom, width, height]
    # box = ax_detec.get_position()
    # box.y0 = box.y0 + 0.6
    # box.y1 = box.y1 + 0.6
    # ax_detec.set_position(box)

    #size = fig_final.get_size_inches()

    plt.subplots_adjust(left=0.08,
                        bottom=0.1,
                        right=0.95,
                        top=0.95,
                        wspace=0,
                        hspace=0)

    # divider2 = make_axes_locatable(ax_spectro)
    # cax2 = divider2.append_axes('top', size=0.2, pad=10.0)
    # det_y = np.asarray(np.ones((1,len(loc_data['time_min_offset']))))[0]
    # det_x = np.asarray(loc_data['time_min_offset'])
    # cax2.plot(det_x,det_y,'.r')
    # cax2.set_xlim(ax_spectro.get_xlim())

    # ax_cmap = mpl.colorbar.ColorbarBase(cax, cmap=cmap,
    #                                     norm=norm,
    #                                     orientation='horizontal')

    gs = fig_final.add_gridspec(3, 2)

    # plot localization top
    ax_toploc = fig_final.add_subplot(gs[1:, 1])
    plot_top_view(hydrophones_config, loc_data, params, cmap, norm, ax_toploc)
    ax_toploc.set_anchor('E')

    # plot localization side
    #ax_sideloc = fig_final.add_subplot(3,3,7,sharex = ax_toploc)
    ax_sideloc = fig_final.add_subplot(gs[1:, 0])
    plot_side_view(hydrophones_config, loc_data, params, cmap, norm,
                   ax_sideloc)
    ax_sideloc.set_anchor('W')

    # set the spacing between subplots
    plt.subplots_adjust(wspace=0, hspace=0)

    # # plot video frame 1
    # fig_video1, ax_video1 = plt.subplots(1,1)
    # frame1_sec = 152.8 # second detection -> 16:38:59.8
    # #ax_video1 = fig_final.add_subplot(3,3,5)
    # plot_video_frame(video_file,frame1_sec, ax_video1)
    # ax_video1.get_xaxis().set_visible(False)
    # ax_video1.get_yaxis().set_visible(False)

    # # plot video frame 2
    # fig_video2, ax_video2 = plt.subplots(1,1)
    # frame2_sec = 160 # 4th detection -> 16:39:07
    # #ax_video2 = fig_final.add_subplot(3,3,6)
    # plot_video_frame(video_file,frame2_sec, ax_video2)
    # ax_video2.get_xaxis().set_visible(False)
    # ax_video2.get_yaxis().set_visible(False)

    fig_final.set_size_inches(9.08, 6.72)

    box = ax_spectro.get_position()
    box.y0 = box.y0 - 0.03
    box.y1 = box.y1 - 0.03
    ax_spectro.set_position(box)
    return fig_final
# detec_idx_forced = 9

# # Config files mini array - Mill Bay - Copper RockFish on top of fishcam 
# deployment_info_file = r'C:\Users\xavier.mouy\Documents\Reports_&_Papers\Papers\10-XAVarray_2020\data\mini_array\deployment_info.csv'
# hydrophones_config_file = r'C:\Users\xavier.mouy\Documents\Reports_&_Papers\Papers\10-XAVarray_2020\data\mini_array\hydrophones_config_05-MILL.csv'
# detection_config_file = r'C:\Users\xavier.mouy\Documents\Reports_&_Papers\Papers\10-XAVarray_2020\config_files\detection_config_mini_array_copper.yaml'
# localization_config_file = r'C:\Users\xavier.mouy\Documents\Reports_&_Papers\Papers\10-XAVarray_2020\config_files\localization_config_mini_array.yaml'
# infile = r'C:\Users\xavier.mouy\Documents\Reports_&_Papers\Papers\10-XAVarray_2020\data\mini_array\671404070.190801232502.wav'
# t1 = 696
# t2 = 713
# #detec_idx_forced = 2


# load configuration parameters
hydrophones_config= pd.read_csv(hydrophones_config_file, skipinitialspace=True, dtype={'name': str, 'file_name_root': str}) # load hydrophone coordinates (meters)
detection_config = read_yaml(detection_config_file)
localization_config = read_yaml(localization_config_file)
if localization_config['METHOD']['linearized_inversion']:
    localization_method_name = 'Linearized inversion'
    if localization_config['METHOD']['grid_search']:
        raise ValueError('Only 1 localization method allowed.')
else:
    localization_method_name = 'Grid search'
    if localization_config['METHOD']['grid_search'] == False:
        raise ValueError('At least 1 localization method needs to be defined.')

# Look up data files for all channels
audio_files = find_audio_files(infile, hydrophones_config)

# run detector on selected channel
print('DETECTION')