Пример #1
0
    def add_plot(self,data_x,data_y=None,label='',mode='lines+markers',row=1,col=1):
        """
        Definition to add data to the plot.

        Parameters
        ----------
        data_x      : ndarray
                      X axis data to be plotted.
        data_y      : ndarray
                      Y axis data to be plotted.
        label       : str
                      Label of the plot.  
        mode        : str
                      Mode for the plot, it can be either lines+markers, lines or markers.
        """
        if type(data_y) == type(None):
           data_y = np.arange(0,data_x.shape[0])
        if np.__name__ == 'cupy':
            data_x = np.asnumpy(data_x)
            data_y = np.asnumpy(data_y)
        self.fig.add_trace(
                           go.Scatter(
                                      x=data_x,
                                      y=data_y,
                                      mode=mode,
                                      name=label,
                                     ),
                           row=row,
                           col=col
                          )
Пример #2
0
def polynomial_fit(line_x, line_y, fit_degree=3):
    """
    Definition to fit polynomials to a vector.

    Parameters
    ----------
    line_x      : ndarray
                  Values along X axis.
    line_y      : ndarray
                  Values along Y axis.
    degree      : int
                  Degree of the polynomial fit.
    
    Returns
    ----------
    p           : numpy.poly1d
                  polynomial fit.
    """
    if np.__name__ == 'numpy':
        fun_poly = np.polyfit(line_x, line_y, fit_degree)
        p = np.poly1d(fun_poly)
    else:
        import numpy
        line_x = np.asnumpy(line_x)
        line_y = np.asnumpy(line_y)
        fun_poly = numpy.polyfit(line_x, line_y, fit_degree)
        p = numpy.poly1d(fun_poly)
    return p
Пример #3
0
def nufft2(field, fx, fy, size=None, sign=1, eps=10**(-12)):
    """
    """
    if np.__name__ == 'cupy':
        fx = np.asnumpy(fx).astype(np.float64)
        fy = np.asnumpy(fy).astype(np.float64)
        image = np.asnumpy(np.copy(field)).astype(np.complex128)
    else:
        image = np.copy(field).astype(np.complex128)
    if type(size) == type(None):
        result = finufft.nufft2d1(fx.flatten(),
                                  fy.flatten(),
                                  image.flatten(),
                                  image.shape,
                                  eps=eps,
                                  isign=sign)
    else:
        result = finufft.nufft2d1(fx.flatten(),
                                  fy.flatten(),
                                  image.flatten(), (size[0], size[1]),
                                  eps=eps,
                                  isign=sign)

    if np.__name__ == 'cupy':
        result = np.asarray(result)
    return result
Пример #4
0
    def add_field(self, field):
        """
        Definition to add a point to the figure.

        Parameters
        ----------
        field          : ndarray
                         Field to be displayed.
        """
        amplitude = calculate_amplitude(field)
        phase = calculate_phase(field, deg=True)
        intensity = calculate_intensity(field)
        if np.__name__ == 'cupy':
            amplitude = np.asnumpy(amplitude)
            phase = np.asnumpy(phase)
            intensity = np.asnumpy(intensity)
        self.fig.add_trace(go.Heatmap(z=amplitude,
                                      colorscale=self.settings['color scale']),
                           row=1,
                           col=1)

        self.fig.add_trace(go.Heatmap(z=phase,
                                      colorscale=self.settings['color scale']),
                           row=1,
                           col=2)

        self.fig.add_trace(go.Heatmap(z=intensity,
                                      colorscale=self.settings['color scale']),
                           row=1,
                           col=3)
