Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

MR Spectroscopy with LCModel

Run this notebook

Analyzing MR Spectra from Rat Hippocampus

Date: 12 Aug 2025

License:

MIT License

Note: If this notebook uses neuroimaging tools from Neurocontainers, those tools retain their original licenses. Please see Neurodesk citation guidelines for details.

Citation and Resources:

Tools included in this workflow

LCModel:

Python:

Ghostscript:

Dataset

  • Dunja Simicic, & Cristina Cudalbu. (2020). MR Spectra from rat hippocampus with LCModel quantification and the corresponding basis set [Data set]. In Magn Reson Med (Version Part1, Bd. 86, Nummer 5, S. 2384–2401). Zenodo. Dunja Simicic & Cristina Cudalbu (2020)

  • Simicic, D., Rackayova, V., Xin, L., Tkáč, I., Borbath, T., Starcuk, Z., Jr, Starcukova, J., Lanz, B., & Cudalbu, C. (2021). In vivo macromolecule signals in rat brain 1 H-MR spectra at 9.4T: Parametrization, spline baseline estimation, and T2 relaxation times. Magnetic resonance in medicine, 86(5), 2384–2401. Simicic et al. (2021)

Load software tools and import python libraries

['lcmodel/6.3']

The command below installs Ghostscript, which provides the ps2pdf utility for converting LCModel’s .ps output into a PDF, as well as tools to convert the .ps file into PNG images for easier inline viewing in notebooks and web pages.

[+] 0.0s
Fetch Shard Index for conda-forge/linux-64                                                ✔ Done (0.1 sec)
Fetch Shard Index for conda-forge/noarch                                                  ✔ Done (0.0 sec)
Fetching and Parsing Packages' Shards                                                     ✔ Done (4.7 sec)

Pinned packages:

  - python=3.13

Pinned packages:

  - python=3.13

Resolving Environment                                                                     ✔ Done (0.4 sec)

Transaction

  Prefix: /opt/conda

  Updating specs:

   - ghostscript


  Package        Version  Build       Channel         Size
────────────────────────────────────────────────────────────
  Install:
────────────────────────────────────────────────────────────

  + ghostscript  10.07.1  hecca717_0  conda-forge     63MB

  Summary:

  Install: 1 packages

  Total download: 63MB

────────────────────────────────────────────────────────────



Transaction starting
[+] 0.0s
Downloading      ╸━━━━━━━━━━━━━━━━━━━━━━   0.0 B                            0.0s
Extracting       ━━━━━━━━━━━━━━━━━━━━━━━       0                            0.0s[+] 0.1s
Downloading  (1) ━━━━━━━━━━━━━━━━━━━━━━━   1.8MB ghostscript                0.0s
Extracting       ━━━━━━━━━━━━━━━━━━━━━━━       0                            0.0s[+] 0.2s
Downloading  (1) ━━━━╸━━━━━━━━━━━━━━━━━━  16.8MB ghostscript                0.1s
Extracting       ━━━━━━━━━━━━━━━━━━━━━━━       0                            0.0s[+] 0.3s
Downloading  (1) ━━━━━━━━━╸━━━━━━━━━━━━━  29.8MB ghostscript                0.2s
Extracting       ━━━━━━━━━━━━━━━━━━━━━━━       0                            0.0s[+] 0.4s
Downloading  (1) ━━━━━━━━━━━━╸━━━━━━━━━━  38.0MB ghostscript                0.3s
Extracting       ━━━━━━━━━━━━━━━━━━━━━━━       0                            0.0s[+] 0.5s
Downloading  (1) ━━━━━━━━━━━━━━━╸━━━━━━━  46.5MB ghostscript                0.4s
Extracting       ━━━━━━━━━━━━━━━━━━━━━━━       0                            0.0s[+] 0.6s
Downloading  (1) ━━━━━━━━━━━━━━━━━━━╸━━━  55.1MB ghostscript                0.5s
Extracting       ━━━━━━━━━━━━━━━━━━━━━━━       0                            0.0sghostscript                                         62.9MB @  98.5MB/s  0.6s
[+] 0.7s
Downloading      ━━━━━━━━━━━━━━━━━━━━━━━  62.9MB                            0.6s
Extracting   (1) ━━━━━━━━━━╸━━━━━━━━━━━━       0 ghostscript                0.0s[+] 0.8s
Downloading      ━━━━━━━━━━━━━━━━━━━━━━━  62.9MB                            0.6s
Extracting   (1) ━━━━━━━━━━━╸━━━━━━━━━━━       0 ghostscript                0.1s[+] 0.9s
Downloading      ━━━━━━━━━━━━━━━━━━━━━━━  62.9MB                            0.6s
Extracting   (1) ━━━━━━━━━━━━━╸━━━━━━━━━       0 ghostscript                0.2sLinking ghostscript-10.07.1-hecca717_0

