#!/usr/bin/env python3
"""
Plots intensity data difference stored in BornAgain "*.int" or "*.int.gz" format
Usage: python plot_dif.py reference.int.gz new.int.gz
"""

import numpy as np
import bornagain as ba
import plot_int as pid
import sys


def plot_diff_int(filename1, filename2):
    intensity_ref   = ba.readData2D(filename1)
    intensity_other = ba.readData2D(filename2)
    data = 2 * np.abs(intensity_ref.npArray() - intensity_other.npArray()) \
           / (np.abs(intensity_ref.npArray()) + np.abs(intensity_other.npArray()))
    if data.max() == 0:
        exit("Both data sets are equal, there is nothing to plot.")
    vmax = data.max()
    vmin = data.min()
    if vmin <=0:
        vmin = vmax / 1e6
    rank = intensity_ref.rank()
    if rank == 2:
        pid.plot_raw_data_2d(data, [
            intensity_ref.xAxis().min()/ba.deg,
            intensity_ref.xAxis().max()/ba.deg,
            intensity_ref.yAxis().min()/ba.deg,
            intensity_ref.yAxis().max()/ba.deg
        ], True, vmin, vmax)
    elif rank == 1:
        axis_values = np.asarray(intensity_ref.xAxis().binCenters())
        pid.plot_raw_data_1d(axis_values, data, ylog=False)
    else:
        exit("Error in plot_diff_int: wrong data rank")


if __name__ == '__main__':
    if len(sys.argv) != 3:
        exit("Usage: plot_diff_int.py reference.int.gz other.int.gz")

    plot_diff_int(sys.argv[1], sys.argv[2])
