master-thesis/python/richard_hops/energy_flow_thermal.org
2021-11-02 14:39:09 +01:00

17 KiB
Raw Blame History

Setup

Jupyter

  %load_ext autoreload
  %autoreload 2
  %load_ext jupyter_spaces
The autoreload extension is already loaded. To reload it, use:
  %reload_ext autoreload
The jupyter_spaces extension is already loaded. To reload it, use:
  %reload_ext jupyter_spaces

Matplotlib

  import matplotlib
  import matplotlib.pyplot as plt

  #matplotlib.use("TkCairo", force=True)
  %gui tk
  %matplotlib inline
  plt.style.use('ggplot')

Richard (old) HOPS

  import hierarchyLib
  import hierarchyData
  import numpy as np

  from stocproc.stocproc import StocProc_FFT
  import bcf
  from dataclasses import dataclass, field
  import scipy
  import scipy.misc
  import scipy.signal
  import pickle
  from scipy.special import gamma as gamma_func
  from scipy.optimize import curve_fit

Auxiliary Definitions

  σ1 = np.matrix([[0,1],[1,0]])
  σ2 = np.matrix([[0,-1j],[1j,0]])
  σ3 = np.matrix([[1,0],[0,-1]])

Model Setup

Basic parameters.

  class params:
      T = .05
  
      t_max = 10
      t_steps = int(t_max * 1/.01)
      k_max = 3
      N = 1000
  
      seed = 100
      dim = 2
      H_s = σ3 + np.eye(dim)
      L = 1 / 2 * (σ1 - 1j * σ2)
      ψ_0 = np.array([0, 1])
  
      s = 1
      num_exp_t = 6
  
      wc = 1
  
      with open("good_fit_data_abs_brute_force", "rb") as f:
          good_fit_data_abs = pickle.load(f)
  
      alpha = 0.8
      # _, g_tilde, w_tilde = good_fit_data_abs[(numExpFit, s)]
      # g_tilde = np.array(g_tilde)
      # w_tilde = np.array(w_tilde)
      # g = 1 / np.pi * gamma_func(s + 1) * wc ** (s + 1) * np.asarray(g_tilde)
      # w = wc * np.asarray(w_tilde)
  
      bcf_scale = np.pi / 2 * alpha * wc ** (1 - s)

BCF and Thermal BCF

  @dataclass
  class CauchyBCF:
      δ: float
      wc: float

      def I(self, ω):
          return np.sqrt(self.δ) / (self.δ + (ω - self.wc) ** 2 / self.δ)

      def __call__(self, τ):
          return np.sqrt(self.δ) * np.exp(-1j * self.wc * τ - np.abs(τ) * self.δ)

      def __bfkey__(self):
          return self.δ, self.wc

  α = bcf.OBCF(s=params.s, eta=1, gamma=params.wc)
  I = bcf.OSD(s=params.s, eta=1, gamma=params.wc)

Fit

We now fit a sum of exponentials against the BCF.

  from lmfit import minimize, Parameters


  def α_apprx(τ, g, w):
      return np.sum(
          g[np.newaxis, :] * np.exp(-w[np.newaxis, :] * (τ[:, np.newaxis])), axis=1
      )


  def _fit():
      def residual(fit_params, x, data):
          resid = 0
          w = np.array([fit_params[f"w{i}"] for i in range(params.num_exp_t)]) + 1j * np.array(
              [fit_params[f"wi{i}"] for i in range(params.num_exp_t)]
          )
          g = np.array([fit_params[f"g{i}"] for i in range(params.num_exp_t)]) + 1j * np.array(
              [fit_params[f"gi{i}"] for i in range(params.num_exp_t)]
          )
          resid = data - α_apprx(x, g, w)

          return resid.view(float)

      fit_params = Parameters()
      for i in range(params.num_exp_t):
          fit_params.add(f"g{i}", value=.1)
          fit_params.add(f"gi{i}", value=.1)
          fit_params.add(f"w{i}", value=.1)
          fit_params.add(f"wi{i}", value=.1)

      ts = np.linspace(0, params.t_max, 1000)
      out = minimize(residual, fit_params, args=(ts, α(ts)))

      w = np.array([out.params[f"w{i}"] for i in range(params.num_exp_t)]) + 1j * np.array(
          [out.params[f"wi{i}"] for i in range(params.num_exp_t)]
      )
      g = np.array([out.params[f"g{i}"] for i in range(params.num_exp_t)]) + 1j * np.array(
          [out.params[f"gi{i}"] for i in range(params.num_exp_t)]
      )

      return w, g


  w, g = _fit()

Plot

Let's look a the result.

  class bcfplt:
      t = np.linspace(0, params.t_max, 1000)
      ω = np.linspace(params.wc - 10, params.wc + 10, 1000)
      fig, axs = plt.subplots(2)
      axs[0].plot(t, np.real(α(t)))
      axs[0].plot(t, np.imag(α(t)))
      axs[0].plot(t, np.real(α_apprx(t, g, w)))
      axs[0].plot(t, np.imag(α_apprx(t, g, w)))
      axs[1].plot(ω, I(ω).real)
      axs[1].plot(ω, I(ω).imag)

/hiro/master-thesis/media/commit/97ac28637dd0bb30acc8ecdce80535c563b44b42/python/richard_hops/.ob-jupyter/5a53952d9dcf681ceb8eba3e084e3619f25101c9.png

Seems ok for now.

Hops setup

  HierachyParam = hierarchyData.HiP(
      k_max=params.k_max,
      # g_scale=None,
      # sample_method='random',
      seed=params.seed,
      nonlinear=True,
      normalized=False,
      # terminator=False,
      result_type=hierarchyData.RESULT_TYPE_ALL,
      # accum_only=None,
      # rand_skip=None
  )

Integration.

  IntegrationParam = hierarchyData.IntP(
      t_max=params.t_max,
      t_steps=params.t_steps,
      # integrator_name='zvode',
      # atol=1e-8,
      # rtol=1e-8,
      # order=5,
      # nsteps=5000,
      # method='bdf',
      # t_steps_skip=1
  )

And now the system.

  SystemParam = hierarchyData.SysP(
      H_sys=params.H_s,
      L=params.L,
      psi0=params.ψ_0,  # excited qubit
      g=np.array(g),
      w=np.array(w),
      H_dynamic=[],
      bcf_scale=params.bcf_scale,  # some coupling strength (scaling of the fit parameters 'g_i')
      gw_hash=None,  # this is used to load g,w from some database
      len_gw=len(g),
  )

The quantum noise.

  Eta = StocProc_FFT(
      I,
      params.t_max,
      α,
      negative_frequencies=False,
      seed=params.seed,
      intgr_tol=1e-3,
      intpl_tol=1e-3,
      scale=params.bcf_scale,
  )
  stocproc.stocproc - INFO - non neg freq only
  stocproc.method_ft - INFO - get_dt_for_accurate_interpolation, please wait ...
  stocproc.method_ft - INFO - acc interp N 33 dt 6.25e-01 -> diff 1.51e-01
  stocproc.method_ft - INFO - acc interp N 65 dt 3.12e-01 -> diff 3.41e-02
  stocproc.method_ft - INFO - acc interp N 129 dt 1.56e-01 -> diff 7.19e-03
  stocproc.method_ft - INFO - acc interp N 257 dt 7.81e-02 -> diff 1.70e-03
  stocproc.method_ft - INFO - acc interp N 513 dt 3.91e-02 -> diff 4.21e-04
  stocproc.method_ft - INFO - requires dt < 3.906e-02
  stocproc.method_ft - INFO - get_N_a_b_for_accurate_fourier_integral, please wait ...
  stocproc.method_ft - INFO - J_w_min:1.00e-02 N 32 yields: interval [0.00e+00,6.47e+00] diff 9.83e-03
  stocproc.method_ft - INFO - J_w_min:1.00e-03 N 32 yields: interval [0.00e+00,9.12e+00] diff 6.55e-03
  stocproc.method_ft - INFO - J_w_min:1.00e-02 N 64 yields: interval [0.00e+00,6.47e+00] diff 1.11e-02
  stocproc.method_ft - INFO - increasing N while shrinking the interval does lower the error -> try next level
  stocproc.method_ft - INFO - J_w_min:1.00e-04 N 32 yields: interval [0.00e+00,1.17e+01] diff 1.32e-02
  stocproc.method_ft - INFO - J_w_min:1.00e-03 N 64 yields: interval [0.00e+00,9.12e+00] diff 9.90e-04
  stocproc.method_ft - INFO - return, cause tol of 0.001 was reached
  stocproc.method_ft - INFO - requires dx < 1.425e-01
  stocproc.stocproc - INFO - Fourier Integral Boundaries: [0.000e+00, 2.166e+02]
  stocproc.stocproc - INFO - Number of Nodes            : 2048
  stocproc.stocproc - INFO - yields dx                  : 1.058e-01
  stocproc.stocproc - INFO - yields dt                  : 2.900e-02
  stocproc.stocproc - INFO - yields t_max               : 5.937e+01

The sample trajectories are smooth.

  %%space plot
  ts = np.linspace(0, params.t_max, 1000)
  Eta.new_process()
  plt.plot(ts, Eta(ts).real)
<matplotlib.lines.Line2D at 0x7f0d09517b20>

/hiro/master-thesis/media/commit/97ac28637dd0bb30acc8ecdce80535c563b44b42/python/richard_hops/.ob-jupyter/2203ae711b676c5126b800cfe209dd822f8a19ac.png

And now the thermal noise.

  EtaTherm = StocProc_FFT(
      spectral_density=bcf.OFTDens(s=params.s, eta=1, gamma=params.wc, beta=1 / params.T),
      t_max=params.t_max,
      alpha=bcf.OFTCorr(s=params.s, eta=1, gamma=params.wc, beta=1 / params.T),
      intgr_tol=1e-3,
      intpl_tol=1e-3,
      seed=params.seed,
      negative_frequencies=False,
      scale=params.bcf_scale,
  )
  stocproc.stocproc - INFO - non neg freq only
  stocproc.method_ft - INFO - get_dt_for_accurate_interpolation, please wait ...
  stocproc.method_ft - INFO - acc interp N 33 dt 6.25e-01 -> diff 1.57e-04
  stocproc.method_ft - INFO - requires dt < 6.250e-01
  stocproc.method_ft - INFO - get_N_a_b_for_accurate_fourier_integral, please wait ...
  stocproc.method_ft - INFO - J_w_min:1.00e-02 N 32 yields: interval [0.00e+00,1.24e-01] diff 6.28e-04
  stocproc.method_ft - INFO - return, cause tol of 0.001 was reached
  stocproc.method_ft - INFO - requires dx < 3.877e-03
  stocproc.stocproc - INFO - Fourier Integral Boundaries: [0.000e+00, 1.264e+01]
  stocproc.stocproc - INFO - Number of Nodes            : 4096
  stocproc.stocproc - INFO - yields dx                  : 3.085e-03
  stocproc.stocproc - INFO - yields dt                  : 4.973e-01
  stocproc.stocproc - INFO - yields t_max               : 2.036e+03

The sample trajectories are smooth too.

  %%space plot
  ts = np.linspace(0, params.t_max, 1000)
  EtaTherm.new_process()
  plt.plot(ts, EtaTherm(ts).real)
<matplotlib.lines.Line2D at 0x7f0ccb9c34f0>

/hiro/master-thesis/media/commit/97ac28637dd0bb30acc8ecdce80535c563b44b42/python/richard_hops/.ob-jupyter/bf7335fba71cb57b5a1af7f2747fab9dc378367b.png

Actual Hops

Generate the key for binary caching.

  hi_key = hierarchyData.HIMetaKey_type(
      HiP=HierachyParam,
      IntP=IntegrationParam,
      SysP=SystemParam,
      Eta=Eta,
      EtaTherm=EtaTherm,
  )

