<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def autofocus(field, nm, res, ival, roi=None, metric="average gradient", padding=True, ret_d=False, ret_grad=False, num_cpus=1):
 """Numerical autofocusing of a field using the Helmholtz equation. Parameters field : 1d or 2d ndarray Electric field is BG-Corrected, i.e. field = EX/BEx nm : float Refractive index of medium. res : float Size of wavelength in pixels. ival : tuple of floats Approximate interval to search for optimal focus in px. roi : rectangular region of interest (x1, y1, x2, y2) Region of interest of `field` for which the metric will be minimized. If not given, the entire `field` will be used. metric : str - "average gradient" : average gradient metric of amplitude - "rms contrast" : RMS contrast of phase data - "spectrum" : sum of filtered Fourier coefficients padding: bool Perform padding with linear ramp from edge to average to reduce ringing artifacts. .. versionchanged:: 0.1.4 improved padding value and padding location red_d : bool Return the autofocusing distance in pixels. Defaults to False. red_grad : bool Return the computed gradients as a list. num_cpus : int Not implemented. Returns ------- field, [d, [grad]] The focused field and optionally, the optimal focusing distance and the computed gradients. """

    if metric == "average gradient":
        def metric_func(x): return metrics.average_gradient(np.abs(x))
    elif metric == "rms contrast":
        def metric_func(x): return -metrics.contrast_rms(np.angle(x))
    elif metric == "spectrum":
        def metric_func(x): return metrics.spectral(np.abs(x), res)
    else:
        raise ValueError("No such metric: {}".format(metric))

    field, d, grad = minimize_metric(field, metric_func, nm, res, ival,
                                     roi=roi, padding=padding)

    ret_list = [field]
    if ret_d:
        ret_list += [d]
    if ret_grad:
        ret_list += [grad]

    if len(ret_list) == 1:
        return ret_list[0]
    else:
        return tuple(ret_list)