Ejemplo n.º 1
0
def main():

    # Read the input file and data of the first run.
    i_clip = None
    dir_PM_1, dir_NM_1, option, l_max_1, _, _ = \
        read_input_NMPostProcess()
    i_mode_1, f_1, l_1, type_1, shell_1 = \
        read_mode_info(dir_NM_1, option, i_clip = i_clip)
    dir_processed = os.path.join(dir_NM_1, 'processed')

    # Read the data of the second run.
    file_compare = 'input_compare.txt'
    with open(file_compare, 'r') as in_id:

        dir_NM_2 = in_id.readline().strip()

    # Read the data of the second run.
    i_mode_2, f_2, l_2, type_2, shell_2 = \
        read_mode_info(dir_NM_2, option, i_clip = i_clip)

    l_max = l_max_1
    compare_two_modes(dir_NM_1, 55, dir_NM_1, 56, l_max)
    compare_two_modes(dir_NM_1, 55, dir_NM_2, 106, l_max)
    compare_two_modes(dir_NM_1, 56, dir_NM_2, 106, l_max)

    return
Ejemplo n.º 2
0
def main():

    parser = argparse.ArgumentParser()
    parser.add_argument('--path_outline', help = 'Specify path to an outline file to be plotted on maps.')
    args = parser.parse_args()
    path_outline = args.path_outline

    # Read the NMPostProcess input file.
    dir_PM, dir_NM, _, l_max, i_mode_str, n_radii = read_input_NMPostProcess()

    # Read the input_plotting file.
    option, i_radius_str, plot_type, i_mode_str, fmt, n_lat_grid, \
    mode_real_or_complex, rotation_period_hrs = read_input_plotting()

    print(option, i_radius_str, plot_type, i_mode_str, fmt, n_lat_grid, mode_real_or_complex, rotation_period_hrs)

    # Decide whether to show the plots.
    if i_mode_str == 'all' or i_radius_str == 'all':

        show = False

    else:

        show = True

    # Plot all modes.
    if i_mode_str == 'all':

        # Spatial plot.
        if plot_type == 'spatial':

            plot_sh_disp_all_modes(dir_NM, n_lat_grid, mode_real_or_complex, fmt = fmt, i_radius_str = i_radius_str,
                    path_outline = path_outline)

        # Spectral plot.
        elif plot_type == 'spectral':

            plot_sh_real_coeffs_3_comp_all_modes(dir_NM, fmt = fmt, i_radius_str = i_radius_str)

        elif plot_type == 'animation':

            raise ValueError('Cannot plot animation for all modes simultaneously.')

        else:

            raise ValueError('Plot type {:} from input file not recognised.'.format(plot_type))

    # Plot one mode.
    else:
        
        i_mode = int(i_mode_str)
        if plot_type == 'spatial':

            plot_sh_disp_wrapper(dir_NM, i_mode, n_lat_grid, mode_real_or_complex, fmt = fmt, i_radius_str = i_radius_str, show = show,
                    path_outline = path_outline)

        elif plot_type == 'spectral':
            
            plot_sh_real_coeffs_3_comp_wrapper(dir_NM, i_mode, fmt = fmt, i_radius_str = i_radius_str, show = show)

        elif plot_type == 'radial_complex':
            
            plot_radial_cmplx_wrapper(dir_NM, i_mode, n_lat_grid, i_radius_str = None)

        elif plot_type == 'animation':

            plot_sh_disp_animation(dir_NM, i_mode, i_radius_str, n_lat_grid, mode_real_or_complex, rotation_period_hrs)

        else:

            raise ValueError('Plot type {:} from input file not recognised.'.format(plot_type))