Transaction finished

/opt/conda/bin/gs
/opt/conda/bin/ps2pdf

Introduction

This example demonstrates the processing of MR spectra acquired from the rat hippocampus using LCModel, a standard tool for automatic quantification of magnetic resonance spectroscopy (MRS) data.

The example Varian-format MRS dataset is processed with LCModel to quantify metabolite concentrations. Both the example data and the corresponding basis set are provided within the Neurodesk LCModel container.

Accurate quantification of MRS data requires precise preprocessing and configuration. This example illustrates the complete workflow, from raw data conversion through LCModel setup and execution to output visualization. The pipeline consists of the following steps:

Pipeline:

  • The example dataset and basis set paths are programmatically identified within the LCModel container.

  • File existence checks ensure that required data and basis files are available.

  • The Varian FID file is converted to the raw format compatible with LCModel.

  • Visualization of raw time-domain data is performed to assess signal quality.

  • Acquisition parameters are extracted to generate the LCModel control file.

  • The control file is created with appropriate settings referencing the data and basis files.

  • LCModel analysis is executed via command line.

  • Resulting postscript (.ps) files are converted to PDF and PNG formats for easy review and sharing.

🧾 Glossary of Common Terms and Abbreviations

This tutorial involves several domain-specific terms and file formats commonly used in MR spectroscopy and LCModel workflows. Below is a brief overview of key abbreviations and concepts to help you get started.

📚 For full technical details, refer to the LCModel manual.

Software & File Formats

TermMeaning
LCModelA widely used software package for automatic quantification of in vivo proton MR spectra.
LCMguiThe graphical user interface for LCModel (optional; not used in this notebook-based workflow).
FIDFree Induction Decay — the raw time-domain MRS data typically acquired from Varian, Bruker, Siemens, or GE scanners.
.RAWLCModel-compatible input file containing unprocessed FID data in a specific ASCII format. Should not be windowed or smoothed.
.CONTROLText file that defines the analysis settings and parameters for LCModel (e.g., file paths, echo time, frequency).
.BASISA file containing simulated model spectra for known metabolites at specific TE/TR/field strength. Used by LCModel to fit your data.
.PSOptional PostScript output of LCModel’s One-Page summary, including spectra and fitted results.
extraInfoA helper file generated by bin2raw with basic scan metadata (e.g., hzpppm, echot).
cpStartAnother helper file from bin2raw, containing default parameters that could populate a .CONTROL file

Key Control Parameters

ParameterDescription
TITLEDescriptive title of the scan (will appear on output).
FILRAWPath to the .RAW file with time-domain data.
FILBASPath to the .BASIS file used to fit the spectrum.
FILPSPath to the output .PS file with the report.
HZPPPMSpectrometer frequency in MHz (e.g., 123.25).
DELTATDwell time (s), i.e., 1 / sampling frequency.
NUNFILNumber of complex points in the FID.
ECHOTEcho time (TE) in milliseconds.
DOECCWhether eddy current correction is applied (1 = yes, 0 = no).
WCONCWater concentration (used for absolute quantification).

Data conversion tools

ToolDescription
bin2rawLCModel utility to convert Varian-format data (FID + procpar) into a .RAW file. Outputs cpStart, extraInfo, and optionally an error log.
bin2ascDependency used internally by bin2raw for reading Varian binary formats.

Get example data from the container

This section locates and verifies access to the example dataset bundled inside the LCModel container. It:

  • Retrieves the path to the lcmodel executable to infer the container base directory.

  • Constructs full paths to the example Varian fid file and BASIS set directory located within the container.

  • Uses glob to select the .BASIS file (expects exactly one).

  • Verifies that the fid file and .BASIS file exist and prints their status and raises an error if any are missing.

