I am trying to port Modelica.Electrical.Analog.Semiconductors.Diode
. The code I came up with is:
using ModelingToolkit
using ModelingToolkitStandardLibrary.Blocks
using ModelingToolkitStandardLibrary.Electrical
using OrdinaryDiffEq
using IfElse: ifelse
using Plots
@parameters t;
exlin(x, max_x) = ifelse(x > max_x, exp(max_x)*(1 + x - max_x), exp(x))
function Diode(;name, Ids=1e-6, Vt=0.04, max_exp=15, R=1e8)
@named oneport = OnePort()
@unpack v, i = oneport
pars = @parameters Ids=Ids Vt=Vt max_exp=max_exp R=R
eqs = [i ~ Ids*(exlin(v/Vt, max_exp) - 1) + (v/R)]
extend(ODESystem(eqs, t, [], pars; name=name), oneport)
end
@named V = Voltage();
@named D = Diode();
@named R = Resistor(R=100);
@named Gnd = Ground();
connections = [
V.V.u ~ 18*sin(2*pi*50*t)
connect(V.p, D.p)
connect(D.n, R.p)
connect(V.n, R.n, Gnd.g)
]
@named model = ODESystem(connections, t, systems=[V, D, R, Gnd]);
sys = structural_simplify(model);
prob1c = ODEProblem(sys, Pair[], (0/50, 1/50), saveat=1/50e2);
sol1c = solve(prob1c, Rodas4());
Plots.plot(sol1c; idxs=[V.v, R.v, D.v], fmt = :png)
prob2c = ODEProblem(sys, Pair[], (0/50, 2/50), saveat=1/50e2);
sol2c = solve(prob2c, Rodas4());
Plots.plot(sol2c; idxs=[V.v, R.v, D.v], fmt = :png)
prob3c = ODEProblem(sys, Pair[], (1/50, 2/50), saveat=1/50e2);
sol3c = solve(prob3c, Rodas4());
Plots.plot(sol3c; idxs=[V.v, R.v, D.v], fmt = :png)
This diode model works fine for any first cycle of the signal, blowing up exponentially for any further cycles.