예제 #1
0
def bundles_step3(nrays=100, rpup=7.5, maxfield_deg=2.):
    """
    Creates an array of collimated RayBundle objects for step 3.
    """
    bundles = []
    fields_rad = np.array([0, 0.5*np.sqrt(2), 1]) * maxfield_deg * pi / 180.

    (px, py) = RectGrid().getGrid(nrays)

    for field in fields_rad:
        starty = -30 * np.tan(field)
        # TODO: this step explicitly sets the pupil
        # so the stop position is ignored. Better get Aimy to run ...

        o = np.vstack((rpup*px, rpup*py + starty, np.zeros_like(px)))
        k = np.zeros_like(o)
        k[1, :] = np.sin(field)
        k[2, :] = np.cos(field)
        E0 = np.cross(k, canonical_ex, axisa=0, axisb=0).T

        bundles += [RayBundle(o, k, E0, wave=Fline)]
        bundles += [RayBundle(o, k, E0, wave=dline)]
        bundles += [RayBundle(o, k, E0, wave=Cline)]

    return bundles
예제 #2
0
파일: demo_spd.py 프로젝트: theinze/pyrate
    def bundle(fpx, fpy, nrays=16, rpup=5):
        """
        Creates a RayBundle

        * o is the origin - this is ok
        * k is the wave vector, i.e. direction; needs to be normalized
        * E0 is the polarization vector

        """

        (px, py) = RectGrid().getGrid(nrays)

        #pts_on_first_surf = np.vstack((rpup*px, rpup*py, np.zeros_like(px)))
        pts_on_entrance_pupil = np.vstack(
            (rpup * px, rpup * py, np.ones(px.shape) * spd.psys.entpup))

        o = np.concatenate([ fpx * spd.psys.field_size_obj() * np.ones([1,len(px)]), \
                            -fpy * spd.psys.field_size_obj() * np.ones([1,len(px)]), \
                             spd.psys.obj_dist() * np.ones([1,len(px)]) ], axis=0 )

        k = (pts_on_entrance_pupil - o)

        normk = np.sqrt([np.sum(k * k, axis=0)])
        k = k / (np.matmul(np.ones([3, 1]), normk))

        E0 = np.cross(k, canonical_ex, axisa=0, axisb=0).T

        #wavelength is in [mm]
        return RayBundle(o, k, E0, wave=0.00058756), px, py
예제 #3
0
파일: demo_spd.py 프로젝트: theinze/pyrate
    def meridional_bundle(fpy, nrays=16, rpup=5):
        """
        Creates a RayBundle

        * o is the origin - this is ok
        * k is the wave vector, i.e. direction; needs to be normalized
        * E0 is the polarization vector

        """

        pts_on_entrance_pupil = np.vstack((np.zeros([1,nrays]), \
                                           np.linspace(rpup,-rpup,nrays)[None,...], \
                                           np.ones([1,nrays]) * spd.psys.entpup) )

        o = np.concatenate([ np.zeros([1,nrays]), \
                            -fpy * spd.psys.field_size_obj() * np.ones([1,nrays]), \
                             spd.psys.obj_dist() * np.ones([1,nrays]) ], axis=0 )

        k = (pts_on_entrance_pupil - o)
        normk = np.sqrt([np.sum(k * k, axis=0)])
        k = k / (np.matmul(np.ones([3, 1]), normk))

        E0 = np.cross(k, canonical_ex, axisa=0, axisb=0).T

        #wavelength is in [mm]
        return RayBundle(o, k, E0, wave=0.00058756)
예제 #4
0
def generatebundle(openangle=0.01, numrays=11):

    o = np.zeros((3, numrays * numrays))
    k = np.zeros_like(o)

    angles = np.linspace(-openangle, openangle, num=numrays)
    #phi = np.linspace(0, 2.*math.pi, num=numrays)
    #theta = np.linspace(-openangle, openangle, num=numrays)
    #(PHI, THETA) = np.meshgrid(phi, theta)
    phiv = np.random.random(numrays * numrays) * 2. * np.pi  #PHI.flatten()
    thetav = (1. - 2. * np.random.random(numrays * numrays)
              ) * openangle  #THETA.flatten()

    k0 = 1.  #2.*math.pi/wavelength

    k[0, :] = np.cos(phiv) * np.sin(thetav)
    k[1, :] = np.sin(phiv) * np.sin(thetav)  #k0*np.sin(angles)
    k[2, :] = np.cos(thetav)  #k0*np.cos(angles)

    ey = np.zeros_like(o)
    ey[1, :] = 1.

    E0 = np.cross(k, ey, axisa=0, axisb=0).T

    return RayBundle(x0=o, k0=k, Efield0=E0, wave=wavelength)
예제 #5
0
def final_meritfunction(my_s, **kwargs):
    """
    Merit function (=function to be minimized) for step 3 and following.
    """
    merit = 0

    initialbundles = kwargs.get("initialbundles", None)
    fno = kwargs.get("fno", 0.0)

    for bundle in initialbundles:
        rpaths = my_s.seqtrace(bundle, seq)
        x = rpaths[0].raybundles[-1].x[-1, 0, :]
        rba.raybundle = rpaths[0].raybundles[-1]
        merit += rba.get_rms_spot_size_centroid()
        merit += 1./(len(x) + 1e-18)  # 10000.*math.exp(-len(x))

    # f number
    o = np.array([[0], [7.5], [0]])
    k = np.zeros_like(o)
    k[2, :] = 1
    E0 = np.cross(k, canonical_ex, axisa=0, axisb=0).T

    initial_marginal = RayBundle(o, k, E0, wave=dline)
    marginal_path = s.seqtrace(initial_marginal, seq)

    kyim = marginal_path[0].raybundles[-1].k[-1, 1, :]
    kzim = marginal_path[0].raybundles[-1].k[-1, 2, :]

    merit += 10 * sum(fno + .5 * np.real(kzim)/np.real(kyim))**2

    return merit
예제 #6
0
파일: aim.py 프로젝트: t4qjXH8N/pyrate
    def aim(self, delta_xy, fieldtype="angle"):
        """
        Generates bundles.
        """

        if fieldtype == "angle":
            (dr_obj, dk_obj) = self.aim_core_angle_known(delta_xy)
        elif fieldtype == "objectheight":
            (dr_obj, dk_obj) = self.aim_core_r_known(delta_xy)
        elif fieldtype == "kvector":
            # (dr_obj, dk_obj) = self.aim_core_k_known(delta_xy)
            raise NotImplementedError()
        else:
            raise NotImplementedError()

        (dim, num_points) = np.shape(dr_obj)

        dr_obj3d = np.vstack((dr_obj, np.zeros(num_points)))
        dk_obj3d = np.vstack((dk_obj, np.zeros(num_points)))

        xp_objsurf = self.objectsurface.rootcoordinatesystem.returnGlobalToLocalPoints(
            self.pilotbundle.x[0, :, 0])
        xp_objsurf = np.repeat(xp_objsurf[:, np.newaxis], num_points, axis=1)
        dx3d = np.dot(self.objectsurface.rootcoordinatesystem.localbasis.T,
                      dr_obj3d)
        xparabasal = xp_objsurf + dx3d

        kp_objsurf = self.objectsurface.rootcoordinatesystem.returnGlobalToLocalDirections(
            self.pilotbundle.k[0, :, 0])
        kp_objsurf = np.repeat(kp_objsurf[:, np.newaxis], num_points, axis=1)
        dk3d = np.dot(self.objectsurface.rootcoordinatesystem.localbasis.T,
                      dk_obj3d)
        # FIXME: k coordinate system for which dispersion relation is respected
        # modified k in general violates dispersion relation

        kparabasal = kp_objsurf + dk3d
        self.debug("E pilotbundle")
        self.debug(str(self.pilotbundle.Efield.shape))
        self.debug(str(self.pilotbundle.Efield))
        E_obj = self.pilotbundle.Efield[0, :, 0]
        self.debug("E_obj")
        self.debug(str(E_obj))
        Eparabasal = np.repeat(E_obj[:, np.newaxis], num_points, axis=1)
        self.debug(str(np.sum(kparabasal * Eparabasal, axis=0)))

        # FIXME: Efield introduces anisotropy in aiming through
        # rotationally symmetric system
        # since copy of Eparabasal is not in the right direction for the
        # dispersion relation (i.e. in isotropic media k perp E which is not
        # fulfilled); solution: use k, insert into propagator, calculate
        # E by (u, sigma, v) = np.linalg.svd(propagator) where E is
        # linearcombination of all u which belong to sigma = 0 values.
        # This is necessary to get the right ray direction also in isotropic
        # case

        # Aimy: returns only linearized results which are not exact
        return RayBundle(xparabasal, kparabasal, Eparabasal, wave=self.wave)
예제 #7
0
def test_arc_length():
    """
    TODO
    """
    k0 = np.zeros((3, 2))
    E0 = np.zeros((3, 2))
    raybundle = RayBundle(x0=np.array([[0, 0], [0, 0], [0, 0]]),
                          k0=k0, Efield0=E0)
    x1 = np.array([[1, 0], [0, 0], [0, 0]])
    x2 = np.array([[1, 1], [1, 1], [0, 0]])
    x3 = np.array([[0, 2], [1, 2], [0, 0]])
    x4 = np.array([[0, 3], [0, 3], [0, 0]])
    valid = np.ones_like([1, 1])
    raybundle.append(x1, k0, E0, valid)
    raybundle.append(x2, k0, E0, valid)
    raybundle.append(x3, k0, E0, valid)
    raybundle.append(x4, k0, E0, valid)
    arclen = RayBundleAnalysis(raybundle).getArcLength()
    assert np.allclose(arclen, np.array([4., 3*np.sqrt(2)]))
예제 #8
0
def meritfunctionrms(s):
    initialbundle = RayBundle(x0=o, k0=k, Efield0=E0, wave=wavelength)
    rpaths = s.seqtrace(initialbundle, sysseq)

    x = rpaths[0].raybundles[-1].x[-1, 0, :]
    y = rpaths[0].raybundles[-1].x[-1, 1, :]

    res = np.sum(x**2 + y**2) + 10. * math.exp(-len(x))

    return res
예제 #9
0
def test_centroid():
    """
    TODO
    """
    raybundle = RayBundle(x0=np.array([[1, 0, 0, 1, 2],
                                       [0, 1, 0, 1, 2],
                                       [0, 0, 1, 1, 2]]),
                          k0=np.zeros((3, 5)), Efield0=np.zeros((3, 5)))
    rayanalysis = RayBundleAnalysis(raybundle)
    centroid = rayanalysis.get_centroid_position()
    assert np.allclose(centroid, 4./5.)
예제 #10
0
def test_rmsspotsize():
    """
    TODO
    """
    raybundle = RayBundle(x0=np.array([[1, 0, 0, 1, 2],
                                       [0, 1, 0, 1, 2],
                                       [0, 0, 1, 1, 2]]),
                          k0=np.zeros((3, 5)), Efield0=np.zeros((3, 5)))
    rayanalysis = RayBundleAnalysis(raybundle)
    rmssize = rayanalysis.get_rms_spot_size(np.array([0, 0, 0]))
    assert np.isclose(rmssize, math.sqrt(18.0/4.0))
예제 #11
0
def meritfunctionrms(s):
    initialbundle_local = RayBundle(x0=o, k0=k, Efield0=E0, wave=wavelength)
    rpaths = s.seqtrace(initialbundle_local, sysseq)
    # other constructions lead to fill up of initial bundle with intersection values

    # for glassy asphere only one path necessary
    x = rpaths[0].raybundles[-1].x[-1, 0, :]
    y = rpaths[0].raybundles[-1].x[-1, 1, :]

    res = np.sum(x**2 + y**2)

    return res
예제 #12
0
def bundle_step1(nrays=100, rpup=7.5):
    """
    Creates an on-axis collimated RayBundle for step 1.
    """

    (px, py) = RectGrid().getGrid(nrays)
    o = np.vstack((rpup*px, rpup*py, np.zeros_like(px)))
    k = np.zeros_like(o)
    k[2, :] = 1.  # 2.*math.pi/wavelength
    E0 = np.cross(k, canonical_ex, axisa=0, axisb=0).T

    return RayBundle(o, k, E0, wave=dline)
예제 #13
0
def meritfunctionrms(my_s):
    """
    Merit function for tracing a raybundle through system and calculate
    rms spot radius without centroid subtraction. Punish low number of
    rays, too.
    """
    my_initialbundle = RayBundle(x0=o, k0=k, Efield0=E0, wave=wavelength)
    rpaths = my_s.seqtrace(my_initialbundle, sysseq)

    x = rpaths[0].raybundles[-1].x[-1, 0, :]
    y = rpaths[0].raybundles[-1].x[-1, 1, :]

    res = np.sum(x**2 + y**2) + 10.*math.exp(-len(x))

    return res
예제 #14
0
def test_direction_centroid():
    """
    TODO
    """
    k0 = np.zeros((3, 5))
    k0[2, :] = 1
    E0 = np.zeros((3, 5))
    E0[1, :] = 1.
    raybundle = RayBundle(x0=np.array([[1, 0, 0, 1, 2],
                                       [0, 1, 0, 1, 2],
                                       [0, 0, 1, 1, 2]]),
                          k0=k0, Efield0=E0)
    rayanalysis = RayBundleAnalysis(raybundle)
    centroiddir = rayanalysis.get_centroid_direction()
    assert np.allclose(centroiddir, np.array([0, 0, 1]))
예제 #15
0
def test_rms_angularsize():
    """
    TODO
    """
    k0 = np.zeros((3, 5))
    k0[2, :] = 1
    E0 = np.zeros((3, 5))
    E0[1, :] = 1.
    raybundle = RayBundle(x0=np.array([[1, 0, 0, 1, 2],
                                       [0, 1, 0, 1, 2],
                                       [0, 0, 1, 1, 2]]),
                          k0=k0, Efield0=E0)
    rayanalysis = RayBundleAnalysis(raybundle)
    angularsize = rayanalysis.get_rms_angluar_size(
        np.array([math.sin(1.*math.pi/180.0), 0, math.cos(1.*math.pi/180.0)]))
    assert np.isclose(angularsize, (1.*math.pi/180.0))
예제 #16
0
def meritfunctionrms(my_s):
    """
    Standard rms spot radius merit function without removing centroid.
    """
    initialbundle_local = RayBundle(x0=o, k0=k, Efield0=E0, wave=wavelength)
    rpaths = my_s.seqtrace(initialbundle_local, sysseq)
    # other constructions lead to fill up of initial bundle with intersection
    # values

    # for glassy asphere only one path necessary
    x = rpaths[0].raybundles[-1].x[-1, 0, :]
    y = rpaths[0].raybundles[-1].x[-1, 1, :]

    res = np.sum(x**2 + y**2)

    return res
예제 #17
0
def final_meritfunction(s, rpup, fno, maxfield_deg):
    """
    Merit function (=function to be minimized) for step 3 and following.
    """
    merit = 0

    initialbundles = bundles_step3(rpup=rpup, maxfield_deg=maxfield_deg)
    for (ind, b) in enumerate(initialbundles):
        rpaths = s.seqtrace(b, seq)
        x = rpaths[0].raybundles[-1].x[-1, 0, :]
        #y = rpaths[0].raybundles[-1].x[-1, 1, :]

        #x = x - np.sum(x) / ( float(len(x)) + 1E-200 )
        #y = y - np.sum(y) / ( float(len(y)) + 1E-200 )
        rba.raybundle = rpaths[0].raybundles[-1]
        merit += rba.getRMSspotSizeCentroid()  #np.sum(x**2 + y**2)
        # FIXME: somehow this former calculation leads not to a useful rms spot calculation and therefore
        # the decz variable is not changed; the rba.getRMS... function is slower but leads to a change in thickness
        merit += 1. / (len(x) + 1e-18)  #10000.*math.exp(-len(x))

    # biconvex lens with same radii
    merit += 10000* (  s.elements["stdelem"].surfaces["lens4front"].shape.curvature() \
                     + s.elements["stdelem"].surfaces["lens4rear"].shape.curvature()  )**2

    # outer radii of both doulets should be symmetric
    merit += 10000* (  s.elements["stdelem"].surfaces["elem2front"].shape.curvature() \
                     + s.elements["stdelem"].surfaces["elem3rear"].shape.curvature()  )**2

    # inner radii of both doulets should be symmetric
    merit += 10000* (  s.elements["stdelem"].surfaces["elem2rear"].shape.curvature() \
                     + s.elements["stdelem"].surfaces["elem3front"].shape.curvature()  )**2
    # f number
    o = np.array([[0], [7.5], [0]])
    k = np.zeros_like(o)
    k[2, :] = 1
    E0 = np.cross(k, canonical_ex, axisa=0, axisb=0).T

    initial_marginal = RayBundle(o, k, E0, wave=dline)
    marginal_path = s.seqtrace(initial_marginal, seq)

    kyim = marginal_path[0].raybundles[-1].k[-1, 1, :]
    kzim = marginal_path[0].raybundles[-1].k[-1, 2, :]

    merit += 10 * sum(fno + .5 * np.real(kzim) / np.real(kyim))**2

    return merit
예제 #18
0
    def aim(self, delta_xy, fieldtype="angle"):
        """
        Generates bundles.
        """

        if fieldtype == "angle":
            (dr_obj, dk_obj) = self.aim_core_angle_known(delta_xy)
        elif fieldtype == "objectheight":

            raise NotImplemented()

            #(dr_obj, dk_obj) = self.aim_core_r_known(delta_xy)
        elif fieldtype == "kvector":

            raise NotImplemented()

            #(dr_obj, dk_obj) = self.aim_core_k_known(delta_xy)

        (dim, num_points) = np.shape(dr_obj)

        dr_obj3d = np.vstack((dr_obj, np.zeros(num_points)))
        dk_obj3d = np.vstack((dk_obj, np.zeros(num_points)))

        xp_objsurf = self.objectsurface.rootcoordinatesystem.returnGlobalToLocalPoints(
            self.pilotbundle.x[0, :, 0])
        xp_objsurf = np.repeat(xp_objsurf[:, np.newaxis], num_points, axis=1)
        dx3d = np.dot(self.objectsurface.rootcoordinatesystem.localbasis.T,
                      dr_obj3d)
        xparabasal = xp_objsurf + dx3d

        kp_objsurf = self.objectsurface.rootcoordinatesystem.returnGlobalToLocalDirections(
            self.pilotbundle.k[0, :, 0])
        kp_objsurf = np.repeat(kp_objsurf[:, np.newaxis], num_points, axis=1)
        dk3d = np.dot(self.objectsurface.rootcoordinatesystem.localbasis.T,
                      dk_obj3d)
        # TODO: k coordinate system for which dispersion relation is respected

        kparabasal = kp_objsurf + dk3d
        E_obj = self.pilotbundle.Efield[0, :, 0]
        Eparabasal = np.repeat(E_obj[:, np.newaxis], num_points, axis=1)

        # Aimy: returns only linearized results which are not exact
        return RayBundle(xparabasal, kparabasal, Eparabasal, wave=self.wave)
예제 #19
0
def buildInitialbundle(osa, s, sysseq, rays_list, numrays, wavelength):
    '''
    Initialises the Initialbundles
    '''

    # We want to build a Matrix with the initialbundles as entrys
    # get size of Matrix
    p = len(wavelength)
    q = len(rays_list)
    # initialize Matrix
    initialbundle = [[0 for x in range(p)] for y in range(q)]
    r2 = []

    #Iterate over all entries
    counteri = 0
    counterj = 0
    for bundle in range(q):
        i = rays_list[bundle]["startx"]
        j = rays_list[bundle]["starty"]
        k = rays_list[bundle]["startz"]
        l = rays_list[bundle]["angley"]
        m = rays_list[bundle]["anglex"]
        n = rays_list[bundle]["radius"]
        counterj = 0
        #Setup dict for current Bundle
        bundle_dict = {
            "startx": i,
            "starty": j,
            "startz": k,
            "angley": l,
            "anglex": m,
            "radius": n,
            "rasterobj": rays_list[bundle]["raster"]
        }
        for o in wavelength:
            (o1, k1, E1) = osa.collimated_bundle(numrays, bundle_dict, wave=o)
            initialbundle[counteri][counterj] = \
                 RayBundle(x0=o1, k0=k1, Efield0=E1, wave=o)
            counterj = counterj + 1
        counteri = counteri + 1
    return initialbundle
예제 #20
0
def calculateRayPaths(os, bundleDict, bundlePropDict, sysseq):
    '''
    os: OpticalSystem
    bundleDict: all bundle data in a dictionary
    bundlePropDict: dictionary which contains all the bundle properties(o1,k1,E1)
                    from above
    sysseq: system sequence

    return are the x,y vectors which contain the (x,y)-coordinates from the 
    raytracer 
    '''
    x = np.array([])
    y = np.array([])

    for i in bundlePropDict.keys():
        bundle = RayBundle(x0=bundlePropDict[i][0],
                           k0=bundlePropDict[i][1],
                           Efield0=bundlePropDict[i][2],
                           wave=bundleDict[i][2])
        rpaths = os.seqtrace(bundle, sysseq)
        x = np.append(x, rpaths[0].raybundles[-1].x[-1, 0, :])
        y = np.append(y, rpaths[0].raybundles[-1].x[-1, 1, :])

    return x, y
예제 #21
0
def test_arc_length():
    """
    TODO
    """
    k0 = np.zeros((3, 2))
    E0 = np.zeros((3, 2))
    raybundle = RayBundle(x0=np.array([[0, 0], [0, 0], [0, 0]]),
                          k0=k0, Efield0=E0)
    x1 = np.array([[1, 0], [0, 0], [0, 0]])
    x2 = np.array([[1, 1], [1, 1], [0, 0]])
    x3 = np.array([[0, 2], [1, 2], [0, 0]])
    x4 = np.array([[0, 3], [0, 3], [0, 0]])
    valid = np.ones_like([1, 1])
    raybundle.append(x1, k0, E0, valid)
    raybundle.append(x2, k0, E0, valid)
    raybundle.append(x3, k0, E0, valid)
    raybundle.append(x4, k0, E0, valid)
    arclen = RayBundleAnalysis(raybundle).get_arc_length()
    assert np.allclose(arclen, np.array([4., 3*np.sqrt(2)]))
