Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Undefined iprint variable in scipy/optimize/cobyla.py #5029

Closed
massich opened this issue Mar 20, 2018 · 1 comment
Closed

Undefined iprint variable in scipy/optimize/cobyla.py #5029

massich opened this issue Mar 20, 2018 · 1 comment

Comments

@massich
Copy link
Contributor

massich commented Mar 20, 2018

Can anyone reproduce this error ? I'm usin mne-python/environment.yml (scipy 1.0.0 py36hbf646e7_0 )

(mne) ❯ pytest mne/tests -k test_arithmetic
Test session starts (platform: linux, Python 3.6.1, pytest 3.4.2, pytest-sugar 0.9.1)
rootdir: /home/sik/code/mne-python, inifile: setup.cfg
plugins: sugar-0.9.1, faulthandler-1.4.1, cov-2.5.1

 mne/tests/test_cov.py ✓                                                                                                                                                                             50% █████     

――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― test_arithmetic ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――

    def test_arithmetic():
        """Test evoked arithmetic."""
        ev = read_evokeds(fname, condition=0)
        ev1 = EvokedArray(np.ones_like(ev.data), ev.info, ev.times[0], nave=20)
        ev2 = EvokedArray(-np.ones_like(ev.data), ev.info, ev.times[0], nave=10)
    
        # combine_evoked([ev1, ev2]) should be the same as ev1 + ev2:
        # data should be added according to their `nave` weights
        # nave = ev1.nave + ev2.nave
        ev = combine_evoked([ev1, ev2], weights='nave')
        assert_equal(ev.nave, ev1.nave + ev2.nave)
        assert_allclose(ev.data, 1. / 3. * np.ones_like(ev.data))
    
        # with same trial counts, a bunch of things should be equivalent
        for weights in ('nave', 'equal', [0.5, 0.5]):
            ev = combine_evoked([ev1, ev1], weights=weights)
            assert_allclose(ev.data, ev1.data)
            assert_equal(ev.nave, 2 * ev1.nave)
            ev = combine_evoked([ev1, -ev1], weights=weights)
            assert_allclose(ev.data, 0., atol=1e-20)
            assert_equal(ev.nave, 2 * ev1.nave)
        ev = combine_evoked([ev1, -ev1], weights='equal')
        assert_allclose(ev.data, 0., atol=1e-20)
        assert_equal(ev.nave, 2 * ev1.nave)
        ev = combine_evoked([ev1, -ev2], weights='equal')
        expected = int(round(1. / (0.25 / ev1.nave + 0.25 / ev2.nave)))
        assert_equal(expected, 27)  # this is reasonable
        assert_equal(ev.nave, expected)
    
        # default comment behavior if evoked.comment is None
        old_comment1 = ev1.comment
        old_comment2 = ev2.comment
        ev1.comment = None
        ev = combine_evoked([ev1, -ev2], weights=[1, -1])
        assert_equal(ev.comment.count('unknown'), 2)
        assert_true('-unknown' in ev.comment)
        assert_true(' + ' in ev.comment)
        ev1.comment = old_comment1
        ev2.comment = old_comment2
    
        # equal weighting
        ev = combine_evoked([ev1, ev2], weights='equal')
        assert_allclose(ev.data, np.zeros_like(ev1.data))
    
        # combine_evoked([ev1, ev2], weights=[1, 0]) should yield the same as ev1
        ev = combine_evoked([ev1, ev2], weights=[1, 0])
        assert_equal(ev.nave, ev1.nave)
        assert_allclose(ev.data, ev1.data)
    
        # simple subtraction (like in oddball)
        ev = combine_evoked([ev1, ev2], weights=[1, -1])
        assert_allclose(ev.data, 2 * np.ones_like(ev1.data))
    
        assert_raises(ValueError, combine_evoked, [ev1, ev2], weights='foo')
        assert_raises(ValueError, combine_evoked, [ev1, ev2], weights=[1])
    
        # grand average
        evoked1, evoked2 = read_evokeds(fname, condition=[0, 1], proj=True)
        ch_names = evoked1.ch_names[2:]
        evoked1.info['bads'] = ['EEG 008']  # test interpolation
        evoked1.drop_channels(evoked1.ch_names[:1])
        evoked2.drop_channels(evoked2.ch_names[1:2])
>       gave = grand_average([evoked1, evoked2])

