# BeautifulJASON AI Cookbook
This cookbook gives AI assistants and developers a compact set of reliable
patterns for working with BeautifulJASON. It is intentionally practical: start
from these recipes, then inspect the local source before using less common
properties, enum values, or JASON action names.
## When To Use Each Layer
Use `beautifuljason.JASON` when the workflow needs the external JASON
application:
- import vendor data such as `.jdf`;
- apply processing, peak picking, integration, or multiplet analysis;
- apply a JASON rules file (`.jjr`);
- export a document to PDF, image, JCAMP-DX, JDF, or another JASON-supported
output format.
Use `beautifuljason.Document` directly when the workflow only needs an existing
`.jjh5` file:
- extract spectral metadata, peaks, multiplets, bins, DOSY peaks, MS data, or
SMILEQ results;
- inspect or update graphics items in a `.jjh5`;
- add supported document items such as text, images, tables, and charts;
- read document IDs and audit log paths.
## Basic Imports
```python
import beautifuljason as bjason
```
The package root exports the main classes, including `JASON`, `Document`,
graphics item classes, data wrappers, `AuditTrail`, `AuditTrailXMLExporter`,
`Font`, `Units`, and common enums.
## Open A JJH5 File Read-Only
Use read-only mode for extraction tasks. This avoids accidental HDF5 mutation.
```python
import beautifuljason as bjason
with bjason.Document("sample.jjh5", mode="r") as doc:
print("Document ID:", doc.document_id)
print("NMR spectra:", len(doc.nmr_data))
print("Graphics items:", len(doc.items))
```
Notes:
- `Document` is a context manager.
- `doc.items` returns visual graphics items.
- `doc.nmr_data`, `doc.ms_data`, `doc.mol_data`, `doc.image_data`,
`doc.text_data`, and `doc.custom_data` return stored data objects.
## Create And Export A Document With JASON
This requires a configured JASON executable. Use `jason_config` to manage paths.
```python
import beautifuljason as bjason
jason = bjason.JASON()
with jason.create_document("sample.jdf", rules="off") as doc:
jason.save(doc, "sample.pdf")
```
Prefer absolute paths in automation scripts. Use a rules file when available:
```python
with jason.create_document("sample.jdf", rules="processing_and_report.jjr") as doc:
jason.save(doc, ["sample.jjh5", "sample.pdf"])
```
## Apply Simple Analysis Actions
Manual actions are useful for small examples. In production, rules files are
usually easier to maintain.
```python
actions = [
{"name": "peak_picking"},
{"name": "integration"},
{"name": "multiplet_analysis"},
]
with jason.create_document("proton.jdf", actions=actions) as doc:
jason.save(doc, "proton_analyzed.jjh5")
```
To apply actions to an existing document:
```python
with bjason.Document("existing.jjh5") as doc:
jason.apply_actions(doc, [{"name": "multiplet_analysis"}])
jason.save(doc, "existing_analyzed.pdf")
```
## Choose Analysis By Spectrum Type
This pattern mirrors the bundled report example: multiplet analysis for 1H 1D
spectra, peak picking for 13C and 2D spectra.
```python
items_1h = []
items_13c = []
items_2d = []
for item in doc.nmr_items:
spec = item.spec_data(0)
if spec.ndim == 2:
items_2d.append(item.id)
elif spec.spec_info.nuclides[0] == "1H":
items_1h.append(item.id)
elif spec.spec_info.nuclides[0] == "13C":
items_13c.append(item.id)
jason.apply_actions(doc, [
{"name": "multiplet_analysis", "items": items_1h},
{"name": "peak_picking", "items": items_13c + items_2d},
])
```
## Extract NMR Metadata
Use `get_param` for normalized JASON parameters and `get_orig_param` for vendor
original parameters.
```python
import beautifuljason as bjason
with bjason.Document("sample.jjh5", mode="r") as doc:
spec = doc.nmr_data[0]
title = bjason.utils.ensure_str(spec.spec_info.get_param("Title"))
solvent = bjason.utils.ensure_str(spec.spec_info.get_param("Solvent"))
nuclides = spec.spec_info.nuclides
original_start = spec.raw_data.spec_info.get_orig_param(
"parameters",
"ACTUAL_START_TIME",
)
print(title, solvent, nuclides, original_start)
```
HDF5 values can be bytes, numpy arrays, or datasets. Decode display strings with
`bjason.utils.ensure_str`.
## Work With NMR Peaks, Multiplets, Bins, And DOSY Peaks
```python
with bjason.Document("sample.jjh5", mode="r") as doc:
spec = doc.nmr_data[0]
for peak in spec.peaks:
print("peak", peak.pos, peak.height, peak.area)
for multiplet in spec.multiplets:
print("multiplet", multiplet.range, multiplet.value_hz)
for bin_item in spec.bins:
print("bin", bin_item.range, bin_item.value_sum, bin_item.value_average)
for dosy_peak in spec.dosy_peaks:
print("dosy", dosy_peak.pos, dosy_peak.height)
```
Property availability depends on what JASON or rules wrote into the `.jjh5`.
Check for empty lists before assuming analysis has been performed.
## Convert NMR Units
Use the built-in converter instead of hand-written formulas.
```python
with bjason.Document("sample.jjh5", mode="r") as doc:
spec = doc.nmr_data[0]
converter = spec.create_unit_converter(dim=0)
point = converter.ppm_to_point(7.26)
index = converter.ppm_to_index(7.26)
ppm_scale = converter.ppm_scale
```
The converter supports frequency-domain units such as `HZ`, `KHZ`, `MHZ`,
`PPM`, and `FPTS`, and time-domain units such as `S`, `MS`, `US`, `NS`,
`TPTS`, and `TVIRT`.
## Customize Spectrum Appearance
```python
font = bjason.Font.default_font()
font["family"] = "Arial"
font["point_size"] = 12
for item in doc.nmr_items:
item.header = "Processed spectrum"
item.header_font = font
item.x_font = font
item.plot_1d_color = "#3556D8"
item.show_y_axis = item.spec_data(0).ndim != 1
```
Colors are typically `#RRGGBB` or `#RRGGBBAA` strings depending on the property.
Fonts are stored in JASON/Qt-compatible string form through `bjason.Font`.
## Add Tables To A Report
Use `Document.create_*` helpers so links and IDs are created consistently.
```python
for spec_item in doc.nmr_items:
spec = spec_item.spec_data(0)
params = doc.create_params_table(spec_item, spec)
params.pos = (spec_item.pos[0], spec_item.pos[1] + spec_item.size[1] + 20)
params.size = spec_item.size
if spec.ndim == 1 and spec.spec_info.nuclides[0] == "1H":
table = doc.create_nmrmultiplets_table(spec_item, spec)
else:
table = doc.create_nmrpeaks_table(spec_item, spec)
table.show_title = True
table.alternating_row_colors = True
```
For column IDs, inspect the relevant class enum before writing code:
- `bjason.NMRPeakTableGraphicsItem.ColumnID`
- `bjason.NMRMultipletTableGraphicsItem.ColumnID`
- `bjason.MSCentroidTableGraphicsItem.ColumnID`
- `bjason.MSPeakTableGraphicsItem.ColumnID`
## Add Text And Images
```python
text_item = doc.create_text_item("Report
Generated by BeautifulJASON")
text_item.pos = (20, 20)
text_item.size = (300, 60)
image_data = doc.create_image_data("logo.png")
image_item = doc.create_image_item(image_data.id)
image_item.pos = (400, 20)
image_item.size = (120, 60)
```
`create_image_data` stores pixels in the document. `create_image_item` places
that stored image on a page.
## Add A Chart From A Table
```python
chart = doc.create_chart_item()
series = chart.add_series(
table.id,
bjason.NMRPeakTableGraphicsItem.ColumnID.POS0,
bjason.NMRPeakTableGraphicsItem.ColumnID.VOLUME,
)
series.name = "Peak volume"
chart.title = "Peak volumes"
chart.pos = (20, 20)
chart.size = (400, 300)
```
Charts reference table columns. Make sure the table exists and uses compatible
column IDs.
## Read MS Data
```python
with bjason.Document("sample.jjh5", mode="r") as doc:
for ms in doc.ms_data:
title = bjason.utils.ensure_str(ms.spec_info.get_param("Title"))
print(title)
for item in doc.ms_items:
ms_entry = item.spec_data(0)
print(item.header, ms_entry.id)
```
MS support includes `MSEntry`, `MSSpecInfo`, `MSSpectrumGraphicsItem`,
`MSCentroidTableGraphicsItem`, and `MSPeakTableGraphicsItem`.
## Read SMILEQ Results
SMILEQ data is stored as custom data. Cast matching custom data to
`SMILEQData`.
```python
with bjason.Document("smileq_result.jjh5", mode="r") as doc:
for custom in doc.custom_data:
if custom.data_type_id == bjason.SMILEQData.DATA_TYPE_ID:
smileq = custom.as_type(bjason.SMILEQData)
print("sample", smileq.sample_name)
print("reference", smileq.reference_name)
for quantity in smileq.quantities:
print(quantity.analyte_name, quantity.molarity.average)
```
SMILEQ supports internal/external standards, mixtures, CCF scenarios, reference
ranges, analytical options, parameter modes, and calculated molarity/purity
values with standard deviations.
## Export Audit Trails
The document can store paths to JASON log files. Parse the log file and export
XML or HTML.
```python
with bjason.Document("sample.jjh5", mode="r") as doc:
logfile_path = doc.logfile_path
trail = bjason.AuditTrail(logfile_path)
print(trail.jason_version, trail.is_complete, trail.is_hash_valid)
exporter = bjason.AuditTrailXMLExporter(trail)
exporter.save_xml("audit.xml")
```
HTML export requires the optional audit dependency:
```python
exporter.save_html("audit.html")
```
Install with `pip install beautifuljason[audit]` when needed.
## Batch Convert Files
The CLI has a dry-run mode by default:
```bash
jason_batch_convert ./input ./output --formats pdf jjh5 --extensions jdf
```
Execute conversion explicitly:
```bash
jason_batch_convert ./input ./output --formats pdf jjh5 --extensions jdf --rules report.jjr --execute
```
Use `--patterns` for directory layouts such as vendor folders:
```bash
jason_batch_convert ./input ./output --formats jjh5 --patterns */10/fid --execute
```
## Extract Integrals To CSV
```bash
batch_extract_integrals ./jjh5_files output.csv -p parameters/ACTUAL_START_TIME jason_parameters/SpectrometerFrequencies[0]
```
This tool expects `.jjh5` files that already contain multiplet integrals, often
created by converting with rules that perform integration or multiplet analysis.
## Configure JASON Paths
```bash
jason_config --display
jason_config --add_path "C:\Program Files\JEOL\JASON\JASON.exe"
jason_config --set_preferred 3
```
The configuration file is stored in the user's home directory under
`.beautifuljason/config.ini`.
## Common Pitfalls
- Do not use `JASON` examples for environments where JASON is not installed.
- Do not mutate `.jjh5` files in extraction examples; open them with `mode="r"`.
- Do not manually create HDF5 groups for graphics items unless there is no
helper. The helper methods set IDs and linked IDs.
- Do not assume every spectrum has peaks, multiplets, bins, or DOSY results.
Those are analysis outputs and may be absent.
- Do not assume strings are Python `str`; decode HDF5 byte values with
`bjason.utils.ensure_str`.
- Do not hard-code table column IDs from memory. Use the local enum classes.
- Do not use `NMRParamTableGraphicsItem` in new examples; it is an alias kept
for compatibility. Use `ParamTableGraphicsItem`.
- Do not treat audit XML/HTML as the authoritative audit record. Preserve the
original JASON log when integrity matters.
## Where To Look Next
- For process execution, plugins, actions, rules, and saving, read
`src/beautifuljason/jason.py`.
- For document structure and creation helpers, read
`src/beautifuljason/document.py`.
- For spectra, metadata, unit conversion, molecules, custom data, and SMILEQ,
read `src/beautifuljason/data.py`.
- For layout and appearance properties, table columns, charts, cuts, and item
types, read `src/beautifuljason/graphics.py`.
- For audit parsing and export, read `src/beautifuljason/audit.py`.
- For full runnable examples, read `src/beautifuljason/examples/`.