def main():
    layout = pya.Layout()
    dbu = layout.dbu = 0.001
    TOP = layout.create_cell("TOP")

    origin = pya.DPoint(0, 0)
    ex = pya.DVector(1, 0)
    ey = pya.DVector(0, 1)

    MZI_Broadband_DC("MZI1x2").place_cell(TOP, origin)

    # from ebeam_pdk import layout_ebeam_waveguide_from_points

    # points_list = [origin, origin + 20 * ex, origin + 20 * ex + 40 * ey]
    # layout_ebeam_waveguide_from_points(TOP, points_list)

    print("Wrote to example_mask.gds")
    layout.write("example_mask.gds")
Example #2
0
 def __setstate__(self, state):
     self.name = state['name']
     x, y = state['position']
     self.position = pya.DPoint(x, y)
     direction = state['direction']
     if isinstance(direction, tuple):
         x, y = direction
         self.direction = pya.DVector(x, y)
     else:
         self.direction = direction
     self.width = state['width']
Example #3
0
    def test_4_Trans(self):

        a = pya.Trans()
        m = pya.CplxTrans(a, 1.1)
        da = pya.DTrans()
        dm = pya.DCplxTrans(da, 1.1)

        self.assertEqual(str(m), "r0 *1.1 0,0")
        self.assertEqual(str(pya.DCplxTrans.from_s(str(m))), str(m))
        self.assertEqual(str(m.trans(pya.Point(5, -7))), "5.5,-7.7")

        im = pya.ICplxTrans(a, 0.5)
        im_old = im.dup()

        self.assertEqual(str(im), "r0 *0.5 0,0")
        self.assertEqual(str(pya.ICplxTrans.from_s(str(im))), str(im))
        self.assertEqual(str(im.trans(pya.Point(5, -7))), "3,-4")

        im = pya.ICplxTrans(m)
        self.assertEqual(str(im), "r0 *1.1 0,0")
        self.assertEqual(str(im.trans(pya.Point(5, -7))), "6,-8")

        im = pya.ICplxTrans(dm)
        self.assertEqual(str(im), "r0 *1.1 0,0")
        self.assertEqual(str(im.trans(pya.Point(5, -7))), "6,-8")

        im.assign(im_old)
        self.assertEqual(str(im), "r0 *0.5 0,0")
        self.assertEqual(str(im.trans(pya.Point(5, -7))), "3,-4")

        self.assertEqual(str(pya.ICplxTrans(5, -7)), "r0 *1 5,-7")

        self.assertEqual(str(pya.ICplxTrans(pya.ICplxTrans.R180, 1.5, 5, -7)),
                         "r180 *1.5 5,-7")
        self.assertEqual(
            str(pya.ICplxTrans(pya.ICplxTrans.R180, 1.5, pya.Point(5, -7))),
            "r180 *1.5 5,-7")
        self.assertEqual(
            str(pya.ICplxTrans(pya.ICplxTrans.R180, 1.5, pya.Vector(5, -7))),
            "r180 *1.5 5,-7")
        self.assertEqual(
            str(pya.ICplxTrans(pya.ICplxTrans.R180, 1.5, pya.DVector(5, -7))),
            "r180 *1.5 5,-7")
        self.assertEqual(str(pya.ICplxTrans(pya.ICplxTrans.R180, 1.5)),
                         "r180 *1.5 0,0")

        c = pya.ICplxTrans.from_dtrans(pya.DCplxTrans.M135)
        self.assertEqual(str(c), "m135 *1 0,0")
        c = pya.ICplxTrans.from_trans(pya.CplxTrans.M135)
        self.assertEqual(str(c), "m135 *1 0,0")
Example #4
0
def place_cell(parent_cell, pcell, ports_dict, placement_origin, relative_to=None, transform_into=False):
    """ Places an pya cell and return ports with updated positions
    Args:
        parent_cell: cell to place into
        pcell, ports_dict: result of KLayoutPCell.pcell call
        placement_origin: pya.Point object to be used as origin
        relative_to: port name
            the cell is placed so that the port is located at placement_origin
        transform_into:
            if used with relative_into, transform the cell's coordinate system
            so that its origin is in the given port.

    Returns:
        ports(dict): key:port.name, value: geometry.Port with positions relative to parent_cell's origin
    """
    offset = pya.DVector(0, 0)
    port_offset = placement_origin
    if relative_to is not None:
        offset = ports_dict[relative_to].position
        port_offset = placement_origin - offset
        if transform_into:
            # print(type(pcell))
            offset_transform = pya.DTrans(pya.DTrans.R0, -offset)
            for instance in pcell.each_inst():
                instance.transform(offset_transform)
            pcell.transform_into(offset_transform)
        else:
            placement_origin = placement_origin - offset

    transformation = pya.DTrans(pya.Trans.R0, placement_origin)
    instance = pya.DCellInstArray(pcell.cell_index(), transformation)
    parent_cell.insert(instance)
    for port in ports_dict.values():
        port.position += port_offset

    return ports_dict
Example #5
0
import pya
from math import pi
from siepic_tools.utils.geometry import rotate, rotate90

EX = pya.DVector(1, 0)


class objectview(object):
    """ Basically allows us to access dictionary values as dict.x
        rather than dict['x']
    """

    def __init__(self, d):
        self.__dict__ = d


def place_cell(parent_cell, pcell, ports_dict, placement_origin, relative_to=None, transform_into=False):
    """ Places an pya cell and return ports with updated positions
    Args:
        parent_cell: cell to place into
        pcell, ports_dict: result of KLayoutPCell.pcell call
        placement_origin: pya.Point object to be used as origin
        relative_to: port name
            the cell is placed so that the port is located at placement_origin
        transform_into:
            if used with relative_into, transform the cell's coordinate system
            so that its origin is in the given port.

    Returns:
        ports(dict): key:port.name, value: geometry.Port with positions relative to parent_cell's origin
    """
