Plotting observed of DiscreteSystem

Hey.

I wanted to try out MTK so I am moving an Excel calculation I had set up for calculating monthly repayments of a inflation linked loan to MTK.

I got the model running. My issue is how to plot the observed values, not just the unknowns.

From what I can see, the observed(sys) returns the values I want to plot, but in the sol it only contains N, ind, P, amortization

I would like to plot the pmt_c, ipmt_c and ppmt_c as well.

I am using MTK v9.26.0

using ModelingToolkit
using ModelingToolkit: t_nounits as t, D_nounits as D
using OrdinaryDiffEq: solve, FunctionMap
using PlutoPlotly

@inline function if_else(
	@nospecialize(condition),
	@nospecialize(trueval),
	@nospecialize(falseval)
)
	return ifelse(condition, trueval, falseval)
end

k = ShiftIndex(t)
@parameters r infl yr yr_periods cost total_payment
@variables P(t) ind(t) N(t) pmt_c(t) ipmt_c(t) ppmt_c(t) amortization(t)

periods = yr*yr_periods
rᵢ = r/yr_periods
eqs = [
	N(k) ~ N(k-1) + 1
	ind(k) ~ ind(k - 1) * (1 + infl)^(1/yr_periods)
	P(k) ~ max((P(k - 1) - amortization(k - 1))*ind(k)/ind(k - 1), 0)
	pmt_c(k) ~ -P(k) * rᵢ / (1 - (1 + rᵢ)^(-periods+N(k-1)))
	ipmt_c(k) ~ -P(k) * rᵢ
	ppmt_c(k) ~ pmt_c(k) - ipmt_c(k)
	amortization(k) ~ if_else(P(k)>0, if_else(total_payment + pmt_c(k) >0, total_payment + pmt_c(k), -ppmt_c(k)), 0)
]
@mtkbuild sys = DiscreteSystem(eqs, t)

u0 = [
	P(k-1) => 10_000_000,
	ind(k-1) => 100, 
	N(k-1) => 0,
	amortization(k-1) => 0
]
p = [
	r => 0.0375,
	infl => 0.0621,
	yr => 30,
	yr_periods => 12,
	cost => 520,
	total_payment => 110_000
]
tspan = (1, 360 + 1)
prob = DiscreteProblem(sys, u0, tspan, p)

sol = solve(prob, FunctionMap())

p1 = plot(sol[:N], sol[:amortization])
p2 = plot(sol[:N], sol[:P])
p0 = hcat(p1, p2)
relayout!(p0, title_text="Loan")
p0

Hello and welcome to the community! :wave:

This feature was actually merged as late as yesterday!

It hasn’t yet made it’s way into a release. Expect it to be available within a few days.

1 Like

Thanks! I suspected it :sweat_smile: Always fun to live on the edge!

And for others, now I found this regarding the variable elimination and the simplification process: