python生成gds

python版图 MOS的sample: import klayout.db as db import math import os #import pandas as pd # define working folder os.chdir('C:\\Users\\xxxxxx\\Documents\\Python_Klayout\\temp') # define crtical rule Ext_PO2AA=0.18 Enc_AAtoCT=0.02 Space_CT=0.10 Space_Lpoly2AA=0.1 阅读详情
import numpy as np
import pya
import cv2
import os
import matplotlib.pyplot as plt
import json
import traceback
import math


def create_flower_gds_with_rotated_rectangles(image_path, output_gds="flower_rotated_rectangles.gds"):
    """
    根据花朵图像的不同区域生成带旋转矩形的GDS
    每个图层都有可旋转的长方形
    """

    print("=" * 70)
    print("花朵区域化旋转矩形GDS生成器 (精确周期)")
    print("=" * 70)

    # 1. 读取和处理图像
    if not os.path.exists(image_path):
        print(f"错误: 文件 {image_path} 不存在")
        return None, None, None

    # 读取灰度图像
    img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
    if img is None:
        print("无法读取图像")
        return None, None, None

    print(f"图像尺寸: {img.shape}")
    print(f"灰度值范围: {img.min()} - {img.max()}")

    # 2. 将图像放大10倍
    print(f"\n将图像放大10倍...")
    original_height, original_width = img.shape

    # 使用最近邻插值放大图像(保持边缘锐利)
    new_width = original_width * 10
    new_height = original_height * 10

    # 放大图像
    img_large = cv2.resize(img, (new_width, new_height),
                           interpolation=cv2.INTER_NEAREST)

    print(f"放大后图像尺寸: {img_large.shape}")
    print(f"放大倍数: 10倍 (像素: {original_width}×{original_height} → {new_width}×{new_height})")

    # 保存放大后的图像
    cv2.imwrite("enlarged_10x.png", img_large)
    print(f"✓ 放大后的图像已保存: enlarged_10x.png")

    # 使用放大后的图像
    img = img_large

    # 3. 分析图像灰度值分布
    unique_vals, counts = np.unique(img, return_counts=True)
    print(f"\n灰度值分布 (前10个):")
    for i, (val, count) in enumerate(zip(unique_vals[:10], counts[:10])):
        if count > 0:
            print(f"  灰度值 {val:3d}: {count:8d} 像素 ({count / img.size * 100:.1f}%)")

    # 4. 定义不同区域的配置 - 添加旋转角度
    # 每个图层有不同的旋转角度配置
    region_configs = {
        'dark_petals': {
            'gray_range': (51, 53),  # 深灰色区域
            'layer': 1,  # 第1层
            'datatype': 0,
            'description': '深灰色花瓣 - 0度旋转',
            'color': (255, 0, 0),  # 红色
            'rect_config': {
                'rect1': {'length': 0.3, 'width': 0.2, 'rotation': 0},  # 长方形1: 0.3×0.2, 旋转0度
                'rect2': {'length': 0.2, 'width': 0.3, 'rotation': 0},  # 长方形2: 0.2×0.3, 旋转0度
                'period_x': 0.74,  # X方向周期
                'period_y': 0.4,  # Y方向周期
                'rect_type': 'dual_rect'
            }
        },
        'medium_petals': {
            'gray_range': (80, 82),  # 中等灰色区域
            'layer': 2,  # 第2层
            'datatype': 0,
            'description': '中等灰色花瓣 - 0度旋转',
            'color': (255, 128, 0),  # 橙色
            'rect_config': {
                'rect1': {'length': 0.28, 'width': 0.2, 'rotation': 0},
                'rect2': {'length': 0.2, 'width': 0.28, 'rotation': 0},
                'period_x': 0.8,  # 修改为0.74
                'period_y': 0.4,
                'rect_type': 'dual_rect'
            }
        },
        'light_petals': {
            'gray_range': (101, 103),  # 浅灰色区域
            'layer': 3,  # 第3层
            'datatype': 0,
            'description': '浅灰色花瓣 - 45度旋转',
            'color': (255, 255, 0),  # 黄色
            'rect_config': {
                'rect1': {'length': 0.3, 'width': 0.15, 'rotation': 45},
                'rect2': {'length': 0.15, 'width': 0.3, 'rotation': 45},
                'period_x': 0.8,  # 修改为0.74
                'period_y': 0.4,
                'rect_type': 'dual_rect'
            }
        },
        'center': {
            'gray_range': (126, 128),  # 花蕊区域
            'layer': 4,  # 第4层
            'datatype': 0,
            'description': '花蕊中心 - 0度/90度',
            'color': (0, 255, 0),  # 绿色
            'rect_config': {
                'rect1': {'length': 0.3, 'width': 0.2, 'rotation': 45},  # 水平
                'rect2': {'length': 0.2, 'width': 0.3, 'rotation': 45},  # 垂直
                'period_x': 0.74,  # 修改为0.74
                'period_y': 0.4,
                'rect_type': 'dual_rect'
            }
        },
        'stem': {
            'gray_range': (153, 155),  # 茎
            'layer': 5,  # 第5层
            'datatype': 0,
            'description': '花茎 - 15度/105度',
            'color': (0, 128, 255),  # 浅蓝色
            'rect_config': {
                'rect1': {'length': 0.3, 'width': 0.2, 'rotation': 22},
                'rect2': {'length': 0.2, 'width': 0.3, 'rotation': 22},
                'period_x': 0.74,  # 修改为0.74
                'period_y': 0.4,
                'rect_type': 'dual_rect'
            }
        },
        'leaves': {
            'gray_range': (178, 180),  # 叶子
            'layer': 6,  # 第6层
            'datatype': 0,
            'description': '叶子1 - 75度旋转',
            'color': (128, 0, 255),  # 紫色
            'rect_config': {
                'rect1': {'length': 0.3, 'width': 0.2, 'rotation': 22},
                'rect2': {'length': 0.2, 'width': 0.3, 'rotation': 22},
                'period_x': 0.76,  # 修改为0.74
                'period_y': 0.4,
                'rect_type': 'dual_rect'
            }
        },
        'leaves1': {
            'gray_range': (202, 204),  # 叶子
            'layer': 7,  # 第7层
            'datatype': 0,
            'description': '叶子2 - 20度/110度',
            'color': (255, 0, 255),  # 粉色
            'rect_config': {
                'rect1': {'length': 0.3, 'width': 0.18, 'rotation': 67},
                'rect2': {'length': 0.18, 'width': 0.3, 'rotation': 67},
                'period_x': 0.74,  # 修改为0.74
                'period_y': 0.4,
                'rect_type': 'dual_rect'
            }
        },
        'leaves2': {
            'gray_range': (228, 230),  # 叶子
            'layer': 8,  # 第8层
            'datatype': 0,
            'description': '叶子3 - 10度/100度',
            'color': (0, 255, 255),  # 青色
            'rect_config': {
                'rect1': {'length': 0.3, 'width': 0.18, 'rotation': 67},
                'rect2': {'length': 0.18, 'width': 0.3, 'rotation': 67},
                'period_x': 0.76,  # 修改为0.74
                'period_y': 0.4,
                'rect_type': 'dual_rect'
            }
        }
    }

    # 5. 创建GDS布局
    layout = pya.Layout()
    layout.dbu = 0.001  # 1nm per database unit

    top_cell = layout.create_cell("FLOWER_ROTATED_RECTANGLES")

    # 创建所有图层
    layer_indices = {}
    for region_name, config in region_configs.items():
        layer_key = (config['layer'], config['datatype'])
        if layer_key not in layer_indices:
            layer_indices[layer_key] = layout.layer(config['layer'], config['datatype'])
            print(f"创建图层: 图层{config['layer']} (数据类型{config['datatype']})")

    print(f"总共创建了 {len(layer_indices)} 个图层")

    # 6. 为每个区域生成带旋转的矩形阵列
    height, width = img.shape

    # 使用浮点数步长实现精确周期
    scale_factor = 0.1  # 像素转微米的缩放因子
    print(f"\n缩放因子: {scale_factor} µm/像素")
    print(f"开始生成带旋转的矩形阵列 (精确周期)...")

    region_stats = {}
    total_rectangles = 0

    for region_name, config in region_configs.items():
        print(f"\n处理区域: {config['description']}")

        # 创建该区域的掩码
        min_gray, max_gray = config['gray_range']
        mask = (img >= min_gray) & (img <= max_gray)

        # 统计区域大小
        region_pixels = np.sum(mask)
        region_stats[region_name] = region_pixels

        if region_pixels == 0:
            print(f"  ⚠️ 未找到像素,跳过")
            continue

        print(f"  找到像素: {region_pixels} 个")
        print(f"  灰度范围: {min_gray}-{max_gray}")

        # 获取图层索引
        layer_index = layer_indices[(config['layer'], config['datatype'])]

        # 获取矩形配置
        rect_config = config['rect_config']
        rect1_length = rect_config['rect1']['length']
        rect1_width = rect_config['rect1']['width']
        rect1_rotation = rect_config['rect1']['rotation']

        rect2_length = rect_config['rect2']['length']
        rect2_width = rect_config['rect2']['width']
        rect2_rotation = rect_config['rect2']['rotation']

        period_x = rect_config['period_x']
        period_y = rect_config['period_y']

        print(f"  旋转矩形结构:")
        print(f"  长方形1: {rect1_length}×{rect1_width} µm, 旋转角度: {rect1_rotation}度")
        print(f"  长方形2: {rect2_length}×{rect2_width} µm, 旋转角度: {rect2_rotation}度")
        print(f"  精确周期: {period_x}×{period_y} µm")

        rect_count = 0

        # 使用浮点数步长实现精确周期
        step_x_float = period_x / scale_factor  # 0.74 / 0.1 = 7.4像素
        step_y_float = period_y / scale_factor  # 0.4 / 0.1 = 4.0像素

        print(f"  浮点步长: {step_x_float:.2f} × {step_y_float:.2f} 像素")

        # 使用浮点数循环实现精确周期
        y_float = 0.0
        while y_float < height:
            x_float = 0.0
            while x_float < width:
                # 将浮点坐标四舍五入到最近的整数索引
                x_idx = int(round(x_float))
                y_idx = int(round(y_float))

                # 检查索引是否在范围内
                if 0 <= x_idx < width and 0 <= y_idx < height and mask[y_idx, x_idx]:
                    # 使用浮点数坐标计算中心位置,确保精确
                    center_x = x_float * scale_factor
                    center_y = (height - y_float) * scale_factor  # 翻转Y轴

                    # 生成第一个旋转矩形
                    rect1_vertices = self_rotated_rectangle(
                        center_x, center_y,
                        rect1_length / 2.0, rect1_width / 2.0,
                        rect1_rotation
                    )

                    # 创建多边形并添加到图层
                    poly1 = pya.DPolygon(rect1_vertices)
                    top_cell.shapes(layer_index).insert(poly1)
                    rect_count += 1

                    # 生成第二个旋转矩形,位置偏移半个周期
                    offset_x = period_x / 2.0

                    rect2_vertices = self_rotated_rectangle(
                        center_x + offset_x, center_y,
                        rect2_length / 2.0, rect2_width / 2.0,
                        rect2_rotation
                    )

                    poly2 = pya.DPolygon(rect2_vertices)
                    top_cell.shapes(layer_index).insert(poly2)
                    rect_count += 1

                x_float += step_x_float
            y_float += step_y_float

        print(f"  生成旋转矩形: {rect_count} 个 (2个/单元)")
        print(f"  图层: {config['layer']}")
        total_rectangles += rect_count

    # 7. 保存GDS文件
    print(f"\n保存GDS文件: {output_gds}")
    layout.write(output_gds)

    # 获取布局边界信息
    bbox = top_cell.bbox()
    print(f"GDS布局边界: {bbox.left:.1f}, {bbox.bottom:.1f} → {bbox.right:.1f}, {bbox.top:.1f} um")
    print(f"布局尺寸: {bbox.width():.1f} × {bbox.height():.1f} um")
    print(f"总矩形数: {total_rectangles}")

    # 8. 生成预览和统计
    generate_previews(img, region_configs, region_stats, scale_factor)

    # 9. 保存配置信息
    save_configuration(region_configs, output_gds, total_rectangles, bbox)

    return region_configs, region_stats, total_rectangles


def self_rotated_rectangle(center_x, center_y, half_length, half_width, rotation_deg):
    """
    创建绕中心旋转的长方形顶点

    参数:
        center_x, center_y: 中心坐标
        half_length: 半长
        half_width: 半宽
        rotation_deg: 旋转角度(度)

    返回:
        4个顶点坐标的列表
    """
    # 将角度转换为弧度
    rotation_rad = math.radians(rotation_deg)

    # 未旋转前的四个角点(相对于中心)
    corners_rel = [
        (-half_width, -half_length),  # 左下
        (half_width, -half_length),  # 右下
        (half_width, half_length),  # 右上
        (-half_width, half_length)  # 左上
    ]

    # 旋转矩阵
    cos_theta = math.cos(rotation_rad)
    sin_theta = math.sin(rotation_rad)

    # 计算旋转后的顶点
    vertices = []
    for dx, dy in corners_rel:
        # 应用旋转
        x_rot = dx * cos_theta - dy * sin_theta
        y_rot = dx * sin_theta + dy * cos_theta

        # 平移回中心位置
        x = center_x + x_rot
        y = center_y + y_rot

        vertices.append(pya.DPoint(x, y))

    return vertices


def generate_previews(img, configs, stats, scale_factor):
    """生成预览图像"""
    fig = plt.figure(figsize=(20, 12))

    # 子图1: 原始灰度图像
    ax1 = plt.subplot(2, 4, 1)
    ax1.imshow(img, cmap='gray', vmin=0, vmax=255)
    ax1.set_title("原始花朵图像", fontsize=12, fontweight='bold')
    ax1.set_xlabel(f"宽度: {img.shape[1]} 像素")
    ax1.set_ylabel(f"高度: {img.shape[0]} 像素")

    im1 = ax1.imshow(img, cmap='gray', vmin=0, vmax=255)
    plt.colorbar(im1, ax=ax1, label='灰度值')

    # 子图2: 旋转矩形结构示意图
    ax2 = plt.subplot(2, 4, 2)
    ax2.axis('off')

    # 获取一个示例配置
    sample_config = None
    for region_name, config in configs.items():
        if 'rect_config' in config:
            sample_config = config
            break

    if sample_config:
        rect_config = sample_config['rect_config']
        unit_cell_info = "旋转矩形结构示意图\n"
        unit_cell_info += "=" * 20 + "\n\n"
        unit_cell_info += f"精确周期: {rect_config['period_x']}×{rect_config['period_y']}µm\n\n"
        unit_cell_info += f"长方形1:\n"
        unit_cell_info += f"  尺寸: {rect_config['rect1']['length']}×{rect_config['rect1']['width']}µm\n"
        unit_cell_info += f"  旋转: {rect_config['rect1']['rotation']}度\n\n"
        unit_cell_info += f"长方形2:\n"
        unit_cell_info += f"  尺寸: {rect_config['rect2']['length']}×{rect_config['rect2']['width']}µm\n"
        unit_cell_info += f"  旋转: {rect_config['rect2']['rotation']}度"

        ax2.text(0.1, 0.5, unit_cell_info, fontsize=10,
                 verticalalignment='center', linespacing=1.5,
                 transform=ax2.transAxes)

        # 绘制示意图
        ax2_sub = ax2.inset_axes([0.6, 0.2, 0.3, 0.6])
        ax2_sub.set_aspect('equal')
        ax2_sub.set_xlim(0, 1)
        ax2_sub.set_ylim(0, 1)
        ax2_sub.set_xticks([])
        ax2_sub.set_yticks([])

        # 绘制旋转矩形示意图
        angle1 = rect_config['rect1']['rotation']
        angle2 = rect_config['rect2']['rotation']

        # 使用matplotlib的旋转矩形
        from matplotlib.patches import Rectangle
        rect1 = Rectangle((0.2, 0.3), 0.3, 0.2, angle=angle1,
                          facecolor='red', alpha=0.7,
                          label=f"{angle1}°")
        rect2 = Rectangle((0.5, 0.5), 0.2, 0.3, angle=angle2,
                          facecolor='blue', alpha=0.7,
                          label=f"{angle2}°")

        ax2_sub.add_patch(rect1)
        ax2_sub.add_patch(rect2)

        # 绘制周期框
        period_box = Rectangle((0, 0), 0.8, 0.4, fill=False,
                               edgecolor='black', linestyle='--', linewidth=1)
        ax2_sub.add_patch(period_box)

        ax2_sub.annotate('', xy=(0.8, 0.2), xytext=(0, 0.2),
                         arrowprops=dict(arrowstyle='<->', color='green'))
        ax2_sub.text(0.4, 0.15, f"{rect_config['period_x']}µm", ha='center', fontsize=8)

        ax2_sub.annotate('', xy=(0.4, 0), xytext=(0.4, 0.4),
                         arrowprops=dict(arrowstyle='<->', color='green'))
        ax2_sub.text(0.45, 0.2, f"{rect_config['period_y']}µm", ha='center', fontsize=8)

        ax2_sub.legend(loc='upper right', fontsize=7)

    # 子图3: 区域划分彩色图
    ax3 = plt.subplot(2, 4, 3)

    # 创建彩色区域图
    color_img = np.zeros((*img.shape, 3), dtype=np.uint8)

    # 为每个有效区域上色
    for region_name, config in configs.items():
        if stats.get(region_name, 0) > 0:
            min_gray, max_gray = config['gray_range']
            mask = (img >= min_gray) & (img <= max_gray)
            color_img[mask] = config['color']

    ax3.imshow(color_img)
    ax3.set_title("8图层区域划分", fontsize=12, fontweight='bold')
    ax3.set_xlabel("不同颜色=不同图层")
    ax3.set_ylabel(f"共{len([s for s in stats.values() if s > 0])}个有效区域")

    # 创建图例
    from matplotlib.patches import Patch
    legend_elements = []

    for region_name, config in configs.items():
        count = stats.get(region_name, 0)
        if count > 0:
            legend_text = f"图层{config['layer']}:\n"
            legend_text += f"{config['description'][:8]}\n"
            if 'rect_config' in config:
                angle1 = config['rect_config']['rect1']['rotation']
                angle2 = config['rect_config']['rect2']['rotation']
                legend_text += f"旋转: {angle1}/{angle2}°\n"
            legend_text += f"像素:{count}"

            legend_elements.append(
                Patch(facecolor=np.array(config['color']) / 255,
                      label=legend_text, edgecolor='black'))

    if legend_elements:
        ax3.legend(handles=legend_elements, loc='upper left',
                   bbox_to_anchor=(1.05, 1), fontsize=7, framealpha=0.9, title="图层说明")

    # 子图4: 图层分布柱状图
    ax4 = plt.subplot(2, 4, 4)

    layers = []
    pixel_counts = []
    colors = []

    for region_name, config in configs.items():
        count = stats.get(region_name, 0)
        if count > 0:
            layers.append(f"L{config['layer']}")
            pixel_counts.append(count)
            colors.append(np.array(config['color']) / 255)

    if pixel_counts:
        bars = ax4.bar(range(len(layers)), pixel_counts, color=colors, edgecolor='black')
        ax4.set_xlabel('图层')
        ax4.set_ylabel('像素数量')
        ax4.set_title('各图层像素数量', fontsize=12, fontweight='bold')
        ax4.set_xticks(range(len(layers)))
        ax4.set_xticklabels(layers, fontsize=10)

        # 添加数值标签
        for bar in bars:
            height = bar.get_height()
            ax4.text(bar.get_x() + bar.get_width() / 2, height,
                     f'{int(height):,}', ha='center', va='bottom', fontsize=8)

        ax4.grid(True, alpha=0.3, axis='y')

    # 子图5: 灰度值分布直方图
    ax5 = plt.subplot(2, 4, 5)

    # 计算灰度直方图
    hist, bins = np.histogram(img.flatten(), bins=256, range=[0, 256])

    ax5.bar(bins[:-1], hist, width=1, color='gray', alpha=0.7)
    ax5.set_xlabel('灰度值')
    ax5.set_ylabel('像素数量')
    ax5.set_title('灰度值分布直方图', fontsize=12, fontweight='bold')
    ax5.set_xlim(0, 256)
    ax5.grid(True, alpha=0.3)

    # 标记配置的灰度范围
    for region_name, config in configs.items():
        if stats.get(region_name, 0) > 0:
            min_gray, max_gray = config['gray_range']
            color = np.array(config['color']) / 255
            ax5.axvspan(min_gray, max_gray, alpha=0.3, color=color)
            ax5.text((min_gray + max_gray) / 2, ax5.get_ylim()[1] * 0.9,
                     f"L{config['layer']}", ha='center', fontsize=8, color=color)

    # 子图6: 旋转角度对比图
    ax6 = plt.subplot(2, 4, 6)

    layers_angle = []
    angles1 = []
    angles2 = []
    colors_angle = []

    for region_name, config in configs.items():
        if stats.get(region_name, 0) > 0 and 'rect_config' in config:
            layers_angle.append(f"L{config['layer']}")
            angles1.append(config['rect_config']['rect1']['rotation'])
            angles2.append(config['rect_config']['rect2']['rotation'])
            colors_angle.append(np.array(config['color']) / 255)

    if layers_angle:
        x = np.arange(len(layers_angle))
        width = 0.35

        bars1 = ax6.bar(x - width / 2, angles1, width,
                        label='长方形1角度', color=colors_angle, edgecolor='black')
        bars2 = ax6.bar(x + width / 2, angles2, width,
                        label='长方形2角度', color=[c * 0.7 for c in colors_angle], edgecolor='black')

        ax6.set_xlabel('图层')
        ax6.set_ylabel('旋转角度 (度)')
        ax6.set_title('各图层旋转角度', fontsize=12, fontweight='bold')
        ax6.set_xticks(x)
        ax6.set_xticklabels(layers_angle, fontsize=10)
        ax6.legend(fontsize=9)
        ax6.grid(True, alpha=0.3, axis='y')

        # 添加数值标签
        for i, (bar1, bar2) in enumerate(zip(bars1, bars2)):
            ax6.text(bar1.get_x() + bar1.get_width() / 2, bar1.get_height(),
                     f'{angles1[i]}°', ha='center', va='bottom', fontsize=8)
            ax6.text(bar2.get_x() + bar2.get_width() / 2, bar2.get_height(),
                     f'{angles2[i]}°', ha='center', va='bottom', fontsize=8)

    # 子图7: 周期配置详情
    ax7 = plt.subplot(2, 4, 7)
    ax7.axis('off')

    config_text = "🔧 各图层精确周期配置\n"
    config_text += "=" * 20 + "\n\n"

    for region_name, config in configs.items():
        count = stats.get(region_name, 0)
        if count > 0 and 'rect_config' in config:
            config_text += f"图层{config['layer']}:\n"
            config_text += f"  {config['description']}\n"
            rect_config = config['rect_config']
            config_text += f"  矩形1: {rect_config['rect1']['length']}×{rect_config['rect1']['width']} µm\n"
            config_text += f"       旋转: {rect_config['rect1']['rotation']}度\n"
            config_text += f"  矩形2: {rect_config['rect2']['length']}×{rect_config['rect2']['width']} µm\n"
            config_text += f"       旋转: {rect_config['rect2']['rotation']}度\n"
            config_text += f"  精确周期: {rect_config['period_x']}×{rect_config['period_y']} µm\n"

            # 计算步长
            step_x = rect_config['period_x'] / 0.1
            step_y = rect_config['period_y'] / 0.1
            config_text += f"  浮点步长: {step_x:.2f}×{step_y:.2f} 像素\n\n"

    ax7.text(0.05, 0.5, config_text, fontsize=8,
             verticalalignment='center', linespacing=1.3,
             transform=ax7.transAxes)

    # 子图8: 信息汇总
    ax8 = plt.subplot(2, 4, 8)
    ax8.axis('off')

    total_pixels = img.size
    active_pixels = sum(stats.values())
    active_regions = len([s for s in stats.values() if s > 0])

    info_text = "📊 8图层旋转矩形GDS\n"
    info_text += "=" * 30 + "\n\n"
    info_text += f"图像尺寸: {img.shape[1]} × {img.shape[0]} 像素\n"
    info_text += f"总像素数: {total_pixels:,}\n"
    info_text += f"有效区域: {active_regions}/8 个\n"
    info_text += f"有效像素: {active_pixels:,} ({active_pixels / total_pixels * 100:.1f}%)\n"
    info_text += f"缩放因子: {scale_factor} µm/像素\n"
    info_text += f"GDS单位: 0.001 (1nm)\n"
    info_text += f"周期模式: 精确0.74×0.4 µm\n\n"

    info_text += "🎯 主要特性:\n"
    info_text += "• 所有图层使用旋转矩形\n"
    info_text += "• 每个单元: 2个不同角度矩形\n"
    info_text += "• 精确周期: 0.74×0.4 µm\n"
    info_text += "• 浮点步长: 确保周期精确\n"

    ax8.text(0.05, 0.5, info_text, fontsize=9,
             verticalalignment='center', linespacing=1.3,
             transform=ax8.transAxes)

    plt.suptitle("花朵GDS生成分析 (8图层旋转矩形结构, 精确周期)", fontsize=16, fontweight='bold', y=0.98)
    plt.tight_layout()

    # 保存预览图像
    plt.savefig("flower_rotated_gds_preview.png", dpi=150, bbox_inches='tight')
    print("✓ 预览图像已保存: flower_rotated_gds_preview.png")

    plt.show()


def save_configuration(configs, gds_filename, total_rects, bbox):
    """保存配置到JSON文件"""
    config_data = {}

    for region_name, config in configs.items():
        config_data[region_name] = {
            'description': config['description'],
            'gray_range': config['gray_range'],
            'layer': config['layer'],
            'datatype': config['datatype'],
            'color': config['color']
        }

        if 'rect_config' in config:
            config_data[region_name]['rect_config'] = config['rect_config']

    config_filename = gds_filename.replace('.gds', '_config.json')

    with open(config_filename, 'w', encoding='utf-8') as f:
        json.dump(config_data, f, indent=2, ensure_ascii=False)

    print(f"✓ 配置已保存: {config_filename}")

    # 生成简化的配置说明
    guide_filename = gds_filename.replace('.gds', '_guide.txt')

    with open(guide_filename, 'w', encoding='utf-8') as f:
        f.write("花朵8图层旋转矩形GDS配置说明 (精确周期)\n")
        f.write("=" * 60 + "\n\n")

        f.write("📁 文件信息:\n")
        f.write(f"GDS文件: {gds_filename}\n")
        f.write(f"生成时间: {np.datetime64('now')}\n")
        f.write(f"总矩形数: {total_rects:,}\n")
        f.write(f"布局边界: {bbox.left:.1f}, {bbox.bottom:.1f} → {bbox.right:.1f}, {bbox.top:.1f} µm\n")
        f.write(f"布局尺寸: {bbox.width():.1f} × {bbox.height():.1f} µm\n\n")

        f.write("🎨 8图层旋转矩形配置 (精确周期0.74×0.4µm):\n")
        f.write("=" * 30 + "\n")

        for region_name, config in configs.items():
            f.write(f"\n图层 {config['layer']}: {config['description']}\n")
            f.write(f"  灰度范围: {config['gray_range'][0]}-{config['gray_range'][1]}\n")

            if 'rect_config' in config:
                rect_config = config['rect_config']
                f.write(f"  结构类型: 旋转双矩形单元\n")
                f.write(f"  长方形1: {rect_config['rect1']['length']}×{rect_config['rect1']['width']} µm\n")
                f.write(f"        旋转角度: {rect_config['rect1']['rotation']}度\n")
                f.write(f"  长方形2: {rect_config['rect2']['length']}×{rect_config['rect2']['width']} µm\n")
                f.write(f"        旋转角度: {rect_config['rect2']['rotation']}度\n")
                f.write(f"  精确周期: {rect_config['period_x']}×{rect_config['period_y']} µm\n")

                # 计算步长
                step_x = rect_config['period_x'] / 0.1
                step_y = rect_config['period_y'] / 0.1
                f.write(f"  浮点步长: {step_x:.2f}×{step_y:.2f} 像素\n")

                # 计算角度差
                angle_diff = abs(rect_config['rect2']['rotation'] - rect_config['rect1']['rotation'])
                f.write(f"  角度差: {angle_diff}度\n")

            f.write(f"  数据类型: {config['datatype']}\n")
            f.write(f"  颜色: RGB{config['color']}\n")

        f.write("\n" + "=" * 60 + "\n")
        f.write("\n精确周期实现方法:\n")
        f.write("1. 使用浮点数步长: 7.4×4.0 像素\n")
        f.write("2. 浮点坐标遍历: 确保0.74µm周期精确\n")
        f.write("3. 四舍五入到最近像素: 保持图像匹配\n")
        f.write("4. 缩放因子: 0.1 µm/像素\n\n")

        f.write("使用说明:\n")
        f.write("1. 用KLayout打开GDS文件查看\n")
        f.write("2. 在KLayout中按 'F' 键打开图层面板\n")
        f.write("3. 可以独立控制每个图层的显示/隐藏\n")
        f.write("4. 所有图层都使用旋转矩形结构\n")
        f.write("5. 旋转是绕矩形中心进行的\n")

    print(f"✓ 使用指南已保存: {guide_filename}")


def main():
    print("🌸 花朵8图层旋转矩形GDS生成器 (精确周期) 🌸")
    print("\n旋转矩形配置说明:")
    print("  • 所有图层: 使用旋转双矩形结构")
    print("  • 每个单元: 2个不同角度的矩形")
    print("  • 旋转中心: 矩形几何中心")
    print("  • 角度范围: 0-360度任意角度")
    print("  • 精确周期: 0.74×0.4 µm (浮点步长实现)")
    print("  • 步长: 7.4×4.0 像素 (浮点数)")

    # 查找图像文件
    possible_files = [
        "flower.png", "flower.jpg", "flower.jpeg",
        "image.png", "image.jpg", "drawing.png",
        "input.png", "flower.bmp", "黑白花.png"
    ]

    image_file = None
    for file in possible_files:
        if os.path.exists(file):
            image_file = file
            break

    if image_file is None:
        print("\n⚠️ 未找到花朵图像文件")
        print("请将花朵图片文件放在当前目录")
        print("当前目录文件:", os.listdir('.'))
        image_file = input("\n请输入图像文件名: ").strip()
        if not os.path.exists(image_file):
            print(f"错误: 文件 {image_file} 不存在")
            return

    print(f"\n找到图像文件: {image_file}")

    # 生成GDS
    try:
        configs, stats, total_rects = create_flower_gds_with_rotated_rectangles(
            image_path=image_file,
            output_gds="flower_8layer_rotated_rect_074.gds"
        )

        if configs is None:
            print("GDS生成失败")
            return

        # 总结
        print("\n" + "=" * 70)
        print("🎉 8图层旋转矩形GDS生成完成! 🎉")
        print("=" * 70)

        active_regions = len([s for s in stats.values() if s > 0])
        active_pixels = sum(stats.values())

        print(f"\n📊 生成统计:")
        print(f"  有效区域: {active_regions}/8 个")
        print(f"  有效像素: {active_pixels:,} 个")
        print(f"  总矩形数: {total_rects:,} 个")

        print(f"\n📁 生成的文件:")
        print(f"  1. flower_8layer_rotated_rect_074.gds - 主GDS文件")
        print(f"  2. flower_8layer_rotated_rect_074_config.json - 配置文件")
        print(f"  3. flower_8layer_rotated_rect_074_guide.txt - 使用说明")
        print(f"  4. flower_rotated_gds_preview.png - 预览图像")

        # 显示各图层配置详情
        print(f"\n📏 各图层精确周期配置:")
        for region_name, config in configs.items():
            if stats.get(region_name, 0) > 0 and 'rect_config' in config:
                rect_config = config['rect_config']
                print(f"\n  图层{config['layer']}: {config['description']}")
                print(
                    f"    长方形1: {rect_config['rect1']['length']}×{rect_config['rect1']['width']} µm, {rect_config['rect1']['rotation']}度")
                print(
                    f"    长方形2: {rect_config['rect2']['length']}×{rect_config['rect2']['width']} µm, {rect_config['rect2']['rotation']}度")
                print(f"    精确周期: {rect_config['period_x']}×{rect_config['period_y']} µm")
                print(f"    浮点步长: {rect_config['period_x'] / 0.1:.2f}×{rect_config['period_y'] / 0.1:.2f} 像素")

        print(f"\n🎯 下一步:")
        print(f"  1. 用KLayout查看: klayout flower_8layer_rotated_rect_074.gds")
        print(f"  2. 放大查看旋转矩形的角度")
        print(f"  3. 验证周期是否精确为0.74µm")
        print(f"  4. 在KLayout中,可以独立控制每个图层的显示")
        print(f"  5. 查看预览图像: flower_rotated_gds_preview.png")

    except Exception as e:
        print(f"\n❌ 生成过程中出错: {e}")
        traceback.print_exc()


if __name__ == "__main__":
    # 检查所需库
    try:
        import cv2
        import pya
        import numpy as np
        import matplotlib.pyplot as plt
        import math
    except ImportError as e:
        print(f"❌ 缺少所需库: {e}")
        print("请安装以下库:")
        print("pip install opencv-python numpy matplotlib")
        print("KLayout Python API 需要单独安装")
        exit(1)

    main()

结果:

IC设计新手必看:GDS2文件从生成到查看的完整实战指南(附Python脚本示例) 本文为IC设计新手提供了GDS2文件从生成到查看的完整实战指南,包括基础概念、主流EDA工具操作流程、Python脚本示例以及常见问题解决方案。通过详细的步骤和代码示例,帮助读者快速掌握版图设计中的GDS2文件处理技能,提升IC设计效率。 阅读详情

相关推荐

Python生成GDS:版图自动化实战与避坑指南

GDSII作为半导体行业通用的版图数据格式,其层级化结构与二进制特性让批量处理和参数化生成变得困难。Python凭借丰富的开源库生态,能将重复性的版图绘制转化为可复现的脚本流程,在测试结构批量生成、版图自动化检查和工具链联动中发挥关键价值。通过理解GDSII的库、结构、元素与单位换算原理,掌握gdspy与gdstk等主流库的选型与用法,即可高效创建从简单矩形到复杂阵列的版图文件。本文从格式原理出发,深入Python生成GDS的工程实践,涵盖环境搭建、代码示例、性能优化及导入Virtuoso和KLayout的

weixin_33404102的博客 243

Python编写自定义结构的GDS文件

2. 在光刻前需要把自己设计的结构转换为GDS文件,这里我设计的是矩形,你也可以设置任何结构。Python版本只支持2.7, 3.6, 3.7, and 3.8。我试了3.9不成功。4. 用常见的Klayout或者L-Edit软件打开进行查看修改。1. 安装gdspy库。3. 效果如下图所示。

weixin_50538161的博客 2906

使用Python进行Klayout版图绘制(1/4)

作为器件研发工程师,能够绘制版图和修改版图是最基本的工作,但是在进行器件研发阶段,我们常常需要绘制不同pitch形状,尺寸的原胞结构,这些工作往往是重复且繁杂的,因为原胞有源区边缘总是整个器件版图绘制中比较难处理的地方,在使用绘图工具进行操作时,稍有不慎,就会在其中引入违反DRC规则的缝隙,并且在手动查找这些缝隙时,需要将版图的局部放大到非常大的倍数才能发现,因此,如果版图的绘制可以使用python代码来实现,将会大大简化在研发阶段版图绘制的时间以及修改版图的时间,提高研发的效率。 目前,在绘制版图中,经常

乐先生 1万+

Python-gdstk 的 API

在中,是最上层的东西,原话是这样说的,文件称为库,其中包含多个单元格。我们保存文件就是通过来保存的,在后面会看到创建的代码。