Ejemplo n.º 3
0
def main():

    print('compare.py:')
    #i_clip = 10
    i_clip = None

    # Read the input file and data of the first run.
    dir_PM_1, dir_NM_1, option, l_max_1, _, _ = \
        read_input_NMPostProcess()
    #i_mode_1, f_1, l_1, type_1, shell_1, coeffs_cplx_1 = \
    i_mode_1, f_1, l_1, type_1, shell_1 = \
        read_mode_info(dir_NM_1, option, i_clip = i_clip)
    dir_processed = os.path.join(dir_NM_1, 'processed')

    # Read the data of the second run.
    file_compare = 'input_compare.txt'
    with open(file_compare, 'r') as in_id:

        dir_NM_2 = in_id.readline().strip()

    # Read the data of the second run.
    #i_mode_2, f_2, l_2, type_2, shell_2, coeffs_cplx_2 = \
    i_mode_2, f_2, l_2, type_2, shell_2 = \
        read_mode_info(dir_NM_2, option, i_clip = i_clip)

    path_fit = os.path.join(dir_processed,
                            'comparison_fit_{:}.npy'.format(option))
    path_index_list = os.path.join(
        dir_processed, 'comparison_fit_indices_{:}.npy'.format(option))
    if os.path.exists(path_fit):

        print('Fit information already exists, loading: {:}'.format(path_fit))
        fit_list = np.load(path_fit, allow_pickle=True)
        index_list = np.load(path_index_list, allow_pickle=True)
        n_mode_1 = len(fit_list)

    else:

        # Read coefficients.
        print('Reading coefficients.')
        coeffs_cplx_1 = load_all_vsh_coefficients(dir_NM_1,
                                                  i_mode_1,
                                                  option=option)
        coeffs_cplx_2 = load_all_vsh_coefficients(dir_NM_2,
                                                  i_mode_2,
                                                  option=option)

        # Apply weight information (full mode only).
        if option == 'full':

            # Read the shell radii.
            _, header_info, _, _ = load_vsh_coefficients(dir_NM_1,
                                                         i_mode_1[0],
                                                         i_radius=0)

            # Calculate weights of each shell.
            volume_weights = calculate_weights(header_info['r_sample'])

            # Apply the weights.
            coeffs_cplx_1 = coeffs_cplx_1 * volume_weights[:, np.newaxis,
                                                           np.newaxis]
            coeffs_cplx_2 = coeffs_cplx_2 * volume_weights[:, np.newaxis,
                                                           np.newaxis]

        # Add empty dimension so the shape is the same for quick and full runs.
        if option == 'quick':

            coeffs_cplx_1 = np.expand_dims(coeffs_cplx_1, 1)
            coeffs_cplx_2 = np.expand_dims(coeffs_cplx_2, 1)

        # Count the number of radii.
        n_radii = coeffs_cplx_1.shape[1]

        # Scale the coefficients by the k values.
        # First, get the list of l and m values of the coefficients.
        l_max = l_max_1
        l, m = make_l_and_m_lists(l_max)
        k = np.sqrt(l * (l + 1.0))
        coeffs_cplx_1 = coeffs_cplx_1 * k
        coeffs_cplx_2 = coeffs_cplx_2 * k

        # Convert the coefficients from complex to real.
        n_mode_1 = coeffs_cplx_1.shape[0]
        n_mode_2 = coeffs_cplx_2.shape[0]
        n_real_coeffs = (l_max + 1) * (l_max + 1)
        coeffs_real_1 = np.zeros((n_mode_1, n_radii, 3, n_real_coeffs))
        coeffs_real_2 = np.zeros((n_mode_2, n_radii, 3, n_real_coeffs))
        print('Converting complex coefficients to real: First run.')
        for i in range(n_mode_1):

            for j in range(n_radii):

                for k in range(3):

                    coeffs_real_1[i, j,
                                  k, :], _, _ = convert_complex_sh_to_real(
                                      coeffs_cplx_1[i, j, k, :], l_max)

        print('Converting complex coefficients to real: Second run.')
        for i in range(n_mode_2):

            for j in range(n_radii):

                for k in range(3):

                    coeffs_real_2[i, j,
                                  k, :], _, _ = convert_complex_sh_to_real(
                                      coeffs_cplx_2[i, j, k, :], l_max)

        # Find the best match for each mode in the first list by comparison
        # with the coefficients in the second list.
        f_thresh = 0.15  # mHz.
        best_match = np.zeros(n_mode_1, dtype=np.int)
        fit_list = []
        index_list = []
        for i in range(n_mode_1):

            print('Calculating fit for mode {:>5d}'.format(i))

            # Narrow down the modes for comparison by using the frequency
            # threshold.
            j_thresh_match = np.where((np.abs(f_1[i] - f_2) < f_thresh))[0]

            # For each mode matching the frequency, compare the coefficients.
            n_thresh_match = len(j_thresh_match)
            fit = np.zeros(n_thresh_match)

            for k, j in enumerate(j_thresh_match):

                fit[k] = coeff_match(coeffs_real_1[i, ...], coeffs_real_2[j,
                                                                          ...])

            #fit_list_array = np.array([j_thresh_match, fit], dtype = [('indices', np.int), ('fit', np.float)])

            index_list.append(j_thresh_match)
            fit_list.append(fit)
            best_match[i] = j_thresh_match[np.argmax(np.abs(fit))]

        # Save fit.
        print('Saving fit information to {:} and {:}.'.format(
            path_fit, path_index_list))
        np.save(path_fit, fit_list)
        np.save(path_index_list, index_list)

    print('Calculating best match.')
    min_fit = 0.75
    best_match = np.zeros(n_mode_1, dtype=np.int)
    best_fit = np.zeros(n_mode_1)
    for i in range(n_mode_1):

        # Get indices of modes matching frequency threshold.
        j_thresh_match = index_list[i]

        # Get fit for this mode.
        fit = fit_list[i]
        abs_fit = np.abs(fit)
        argmax_abs_fit = np.argmax(abs_fit)
        max_abs_fit = abs_fit[argmax_abs_fit]

        best_fit[i] = max_abs_fit

        if max_abs_fit > min_fit:

            # Find the best match.
            best_match[i] = j_thresh_match[
                argmax_abs_fit]  #np.argmax(np.abs(fit))]

        else:

            best_match[i] = -1

    print('Best-matching modes:')
    for i in range(n_mode_1):

        if best_match[i] == -1:

            #print('{:>5d} No good matches.'.format(i))
            pass

        else:

            print('{:>5d} {:>5d}, {:5.1f} %'.format(i_mode_1[i],
                                                    i_mode_2[best_match[i]],
                                                    100.0 * best_fit[i]))

    path_out = os.path.join(dir_processed, 'comparison.txt')
    print('Saving match information to {:}'.format(path_out))
    with open(path_out, 'w') as out_id:

        for i in range(n_mode_1):

            out_id.write('{:>5d} {:>5d}\n'.format(i, best_match[i]))

    #best_fit = np.zeros(n_mode_1)
    #for i in range(n_mode_1):

    ##    best_fit[i] = np.abs(fit_list[i][best_match[i]])
    #    best_fit[i] = np.max(np.abs(fit_list[i]))

    best_match_sorted = np.sort(best_match)
    matched, n_match = np.unique(best_match_sorted,
                                 return_index=False,
                                 return_inverse=False,
                                 return_counts=True)
    if best_match_sorted[0] == -1:
        n_unmatched = n_match[0]
        matched = matched[1:]
        n_match = n_match[1:]

    i_multiply_counted = np.where(n_match > 1)[0]

    for i in i_multiply_counted:

        match = matched[i]
        j_match = np.where(best_match == match)[0]

        print('\n')
        print(
            'The following modes in the first list all match mode {:>5d} in the second list'
            .format(i_mode_2[match]))
        for j in j_match:
            print('{:>5d}'.format(i_mode_1[j]))

    print('Number of modes not matched: {:>5d}'.format(n_unmatched))
    print('Number of multiply-counted modes: {:>5d}'.format(np.sum(n_match -
                                                                   1)))

    import matplotlib.pyplot as plt

    fig = plt.figure()
    ax = plt.gca()

    dir_processed = os.path.join(dir_NM_1, 'processed')
    dir_plot = os.path.join(dir_processed, 'plots')
    path_fig = os.path.join(dir_plot,
                            'comparison_mode_diagram_{:}.png'.format(option))

    match_condition = (best_match > -1)
    i_matched = np.where(match_condition)[0]
    i_not_matched = np.where(~match_condition)[0]

    f_diff = f_1 - f_2[best_match]
    abs_f_diff = np.abs(f_diff)
    print(np.max(abs_f_diff[i_matched]))
    print(np.max(f_1))
    ax.scatter(l_1[i_not_matched], f_1[i_not_matched], c='r', alpha=1.0, s=3)
    ax.scatter(l_1[i_matched],
               f_1[i_matched],
               c='k',
               alpha=1.0,
               s=1.0E4 * abs_f_diff[i_matched])

    ax.scatter([], [], c='r', s=3, label='Not matched')
    ax.scatter([], [], c='k', s=10, label='Matched (0.01 $\mu$Hz)')
    ax.scatter([], [], c='k', s=100, label='Matched (0.10 $\mu$Hz)')

    font_size_label = 14
    ax.set_xlabel('Angular order, $\ell$', fontsize=font_size_label)
    ax.set_ylabel('Frequency (mHz)', fontsize=font_size_label)

    ax.legend()

    plt.tight_layout()

    print('Saving to {:}'.format(path_fig))
    plt.savefig(path_fig, dpi=300)

    plt.show()

    #fig = plt.figure()
    #ax = plt.gca()

    #dir_processed = os.path.join(dir_NM_1, 'processed')
    #dir_plot = os.path.join(dir_processed, 'plots')
    #path_fig = os.path.join(dir_plot, 'comparison_similarity_{:}.png'.format(option))

    #ax.hist(best_fit)

    #font_size_label = 14
    #ax.set_xlabel('Similarity', fontsize = font_size_label)
    #ax.set_ylabel('Number of modes', fontsize = font_size_label)

    #ax.axvline(min_fit, linestyle = ':', color = 'k')

    #plt.tight_layout()

    #print('Saving to {:}'.format(path_fig))
    #plt.savefig(path_fig, dpi = 300)

    #plt.show()

    return
