Exemplo n.º 1
0
def test_3d_backprop_real():
    """
    Check if the real reconstruction matches the real part
    of the complex reconstruction.
    """
    sino, angles = create_test_sino_3d(Nx=10, Ny=10)
    parameters = get_test_parameter_set(2)
    # complex
    r = list()
    for p in parameters:
        f = odtbrain.backpropagate_3d(sino,
                                      angles,
                                      padval=0,
                                      dtype=np.float64,
                                      onlyreal=False,
                                      **p)
        r.append(f)
    # real
    r2 = list()
    for p in parameters:
        f = odtbrain.backpropagate_3d(sino,
                                      angles,
                                      padval=0,
                                      dtype=np.float64,
                                      onlyreal=True,
                                      **p)
        r2.append(f)
    assert np.allclose(np.array(r).real, np.array(r2))
Exemplo n.º 2
0
def test_3d_backprop_weights_even():
    """
    even weights
    """
    platform.system = lambda: "Windows"
    sino, angles = create_test_sino_3d()
    p = get_test_parameter_set(1)[0]
    f1 = odtbrain.backpropagate_3d(sino, angles, weight_angles=False, **p)
    f2 = odtbrain.backpropagate_3d(sino, angles, weight_angles=True, **p)
    data1 = np.array(f1).flatten().view(float)
    data2 = np.array(f2).flatten().view(float)
    assert np.allclose(data1, data2)
Exemplo n.º 3
0
def test_back3d():
    sino, angles = create_test_sino_3d(Nx=10, Ny=10)
    p = get_test_parameter_set(1)[0]
    # complex
    jmc = mp.Value("i", 0)
    jmm = mp.Value("i", 0)
    odtbrain.backpropagate_3d(sino,
                              angles,
                              padval=0,
                              dtype=np.float64,
                              count=jmc,
                              max_count=jmm,
                              **p)
    assert jmc.value == jmm.value
    assert jmc.value != 0
Exemplo n.º 4
0
def test_correct_reproduce():
    myframe = sys._getframe()
    sino, angles = create_test_sino_3d(Nx=10, Ny=10)
    p = get_test_parameter_set(1)[0]
    sryt = odtbrain.sinogram_as_rytov(uSin=sino, u0=1, align=False)
    f = odtbrain.backpropagate_3d(sryt,
                                  angles,
                                  padval=0,
                                  dtype=np.float64,
                                  copy=False,
                                  **p)
    fc = odtbrain.apple.correct(f=f,
                                res=p["res"],
                                nm=p["nm"],
                                enforce_envelope=.95,
                                max_iter=100,
                                min_diff=0.01)
    fo = cutout(fc)
    fo = np.array(fo, dtype=np.complex128)

    if WRITE_RES:
        write_results(myframe, fo)

    data = fo.flatten().view(float)
    assert np.allclose(data, get_results(myframe))
Exemplo n.º 5
0
def test_back3d():
    sino, angles = create_test_sino_3d(Nx=10, Ny=10)
    p = get_test_parameter_set(1)[0]
    # complex
    f1 = odtbrain.backpropagate_3d(sino,
                                   angles,
                                   padval=0,
                                   dtype=np.float64,
                                   copy=False,
                                   **p)
    f2 = odtbrain.backpropagate_3d(sino,
                                   angles,
                                   padval=0,
                                   dtype=np.float64,
                                   copy=True,
                                   **p)
    assert np.allclose(f1, f2)
Exemplo n.º 6
0
def test_3d_backprop_phase32():
    sino, angles = create_test_sino_3d()
    parameters = get_test_parameter_set(2)
    r = list()
    for p in parameters:
        f = odtbrain.backpropagate_3d(sino,
                                      angles,
                                      dtype=np.float32,
                                      padval=0,
                                      **p)
        r.append(cutout(f))
    data32 = np.array(r).flatten().view(np.float32)
    data64 = test_3d_backprop_phase()
    assert np.allclose(data32, data64, atol=6e-7, rtol=0)
Exemplo n.º 7
0
def test_back3d():
    sino, angles = create_test_sino_3d(Nx=10, Ny=10)
    parameters = get_test_parameter_set(2)
    # complex
    r = list()
    for p in parameters:
        f = odtbrain.backpropagate_3d(sino,
                                      angles,
                                      padval=0,
                                      dtype=np.float64,
                                      save_memory=False,
                                      **p)
        r.append(f)
    # real
    r2 = list()
    for p in parameters:
        f = odtbrain.backpropagate_3d(sino,
                                      angles,
                                      padval=0,
                                      dtype=np.float64,
                                      save_memory=True,
                                      **p)
        r2.append(f)
    assert np.allclose(np.array(r), np.array(r2))
Exemplo n.º 8
0
def test_3d_backprop_phase():
    myframe = sys._getframe()
    sino, angles = create_test_sino_3d()
    parameters = get_test_parameter_set(2)
    r = list()
    for p in parameters:
        f = odtbrain.backpropagate_3d(sino,
                                      angles,
                                      padval=0,
                                      dtype=np.float64,
                                      **p)
        r.append(cutout(f))
    if WRITE_RES:
        write_results(myframe, r)
    data = np.array(r).flatten().view(float)
    assert np.allclose(data, get_results(myframe))
    return data
Exemplo n.º 9
0
def test_3d_backprop_phase_real():
    sino, angles = create_test_sino_3d()
    parameters = get_test_parameter_set(2)
    # reference
    rref = list()
    for p in parameters:
        fref = odtbrain.backpropagate_3d(sino, angles, padval=0,
                                         dtype=np.float64, onlyreal=True, **p)
        rref.append(cutout(fref))
    dataref = np.array(rref).flatten().view(float)

    r = list()
    for p in parameters:
        f = odtbrain.backpropagate_3d_tilted(sino, angles, padval=0,
                                             dtype=np.float64, onlyreal=True,
                                             **p)
        r.append(cutout(f))
    data = np.array(r).flatten().view(float)
    assert np.allclose(data, dataref)
Exemplo n.º 10
0
def test_correct_values():
    sino, angles = create_test_sino_3d(Nx=10, Ny=10)
    p = get_test_parameter_set(1)[0]
    f = odtbrain.backpropagate_3d(sino,
                                  angles,
                                  padval=0,
                                  dtype=np.float64,
                                  copy=False,
                                  **p)
    try:
        odtbrain.apple.correct(
            f=f,
            res=p["res"],
            nm=p["nm"],
            enforce_envelope=1.05,
        )
    except ValueError:
        pass
    else:
        assert False, "`enforce_envelope` must be in [0, 1]"
Exemplo n.º 11
0
def test_correct_counter():
    count = mp.Value("I", lock=True)
    max_count = mp.Value("I", lock=True)

    sino, angles = create_test_sino_3d(Nx=10, Ny=10)
    p = get_test_parameter_set(1)[0]
    f = odtbrain.backpropagate_3d(sino,
                                  angles,
                                  padval=0,
                                  dtype=np.float64,
                                  copy=False,
                                  **p)
    odtbrain.apple.correct(f=f,
                           res=p["res"],
                           nm=p["nm"],
                           enforce_envelope=.95,
                           max_iter=100,
                           min_diff=0.01,
                           count=count,
                           max_count=max_count)

    assert count.value == max_count.value
Exemplo n.º 12
0
def test_3d_backprop_nopadreal():
    """
    - no padding
    - only real result
    """
    platform.system = lambda: "Windows"
    myframe = sys._getframe()
    sino, angles = create_test_sino_3d()
    parameters = get_test_parameter_set(2)
    r = list()
    for p in parameters:
        f = odtbrain.backpropagate_3d(sino,
                                      angles,
                                      padding=(False, False),
                                      dtype=np.float64,
                                      onlyreal=True,
                                      **p)
        r.append(cutout(f))
    if WRITE_RES:
        write_results(myframe, r)
    data = np.array(r).flatten().view(float)
    assert np.allclose(data, get_results(myframe))
