# Add parent directory to beginning of path variable
    DIR = dirname(abspath(__file__))
    sys.path.insert(0, split(DIR)[0])
    
    import odtbrain as odt
    
    # use jobmanager if available
    try:
        import jobmanager as jm
        jm.decorators.decorate_module_ProgressBar(odt, 
                            decorator=jm.decorators.ProgressBarOverrideCount,
                            interval=.1)
    except:
        pass

    datazip = get_file("mie_2d_noncentered_cylinder_A250_R2.zip")
    
    # Get simulation data
    arc = zipfile.ZipFile(datazip)

    angles = np.loadtxt(arc.open("mie_angles.txt"))

    # sinogram computed with mie
    # computed with
    # miefield.GetSinogramCylinderRotation(radius, nmed, ncyl, lD, lC, size, A, res)
    sino_real = np.loadtxt(arc.open("sino_real.txt"))
    sino_imag = np.loadtxt(arc.open("sino_imag.txt"))
    sino = sino_real + 1j*sino_imag
    A, size = sino_real.shape

    # background sinogram computed with mie
`on figshare <https://doi.org/10.6084/m9.figshare.8055407.v1>`
(hl60_sinogram_qpi.h5).
"""
import pathlib
import tarfile
import tempfile

import matplotlib.pylab as plt
import numpy as np
import odtbrain as odt
import qpimage

from example_helper import get_file, extract_lzma

# ascertain the data
path = get_file("qlsi_3d_hl60-cell_A140.tar.lzma")
tarf = extract_lzma(path)
tdir = tempfile.mkdtemp(prefix="odtbrain_example_")

with tarfile.open(tarf) as tf:
    tf.extract("series.h5", path=tdir)
    angles = np.loadtxt(tf.extractfile("angles.txt"))

# extract the complex field sinogram from the qpimage series data
h5file = pathlib.Path(tdir) / "series.h5"
with qpimage.QPSeries(h5file=h5file, h5mode="r") as qps:
    qp0 = qps[0]
    meta = qp0.meta
    sino = np.zeros((len(qps), qp0.shape[0], qp0.shape[1]), dtype=np.complex)
    for ii in range(len(qps)):
        sino[ii] = qps[ii].field
                      "without autofocusing.")
        autofocus = False
    else:
        autofocus = True
    
    # use jobmanager if available
    try:
        import jobmanager as jm
        jm.decorators.decorate_module_ProgressBar(odt, 
                            decorator=jm.decorators.ProgressBarOverrideCount,
                            interval=.1)
    except:
        pass
    

    datazip = get_file("mie_3d_sphere_field.zip")
    # Get simulation data
    arc = zipfile.ZipFile(datazip)

    Ex_real = np.loadtxt(arc.open("mie_sphere_real.txt"))
    Ex_imag = np.loadtxt(arc.open("mie_sphere_imag.txt"))
    Ex = Ex_real +1j*Ex_imag
    # get nm, lD, res
    with arc.open("mie_info.txt") as info:
        cfg = {}
        for l in info.readlines():
            l = l.decode()
            if l.count("=") == 1:
                key, val = l.split("=")
                cfg[key.strip()] = float(val.strip())
    # Add parent directory to beginning of path variable
    DIR = dirname(abspath(__file__))
    sys.path.insert(0, split(DIR)[0])
    
    import odtbrain as odt
    
    # use jobmanager if available
    try:
        import jobmanager as jm
        jm.decorators.decorate_module_ProgressBar(odt, 
                            decorator=jm.decorators.ProgressBarOverrideCount,
                            interval=.1)
    except:
        pass

    datazip = get_file("fdtd_2d_sino_A100_R13.zip")
    # Get simulation data
    arc = zipfile.ZipFile(datazip)

    angles = np.loadtxt(arc.open("fdtd_angles.txt"))
    phantom = np.loadtxt(arc.open("fdtd_phantom.txt"))
    sino_real = np.loadtxt(arc.open("fdtd_real.txt"))
    sino_imag = np.loadtxt(arc.open("fdtd_imag.txt"))
    sino = sino_real +1j*sino_imag
    # get nm, lD, res
    with arc.open("fdtd_info.txt") as info:
        cfg = {}
        for l in info.readlines():
            l = l.decode()
            if l.count("=") == 1:
                key, val = l.split("=")
    DIR = dirname(abspath(__file__))
    sys.path.insert(0, split(DIR)[0])
    
    import odtbrain as odt
    
    # use jobmanager if available
    try:
        import jobmanager as jm
        jm.decorators.decorate_module_ProgressBar(odt, 
                            decorator=jm.decorators.ProgressBarOverrideCount,
                            interval=.1)
    except:
        pass


    lzmafile = get_file("fdtd_3d_sino_A180_R6.500.tar.lzma")
    sino, angles, phantom, cfg = load_tar_lzma_data(lzmafile)

    A = angles.shape[0]
    
    print("Example: Backpropagation from 3d FDTD simulations")
    print("Refractive index of medium:", cfg["nm"])
    print("Measurement position from object center:", cfg["lD"])
    print("Wavelength sampling:", cfg["res"])
    print("Number of projections:", A)
    print("Performing backpropagation.")

    ## Apply the Rytov approximation
    sinoRytov = odt.sinogram_as_rytov(sino)

    
    import odtbrain as odt
    


    try:
        # use jobmanager if available
        import jobmanager as jm
        jm.decorators.decorate_module_ProgressBar(odt, 
                            decorator=jm.decorators.ProgressBarOverrideCount,
                            interval=.1)
    except:
        pass


    lzmafile = get_file("fdtd_3d_sino_A220_R6.500_tiltyz0.2.tar.lzma")
    
    sino, angles, phantom, cfg = load_tar_lzma_data(lzmafile)

    # Perform titlt by -.42 rad in detector plane    
    rotang = -0.42
    from scipy.ndimage import rotate
    rotkwargs= {"mode":"constant",
                "order":2,
                "reshape":False,
                }
    for ii in range(len(sino)):
        sino[ii].real = rotate(sino[ii].real, np.rad2deg(rotang), cval=1, **rotkwargs)
        sino[ii].imag = rotate(sino[ii].imag, np.rad2deg(rotang), cval=0, **rotkwargs)

    A = angles.shape[0]