예제 #22
0
파일: aim.py 프로젝트: mniehus/pyrate
    def aim(self, delta_xy, fieldtype="angle"):
        """
        Generates bundles.
        """

        if fieldtype == "angle":
            (dr_obj, dk_obj) = self.aim_core_angle_known(delta_xy)
        elif fieldtype == "objectheight":
            (dr_obj, dk_obj) = self.aim_core_r_known(delta_xy)
        elif fieldtype == "kvector":
            # (dr_obj, dk_obj) = self.aim_core_k_known(delta_xy)
            raise NotImplementedError()
        else:
            raise NotImplementedError()

        (_, num_points) = np.shape(dr_obj)

        dr_obj3d = np.vstack((dr_obj, np.zeros(num_points)))
        dk_obj3d = np.vstack((dk_obj, np.zeros(num_points)))

        xp_objsurf = self.objectsurface.rootcoordinatesystem.\
            returnGlobalToLocalPoints(self.pilotbundle.x[0, :, 0])
        xp_objsurf = np.repeat(xp_objsurf[:, np.newaxis], num_points, axis=1)
        dx3d = np.dot(self.objectsurface.rootcoordinatesystem.localbasis.T,
                      dr_obj3d)
        xparabasal = xp_objsurf + dx3d

        kp_objsurf = self.objectsurface.rootcoordinatesystem.\
            returnGlobalToLocalDirections(self.pilotbundle.k[0, :, 0])
        kp_objsurf = np.repeat(kp_objsurf[:, np.newaxis], num_points, axis=1)
        dk3d = np.dot(self.objectsurface.rootcoordinatesystem.localbasis.T,
                      dk_obj3d)
        # FIXME: k coordinate system for which dispersion relation is respected
        # modified k in general violates dispersion relation

        kparabasal = kp_objsurf + dk3d
        efield_obj = self.pilotbundle.Efield[0, :, 0]
        efield_parabasal = np.repeat(efield_obj[:, np.newaxis],
                                     num_points,
                                     axis=1)

        # Eparabasal introduces anisotropy in aiming through
        # rotationally symmetric system since copy of Eparabasal (above)
        # is not in the right direction for the
        # dispersion relation (i.e. in isotropic media k perp E which is not
        # fulfilled); solution: use k, insert into propagator (svdmatrix),
        # calculate E by (u, sigma, v) = np.linalg.svd(propagator) where E is
        # some linearcombination of all u which belong to sigma = 0 values.
        # This is necessary to get the right ray direction also in isotropic
        # case
        # Outstanding problems:
        # * Only vacuum considered (attach to material!)
        #   [i.e. svdmatrix should come from material]
        # * Selection of E depends only on smallest eigenvalue
        #   (this is the "I don't care about polarization variant")
        #   => Later the user should choose the polarization in an stable
        #   reproducible way (i.e. sorting by scalar products)

        (_, nlength) = kparabasal.shape

        kronecker = np.repeat(np.identity(3)[np.newaxis, :, :],
                              nlength,
                              axis=0)

        svdmatrix = -kronecker * np.sum(kparabasal * kparabasal,
                                        axis=0)[:, np.newaxis, np.newaxis] +\
            np.einsum("i...,j...", kparabasal, kparabasal) +\
            kronecker  # epstensor

        # svdmatrix = -delta_ij (k*k) + k_i k_j + delta

        (unitary_arrays, singular_values, _) = np.linalg.svd(svdmatrix)

        smallest_absolute_values = np.argsort(np.abs(singular_values),
                                              axis=1).T[0]

        for i in range(nlength):
            efield_parabasal[:, i] =\
                unitary_arrays[i, :, smallest_absolute_values[i]]

        # Aimy: returns only linearized results which are not exact
        return RayBundle(xparabasal,
                         kparabasal,
                         efield_parabasal,
                         wave=self.wave)
예제 #23
0
rstobj = raster.MeridionalFan()
(px, py) = rstobj.getGrid(num_rays)

rpup = enpd*0.5 #7.5
o = np.vstack((rpup*px, rpup*py, -5.*np.ones_like(px)))

k = np.zeros_like(o)
k[1,:] = math.sin(0.0)
k[2,:] = math.cos(0.0)

ey = np.zeros_like(o)
ey[1,:] =  1.

E0 = np.cross(k, ey, axisa=0, axisb=0).T