Exemplo n.º 13
0
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)

# perform backpropagation to obtain object function f
f = odt.backpropagate_3d(uSin=sinoRytov,
                         angles=angles,
                         res=cfg["res"],
                         nm=cfg["nm"],
                         lD=cfg["lD"]
                         )

# compute refractive index n from object function
n = odt.odt_to_ri(f, res=cfg["res"], nm=cfg["nm"])

sx, sy, sz = n.shape
px, py, pz = phantom.shape

sino_phase = np.angle(sino)

# compare phantom and reconstruction in plot
fig, axes = plt.subplots(2, 3, figsize=(8, 4))
kwri = {"vmin": n.real.min(), "vmax": n.real.max()}
kwph = {"vmin": sino_phase.min(), "vmax": sino_phase.max(),
Exemplo n.º 14
0
# initialize cell phantom
phantom = cellsino.phantoms.SimpleCell()

# initialize sinogram with geometric parameters
sino = cellsino.Sinogram(phantom=phantom,
                         wavelength=wavelength,
                         pixel_size=pixel_size,
                         grid_size=grid_size)

# compute sinogram (field according to Rytov approximation and fluorescence)
sino_field, sino_fluor = sino.compute(angles=angles, propagator="rytov")

# reconstruction of refractive index
sino_rytov = odt.sinogram_as_rytov(sino_field)
potential = odt.backpropagate_3d(uSin=sino_rytov,
                                 angles=angles,
                                 res=wavelength/pixel_size,
                                 nm=medium_index)
ri = odt.odt_to_ri(f=potential,
                   res=wavelength/pixel_size,
                   nm=medium_index)

# reconstruction of fluorescence
fl = rt.backproject_3d(sinogram=sino_fluor,
                       angles=angles)

# reference for comparison
rimod, flmod = phantom.draw(grid_size=ri.shape,
                            pixel_size=pixel_size)

# plotting
idx = 150
# 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

# perform backgpropagation
u_sinR = odt.sinogram_as_rytov(sino)
res = meta["wavelength"] / meta["pixel size"]
nm = meta["medium index"]

fR = odt.backpropagate_3d(uSin=u_sinR, angles=angles, res=res, nm=nm)

ri = odt.odt_to_ri(fR, res, nm)

# plot results
ext = meta["pixel size"] * 1e6 * 70
kw = {
    "vmin": ri.real.min(),
    "vmax": ri.real.max(),
    "extent": [-ext, ext, -ext, ext]
}
fig, axes = plt.subplots(1, 3, figsize=(8, 2.5))
axes[0].imshow(ri[70, :, :].real, **kw)
axes[0].set_xlabel("x [µm]")
axes[0].set_ylabel("y [µm]")
                                   ret_d=True)
        lD = 0
        print("Autofocusing distance [px]: ", d)
    else:
        lD = cfg["lD"]*cfg["res"]

    # Create sinogram
    u_sin = np.tile(Ex.flat,A).reshape(A, cfg["size"], cfg["size"])

    # Apply the Rytov approximation
    u_sinR = odt.sinogram_as_rytov(u_sin)

    # Backpropagation
    fR = odt.backpropagate_3d(uSin = u_sinR, 
                              angles = angles, 
                              res = cfg["res"],
                              nm = cfg["nm"],
                              lD = lD,
                              padfac=2.1)

    # RI computation
    nR = odt.odt_to_ri(fR, cfg["res"], cfg["nm"])

    # Plotting
    fig, axes = plt.subplots(2, 3, figsize=(12,8), dpi=300)
    axes = np.array(axes).flatten()
    # field
    axes[0].set_title("Mie field phase")
    axes[0].set_xlabel("xD")
    axes[0].set_ylabel("yD")
    axes[0].imshow(np.angle(Ex), cmap=plt.cm.coolwarm)  # @UndefinedVariable
    axes[1].set_title("Mie field amplitude")