Example #6
0
    def test_1_DTrans(self):

        a = pya.DTrans()
        b = pya.DTrans(pya.DTrans.M135, pya.DPoint(17, 5))
        c = pya.DTrans(3, True, pya.DPoint(17, 5))
        d = pya.DTrans(pya.DPoint(17, 5))
        e = pya.DTrans(pya.DTrans.M135)
        e2 = pya.DTrans.from_itrans(pya.Trans.M135)
        f = pya.DTrans(pya.Trans(pya.Trans.M135, pya.Point(17, 5)))

        self.assertEqual(str(a), "r0 0,0")
        self.assertEqual(str(pya.DTrans.from_s(str(a))), str(a))
        self.assertEqual(str(b), "m135 17,5")
        self.assertEqual(str(c), "m135 17,5")
        self.assertEqual(str(d), "r0 17,5")
        self.assertEqual(str(e), "m135 0,0")
        self.assertEqual(str(e2), "m135 0,0")
        self.assertEqual(str(f), "m135 17,5")
        self.assertEqual(str(pya.DTrans.from_s(str(f))), str(f))

        self.assertEqual(str(b.trans(pya.DPoint(1, 0))), "17,4")

        self.assertEqual(a == b, False)
        self.assertEqual(a == a, True)
        self.assertEqual(a != b, True)
        self.assertEqual(a != a, False)
        self.assertEqual((d * e) == b, True)
        self.assertEqual((e * d) == b, False)

        i = c.inverted()

        self.assertEqual(str(i), "m135 5,17")
        self.assertEqual((i * b) == a, True)
        self.assertEqual((b * i) == a, True)

        c = pya.DTrans(3, True, pya.DPoint(17, 5))
        self.assertEqual(str(c), "m135 17,5")
        c.disp = pya.DPoint(1, 7)
        self.assertEqual(str(c), "m135 1,7")
        c.angle = 1
        self.assertEqual(str(c), "m45 1,7")
        c.rot = 3
        self.assertEqual(str(c), "r270 1,7")
        c.mirror = True
        self.assertEqual(str(c), "m135 1,7")

        self.assertEqual(str(pya.Trans(pya.Trans.R180, 5, -7)), "r180 5,-7")
        self.assertEqual(str(pya.Trans(pya.Trans.R180, pya.Point(5, -7))),
                         "r180 5,-7")
        self.assertEqual(str(pya.Trans(pya.Trans.R180, pya.Vector(5, -7))),
                         "r180 5,-7")
        self.assertEqual(str(pya.Trans(pya.Trans.R180, pya.DVector(5, -7))),
                         "r180 5,-7")
        self.assertEqual(str(pya.Trans(pya.Trans.R180)), "r180 0,0")

        self.assertEqual(str(e.trans(pya.Edge(0, 1, 2, 3))), "(-3,-2;-1,0)")
        self.assertEqual(str((e * pya.Edge(0, 1, 2, 3))), "(-3,-2;-1,0)")
        self.assertEqual(str(e.trans(pya.Box(0, 1, 2, 3))), "(-3,-2;-1,0)")
        self.assertEqual(str((e * pya.Box(0, 1, 2, 3))), "(-3,-2;-1,0)")
        self.assertEqual(str(e.trans(pya.Text("text", pya.Vector(0, 1)))),
                         "('text',m135 -1,0)")
        self.assertEqual(str((e * pya.Text("text", pya.Vector(0, 1)))),
                         "('text',m135 -1,0)")
        self.assertEqual(
            str(
                e.trans(
                    pya.Polygon(
                        [pya.Point(0, 1),
                         pya.Point(2, -3),
                         pya.Point(4, 5)]))), "(-5,-4;-1,0;3,-2)")
        self.assertEqual(
            str((e * pya.Polygon(
                [pya.Point(0, 1),
                 pya.Point(2, -3),
                 pya.Point(4, 5)]))), "(-5,-4;-1,0;3,-2)")
        self.assertEqual(
            str(e.trans(pya.Path(
                [pya.Point(0, 1), pya.Point(2, 3)], 10))),
            "(-1,0;-3,-2) w=10 bx=0 ex=0 r=false")
        self.assertEqual(
            str((e *
                 pya.Path([pya.Point(0, 1), pya.Point(2, 3)], 10))),
            "(-1,0;-3,-2) w=10 bx=0 ex=0 r=false")

        # Constructor variations
        self.assertEqual(str(pya.Trans()), "r0 0,0")
        self.assertEqual(str(pya.Trans(1)), "r90 0,0")
        self.assertEqual(str(pya.Trans(2, True)), "m90 0,0")
        self.assertEqual(str(pya.Trans(2, True, pya.Vector(100, 200))),
                         "m90 100,200")
        self.assertEqual(str(pya.Trans(2, True, 100, 200)), "m90 100,200")
        self.assertEqual(str(pya.Trans(pya.Vector(100, 200))), "r0 100,200")
        self.assertEqual(str(pya.Trans(100, 200)), "r0 100,200")
        self.assertEqual(str(pya.Trans(pya.Trans(100, 200), 10, 20)),
                         "r0 110,220")
        self.assertEqual(
            str(pya.Trans(pya.Trans(100, 200), pya.Vector(10, 20))),
            "r0 110,220")

        self.assertEqual(str(pya.DTrans()), "r0 0,0")
        self.assertEqual(str(pya.DTrans(1)), "r90 0,0")
        self.assertEqual(str(pya.DTrans(2, True)), "m90 0,0")
        self.assertEqual(str(pya.DTrans(2, True, pya.DVector(0.1, 0.2))),
                         "m90 0.1,0.2")
        self.assertEqual(str(pya.DTrans(2, True, 0.1, 0.2)), "m90 0.1,0.2")
        self.assertEqual(str(pya.DTrans(pya.DVector(0.1, 0.2))), "r0 0.1,0.2")
        self.assertEqual(str(pya.DTrans(0.1, 0.2)), "r0 0.1,0.2")
        self.assertEqual(str(pya.DTrans(pya.DTrans(0.1, 0.2), 0.01, 0.02)),
                         "r0 0.11,0.22")
        self.assertEqual(
            str(pya.DTrans(pya.DTrans(0.1, 0.2), pya.DVector(0.01, 0.02))),
            "r0 0.11,0.22")
Example #7
0
    def test_3_DTrans(self):

        c = pya.DCplxTrans(5.0, -7.0)
        self.assertEqual(str(c), "r0 *1 5,-7")

        c = pya.DCplxTrans(pya.DCplxTrans.M135)
        self.assertEqual(str(c), "m135 *1 0,0")
        self.assertEqual(c.is_unity(), False)
        self.assertEqual(c.is_ortho(), True)
        self.assertEqual(c.is_mag(), False)
        self.assertEqual(c.is_mirror(), True)
        self.assertEqual(c.rot(), pya.DCplxTrans.M135.rot())
        self.assertEqual(str(c.s_trans()), "m135 0,0")
        self.assertAlmostEqual(c.angle, 270)

        self.assertEqual(str(c.trans(pya.DEdge(0, 1, 2, 3))), "(-3,-2;-1,0)")
        self.assertEqual(str((c * pya.DEdge(0, 1, 2, 3))), "(-3,-2;-1,0)")
        self.assertEqual(str(c.trans(pya.DBox(0, 1, 2, 3))), "(-3,-2;-1,0)")
        self.assertEqual(str((c * pya.DBox(0, 1, 2, 3))), "(-3,-2;-1,0)")
        self.assertEqual(str(c.trans(pya.DText("text", pya.DVector(0, 1)))),
                         "('text',m135 -1,0)")
        self.assertEqual(str((c * pya.DText("text", pya.DVector(0, 1)))),
                         "('text',m135 -1,0)")
        self.assertEqual(
            str(
                c.trans(
                    pya.DPolygon([
                        pya.DPoint(0, 1),
                        pya.DPoint(2, -3),
                        pya.DPoint(4, 5)
                    ]))), "(-5,-4;-1,0;3,-2)")
        self.assertEqual(
            str((c * pya.DPolygon(
                [pya.DPoint(0, 1),
                 pya.DPoint(2, -3),
                 pya.DPoint(4, 5)]))), "(-5,-4;-1,0;3,-2)")
        self.assertEqual(
            str(c.trans(pya.DPath(
                [pya.DPoint(0, 1), pya.DPoint(2, 3)], 10))),
            "(-1,0;-3,-2) w=10 bx=0 ex=0 r=false")
        self.assertEqual(
            str((c * pya.DPath(
                [pya.DPoint(0, 1), pya.DPoint(2, 3)], 10))),
            "(-1,0;-3,-2) w=10 bx=0 ex=0 r=false")

        c = pya.DCplxTrans.from_itrans(pya.CplxTrans.M135)
        self.assertEqual(str(c), "m135 *1 0,0")

        c = pya.DCplxTrans(1.5)
        self.assertEqual(str(c), "r0 *1.5 0,0")
        self.assertEqual(c.is_unity(), False)
        self.assertEqual(c.is_ortho(), True)
        self.assertEqual(c.is_mag(), True)
        self.assertEqual(c.is_mirror(), False)
        self.assertEqual(c.rot(), pya.DCplxTrans.R0.rot())
        self.assertEqual(str(c.s_trans()), "r0 0,0")
        self.assertAlmostEqual(c.angle, 0)

        c = pya.DCplxTrans(0.75, 45, True, 2.5, -12.5)
        self.assertEqual(str(c), "m22.5 *0.75 2.5,-12.5")
        c = pya.DCplxTrans(0.75, 45, True, pya.DPoint(2.5, -12.5))
        self.assertEqual(str(c), "m22.5 *0.75 2.5,-12.5")
        self.assertEqual(c.is_unity(), False)
        self.assertEqual(c.is_ortho(), False)
        self.assertEqual(c.is_mag(), True)
        self.assertEqual(c.rot(), pya.DCplxTrans.M0.rot())
        self.assertEqual(str(c.s_trans()), "m0 2.5,-12.5")
        self.assertAlmostEqual(c.angle, 45)

        self.assertEqual(str(c.ctrans(5)), "3.75")
        self.assertEqual(str(c.trans(pya.DPoint(12, 16))),
                         "17.3492424049,-14.6213203436")

        self.assertEqual(str(pya.DCplxTrans()), "r0 *1 0,0")
        self.assertEqual(pya.DCplxTrans().is_unity(), True)
        self.assertEqual((c * c.inverted()).is_unity(), True)

        c.mirror = False
        self.assertEqual(str(c), "r45 *0.75 2.5,-12.5")
        c.mag = 1.5
        self.assertEqual(str(c), "r45 *1.5 2.5,-12.5")
        c.disp = pya.DPoint(-1.0, 5.5)
        self.assertEqual(str(c), "r45 *1.5 -1,5.5")
        self.assertEqual(c.mag, 1.5)
        c.angle = 60
        self.assertEqual(str(c), "r60 *1.5 -1,5.5")
        self.assertEqual(("%g" % c.angle), "60")

        # Constructor variations
        self.assertEqual(str(pya.ICplxTrans()), "r0 *1 0,0")
        self.assertEqual(str(pya.ICplxTrans(1.5)), "r0 *1.5 0,0")
        self.assertEqual(str(pya.ICplxTrans(pya.Trans(1, False, 10, 20), 1.5)),
                         "r90 *1.5 10,20")
        self.assertEqual(str(pya.ICplxTrans(pya.Trans(1, False, 10, 20))),
                         "r90 *1 10,20")
        self.assertEqual(
            str(pya.ICplxTrans(1.5, 80, True, pya.Vector(100, 200))),
            "m40 *1.5 100,200")
        self.assertEqual(str(pya.ICplxTrans(1.5, 80, True, 100, 200)),
                         "m40 *1.5 100,200")
        self.assertEqual(str(pya.ICplxTrans(pya.Vector(100, 200))),
                         "r0 *1 100,200")
        self.assertEqual(str(pya.ICplxTrans(100, 200)), "r0 *1 100,200")
        self.assertEqual(str(pya.ICplxTrans(pya.ICplxTrans(100, 200))),
                         "r0 *1 100,200")
        self.assertEqual(str(pya.ICplxTrans(pya.ICplxTrans(100, 200), 1.5)),
                         "r0 *1.5 150,300")
        self.assertEqual(
            str(
                pya.ICplxTrans(pya.ICplxTrans(100, 200), 1.5,
                               pya.Vector(10, 20))), "r0 *1.5 160,320")
        self.assertEqual(
            str(pya.ICplxTrans(pya.ICplxTrans(100, 200), 1.5, 10, 20)),
            "r0 *1.5 160,320")

        self.assertEqual(str(pya.DCplxTrans()), "r0 *1 0,0")
        self.assertEqual(str(pya.DCplxTrans(1.5)), "r0 *1.5 0,0")
        self.assertEqual(
            str(pya.DCplxTrans(pya.DTrans(1, False, 0.01, 0.02), 1.5)),
            "r90 *1.5 0.01,0.02")
        self.assertEqual(str(pya.DCplxTrans(pya.DTrans(1, False, 0.01, 0.02))),
                         "r90 *1 0.01,0.02")
        self.assertEqual(
            str(pya.DCplxTrans(1.5, 80, True, pya.DVector(0.1, 0.2))),
            "m40 *1.5 0.1,0.2")
        self.assertEqual(str(pya.DCplxTrans(1.5, 80, True, 0.1, 0.2)),
                         "m40 *1.5 0.1,0.2")
        self.assertEqual(str(pya.DCplxTrans(pya.DVector(0.1, 0.2))),
                         "r0 *1 0.1,0.2")
        self.assertEqual(str(pya.DCplxTrans(0.1, 0.2)), "r0 *1 0.1,0.2")
        self.assertEqual(str(pya.DCplxTrans(pya.DCplxTrans(0.1, 0.2))),
                         "r0 *1 0.1,0.2")
        self.assertEqual(str(pya.DCplxTrans(pya.DCplxTrans(0.1, 0.2), 1.5)),
                         "r0 *1.5 0.15,0.3")
        self.assertEqual(
            str(
                pya.DCplxTrans(pya.DCplxTrans(0.1, 0.2), 1.5,
                               pya.DVector(0.01, 0.02))), "r0 *1.5 0.16,0.32")
        self.assertEqual(
            str(pya.DCplxTrans(pya.DCplxTrans(0.1, 0.2), 1.5, 0.01, 0.02)),
            "r0 *1.5 0.16,0.32")
