This document describes the scripts contained in src/scripts and its subfolders. For each script we list the relative path, a verbose description of behavior, inputs/outputs, and notes on where results are written.
- Location root:
src/scripts - Subfolders:
dynamic_selection_sims/(orbit simulation — see alsocontinuous_dynamic.mdfor the math behind the control policy),hardware_characterization/(withplotting/), andutils/ - Common outputs:
- Saleae captures and raw CSVs (digital/analog) →
results/captures/*/saleae_raw - Processed plots →
results/plotsor script-specificoutput_dir - Measurement CSVs (e.g., inference results) →
inference_results.csvor user-specified file - Merged model performance map →
data/compiled_characterization.json(produced byutils/characterization_ouput.py, consumed bydynamic_selection_sims/selection_case_studies.py)
- Saleae captures and raw CSVs (digital/analog) →
- Purpose: Full automation of firmware build, board flash, and capture collection for EdgeTPU-compiled models.
- Behavior: For each compiled
_edgetpu.tflitemodel it can (optionally) build the coralmicro firmware (via CMake + Make), flash the target board using the coralmicro flashtool, and then call the Saleae Logic 2 automation API to perform a timed capture. After capture it uses theSaleaeOutputParsinghelper to compute average inference time and energy metrics. - Inputs: model directory (
--model_dir, defaults to~/Coral-TPU-Characterization/data/models/edgeTPU_acc— a path from an earlier name of this project; pass--model_direxplicitly to point at e.g.data/models/coral_target), capture directory, serial port (--port, default/dev/ttyACM0), shunt resistance and supply voltage, build/test flags. - Outputs: One capture folder per run (default
results/captures/<model_stem>_<timestamp>/saleae_raw) and aninference_results.csvwith rows: model, avg inference time (ms), average energy per inference (J or mJ), category. - Notes: Relies on the
saleae.automationpackage and a local Saleae Manager; requires correct serial port and coralmicro flashtool available on PATH.
- Purpose: Generate comparative plots across model sweeps (image classification, object detection, etc.) using Saleae-derived power/latency metrics and spreadsheet metadata.
- Behavior: Collects measured latency/power using
SaleaeOutputParsing, combines these with Excel metadata (accuracy, quoted latency), computes derived metrics (Inf/s, Inf/J, Correct Inf metrics) and produces multi-panel figures (parameter count, latency, accuracy, combined quoted vs measured plots) written to a user-specifiedplotdirorresults/plots. - Inputs: Excel metadata workbook + run directories under
results/capturesor an explicit directory pointer. - Outputs: PNG plots (e.g.,
img_class_plot.png,img_class_combined.png) and optionally appended Excel sheets with collected/derived values. - Notes: Exposes
ModelStatsPlottingclass for programmatic use and helper functions for quick analyses (e.g.,jacknet_sweep_plot).
- Purpose: Aggregate grid sweep JSON metrics and Saleae measurements for the custom Grid/TpuNet model family and produce rich plotting tools and champion-finding helpers.
- Behavior:
GridStatsPlottingloads JSON evaluation files (e.g.,Grid_A0.25_D02_quant_eval.json), finds corresponding Saleae captures (searchingsaleae_rawlocations), usesParamCountsto attach parameter counts, derives efficiency/throughput metrics and provides several plotting methods (standard metrics, grouped metrics by alpha/depth, efficiency overviews, 3D surfaces). - Inputs: Directory of JSON metric files,
saleae_rootpointing to the base captures directory, and anoutput_dirfor plots. - Outputs: Multiple PNGs (grid metrics, grouped metrics, 3D surfaces) saved under the provided
output_dir. - Notes: Designed to be robust to missing JSONs or missing Saleae runs (will warn and skip missing entries).
- Purpose: Parse Saleae captures produced by the
model_swaps.ccfirmware application (see../model_swaps.cc) into the model-switching cost dataset used by the switching-cost case studies. - Behavior: Expects each capture to expose digital channels
CH0(Inference) andCH1(Switching) and analog channelsCH2/CH3/CH4(voltage before/after shunt, VSYS). Walks a directory of per-alpha/per-depth capture subfolders (seeRUN_CONFIG), computes average inference time and average model-switch energy/time per model, and writes the aggregated result tomodel_switching_results.json. - Inputs: A local directory of raw Saleae captures, one subfolder per
(alpha, depth)run. - Outputs:
model_switching_results.jsonat the repository root. - Notes:
BASE_DIRandRUN_CONFIGat the top of the script are hardcoded to the author's local capture layout — edit them to point at your own capture directory and folder names before running.
- Purpose: Core continuous-time satellite simulation engine used by all per-orbit case studies. Implements
ContinuousSatSim, whose control policy, energy budgeting, and workload model are described in detail incontinuous_dynamic.md. - Behavior: Loads STK orbit/lighting data (via
stk_utils.load_orbit_data), loads the compiled model performance map (data/compiled_characterization.json), and time-steps through an orbit computing per-frame imaging demand, a predictive energy budget (targeting a full battery at eclipse entry and a safe floor at eclipse exit), and a greedy model choice that maximizes(inferences possible) × accuracywithin that budget. Also runs a naive hysteresis baseline and a static (single fixed model) baseline for comparison, and produces plots/CSVs per case study viarun_case_study(...). - Inputs: STK CSV directory (
data/stk), compiled characterization JSON, per-orbit configuration (battery capacity, solar generation, baseload, thresholds — seeget_sso_config()/get_heo_config()), and optionalevents(transient demand/power perturbations, e.g. a data-collection burst). - Outputs: Per case study, writes plots and CSVs under
results/case_studies/<orbit>/(cumulative yield, delivered yield, energy margin, throughput margin, orbit dynamics, frame budgets CSV) and prints a summary to stdout. - Notes: Not meant to be run directly — invoked by the per-orbit case study scripts below.
- Purpose: Entry-point scripts that configure and run
ContinuousSatSimcase studies for the equatorial-LEO, sun-synchronous, and highly-elliptical orbit regimes respectively. - Behavior: Each constructs a
ContinuousSatSimfor its orbit (sat_prefix='eLEO' | 'SSO' | 'HEO'), applies that orbit's baseline config, and callsrun_case_study(...)one or more times — including some orbit-specific perturbation scenarios (e.g. a perigee data-collection burst or a power-starved perigee pass for HEO) that are commented out by default. - Inputs:
data/compiled_characterization.json,data/stk. - Outputs:
results/case_studies/eleo/,results/case_studies/sso/, andresults/case_studies/heo/respectively (theheooutput directory does not exist yet underresults/case_studies— it is created on first run). - Notes: Run directly, e.g.
python SSO_Cases.py, from withindynamic_selection_sims/. Each script'stry/exceptfallback to resolveROOT_DIRreferences an old package path (libs.coral_tpu_characterization...) that no longer exists in this repository; theexcept ImportErrorbranch (resolve relative to the current working directory) is what actually runs today.
- Purpose: Load and clean STK-exported orbit/lighting CSVs for use by
ContinuousSatSim. - Behavior:
parse_lighting_schedule()extracts sunlight start/stop intervals from an STK lighting-times export;load_orbit_data()merges the position/velocity, classical orbital elements, and LLA position exports for a given satellite prefix (e.g.SSO,HEO,eLEO) into a single DataFrame, plus aninterpolate_orbit()helper for resampling onto the simulation's time step. - Inputs: Directory of STK CSV exports (
data/stk) and a satellite prefix matching the STK filenames. - Outputs: A cleaned pandas DataFrame plus a list of sunlight intervals, ready for simulation.
- Purpose: Shared plotting helpers for the case study outputs produced by
selection_case_studies.py. - Behavior: Sets a consistent small-multiples plot style (
set_plot_style()), assigns consistent per-model colors from a perceptually-uniform colormap while keeping non-compute states (idle/recharge/blind/blocked) a fixed gray (_get_model_colors()), and provides the figure-generating functionsrun_case_study()calls for each plot type (cumulative yield, delivered yield, energy margin, throughput margin, orbit dynamics, static-vs-dynamic comparison). - Inputs: The per-step decision DataFrame produced by a
ContinuousSatSimrun. - Outputs: PNG/PDF figures saved to the case study's output directory.
- Purpose: Core parser for Saleae Logic 2 raw CSV outputs (digital and analog channels).
- Behavior:
SaleaeOutputParsinglocatesdigital.csvandanalog.csv(insaleae_rawfolders), extracts rising/falling edge times, computes average inference time, average power and energy per inference (with optional idle subtraction), and provides plotting helpers such asplot_saleae_trace()for diagnostics. - Inputs: Directory containing
digital.csvandanalog.csv; parameters for PSU voltage and shunt resistance. - Outputs: Programmatic metrics (avg inference time [s], avg power [W], energy per inference [J]) and optional diagnostic PNGs.
- Notes: Saves/loads computed idle power at
results/captures/idle_power/idle.csvto allow subtracting idle consumption across runs.
- Purpose: Count model parameters from
.tflitefiles using FlatBuffers and the TFLite schema. - Behavior: Walks a provided directory, loads each
.tflitemodel, inspects buffers and tensor types, and calculates total parameter count (raw element counts) while handling different tensor data types (float32, int8, etc.). - Inputs: Directory root to scan for
.tflitefiles. - Outputs: A tuple
(list_of_counts, dict_name_to_count)and optionally aparam_counts.jsonwhen run directly in a script context. - Notes: Intended for CPU
.tflitemodels — when using EdgeTPU compiled models, parameter arrays may differ or be fused; interpret with care.
- Purpose: Produce a clean, merged DataFrame combining Excel metadata (accuracies, quoted latencies) with Saleae-collected measurements for downstream plotting or simulations.
- Behavior:
ModelDataManagerscans aresults/captures-like directory for Saleae runs, loads the referenced Excel sheet (Img_Classby default), aligns measured runs with metadata, coalesces measured vs quoted accuracy, drops invalid rows, and computes derived metrics (Inf_per_Sec,Inf_per_Joule,Correct_Inf_per_Sec,Correct_Inf_per_Joule). - Inputs: Path to Excel workbook and results directory containing Saleae captures.
- Outputs: A tidy pandas DataFrame ready for plotting or simulation.
- Purpose: Build
data/compiled_characterization.json— the single merged dataset (pretrained + custom models) thatselection_case_studies.pyreads as its model performance map. - Behavior: Defines its own
ModelDataManager(a variant of the one inmodel_data_manager.py) to compile pretrained-model Saleae/Excel data, usesGridStatsPlotting(fromhardware_characterization/plotting/tpunet_plotting.py) to compile the custom Grid/TpuNet models, unifies both into a common schema (Model name, inference time, energy per inference, accuracy,Source), drops rows with missing numeric data, and writes the result as JSON viagenerate_unified_dataset(...). - Inputs: Excel metadata workbook, pretrained-model Saleae capture directory, custom-model JSON directory (
data/tpunet_acc), custom-model Saleae capture directory. - Outputs:
data/compiled_characterization.json. - Notes: The
__main__block hardcodes the author's local absolute paths (under~/CoralGUI/...) for the Excel workbook and Saleae capture directories — treat it as a template and edit those paths (or callgenerate_unified_dataset()directly with your own paths) rather than running it as-is. The filename keeps its original spelling (ouput).
- Purpose: Locate the repository root and provide a single canonical method to build absolute paths within scripts.
- Behavior:
get_repo_root()prefers theCORAL_REPOenvironment variable if set, then climbs parent directories from the calling file location looking for a.gitdirectory or a siblinglibs/+results/pair, then falls back to a few hardcoded personal directory names from earlier iterations of this project. In a normal git checkout the.gitmarker always matches first, so the legacy fallbacks are effectively dead code. - Inputs: None (auto-detects from file location); optional env var
CORAL_REPOcan set path explicitly. - Outputs:
pathlib.Pathpointing to the repository root. - Notes: This function is used widely in scripts to build paths independent of the current working directory.