ch_names   = ['MEG 0111', 'MEG 0122', 'MEG 0123', 'MEG 0121', 'MEG 0132', 'MEG 0133', ...]
ev         = <Evoked  |  comment : '1.000 * unknown + -1.000 * unknown', kind : average, time : [-0.199795, 0.499488], n_epochs : 7, n_channels x n_times : 376 x 421, ~4.8 MB>
ev1        = <Evoked  |  comment : '', kind : average, time : [-0.199795, 0.499488], n_epochs : 20, n_channels x n_times : 376 x 421, ~4.8 MB>
ev2        = <Evoked  |  comment : '', kind : average, time : [-0.199795, 0.499488], n_epochs : 10, n_channels x n_times : 376 x 421, ~4.8 MB>
evoked1    = <Evoked  |  comment : 'Left Auditory', kind : average, time : [-0.199795, 0.499488], n_epochs : 3, n_channels x n_times : 375 x 421, ~4.8 MB>
evoked2    = <Evoked  |  comment : 'Right Auditory', kind : average, time : [-0.199795, 0.499488], n_epochs : 6, n_channels x n_times : 375 x 421, ~4.8 MB>
expected   = 27
old_comment1 = ''
old_comment2 = ''
weights    = [0.5, 0.5]

mne/tests/test_evoked.py:493: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
mne/utils.py:2511: in grand_average
    else inst for inst in all_inst]
mne/utils.py:2511: in <listcomp>
    else inst for inst in all_inst]
<string>:2: in interpolate_bads
    ???
mne/utils.py:728: in verbose
    return function(*args, **kwargs)
mne/channels/channels.py:920: in interpolate_bads
    _interpolate_bads_eeg(self)
<string>:2: in _interpolate_bads_eeg
    ???
mne/utils.py:728: in verbose
    return function(*args, **kwargs)
mne/channels/interpolation.py:142: in _interpolate_bads_eeg
    radius, center = _fit_sphere(pos_good)
mne/bem.py:1001: in _fit_sphere
    rhoend=radius_init * 1e-6, disp=disp)
../../miniconda3/envs/mne/lib/python3.6/site-packages/scipy/optimize/cobyla.py:1
scipy/optimize/cobyla.py:167: in fmin_cobyla
    **opts)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

fun = <function _fit_sphere.<locals>.cost_fun at 0x7fcd69534378>, x0 = array([-0.0127069 ,  0.00408325,  0.08565747,  0.06573494]), args = ()
constraints = ({'args': (), 'fun': <function _fit_sphere.<locals>.constraint at 0x7fcd69534730>, 'type': 'ineq'},), rhobeg = 0.065734940201687325, tol = 6.5734940201687326e-08, maxiter = 1000, disp = True
catol = 0.0002, unknown_options = {}, maxfun = 1000, rhoend = 6.5734940201687326e-08, ic = 0, con = {'args': (), 'fun': <function _fit_sphere.<locals>.constraint at 0x7fcd69534730>, 'type': 'ineq'}
ctype = 'ineq', c = {'args': (), 'fun': <function _fit_sphere.<locals>.constraint at 0x7fcd69534730>, 'type': 'ineq'}

    def _minimize_cobyla(fun, x0, args=(), constraints=(),
                         rhobeg=1.0, tol=1e-4, maxiter=1000,
                         disp=False, catol=2e-4, **unknown_options):
        """
        Minimize a scalar function of one or more variables using the
        Constrained Optimization BY Linear Approximation (COBYLA) algorithm.
    
        Options
        -------
        rhobeg : float
            Reasonable initial changes to the variables.
        tol : float
            Final accuracy in the optimization (not precisely guaranteed).
            This is a lower bound on the size of the trust region.
        disp : bool
            Set to True to print convergence messages. If False,
            `verbosity` is ignored as set to 0.
        maxiter : int
            Maximum number of function evaluations.
        catol : float
            Tolerance (absolute) for constraint violations
    
        """
        _check_unknown_options(unknown_options)
        maxfun = maxiter
        rhoend = tol
        if not disp:
            iprint = 0
    
        # check constraints
        if isinstance(constraints, dict):
            constraints = (constraints, )
    
        for ic, con in enumerate(constraints):
            # check type
            try:
                ctype = con['type'].lower()
            except KeyError:
                raise KeyError('Constraint %d has no type defined.' % ic)
            except TypeError:
                raise TypeError('Constraints must be defined using a '
                                'dictionary.')
            except AttributeError:
                raise TypeError("Constraint's type must be a string.")
            else:
                if ctype != 'ineq':
                    raise ValueError("Constraints of type '%s' not handled by "
                                     "COBYLA." % con['type'])
    
            # check function
            if 'fun' not in con:
                raise KeyError('Constraint %d has no function defined.' % ic)
    
            # check extra arguments
            if 'args' not in con:
                con['args'] = ()
    
        # m is the total number of constraint values
        # it takes into account that some constraints may be vector-valued
        cons_lengths = []
        for c in constraints:
            f = c['fun'](x0, *c['args'])
            try:
                cons_length = len(f)
            except TypeError:
                cons_length = 1
            cons_lengths.append(cons_length)
        m = sum(cons_lengths)
    
        def calcfc(x, con):
            f = fun(x, *args)
            i = 0
            for size, c in izip(cons_lengths, constraints):
                con[i: i + size] = c['fun'](x, *c['args'])
                i += size
            return f
    
        info = np.zeros(4, np.float64)
        xopt, info = _cobyla.minimize(calcfc, m=m, x=np.copy(x0), rhobeg=rhobeg,
>                                     rhoend=rhoend, iprint=iprint, maxfun=maxfun,
                                      dinfo=info)
