analyze_TFT_refactored.py ダウンロード/コピー

analyze_TFT_refactored.py をダウンロード

analyze_TFT_refactored.py
analyze_TFT_refactored.py
  1#!/usr/bin/env python3
  2"""Analyze TFT transfer characteristics from Id-Vg Excel files.
  3
  4This script reads two Excel files, one for the linear-region transfer curve
  5and one for the saturation-region transfer curve, and calculates typical TFT
  6parameters such as Vth, mobility, SS, and Ion.
  7
  8The default input/output filenames are kept compatible with the original
  9script:
 10
 11    IdVg-Vd0.1.xlsx
 12    IdVg-Vd10.xlsx
 13
 14Default output files:
 15
 16    IdVg-Vd10_analyze.csv
 17    IdVg-Vd0.1_analyze.csv
 18    output.csv
 19    output_log.csv
 20    rootIdVg.png
 21    IdVg_LIN.png
 22"""
 23
 24from __future__ import annotations
 25
 26import argparse
 27import logging
 28import os
 29import sys
 30from dataclasses import dataclass
 31from typing import Optional
 32
 33import numpy as np
 34import pandas as pd
 35from matplotlib import pyplot as plt
 36from sklearn.linear_model import LinearRegression
 37
 38
 39# -----------------------------------------------------------------------------
 40# Default analysis parameters kept from the original script
 41# -----------------------------------------------------------------------------
 42DEFAULT_COX = 2.24e-8
 43DEFAULT_L = 50.0e-6
 44DEFAULT_W = 300.0e-6
 45DEFAULT_TARGET_CURRENT = 1.0e-10
 46DEFAULT_IOFF_THRESHOLD = 1.0e-14
 47DEFAULT_ROLLING_WINDOW = 7
 48
 49
 50@dataclass(frozen=True)
 51class AnalysisConfig:
 52    """Configuration values used for TFT parameter extraction.
 53
 54    Attributes:
 55        cox: Gate capacitance per unit area. The unit must be consistent with L,
 56            W, Id, and Vd. In the original script this was 2.24e-8.
 57        channel_length: Channel length L.
 58        channel_width: Channel width W.
 59        target_current: Current threshold used to evaluate SS and Von.
 60        ioff_threshold: Upper current threshold used for Ioff averaging.
 61        rolling_window: Window size for rolling average of the local slope.
 62    """
 63
 64    cox: float = DEFAULT_COX
 65    channel_length: float = DEFAULT_L
 66    channel_width: float = DEFAULT_W
 67    target_current: float = DEFAULT_TARGET_CURRENT
 68    ioff_threshold: float = DEFAULT_IOFF_THRESHOLD
 69    rolling_window: int = DEFAULT_ROLLING_WINDOW
 70
 71
 72@dataclass
 73class IdVgResult:
 74    """Summary values calculated from an Id-Vg curve."""
 75
 76    dataframe: pd.DataFrame
 77    vth: float
 78    max_slope: float
 79    vg_at_max_slope: float
 80    mobility: float
 81    ss: float
 82    ion: float
 83    ioff: Optional[float]
 84    ion_ioff_ratio: Optional[float]
 85    von: float
 86
 87
 88@dataclass
 89class IdVdResult:
 90    """Summary values calculated from an Id-Vd curve."""
 91
 92    dataframe: pd.DataFrame
 93    mueff: float
 94
 95
 96# -----------------------------------------------------------------------------
 97# Input and validation
 98# -----------------------------------------------------------------------------
 99def read_excel_file(path: str, label: str) -> pd.DataFrame:
100    """Read an Excel file and add a clear error message on failure.
101
102    Args:
103        path: Path to the Excel file.
104        label: Human-readable name used in error messages.
105
106    Returns:
107        DataFrame loaded from the Excel file.
108
109    Raises:
110        FileNotFoundError: If the file does not exist.
111        ValueError: If pandas cannot read the file.
112    """
113
114    if not os.path.exists(path):
115        raise FileNotFoundError(f"{label} file not found: {path}")
116
117    try:
118        return pd.read_excel(path)
119    except Exception as exc:  # pandas may raise different exceptions by engine/version
120        raise ValueError(f"Failed to read {label} Excel file: {path}") from exc
121
122
123def validate_required_columns(df: pd.DataFrame, required_columns: list[str], label: str) -> None:
124    """Validate that a DataFrame contains required columns.
125
126    Args:
127        df: DataFrame to validate.
128        required_columns: Column names required by the analysis.
129        label: Human-readable name used in error messages.
130
131    Raises:
132        ValueError: If one or more required columns are missing.
133    """
134
135    missing = [col for col in required_columns if col not in df.columns]
136    if missing:
137        raise ValueError(
138            f"{label} data is missing required columns: {missing}. "
139            f"Available columns: {list(df.columns)}"
140        )
141
142
143# -----------------------------------------------------------------------------
144# Numerical helper functions
145# -----------------------------------------------------------------------------
146def calculate_local_slope_by_linear_fit(
147    df: pd.DataFrame,
148    x_series: pd.Series,
149    y_series: pd.Series,
150    half_window: int = 1,
151) -> list[float]:
152    """Calculate local slopes by fitting y = a*x + b around each data point.
153
154    This function replaces the original ``slope3data`` and ``slope7data`` style
155    functions. With ``half_window=1``, it uses approximately three points,
156    matching the original ``slope3data`` behavior as closely as possible.
157
158    Args:
159        df: Source DataFrame. Only its length is used.
160        x_series: X values.
161        y_series: Y values.
162        half_window: Number of neighboring points on each side.
163
164    Returns:
165        List of local slopes. Points that cannot be fitted are returned as NaN.
166    """
167
168    slopes: list[float] = []
169
170    for index in range(len(df)):
171        x_window = x_series[index - half_window : index + half_window + 1]
172        y_window = y_series[index - half_window : index + half_window + 1]
173
174        valid = pd.concat([x_window, y_window], axis=1).dropna()
175        if len(valid) < 2:
176            slopes.append(np.nan)
177            continue
178
179        try:
180            x = valid.iloc[:, 0].to_numpy().reshape(-1, 1)
181            y = valid.iloc[:, 1].to_numpy()
182            model = LinearRegression().fit(x, y)
183            slopes.append(float(model.coef_[0]))
184        except ValueError as exc:
185            logging.debug("Local slope fitting failed at index %s: %s", index, exc)
186            slopes.append(np.nan)
187
188    return slopes
189
190
191def intercept_x(x: float, y: float, slope: float) -> float:
192    """Calculate the x-intercept of the line y_line = slope * (x_line - x0).
193
194    Args:
195        x: X coordinate of a point on the line.
196        y: Y coordinate of a point on the line.
197        slope: Slope of the line.
198
199    Returns:
200        X-intercept value.
201    """
202
203    if pd.isna(slope) or slope == 0:
204        return np.nan
205    return float(x - y / slope)
206
207
208def calculate_vth_by_max_slope(
209    vg_series: pd.Series,
210    y_series: pd.Series,
211    slope_series: pd.Series,
212) -> tuple[float, float, float]:
213    """Calculate threshold voltage using the maximum-slope tangent method.
214
215    Args:
216        vg_series: Gate voltage values.
217        y_series: Id or sqrt(Id), depending on the analysis mode.
218        slope_series: Local slope values.
219
220    Returns:
221        Tuple of ``(Vth, max_slope, Vg_at_max_slope)``.
222
223    Raises:
224        ValueError: If no valid slope can be found.
225    """
226
227    valid_slope = slope_series.replace([np.inf, -np.inf], np.nan).dropna()
228    if valid_slope.empty:
229        raise ValueError("No valid slope values are available for Vth calculation.")
230
231    idx = valid_slope.idxmax()
232    max_slope = float(valid_slope.loc[idx])
233    x = float(vg_series.loc[idx])
234    y = float(y_series.loc[idx])
235    vth = intercept_x(x, y, max_slope)
236    return vth, max_slope, x
237
238
239def calculate_ion_ioff(id_series: pd.Series, ioff_threshold: float) -> tuple[float, Optional[float], Optional[float]]:
240    """Calculate Ion, Ioff, and Ion/Ioff ratio.
241
242    Args:
243        id_series: Drain current values. Positive values are expected.
244        ioff_threshold: Data points satisfying ``0 < Id < ioff_threshold`` are
245            averaged to estimate Ioff.
246
247    Returns:
248        Tuple of ``(Ion, Ioff, Ion/Ioff)``. If Ioff cannot be estimated,
249        ``Ioff`` and ``Ion/Ioff`` are returned as None.
250    """
251
252    valid_id = pd.to_numeric(id_series, errors="coerce").replace([np.inf, -np.inf], np.nan)
253    ion = float(valid_id.max()) if not valid_id.dropna().empty else np.nan
254
255    ioff_data = valid_id[(valid_id > 0) & (valid_id < ioff_threshold)].dropna()
256    if ioff_data.empty:
257        return ion, None, None
258
259    ioff = float(ioff_data.mean())
260    ratio = float(ion / ioff) if ioff != 0 else None
261    return ion, ioff, ratio
262
263
264def first_index_at_or_above(series: pd.Series, threshold: float) -> Optional[int]:
265    """Return the first index where the series value is at least threshold.
266
267    Args:
268        series: Numeric series.
269        threshold: Threshold value.
270
271    Returns:
272        First matching index, or None if no point satisfies the condition.
273    """
274
275    matched = series.index[series >= threshold]
276    if len(matched) == 0:
277        return None
278    return matched.min()
279
280
281def safe_inverse(value: float) -> float:
282    """Return 1/value, or NaN if the inverse is not well-defined."""
283
284    if pd.isna(value) or value == 0:
285        return np.nan
286    return float(1.0 / value)
287
288
289# -----------------------------------------------------------------------------
290# TFT analysis functions
291# -----------------------------------------------------------------------------
292def analyze_idvg_sat(df: pd.DataFrame, config: AnalysisConfig) -> IdVgResult:
293    """Analyze saturation-region Id-Vg data.
294
295    The calculation follows the original script:
296
297    - Convert negative/non-positive Id to NaN for log and sqrt operations.
298    - Calculate log10(Id) and sqrt(Id).
299    - Calculate local slopes by three-point linear fitting.
300    - Smooth sqrt(Id) slope by centered rolling average.
301    - Calculate saturation mobility from the smoothed sqrt(Id) slope.
302    - Calculate Vth by maximum-slope tangent method.
303    - Calculate SS at the first point where Id >= target_current.
304
305    Args:
306        df: Input DataFrame. Required columns: ``Vg`` and ``Id``.
307        config: Analysis configuration.
308
309    Returns:
310        IdVgResult containing the processed DataFrame and summary values.
311    """
312
313    validate_required_columns(df, ["Vg", "Id"], "SAT Id-Vg")
314    df = df.copy()
315
316    df["Id"] = pd.to_numeric(df["Id"], errors="coerce")
317    df["Id_rm"] = np.where(df["Id"] > 0, df["Id"], np.nan)
318    df["logId"] = np.log10(df["Id_rm"])
319    df["rootId"] = df["Id_rm"] ** 0.5
320
321    df["slope logId"] = calculate_local_slope_by_linear_fit(df, df["Vg"], df["logId"], half_window=1)
322    df["slope rootId"] = calculate_local_slope_by_linear_fit(df, df["Vg"], df["rootId"], half_window=1)
323    df["slope logId"] = df["slope logId"].replace([np.inf, -np.inf], np.nan)
324    df["slope rootId"] = df["slope rootId"].replace([np.inf, -np.inf], np.nan)
325    df["slope rootId smooth"] = df["slope rootId"].rolling(config.rolling_window, center=True).mean()
326
327    df["muSAT"] = (
328        2.0
329        * config.channel_length
330        / config.channel_width
331        / config.cox
332        * (df["slope rootId smooth"] ** 2)
333    )
334    df["muSAT"] = df["muSAT"].replace([np.inf, -np.inf], np.nan)
335
336    vth, max_slope, vg_at_max_slope = calculate_vth_by_max_slope(
337        df["Vg"], df["rootId"], df["slope rootId smooth"]
338    )
339    mobility = float(df["muSAT"].max()) if not df["muSAT"].dropna().empty else np.nan
340
341    idx = first_index_at_or_above(df["Id_rm"], config.target_current)
342    if idx is None:
343        logging.warning("SAT: Id never reaches target current %.3e A. SS and Von are set to NaN.", config.target_current)
344        ss = np.nan
345        von = np.nan
346    else:
347        ss = safe_inverse(df.loc[idx, "slope logId"])
348        von = float(df.loc[idx, "Vg"])
349
350    ion, ioff, ratio = calculate_ion_ioff(df["Id_rm"], config.ioff_threshold)
351
352    return IdVgResult(
353        dataframe=df,
354        vth=vth,
355        max_slope=max_slope,
356        vg_at_max_slope=vg_at_max_slope,
357        mobility=mobility,
358        ss=ss,
359        ion=ion,
360        ioff=ioff,
361        ion_ioff_ratio=ratio,
362        von=von,
363    )
364
365
366def analyze_idvg_lin(df: pd.DataFrame, config: AnalysisConfig) -> IdVgResult:
367    """Analyze linear-region Id-Vg data.
368
369    The calculation follows the original script:
370
371    - Convert negative/non-positive Id to NaN.
372    - Calculate local slopes of Id and log10(Id).
373    - Smooth Id slope by centered rolling average.
374    - Calculate field-effect mobility from the smoothed Id slope.
375    - Calculate Vth by maximum-slope tangent method.
376    - Calculate SS at the first point where Id >= target_current.
377
378    Args:
379        df: Input DataFrame. Required columns: ``Vg``, ``Vd``, and ``Id``.
380        config: Analysis configuration.
381
382    Returns:
383        IdVgResult containing the processed DataFrame and summary values.
384    """
385
386    validate_required_columns(df, ["Vg", "Vd", "Id"], "LIN Id-Vg")
387    df = df.copy()
388
389    df["Id"] = pd.to_numeric(df["Id"], errors="coerce")
390    df["Id_rm"] = np.where(df["Id"] > 0, df["Id"], np.nan)
391    df["logId"] = np.log10(df["Id_rm"])
392
393    df["slope Id"] = calculate_local_slope_by_linear_fit(df, df["Vg"], df["Id_rm"], half_window=1)
394    df["slope logId"] = calculate_local_slope_by_linear_fit(df, df["Vg"], df["logId"], half_window=1)
395    df["slope Id"] = df["slope Id"].replace([np.inf, -np.inf], np.nan)
396    df["slope Id smooth"] = df["slope Id"].rolling(config.rolling_window, center=True).mean()
397    df["slope logId"] = df["slope logId"].replace([np.inf, -np.inf], np.nan)
398
399    df["muFE"] = (
400        config.channel_length
401        / config.channel_width
402        / config.cox
403        / df["Vd"]
404        * df["slope Id smooth"]
405    )
406    df["muFE"] = df["muFE"].replace([np.inf, -np.inf], np.nan)
407
408    vth, max_slope, vg_at_max_slope = calculate_vth_by_max_slope(
409        df["Vg"], df["Id_rm"], df["slope Id smooth"]
410    )
411    mobility = float(df["muFE"].max()) if not df["muFE"].dropna().empty else np.nan
412
413    idx = first_index_at_or_above(df["Id_rm"], config.target_current)
414    if idx is None:
415        logging.warning("LIN: Id never reaches target current %.3e A. SS and Von are set to NaN.", config.target_current)
416        ss = np.nan
417        von = np.nan
418    else:
419        ss = safe_inverse(df.loc[idx, "slope logId"])
420        von = float(df.loc[idx, "Vg"])
421
422    ion, ioff, ratio = calculate_ion_ioff(df["Id_rm"], config.ioff_threshold)
423
424    return IdVgResult(
425        dataframe=df,
426        vth=vth,
427        max_slope=max_slope,
428        vg_at_max_slope=vg_at_max_slope,
429        mobility=mobility,
430        ss=ss,
431        ion=ion,
432        ioff=ioff,
433        ion_ioff_ratio=ratio,
434        von=von,
435    )
436
437
438def analyze_idvd_lin(df: pd.DataFrame, vth: float, config: AnalysisConfig) -> IdVdResult:
439    """Analyze linear-region Id-Vd data.
440
441    This function is kept because the original script contained ``analyze_IdVd_LIN``,
442    although it was not called by the main process.
443
444    Args:
445        df: Input DataFrame. Required columns: ``Vd``, ``Vg``, and ``Id``.
446        vth: Threshold voltage used for mueff calculation.
447        config: Analysis configuration.
448
449    Returns:
450        IdVdResult containing the processed DataFrame and maximum mueff.
451    """
452
453    validate_required_columns(df, ["Vd", "Vg", "Id"], "LIN Id-Vd")
454    df = df.copy()
455
456    df["Id"] = pd.to_numeric(df["Id"], errors="coerce")
457    df["Id_rm"] = np.where(df["Id"] > 0, df["Id"], np.nan)
458    df = df.sort_values(by="Vd")
459    df["slope Id"] = calculate_local_slope_by_linear_fit(df, df["Vd"], df["Id_rm"], half_window=1)
460    df["mueff"] = (
461        config.channel_length
462        / config.channel_width
463        / config.cox
464        / (df["Vg"] - vth)
465        * df["slope Id"]
466    )
467    df["mueff"] = df["mueff"].replace([np.inf, -np.inf], np.nan)
468    mueff = float(df["mueff"].max()) if not df["mueff"].dropna().empty else np.nan
469
470    return IdVdResult(dataframe=df, mueff=mueff)
471
472
473# -----------------------------------------------------------------------------
474# Plot functions
475# -----------------------------------------------------------------------------
476def plot_idvg_lin(df: pd.DataFrame, vth: float, max_slope: float, output_path: str) -> None:
477    """Save the linear-region Id-Vg plot with maximum-slope tangent line."""
478
479    plt.figure()
480    plt.scatter(df["Vg"], df["Id"], label="Vd=0.1V", s=4)
481    df_line = max_slope * (df["Vg"] - vth)
482    plt.plot(df["Vg"], df_line, color="red")
483    plt.xlabel("Vg(V)")
484    plt.ylabel("Id(A)")
485    plt.ylim(0, 1.1 * df["Id"].max())
486    plt.legend()
487    plt.savefig(output_path)
488    plt.close()
489
490
491def plot_root_idvg(df: pd.DataFrame, vth: float, max_slope: float, output_path: str) -> None:
492    """Save the saturation-region sqrt(Id)-Vg plot with tangent line."""
493
494    plt.figure()
495    plt.scatter(df["Vg"], df["rootId"], label="Vd=10V", s=4)
496    df_line = max_slope * (df["Vg"] - vth)
497    plt.plot(df["Vg"], df_line, color="red")
498    plt.xlabel("Vg(V)")
499    plt.ylabel("Id^0.5(A^0.5)")
500    plt.ylim(0, 1.1 * df["rootId"].max())
501    plt.legend()
502    plt.savefig(output_path)
503    plt.close()
504
505
506# -----------------------------------------------------------------------------
507# Output functions
508# -----------------------------------------------------------------------------
509def output_path(output_dir: str, filename: str) -> str:
510    """Return a path inside the output directory."""
511
512    return os.path.join(output_dir, filename)
513
514
515def write_summary_outputs(sat: IdVgResult, lin: IdVgResult, output_dir: str) -> None:
516    """Write summary CSV files compatible with the original script.
517
518    This function intentionally keeps the original output column names for
519    compatibility, including ``output_log.csv`` where SS and Ion values are
520    converted to log10 without changing the column names.
521    """
522
523    df_summary = pd.DataFrame()
524
525    df_summary["Vth_SAT"] = [sat.vth]
526    # df_summary["Von_SAT"] = [sat.von]
527    df_summary["muSAT"] = [sat.mobility]
528    # df_summary["Vgmaxslope_SAT"] = [sat.vg_at_max_slope]
529    df_summary["SS_SAT"] = [sat.ss]
530    df_summary["Ion_SAT"] = [sat.ion]
531
532    df_summary["Vth_LIN"] = [lin.vth]
533    # df_summary["Von_LIN"] = [lin.von]
534    df_summary["muFE"] = [lin.mobility]
535    # df_summary["Vgmaxslope_LIN"] = [lin.vg_at_max_slope]
536    df_summary["SS_LIN"] = [lin.ss]
537    df_summary["Ion_LIN"] = [lin.ion]
538
539    df_summary.to_csv(output_path(output_dir, "output.csv"), index=False)
540
541    df_log = df_summary.copy()
542    for column in ["SS_SAT", "Ion_SAT", "SS_LIN", "Ion_LIN"]:
543        df_log[column] = np.log10(df_log[column])
544    df_log.to_csv(output_path(output_dir, "output_log.csv"), index=False)
545
546
547# -----------------------------------------------------------------------------
548# Command line interface
549# -----------------------------------------------------------------------------
550def parse_args(argv: Optional[list[str]] = None) -> argparse.Namespace:
551    """Parse command-line arguments."""
552
553    parser = argparse.ArgumentParser(
554        description="Analyze TFT Id-Vg data and calculate Vth, mobility, SS, and Ion."
555    )
556    parser.add_argument(
557        "--lin",
558        default="IdVg-Vd0.1.xlsx",
559        help="Excel file for linear-region Id-Vg data. Default: %(default)s",
560    )
561    parser.add_argument(
562        "--sat",
563        default="IdVg-Vd10.xlsx",
564        help="Excel file for saturation-region Id-Vg data. Default: %(default)s",
565    )
566    parser.add_argument(
567        "--outdir",
568        default=".",
569        help="Output directory. Default: current directory",
570    )
571    parser.add_argument(
572        "--cox",
573        type=float,
574        default=DEFAULT_COX,
575        help="Gate capacitance per unit area. Default: %(default).3e",
576    )
577    parser.add_argument(
578        "--length",
579        type=float,
580        default=DEFAULT_L,
581        help="Channel length L. Default: %(default).3e",
582    )
583    parser.add_argument(
584        "--width",
585        type=float,
586        default=DEFAULT_W,
587        help="Channel width W. Default: %(default).3e",
588    )
589    parser.add_argument(
590        "--target-current",
591        type=float,
592        default=DEFAULT_TARGET_CURRENT,
593        help="Current threshold used for SS and Von. Default: %(default).3e",
594    )
595    parser.add_argument(
596        "--ioff-threshold",
597        type=float,
598        default=DEFAULT_IOFF_THRESHOLD,
599        help="Upper current threshold used for Ioff averaging. Default: %(default).3e",
600    )
601    parser.add_argument(
602        "--rolling-window",
603        type=int,
604        default=DEFAULT_ROLLING_WINDOW,
605        help="Centered rolling-average window for slope smoothing. Default: %(default)s",
606    )
607    parser.add_argument(
608        "--verbose",
609        action="store_true",
610        help="Show detailed traceback on error.",
611    )
612    return parser.parse_args(argv)
613
614
615def validate_config(config: AnalysisConfig) -> None:
616    """Validate command-line configuration values."""
617
618    if config.cox == 0:
619        raise ValueError("cox must not be zero.")
620    if config.channel_width == 0:
621        raise ValueError("channel width must not be zero.")
622    if config.rolling_window < 1:
623        raise ValueError("rolling-window must be at least 1.")
624    if config.target_current <= 0:
625        raise ValueError("target-current must be positive.")
626    if config.ioff_threshold <= 0:
627        raise ValueError("ioff-threshold must be positive.")
628
629
630def run(args: argparse.Namespace) -> None:
631    """Run the complete analysis workflow."""
632
633    config = AnalysisConfig(
634        cox=args.cox,
635        channel_length=args.length,
636        channel_width=args.width,
637        target_current=args.target_current,
638        ioff_threshold=args.ioff_threshold,
639        rolling_window=args.rolling_window,
640    )
641    validate_config(config)
642
643    os.makedirs(args.outdir, exist_ok=True)
644
645    df_sat_input = read_excel_file(args.sat, "SAT Id-Vg")
646    df_lin_input = read_excel_file(args.lin, "LIN Id-Vg")
647
648    sat = analyze_idvg_sat(df_sat_input, config)
649    sat.dataframe.to_csv(output_path(args.outdir, "IdVg-Vd10_analyze.csv"), index=False)
650    plot_root_idvg(
651        sat.dataframe,
652        sat.vth,
653        sat.max_slope,
654        output_path(args.outdir, "rootIdVg.png"),
655    )
656
657    lin = analyze_idvg_lin(df_lin_input, config)
658    lin.dataframe.to_csv(output_path(args.outdir, "IdVg-Vd0.1_analyze.csv"), index=False)
659    plot_idvg_lin(
660        lin.dataframe,
661        lin.vth,
662        lin.max_slope,
663        output_path(args.outdir, "IdVg_LIN.png"),
664    )
665
666    write_summary_outputs(sat, lin, args.outdir)
667
668    print("Analysis finished.")
669    print(f"Output directory: {args.outdir}")
670    print(f"Vth_SAT = {sat.vth}")
671    print(f"muSAT   = {sat.mobility}")
672    print(f"SS_SAT  = {sat.ss}")
673    print(f"Ion_SAT = {sat.ion}")
674    print(f"Vth_LIN = {lin.vth}")
675    print(f"muFE    = {lin.mobility}")
676    print(f"SS_LIN  = {lin.ss}")
677    print(f"Ion_LIN = {lin.ion}")
678
679
680def main(argv: Optional[list[str]] = None) -> int:
681    """Entry point for command-line execution."""
682
683    args = parse_args(argv)
684    logging.basicConfig(
685        level=logging.DEBUG if args.verbose else logging.INFO,
686        format="%(levelname)s: %(message)s",
687    )
688
689    try:
690        run(args)
691    except Exception as exc:
692        print(f"Error: {exc}", file=sys.stderr)
693        if args.verbose:
694            raise
695        return 1
696
697    return 0
698
699
700if __name__ == "__main__":
701    raise SystemExit(main())