Commit 7ebdf61f authored by William Clarke's avatar William Clarke
Browse files

Auto conjugation and dir in mrs_vis.

parent 1d703575
......@@ -14,7 +14,8 @@ from fsl_mrs import __version__
from fsl_mrs.utils.splash import splash
from fsl_mrs.utils import mrs_io
import numpy as np
import os
import os.path as op
from os import mkdir
# NOTE!!!! THERE ARE MORE IMPORTS IN THE CODE BELOW (AFTER ARGPARSING)
......@@ -80,7 +81,6 @@ def main():
# ######################################################
# DO THE IMPORTS AFTER PARSING TO SPEED UP HELP DISPLAY
import os
import shutil
from fsl_mrs.utils import preproc
from fsl_mrs.utils import plotting
......@@ -89,7 +89,7 @@ def main():
# Check if output folder exists
overwrite = args.overwrite
if os.path.exists(args.output):
if op.exists(args.output):
if not overwrite:
print(f"Folder '{args.output}' exists."
"Are you sure you want to delete it? [Y,N]")
......@@ -100,12 +100,12 @@ def main():
exit()
else:
shutil.rmtree(args.output)
os.mkdir(args.output)
mkdir(args.output)
else:
os.mkdir(args.output)
mkdir(args.output)
# Save chosen arguments
with open(os.path.join(args.output, "options.txt"), "w") as f:
with open(op.join(args.output, "options.txt"), "w") as f:
f.write(str(args))
f.write("\n--------\n")
f.write(p.format_values())
......@@ -389,19 +389,20 @@ def main():
import glob
if args.verbose:
print('Create report')
htmlfiles = glob.glob(os.path.join(args.output, '*.html'))
htmlfiles = glob.glob(op.join(args.output, '*.html'))
subprocess.call(['merge_mrs_reports', '-d',
os.path.join(args.output, 'metab'),
op.join(args.output, 'metab'),
'-o', args.output,
'--delete']+htmlfiles)
if args.t1 is not None:
if datatype == 'NIFTI':
fig = plotting.plot_world_orient(args.t1, args.data[0])
fig.savefig(os.path.join(args.output, 'voxel_location.png'))
fig.savefig(op.join(args.output, 'voxel_location.png'))
def readData(files, conjugate):
from fsl_mrs.core import MRS
FIDlist = []
shape = None
datatype = None
......@@ -411,6 +412,11 @@ def readData(files, conjugate):
fid = np.squeeze(fid)
if conjugate:
fid = np.conj(fid)
else:
mrs = MRS(FID=fid, header=header)
mrs.check_FID(repair=True)
fid = mrs.FID
if shape is not None:
if fid.shape != shape:
raise(Exception('FIDs are incompatible in shapes'))
......@@ -429,16 +435,16 @@ def readData(files, conjugate):
def saveData(FIDlist, hdr, outputDir, basename, datatype='NIFTI'):
if len(FIDlist) == 1:
def nameGen(x, y):
return os.path.join(outputDir, f'{basename}.{y}')
return op.join(outputDir, f'{basename}.{y}')
else:
def nameGen(x, y):
return os.path.join(outputDir, f'{basename}_{x:03.0f}.{y}')
return op.join(outputDir, f'{basename}_{x:03.0f}.{y}')
for iDx, f in enumerate(FIDlist):
if datatype == 'RAW':
filename = nameGen(iDx, 'RAW')
mrs_io.lcm_io.saveRAW(filename, f, hdr)
elif datatype == 'NIFTI':
filename = nameGen(iDx, 'nii')
filename = nameGen(iDx, 'nii.gz')
mrs_io.fsl_io.saveNIFTI(filename, f, hdr)
......
......@@ -27,14 +27,19 @@ def main():
from fsl_mrs.utils.plotting import plot_spectrum, FID2Spec, plot_spectra
from fsl_mrs.utils.mrs_io import read_FID, read_basis
import matplotlib.pyplot as plt
import os.path as op
from fsl_mrs.core import MRS, MRSI
import numpy as np
from fsl_mrs.utils.preproc.combine import combine_FIDs
import nibabel as nib
from pathlib import Path
if op.isdir(args.file) or \
op.splitext(op.basename(args.file))[1].upper() == '.BASIS':
# Some logic to figure out what we are dealing with
p = Path(args.file)
nifti_files = list(p.glob('*.nii*'))
# Identify BASIS
if p.is_dir() and len(nifti_files) == 0 or \
p.suffix.upper() == '.BASIS':
basis, names, basishdr = read_basis(args.file)
fid = np.zeros(basis.shape[0])
......@@ -61,14 +66,55 @@ def main():
else:
plt.show()
elif op.isfile(args.file):
# Identify directory of nifti files
elif p.is_dir() and len(nifti_files) > 0:
mrs_obj = []
conj = 0
for f in p.glob('*.nii*'):
fid, header = read_FID(str(f), squeezeSVS=False)
if np.prod(fid.shape[:3]) > 1:
raise ValueError("Can't handle directory of CSI files."
"Pass as individual file.")
fid = np.squeeze(fid)
if fid.ndim == 1:
mrs = MRS(FID=fid, header=header)
conj += mrs.check_FID(repair=True)
mrs_obj.append(mrs)
else:
mrs_list = []
tmp_conj = 0
for ff in fid.T:
tmpmrs = MRS(FID=ff, header=header)
tmp_conj += tmpmrs.check_FID(repair=True)
mrs_list.append(tmpmrs)
conj += tmp_conj/len(mrs_list)
fidList = [m.FID for m in mrs_list]
combfid = combine_FIDs(fidList, 'svd', do_prewhiten=True)
mrs_obj.append(MRS(FID=combfid, header=header))
fig = plot_spectra(mrs_obj,
ppmlim=args.ppmlim)
if args.save is not None:
fig.savefig(args.save)
else:
plt.show()
if conj/len(mrs_obj) > 0.5:
print('Spectra were conjugated. '
'Run "fsl_proc conj" on the data.')
# Plain nifti file
elif p.is_file():
fid, header = read_FID(args.file, squeezeSVS=False)
if np.prod(fid.shape[:3]) == 1:
# SVS
conj = 0
fid = np.squeeze(fid)
if fid.ndim == 1:
mrs = MRS(FID=fid, header=header)
mrs.check_FID(repair=True)
conj = mrs.check_FID(repair=True)
fig = plot_spectrum(mrs, ppmlim=args.ppmlim)
if args.save is not None:
fig.savefig(args.save)
......@@ -76,10 +122,12 @@ def main():
plt.show()
else:
mrs_list = []
tmp_conj = 0
for f in fid.T:
tmpmrs = MRS(FID=f, header=header)
tmpmrs.check_FID(repair=True)
tmp_conj += tmpmrs.check_FID(repair=True)
mrs_list.append(tmpmrs)
conj += tmp_conj/len(mrs_list)
fidList = [m.FID for m in mrs_list]
combfid = combine_FIDs(fidList, 'svd', do_prewhiten=True)
single_mrs = MRS(FID=combfid, header=header)
......@@ -90,6 +138,11 @@ def main():
fig.savefig(args.save)
else:
plt.show()
if conj > 0.5:
print('Spectra were conjugated. '
'Run "fsl_proc conj" on the data.')
else:
if args.mask is not None:
mask_hdr = nib.load(args.mask)
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment