def to_code(objective):
    """
    Create executable Python code fragment that corresponds to the model in the
    GUI.

    Parameters
    ----------
    objective: refnx.analysis.Objective

    Returns
    -------
    code: str
        Python code that can construct a reflectometry fitting system

    """
    header = """import numpy as np
import refnx
from refnx.analysis import Objective, CurveFitter, Transform
from refnx.reflect import SLD, Slab, ReflectModel, Structure
from refnx.dataset import ReflectDataset

print(refnx.version.version)
    """
    code = [header]
    code.append('data = ReflectDataset("{0}")'.format(objective.data.filename))
    slds = ['\n# set up the SLD objects for each layer']
    slabs = ['\n# set up the Slab objects for each layer']
    limits = []
    structure = 'structure = '
    for i, slab in enumerate(objective.model.structure):
        sld = slab.sld
        lims = [(sld.real, 'sld{0}.real'), (sld.imag, 'sld{0}.imag'), (slab
            .thick, 'slab{0}.thick'), (slab.rough, 'slab{0}.rough')]
        slds.append("sld{0} = SLD({1} + {2}j, name='{3}')".format(i, sld.
            real.value, sld.imag.value, slab.name))
        slabs.append("slab{0} = Slab({1}, sld{0}, {2}, name='{3}')".format(
            i, slab.thick.value, slab.rough.value, slab.name))
        for p, temp in lims:
            if p.vary:
                limits.append((temp + '.setp(vary=True, bounds=({1}, {2}))'
                    ).format(i, p.bounds.lb, p.bounds.ub))
        if not i:
            structure += 'slab{0}'.format(i)
        else:
            structure += ' | slab{0}'.format(i)
    code.extend(slds)
    code.extend(slabs)
    code.append("\n# set up the limits for SLD's and Slabs")
    code.extend(limits)
    code.append('\n# set up the Structure object from the Slabs')
    code.append(structure)
    model = objective.model
    code.append('\n# make the reflectometry model')
    code.append('model = ReflectModel(structure, scale={0}, bkg={1}, dq={2})'
        .format(model.scale.value, model.bkg.value, model.dq.value))
    lims = [(model.scale, 'model.scale'), (model.bkg, 'model.bkg'), (model.
        dq, 'model.dq')]
    for p, temp in lims:
        if p.vary:
            code.append((temp + '.setp(vary=True, bounds=({0}, {1}))').
                format(p.bounds.lb, p.bounds.ub))
    code.append('\n# make the objective')
    code.append('transform = {}'.format(repr(objective.transform)))
    code.append(
        'objective = Objective(model, data, transform=transform, use_weights={})'
        .format(objective.weighted))
    code.append('\n# make the curvefitter')
    code.append('fitter = CurveFitter(objective)')
    code.append("fitter.fit('differential_evolution')")
    code.append('print(objective)')
    return '\n'.join(code)
