def planoConvex(self, lens1, lens2, diameters):
        """A function which calculates and plots the RMS spot radius for the range of diameters input"""

        lenses = [lens1, lens2]
        testRay = rt.Ray([0.1, 0, 0], [0, 0, 1])

        for lens in lenses:
            lens.propagateRay(testRay)

        output = lenses[-1].paraxial(
            testRay
        )  #Setting the output plane at the paraxial focus of the setup
        lenses.append(output)
        focalLength = output.getz() - (
            (lens1.getz0() + lens2.getz0()) / 2
        )  #Calculating the focal length of the lens
        wavelength = 588e-6  #The wavelength of the light is 588nm (The units used in the simulation are mm)
        ray = rt.Ray([0, 0, 0], [0, 0, 1])
        diameterList = []
        RMSList = []
        diffractionList = []

        for i in diameters:
            diameterList.append(i)
            rays = rt.Bundle(10, i / 2, 10).getBundle(
                ray)  #Creating a bundle of rays for each diameter
            for lens in lenses:
                lens.propagateBundle(
                    rays)  #Propagating the rays through the lenses
            plot = pt.Plot(rays)
            RMS = plot.rms(
            )  #Calculating the RMS spot radius of the rays at the output for each diameter
            RMSList.append(RMS)
            diffractionLimit = (
                focalLength * wavelength
            ) / i  #Also calculating the diffraction scale for each diameter
            diffractionList.append(diffractionLimit)

        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.set_xlabel('Diameter (mm)')
        ax.set_ylabel('RMS (mm)')
        ax.set_title('Diffaction Limit')
        plt.grid(True)
        ax.plot(diameterList, RMSList,
                'green')  #Plotting the RMS spot radius against diameter
        ax.plot(diameterList, diffractionList,
                'red')  #Plotting the diffraction scale against diameter

        RMSValues = np.array(RMSList, dtype='float')
        diffractionValues = np.array(diffractionList, dtype='float')
        difference = (diffractionValues - RMSValues).tolist()
        difference = [
            abs(i) for i in difference
        ]  #Calculating the differences between the RMS spot radius and the diffraction scale at each diameter

        index = difference.index(min(difference))
        intersection = diameterList[
            index]  #Finding the point on the graph where the difference between the two functions is a minimum, and taking this to be the intersection point of the two plots.
        print 'Intersection is: ', intersection
    def plotRays(self, rayVectors):
        """A function which shows all the various plots of the rays"""

        plot = pt.Plot(rayVectors)
        plot.plotRays2D()
        plot.plotRays3D()
        plot.plotInput()
        plot.plotOutput()
        plt.show()
    def optimalRMS(self, curvatures):
        """A function which calculates and returns the log of the RMS spot radius for two given curvatures of a biconvex lens"""

        lens1 = op.SphericalRefraction(100, 20, curvatures[0], 1, 1.5168)
        lens2 = op.SphericalRefraction(105, 20, curvatures[1], 1.5168, 1)
        output = op.OutputPlane(200)  #The output plane is set at z=200mm
        lenses = [lens1, lens2, output]

        ray = rt.Ray([0, 0, 0], [0, 0, 1])
        rays = rt.Bundle(10, 5,
                         10).getBundle(ray)  #A bundle of rays is created

        for lens in lenses:
            lens.propagateBundle(
                rays)  #The rays are propagated through the biconvex lens
        plot = pt.Plot(rays)
        RMS = plot.rms(
        )  #Calculating the RMS spot radius of the rays at the output for the given curvatures
        log = np.log(RMS)
        return log
Example #4
0
import sys
import numpy as np
from decimal import Decimal
from my_utils import *
from load_and_save_data import *
import scenario_objects
import agent
import plotting
from gym import spaces, logger
import os

load = Loader()
load.maps_data()
load.users_clusters()
load.maps_status()
plot = plotting.Plot()

class UAVEnv(gym.Env):

    def __init__(self):
        # Setting upper and lower bounds for actions values:
        upper_limits = np.array([val[0] for val in LIMIT_VALUES_FOR_ACTION])
        lower_limits = np.array([val[1] for val in LIMIT_VALUES_FOR_ACTION])

        self.action_set_min = ACTION_SPACE_3D_MIN if DIMENSION_2D==False else ACTION_SPACE_2D_MIN
        if (UNLIMITED_BATTERY==True):
            self.q_table_action_set = self.action_set_min
        else:
            if (self.action_set_min==ACTION_SPACE_2D_MIN):
                self.q_table_action_set = ACTION_SPACE_2D_TOTAL
                self.charging_set = ACTION_SPACE_2D_WHILE_CHARGING
Example #5
0
 def setUp(self):
     self.plot = plt.Plot([SomeTrace()])