Example #8
0
gdsname = os.path.realpath('box.gds')

# Create and place a rectangle
box = pya.DBox(pya.DPoint(0, 0), pya.DPoint(20, 20))
TOP.shapes(l1).insert(box)

# Write and tell Klayout GUI to open the file
layout.write(gdsname)
ipc.load(gdsname)


### Using python debugger and quick plot function ###

from lyipc import kqp

origin = pya.DPoint(0, 0)
turn = 0
for i in range(19):
    if i == 5:
        import pdb; pdb.set_trace()
        # Path 1: let the debugger continue
        # Path 2: execute "turn = 20" in debugger, then continue

    width = 40 - 2 * i
    box2 = pya.DBox(0, 0, width, width)
    box2 = box2.move(pya.DVector(origin))
    TOP.shapes(l1).insert(box2)
    origin = box2.p2 + pya.DVector(-turn, 0)

    kqp(layout, fresh=True)
Example #9
0
horizontal = np.concatenate((
  np.array([0, 4, 4]),
  np.full(6, 4)))   # Pad to total length 9 with 4's

vertical = np.concatenate((
  np.array([16, 20, 20]),
  np.full(6, 20)))  # Pad to total length 9 with 20's

# Generate the spiral and instantiate its cell
paths.delay_spiral_geo(layout, rib, sp, 
  turns=4, 
  spacing=2.5, 
  vertical=vertical,
  horizontal=horizontal,
  horizontal_mode='symmetric',
  vertical_mode='symmetric',
  quad_shift=0,
  start_turn=1, 
  start_angle=0, 
  end_angle=0,
  radial_shift=4.80, 
  n_pts=5000)
  
top.insert(pya.DCellInstArray(
  sp.cell_index(),
  pya.DTrans(pya.DVector(0, 30))
))