Ejemplo n.º 4
0
def main():

    # Read the NMPostProcess input file.
    dir_PM, dir_NM, option, l_max, i_mode_str, n_radii = read_input_NMPostProcess()

    # Load the mode identification information.
    dir_processed = os.path.join(dir_NM, 'processed')
    path_ids = os.path.join(dir_processed, 'mode_ids_{:}.txt'.format(option))
    i_mode, l, type_, shell = np.loadtxt(path_ids, dtype = np.int).T

    # Read the mode frequency. 
    file_eigval_list        = os.path.join(dir_processed, 'eigenvalue_list.txt')
    _, f = read_eigenvalues(file_eigval_list)
    num_modes = len(f)

    # Read 3-D mode information.
    mode_info = mode_id_information_to_dict(type_, l, f, shell)

    # Find 1-D mode information.
    Ouroboros_input_file = '../Ouroboros/input_Magrathea.txt'
    Ouroboros_info = read_Ouroboros_input_file(Ouroboros_input_file)

    mode_types = list(mode_info.keys())
    NormalModes_to_Ouroboros_T_layer_num_dict = {0 : 1, 2 : 0}
    paths_ref = dict()
    for mode_type in mode_types:
        
        if mode_type[0] == 'T':

            _, _, _, dir_type = get_Ouroboros_out_dirs(Ouroboros_info, 'T')
            layer_number_NormalModes = int(mode_type[1])
            layer_number_Ouroboros = \
                NormalModes_to_Ouroboros_T_layer_num_dict[layer_number_NormalModes]

            path_ref = os.path.join(dir_type, 'eigenvalues_{:>03d}.txt'.format(layer_number_Ouroboros))

        else:

            _, _, _, dir_type = get_Ouroboros_out_dirs(Ouroboros_info, mode_type)

            path_ref = os.path.join(dir_type, 'eigenvalues.txt')
        
        paths_ref[mode_type] = path_ref

    # Read 1-D reference information.
    nlf_ref = reference_mode_info_to_dict(paths_ref)

    # For each mode, find best fitting reference mode.
    n       = np.zeros(num_modes, dtype = np.int)
    f_ref   = np.zeros(num_modes)
    ref_key_list = []
    for i in range(num_modes):


        if type_[i] == 0:

            ref_key = 'R'

        elif type_[i] == 1:

            ref_key = 'S'

        elif type_[i] == 2:

            ref_key = 'T{:>1d}'.format(shell[i])

        else:

            raise ValueError

        ref_key_list.append(ref_key)

        j_match = np.where(nlf_ref[ref_key]['l'] == l[i])[0]
        k_match = np.argmin(np.abs(nlf_ref[ref_key]['f'][j_match] - f[i]))
        i_match = j_match[k_match]

        n[i] = nlf_ref[ref_key]['n'][i_match]
        f_ref[i] = nlf_ref[ref_key]['f'][i_match]

    f_diff = f - f_ref

    format_string = '{:>5d} {:>1d} {:>4} {:>1d} {:>9.6f} {:>9.6f} {:>+10.6f}'
    print('{:>5} {:>1} {:>4} {:>1} {:>9} {:>9}'.format('Mode', 'n', 'type', 'l', 'f', 'f_ref', 'f_diff'))
    for i in range(num_modes):

        print(format_string.format(i_mode[i], n[i], ref_key_list[i], l[i], f[i], f_ref[i], f_diff[i]))

    return
