import gdstk

lib = gdstk.Library()

def calc(cell_name, radius, width, f):
    cell = lib.new_cell(cell_name)
    ring = gdstk.ellipse((0,0), radius, inner_radius=radius-width, tolerance=0.001)
    xmax = int((radius+f) / f)
    count = 0
    for x in range(-xmax-1, xmax+2):
        for y in range(-xmax-1, xmax+2):
            box = gdstk.rectangle((x*f, y*f), (x*f+f, y*f+f))
            shape = gdstk.boolean(ring, box, "and")
            if shape:
                shape_cell = lib.new_cell(f"{cell_name}_{x}_{y}").add(*shape)
                cell.add(gdstk.Reference(shape_cell))
                count += 1
    return count

f_list = [0.53, 0.9, 2.0]
f_maxnum = [80, 45, 20]
radius_list = [5.0, 2.5, 3.75]
width_list = [0.5, 0.4]

for radius in radius_list:
    for width in width_list:
        for f, f_max in zip(f_list, f_maxnum):
            cell_name = f"c{radius}um{width}um_f{f}"
            count = calc(cell_name, radius, width, f)
            if count > f_max:
                lib.remove(*list(c for c in lib.cells if c.name.startswith(cell_name)))
                continue
            print(f"{cell_name}: {count} (max {f_max})")
            break

lib.write_gds("mr.gds")