Пример #5
0
    def add_field(self,field,row=1,col=1,showscale=False):
        """
        Definition to add a point to the figure.

        Parameters
        ----------
        field          : ndarray
                         Field to be displayed.
        row            : int
                         Row number.
        col            : int
                         Column number.
        showscale      : bool
                         Set True to show color bar.
        """
        amplitude = calculate_amplitude(field)
        phase     = calculate_phase(field,deg=True)
        intensity = calculate_intensity(field)
        if np.__name__ == 'cupy':
            amplitude = np.asnumpy(amplitude)
            phase     = np.asnumpy(phase)
            intensity = np.asnumpy(intensity)
        col = (col-1)*(self.settings["sub column no"])+1
        if self.settings["show amplitude"] == True:
            self.fig.add_trace(
                               go.Heatmap(
                                          z=amplitude,
                                          colorscale=self.settings['color scale'],
                                          showscale = showscale
                                         ),
                               row=row,
                               col=col
                              )
            col += 1

        if self.settings["show phase"] == True:
            self.fig.add_trace(
                               go.Heatmap(
                                          z=phase,
                                          colorscale=self.settings['color scale'],
                                          showscale = showscale
                                         ),
                               row=row,
                               col=col
                              )
            col += 1

        if self.settings["show intensity"] == True:
            self.fig.add_trace(
                               go.Heatmap(
                                          z=intensity,
                                          colorscale=self.settings['color scale'],
                                          showscale = showscale
                                         ),
                               row=row,
                               col=col
                              )
            col += 1
Пример #6
0
    def add_line(self,point_start,point_end,row=1,column=1,color='red'):
        """
        Definition to add a ray to the figure.

        Parameters
        ----------
        point_start    : ndarray
                         Starting point(s).
        point_end      : ndarray
                         Ending point(s).
        row            : int
                         Row number of the figure.
        column         : int
                         Column number of the figure.
        color          : str
                         Color of the lune to be drawn.
        """
        if np.__name__ == 'cupy':
            point_start = np.asnumpy(point_start)
            point_end   = np.asnumpy(point_end)
        if len(point_start.shape) == 1:
            point_start = point_start.reshape((1,3))
        if len(point_end.shape) == 1:
            point_end   = point_end.reshape((1,3))
        if point_start.shape != point_end.shape:
            print('Size mismatch in line plot. Sizes are {} and {}.'.format(point_start.shape,point_end.shape))
            sys.exit()
        for point_id in range(0,point_start.shape[0]):
            points = np.array(
                              [
                               point_start[point_id],
                               point_end[point_id]
                              ]
                             )
            points = points.reshape((2,3))
            if np.__name__ == 'cupy':
                points = np.asnumpy(points)
            self.fig.add_trace(
                               go.Scatter3d(
                                            x=points[:,0],
                                            y=points[:,1],
                                            z=points[:,2],
                                            mode='lines',
                                            line=dict(
                                                      width=self.settings["line width"],
                                                      color=color,
                                                     ),
                                            opacity=self.settings["opacity"]
                                           ),
                               row=row,
                               col=column
                              )
Пример #7
0
    def add_surface(self,
                    data_x,
                    data_y,
                    data_z,
                    surface_color,
                    row=1,
                    column=1,
                    label='',
                    mode='lines+markers',
                    opacity=1.,
                    contour=False):
        """
        Definition to add data to the plot.

        Parameters
        ----------
        data_x        : ndarray
                        X axis data to be plotted.
        data_y        : ndarray
                        Y axis data to be plotted.
        data_z        : ndarray
                        Z axis data to be plotted.
        surface_color : ndarray
                        Colors of the surface.
        label         : str
                        Label of the plot.  
        mode          : str
                        Mode for the plot, it can be either lines+markers, lines or markers.
        opacity       : float
                        Opacity of the plot. The value must be between one to zero. Zero is fully trasnparent, while one is opaque.
        """
        if np.__name__ == 'cupy':
            data_x = np.asnumpy(data_x)
            data_y = np.asnumpy(data_y)
            data_z = np.asnumpy(data_z)
            surface_color = np.asnumpy(surface_color)
        self.fig.add_trace(
            go.Surface(x=data_x,
                       y=data_y,
                       z=data_z,
                       surfacecolor=surface_color,
                       colorscale=self.settings['color scale'],
                       opacity=opacity,
                       contours={
                           'z': {
                               'show': contour,
                           },
                       }),
            row=row,
            col=column,
        )
