# %%
# ======================================================================================
# Copyright (©) 2014-2026 Laboratoire Catalyse et Spectrochimie (LCS), Caen, France.
# CeCILL-B FREE SOFTWARE LICENSE AGREEMENT
# See full LICENSE agreement in the root directory.
# ======================================================================================
# ruff: noqa
"""

Fitting 1D dataset
==================
In this example, we find the least  square solution of a simple linear
equation.

"""
# sphinx_gallery_thumbnail_number = 2

# %%
import os

import spectrochempy as scp

# %%
# Load and prepare an IR spectrum
# --------------------------------
nd = scp.read_omnic(os.path.join("irdata", "nh4y-activation.spg"))

# %%
# Select the OH region and mask a noisy interval:
ndOH = nd[54, 3800.0:3300.0]
ndOH[:, 3505.0:3500.0] = scp.MASKED
_ = ndOH.plot()

# %%
# Define the fitting model
# -------------------------
# Fit parameters are defined in a script with the following syntax:
script = """
#-----------------------------------------------------------
# syntax for parameters definition:
# name: value, low_bound,  high_bound
# available prefix:
#  # for comments
#  * for fixed parameters
#  $ for variable parameters
#  > for reference to a parameter in the COMMON block
#    (> is forbidden in the COMMON block)
# common block parameters should not have a _ in their names
#-----------------------------------------------------------
#

COMMON:
# common parameters ex.
# $ gwidth: 1.0, 0.0, none
$ gratio: 0.1, 0.0, 1.0

MODEL: LINE_1
shape: asymmetricvoigtmodel
    * ampl:  1.1, 0.0, none
    $ pos:   3620, 3400.0, 3700.0
    $ ratio: 0.0147, 0.0, 1.0
    $ asym: 0.1, 0, 1
    $ width: 50, 0, 1000

MODEL: LINE_2
shape: asymmetricvoigtmodel
    $ ampl:  0.8, 0.0, none
    $ pos:   3540, 3400.0, 3700.0
    > ratio: gratio
    $ asym: 0.1, 0, 1
    $ width: 50, 0, 1000

"""

# %%
# Create the optimizer and inspect the starting model
# ----------------------------------------------------
f1 = scp.Optimize(log_level="INFO")
f1.script = script

# Use dry mode to preview the starting parameters
f1.dry = True
f1.autobase = True
_ = f1.fit(ndOH)

scp.info_(f"numbers of components: {f1.n_components}")
_ = ndOH.plot()
ax = (f1.components[:]).plot(clear=False)
ax.autoscale(enable=True, axis="y")

# %%
# Fit the model
# --------------
f1.max_iter = 1000
_ = f1.fit(ndOH)

# %%
# Show the result
_ = ndOH.plot()
ax = (f1.components[:]).plot(clear=False)
ax.autoscale(enable=True, axis="y")

# %%
# Evaluate the fit quality
som = f1.inverse_transform()
_ = f1.plot_merit(ndOH, som, offset=15)

# %%
# This ends the example ! The following line can be uncommented if no plot shows when
# running the .py script with python

# scp.show()
