"""Ideal zero-drop diode, zero source resistance, parallel RC load. MIT license.
Independent continuous-time solution v(t)=max(0,max_{0<=u<=t} s(u)exp(-(t-u)/tau)).
Search each positive carrier lobe; default model mu=.8, fc=100 Hz, fm=1 Hz.
This is not a SPICE or hardware simulation. Python standard library only.
"""
import math
import json

def voltage(t, tau, mu=.8, fc=100, fm=1):
    if not (t >= 0 and tau > 0 and 0 < mu < 1 and fc/fm >= 20):
        raise ValueError('invalid model')
    def f(u):
        return (1+mu*math.cos(2*math.pi*fm*u))*math.cos(2*math.pi*fc*u)*math.exp(-(t-u)/tau)
    best = 0.0
    phi = (math.sqrt(5)-1)/2
    for k in range(math.ceil(t*fc)+1):
        lo, hi = max(0,(k-.25)/fc), min(t,(k+.25)/fc)
        if hi < lo:
            continue
        best=max(best,f(lo),f(hi))
        a,b=lo,hi
        for _ in range(80):
            c=b-phi*(b-a);d=a+phi*(b-a)
            if f(c)>f(d): b=d
            else: a=c
        best=max(best,f((a+b)/2))
    return best

if __name__=='__main__':
    times=[.005,.025,.125,.305,.405,.505,.705,.905]
    print(json.dumps({'mu':.8,'fc':100,'fm':1,'limit':math.sqrt(1-.8**2)/(2*math.pi*.8),
        'rows':[dict(tau=tau,t=t,voltage=voltage(t,tau),envelope=1+.8*math.cos(2*math.pi*t))
            for tau in [.001,.05,.5] for t in times]},indent=2))