FID path:          /cvmfs/neurodesk.ardc.edu.au/containers/lcmodel_6.3_20220222/lcmodel_6.3_20220222.simg/opt/datasets/Spectra_hippocampus(rat)_TE02/s_20131015_03_BDL106_scan0/isise_01.fid/fid
BASIS file:        /cvmfs/neurodesk.ardc.edu.au/containers/lcmodel_6.3_20220222/lcmodel_6.3_20220222.simg/opt/datasets/Spectra_hippocampus(rat)_TE02/Control_files_Basis_set/9T_TE02_smallTMS_simulated-apoL0,2Hz-apoG1,8Hz_MM-ourMM_newGrad750_allRemoved.BASIS
FID exists?        ✅
BASIS dir exists?  ✅
BASIS file exists?  ✅

Set up LCModel configuration files

This script sets up the LCModel environment by copying the hidden .lcmodel directory (containing all required binaries and configuration files) into your home folder. If the .lcmodel directory already exists, the script normally prompts whether to overwrite it — however, in a notebook environment, this prompt is not interactive. To avoid errors, the script can be conditionally run only if .lcmodel does not already exist.

Setting up lcmodel...
done.

Convert Varian FID file to LCModel-compatible .RAW format

This step uses the bin2raw utility provided by LCModel to convert a Varian-format FID dataset and its associated procpar file into a .RAW file suitable for spectral fitting in LCModel. In addition to the .RAW file, two auxiliary files are generated: cpStart and extraInfo. These are typically used by LCMgui to autofill settings, but in this notebook-based workflow, we’ll manually extract relevant parameters from extraInfo and .RAW to generate a custom control (.CONTROL) file for LCModel.

Details & Requirements for bin2raw:

  • The FID file must be named fid, with the corresponding procpar file in the same directory.

  • bin2raw assumes a voxel volume of 1.0, so water-scaling will only be accurate if the suppressed and unsuppressed water scans were acquired with identical voxel sizes.

  • bin2raw depends on a helper binary bin2asc, both of which must be located in ~/.lcmodel/varian/.

Check if the required binaries are present:

bin2asc  bin2raw  preprocessors

Run bin2raw to convert the Varian fid file into an LCModel .RAW file.

📁 Output:

This command creates the following files inside ./lcmodel_outputs/raw/:

  • .RAW: The converted LCModel-compatible spectral data.

  • cpStart: Text file containing scan parameters and file paths.

  • extraInfo: Text file providing only a subset of the scan metadata.

  • error: A plain text log file capturing any issues or warnings during conversion. It’s a good idea to check this file automatically after conversion to confirm success.

Visualizing the RAW FID data from the RAW file

The following code loads and visualizes the raw time-domain data from the .RAW file. This file contains the input data for a single rat from the Simicic and Cudalbu (2020) dataset. According to the study’s methods, the data were acquired using a single-voxel SPECIAL sequence in the rat hippocampus, with sequence timing parameters TE = 2.8 ms and TR = 4 s. The full experiment involved collecting 160 individual acquisitions (transients) to ensure a high signal-to-noise ratio.

In MRS, a transient refers to one individual acquisition of the free induction decay (FID) signal following an excitation pulse. Multiple transients are collected and typically averaged to improve data quality.

Our plot displays a subset of this data. As will be confirmed in the next step, when we extract the acquisition parameters, the file contains the first 10 of these transients, each composed of 4096 complex data points. Each large spike in the plot marks the beginning of one of these 10 transients, corresponding to the strong initial FID signal immediately following the excitation pulse.

Raw Free Induction Decay (FID) Signal:

This plot shows the unprocessed time-domain MR spectroscopy signal extracted from the .RAW file. The real (blue) and imaginary (red dashed) components represent the complex-valued FID acquired after excitation, before any frequency or phase correction. Visual inspection of the FID can help identify noise, artifacts, or unexpected decay behavior prior to Fourier transformation and spectral fitting.

<Figure size 1200x600 with 1 Axes>

Extracting parameters to generate the control file

