<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def montage(data, ref_chan=None, ref_to_avg=False, bipolar=None, method='average'):
 """Apply linear transformation to the channels. Parameters data : instance of DataRaw the data to filter ref_chan : list of str list of channels used as reference ref_to_avg : bool if re-reference to average or not bipolar : float distance in mm to consider two channels as neighbors and then compute the bipolar montage between them. method : str 'average' or 'regression'. 'average' takes the average across the channels selected as reference (it can be all) and subtract it from each channel. 'regression' keeps the residuals after regressing out the mean across channels. Returns ------- filtered_data : instance of DataRaw filtered data Notes ----- If you don't change anything, it returns the same instance of data. """

    if ref_to_avg and ref_chan is not None:
        raise TypeError('You cannot specify reference to the average and '
                        'the channels to use as reference')

    if ref_chan is not None:
        if (not isinstance(ref_chan, (list, tuple)) or
            not all(isinstance(x, str) for x in ref_chan)):
                raise TypeError('chan should be a list of strings')

    if ref_chan is None:
        ref_chan = []  # TODO: check bool for ref_chan

    if bipolar:
        if not data.attr['chan']:
            raise ValueError('Data should have Chan information in attr')

        _assert_equal_channels(data.axis['chan'])
        chan_in_data = data.axis['chan'][0]
        chan = data.attr['chan']
        chan = chan(lambda x: x.label in chan_in_data)
        chan, trans = create_bipolar_chan(chan, bipolar)
        data.attr['chan'] = chan

    if ref_to_avg or ref_chan or bipolar:
        mdata = data._copy()

        idx_chan = mdata.index_of('chan')

        for i in range(mdata.number_of('trial')):
            if ref_to_avg or ref_chan:
                if ref_to_avg:
                    ref_chan = data.axis['chan'][i]

                ref_data = data(trial=i, chan=ref_chan)
                if method == 'average':
                    mdata.data[i] = (data(trial=i) - mean(ref_data, axis=idx_chan))
                elif method == 'regression':
                    mdata.data[i] = compute_average_regress(data(trial=i), idx_chan)

            elif bipolar:

                if not data.index_of('chan') == 0:
                    raise ValueError('For matrix multiplication to work, '
                                     'the first dimension should be chan')
                mdata.data[i] = dot(trans, data(trial=i))
                mdata.axis['chan'][i] = asarray(chan.return_label(),
                                                dtype='U')

    else:
        mdata = data

    return mdata