def test_sub_kwargs(): """ Test creating a sub workspace with kwargs """ wsp = Workspace() wsp.sub("child", wibble="squid", pudding=4) assert(isinstance(wsp.child, Workspace)) assert(wsp.child.wibble == "squid") assert(wsp.child.pudding == 4)
def test_t1im(): """ Check T1 image priors are correctly handled """ d = np.random.rand(5, 5, 5, 6) img = AslImage(name="asldata", image=d, tis=[1.5], order="prt") wsp = Workspace(infertiss=True, inferbat=True, infert1=True) wsp.t1im = Image(np.random.rand(5, 5, 5)) steps = basil.basil_steps(wsp, img) assert (len(steps) == 2) options = _get_defaults(img) _check_step(steps[0], desc_text="tissue", options=dict(options, **{ "inct1": True, })) _check_step( steps[1], desc_text="T1", options=dict( options, **{ "inct1": True, "infert1": True, "PSP_byname1": "T_1", "PSP_byname1_type": "I", #"PSP_byname1_image" : "t1file", }))
def test_sub(): """ Test sub-workspaces """ wsp = Workspace() wsp.sub("child") assert(isinstance(wsp.child, Workspace)) assert(wsp.child.wibble is None) assert(wsp.child.log == wsp.log)
def test_pvc(): """ FIXME we need to test the PVC initialization step and how to do this is not finalized """ d = np.random.rand(5, 5, 5, 6) img = AslImage(name="asldata", image=d, tis=[1.5], order="prt") wsp = Workspace(infertiss=True, inferbat=True) wsp.pgm = Image(np.random.rand(5, 5, 5)) wsp.pwm = Image(np.random.rand(5, 5, 5)) steps = basil.basil_steps(wsp, img) assert (len(steps) == 3) options = _get_defaults(img) # options.update({ # "incpve" : True, # }) _check_step(steps[0], desc_text="tissue", options=options) # _check_step(steps[1], desc_text="PVE", options=options) options.update({ "method": "spatialvb", "param-spatial-priors": "N+", "PSP_byname1": "ftiss", "PSP_byname1_type": "M", "max-iterations": 200, "convergence": "maxits", }) options.pop("max-trials") _check_step(steps[2], desc_text="spatial")
def main(): """ Entry point for BASIL command line application """ try: parser = AslOptionParser(usage="basil -i <ASL input file> [options...]", version=__version__) parser.add_category(image.AslImageOptions()) parser.add_category(BasilOptions()) parser.add_category(GenericOptions()) options, _ = parser.parse_args() if not options.output: options.output = "basil" if not options.asldata: sys.stderr.write("Input file not specified\n") parser.print_help() sys.exit(1) wsp = Workspace(savedir=options.output, separate_input=True, auto_asldata=True, **vars(options)) # Deal with --artonly if wsp.artonly: wsp.infertiss = False wsp.inferart = True # Adjust number of iterations based on fast option if not wsp.fast: num_iter, num_trials, onestep = 20, 10, False elif wsp.fast == 1: num_iter, num_trials, onestep = 5, 2, False elif wsp.fast == 2: num_iter, num_trials, onestep = 10, 5, True else: raise ValueError("Not a valid option for fast: %s" % str(wsp.fast)) wsp.max_iterations = num_iter wsp.max_trials = num_trials wsp.onestep = onestep # Read in additional model options from a file wsp.model_options = {} if wsp.model_options: with open(wsp.model_options) as optfile: for line in optfile: keyval = line.strip().rstrip("\n").lstrip("--").split("=", 1) key = keyval[0].strip().replace("-", "_") if key != "": if len(keyval) == 1: wsp.model_options[key] = True else: wsp.model_options[key] = keyval[1].strip() # Run BASIL processing basil(wsp) except ValueError as exc: sys.stderr.write("\nERROR: " + str(exc) + "\n") sys.stderr.write("Use --help for usage information\n") sys.exit(1)
def test_pvc_only_one_map_given2(): """ Check that PVC correction fails if you only give the WM map """ d = np.random.rand(5, 5, 5, 6) img = AslImage(name="asldata", image=d, tis=[1.5], order="prt") wsp = Workspace(infertiss=True, inferbat=True) wsp.pwm = Image(np.random.rand(5, 5, 5)) with pytest.raises(ValueError): basil.basil_steps(wsp, img)
def test_preproc_none(): wsp = Workspace() d = np.random.rand(5, 5, 5, 6) wsp.asldata = AslImage(d, name="asldata", tis=[1.5], iaf="tc", order="lrt") preproc.preprocess(wsp) assert wsp.asldata.ntis == wsp.asldata_preproc.ntis assert wsp.asldata.tis == wsp.asldata_preproc.tis assert wsp.asldata.have_plds == wsp.asldata_preproc.have_plds assert wsp.asldata.rpts == wsp.asldata_preproc.rpts assert wsp.asldata.ntc == wsp.asldata_preproc.ntc assert wsp.asldata.order == wsp.asldata_preproc.order
def test_custom_save_nosave(): """ Test matrices are saved in the savedir with the specified name """ tempdir = tempfile.mkdtemp("_oxasl") try: wsp = Workspace(savedir=tempdir) mat = np.random.rand(4, 4) wsp.set_item("testmat", mat, save_fn=_custom_save, save=False) path = os.path.join(tempdir, "testmat") assert(not os.path.exists(path)) finally: shutil.rmtree(tempdir)
def test_pvc_no_tissue(): """ Check that PVC correction fails if you do not infer the tissue component """ d = np.random.rand(5, 5, 5, 6) img = AslImage(name="asldata", image=d, tis=[1.5], order="prt") wsp = Workspace(infertiss=False, inferbat=True) wsp.pgm = Image(np.random.rand(5, 5, 5)) wsp.pwm = Image(np.random.rand(5, 5, 5)) with pytest.raises(ValueError): basil.basil_steps(wsp, img)
def test_savedir_sub(): """ Test sub-workspace have subdirs created """ tempdir = tempfile.mktemp("_oxasl") try: log = StringIO() wsp = Workspace(savedir=tempdir, log=log) wsp.sub("quark") path = os.path.join(tempdir, "quark") assert(wsp.quark.savedir == path) assert(os.path.isdir(path)) assert("WARNING" not in log.getvalue()) finally: shutil.rmtree(tempdir)
def test_matrix_nosave(): """ Test setting an matrix without saving """ tempdir = tempfile.mkdtemp("_oxasl") try: wsp = Workspace(savedir=tempdir) mat = np.random.rand(4, 4) wsp.set_item("testmat", mat, save=False) path = os.path.join(tempdir, "testmat.mat") assert(not os.path.exists(path)) assert(np.all(mat == wsp.testmat)) finally: shutil.rmtree(tempdir)
def test_image_nosave(): """ Test setting an image without saving """ tempdir = tempfile.mkdtemp("_oxasl") try: wsp = Workspace(savedir=tempdir) img = Image(np.random.rand(5, 5, 5)) wsp.set_item("testimg", img, save=False) path = os.path.join(tempdir, "testimg.nii.gz") assert(not os.path.exists(path)) assert(np.all(img.data == wsp.testimg.data)) finally: shutil.rmtree(tempdir)
def test_default_wsp_multiple(): """ Test multiple default sub-workspaces for search """ wsp = Workspace(defaults=["plants", "trees"]) wsp.daffodil = 9 wsp.larch = 1 wsp.sub("trees") wsp.trees.oak = 3 wsp.trees.larch = 2 wsp.trees.apple = 7 assert(wsp.daffodil == 9) assert(wsp.larch == 1) assert(wsp.oak == 3) assert(wsp.apple == 7) assert(wsp.trees.larch == 2) assert(wsp.trees.oak == 3) assert(wsp.trees.daffodil is None) assert(wsp.trees.apple == 7) wsp.sub("plants") wsp.plants.lily = 4 wsp.plants.oak = 5 assert(wsp.daffodil == 9) assert(wsp.larch == 1) assert(wsp.lily == 4) assert(wsp.oak == 5) assert(wsp.apple == 7) assert(wsp.trees.oak == 3) assert(wsp.trees.lily is None) assert(wsp.plants.daffodil is None) assert(wsp.plants.lily == 4) assert(wsp.plants.oak == 5)
def test_initmvn(): """ Check the supply of an initialization MVN """ d = np.random.rand(5, 5, 5, 6) img = AslImage(name="asldata", image=d, tis=[1.5], order="prt") wsp = Workspace(infertiss=True, inferbat=True) wsp.initmvn = Image(np.random.rand(5, 5, 5, 6)) steps = basil.basil_steps(wsp, img) assert (len(steps) == 1) options = _get_defaults(img) options.update({"continue-from-mvn": wsp.initmvn}) _check_step(steps[0], desc_text="tissue", options=options)
def test_defaults(): """ Check the basic defaults (infer tissue perfusion and bolus arrival time) """ d = np.random.rand(5, 5, 5, 6) img = AslImage(name="asldata", image=d, tis=[1.5], order="prt") wsp = Workspace() wsp.infertiss = True wsp.inferbat = True steps = basil.basil_steps(wsp, img) assert (len(steps) == 1) options = _get_defaults(img) _check_step(steps[0], desc_text="tissue", options=options)
def main(): """ Entry point for command line tool """ try: parser = AslOptionParser(usage="asl_reg [options]", version=__version__) parser.add_category(RegOptions()) parser.add_category(struc.StructuralImageOptions()) parser.add_category(GenericOptions()) options, _ = parser.parse_args(sys.argv) wsp = Workspace(**vars(options)) if not options.regfrom: sys.stderr.write("Input file not specified\n") parser.print_help() sys.exit(1) reg_asl2struc(wsp, wsp.do_flirt, wsp.do_bbr) if wsp.output: wsp.reg.regto.save(wsp.output) if wsp.reg.asl2struc: with open(wsp.omat, "w") as transform_file: for row in wsp.reg.asl2struc: transform_file.write(" ".join(["%f" % val for val in row]) + "\n") except ValueError as exc: sys.stderr.write("ERROR: " + str(exc) + "\n") sys.exit(1)
def test_refregion_gain(): """ Modify calibration gain """ GAIN = 3.4 perf_img, calib_img = _get_imgs() ref_d = np.ones((5, 5, 5)) ref_img = Image(name="refmask", image=ref_d) wsp = Workspace(calib=calib_img, calib_method="refregion", refmask=ref_img, calib_aslreg=True, tissref="wm", calib_gain=GAIN) perf_calib = calib.calibrate(wsp, perf_img) calibrated_d = perf_calib.data m0_expected = _expected_m0(np.mean(calib_img.data), 1.0, 50, 0.82, gain=GAIN) np.testing.assert_allclose(calibrated_d, perf_img.data / m0_expected)
def test_image_save(): """ Test images are saved in the savedir """ tempdir = tempfile.mkdtemp("_oxasl") try: wsp = Workspace(savedir=tempdir) img = Image(np.random.rand(5, 5, 5)) wsp.testimg = img path = os.path.join(tempdir, "testimg.nii.gz") assert(os.path.isfile(path)) otherimg = Image(path) assert(np.all(img.data == wsp.testimg.data)) assert(np.all(img.data == otherimg.data)) finally: shutil.rmtree(tempdir)
def test_onestep(): """ Check that single step mode works when you would normally get multiple steps """ d = np.random.rand(5, 5, 5, 6) img = AslImage(name="asldata", image=d, tis=[1.5], order="prt") wsp = Workspace(infertiss=True, inferbat=True, infertau=True, inferart=True, spatial=True, onestep=True) steps = basil.basil_steps(wsp, img) assert (len(steps) == 1) options = _get_defaults(img) options.update({ "method": "spatialvb", "param-spatial-priors": "N+", "PSP_byname1": "ftiss", "PSP_byname1_type": "M", "inctau": True, "incart": True, "inferart": True, "infertau": True, "convergence": "maxits", }) options.pop("max-trials") _check_step(steps[0], desc_text="spatial", options=options)
def qp_oxasl(worker_id, queue, fsldir, fsldevdir, asldata, options): """ Worker function for asynchronous oxasl run Note that images are passed as QpData because it's pickleable but need to be converted to fsl.data.image.Image """ try: from oxasl import Workspace from oxasl.oxford_asl import oxasl options["fabber_dirs"] = get_plugins("fabber-dirs") if "FSLOUTPUTTYPE" not in os.environ: os.environ["FSLOUTPUTTYPE"] = "NIFTI_GZ" if fsldir: os.environ["FSLDIR"] = fsldir if fsldevdir: os.environ["FSLDEVDIR"] = fsldevdir for key, value in options.items(): if isinstance(value, QpData): options[key] = qpdata_to_fslimage(value) options["asldata"], _ = qpdata_to_aslimage(asldata) output_monitor = OutputStreamMonitor(queue) wsp = Workspace(log=output_monitor, **options) oxasl(wsp) return worker_id, True, {} except: traceback.print_exc() return worker_id, False, sys.exc_info()[1]
def test_nodata(): """ Check we get an error if there is no data """ wsp = Workspace() with pytest.raises(ValueError): steps = basil.basil_steps(wsp, None)
def test_custom_save_name(): """ Test matrices are saved in the savedir with the specified name """ tempdir = tempfile.mkdtemp("_oxasl") try: wsp = Workspace(savedir=tempdir) mat = np.random.rand(4, 4) wsp.set_item("testmat", mat, save_name="potato", save_fn=_custom_save) path = os.path.join(tempdir, "testmat") assert(not os.path.exists(path)) path = os.path.join(tempdir, "potato") assert(os.path.exists(path)) with open(path) as sfile: assert("Custom Save" == sfile.read()) finally: shutil.rmtree(tempdir)
def run(self): ret = -1 try: wsp = Workspace(log=LogWriter(), **self.options) oxasl(wsp) ret = 0 finally: wx.CallAfter(pub.sendMessage, "run_finished", retcode=ret)
def test_input_wsp(): """ Test putting constructor attributes in a default sub workspaces """ wsp = Workspace(input_wsp="cakes", flapjack=4, fruit=3, defaults=[]) assert(wsp.cakes is not None) assert(wsp.cakes.flapjack == 4) assert(wsp.cakes.fruit == 3) assert(wsp.flapjack is None) assert(wsp.fruit is None)
def test_matrix_save(): """ Test 2D matrices are saved in the savedir """ tempdir = tempfile.mkdtemp("_oxasl") try: wsp = Workspace(savedir=tempdir) mat = np.random.rand(4, 4) wsp.testmat = mat path = os.path.join(tempdir, "testmat.mat") assert(os.path.isfile(path)) with open(path) as matfile: othermat = text_to_matrix(matfile.read()) assert(np.all(mat == wsp.testmat)) assert(np.all(mat == othermat)) finally: shutil.rmtree(tempdir)
def test_image_save_name(): """ Test images are saved in the savedir with the specified name """ tempdir = tempfile.mkdtemp("_oxasl") try: wsp = Workspace(savedir=tempdir) img = Image(np.random.rand(5, 5, 5)) wsp.set_item("testimg", img, save_name="pumpkin") path = os.path.join(tempdir, "testimg.nii.gz") assert(not os.path.exists(path)) path = os.path.join(tempdir, "pumpkin.nii.gz") assert(os.path.isfile(path)) otherimg = Image(path) assert(np.all(img.data == wsp.testimg.data)) assert(np.all(img.data == otherimg.data)) finally: shutil.rmtree(tempdir)
def test_nocalib(): """ Check we get an error if there is no calibration data """ d = np.random.rand(5, 5, 5, 6) perf_img = Image(name="perfusion", image=d) wsp = Workspace(calib_method="voxelwise") with pytest.raises(ValueError): calib.calibrate(wsp, perf_img)
def test_matrix_save_name(): """ Test matrices are saved in the savedir with the specified name """ tempdir = tempfile.mkdtemp("_oxasl") try: wsp = Workspace(savedir=tempdir) mat = np.random.rand(4, 4) wsp.set_item("testmat", mat, save_name="parsnip") path = os.path.join(tempdir, "testmat.mat") assert(not os.path.exists(path)) path = os.path.join(tempdir, "parsnip.mat") assert(os.path.isfile(path)) with open(path) as matfile: othermat = text_to_matrix(matfile.read()) assert(np.all(mat == wsp.testmat)) assert(np.all(mat == othermat)) finally: shutil.rmtree(tempdir)
def test_fsllog_default(): """ Test the FSL logging context created """ log = StringIO() wsp = Workspace(log=log) assert(isinstance(wsp.fsllog, dict)) assert(wsp.fsllog.get("stdout", None) is None) assert(wsp.fsllog.get("stderr", None) == log) assert(wsp.fsllog.get("cmd", None) is None)
def test_fsllog_debug(): """ Test the FSL logging context created in debug mode """ log = StringIO() wsp = Workspace(debug=True, log=log) assert(isinstance(wsp.fsllog, dict)) assert(wsp.fsllog.get("stdout", None) == log) assert(wsp.fsllog.get("stderr", None) == log) assert(wsp.fsllog.get("cmd", None) == log)