Apply correction factors for a pseudo-2D measurement setup. See Weigand
    and Kemna, 2017, Biogeosciences, for detailed information.

def apply_correction_factors(df, correction_file):
    """Apply correction factors for a pseudo-2D measurement setup. See Weigand
    and Kemna, 2017, Biogeosciences, for detailed information.
    """
    if isinstance(correction_file, (list, tuple)):
        corr_data_raw = np.vstack(
            [np.loadtxt(x) for x in correction_file]
        )
    else:
        corr_data_raw = np.loadtxt(correction_file)

        if corr_data_raw.shape[1] == 3:
            A = (corr_data_raw[:, 0] / 1e4).astype(int)
            B = (corr_data_raw[:, 0] % 1e4).astype(int)
            M = (corr_data_raw[:, 1] / 1e4).astype(int)
            N = (corr_data_raw[:, 1] % 1e4).astype(int)
            corr_data = np.vstack((A, B, M, N, corr_data_raw[:, 2])).T

        elif corr_data_raw.shape[1] == 5:
            corr_data = corr_data_raw
        else:
            raise Exception('error')
    corr_data[:, 0:2] = np.sort(corr_data[:, 0:2], axis=1)
    corr_data[:, 2:4] = np.sort(corr_data[:, 2:4], axis=1)

    if 'frequency' not in df.columns:
        raise Exception(
            'No frequency data found. Are you sure this is a seit data set?'
        )

    df = df.reset_index()
    gf = df.groupby(['a', 'b', 'm', 'n'])
    for key, item in gf.indices.items():
        # print('key', key)
        # print(item)
        item_norm = np.hstack((np.sort(key[0:2]), np.sort(key[2:4])))
        # print(item_norm)
        index = np.where(
            (corr_data[:, 0] == item_norm[0]) &
            (corr_data[:, 1] == item_norm[1]) &
            (corr_data[:, 2] == item_norm[2]) &
            (corr_data[:, 3] == item_norm[3])
        )[0]
        # print(index, corr_data[index])
        if len(index) == 0:
            print(key)
            import IPython
            IPython.embed()
            raise Exception(
                'No correction factor found for this configuration'
            )

        factor = corr_data[index, 4]
        # if key == (1, 4, 2, 3):
        #     print(key)
        #     print(factor)
        #     print(df['R'])
        #     print(df['k'])
        #     import IPython
        #     IPython.embed()
        #     exit()
        # apply correction factor
        for col in ('r', 'Zt', 'Vmn', 'rho_a'):
            if col in df.columns:
                df.ix[item, col] *= factor
        df.ix[item, 'corr_fac'] = factor
    return df, corr_data