initialbundle = RayBundle(x0=o, k0=k, Efield0=E0, wave=standard_wavelength)
rays = s.seqtrace(initialbundle, seq)




fig = plt.figure(1)
ax = fig.add_subplot(111)

ax.axis('equal')
if StrictVersion(matplotlib.__version__) < StrictVersion('2.0.0'):
    ax.set_axis_bgcolor('white')
else:
    ax.set_facecolor('white')

for r in rays:
예제 #24
0
#plt.subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0)
#plots.drawLayout2d(ax2, s, [r2, r3, r4])
#plt.subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0)
#plots.drawSpotDiagram(ax3, s, r3, -1)
#plt.subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0)

sysseq = [("lenssys", [("object", {}), ("surf1", {}), ("surf2", {}),
                       ("surf3", {}), ("surf4", {}), ("stop", {
                           "is_stop": True
                       }), ("surf6", {}), ("surf7", {}), ("image", {})])]

osa = OpticalSystemAnalysis(s, sysseq, name="Analysis")

divbundledict = {"radius": 10 * degree, "raster": RandomGrid()}
(o, k, E0) = osa.divergent_bundle(900, divbundledict, wave=wavelength)
initialbundle = RayBundle(x0=o, k0=k, Efield0=E0)
r2 = s.seqtrace(initialbundle, sysseq)

fig = plt.figure(1)
ax = fig.add_subplot(311)
ax2 = fig.add_subplot(312)
ax3 = fig.add_subplot(313)

ax.axis('equal')
ax2.axis('equal')
if StrictVersion(matplotlib.__version__) < StrictVersion('2.0.0'):
    ax.set_axis_bgcolor('white')
else:
    ax.set_facecolor('white')

phi = 0.  #math.pi/4
예제 #25
0
        return time.perf_counter()
    else:
        return time.clock()


nrays = 100000
nrays_draw = 21

osa = OpticalSystemAnalysis(s, seq, name="Analysis")

(x0, k0, E0) = osa.divergent_bundle(nrays, {
    "radius": 10. * degree,
    "raster": raster.RectGrid()
})
t0 = mytiming()
initialraybundle = RayBundle(x0=x0, k0=k0, Efield0=E0)
t1 = mytiming()
raypath = s.seqtrace(initialraybundle, seq)
t2 = mytiming()
logging.info("benchmark : " + str(t2 - t1) + " s for tracing " + str(nrays) +
             " rays through " + str(len(s.elements["stdelem"].surfaces) - 1) +
             " surfaces.")
logging.info("That is " + str(
    int(round(nrays * (len(s.elements["stdelem"].surfaces) - 1) /
              (t2 - t1)))) + " ray-surface-operations per second")

# plot

(x0_draw, k0_draw, E0_draw) =\
    osa.divergent_bundle(nrays_draw,
                         {"radius": 10.*degree,
예제 #26
0
# plt.subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0)
# plots.drawLayout2d(ax2, s, [r2, r3, r4])
# plt.subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0)
# plots.draw_spotdiagram(ax3, s, r3, -1)
# plt.subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0)

sysseq = [("lenssys", [("object", {}), ("surf1", {}), ("surf2", {}),
                       ("surf3", {}), ("surf4", {}), ("stop", {
                           "is_stop": True
                       }), ("surf6", {}), ("surf7", {}), ("image", {})])]

osa = OpticalSystemAnalysis(s, sysseq, name="Analysis")

divbundledict = {"radius": 10 * degree, "raster": RandomGrid()}
(o, k, E0) = osa.divergent_bundle(900, divbundledict, wave=wavelength)
initialbundle = RayBundle(x0=o, k0=k, Efield0=E0)
r2 = s.seqtrace(initialbundle, sysseq)

fig = plt.figure(1)
ax = fig.add_subplot(311)
ax2 = fig.add_subplot(312)
ax3 = fig.add_subplot(313)

ax.axis('equal')
ax2.axis('equal')
if StrictVersion(matplotlib.__version__) < StrictVersion('2.0.0'):
    ax.set_axis_bgcolor('white')
else:
    ax.set_facecolor('white')

phi = 0.  # math.pi/4
예제 #27
0
},
                                    wave=standard_wavelength)
(o, k2, E2) = osa.collimated_bundle(3, {
    "radius": 2,
    "raster": raster.MeridionalFan(),
    "anglex": 15 * degree
},
                                    wave=standard_wavelength)
