from easyDiffractionLib.sample import Sample
from easyDiffractionLib import Phase, Phases
from easyDiffractionLib.interface import InterfaceFactory
from easyDiffractionLib.Profiles.P1D import Instrument1DCWParameters

import matplotlib.pyplot as plt


i = InterfaceFactory()

c = Phases.from_cif_file('tests/SrTiO3.cif')

S = Sample(phases=c, parameters=Instrument1DCWParameters.default(), interface=i)

x_data = np.linspace(5, 150, 10000)
y_data = i.fit_func(x_data)

i.switch('CrysPy')
S._updateInterface()

y_data2 = np.array(i.fit_func(x_data))

fig = plt.figure()
axprops = dict()
ax1 = fig.add_axes([0.1, 0.5, 0.8, 0.4], **axprops)
ax1.plot(x_data, y_data, label="CrysFML")
ax1.legend()
axprops['sharex'] = ax1
# axprops['sharey'] = ax1
# force x axes to remain in register, even with toolbar navigation
ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.4], **axprops)
bg = PointBackground(linked_experiment='PbSO4')
bg.append(BackgroundPoint.from_pars(data_x[0], 200))
bg.append(BackgroundPoint.from_pars(data_x[-1], 200))

S.set_background(bg)
f = Fitter(S, interface.fit_func)

# Vary the scale and the BG points
S.pattern.scale.fixed = False
S.pattern.zero_shift.fixed = False
S.parameters.resolution_u.fixed = False
S.parameters.resolution_v.fixed = False
S.parameters.resolution_w.fixed = False
S.backgrounds[0][0].y.fixed = True
S.backgrounds[0][1].y.fixed = True

result = f.fit(data_x, data_y)
# result = data_set['I'].easyCore.fit(f)

if result.success:
    print("The fit has been successful: {}".format(result.success))
    print("The gooodness of fit is: {}".format(result.goodness_of_fit))

sim_y_data = interface.fit_func(data_x)

import matplotlib.pyplot as plt

plt.plot(data_x, data_y, label='Data')
plt.plot(data_x, result.y_calc, label='Calculate')
plt.show()
import matplotlib.pyplot as plt

calculator = Calculator()

phase = Phase.from_cif_file('tests/SrTiO3.cif')

sample = Sample(phases=phase,
                parameters=Instrument1DCWParameters.default(),
                calculator=calculator)

# sample.phase.cell.length_a = 5
sample.parameters.wavelength = 1.25
# print(S)
x_data = np.linspace(5, 150, 100)
y_data = calculator.fit_func(x_data)

plt.plot(x_data, y_data, label="CrysPy")
plt.show()

sample.parameters.wavelength = 2.5
y_data = calculator.fit_func(x_data)
plt.plot(x_data, y_data, label="CrysPy")
plt.show()

sample.phases[0].cell.length_a = 10
y_data = calculator.fit_func(x_data)
plt.plot(x_data, y_data, label="CrysPY")
plt.show()

calculator.switch('CrysFML')