As noted earlier, the bin2raw conversion produces auxiliary files such as cpStart and embeds a $SEQPAR block in the .RAW file. These contain key acquisition and sequence parameters needed to generate the LCModel control file. In this step, we extract those parameters by parsing both cpStart and the $SEQPAR block from the RAW file. The parsed values are merged into a single dictionary, with $SEQPAR values overriding cpStart in case of overlap. This consolidated parameter set will be used to programmatically construct the .CONTROL file for LCModel.

{'title': 's_20131015_03  (2013/10/15 22:28:27)  isise  TE/TR/NS=3/4000/16', 'filraw': './lcmodel_outputs/raw/RAW', 'filps': './lcmodel_outputs/ps', 'hzpppm': 400.268, 'deltat': 0.0002, 'nunfil': 4096, 'ndcols': 1, 'ndrows': 10, 'ndslic': 1, 'echot': 3.0}

Write and run the control file

With all required acquisition parameters parsed from the .RAW and cpStart files, we now generate the LCModel control file programmatically. This file defines the input data (.RAW), output locations (e.g., .TABLE, .PS, .CSV, .COORD), basis set, and sequence-specific parameters such as spectral width or echo time. The control file is written to disk using the write_lcmodel_control() function. Finally, LCModel is executed by piping the control file into the lcmodel command-line tool, launching the spectral fitting and quantification process.

Note: LCModel is now a free software, but still requires a license key for execution. The key = 210387309 is a universal license key provided by the developer for non-commercial academic use. It must be included in the LCModel control file (typically under the key parameter).
For details, see: http://s-provencher.com/lcmodel.shtml
--> Copying basis file to local directory...
'./lcmodel_outputs/9T_TE02_smallTMS_simulated-apoL0,2Hz-apoG1,8Hz_MM-ourMM_newGrad750_allRemoved.BASIS'
✅ CONTROL file written to ./lcmodel_outputs/control
--- Verifying content of control file ---
 $LCMODL
 title= 's_20131015_03  (2013/10/15 22:28:27)  isise  TE/TR/NS=3/4000/16'
 srcraw= '/cvmfs/neurodesk.ardc.edu.au/containers/lcmodel_6.3_20220222/lcmodel_6.3_20220222.simg/opt/datasets/Spectra_hippocampus(rat)_TE02/s_20131015_03_BDL106_scan0/isise_01.fid/fid'
 ppmst= 4.0
 ppmend= 0.2
 nunfil= 4096
 ndslic= 1
 ndrows= 10
 ndcols= 1
 ltable= 7
 lps= 8
 islice= 1
 irowst= 1
 irowen= 10
 icolst= 1
 icolen= 1
 hzpppm= 400.268
 filtab= './lcmodel_outputs/results/table'
 filraw= './lcmodel_outputs/raw/RAW'
 filps= './lcmodel_outputs/results/ps'
 filbas= './lcmodel_outputs/9T_TE02_smallTMS_simulated-apoL0,2Hz-apoG1,8Hz_MM-ourMM_newGrad750_allRemoved.BASIS'
 echot= 3.0
 deltat= 0.0002
 key= 210387309
 lcsv= 11
 filcsv= './lcmodel_outputs/results/csv'
 lcoord= 9
 filcoo= './lcmodel_outputs/results/coord'
 $END

Run lcmodel

The following command runs the LCModel software by feeding it the control file via standard input. This control file contains all necessary parameters and file references that LCModel needs to perform the spectral quantification analysis.

Note: Because the data contains multiple transients, LCModel generates separate output files for each transient, enabling detailed per-transient analysis.

Results

Exporting LCModel Output to PDF and PNG Formats

LCModel outputs PostScript (.ps) files summarizing the spectral fit results, which can be converted to other formats like PDF or to PNG images for easier viewing and sharing. Converting to PDF using ps2pdf preserves the vector graphics and multipage layout, making it suitable for high-quality printing and detailed inspection.

Alternatively, converting the .ps to PNG images with Ghostscript (gs) produces raster images (one per page) that are easy to display inline in notebooks and web pages without requiring PDF viewers.

The following gs command converts a multi-page PostScript (.ps) file into one or more high-resolution PNG images — one image per page.

Explanation of options:

OptionDescription
-dSAFERRuns Ghostscript in safe mode, restricting file access for security.
-dBATCHTells Ghostscript to exit after processing is complete.
-dNOPAUSEDisables pausing between pages — needed for automated or batch conversion.
-dAutoRotatePages=/NonePrevents Ghostscript from automatically rotating pages based on their orientation.
-sDEVICE=png16mSets the output format to PNG with 24-bit color (8 bits per RGB channel).
-r300Sets the resolution of the output images to 300 DPI (high quality).
-dFirstPage=1Starts processing from page 1. You can also add -dLastPage=N to limit how many pages are processed.
-sOutputFile=./lcmodel_outputs/results/sl1_1-1_page_%d.pngSpecifies the output filename pattern. The %d is a placeholder for the page number (e.g., page_1.png, page_2.png).
-c "<</Orientation 1>> setpagedevice"Forces portrait orientation for all output pages.
-f ./lcmodel_outputs/results/sl1_1-1.psSpecifies the input PostScript file to convert.
GPL Ghostscript 10.07.1 (2026-05-19)
Copyright (C) 2026 Artifex Software, Inc.  All rights reserved.
This software is supplied under the GNU AGPLv3 and comes with NO WARRANTY:
see the file COPYING for details.
Loading NimbusSans-Regular font from %rom%Resource/Font/NimbusSans-Regular... 3504560 2128722 1997048 697687 1 done.
Loading NimbusSans-Italic font from %rom%Resource/Font/NimbusSans-Italic... 3645176 2334640 2017248 713785 1 done.
Loading NimbusMonoPS-Bold font from %rom%Resource/Font/NimbusMonoPS-Bold... 3906992 2599041 2077848 766552 1 done.
Loading NimbusMonoPS-Regular font from %rom%Resource/Font/NimbusMonoPS-Regular... 4148608 2841738 2098048 773774 1 done.
<IPython.core.display.Image object>
<IPython.core.display.Image object>

Note on PDF viewing: PDFs can be displayed directly within Jupyter notebooks using IFrame, but this only works in interactive environments (local Jupyter, Colab, etc.). When viewing this notebook on GitHub Pages, the PDFs won’t render due to security restrictions.

# This works in Jupyter but not on GitHub Pages
IFrame("./lcmodel_outputs/results/sl1_1-1.pdf", width=1000, height=800)
💡 Helpful Hint:

To download the output PNGs or PDFs, open the file browser in the JupyterLab interface, navigate to the output directory (e.g., ./lcmodel_outputs/results/), right-click the desired file, and select Download.

<IPython.core.display.Image object>

Dependencies in Jupyter/Python

  • Using the package watermark to document system environment and software versions used in this notebook, alongside the Neurodesktop version extracted from the JUPYTER_IMAGE or NEURODESKTOP_VERSION environment variables.

Last updated: 2026-08-27T23:03:13.191437+00:00

Python implementation: CPython
Python version       : 3.13.14
IPython version      : 9.12.0

Compiler    : GCC 14.3.0
OS          : Linux
Release     : 6.8.0-111-generic
Machine     : x86_64
Processor   : x86_64
CPU cores   : 16
Architecture: 64bit

IPython   : 9.12.0
matplotlib: 3.11.0
nibabel   : 5.4.2
numpy     : 2.5.1
re        : 2.2.1

Neurodesktop version: 2026-07-11
References
  1. Provencher, S. W. (1993). Estimation of metabolite concentrations from localized                    in vivo                    proton NMR spectra. Magnetic Resonance in Medicine, 30(6), 672–679. 10.1002/mrm.1910300604
  2. Dunja Simicic, & Cristina Cudalbu. (2020). MR Spectra from rat hippocampus with LCModel quantification and the corresponding basis set. Zenodo. 10.5281/ZENODO.3904443
  3. Simicic, D., Rackayova, V., Xin, L., Tkáč, I., Borbath, T., Starcuk, Z., Starcukova, J., Lanz, B., & Cudalbu, C. (2021). In vivo macromolecule signals in rat brain 1 H‐MR spectra at 9.4T: Parametrization, spline baseline estimation, and T 2 relaxation times. Magnetic Resonance in Medicine, 86(5), 2384–2401. 10.1002/mrm.28910