Exemplo n.º 17
0
def backpropagate_sinogram(
    sinogram,
    angles,
    approx,
    res,
    nm,
    ld=0,
):
    """Backpropagate a 2D or 3D sinogram

    Parameters
    ----------
    sinogram: complex ndarray
        The scattered field data
    angles: 1d ndarray
        The angles at which the sinogram data were recorded
    approx: str
        Approximation to use, one of ["radon", "born", "rytov"]
    res: float
        Size of vacuum wavelength in pixels
    nm: float
        Refractive index of surrounding medium
    ld: float
        Reconstruction distance. Values !=0 only make sense for the
        Born approximation (which itself is not very usable).
        See the ODTbrain documentation for more information.

    Returns
    -------
    ri: ndarray
        The 2D or 3D reconstructed refractive index
    """
    sshape = len(sinogram.shape)
    assert sshape in [2, 3], "sinogram must have dimension 2 or 3"

    uSin = sinogram
    assert approx in ["radon", "born", "rytov"]

    if approx == "rytov":
        uSin = odt.sinogram_as_rytov(uSin)
    elif approx == "radon":
        uSin = odt.sinogram_as_radon(uSin)

    if approx in ["born", "rytov"]:
        # Perform reconstruction with ODT
        if sshape == 2:
            f = odt.backpropagate_2d(uSin,
                                     angles=angles,
                                     res=res,
                                     nm=nm,
                                     lD=ld)
        else:
            f = odt.backpropagate_3d(uSin,
                                     angles=angles,
                                     res=res,
                                     nm=nm,
                                     lD=ld)

        ri = odt.odt_to_ri(f, res, nm)
    else:
        # Perform reconstruction with OPT
        # works in 2d and 3d
        f = rt.backproject(uSin, angles=angles)
        ri = odt.opt_to_ri(f, res, nm)

    return ri
    d=-cfg["lD"] * cfg["res"],
    nm=cfg["nm"],
    res=cfg["res"],
)

# Create sinogram
u_sin = np.tile(Ex.flat, A).reshape(A, int(cfg["size"]), int(cfg["size"]))

# Apply the Rytov approximation
u_sinR = odt.sinogram_as_rytov(u_sin)

# Backpropagation
fR = odt.backpropagate_3d(uSin=u_sinR,
                          angles=angles,
                          res=cfg["res"],
                          nm=cfg["nm"],
                          lD=0,
                          padfac=2.1,
                          save_memory=True)

# RI computation
nR = odt.odt_to_ri(fR, cfg["res"], cfg["nm"])

# Plotting
fig, axes = plt.subplots(2, 3, figsize=(8, 5))
axes = np.array(axes).flatten()
# field
axes[0].set_title("Mie field phase")
axes[0].set_xlabel("detector x")
axes[0].set_ylabel("detector y")
axes[0].imshow(np.angle(Ex), cmap="coolwarm")
Exemplo n.º 19
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)


    ## perform backpropagation to obtain object function f
    f = odt.backpropagate_3d( uSin=sinoRytov,
                              angles=angles,
                              res=cfg["res"],
                              nm=cfg["nm"],
                              lD=cfg["lD"]
                              )

    ## compute refractive index n from object function
    n = odt.odt_to_ri(f, res=cfg["res"], nm=cfg["nm"])

    sx, sy, sz = n.shape
    px, py, pz = phantom.shape


    sino_phase = np.angle(sino)    
    
    ## compare phantom and reconstruction in plot
    fig, axes = plt.subplots(2, 3, figsize=(12,7), dpi=300)
    kwri = {"vmin": n.real.min(), "vmax": n.real.max()}