Initialize Hierarchy.

  myHierarchy = hierarchyLib.HI(hi_key, number_of_samples=params.N, desc="calculate the heat flow")
init Hi class, use 168 equation
/home/hiro/Documents/Projects/UNI/master/masterarb/python/richard_hops/hierarchyLib.py:1058: UserWarning: sum_k_max is not implemented! DO SO BEFORE NEXT USAGE (use simplex).HierarchyParametersType does not yet know about sum_k_max
  warnings.warn(

Run the integration.

  myHierarchy.integrate_simple(data_path="data", data_name="energy_flow_therm_new_again_less.data")
samples     :0.0%
integration :0.0%
samples     : 100%
integration :0.0%


Get the samples.

  # to access the data the 'hi_key' is used to find the data in the hdf5 file
  class int_result:
      with hierarchyData.HIMetaData(
          hid_name="energy_flow_therm_new_again_less.data", hid_path="data"
      ) as metaData:
          with metaData.get_HIData(hi_key, read_only=True) as data:
              smp = data.get_samples()
              print("{} samples found in database".format(smp))
              τ = data.get_time()
              rho_τ = data.get_rho_t()
              s_proc = np.array(data.stoc_proc)
              states = np.array(data.aux_states).copy()
              ψ_1 = np.array(data.aux_states)[:, :, 0 : params.num_exp_t * params.dim]
              ψ_0 = np.array(data.stoc_traj)
              y = np.array(data.y)
              η = np.array(data.stoc_proc)
              temp_y = np.array(data.temp_y)
1000 samples found in database

Calculate energy.

  %matplotlib inline
  energy = np.array([np.trace(ρ @ params.H_s).real for ρ in int_result.rho_τ])
  plt.plot(int_result.τ, energy)
<matplotlib.lines.Line2D at 0x7f0ccb9fd430>

/hiro/master-thesis/media/commit/97ac28637dd0bb30acc8ecdce80535c563b44b42/python/richard_hops/.ob-jupyter/eade23502ba1ab1f82b249e4a8eb20b9f2bad2f1.png

Energy Flow

  int_result.ψ_1.shape
1280 1000 12

Let's look at the norm.

  plt.plot(int_result.τ, (int_result.ψ_0[0].conj() * int_result.ψ_0[0]).sum(axis=1).real)
<matplotlib.lines.Line2D at 0x7f0d093fa580>

/hiro/master-thesis/media/commit/97ac28637dd0bb30acc8ecdce80535c563b44b42/python/richard_hops/.ob-jupyter/a435baf6359e2e8045148f25bc3f42bbfad68dc3.png

And try to calculate the energy flow.

  def flow_for_traj(ψ_0, ψ_1, temp_y):
      a = np.array((params.L @ ψ_0.T).T)
      EtaTherm.new_process(temp_y)
      η_dot = scipy.misc.derivative(EtaTherm, int_result.τ, dx=1e-3, order=5)
  
      ψ_1 = (-w * g * params.bcf_scale)[None, :, None] * ψ_1.reshape(
          params.t_steps, params.num_exp_t, params.dim
      )
  
      # return np.array(np.sum(ψ_0.conj() * ψ_0, axis=1)).flatten().real
      j_0 = np.array(
          2
          ,* (
              1j
              ,* (np.sum(a.conj()[:, None, :] * ψ_1, axis=(1, 2)))
              / np.sum(ψ_0.conj() * ψ_0, axis=1)
          ).real
      ).flatten()
  
      j_therm = np.array(
          2
          ,* (
              1j
              ,* (np.sum(a.conj() * ψ_0, axis=1)) * η_dot
              / np.sum(ψ_0.conj() * ψ_0, axis=1)
          ).real
      ).flatten()
      return j_0, j_therm

Now we calculate the average over all trajectories.

  class Flow:
      j_0 = np.zeros_like(int_result.τ)
      j_therm = np.zeros_like(int_result.τ)
      for i in range(0, params.N):
          dj, dj_therm = flow_for_traj(
              int_result.ψ_0[i], int_result.ψ_1[i], int_result.temp_y[i]
          )
  
          j_0 += dj
          j_therm += dj_therm
      j_0 /= params.N
      j_therm /= params.N
      j = j_0 + j_therm

And plot it :).

  %matplotlib inline
  plt.plot(int_result.τ, Flow.j_0, label=r"$j_0$")
  plt.plot(int_result.τ, Flow.j_therm, label=r"$j_\mathrm{therm}$")
  plt.plot(int_result.τ, Flow.j, label=r"$j$")
  plt.legend()