E       UnboundLocalError: local variable 'iprint' referenced before assignment

args       = ()
c          = {'args': (), 'fun': <function _fit_sphere.<locals>.constraint at 0x7fcd69534730>, 'type': 'ineq'}
calcfc     = <function _minimize_cobyla.<locals>.calcfc at 0x7fcd695347b8>
catol      = 0.0002
con        = {'args': (), 'fun': <function _fit_sphere.<locals>.constraint at 0x7fcd69534730>, 'type': 'ineq'}
cons_length = 1
cons_lengths = [1]
constraints = ({'args': (), 'fun': <function _fit_sphere.<locals>.constraint at 0x7fcd69534730>, 'type': 'ineq'},)
ctype      = 'ineq'
disp       = True
f          = 0.065734940201687325
fun        = <function _fit_sphere.<locals>.cost_fun at 0x7fcd69534378>
ic         = 0
info       = array([ 0.,  0.,  0.,  0.])
m          = 1
maxfun     = 1000
maxiter    = 1000
rhobeg     = 0.065734940201687325
rhoend     = 6.5734940201687326e-08
tol        = 6.5734940201687326e-08
unknown_options = {}
x0         = array([-0.0127069 ,  0.00408325,  0.08565747,  0.06573494])

../../miniconda3/envs/mne/lib/python3.6/site-packages/scipy/optimize/cobyla.py:252: UnboundLocalError
---------------------------------------------------------------------------------------------- Captured stdout call -----------------------------------------------------------------------------------------------
Reading /home/sik/code/mne-python/mne/tests/../io/tests/data/test-ave.fif ...
    Read a total of 4 projection items:
        PCA-v1 (1 x 102)  idle
        PCA-v2 (1 x 102)  idle
        PCA-v3 (1 x 102)  idle
        Average EEG reference (1 x 60)  idle
    Found the data of interest:
        t =    -199.80 ...     499.49 ms (Left Auditory)
        0 CTF compensation matrices available
        nave = 3 - aspect type = 100
Created an SSP operator (subspace dimension = 4)
4 projection items activated
SSP projectors applied...
No baseline correction applied
Reading /home/sik/code/mne-python/mne/tests/../io/tests/data/test-ave.fif ...
    Read a total of 4 projection items:
        PCA-v1 (1 x 102)  idle
        PCA-v2 (1 x 102)  idle
        PCA-v3 (1 x 102)  idle
        Average EEG reference (1 x 60)  idle
    Found the data of interest:
        t =    -199.80 ...     499.49 ms (Left Auditory)
        0 CTF compensation matrices available
        nave = 3 - aspect type = 100
Created an SSP operator (subspace dimension = 4)
4 projection items activated
SSP projectors applied...
No baseline correction applied
    Read a total of 4 projection items:
        PCA-v1 (1 x 102)  idle
        PCA-v2 (1 x 102)  idle
        PCA-v3 (1 x 102)  idle
        Average EEG reference (1 x 60)  idle
    Found the data of interest:
        t =    -199.80 ...     499.49 ms (Right Auditory)
        0 CTF compensation matrices available
        nave = 6 - aspect type = 100
Created an SSP operator (subspace dimension = 4)
4 projection items activated
SSP projectors applied...
No baseline correction applied

 mne/tests/test_evoked.py ⨯                                                                                                                                                                         100% ██████████
============================================================================================ slowest 20 test durations ============================================================================================
0.38s call     mne/tests/test_evoked.py::test_arithmetic
0.01s call     mne/tests/test_cov.py::test_arithmetic_cov
0.00s setup    mne/tests/test_cov.py::test_arithmetic_cov
0.00s teardown mne/tests/test_evoked.py::test_arithmetic
0.00s teardown mne/tests/test_cov.py::test_arithmetic_cov
0.00s setup    mne/tests/test_evoked.py::test_arithmetic
============================================================================================== 276 tests deselected ===============================================================================================

Results (1.39s):
       1 passed
       1 failed
         - mne/tests/test_evoked.py:431 test_arithmetic
     276 deselected
@larsoner
Copy link
Member

Dup of scipy/scipy#8118 fixed in scipy/scipy#8144 will be out in SciPy 1.0.1

You can work around it at the MNE end by putting verbose=False in the call to the interpolate_* function as done here #4745

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants