layouttk 0.3.0

GDSII and OASIS layout toolkit for layer extraction, verification, and window clipping
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use layouttk::file_workflows::{self, ClipOptions, Window};
use layouttk::{DEFAULT_OAS_BUDGET, Layer, Point, ReadOptions};
use std::collections::BTreeSet;
use std::fs::File;
use std::io::{self, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

#[path = "layouttk/create.rs"]
mod create;
#[path = "layouttk/edit.rs"]
mod edit;
#[path = "layouttk/font.rs"]
mod font;
#[path = "layouttk/gds.rs"]
mod gds;
#[path = "layouttk/geometry.rs"]
mod geometry;
#[path = "layouttk/query.rs"]
mod query;
#[path = "layouttk/raster.rs"]
mod raster;
#[path = "layouttk/view.rs"]
mod view;

#[derive(Parser)]
#[command(
    version,
    about = "Create, inspect, edit, compare and convert GDSII and OASIS layouts",
    after_help = "Start with layouttk inventory chip.oas to find the top cell and layer pairs.\nUse layouttk <command> --help for examples, or layouttk describe --json for the local command index."
)]
struct Cli {
    /// Budget in bytes for retained OASIS data, independent of compressed file size.
    #[arg(long, global = true, default_value_t = DEFAULT_OAS_BUDGET)]
    oas_budget_bytes: usize,
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Create a layout from a versioned JSON specification. Use - to read stdin.
    #[command(
        after_help = "Example JSON for layouttk create input.json chip.oas:\n{\"version\":1,\"name\":\"MASK\",\"dbu_nm\":1,\"cells\":[{\"name\":\"TOP\",\"elements\":[{\"kind\":\"rectangle\",\"layer\":[7,0],\"corner1\":[0,0],\"corner2\":[100,40]}]}]}"
    )]
    Create {
        #[arg(value_name = "SPEC.json|-")]
        spec: PathBuf,
        output: PathBuf,
        /// Exact integer grid refinement. 2 halves the physical DBU and doubles all coordinates.
        #[arg(long, default_value_t = 1)]
        regrid_factor: u32,
    },
    /// Print library metadata, top cells, layers and stored element counts as JSON.
    Inspect { input: PathBuf },
    /// Scan a file for cell definitions, dependencies, layer pairs and repetition counts.
    #[command(after_help = "Example: layouttk inventory chip.oas --top TOP --layer 7/0")]
    Inventory {
        input: PathBuf,
        #[arg(long)]
        top: Option<String>,
        #[arg(long = "layer", value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
        layers: Vec<Layer>,
    },
    /// Verify stored records and placed layer geometry of two files on the same grid.
    #[command(
        after_help = "Example: layouttk verify source.gds copy.oas --left-top TOP --right-top TOP\nRead the JSON status: equal returns exit 0, different or a processing error returns exit 1."
    )]
    Verify {
        left: PathBuf,
        right: PathBuf,
        #[arg(long)]
        left_top: Option<String>,
        #[arg(long)]
        right_top: Option<String>,
        #[arg(long = "layer", value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
        layers: Vec<Layer>,
        #[arg(long, default_value_t = layouttk::hierarchy::DEFAULT_EXPANSION_LIMIT)]
        limit: usize,
        #[arg(long, default_value_t = 0.25)]
        tolerance_dbu: f64,
    },
    /// Scan a file twice and write one flat geometry cell per requested window.
    #[command(
        after_help = "Example: layouttk clip chip.oas roi.oas --top TOP --layer 7/0 --window=0,0,1000,800\nWindow coordinates are integer grid steps (DBU) in the selected top cell."
    )]
    Clip {
        input: PathBuf,
        output: PathBuf,
        #[arg(long)]
        top: String,
        #[arg(long = "window", value_parser = parse_window, value_name = "X0,Y0,X1,Y1", required = true, allow_hyphen_values = true)]
        windows: Vec<Window>,
        #[arg(long = "layer", value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
        layers: Vec<Layer>,
        #[arg(long, default_value_t = layouttk::hierarchy::DEFAULT_EXPANSION_LIMIT)]
        placement_limit: usize,
        #[arg(long, default_value_t = 4_000_000)]
        output_vertex_limit: usize,
        #[arg(long, default_value_t = 0.25)]
        tolerance_dbu: f64,
    },
    /// Check that a target format can encode the source, without creating an output.
    Check {
        input: PathBuf,
        #[arg(long, value_name = "gds|oas")]
        to: layouttk::Format,
        /// Print all destination constraints and metadata normalizations as JSON.
        #[arg(long)]
        json: bool,
        /// Exact integer grid refinement. 2 halves the physical DBU and doubles all coordinates.
        #[arg(long, default_value_t = 1)]
        regrid_factor: u32,
    },
    /// Read and rewrite a layout. The output suffix selects the format.
    Convert {
        input: PathBuf,
        output: PathBuf,
        #[arg(long, default_value_t = 1)]
        regrid_factor: u32,
    },
    /// Select layers during read and optionally retain one cell with its dependencies.
    #[command(
        after_help = "Example: layouttk extract chip.oas metal.gds --top TOP --layer 7/0\nRepeat --layer to keep more than one layer/datatype pair."
    )]
    Extract {
        input: PathBuf,
        output: PathBuf,
        #[arg(long)]
        top: Option<String>,
        #[arg(long = "layer", value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
        layers: Vec<Layer>,
        #[arg(long, default_value_t = 1)]
        regrid_factor: u32,
    },
    /// Calculate polygon and path geometry from JSON without opening a layout file.
    #[command(subcommand)]
    Geometry(geometry::Command),
    /// Compute a Boolean operation on two placed layers and write the result.
    #[command(
        after_help = "Example: layouttk boolean a.oas b.oas result.gds --op difference --left-top TOP --right-top TOP --left-layer 7/0 --right-layer 8/0 --output-layer 7/0"
    )]
    Boolean {
        left: PathBuf,
        right: PathBuf,
        output: PathBuf,
        #[arg(long)]
        op: layouttk::geometry::BooleanOp,
        #[arg(long)]
        left_top: String,
        #[arg(long)]
        right_top: String,
        #[arg(long, value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
        left_layer: Layer,
        #[arg(long, value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
        right_layer: Layer,
        #[arg(long, value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
        output_layer: Layer,
        #[arg(long, default_value_t = 0.25)]
        tolerance_dbu: f64,
        #[arg(long, default_value_t = layouttk::hierarchy::DEFAULT_EXPANSION_LIMIT)]
        limit: usize,
    },
    /// Get placed shapes, bounds, areas, labels, or cell information as JSON.
    #[command(subcommand)]
    Query(query::Command),
    /// Apply a versioned set of cell, layer, or element edits in one file write.
    #[command(after_help = edit::HELP)]
    Edit {
        input: PathBuf,
        #[arg(value_name = "EDITS.json|-")]
        spec: PathBuf,
        output: PathBuf,
        #[arg(long, default_value_t = 1)]
        regrid_factor: u32,
    },
    /// Re-express the layout on a new grid while preserving physical dimensions.
    Resample {
        input: PathBuf,
        output: PathBuf,
        /// Physical size of one new grid step in nanometres.
        #[arg(long)]
        dbu_nm: f64,
        /// Use nearest-grid rounding when an exact conversion is unavailable.
        #[arg(long, value_enum, default_value = "exact")]
        rounding: Rounding,
    },
    /// Change the physical size of a grid step, keeping stored coordinates unchanged.
    ReinterpretDbu {
        input: PathBuf,
        output: PathBuf,
        #[arg(long)]
        dbu_nm: f64,
    },
    /// Inspect GDSII units and records, hash content, or work with raw cells.
    #[command(subcommand)]
    Gds(gds::Command),
    /// Exchange binary masks with layout layers, or export a window as PNG.
    #[command(subcommand)]
    Raster(raster::Command),
    /// Export layer drawings as SVG or a self-contained HTML preview.
    #[command(subcommand)]
    View(view::Command),
    /// Export or import the stored model as versioned JSON, including properties.
    Model {
        #[command(subcommand)]
        command: edit::Model,
    },
    /// List the commands and parameters supported by this binary.
    Describe {
        /// Print the command index as JSON on stdout.
        #[arg(long)]
        json: bool,
    },
}

#[derive(Clone, Copy, ValueEnum)]
enum Rounding {
    Exact,
    Nearest,
}

type CliResult<T> = Result<T, Box<dyn std::error::Error>>;

fn read_json<T: serde::de::DeserializeOwned>(path: &Path) -> CliResult<T> {
    Ok(if path.as_os_str() == "-" {
        serde_json::from_reader(io::stdin().lock())?
    } else {
        serde_json::from_reader(BufReader::new(File::open(path)?))?
    })
}

fn write_file(path: &Path, write: impl FnOnce(&mut File) -> CliResult<()>) -> CliResult<()> {
    let dir = path
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or(Path::new("."));
    let mut temp = tempfile::NamedTempFile::new_in(dir)?;
    write(temp.as_file_mut())?;
    temp.as_file_mut().flush()?;
    temp.persist(path).map_err(|e| e.error)?;
    Ok(())
}

fn command_index(command: &clap::Command) -> serde_json::Value {
    serde_json::json!({
        "name": command.get_name(),
        "about": command.get_about().map(ToString::to_string),
        "details": command.get_after_help().map(ToString::to_string),
        "arguments": command.get_arguments().map(|arg| serde_json::json!({
            "id": arg.get_id().as_str(),
            "long": arg.get_long(),
            "short": arg.get_short(),
            "position": arg.get_index(),
            "required": arg.is_required_set(),
            "help": arg.get_help().map(ToString::to_string),
            "defaults": arg.get_default_values().iter().map(|v| v.to_string_lossy()).collect::<Vec<_>>(),
            "takes_values": arg.get_action().takes_values(),
            "repeatable": matches!(arg.get_action(), clap::ArgAction::Append | clap::ArgAction::Count),
            "choices": arg.get_possible_values().iter().map(|v| v.get_name()).collect::<Vec<_>>(),
        })).collect::<Vec<_>>(),
        "commands": command.get_subcommands().filter(|sub| sub.get_name() != "help").map(command_index).collect::<Vec<_>>(),
    })
}

fn parse_layer(value: &str) -> Result<Layer, String> {
    let (number, datatype) = value.split_once('/').ok_or("expected LAYER/DATATYPE")?;
    Ok(Layer {
        number: number.parse().map_err(|_| "invalid layer number")?,
        datatype: datatype.parse().map_err(|_| "invalid datatype")?,
    })
}

fn parse_window(value: &str) -> Result<Window, String> {
    let error = "expected four signed integers X0,Y0,X1,Y1";
    let coords = value
        .split(',')
        .map(str::parse::<i64>)
        .collect::<Result<Vec<_>, _>>()
        .map_err(|_| error)?;
    let [x0, y0, x1, y1] = coords.as_slice() else {
        return Err(error.into());
    };
    Window::new(Point { x: *x0, y: *y0 }, Point { x: *x1, y: *y1 }).map_err(|e| e.to_string())
}

fn selection<'a>(layers: &'a BTreeSet<Layer>, options: ReadOptions<'a>) -> ReadOptions<'a> {
    ReadOptions {
        layers: (!layers.is_empty()).then_some(layers),
        ..options
    }
}

fn print_report(status: &str, data: impl serde::Serialize) -> CliResult<()> {
    #[derive(serde::Serialize)]
    struct Report<'a, T> {
        schema_version: u32,
        status: &'a str,
        report: T,
    }
    let mut stdout = io::stdout().lock();
    serde_json::to_writer_pretty(
        &mut stdout,
        &Report {
            schema_version: 1,
            status,
            report: data,
        },
    )?;
    stdout.write_all(b"\n")?;
    Ok(())
}

fn report<T>(result: layouttk::Result<T>) -> layouttk::Result<T> {
    result.inspect_err(|err| {
        let _ = print_report("error", serde_json::json!({"message":err.to_string()}));
    })
}

