module LevMar.Fitting.AD
(
LMA.Model
, LMA.SimpleModel
, LMA_I.LevMarable
, levmar
, LinearConstraints
, noLinearConstraints
, Matrix
, LMA_I.Options(..)
, LMA_I.defaultOpts
, LMA_I.Info(..)
, LMA_I.StopReason(..)
, CovarMatrix
, LMA_I.LevMarError(..)
, Z, S, Nat
, SizedList(..)
, NFunction
) where
import qualified LevMar.Fitting as LMA
import qualified LevMar.Intermediate.Fitting as LMA_I
import LevMar.Utils ( LinearConstraints
, noLinearConstraints
, convertLinearConstraints
, Matrix
, CovarMatrix
, convertResult
)
import TypeLevelNat ( Z, S, Nat )
import SizedList ( SizedList(..), toList, unsafeFromList )
import NFunction ( NFunction, ($*) )
import LevMar.Utils.AD ( value, firstDeriv, constant, idDAt )
import Data.Derivative ( (:~>) )
import Data.VectorSpace ( VectorSpace, Scalar )
import Data.Basis ( HasBasis, Basis )
levmar :: forall m k r a.
( Nat m
, Nat k
, HasBasis r
, Basis r ~ ()
, VectorSpace (Scalar r)
, LMA_I.LevMarable r
)
=> LMA.Model m (r :~> r) a
-> SizedList m r
-> [(a, r)]
-> Integer
-> LMA_I.Options r
-> Maybe (SizedList m r)
-> Maybe (SizedList m r)
-> Maybe (LinearConstraints k m r)
-> Maybe (SizedList m r)
-> Either LMA_I.LevMarError (SizedList m r, LMA_I.Info r, CovarMatrix m r)
levmar model params ys itMax opts mLowBs mUpBs mLinC mWghts =
fmap convertResult $ LMA_I.levmar (convertModel model)
(Just $ jacobianOf model)
(toList params)
ys
itMax
opts
(fmap toList mLowBs)
(fmap toList mUpBs)
(fmap convertLinearConstraints mLinC)
(fmap toList mWghts)
where
convertModel :: LMA.Model m (r :~> r) a -> LMA_I.Model r a
(convertModel f) ps x = value $ (f $* pDs :: a -> r :~> r) x
where
pDs :: SizedList m (r :~> r)
pDs = unsafeFromList $ fmap constant ps
jacobianOf :: LMA.Model m (r :~> r) a -> LMA_I.Jacobian r a
(jacobianOf f) ps x = fmap combine $ zip [0..] ps
where
combine (ix, p) = firstDeriv $ (f $* pDs :: a -> r :~> r) x p
where
pDs :: SizedList m (r :~> r)
pDs = unsafeFromList $ idDAt ix ps