# Functional test: tests of IO operations with the IntensityData object

import math, unittest, numpy
import bornagain as ba
from bornagain import deg


def is_the_same_data(data1, data2):
    """
    Checks if two data are identical
    """
    if data1.size() != data2.size():
        return False
    if data1.rank() != data2.rank():
        return False
    for i in range(0, data1.rank()):
        if data1.axis(i) != data2.axis(i):
            return False
    for i in range(0, data1.size()):
        if data1[i] != data2[i]:
            return False
    return True


def get_boundaries_flat_in_sin(nbins, start, end):
    """
    Returns flat_in_sin binning of angle axis
    """
    result = []
    start_sin = math.sin(start)
    end_sin = math.sin(end)
    step = (end_sin - start_sin) / nbins
    for i in range(0, nbins + 1):
        result.append(math.degrees(math.asin(start_sin + step * i)))
    return result


class IOTest(unittest.TestCase):
    """
    Test serialization of IntensityData
    """

    def test_SaveNumpyArray_ReadDatafield(self):
        arr = numpy.array([[0, 1, 2, 3.0], [4, 5, 6, 7.0], [8, 9, 10, 11.0]])
        numpy.savetxt('tmp.txt', arr)
        newdata = ba.readData2D("tmp.txt")
        self.assertTrue(numpy.array_equal(newdata.npArray(), arr))

    def test_SaveNumpyArray_ReadRawDataVector(self):
        arr = numpy.array([[0, 1, 2, 3.0], [4, 5, 6, 7.0], [8, 9, 10, 11.0]])
        numpy.savetxt('tmp.txt', arr)
        newdata = numpy.array(
            ba.readData2D("tmp.txt").flatVector())
        expected = numpy.array(
            [8., 4., 0., 9., 5., 1., 10., 6., 2., 11., 7., 3.])
        self.assertTrue(numpy.array_equal(newdata, expected))


if __name__ == '__main__':
    unittest.main()