def compare():
    wavelength = 0.5 * pow(10, -6)
    pixeltom = 6 * pow(10, -6)
    distance = 0.2
    propagation_type = 'Bandlimited Angular Spectrum'
    k = wavenumber(wavelength)
    sample_field = np.zeros((500, 500), dtype=np.complex64)
    sample_field[240:260, 240:260] = 1000
    random_phase = np.pi * np.random.random(sample_field.shape)
    sample_field = sample_field * np.cos(
        random_phase) + 1j * sample_field * np.sin(random_phase)

    if np.__name__ == 'cupy':
        sample_field = np.asnumpy(sample_field)

    sample_field_torch = torch.from_numpy(sample_field)

    ## Propagate and reconstruct using torch.
    hologram_torch = propagate_beam_torch(sample_field_torch, k, distance,
                                          pixeltom, wavelength,
                                          propagation_type)
    reconstruction_torch = propagate_beam_torch(hologram_torch, k, -distance,
                                                pixeltom, wavelength,
                                                propagation_type)

    ## Propagate and reconstruct using np.
    hologram = propagate_beam(sample_field, k, distance, pixeltom, wavelength,
                              propagation_type)
    reconstruction = propagate_beam(hologram, k, -distance, pixeltom,
                                    wavelength, propagation_type)

    np.testing.assert_array_almost_equal(hologram_torch.numpy(), hologram, 3)
Пример #9
0
    def add_point(self,point,row=1,column=1,color='red'):
        """
        Definition to add a point to the figure.

        Parameters
        ----------
        point          : ndarray
                         Point(s).
        row            : int
                         Row number of the figure.
        column         : int
                         Column number of the figure.

        """
        if np.__name__ == 'cupy':
            point = np.asnumpy(point)
        self.fig.add_trace(
                           go.Scatter3d(
                                        x=point[:,0].flatten(),
                                        y=point[:,1].flatten(),
                                        z=point[:,2].flatten(),
                                        mode='markers',
                                        marker=dict(
                                                    size=self.settings["marker size"],
                                                    color=color,
                                                    opacity=self.settings["opacity"]
                                                   ),
                                       ),
                           row=row,
                           col=column
                          )
Пример #10
0
def test():
    from odak import np
    import torch
    from odak.learn.wave import gerchberg_saxton, produce_phase_only_slm_pattern, calculate_amplitude
    from odak.tools import save_image
    wavelength = 0.000000532
    dx = 0.0000064
    distance = 0.2
    input_field = np.zeros((500, 500), dtype=np.complex64)
    input_field[0::50, :] += 1
    iteration_number = 3
    if np.__name__ == 'cupy':
        input_field = np.asnumpy(input_field)
    input_field = torch.from_numpy(input_field)
    hologram, reconstructed = gerchberg_saxton(input_field, iteration_number,
                                               distance, dx, wavelength,
                                               np.pi * 2, 'IR Fresnel')
    # hologram               = produce_phase_only_slm_pattern(
    #                                                         hologram,
    #                                                         2*np.pi
    #                                                         )
    # amplitude              = calculate_amplitude(reconstructed)
    # amplitude              = amplitude.numpy()
    # save_image(
    #             'output_amplitude_torch.png',
    #             amplitude,
    #             cmin=0,
    #             cmax=np.amax(amplitude)
    #             )
    assert True == True