<matplotlib.legend.Legend at 0x7f0d1c55c9d0>

/hiro/master-thesis/media/commit/97ac28637dd0bb30acc8ecdce80535c563b44b42/python/richard_hops/.ob-jupyter/7cbd05333f1c93836f087cff77e43ab0242be1f0.png

Let's calculate the integrated energy.

  E_t = np.array(
      [0]
      + [
          scipy.integrate.simpson(Flow.j[0:n], int_result.τ[0:n])
          for n in range(1, len(int_result.τ))
      ]
  )
  E_t[-1]
0.0001533883783057427

With this we can retrieve the energy of the interaction Hamiltonian.

  E_I = - energy - E_t
  %%space plot
  #plt.plot(τ, j, label="$J$", linestyle='--')
  plt.plot(int_result.τ, E_t, label=r"$\langle H_{\mathrm{B}}\rangle$")
  plt.plot(int_result.τ, E_I, label=r"$\langle H_{\mathrm{I}}\rangle$")
  plt.plot(int_result.τ, energy, label=r"$\langle H_{\mathrm{S}}\rangle$")

  plt.xlabel("τ")
  plt.legend()
  plt.show()
<matplotlib.lines.Line2D at 0x7f0d0204f9a0>
<matplotlib.lines.Line2D at 0x7f0d0204fd90>
<matplotlib.lines.Line2D at 0x7f0d0205c250>
Text(0.5, 0, 'τ')
<matplotlib.legend.Legend at 0x7f0d0204f7c0>

/hiro/master-thesis/media/commit/97ac28637dd0bb30acc8ecdce80535c563b44b42/python/richard_hops/.ob-jupyter/cacd471986b310d098044a14b37648d454668ce9.png

System + Interaction Energy

  def h_si_for_traj(ψ_0, ψ_1, temp_y):
      a = np.array((params.L @ ψ_0.T).T)
      b = np.array((params.H_s @ ψ_0.T).T)
      ψ_1 = (g*params.bcf_scale)[None, :, None] * ψ_1.reshape(
          params.t_steps, params.num_exp_t, params.dim
      )
      EtaTherm.new_process(temp_y)
      
      E_i = np.array(
          2
          ,* (
              -1j
              ,* np.sum(
                  a.conj()[:, None, :]
                  ,* ψ_1,
                  axis=(1, 2),
              )
          ).real
      ).flatten()
  
      E_i += np.array(
          2
          ,* (
              -1j * EtaTherm(int_result.τ)
              ,* np.sum(
                  a.conj()
                  ,* ψ_0,
                  axis=1,
              )
          ).real
      ).flatten()
      
      E_s = np.array(np.sum(b.conj() * ψ_0, axis=1)).flatten().real * 0
  
      return (E_i + E_s) / np.sum(ψ_0.conj() * ψ_0, axis=1).real
  e_si = np.zeros_like(int_result.τ)
  for i in range(0, params.N):
      e_si += h_si_for_traj(int_result.ψ_0[i], int_result.ψ_1[i], int_result.temp_y[i])
  e_si /= params.N

Not too bad…

  plt.plot(int_result.τ, e_si, label=r"direct")
  plt.plot(int_result.τ, E_I)
  plt.legend()
<matplotlib.legend.Legend at 0x7f0d01ef9fa0>

/hiro/master-thesis/media/commit/97ac28637dd0bb30acc8ecdce80535c563b44b42/python/richard_hops/.ob-jupyter/87f4bb117751bde97d8033fe37a50cc8b8b4dced.png