layout.write(my_constants.gds_models_path + 'test_spiral.gds')
Example #10
0
    def produce_impl(self):
        #Calculate layout database unit
        #dbu = self.layout.dbu
        dbu = 1
        size = []
        if len(self.size) < 2:
            if self.debug:
                print("Size < 2 dimension")
            if len(self.size) == 0:
                if self.debug:
                    print(
                        "paramter size has been adjusted to default - invalid data have provided"
                    )
                size = [100.0, 100.0]
            else:
                if self.debug:
                    print("Size has been adjusted to {}:{}".format(
                        self.size[0] / dbu, self.size[0] / dbu))
                size.append(float(self.size[0]) / dbu)
                size.append(float(self.size[0]) / dbu)
        else:
            size.append(float(self.size[0]) / dbu)
            size.append(float(self.size[1]) / dbu)

        ovSize = []
        if len(self.ovsize) < 2:
            if self.debug:
                print("overal size < 2 dimension")
            if len(self.ovsize) == 0:
                if self.debug:
                    print(
                        "paramter size has been adjusted to default - invalid data have provided"
                    )
                ovSize = [100.0, 100.0]
            else:
                ovSize.append(float(self.ovsize[0]) / dbu)
                ovSize.append(float(self.ovsize[0]) / dbu)
        else:
            ovSize.append(float(self.ovsize[0]) / dbu)
            ovSize.append(float(self.ovsize[1]) / dbu)

        armLenght = self.armLenght / dbu
        armWidth = self.armWidth / dbu
        activeArea = [size[0] - self.actOffset, size[1] - self.actOffset]
        woW = self.woW / dbu
        woOP = self.woOP / dbu

        # Membrane Geometry:

        ## arm location on a rectangle = edgeArmOffset
        edgeArmOffset = armWidth / 2 * math.sqrt(2)

        if self.debug:
            print("Size 0:{:.3f}, {}, {}".format(size[0], armLenght, armWidth))
        ## arm starts at following points
        pointArmA = pya.DPoint(size[0] / 2 - edgeArmOffset, size[1] / 2)
        pointArmD = pya.DPoint(size[0] / 2, size[1] / 2 - edgeArmOffset)

        ## arm ends in the point P - might be usefull as a connector point
        pointP = pya.DPoint(size[0] / 2 + armLenght / math.sqrt(2),
                            size[1] / 2 + armLenght / math.sqrt(2))

        ## arm edge points offsets from the center point P
        armEndPointoffset = armWidth / 2 / math.sqrt(2)

        ## Arm edge points in relation to the P point

        pointArmB = pya.DPoint(pointP.x - armEndPointoffset,
                               pointP.y + armEndPointoffset)
        pointArmC = pya.DPoint(pointP.x + armEndPointoffset,
                               pointP.y - armEndPointoffset)

        ## Lets Try to assemble the membrane as 1/4

        polyPoints = []
        polyPoints.append(pya.DPoint(0.0, 0.0))
        polyPoints.append(pya.DPoint(0.0, size[1] / 2))
        polyPoints.append(pointArmA)
        polyPoints.append(pointArmB)
        polyPoints.append(pointArmC)
        polyPoints.append(pointArmD)
        polyPoints.append(pya.DPoint(size[0] / 2, 0.0))

        #Lets put it there
        shapeSet = []

        Poly = pya.DPolygon(polyPoints)
        shapeSet.append(Poly)

        t = pya.DCplxTrans(1.0, 180, False, 0.0, 0.0)
        Poly1 = pya.DPolygon(polyPoints)
        Poly1.transform(t)
        shapeSet.append(Poly1)

        t = pya.DCplxTrans(1.0, 0, True, 0.0, 0.0)
        Poly2 = pya.DPolygon(polyPoints)
        Poly2.transform(t)
        shapeSet.append(Poly2)

        t = pya.DCplxTrans(1.0, 180, True, 0.0, 0.0)
        Poly3 = pya.DPolygon(polyPoints)
        Poly3.transform(t)
        shapeSet.append(Poly3)

        tr = pya.DCplxTrans(1000.0)
        region = pya.Region(shapeSet)
        region.merge()
        region.transform(tr)

        self.cell.shapes(self.l_layer).insert(region)

        #Active Area
        if self.showAct:
            actBox = pya.DBox(-activeArea[0] / 2, -activeArea[1] / 2,
                              activeArea[0] / 2, activeArea[1] / 2)
            self.cell.shapes(self.la_layer).insert(actBox)

        # Etch area - a rectangele limited by the membrane shape and P point
        etchBox = pya.DBox(-pointP.x, -pointP.y, pointP.x, pointP.y)
        etchRegion = pya.Region(etchBox)
        etchRegion.transform(tr)
        tempRegion = region ^ etchRegion
        etchRegion = tempRegion & etchRegion
        self.cell.shapes(self.ool_layer).insert(etchRegion)

        # Heater wire
        if self.genHeater:
            if self.heatType == 0:
                #Hilbert is defined only for square areas. We would fit whatever is smaller

                if activeArea[0] != activeArea[1]:
                    if (activeArea[0] > activeArea[1]):
                        wireArea = activeArea[1] / 2
                    else:
                        wireArea = activeArea[0] / 2
                else:
                    wireArea = activeArea[0] / 2

                #issue num2:
                #  the diagonal contact placemnet is required
                #  so we have to calculate space for the return path
                #  segment separation 1sqg => seg = wireArea / 2^n + 1

                Hcnt = 2**self.heatOrder + 1
                Hseg = wireArea / (Hcnt)
                print("Hseq: {:.3f}".format(Hseg))
                wireAreaRed = wireArea - Hseg
                a = wireAreaRed + wireAreaRed * 1j
                b = wireAreaRed - wireAreaRed * 1j
                z = 0

                for i in range(1, self.heatOrder + 1):
                    w = 1j * z.conjugate()
                    z = numpy.array([w - a, z - b, z + a, b - w]) / 2
                z = z.flatten()
                X = [x.real for x in z]
                Y = [x.imag for x in z]

                heatPoints = []

                for i in range(0, len(X)):
                    heatPoints.append(pya.DPoint(X[i], Y[i]))

                #lets add the return path
                #  start with calculation of intersection to the beam

                #  linEqa = -1*(pointP.y / pointP.x) - valid only for Square
                #
                #print("Linear equation is y = {:.3f}.x".format(linEqa))

                heatInitial = heatPoints[0]

                pointS1 = pya.DPoint(-size[0] / 2, size[1] / 2)
                #pointS2 = pya.DPoint(activeArea[0]/2, -activeArea[1]/2)
                if self.debug:
                    print("P:{:.3f},{:.3f} ; S:{:.3f},{:.3f}".format(
                        -pointP.x, pointP.y, pointS1.x, pointS1.y))
                linEqa = (pointP.y - pointS1.y) / (-pointP.x - pointS1.x)
                linEqb = pointP.y - linEqa * -pointP.x
                if self.debug:
                    print("Line equation is: y={:.3f}x+{:.3f}".format(
                        linEqa, linEqb))

                heatPoints.insert(
                    0, pya.DPoint(heatPoints[0].x - 2 * Hseg, heatPoints[0].y))
                heatPoints.insert(
                    0,
                    pya.DPoint(heatPoints[0].x,
                               linEqa * (heatPoints[0].x + Hseg) + linEqb))
                heatPoints.append(pya.DPoint(heatPoints[len(heatPoints)-1].x, \
                    linEqa*(heatPoints[len(heatPoints)-1].x+Hseg)-linEqb))

                heatPoints.append(pya.DPoint(pointP.x - Hseg,
                                             -pointP.y))  #arm contacts
                heatPoints.insert(0, pya.DPoint(-pointP.x - Hseg, pointP.y))

                #probably somewhere here is a good time to calculate perforations
                # teoretically first opening should be -Heg/2 to the left of the very first
                # point and should repeat in X and Y axis with interval of Hseg
                #

                # center is HeatPoints[2] -Hseg/2 ?
                if self.perfAct:
                    perfW = self.perfSize / 2 / dbu
                    #perfCenter = pya.DPoint(heatPoints[2].x - Hseg, heatPoints[2].y - Hseg)
                    #perfBox = pya.DBox(perfCenter.x-perfW, perfCenter.y-perfW, perfCenter.x+perfW, perfCenter.y-perfW)
                    elCell = self.layout.create_cell("Perforator")
                    perfBox = pya.DPolygon(
                        pya.DBox(-perfW, -perfW, perfW, perfW))
                    if self.roundPath:
                        perfBox = perfBox.round_corners(Hseg / 2, Hseg / 2, 32)
                    elCell.shapes(self.perfl_layer).insert(perfBox)

                    #lets make an array of them
                    x_vect = pya.DVector(2 * Hseg, 0.0)
                    y_vect = pya.DVector(0.0, 2 * Hseg)
                    t = pya.DCplxTrans(heatInitial.x, heatInitial.y + Hseg)
                    perfArr = pya.DCellInstArray(elCell.cell_index(), t,
                                                 x_vect, y_vect, Hcnt - 1,
                                                 Hcnt - 2)

                    self.cell.insert(perfArr)

                    #move to the right coordinates
                    pathT = pya.DCplxTrans(Hseg, 0)
                    heatPath = pya.DPath(heatPoints, self.heatW)
                    heatPathT = heatPath.transformed(pathT)
                    if self.roundPath:
                        heatPathT = heatPath.round_corners(Hseg / 2, 32, 0.001)
                        heatCenter = heatPathT.bbox().center()
                        print(heatCenter)
                        print("Rounded Path center: {}:{}".format(
                            heatCenter.x, heatCenter.y))
                        pathTr = pya.DCplxTrans(-heatCenter.x, -heatCenter.y)
                        heatPathT = heatPathT.transformed(pathTr)
                    self.cell.shapes(self.heatl_layer).insert(heatPathT)
            else:
                print("Wire definition has not been found!")
                #TODO ... other types of heaters

        if self.genWO:
            #we would make a wire connection from the P point to the edge of the membrane
            # overpass on both sides as an option

            # it has to be realized as a set of the 4 path
            print("Overal size: {}:{}".format(ovSize[0], ovSize[1]))
            woPathA = pya.DPath(
                [pointP, pya.DPoint(ovSize[0] / 2, ovSize[1] / 2)], woW, woOP,
                woOP)
            woPathB = pya.DPath([pya.DPoint(-pointP.x, pointP.y), pya.DPoint(-ovSize[0]/2, ovSize[1]/2)],\
                woW, woOP, woOP)
            woPathC = pya.DPath([pya.DPoint(-pointP.x, -pointP.y), pya.DPoint(-ovSize[0]/2, -ovSize[1]/2)],\
                woW, woOP, woOP)
            woPathD = pya.DPath([pya.DPoint(pointP.x, -pointP.y), pya.DPoint(ovSize[0]/2, -ovSize[1]/2)],\
                woW, woOP, woOP)
            self.cell.shapes(self.cntl_layer).insert(woPathA)
            self.cell.shapes(self.cntl_layer).insert(woPathB)
            self.cell.shapes(self.cntl_layer).insert(woPathC)
            self.cell.shapes(self.cntl_layer).insert(woPathD)

        if self.genCnt:
            # Ok that would be fun ...
            #   so at first we should be able to find how many of the IGC we would be able to fit
            #   in between of the perforations (maybe we should count also for the minimal separation)
            #   principally:
            #       single IGS pair consists of 2 wires and 2 gaps = IGSpairW?
            #       testing condition is therefore IGSCnt = floor((Hseg - perfW) / IGSpairW)
            cntW = self.cntW / dbu
            cntSp = self.cntSp / dbu
            cntB = self.cntB / dbu
            cntBunchW = 2 * (cntW + cntSp)
            cntCnt = math.floor((2 * Hseg - 2 * perfW) / cntBunchW)
            if self.debug:
                print("IDC W={}".format(cntBunchW))
                print("IDCs per bunch: {}".format(cntCnt))
            if cntCnt == 0:
                print(
                    "Error: Interdigital contacts with given specs could not be realized because of geometric containts!"
                )
            else:
                #lets make a subcell with interdigital pair
                #   so first calculate the active area - contact bars to get the lenght
                #   contacts singles
                cntCell = self.layout.create_cell("IDC_subcell")
                cntArrCell = self.layout.create_cell("IDC_cell")

                #cntLenght = activeArea - 2*cntB - cntSp

                cntPath_p1 = pya.DPoint((cntSp + cntW) / 2,
                                        activeArea[1] / 2 - cntB)
                cntPath_p2 = pya.DPoint((cntSp + cntW) / 2,
                                        -activeArea[1] / 2 + cntSp +
                                        cntB)  #TODO tohle je asi blbe ...
                cntPath_pA = [cntPath_p1, cntPath_p2]
                cntPath_pB = [cntPath_p1 * -1, cntPath_p2 * -1]

                cntPath_A = pya.DPath(cntPath_pA, cntW, 0.0, 0.0)
                cntPath_B = pya.DPath(cntPath_pB, cntW, 0.0, 0.0)

                cntCell.shapes(self.idcl_layer).insert(cntPath_A)
                cntCell.shapes(self.idcl_layer).insert(cntPath_B)

                #now lets make bunches of cntCnt and center them
                # TODO: tady jsem skoncil ... potreba projit odstavec pod
                #BEGIN
                x_vect = pya.DVector(cntBunchW, 0.0)
                y_vect = pya.DVector(0.0, 0.0)
                if self.debug:
                    print("IDC bunch Vectors: {}, {}, {}, {}".format(\
                        x_vect.x, x_vect.y, y_vect.x, y_vect.y))
                t = pya.DCplxTrans(0, 0)
                cntArr = pya.DCellInstArray(cntCell.cell_index(), t, x_vect,
                                            y_vect, cntCnt, 1)

                #center the origins on top of each other
                #   here we have a bunch of IDCs
                cntArr_center = cntArr.bbox(self.layout).center()
                if self.debug:
                    print("Bunch center: {},{}".format(cntArr_center.x,
                                                       cntArr_center.y))
                t = pya.DCplxTrans(1.0, 0, False, -cntArr_center.x,
                                   -cntArr_center.y)
                cntArr.transform(t)
                cntArrCell.insert(cntArr)

                #   move the array to the position of Hilb. initial and paste it into the overal array

                a_vect = pya.DVector(2 * Hseg, 0.0)
                b_vect = pya.DVector(0.0, 0.0)

                cntLoct = pya.DCplxTrans(1.0, 0, False, heatInitial.x - Hseg,
                                         0.0)

                cntArrAll = pya.DCellInstArray(cntArrCell.cell_index(),
                                               cntLoct, a_vect, b_vect, Hcnt,
                                               1)
                self.cell.insert(cntArrAll)

                #Top and bottom contact
                #  by principle the bar-contact should be horizontally oriented across the active zone
                #  then they should continue to the respective P-points (upright, lowerleft)

                #  Contact bar would be a box from the edge to the edge of active area with a width of
                #  cntB

                # pointCNT1A = pya.DPoint(activeArea[0]/2, activeArea[1]/2)

                # if self.debug:
                #     print("P:{:.3f},{:.3f} ; CNT:{:.3f},{:.3f}".format(-pointP.x, pointP.y, pointCNT1A.x, pointCNT1A.y))
                # linCntEqa = (pointP.y-pointCNT1A.y)/(-pointP.x-pointCNT1A.x)
                # linCntEqb = pointP.y - linCntEqa*-pointP.x

                # if self.debug:
                #     print("CNT line equation is: y={:.3f}x+{:.3f}".format(linEqa,linEqb))

                # pointCNT1B =

                # Contact Bars
                cntBarW = self.cntB / dbu
                cntWoW = self.cntWO / dbu
                shapeSetCNT = []
                #cntBarA
                shapeSetCNT.append(pya.DBox(-activeArea[0]/2, activeArea[1]/2-cntBarW,\
                    activeArea[0]/2, activeArea[1]/2))
                #cntBarB
                shapeSetCNT.append(pya.DBox(-activeArea[0]/2, -activeArea[1]/2,\
                    activeArea[0]/2, -activeArea[1]/2+cntBarW))

                pointS2 = pya.DPoint(activeArea[0] / 2, activeArea[1] / 2)
                #cntWOPathA
                shapeSetCNT.append(
                    pya.DPath([pointS2, pointP], cntWoW, cntWoW / 2,
                              cntWoW).polygon())
                #cntWOPathB
                shapeSetCNT.append(
                    pya.DPath([-pointS2, -pointP], cntWoW, cntWoW / 2,
                              cntWoW).polygon())

                for shape in shapeSetCNT:
                    self.cell.shapes(self.idcl_layer).insert(shape)

                #Vias
                #TODO: repair position of the vias

                cntViaW = cntWoW * 0.9 / 2  # 10% smaller then the wire
                tr = pya.DCplxTrans(1.0, 45.0, False, pya.DVector(pointP))
                cntViaA = pya.DPolygon(pya.DBox(-cntViaW, -cntViaW,\
                    cntViaW, cntViaW)).transform(tr)
                tr = pya.DCplxTrans(1.0, 45.0, False, pya.DVector(-pointP))
                cntViaB = pya.DPolygon(pya.DBox(-cntViaW, -cntViaW,\
                    cntViaW, cntViaW)).transformed(tr)
                self.cell.shapes(self.lvia_layer).insert(cntViaA)
                self.cell.shapes(self.lvia_layer).insert(cntViaB)
