# %% import os import sys print(sys.executable) # %% import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np # %% import corner import emcee import pandas as pd import tqdm # %% mpl.rcParams.update({ "figure.dpi": 300, "savefig.bbox": "tight", }) # %% def makegrid(ax): ax.grid(True, which="major", color="k", alpha=0.05) ax.grid(True, which="minor", color="k", alpha=0.025) # %% [markdown] # # Load data # %% fname = "20_1V.csv" flabel = '.'.join(fname.split('.')[:-1]) # Try to guess at the extension and drop it data = pd.read_csv(fname) tdata = data["Time(s)"] Vdata = data["CH1(V)"] Nsmooth = 200 tdata = np.convolve(tdata, np.ones(Nsmooth)/Nsmooth, mode="valid")[::Nsmooth//2] Vdata = np.convolve(Vdata, np.ones(Nsmooth)/Nsmooth, mode="valid")[::Nsmooth//2] Verr = 0.001 # %% [markdown] # # Define fitting function # %% def deep_freq_mod_n(t, V0, Vfringe, phi, psi, *m_arr, fmod=1e3): """Return a time series of the modeled voltage. Arguments: m_arr -- a sequence of n modulation depths """ mod_phase = np.zeros_like(t) for ii, mm in enumerate(m_arr): mod_phase += mm * np.cos(2 * np.pi * (ii + 1) * fmod * t + psi) return V0 + Vfringe * np.cos(phi + mod_phase) # %% [markdown] # # Set up MCMC # # The rest is cribbed from https://emcee.readthedocs.io/en/stable/tutorials/line/ # %% def log_prior(theta): """Establish the prior volume. Return a finite prior only if all the fit parameters are within the allowed parameter space. """ V0, Vfringe, phi, psi, *m_arr = theta if V0 < 0: return -np.inf if Vfringe < 0 or Vfringe > 10: return -np.inf if phi < 0 or phi >= 2 * np.pi: return -np.inf if psi < 0 or psi >= 2 * np.pi: return -np.inf m_arr = np.array(m_arr) if np.any(m_arr < 0) or np.any(m_arr > 10): return -np.inf return 0 # %% def log_likelihood(theta, t, V, Verr=0.05): """Return the log-likelihood of the fit assuming Gaussian errors """ Vmodel = deep_freq_mod_n(t, *theta) return -0.5 * np.sum((V - Vmodel)**2 / Verr**2) # %% def log_probability(theta, t, V, Verr=0.05): """Return the log-likelihood plus the log-prior """ lp = log_prior(theta) if not np.isfinite(lp): return -np.inf return lp + log_likelihood(theta, t, V, Verr) # %% [markdown] # # Make guesses # %% Nmod = 4 # number of modulation depths # Initialize guesses of V0, Vfringe, phi, psi, and m_arr # Guess that m1 = 1, while m2 = m3 = ... = m_n = 0 guesses = np.array([np.mean(Vdata), (np.max(Vdata)-np.min(Vdata))/2, 0, 0, 1, *np.zeros(Nmod-1)]) Ndim = guesses.shape[0] Nwalkers = 32 # number of MCMC walkers pos = np.random.normal(guesses, guesses/10+0.001, (Nwalkers, Ndim)) # %% theta_labels = [ r"$V_0$", r"$V_\text{fringe}$", r"$\phi$", r"$\psi$", ] + [r"$m_{:}$".format(i+1) for i in range(Nmod)] # %% [markdown] # # Run MCMC # %% sampler = emcee.EnsembleSampler( Nwalkers, Ndim, log_probability, args=(tdata, Vdata) ) sampler.run_mcmc(pos, 10000, progress=True); # %% fig, axes = plt.subplots(Ndim, figsize=(10, 7), sharex=True) samples = sampler.get_chain() for i in range(Ndim): ax = axes[i] ax.plot(samples[:, :, i], "k", alpha=0.3) ax.set_xlim(0, len(samples)) ax.set_ylabel(theta_labels[i]) ax.yaxis.set_label_coords(-0.1, 0.5) axes[-1].set_xlabel("step number"); # %% [markdown] # # Analyze results # %% tau = sampler.get_autocorr_time() print(tau) # %% flat_samples = sampler.get_chain(discard=6000, thin=50, flat=True) print(flat_samples.shape) # %% fig_corner = corner.corner( flat_samples, labels=theta_labels, quantiles=[0.1, 0.5, 0.9], ) # %% # The median fit to the data print(np.median(flat_samples, axis=0)) Vmedian = deep_freq_mod_n(tdata, *np.median(flat_samples, axis=0)) # %% fig_ts, axs_ts = plt.subplots(2, height_ratios=[3, 1], sharex=True, figsize=(6, 6)) axs_ts[0].plot( tdata * 1e3, Vdata, color="xkcd:forest green", label="Data", ) axs_ts[0].plot( tdata * 1e3, Vmedian, color="xkcd:bright orange", alpha=0.7, label=r"Fit, $N_\text{{mod}} = {:}$".format(Nmod), ) axs_ts[1].plot( tdata * 1e3, Vdata - Vmedian, color="xkcd:forest green", ) axs_ts[0].xaxis.set_tick_params(labelbottom=True) axs_ts[-1].set_xlim([1e3 * tdata[0], 1e3 * tdata[-1]]) axs_ts[-1].set_xlabel("Time [ms]") axs_ts[0].set_ylabel("Photodetector voltage [V]") axs_ts[1].set_ylabel("Residual [V]") axs_ts[0].legend() for ax in axs_ts: makegrid(ax) fig_ts.savefig(f"{flabel}_fit_Nmod_{Nmod}.pdf") # %%