honeysuckle_luo的博客 3568

光子芯片设计自动化工具包:Python驱动的GDS版图生成与器件建模(v4.0.17)

GDSFactory 4.0.17 是面向光子集成电路开发者的Python工具包,专注自动化完成从器件建模、版图绘制到GDS文件导出的完整流程。支持波导、光栅耦合器、端口定义等基础光子元件快速构建,提供自动布线、网格对齐、填充、标注、像素化处理能力。内置标准工艺层配置(layers.py)、横截面定义(cross_section.py)、路径建模(path.py)、单元封装(cell.py)、引脚自动生成(add_pins.py)、光栅耦合器集成(add_grating_couplers.py)、布局打包(

pink的博客 293

gdsfactory 4.0.17 源码包安装与GDS版图生成实战

在Python生态中,以tar.gz结尾的软件包往往代表源码分发,需要手动解压、配置环境并安装依赖。这种安装方式虽古老,但对于依赖gdspy等编译组件的芯片版图设计库而言,却是稳定灵活的选择。gdsfactory作为面向光子芯片与硅光版图的开发框架,通过KCell对象抽象波导、弯曲等结构,并能一键导出标准GDSII文件。本文从源码包的结构检查入手,详解conda环境创建、pip本地安装及版本兼容性排查,帮助读者避开Python 3.12与gdspy wheel缺失等常见坑。随后通过最小示例演示如何定义直波导

weixin_31188927的博客 179

[python]gdspy安装后测试代码

gds源码:import gdspy结果:

FL1623863129的博客 1786

gdspy:用于创建GDSII流文件(通常为CAD布局)的Python模块

GDSPY自述文件 Gdspy是用于创建和操作GDSII流文件的Python模块。 包括用于创建复杂CAD布局的关键功能: 基于裁剪算法对多边形(AND,OR,NOT,XOR)进行布尔运算 多边形偏移(多边形的向内和向外缩放) 大型阵列集的高效多边形点解决方案 Gdspy还包括一个简单的布局查看器。 Gdspy的典型应用是在电子芯片设计,平面光波电路设计和机械工程领域。 Gdspy的未来 在尝试针对大型布局提高Gdspy的性能时,我们得出结论,达到目标的最佳方法是将库的关键部分重写为C扩展。 事实证明,除了显而易见的功能外,由于方法调用带来的开销,它对性能也有很大的影响。 最好的解决方案是用一个薄的Python包装器将整个项目重新设计为一个C ++库:因此诞生了。 因此,版本1.6将是Gdspy的最后一个主要发行版,其开发仅专注于错误修复。 鼓励用户从Gdspy迁移到Gdstk:

【亲测免费】 推荐开源项目:PHIDL——Python的高效GDS脚本库

PHIDL(Physical Hardware Interface Description Language)是一个基于Python的开放源代码GDS设计工具,它在著名的gdspy基础上进行了扩展和增强。该项目致力于将图形设计软件的易用性引入到GDS脚本环境中,让您可以更方便地创建、编辑和管理复杂的微纳米结构设计。 ## 项目技术分析 PHIDL的核心特点是其直观、快速且强大的API设计。它提...

gitblog_00059的博客 1031

gdsCAD:一个简单但功能强大的Python软件包,用于创建GDSII格式的光刻掩模

gdsCAD-Python中的简单GDSII设计 gdsCAD是一个简单但功能强大的Python软件包,用于创建,读取和操作GDSII布局文件。 它适合脚本编写和交互式使用。 它在生成带有多个增量调整对象的设计时尤其出色。 gdsCAD使用matplotlib可视化从单个几何图元到整个布局的所有内容。 文献资料 完整的文档可以在以下位置找到: /# 下载 可以通过easy_install在以下位置下载软件包以进行安装: 画廊 一个简单的例子 这是一个简单的示例,显示了一些具有对齐功能的文本的创建。 它涉及图形几何, Cell和Layout 。 结果保存为GDSII文件,并显示在屏幕上: import os.path from gdsCAD import * # Create some things to draw: amarks = templates.AlignmentMarks(

Python库 | gdsfactory-3.0.1-py3-none-any.whl

资源分类:Python库 所属语言:Python 使用前提:需要解压 资源全名:gdsfactory-3.0.1-py3-none-any.whl 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

用Python脚本高效生成GDS版图:从库选型到工程实践

GDSII是芯片版图的标准数据格式,它以二进制记录描述多边形、单元引用和文本标注,是连接设计与制造的桥梁。面对批量测试图形、参数化器件或全芯片集成需求,手工拖拽画版图效率低下且难以追溯。借助Python脚本,开发者可以用gdspy、phidl、gdstk等库自动构建GDS对象,通过循环、参数配置和引用嵌套实现从简单图形到复杂系统的快速生成。这种脚本化方案的价值在于将设计过程转化为可复现、可版本管理的工程文件,并能无缝衔接到KLayout、Virtuoso等EDA工具的DRC与验收流程,大幅缩短迭代周期。本文

weixin_29189003的博客 259

PyPI 官网下载 | gdsfactory-3.2.1.tar.gz

资源来自pypi官网。 资源全名:gdsfactory-3.2.1.tar.gz

用Python生成GDS版图:从入门到自动化实践

版图数据交换格式GDSII是半导体行业几十年来的通用语言,无论是流片、DRC/LVS还是封装制造,都离不开它。GDS本质是二进制流格式,通过图层、坐标和层次化结构描述几何图形。传统的手动版图编辑效率低下,而Python脚本可以精确、可复用地生成GDS文件,实现自动化版图设计。借助gdspy这样的轻量级库,工程师无需依赖大型EDA工具,即可在服务器上批量创建testkey阵列、参数化单元甚至完整的版图布局。从理解GDS的图层与坐标机制,到掌握单元引用和布尔运算,再到结合CSV数据驱动批量放置,Python为版

weixin_32715349的博客 273

【车辆动力学】专栏目录汇总

车辆动力学知识目录汇总

CrazyRabbit的博客 1719

从零到一:TI AWR1843 Boost EVM与DCA1000 EVM的ADC数据采集实战指南

本文详细介绍了TI AWR1843 Boost EVM与DCA1000 EVM的ADC数据采集实战指南,涵盖硬件连接、软件配置、固件烧录、雷达参数设置及数据处理等关键步骤。通过MATLAB等工具,开发者可高效实现毫米波雷达数据采集,适用于自动驾驶、工业检测等领域。

weixin_29001327的博客 971

不同格式图片转到GDS格式

其中test.jpg和test.png是你需要转格式的图片,把自己需要转格式的图片放到这个目录下就可以了,名字图省事也可以改成test的,后缀名可以按自己需要改。在图像处理中,抖动是一种减少颜色带状效应的技术,使图像看起来更平滑。因为别人问我这个怎么转,在网上找了很多,但都没有一个确切的答案,最后在GitHub上看到了一个脚本,可以解决这个问题。的图像文件进行转换,应用2倍的缩放比例,并启用抖动算法,最终生成一个单位大小为1微米、有2层的GDSII文件。在这个例子中,单位大小为1微米(1.0微米)。

weixin_74284343的博客 1780

Oracle 11g管理工具PLSQL Developer 12.0.7版本安装及汉化包安装(超详细保姆级)

1. ORACLE是数据库(Oracle服务端)。是连接数据库的客户端(Oracle客户端)。是连接oracle的可视化客户端软件。我们个人用于学习和练习的时候,选择安装1和2就够了。

2302_81846649的博客 3041

CodeX + KLayout Macro:用 Ruby 脚本自动生成光刻 GDS 版图的完整实践

用 CodeX 生成 KLayout Ruby Macro,参数化自动铺满十字 marker、文字编号与四角对准标记,一键输出可流片 GDS。文中给出可复制提示词模板、完整脚本与批处理验证方法,并说明通过 TaoToken 稳定调用 CodeX 的配置要点,从零到生成首个 GDS 约 15 分钟。详见 https://taotoken.net/?utm_source=taotoken_aicg_blog_end

weixin_42601608的博客 8

Quartus II编译时出现Error (119013): Current license file does not support the EP4CE6E22C6 device

Quartus II编译时出现Error (119013): Current license file does not support the EP4CE6E22C6 device, Quartus的安装过程不同于ISE/vivado的安装。“Current license file does not support”这种情况多出现在高版本的quartus中综合很久以前的代码,使用很早型号的FPGA或是CPLD。对于这种情况,就得在官网或是其他网站上下载包含所需Device的库文件。

夜半少年的博客 1万+

激光打标轴坐标计算分析

‌:基于坐标差的平方和开方运算,勾股定理将几何关系转化为代数计算,从而实现了从坐标到距离的精确转换‌12。直角三角形的应用从上图可以看到A,B,P三个点连起来就是一个直角三角形了。用勾股定理计算距离 C#有相关的方法直接传参数就可以了。很方便。

StevenChen的博客 314

使用Python绘制Klayout超表面版图

使用python代码来绘制Klayout的.gds超表面版图,首先在python中使用 pip install klayout命令加载 klayout工具包,接着加载将包含相位分布值和超构原子的位置信息的Layout.csv文件,这里绘制的是(n,n)个单元的PB相位超表面,Layout_VPP_lens.csv文件存储的是(n, n*3)的矩阵,其中data[0:n,0:n]是超表面每个原子的x坐标位置,data[0:n,n:2*n]是超表面每个原子的y坐标位置,data[0:n,2*n:3*n]则是每个

m0_60667496的博客 706

【深度学习基础】多任务学习(Multi-Task Learning)

多任务学习(Multi-task learning)是和单任务学习(single-task learning)相对的一种机器学习方法。在机器学习领域,标准的算法理论是一次学习一个任务,也就是系统的输出为实数的情况。复杂的学习问题先被分解成理论上独立的子问题,然后分别对每个子问题进行学习,最后通过对子问题学习结果的组合建立复杂问题的数学模型。多任务学习是一种联合学习,多个任务并行学习,结果相互影响。一次只学习一个任务(task),大部分的机器学习任务都属于单任务学习。

十二月的猫 1万+

gdsfactory性能优化:如何实现比gdspy快216倍的布局速度

gdsfactory是一款强大的Python库,专为芯片(光子学、模拟、量子、MEMS)、PCB和3D可打印对象设计而打造。它致力于让硬件设计变得更加容易、直观且有趣,让每个人都能参与构建未来。在硬件设计过程中,布局速度是至关重要的因素,而gdsfactory通过一系列性能优化,实现了比gdspy快216倍的布局速度,为设计师们带来了极大的效率提升。 ## 为什么布局速度对硬件设计如此重要?

gitblog_00979的博客 423

ESP32-S3 调试经验:使用 ESP-PROG 与内置 USB-JTAG

关键词:ESP32 调试、ESP32-S3、ESP-PROG、JTAG、VSCode、OpenOCD、GDB作为一个前端开发转硬件调试新手,我最近花了不少时间在上。因为国内开发者常用 ESP32 做 IoT 项目,但大多数教程都比较零散,有些还过时,所以我决定把这次调试经历整理下来,希望能帮到后来人。

代码简单说 Vue、JAVA、PHP、Node.js 熟练运用,接口、架构、性能全搞定。 1238

华为OD机试 - 魔法收积木 - 二进制(Java 新系统 200分)

华为OD机试 新系统 题库疯狂收录中,刷题。

学Java,找哪吒 449
上一篇: zemax学习第六天
下一篇: ZEMAX学习第7天-手机镜头光学系统设计全过程案例
贩卖日
博客等级 码龄5年 5粉丝 8原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值