Example #11
0
sp = layout.create_cell("spiral")  # create cell for a delay spiral
rib = layout.layer(1, 0)  # create strip waveguide layer

horizontal = np.concatenate(
    (np.array([0, 4, 8]), np.full(6, 8)))  # Pad to total length 9 with 8's

vertical = np.concatenate(
    (np.array([16, 20, 24]), np.full(6,
                                     24)))  # Pad to total length 9 with 24's

# Generate the spiral and instantiate its cell
paths.delay_spiral_geo(layout,
                       rib,
                       sp,
                       turns=4,
                       spacing=2.5,
                       vertical=vertical,
                       horizontal=horizontal,
                       horizontal_mode='symmetric',
                       vertical_mode='symmetric',
                       quad_shift=0,
                       start_turn=1,
                       start_angle=0,
                       end_angle=0,
                       radial_shift=4.80,
                       n_pts=5000)

top.insert(pya.DCellInstArray(sp.cell_index(), pya.DTrans(pya.DVector(0, 30))))

layout.write(my_constants.gds_models_path + 'test_spiral.gds')
Example #12
0
def main(args):

    SIM_CELL = pya.LayerInfo(0, 0)
    Si = pya.LayerInfo(1, 0)
    MEEP_SOURCE = pya.LayerInfo(10, 0)
    MEEP_PORT1 = pya.LayerInfo(20, 0)
    MEEP_PORT2 = pya.LayerInfo(21, 0)
    MEEP_PORT3 = pya.LayerInfo(22, 0)
    MEEP_PORT4 = pya.LayerInfo(23, 0)


    # ## Simulation Parameters

    # In[3]:


    ring_radius = 8 # um
    ring_width = 0.5 # um
    pml_width = 1.0 # um
    gap = args.gap # um
    src_port_gap = 0.2 # um
    straight_wg_length = pml_width + 1 # um

    # Simulation resolution
    res = 100        # pixels/μm


    # ## Step 1. Drawing a waveguide coupler and saving into a temporary .gds file

    # In[4]:


    from zeropdk.layout import layout_arc, layout_waveguide, layout_path, layout_box
    from tempfile import NamedTemporaryFile
    from math import sqrt

    # Create a temporary filename
    temp_file = NamedTemporaryFile(delete=False, suffix='.gds')
    filename = temp_file.name
    # temp_file = None
    # filename = "test.gds"

    # Instantiate a layout and a top cell
    layout = pya.Layout()
    layout.dbu = 0.001
    TOP = layout.create_cell("TOP")

    sqrt2 = sqrt(2)

    # Unit vectors
    ex = pya.DVector(1, 0)
    ey = pya.DVector(0, 1)
    e45 = (ex + ey) / sqrt2
    e135 = (-ex + ey) / sqrt2

    # Draw circular bend
    layout_arc(TOP, Si, - ring_radius*ey, ring_radius, ring_width, 0, np.pi/2)

    # Extend the bend to avoid discontinuities
    layout_waveguide(TOP, Si, [0*ex, - straight_wg_length*ex], ring_width)
    layout_waveguide(TOP, Si, [-1*ring_radius*ey + ring_radius*ex, 
                               -straight_wg_length * ey - ring_radius*ey + ring_radius*ex], ring_width)

    # Add the ports as 0-width paths
    port_size = ring_width * 4.0


    # Draw add/drop waveguide

    coupling_point = (ring_radius + gap + ring_width) * e45 - ring_radius * ey
    add_drop_length = (ring_radius + gap + ring_width) * sqrt2
    layout_waveguide(TOP, Si, [coupling_point + (add_drop_length + 0.4) * e135,
                               coupling_point - (add_drop_length + 0.4) * e135],
                    ring_width)


    # Source at port 1
    layout_path(TOP, MEEP_SOURCE, [coupling_point - port_size/2*ex + (add_drop_length / 2 + src_port_gap) * e135, 
                                   coupling_point + port_size/2*ex + (add_drop_length / 2 + src_port_gap) * e135], 0)

    # Source at port 2 (alternative)
    # layout_path(TOP, MEEP_SOURCE, [-port_size/2*ey - src_port_gap*ex, port_size/2*ey - 0.2*ex], 0)

    # Port 1
    layout_path(TOP, MEEP_PORT1,   [coupling_point - port_size/2*ex + (add_drop_length / 2) * e135, 
                                    coupling_point + port_size/2*ex  + (add_drop_length / 2) * e135], 0)

    # Port 2
    layout_path(TOP, MEEP_PORT2,   [-port_size/2*ey, port_size/2*ey], 0)

    # Port 3
    layout_path(TOP, MEEP_PORT3,   [coupling_point - port_size/2*ey - (add_drop_length / 2) * e135, 
                                    coupling_point + port_size/2*ey - (add_drop_length / 2) * e135], 0)
    # Port 4
    layout_path(TOP, MEEP_PORT4,   [-1*ring_radius*ey + ring_radius*ex - port_size/2*ex, 
                                    -1*ring_radius*ey + ring_radius*ex + port_size/2*ex], 0)

    # Draw simulation region
    layout_box(TOP, SIM_CELL, 
               -1.0*ring_radius*ey - (pml_width + src_port_gap) * (ex + ey), # Bottom left point 
               coupling_point + (add_drop_length / 2 + src_port_gap) * e45 + pml_width * (ex + ey),  # Top right point
               ex)

    # Write to file
    layout.write(filename)
    print(f"Produced file {filename}.")


    # ## Step 2. Load gds file into meep
    # 
    # ### Visualization and simulation
    # 
    # If you choose a normal filename (not temporary), you can download the GDSII file from the cluster (see Files in MyAdroit dashboard) to see it with your local Klayout. Otherwise, let's get simulating:

    # In[5]:


    def round_vector(vector, decimal_places=3):
        x = round(vector.x, decimal_places)
        y = round(vector.y, decimal_places)
        z = round(vector.z, decimal_places)
        return mp.Vector3(x, y, z)


    # In[6]:


    gdsII_file = filename
    CELL_LAYER = 0
    SOURCE_LAYER = 10
    Si_LAYER = 1
    PORT1_LAYER = 20
    PORT2_LAYER = 21
    PORT3_LAYER = 22
    PORT4_LAYER = 23

    t_oxide = 1.0
    t_Si = 0.22
    t_SiO2 = 0.78

    oxide = mp.Medium(epsilon=2.25)
    silicon=mp.Medium(epsilon=12)

    lcen = 1.55
    fcen = 1/lcen
    df = 0.2*fcen
    nfreq = 25

    cell_zmax =  0
    cell_zmin =  0
    si_zmax = 10
    si_zmin = -10

    # read cell size, volumes for source region and flux monitors,
    # and coupler geometry from GDSII file
    # WARNING: Once the file is loaded, the prism contents is cached and cannot be reloaded.
    # SOLUTION: Use a different filename or restart the kernel

    si_layer = mp.get_GDSII_prisms(silicon, gdsII_file, Si_LAYER, si_zmin, si_zmax)

    cell = mp.GDSII_vol(gdsII_file, CELL_LAYER, cell_zmin, cell_zmax)
    src_vol = mp.GDSII_vol(gdsII_file, SOURCE_LAYER, si_zmin, si_zmax)
    p1 = mp.GDSII_vol(gdsII_file, PORT1_LAYER, si_zmin, si_zmax)
    p2 = mp.GDSII_vol(gdsII_file, PORT2_LAYER, si_zmin, si_zmax)
    p3 = mp.GDSII_vol(gdsII_file, PORT3_LAYER, si_zmin, si_zmax)
    p4 = mp.GDSII_vol(gdsII_file, PORT4_LAYER, si_zmin, si_zmax)


    sources = [mp.EigenModeSource(src=mp.GaussianSource(fcen,fwidth=df),
                                  size=round_vector(src_vol.size),
                                  center=round_vector(src_vol.center),
                                  direction=mp.NO_DIRECTION,
                                  eig_kpoint=mp.Vector3(1, -1, 0), # -45 degree angle
                                  eig_band=1,
                                  eig_parity=mp.NO_PARITY,
                                  eig_match_freq=True)]

    # Display simulation object
    sim = mp.Simulation(resolution=res,
                        default_material=oxide,
                        eps_averaging=False,
                        cell_size=cell.size,
                        geometry_center=round_vector(cell.center,2),
                        boundary_layers=[mp.PML(pml_width)],
                        sources=sources,
                        geometry=si_layer)

    # Delete file created in previous cell

    import os
    if temp_file:
        temp_file.close()
        os.unlink(filename)


    # ## Step 3. Setup simulation environment
    # 
    # This will load the python-defined parameters from the previous cell and instantiate a fast, C++ based, simulation environment using meep. It will also compute the eigenmode of the source, in preparation for the FDTD simulation.

    # In[7]:


    sim.reset_meep()

    # Could add monitors at many frequencies by looping over fcen
    # Means one FDTD for many results!
    mode1 = sim.add_mode_monitor(fcen, df, nfreq, mp.ModeRegion(volume=p1))
    mode2 = sim.add_mode_monitor(fcen, df, nfreq, mp.ModeRegion(volume=p2))
    mode3 = sim.add_mode_monitor(fcen, df, nfreq, mp.ModeRegion(volume=p3))
    mode4 = sim.add_mode_monitor(fcen, df, nfreq, mp.ModeRegion(volume=p4))

    # Let's store the frequencies that were generated by this mode monitor
    mode1_freqs = np.array(mp.get_eigenmode_freqs(mode1))
    mode2_freqs = np.array(mp.get_eigenmode_freqs(mode2))
    mode3_freqs = np.array(mp.get_eigenmode_freqs(mode3))
    mode4_freqs = np.array(mp.get_eigenmode_freqs(mode4))

    sim.init_sim()


    # ### Verify if there are numerical errors.
    # - You should see a clean black and white plot.
    # - If there are other weird structures, try increasing the resolution.

    # In[8]:


    eps_data = sim.get_array(center=cell.center, size=cell.size, component=mp.Dielectric)
    plt.figure(dpi=res)
    plt.imshow(eps_data.transpose(), interpolation='none', cmap='binary', origin='lower')
    plt.colorbar()
    plt.show()


    # ### Verify that the structure makes sense.
    # 
    # Things to check:
    # - Are the sources and ports outside the PML?
    # - Are dimensions correct?
    # - Is the simulation region unnecessarily large?

    # In[9]:


    # If there is a warning that reads "The specified user volume
    # is larger than the simulation domain and has been truncated",
    # It has to do with some numerical errors between python and meep.
    # Ignore.
    # sim.init_sim()

    f = plt.figure(dpi=100)
    sim.plot2D(ax=f.gca())
    plt.show()


    # Looks pretty good. Simulations at the high enough resolution required to avoid spurious reflections in the bend are very slow! This can be sped up quite a bit by running the code in parallel from the terminal. Later, we will put this notebook's code into a script and run it in parallel.

    # ## Step 4. Simulate FDTD and Animate results
    # 
    # More detailed meep documentation available [here](https://meep.readthedocs.io/en/latest/Python_Tutorials/Basics/#transmittance-spectrum-of-a-waveguide-bend).

    # In[10]:


    # Set to true to compute animation (may take a lot of memory)
    # Turn this off if you don't need to visualize.
    compute_animation = False


    # In[11]:


    # Setup and run the simulation

    # The following line defines a stopping condition depending on the square
    # of the amplitude of the Ez field at the port 2.
    print(f"Stop condition: decay to 0.1% of peak value in the last {2.0/df:.1f} time units.")
    stop_condition = mp.stop_when_fields_decayed(2.0/df,mp.Ez,p3.center,1e-3)
    if compute_animation:
        f = plt.figure(dpi=100)
        animate = mp.Animate2D(sim,mp.Ez,f=f,normalize=True)
        sim.run(mp.at_every(1,animate), until_after_sources=stop_condition)
        plt.close()
        animate.to_mp4(10, 'media/coupler1.mp4')
    else:
        sim.run(until_after_sources=stop_condition)


    # ### Visualize results
    # 
    # Things to check:
    # - Was the simulation time long enough for the pulse to travel through the output port in its entirety? Given the automatic stop condition, this should be the case.

    # In[12]:


    from IPython.display import Video, display
    if compute_animation:
        display(Video('media/coupler1.mp4'))

    # ## Step 5. Compute S parameters of the coupler

    # In[13]:


    # Every mode monitor measures the power flowing through it in either the forward or backward direction

    # This time, the monitor is at an oblique angle to the waveguide. This is because meep
    # can only compute fluxes in either the x, y, or z planes. In order to correctly measure
    # the flux, we need to provide a k-vector at an angle. 
    # So we compute a unit vector at a -45 angle like so:
    kpoint135 = mp.Vector3(x=1).rotate(mp.Vector3(z=1), np.radians(-45))

    # In this simulation, the ports 1 and 3 are on an angled waveguide, and
    # 2 and 4 are perpendicular to the waveguide.
    eig_mode1 = sim.get_eigenmode_coefficients(mode1, [1], eig_parity=mp.NO_PARITY, 
                                               direction=mp.NO_DIRECTION, kpoint_func=lambda f,n: kpoint135)

    eig_mode2 = sim.get_eigenmode_coefficients(mode2, [1], eig_parity=mp.NO_PARITY)

    eig_mode3 = sim.get_eigenmode_coefficients(mode3, [1], eig_parity=mp.NO_PARITY, 
                                               direction=mp.NO_DIRECTION, kpoint_func=lambda f,n: kpoint135)

    eig_mode4 = sim.get_eigenmode_coefficients(mode4, [1], eig_parity=mp.NO_PARITY)

    # We proceed like last time.

    # First, we need to figure out which direction the "dominant planewave" k-vector is
    # We can pick the first frequency (0) for that, assuming that for all simulated frequencies,
    # The dominant k-vector will point in the same direction.
    k1 = eig_mode1.kdom[0]
    k2 = eig_mode2.kdom[0]
    k3 = eig_mode3.kdom[0]
    k4 = eig_mode4.kdom[0]

    # eig_mode.alpha[0,0,0] corresponds to the forward direction, whereas
    # eig_mode.alpha[0,0,1] corresponds to the backward direction

    # For port 1, we are interested in the -y direction, so if k1.y is positive, select 1, otherwise 0
    idx = (k1.y > 0) * 1
    p1_thru_coeff = eig_mode1.alpha[0,:,idx]
    p1_reflected_coeff = eig_mode1.alpha[0,:,1-idx]

    # For port 3, we are interestred in the +x direction
    idx = (k3.x < 0) * 1
    p3_thru_coeff = eig_mode3.alpha[0,:,idx]
    p3_reflected_coeff = eig_mode3.alpha[0,:,1-idx]

    # For port 2, we are interested in the -x direction
    idx = (k2.x > 0) * 1
    p2_thru_coeff = eig_mode2.alpha[0,:,idx]
    p2_reflected_coeff = eig_mode2.alpha[0,:,1-idx]

    # For port 4, we are interested in the -y direction
    idx = (k4.y > 0) * 1
    p4_thru_coeff = eig_mode4.alpha[0,:,idx]
    p4_reflected_coeff = eig_mode4.alpha[0,:,1-idx]


    # transmittance
    S41 = p4_thru_coeff/p1_thru_coeff
    S31 = p3_thru_coeff/p1_thru_coeff
    S21 = p2_thru_coeff/p1_thru_coeff
    S11 = p1_reflected_coeff/p1_thru_coeff

    print("----------------------------------")
    print(f"Parameters: radius={ring_radius:.1f}")
    print(f"Frequencies: {mode1_freqs}")


    # In[20]:


    #Write to csv file
    import csv
    with open(f'sparams1.gap{gap:.2f}um.csv', mode='w') as sparams_file:
        sparam_writer = csv.writer(sparams_file, delimiter=',')
        sparam_writer.writerow(['f(Hz)',
                                'real(S11)','imag(S11)',
                                'real(S21)','imag(S21)',
                                'real(S31)','imag(S31)',
                                'real(S41)','imag(S41)'
                               ])
        for i in range(len(mode1_freqs)):
            sparam_writer.writerow([mode1_freqs[i] * 3e14,
                                    np.real(S11[i]),np.imag(S11[i]),
                                    np.real(S21[i]),np.imag(S21[i]),
                                    np.real(S31[i]),np.imag(S31[i]),
                                    np.real(S41[i]),np.imag(S41[i])
                                   ])