Ejemplo n.º 5
0
def main():

    # Read the NMPostProcess input file.
    _, dir_NM_1, _, _, _, _ = read_input_NMPostProcess()

    # Read the comparison input file.
    file_compare = 'input_compare.txt'
    with open(file_compare, 'r') as in_id:

        dir_NM_2 = in_id.readline().strip()

    # Read the mode frequencies.
    dir_processed_1 = os.path.join(dir_NM_1, 'processed')
    file_eigval_list_1 = os.path.join(dir_processed_1, 'eigenvalue_list.txt')
    _, f_1 = read_eigenvalues(file_eigval_list_1)
    #
    dir_processed_2 = os.path.join(dir_NM_2, 'processed')
    file_eigval_list_2 = os.path.join(dir_processed_2, 'eigenvalue_list.txt')
    _, f_2 = read_eigenvalues(file_eigval_list_2)

    # Read the comparison information.
    path_compare = os.path.join(dir_processed_1, 'comparison.txt')
    i_mode_1, i_mode_2 = np.loadtxt(path_compare, dtype=np.int).T

    # Load the mode identification information.
    path_ids_1 = os.path.join(dir_processed_1, 'mode_ids_quick.txt')
    _, l_1, _, _ = np.loadtxt(path_ids_1, dtype=np.int).T
    #i_mode, l, type_, shell = np.loadtxt(path_ids, dtype = np.int).T

    # Sort the frequencies of the comparison run to their best match in the
    # original run.
    f_2_reordered = f_2[i_mode_2]

    # Find minimum and maximum frequencies.
    f_min = np.min(np.concatenate([f_1, f_2]))
    f_max = np.max(np.concatenate([f_1, f_2]))

    # Find maximum frequency difference.
    f_diff = f_1 - f_2_reordered
    f_diff_frac = f_diff / (0.5 * (f_1 + f_2_reordered))
    f_diff_max = np.max(np.abs(f_diff))
    print('Maximum frequency difference: {:>12.6} muHz'.format(f_diff_max *
                                                               1.0E3))

    #fig = plt.figure(figsize = (7.0, 7.0))
    #ax  = plt.gca()

    #ax.scatter(f_1, f_2_reordered)

    ## Plot guide line.
    #f_line_buff = 0.2
    #f_min_line = f_min*(1.0 - f_line_buff)
    #f_max_line = f_max*(1.0 + f_line_buff)
    #ax.plot([f_min_line, f_max_line], [f_min_line, f_max_line])

    ## Set axis limits.
    #f_lim_buff = 0.1
    #f_min_lim = f_min*(1.0 - f_lim_buff)
    #f_max_lim = f_max*(1.0 + f_lim_buff)
    #ax.set_xlim([f_min_lim, f_max_lim])
    #ax.set_ylim([f_min_lim, f_max_lim])

    #font_size_label = 12
    #ax.set_xlabel('Frequency (mHz) of mode in run 1', fontsize = font_size_label)
    #ax.set_ylabel('Frequency (mHz) of mode in run 2', fontsize = font_size_label)

    #ax.set_aspect(1.0)

    #plt.show()

    #fig = plt.figure()
    #ax = plt.gca()

    ##ax.plot(i_mode_1, f_diff*1.0E3, 'k.-')
    #ax.plot(i_mode_1, f_diff_frac*1.0E2, 'k.-')

    #font_size_label = 12
    #ax.set_xlabel('Mode number', fontsize = font_size_label)
    ##ax.set_ylabel('Frequency difference ($\mu$Hz)', fontsize = font_size_label)
    #ax.set_ylabel('Frequency difference (%)', fontsize = font_size_label)

    #fig = plt.figure()
    #ax = plt.gca()

    #ax.scatter(f_1, f_diff*1.0E3, c = 'k', alpha = 0.5)
    ##ax.plot(i_mode_1, f_diff_frac*1.0E2, 'k.-')

    #font_size_label = 12
    #ax.set_xlabel('Frequency', fontsize = font_size_label)
    #ax.set_ylabel('Frequency difference ($\mu$Hz)', fontsize = font_size_label)
    ##ax.set_ylabel('Frequency difference (%)', fontsize = font_size_label)

    fig = plt.figure()
    ax = plt.gca()

    ax.scatter(l_1, f_1, s=10 * 1.0E3 * np.abs(f_diff), c='k', alpha=0.5)
    #ax.plot(i_mode_1, f_diff_frac*1.0E2, 'k.-')

    ax.scatter([], [], c='k', s=10.0, label='1 $\mu Hz$')
    ax.scatter([], [], c='k', s=100.0, label='10 $\mu Hz$')
    ax.legend()

    font_size_label = 12
    ax.set_xlabel('Angular order, $\ell$', fontsize=font_size_label)
    ax.set_ylabel('Frequency (mHz)', fontsize=font_size_label)
    #ax.set_ylabel('Frequency difference ($\mu$Hz)', fontsize = font_size_label)
    ##ax.set_ylabel('Frequency difference (%)', fontsize = font_size_label)

    plt.show()