Пример #11
0
def main():
    # Variables to be set.
    wavelength = 0.5 * pow(10, -6)
    pixeltom = 6 * pow(10, -6)
    distance = 0.2
    propagation_type = 'Bandlimited Angular Spectrum'
    k = wavenumber(wavelength)
    sample_field = np.zeros((500, 500), dtype=np.complex64)
    sample_field[240:260, 240:260] = 1000
    random_phase = np.pi * np.random.random(sample_field.shape)
    sample_field = sample_field * np.cos(
        random_phase) + 1j * sample_field * np.sin(random_phase)

    if np.__name__ == 'cupy':
        sample_field = np.asnumpy(sample_field)

    sample_field = torch.from_numpy(sample_field)

    hologram = propagate_beam_torch(sample_field, k, distance, pixeltom,
                                    wavelength, propagation_type)
    reconstruction = propagate_beam_torch(hologram, k, -distance, pixeltom,
                                          wavelength, propagation_type)

    #    reconstruction = np.asarray(reconstruction.numpy())
    #    sample_field   = np.asarray(sample_field.numpy())
    #    hologram       = np.asarray(hologram.numpy())
    #    from odak.visualize.plotly import detectorshow
    #    detector       = detectorshow()
    #    detector.add_field(sample_field)
    #    detector.show()
    #    detector.add_field(hologram)
    #    detector.show()
    #    detector.add_field(reconstruction)
    #    detector.show()
    assert True == True
Пример #12
0
def nuifft2(field, fx, fy, size=None, sign=1, eps=10**(-12)):
    """
    A definition to take 2D Adjoint Non-Uniform Fast Fourier Transform (NUFFT).

    Parameters
    ----------
    field       : ndarray
                  Input field.
    fx          : ndarray
                  Frequencies along x axis.
    fy          : ndarray
                  Frequencies along y axis.
    size        : list or ndarray
                  Shape of the NUFFT calculated for an input field.
    sign        : float
                  Sign of the exponential used in NUFFT kernel.
    eps         : float
                  Accuracy of NUFFT.

    Returns
    ----------
    result      : ndarray
                  NUFFT of the input field.
    """
    if np.__name__ == 'cupy':
        fx = np.asnumpy(fx).astype(np.float64)
        fy = np.asnumpy(fy).astype(np.float64)
        image = np.asnumpy(np.copy(field)).astype(np.complex128)
    else:
        image = np.copy(field).astype(np.complex128)
    if type(size) == type(None):
        result = finufft.nufft2d1(fx.flatten(),
                                  fy.flatten(),
                                  image.flatten(),
                                  image.shape,
                                  eps=eps,
                                  isign=sign)
    else:
        result = finufft.nufft2d1(fx.flatten(),
                                  fy.flatten(),
                                  image.flatten(), (size[0], size[1]),
                                  eps=eps,
                                  isign=sign)
    if np.__name__ == 'cupy':
        result = np.asarray(result)
    return result
Пример #13
0
def resize_image(img, target_size):
    if np.__name__ == 'cupy':
        import numpy
        img = np.asnumpy(img)
    img = scipy.misc.imresize(img, (target_size[0], target_size[1]))
    if np.__name__ == 'cupy':
        img = np.asarray(img)
    return img
Пример #14
0
def nuifft2(field, fx, fy, sign=1, eps=10**(-12)):
    """
    """
    if np.__name__ == 'cupy':
        fx = np.asnumpy(fx).astype(np.float64)
        fy = np.asnumpy(fy).astype(np.float64)
        image = np.asnumpy(np.copy(field)).astype(np.complex128)
    else:
        image = np.copy(field).astype(np.complex128)
    result = finufft.nufft2d2(fx.flatten(),
                              fy.flatten(),
                              image,
                              eps=eps,
                              isign=sign)
    result = result.reshape(field.shape)
    if np.__name__ == 'cupy':
        result = np.asarray(result)
    return result