Example #13
0
def main(args):

    SIM_CELL = pya.LayerInfo(0, 0)
    Si = pya.LayerInfo(1, 0)
    MEEP_SOURCE1 = pya.LayerInfo(10, 0)
    MEEP_PORT1 = pya.LayerInfo(20, 0)
    MEEP_PORT2 = pya.LayerInfo(21, 0)

    # ## Simulation Parameters

    # In[3]:

    ring_radius = args.radius  # um
    ring_width = 0.5  # um
    pml_width = 1.0  # um
    straight_wg_length = pml_width + 0.2  # um

    # Simulation resolution
    res = 100  # pixels/μm

    # ## Step 1. Drawing a bent waveguide and saving into a temporary .gds file

    # In[4]:

    from zeropdk.layout import layout_arc, layout_waveguide, layout_path, layout_box
    from tempfile import NamedTemporaryFile

    # Create a temporary filename
    temp_file = NamedTemporaryFile(delete=False, suffix='.gds')
    filename = temp_file.name

    # Instantiate a layout and a top cell
    layout = pya.Layout()
    layout.dbu = 0.001
    TOP = layout.create_cell("TOP")

    # Unit vectors
    ex = pya.DVector(1, 0)
    ey = pya.DVector(0, 1)

    # Draw circular bend
    layout_arc(TOP, Si, -ring_radius * ey, ring_radius, ring_width, 0,
               np.pi / 2)

    # Extend the bend to avoid discontinuities
    layout_waveguide(TOP, Si, [0 * ex, -straight_wg_length * ex], ring_width)
    layout_waveguide(TOP, Si, [
        -1 * ring_radius * ey + ring_radius * ex,
        -straight_wg_length * ey - ring_radius * ey + ring_radius * ex
    ], ring_width)

    # Add the ports as 0-width paths
    port_size = ring_width * 4.0

    # Source port
    layout_path(
        TOP, MEEP_SOURCE1,
        [-port_size / 2 * ey - 0.2 * ex, port_size / 2 * ey - 0.2 * ex], 0)
    # Input port (immediately at the start of the bend)
    layout_path(TOP, MEEP_PORT1, [-port_size / 2 * ey, port_size / 2 * ey], 0)
    # Output port (immediately at the end of the bend)
    layout_path(TOP, MEEP_PORT2, [
        -1 * ring_radius * ey + ring_radius * ex - port_size / 2 * ex,
        -1 * ring_radius * ey + ring_radius * ex + port_size / 2 * ex
    ], 0)

    # Draw simulation region
    layout_box(
        TOP,
        SIM_CELL,
        -1.0 * ring_radius * ey - straight_wg_length *
        (ex + ey),  # Bottom left point 
        1.0 * ring_radius * ex + (straight_wg_length + port_size / 2) *
        (ex + ey),  # Top right point
        ex)

    # Write to file
    layout.write(filename)
    print(f"Produced file {filename}.")

    # ## Step 2. Load gds file into meep
    #
    # ### Visualization and simulation
    #
    # If you choose a normal filename (not temporary), you can download the GDSII file from the cluster (see Files in MyAdroit dashboard) to see it with your local Klayout. Otherwise, let's get simulating:

    # In[5]:

    gdsII_file = filename
    CELL_LAYER = 0
    SOURCE_LAYER = 10
    Si_LAYER = 1
    PORT1_LAYER = 20
    PORT2_LAYER = 21

    t_oxide = 1.0
    t_Si = 0.22
    t_SiO2 = 0.78

    oxide = mp.Medium(epsilon=2.25)
    silicon = mp.Medium(epsilon=12)

    lcen = 1.55
    fcen = 1 / lcen
    df = 0.2 * fcen
    nfreq = 25

    cell_zmax = 0
    cell_zmin = 0
    si_zmax = 10
    si_zmin = -10

    # read cell size, volumes for source region and flux monitors,
    # and coupler geometry from GDSII file
    # WARNING: Once the file is loaded, the prism contents is cached and cannot be reloaded.
    # SOLUTION: Use a different filename or restart the kernel

    si_layer = mp.get_GDSII_prisms(silicon, gdsII_file, Si_LAYER, si_zmin,
                                   si_zmax)

    cell = mp.GDSII_vol(gdsII_file, CELL_LAYER, cell_zmin, cell_zmax)
    src_vol = mp.GDSII_vol(gdsII_file, SOURCE_LAYER, si_zmin, si_zmax)
    p1 = mp.GDSII_vol(gdsII_file, PORT1_LAYER, si_zmin, si_zmax)
    p2 = mp.GDSII_vol(gdsII_file, PORT2_LAYER, si_zmin, si_zmax)

    sources = [
        mp.EigenModeSource(src=mp.GaussianSource(fcen, fwidth=df),
                           size=src_vol.size,
                           center=src_vol.center,
                           eig_band=1,
                           eig_parity=mp.NO_PARITY,
                           eig_match_freq=True)
    ]

    # Display simulation object
    sim = mp.Simulation(resolution=res,
                        default_material=oxide,
                        eps_averaging=False,
                        cell_size=cell.size,
                        boundary_layers=[mp.PML(pml_width)],
                        sources=sources,
                        geometry=si_layer,
                        geometry_center=cell.center)

    # Delete file created in previous cell

    import os
    temp_file.close()
    os.unlink(filename)

    # ## Step 3. Setup simulation environment
    #
    # This will load the python-defined parameters from the previous cell and instantiate a fast, C++ based, simulation environment using meep. It will also compute the eigenmode of the source, in preparation for the FDTD simulation.

    # In[6]:

    sim.reset_meep()

    # Could add monitors at many frequencies by looping over fcen
    # Means one FDTD for many results!
    mode1 = sim.add_mode_monitor(fcen, df, nfreq, mp.ModeRegion(volume=p1))
    mode2 = sim.add_mode_monitor(fcen, df, nfreq, mp.ModeRegion(volume=p2))

    # Let's store the frequencies that were generated by this mode monitor
    mode1_freqs = np.array(mp.get_eigenmode_freqs(mode1))
    mode2_freqs = np.array(mp.get_eigenmode_freqs(mode2))

    sim.init_sim()

    # ### Verify that the structure makes sense.
    #
    # Things to check:
    # - Are the sources and ports outside the PML?
    # - Are dimensions correct?
    # - Is the simulation region unnecessarily large?

    # In[7]:

    # If there is a warning that reads "The specified user volume
    # is larger than the simulation domain and has been truncated",
    # It has to do with some numerical errors between python and meep.
    # Ignore.

    # f = plt.figure(dpi=100)
    # sim.plot2D(ax=f.gca())
    # plt.show()

    # Looks pretty good. Simulations at the high enough resolution required to avoid spurious reflections in the bend are very slow! This can be sped up quite a bit by running the code in parallel from the terminal. Later, we will put this notebook's code into a script and run it in parallel.

    # ## Step 4. Simulate FDTD and Animate results
    #
    # More detailed meep documentation available [here](https://meep.readthedocs.io/en/latest/Python_Tutorials/Basics/#transmittance-spectrum-of-a-waveguide-bend).

    # In[8]:

    # Set to true to compute animation (may take a lot of memory)
    compute_animation = False

    # In[9]:

    # Setup and run the simulation

    # The following line defines a stopping condition depending on the square
    # of the amplitude of the Ez field at the port 2.
    print(
        f"Stop condition: decay to 0.1% of peak value in the last {2.0/df:.1f} time units."
    )
    stop_condition = mp.stop_when_fields_decayed(2.0 / df, mp.Ez, p2.center,
                                                 1e-3)
    if compute_animation:
        f = plt.figure(dpi=100)
        animate = mp.Animate2D(sim, mp.Ez, f=f, normalize=True)
        sim.run(mp.at_every(1, animate), until_after_sources=stop_condition)
        plt.close()
        # Save video as mp4
        animate.to_mp4(10, 'media/bend.mp4')
    else:
        sim.run(until_after_sources=stop_condition)

    # ### Visualize results
    #
    # Things to check:
    # - Was the simulation time long enough for the pulse to travel through port2 in its entirety? Given the automatic stop condition, this should be the case.

    # In[10]:

    from IPython.display import Video, display
    # display(Video('media/bend.mp4'))

    # ## Step 5. Compute loss and reflection of the bend

    # In[11]:

    # Every mode monitor measures the power flowing through it in either the forward or backward direction
    eig_mode1 = sim.get_eigenmode_coefficients(mode1, [1],
                                               eig_parity=mp.NO_PARITY)
    eig_mode2 = sim.get_eigenmode_coefficients(mode2, [1],
                                               eig_parity=mp.NO_PARITY)

    # First, we need to figure out which direction the "dominant planewave" k-vector is
    # We can pick the first frequency (0) for that, assuming that for all simulated frequencies,
    # The dominant k-vector will point in the same direction.
    k1 = eig_mode1.kdom[0]
    k2 = eig_mode2.kdom[0]

    # eig_mode.alpha[0,0,0] corresponds to the forward direction, whereas
    # eig_mode.alpha[0,0,1] corresponds to the backward direction

    # For port 1, we are interested in the +x direction, so if k1.x is positive, select 0, otherwise 1
    idx = (k1.x < 0) * 1
    p1_thru_coeff = eig_mode1.alpha[0, :, idx]
    p1_reflected_coeff = eig_mode1.alpha[0, :, 1 - idx]

    # For port 2, we are interestred in the -y direction
    idx = (k2.y > 0) * 1
    p2_thru_coeff = eig_mode2.alpha[0, :, idx]
    p2_reflected_coeff = eig_mode2.alpha[0, :, 1 - idx]

    # transmittance
    p2_trans = abs(p2_thru_coeff / p1_thru_coeff)**2
    p2_reflected = abs(p1_reflected_coeff / p1_thru_coeff)**2

    print("----------------------------------")
    print(f"Parameters: radius={ring_radius:.1f}")
    print(f"Frequencies: {mode1_freqs}")
    print(f"Transmitted fraction: {p2_trans}")
    print(f"Reflected fraction: {p2_reflected}")

    # In[1]:

    S21 = p2_thru_coeff / p1_thru_coeff
    S11 = p1_reflected_coeff / p1_thru_coeff

    S21_mag = np.abs(S21)
    S21_phase = np.unwrap(np.angle(S21))
    S11_mag = np.abs(S11)
    S11_phase = np.unwrap(np.angle(S11))

    # In[13]:

    #     # Plot S21
    #     f, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(5, 8))
    #     ax1.plot(1/mode1_freqs, 10 * np.log10(S21_mag), '.-')
    #     ax1.set_title("S21")
    #     ax1.set_xlabel(r"$\lambda$ (um)")
    #     ax1.set_ylabel("Magnitude (dB)")
    #     ax1.set_ylim(None, 0)
    #     ax1.grid()

    #     ax2.plot(1/mode1_freqs, S21_phase, '.-')
    #     ax2.set_xlabel(r"$\lambda$ (um)")
    #     ax2.set_ylabel("Phase (rad)")
    #     ax2.grid()
    #     plt.tight_layout()

    #     # In[14]:

    #     # Plot S11
    #     f, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(5, 8))
    #     ax1.plot(1/mode1_freqs, 10 * np.log10(S11_mag), '.-')
    #     ax1.set_title("S11")
    #     ax1.set_xlabel(r"$\lambda$ (um)")
    #     ax1.set_ylabel("Magnitude (dB)")
    #     ax1.set_ylim(None, 0)
    #     ax1.grid()

    #     ax2.plot(1/mode1_freqs, S11_phase, '.-')
    #     ax2.set_xlabel(r"$\lambda$ (um)")
    #     ax2.set_ylabel("Phase (rad)")
    #     ax2.grid()
    #     plt.tight_layout()

    # # Milestones
    #
    # Goal: Compute the transmission profile for bend radii between 1.5um and 10um.
    #
    # - Q: Is the reflection significant for any radius? What explain the loss?
    # - Q: What is the formula total size of the simulation region? How many pixels are there?
    # - Q: If each pixel can host 3-dimensional E-field and H-field vectors with 64bit complex float stored in each dimension, how many megabytes of data needs to be stored at each time step? Is it feasible to save all this information throughout the FDTD simulation?
    # - Bonus: Collect the simulation runtime for each radius. How does it change with different radii?
    # - Bonus: At what resolution does the accuracy of the simulation start degrading? In other words, if halving the resolution only results in a 1% relative difference in the most important target metric, it is still a good resolution.

    # In[2]:

    #Write to csv file
    import csv
    with open(f'sparams.r{ring_radius:.1f}um.csv', mode='w') as sparams_file:
        sparam_writer = csv.writer(sparams_file, delimiter=',')
        sparam_writer.writerow(
            ['f(Hz)', 'real(S11)', 'imag(S11)', 'real(S21)', 'imag(S21)'])
        for i in range(len(mode1_freqs)):
            sparam_writer.writerow([
                mode1_freqs[i] * 3e14,
                np.real(S11[i]),
                np.imag(S11[i]),
                np.real(S21[i]),
                np.imag(S21[i])
            ])