def compare_mode(args):

    # ---------------
    # LOAD HISTOGRAMS
    # -----------------------------------------
    histfile = h5py.File(args.histfilename, 'r')
    Hmap = histfile['data/histogram']
    Hbinsize = histfile['data/histogramBinsize'][0]
    Hcount = histfile['data/histogramCount'][0]
    Hmin = histfile['data/histogramMin'][0]
    Hnbins = histfile['data/histogramNbins'][0]
    dark_offset = histfile['data/offset'][:]
    Hbins = np.arange(Hmin, (Hbinsize * (Hnbins - 1) + Hmin) + Hbinsize,
                      Hbinsize)
    NY = Hmap.shape[0]
    NX = Hmap.shape[1]
    SH = (NY, NX)
    NXY = NX * NY

    # --------------------
    # LOAD FITTING RESULTS
    # ----------------------------------------
    fitfile = h5py.File(args.fitfilename, 'r')
    bg_offset = fitfile['bg_offset'][:].reshape(
        tuple(fitfile['bg_offset'].attrs['shape']))
    bg_amp = fitfile['bg_amp'][:].reshape(
        tuple(fitfile['bg_amp'].attrs['shape']))
    bg_sigma = fitfile['bg_sigma'][:].reshape(
        tuple(fitfile['bg_sigma'].attrs['shape']))
    photon_offset = fitfile['photon_offset'][:].reshape(
        tuple(fitfile['photon_offset'].attrs['shape']))
    photon_amp = fitfile['photon_amp'][:].reshape(
        tuple(fitfile['photon_amp'].attrs['shape']))
    photon_sigma = fitfile['photon_sigma'][:].reshape(
        tuple(fitfile['photon_sigma'].attrs['shape']))
    status = fitfile['status'][:].reshape(
        tuple(fitfile['status'].attrs['shape']))
    dark = fitfile['dark_offset'][:] + bg_offset
    gain = photon_offset - bg_offset

    # ---------
    # LOAD MASK
    # ----------------------------------------------------
    if args.m is None: mask = np.zeros(SH).astype(np.bool)
    else:
        maskfile = h5py.File(args.m, 'r')
        mask = (1 - maskfile['data/data'][:]).astype(np.bool)
        maskfile.close()
        gain[mask] = np.nan

    # -------------
    # PLOT GAIN MAP
    # ------------------------------------------------------
    plot = plotting.Plot(colorbar=True)
    plot.xlabel = 'x (total width = %d pixel)' % gain.shape[1]
    plot.ylabel = 'y (total height = %d pixel)' % gain.shape[0]
    plot.title_label = '%s - gain' % (args.fitfilename)
    plot.colorbar_label = 'ADUs'
    plot.plotting_a_map(0,
                        gain,
                        cmap=args.cmap,
                        vmin=args.vmin,
                        vmax=args.vmax)
    #plot.show()

    # ---------------------
    # PHOTON DETECTION RATE
    # ---------------------
    if args.d:
        N = (photon_amp * np.sqrt(2 * math.pi * photon_sigma**2))
        bg_amp /= N
        photon_amp /= N
        Hmap /= N
        pdr = []
        thresholds = np.linspace(0, 2, 200)
        for i in range(200):
            threshold = bg_offset + thresholds[i] * gain
            pdr_t = (math.sqrt(math.pi) /
                     2) * (photon_amp * photon_sigma * sp.special.erfc(
                         (threshold - photon_offset) /
                         (math.sqrt(2) * photon_sigma)) -
                           bg_amp * bg_sigma * sp.special.erfc(
                               (threshold - bg_offset) /
                               (math.sqrt(2) * bg_sigma)))
            pdr.append(pdr_t)

        pdr = np.dstack(pdr)
        bestth = thresholds[np.argmax(pdr, axis=2)]
        pdrmap = np.amax(pdr, axis=2)

    # -------------------------
    # PLOT PHOTON DETECTABILITY
    # --------------------------
    gaussian_model = lambda x, p: p[0] * np.exp(-(np.power(x - p[1], 2)) / (
        2 * np.power(p[2], 2)))  # the gaussian model
    y, x = args.pixel
    H = Hmap[y, x]
    bg_params = [bg_amp[y, x], bg_offset[y, x], bg_sigma[y, x]]
    photon_params = [photon_amp[y, x], photon_offset[y, x], photon_sigma[y, x]]
    photon2_params = [
        0.08 * photon_amp[y, x], 2 * photon_offset[y, x], photon_sigma[y, x]
    ]
    bfit = gaussian_model(Hbins, bg_params)
    pfit = gaussian_model(Hbins, photon_params)
    p2fit = gaussian_model(Hbins, photon2_params)
    sfit = 0
    for i in range(5, int(photon_offset[y, x]) - 5 + 1):
        split_params = [
            0.5 * photon_amp[y, x] / (int(photon_offset[y, x] + 1) - 9), i,
            bg_sigma[y, x]
        ]
        sfit += gaussian_model(Hbins, split_params)
    sfit2 = 0
    for i in range(5, int(photon_offset[y, x]) - 5 + 1):
        i += photon_offset[y, x]
        split_params = [
            0.5 * 0.08 * photon_amp[y, x] / (int(photon_offset[y, x] + 1) - 5),
            i, bg_sigma[y, x]
        ]
        sfit2 += gaussian_model(Hbins, split_params)
    print photon_params, bg_params
    plot = plotting.Plot(save_png=True)
    plot.axes[0].plot((Hbins - bg_offset[y, x]) / gain[y, x],
                      H,
                      'r-',
                      label='Data')
    plot.axes[0].plot((Hbins - bg_offset[y, x]) / gain[y, x],
                      bfit,
                      'b-',
                      label='Gaussian fit to 0-ph peak')
    plot.axes[0].plot((Hbins - bg_offset[y, x]) / gain[y, x],
                      pfit,
                      'g-',
                      label='Gaussian fit to 1-ph peak')
    plot.axes[0].plot((Hbins - bg_offset[y, x]) / gain[y, x],
                      p2fit,
                      'g-',
                      label='Gaussian fit to 2-ph peak')
    plot.axes[0].plot((Hbins - bg_offset[y, x]) / gain[y, x],
                      sfit,
                      'm-',
                      label='Gaussian fit to 0/1-ph peak')
    plot.axes[0].plot((Hbins - bg_offset[y, x]) / gain[y, x],
                      sfit2,
                      'm-',
                      label='Gaussian fit to 1/2-ph peak')
    plot.axes[0].plot((Hbins - bg_offset[y, x]) / gain[y, x],
                      bfit + pfit + p2fit + sfit + sfit2,
                      'k--',
                      label='Sum of Gaussians')
    if args.d:
        pdryx = pdr[y, x]
        plot.axes[0].plot(thresholds,
                          pdryx,
                          color='0.5',
                          label='Photon detection rate')
        plot.axes[0].axvline(bestth[y, x], color='k', lw=1, ls='dotted')
    #plot.axes[0].plot(Hbins, H-(bfit + pfit), 'm-')
    plot.axes[0].semilogy()
    plot.axes[0].set_ylim([1, None])
    plot.axes[0].set_xlim([-1, 4])
    plot.axes[0].set_xlabel("Signal in nr. of photons")
    plot.axes[0].set_title("Pixel: X=%d, Y=%d" % (x, y))
    plot.axes[0].legend()
    plot.show()
    plot.save("fit.png")

    # -------------------------
    # PLOT FITTING TO HISTOGRAM
    # ----------------------
    y, x = args.pixel
    H = Hmap[y, x]
    bg_params = [bg_amp[y, x], bg_offset[y, x], bg_sigma[y, x]]
    photon_params = [photon_amp[y, x], photon_offset[y, x], photon_sigma[y, x]]
    gaussian_model = lambda x, p: p[0] * np.exp(-(np.power(x - p[1], 2)) / (
        2 * np.power(p[2], 2)))  # the gaussian model
    bfit = gaussian_model(Hbins, bg_params)
    pfit = gaussian_model(Hbins, photon_params)

    print 'Status: ', status[y, x]
    print '0-photon, mean = %.2f, std = %.2f' % (bg_offset[y, x], bg_sigma[y,
                                                                           x])
    print '1-photon, mean = %.2f, std = %.2f' % (photon_offset[y, x],
                                                 photon_sigma[y, x])
    print 'Estimated gain: ', gain[y, x]
    #print 'Optimal threshold: ', bestth[y,x]
    #print 'Max. photon detectability rate: ', pdrmap[y,x]

    plot = plotting.Plot(save_pdf=True)
    plot.axes[0].plot(Hbins, H, 'r-', label='Data')
    plot.axes[0].plot(Hbins, bfit, 'b-', label='Gaussian fit to 0-ph peak')
    plot.axes[0].plot(Hbins, pfit, 'g-', label='Gaussian fit to 1-ph peak')
    plot.axes[0].plot(Hbins, bfit + pfit, 'k--', label='Sum of Gaussians')
    #plot.axes[0].plot(Hbins, H-(bfit + pfit), 'm-')
    plot.axes[0].semilogy()
    plot.axes[0].set_ylim([1, None])
    plot.axes[0].set_xlabel("Signal in ADUs")
    plot.axes[0].set_title("Pixel: X=%d, Y=%d" % (x, y))
    plot.axes[0].legend()
    plot.show()
    plot.save("test.pdf")