Пример #15
0
def main():
    # Variables to be set.
    wavelength                 = 0.5*pow(10,-6)
    pixeltom                   = 6*pow(10,-6)
    distance                   = 0.2
    propagation_type           = 'Bandlimited Angular Spectrum'
    k                          = wavenumber(wavelength)
    sample_field               = np.zeros((500,500),dtype=np.complex64)
    sample_field[
                 240:260,
                 240:260
                ]              = 1000
    random_phase               = np.pi*np.random.random(sample_field.shape)
    sample_field               = sample_field*np.cos(random_phase)+1j*sample_field*np.sin(random_phase)
    criterion = torch.nn.MSELoss()

    if np.__name__ == 'cupy':
        sample_field = np.asnumpy(sample_field)

    sample_field               = torch.from_numpy(sample_field)

    hologram                   = propagate_beam_torch(
                                                sample_field,
                                                k,
                                                distance,
                                                pixeltom,
                                                wavelength,
                                                propagation_type
                                               )
    hologram.requires_grad = True
    reconstruction             = propagate_beam_torch(
                                                hologram,
                                                k,
                                                -distance,
                                                pixeltom,
                                                wavelength,
                                                propagation_type
                                               )
    loss = criterion(torch.abs(sample_field), torch.abs(reconstruction))
    loss.backward()
    print(hologram.grad)
    print('backward successfully')

    #from odak.visualize.plotly import detectorshow
    #detector       = detectorshow()
    #detector.add_field(sample_field)
    #detector.show()
    #detector.add_field(hologram)
    #detector.show()
    #detector.add_field(reconstruction)
    #detector.show()
    assert True==True
Пример #16
0
def test_plano_convex():
    import odak.raytracing as raytracer
    import odak.tools as tools
    import odak.catalog as catalog
    end_points        = tools.grid_sample(
                                          no=[5,5],
                                          size=[2.0,2.0],
                                          center=[0.,0.,0.],
                                          angles=[0.,0.,0.]
                                         )
    start_point       = [0.,0.,-5.]
    rays              = raytracer.create_ray_from_two_points(
                                                             start_point,
                                                             end_points
                                                            )
    lens              = catalog.plano_convex_lens()
    normals,distances = lens.intersect(rays)
    return True

    from odak import np
    import plotly
    import plotly.graph_objs as go    
    if np.__name__ == 'cupy':
        df = np.asnumpy(normals[:,0])
        dx = np.asnumpy(end_points)
        dy = np.asnumpy(start_point)
    else:
        df = normals[:,0]
        dx = end_points
        dy = start_point
    trace0 = go.Scatter3d(x=df[:,0],y=df[:,1],z=df[:,2])
    trace1 = go.Scatter3d(x=dx[:,0],y=dx[:,1],z=dx[:,2])
    trace2 = go.Scatter3d(x=[dy[0],],y=[dy[1],],z=[dy[2],])
    data   = [trace0,trace1,trace2]
    fig    = dict(data=data)
    plotly.offline.plot(fig)
    assert True==True
Пример #17
0
def save_image(fn, img, cmin=0, cmax=255):
    """
    Definition to save a Numpy array as an image.

    Parameters
    ----------
    fn           : str
                   Filename.
    img          : ndarray
                   A numpy array with NxMx3 or NxMx1 shapes.
    cmin         : int
                   Minimum value that will be interpreted as 0 level in the final image.
    cmax         : int
                   Maximum value that will be interpreted as 255 level in the final image.

    Returns
    ----------
    bool         :  bool
                    True if successful.

    """
    input_img = np.copy(img).astype(np.float)
    colorflag = False
    if len(input_img.shape) == 3:
        if input_img.shape[2] > 1:
            input_img = input_img[:, :, 0:3]
            colorflag = True
    input_img[input_img < cmin] = cmin
    input_img[input_img > cmax] = cmax
    input_img /= cmax
    input_img *= 255
    input_img = input_img.astype(np.uint8)
    if np.__name__ == 'cupy':
        input_img = np.asnumpy(input_img)
    if colorflag == True:
        result_img = Image.fromarray(input_img)
    elif colorflag == False:
        result_img = Image.fromarray(input_img).convert("L")
    result_img.save(fn)
    return True
Пример #18
0
def line_spread_function(line):
    """
    Definition to take the gradient of a 1D function.

    Parameters
    ----------
    line          : ndarray
                    1D array.

    Returns
    ----------
    result        : ndarray
                    Gradient of the given 1D array.
    """
    if np.__name__ == 'cupy':
        import numpy
        cache = np.asnumpy(line)
        result = numpy.gradient(cache)
    else:
        result = np.gradient(line)
    result = np.asarray(result)
    return result