fn run(cli: Cli) -> Result<(), Box<dyn std::error::Error>> {
    let options = ReadOptions {
        oas_budget_bytes: cli.oas_budget_bytes,
        ..Default::default()
    };
    match cli.command {
        Command::Create {
            spec,
            output,
            regrid_factor,
        } => {
            let layout = if spec.as_os_str() == "-" {
                create::read(io::stdin().lock())?
            } else {
                create::read(BufReader::new(File::open(spec)?))?
            };
            layouttk::write(layout.with_regrid(regrid_factor)?.as_ref(), output)?;
        }
        Command::Check {
            input,
            to,
            json,
            regrid_factor,
        } => {
            if !json {
                let layout = options.read(input)?;
                layouttk::check_write(layout.with_regrid(regrid_factor)?.as_ref(), to)?;
            } else {
                use layouttk::conversion::{Diagnostic, Severity};
                let report = options
                    .read(&input)
                    .map_err(|e| ("input", e))
                    .and_then(|layout| {
                        let target = layout
                            .with_regrid(regrid_factor)
                            .map_err(|e| ("regrid_factor", e))?;
                        Ok(target.conversion_diagnostics(to))
                    });
                let rows = report.unwrap_or_else(|(field, err)| {
                    vec![Diagnostic {
                        severity: Severity::Error,
                        cell: None,
                        element: None,
                        layer: None,
                        field: field.into(),
                        reason: err.to_string(),
                    }]
                });
                let can_write = rows.iter().all(|row| row.severity != Severity::Error);
                let target = match to {
                    layouttk::Format::Gdsii => "gds",
                    layouttk::Format::Oasis => "oas",
                };
                println!(
                    "{}",
                    serde_json::to_string_pretty(&serde_json::json!({
                        "file":input, "target_format":target,"regrid_factor":regrid_factor,
                        "can_write":can_write,"diagnostics":rows,
                    }))?
                );
                if !can_write {
                    return Err("conversion preflight failed".into());
                }
            }
        }
        Command::Inspect { input } => {
            let layout = options.read(input)?;
            println!("{}", serde_json::to_string_pretty(&layout.summary())?);
        }
        Command::Inventory { input, top, layers } => {
            let layers = layers.into_iter().collect();
            let inventory = report(file_workflows::inventory(
                selection(&layers, options),
                input,
                top.as_deref(),
            ))?;
            print_report("ok", inventory)?;
        }
        Command::Verify {
            left,
            right,
            left_top,
            right_top,
            layers,
            limit,
            tolerance_dbu,
        } => {
            let layers: BTreeSet<_> = layers.into_iter().collect();
            let comparison = report(file_workflows::verify(
                selection(&layers, options),
                left,
                right,
                left_top.as_deref(),
                right_top.as_deref(),
                limit,
                tolerance_dbu,
            ))?;
            let equal = comparison.geometry_equal && comparison.stored_equal;
            print_report(if equal { "equal" } else { "different" }, comparison)?;
            if !equal {
                return Err("verification found differences".into());
            }
        }
        Command::Clip {
            input,
            output,
            top,
            windows,
            layers,
            placement_limit,
            output_vertex_limit,
            tolerance_dbu,
        } => {
            let layers = layers.into_iter().collect();
            let layout = report(file_workflows::clip_file(
                input,
                &top,
                &windows,
                ClipOptions {
                    read: selection(&layers, options),
                    placement_limit,
                    output_vertex_limit,
                    tolerance_dbu,
                },
            ))?;
            report(layouttk::write(&layout, &output))?;
            let rows: Vec<_> = windows.iter().zip(&layout.cells).map(|(window, cell)|
                serde_json::json!({"cell": cell.name, "window": window, "polygons": cell.elements.len()})
            ).collect();
            print_report(
                "ok",
                serde_json::json!({
                    "file": output, "top": top, "dbu_nm": layout.dbu_meters * 1e9,
                    "dbu_meters": layout.dbu_meters, "output_kind": "flat_polygons",
                    "tolerance_dbu": tolerance_dbu, "windows": rows,
                }),
            )?;
        }
        Command::Convert {
            input,
            output,
            regrid_factor,
        } => {
            let layout = options.read(input)?;
            layouttk::write(layout.with_regrid(regrid_factor)?.as_ref(), output)?;
        }
        Command::Extract {
            input,
            output,
            top,
            layers,
            regrid_factor,
        } => {
            let layers: BTreeSet<_> = layers.into_iter().collect();
            let mut layout = selection(&layers, options).read(input)?;
            if let Some(top) = top {
                layout.retain_tree(&top)?;
            }
            layouttk::write(layout.with_regrid(regrid_factor)?.as_ref(), output)?;
        }
        Command::Geometry(command) => command.run()?,
        Command::Boolean {
            left,
            right,
            output,
            op,
            left_top,
            right_top,
            left_layer,
            right_layer,
            output_layer,
            tolerance_dbu,
            limit,
        } => {
            if !tolerance_dbu.is_finite() || tolerance_dbu <= 0.0 || limit == 0 {
                return Err("use a positive tolerance and expansion limit".into());
            }
            let a = selection(&BTreeSet::from([left_layer]), options).read(left)?;
            let b = selection(&BTreeSet::from([right_layer]), options).read(right)?;
            if a.dbu_meters != b.dbu_meters {
                return Err("input grids differ; use layouttk resample to match them".into());
            }
            let left = file_workflows::placed_rings(&a, &left_top, limit, tolerance_dbu)?;
            let right = file_workflows::placed_rings(&b, &right_top, limit, tolerance_dbu)?;
            let subject = left.get(&left_layer).map(Vec::as_slice).unwrap_or_default();
            let clip = right
                .get(&right_layer)
                .map(Vec::as_slice)
                .unwrap_or_default();
            let rings = layouttk::geometry::boolean(subject, clip, op)?;
            let polygons = layouttk::geometry::fracture(&rings, 8_190)?;
            let mut layout = layouttk::Layout::new("BOOLEAN", a.dbu_meters)?;
            let top = layout.add_cell("TOP")?;
            top.elements.extend(
                polygons
                    .into_iter()
                    .map(|points| layouttk::Element::Polygon {
                        layer: output_layer,
                        points,
                    }),
            );
            let count = top.elements.len();
            layouttk::write(&layout, &output)?;
            print_report(
                "ok",
                serde_json::json!({"file": output, "top": "TOP", "polygons": count}),
            )?;
        }
        Command::Query(command) => command.run(options)?,
        Command::Edit {
            input,
            spec,
            output,
            regrid_factor,
        } => {
            edit::run(input, spec, output, regrid_factor, options)?;
        }
        Command::Resample {
            input,
            output,
            dbu_nm,
            rounding,
        } => {
            let rounding = match rounding {
                Rounding::Exact => layouttk::GridRounding::Exact,
                Rounding::Nearest => layouttk::GridRounding::Nearest,
            };
            let layout = options.read(input)?.resample(dbu_nm / 1e9, rounding)?;
            layouttk::write(&layout, output)?;
        }
        Command::ReinterpretDbu {
            input,
            output,
            dbu_nm,
        } => {
            let layout = options.read(input)?.reinterpret_dbu(dbu_nm / 1e9)?;
            layouttk::write(&layout, output)?;
        }
        Command::Gds(command) => command.run(options)?,
        Command::Raster(command) => command.run(options)?,
        Command::View(command) => command.run(options)?,
        Command::Model { command } => command.run(options)?,
        Command::Describe { json: true } => {
            let mut clap = Cli::command();
            clap.build();
            print_report(
                "ok",
                serde_json::json!({"version": env!("CARGO_PKG_VERSION"), "cli": command_index(&clap)}),
            )?;
        }
        Command::Describe { json: false } => Cli::command().print_long_help()?,
    }
    Ok(())
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    let structured_error = matches!(
        cli.command,
        Command::Boolean { .. }
            | Command::Geometry(_)
            | Command::Query(_)
            | Command::Edit { .. }
            | Command::Resample { .. }
            | Command::ReinterpretDbu { .. }
            | Command::Gds(_)
            | Command::Model { .. }
            | Command::Raster(_)
            | Command::View(_)
    );
    match run(cli) {
        Ok(()) => ExitCode::SUCCESS,
        Err(err) => {
            if structured_error {
                let _ = print_report("error", serde_json::json!({"message": err.to_string()}));
            }
            eprintln!("layouttk: {err}");
            ExitCode::FAILURE
        }
    }
}