(o, k3, E3) = osa.collimated_bundle(3, {
    "radius": 2,
    "raster": raster.MeridionalFan(),
    "anglex": -15 * degree
},
                                    wave=standard_wavelength)

initialbundle1 = RayBundle(x0=o, k0=k1, Efield0=E1, wave=standard_wavelength)
initialbundle2 = RayBundle(x0=o, k0=k2, Efield0=E2, wave=standard_wavelength)
initialbundle3 = RayBundle(x0=o, k0=k3, Efield0=E3, wave=standard_wavelength)
print("performing sequential raytrace")
r1 = s.seqtrace(initialbundle1, sysseq)
r2 = s.seqtrace(initialbundle2, sysseq)
r3 = s.seqtrace(initialbundle3, sysseq)

obj_dx = 0.1
obj_dphi = 5 * degree

print("calculating pilotbundles")
pilotbundles = build_pilotbundle_complex(objsurf,
                                         air, (obj_dx, obj_dx),
                                         (obj_dphi, obj_dphi),
                                         num_sampling_points=3)
예제 #28
0
imsurf = s.elements["stdelem"].surfaces["image"]
imsurf.rootcoordinatesystem.tiltx.setvalue(alpha)
imsurf.rootcoordinatesystem.update()
objsurf = s.elements["stdelem"].surfaces["object"]
osa = OpticalSystemAnalysis(s, seq, name="Analysis")
(x01, k01, E01) = osa.collimated_bundle(11, {
    "radius": epd,
    "raster": MeridionalFan()
})
(x02, k02, E02) = osa.collimated_bundle(11, {
    "radius": epd,
    "raster": MeridionalFan(),
    "anglex": 1. * degree
})
mybundle1 = RayBundle(x01, k01, E01)
mybundle2 = RayBundle(x02, k02, E02)

raypaths1 = s.seqtrace(mybundle1, seq)
raypaths2 = s.seqtrace(mybundle2, seq)

obj_dx = 0.1
obj_dphi = 0.1 * degree

pilotbundles = build_pilotbundle_complex(objsurf,
                                         s.material_background,
                                         (obj_dx, obj_dx),
                                         (obj_dphi, obj_dphi),
                                         num_sampling_points=3)
(m_obj_stop, m_stop_img) = s.extractXYUV(pilotbundles[-1], seq)
예제 #29
0
(x01, k01, E01) = osa.collimated_bundle(11, {
    "radius": epd,
    "raster": MeridionalFan()
})
(x02, k02, E02) = osa.collimated_bundle(11, {
    "radius": epd,
    "raster": MeridionalFan(),
    "anglex": 1. * degree
})
(x03, k03, E03) = osa.collimated_bundle(11, {
    "radius": epd,
    "raster": MeridionalFan(),
    "anglex": -1. * degree
})

mybundle1 = RayBundle(x01, k01, E01)
mybundle2 = RayBundle(x02, k02, E02)
mybundle3 = RayBundle(x03, k03, E03)

raypaths1 = s.seqtrace(mybundle1, seq)
raypaths2 = s.seqtrace(mybundle2, seq)
raypaths3 = s.seqtrace(mybundle3, seq)

obj_dx = 0.1
obj_dphi = 0.1 * degree

pilotbundles = build_pilotbundle_complex(objsurf,
                                         s.material_background,
                                         (obj_dx, obj_dx),
                                         (obj_dphi, obj_dphi),
                                         num_sampling_points=3)
예제 #30
0
ey = np.zeros_like(o)
ey[1,:] =  1.

E0_red = np.cross(k_red, ey, axisa=0, axisb=0).T
E0_blue = np.cross(k_blue, ey, axisa=0, axisb=0).T

sysseq = [("prism", 
               [("stop", {"is_stop":True}), 
                ("surf1", {}), 
                ("surf2", {}), 
                ("image", {})])]

phi = 5.*math.pi/180.0

initialbundle_red = RayBundle(x0=o, k0=k_red, Efield0=E0_red, wave=wave_red)
initialbundle_blue = RayBundle(x0=o, k0=k_blue, Efield0=E0_blue, wave=wave_blue)
r_red = s.seqtrace(initialbundle_red, sysseq)
r_blue = s.seqtrace(initialbundle_blue, sysseq)

fig = plt.figure(1)
ax = fig.add_subplot(111)

ax.axis('equal')
if StrictVersion(matplotlib.__version__) < StrictVersion('2.0.0'):
    ax.set_axis_bgcolor('white')
else:
    ax.set_facecolor('white')

phi = 0.#math.pi/4
pn = np.array([math.cos(phi), 0, math.sin(phi)]) # canonical_ex