예제 #1
0
    def iteration_stats(self):
        """Construct iteration stats record tuple."""

        tk = self.timer.elapsed(self.opt['IterTimer'])
        if self.xstep_itstat is None:
            objfn = (0.0, ) * 3
            rsdl = (0.0, ) * 2
            rho = (0.0, )
        else:
            objfn = (self.xstep_itstat.ObjFun, self.xstep_itstat.DFid,
                     self.xstep_itstat.RegL1)
            rsdl = (self.xstep_itstat.PrimalRsdl, self.xstep_itstat.DualRsdl)
            rho = (self.xstep_itstat.Rho, )

        cnstr = np.linalg.norm(cr.zpad(self.D, self.cri.Nv) - self.G)
        dltd = np.linalg.norm(self.D - self.Dprv)

        tpl = (self.j,) + objfn + rsdl + rho + (cnstr, dltd, self.eta) + \
              self.itstat_extra() + (tk,)
        return type(self).IterationStats(*tpl)
예제 #2
0
            method='ism')


"""
Normalise dictionary according to dictionary Y update options.
"""

D0n = cnvrep.Pcn(D0, D0.shape, cri.Nv, dimN=2, dimC=0, crp=True,
                 zm=optd['ZeroMean'])


"""
Update D update options to include initial values for Y and U.
"""

optd.update({'Y0': cnvrep.zpad(cnvrep.stdformD(D0n, cri.Cd, cri.M), cri.Nv),
             'U0': np.zeros(cri.shpD)})


"""
Create X update object.
"""

xstep = cbpdn.ConvBPDNJoint(D0n, sh, lmbda, mu, optx)


"""
Create D update object.
"""

dstep = ccmod.ConvCnstrMOD(None, sh, D0.shape, optd, method='ism')
예제 #3
0
    def __init__(self,
                 D0,
                 S,
                 lmbda,
                 W,
                 opt=None,
                 xmethod=None,
                 dmethod=None,
                 dimK=1,
                 dimN=2):
        """

        |

        **Call graph**

        .. image:: ../_static/jonga/cbpdnmddl_init.svg
           :width: 20%
           :target: ../_static/jonga/cbpdnmddl_init.svg

        |


        Parameters
        ----------
        D0 : array_like
          Initial dictionary array
        S : array_like
          Signal array
        lmbda : float
          Regularisation parameter
        W : array_like
          Mask array. The array shape must be such that the array is
          compatible for multiplication with the *internal* shape of
          input array S (see :class:`.cnvrep.CDU_ConvRepIndexing` for a
          discussion of the distinction between *external* and *internal*
          data layouts) after reshaping to the shape determined by
          :func:`.cnvrep.mskWshape`.
        opt : :class:`ConvBPDNMaskDictLearn.Options` object
          Algorithm options
        xmethod : string, optional (default 'admm')
          String selecting sparse coding solver. Valid values are
          documented in function :func:`.ConvBPDNMask`.
        dmethod : string, optional (default 'pgm')
          String selecting dictionary update solver. Valid values are
          documented in function :func:`.ConvCnstrMODMask`.
        dimK : int, optional (default 1)
          Number of signal dimensions. If there is only a single input
          signal (e.g. if `S` is a 2D array representing a single image)
          `dimK` must be set to 0.
        dimN : int, optional (default 2)
          Number of spatial/temporal dimensions
        """

        if opt is None:
            opt = ConvBPDNMaskDictLearn.Options(xmethod=xmethod,
                                                dmethod=dmethod)
        if xmethod is None:
            xmethod = opt.xmethod
        if dmethod is None:
            dmethod = opt.dmethod
        if opt.xmethod != xmethod or opt.dmethod != dmethod:
            raise ValueError('Parameters xmethod and dmethod must have the '
                             'same values used to initialise the Options '
                             'object')
        self.opt = opt
        self.xmethod = xmethod
        self.dmethod = dmethod

        # Get dictionary size
        if self.opt['DictSize'] is None:
            dsz = D0.shape
        else:
            dsz = self.opt['DictSize']

        # Construct object representing problem dimensions
        cri = cr.CDU_ConvRepIndexing(dsz, S, dimK, dimN)

        # Normalise dictionary
        D0 = cr.Pcn(D0,
                    dsz,
                    cri.Nv,
                    dimN,
                    cri.dimCd,
                    crp=True,
                    zm=opt['CCMOD', 'ZeroMean'])

        # Modify D update options to include initial values for Y
        if cri.C == cri.Cd:
            Y0b0 = np.zeros(cri.Nv + (cri.C, 1, cri.K))
        else:
            Y0b0 = np.zeros(cri.Nv + (1, 1, cri.C * cri.K))
        Y0b1 = cr.zpad(cr.stdformD(D0, cri.Cd, cri.M, dimN), cri.Nv)
        if dmethod == 'pgm':
            opt['CCMOD'].update({'X0': Y0b1})
        else:
            if dmethod == 'cns':
                Y0 = Y0b1
            else:
                Y0 = np.concatenate((Y0b0, Y0b1), axis=cri.axisM)
            opt['CCMOD'].update({'Y0': Y0})

        # Create X update object
        xstep = ConvBPDNMask(D0,
                             S,
                             lmbda,
                             W,
                             opt['CBPDN'],
                             method=xmethod,
                             dimK=dimK,
                             dimN=dimN)

        # Create D update object
        dstep = ConvCnstrMODMask(None,
                                 S,
                                 W,
                                 dsz,
                                 opt['CCMOD'],
                                 method=dmethod,
                                 dimK=dimK,
                                 dimN=dimN)

        # Configure iteration statistics reporting
        isc = dictlrn.IterStatsConfig(isfld=dc.isfld(xmethod, dmethod, opt),
                                      isxmap=dc.isxmap(xmethod, opt),
                                      isdmap=dc.isdmap(dmethod),
                                      evlmap=dc.evlmap(opt['AccurateDFid']),
                                      hdrtxt=dc.hdrtxt(xmethod, dmethod, opt),
                                      hdrmap=dc.hdrmap(xmethod, dmethod, opt),
                                      fmtmap={
                                          'It_X': '%4d',
                                          'It_D': '%4d'
                                      })

        # Call parent constructor
        super(ConvBPDNMaskDictLearn, self).__init__(xstep, dstep, opt, isc)
예제 #4
0
Normalise dictionary according to Y update options.
"""

D0n = cnvrep.Pcn(D0,
                 D0.shape,
                 cri.Nv,
                 dimN=2,
                 dimC=0,
                 crp=True,
                 zm=optd['ZeroMean'])
"""
Update D update options to include initial values for Y and U.
"""

optd.update({
    'Y0': cnvrep.zpad(cnvrep.stdformD(D0n, cri.Cd, cri.M), cri.Nv),
    'U0': np.zeros(cri.shpD)
})
"""
Create X update object.
"""

xstep = cbpdn.ConvBPDNJoint(D0n, sh, lmbda, mu, optx)
"""
Create D update object.
"""

dstep = ccmod.ConvCnstrMOD(None, sh, D0.shape, optd, method='ism')
"""
Create DictLearn object and solve.
"""
예제 #5
0
    def __init__(self, D0, S, lmbda, W, opt=None, dimK=1, dimN=2):
        """
        Initialise a MixConvBPDNMaskDcplDictLearn object with problem
        size and options.


        Parameters
        ----------
        D0 : array_like
          Initial dictionary array
        S : array_like
          Signal array
        lmbda : float
          Regularisation parameter
        W : array_like
          Mask array. The array shape must be such that the array is
          compatible for multiplication with the *internal* shape of
          input array S (see :class:`.cnvrep.CDU_ConvRepIndexing` for a
          discussion of the distinction between *external* and *internal*
          data layouts).
        opt : :class:`MixConvBPDNMaskDcplDictLearn.Options` object
          Algorithm options
        dimK : int, optional (default 1)
          Number of signal dimensions. If there is only a single input
          signal (e.g. if `S` is a 2D array representing a single image)
          `dimK` must be set to 0.
        dimN : int, optional (default 2)
          Number of spatial/temporal dimensions
        """

        if opt is None:
            opt = MixConvBPDNMaskDcplDictLearn.Options()
        self.opt = opt

        # Get dictionary size
        if self.opt['DictSize'] is None:
            dsz = D0.shape
        else:
            dsz = self.opt['DictSize']

        # Construct object representing problem dimensions
        cri = cr.CDU_ConvRepIndexing(dsz, S, dimK, dimN)

        # Normalise dictionary
        D0 = cr.Pcn(D0,
                    dsz,
                    cri.Nv,
                    dimN,
                    cri.dimCd,
                    crp=True,
                    zm=opt['CCMOD', 'ZeroMean'])

        # Modify D update options to include initial values for X
        X0 = cr.zpad(cr.stdformD(D0, cri.Cd, cri.M, dimN), cri.Nv)
        opt['CCMOD'].update({'X0': X0})

        # Create X update object
        xstep = Acbpdn.ConvBPDNMaskDcpl(D0,
                                        S,
                                        lmbda,
                                        W,
                                        opt['CBPDN'],
                                        dimK=dimK,
                                        dimN=dimN)

        # Create D update object
        dstep = ccmod.ConvCnstrMODMask(None,
                                       S,
                                       W,
                                       dsz,
                                       opt['CCMOD'],
                                       dimK=dimK,
                                       dimN=dimN)

        # Configure iteration statistics reporting
        if self.opt['AccurateDFid']:
            isxmap = {
                'XPrRsdl': 'PrimalRsdl',
                'XDlRsdl': 'DualRsdl',
                'XRho': 'Rho'
            }
            evlmap = {'ObjFun': 'ObjFun', 'DFid': 'DFid', 'RegL1': 'RegL1'}
        else:
            isxmap = {
                'ObjFun': 'ObjFun',
                'DFid': 'DFid',
                'RegL1': 'RegL1',
                'XPrRsdl': 'PrimalRsdl',
                'XDlRsdl': 'DualRsdl',
                'XRho': 'Rho'
            }
            evlmap = {}

        if dstep.opt['BackTrack', 'Enabled']:
            isfld = [
                'Iter', 'ObjFun', 'DFid', 'RegL1', 'Cnstr', 'XPrRsdl',
                'XDlRsdl', 'XRho', 'D_F_Btrack', 'D_Q_Btrack', 'D_ItBt', 'D_L',
                'Time'
            ]
            isdmap = {
                'Cnstr': 'Cnstr',
                'D_F_Btrack': 'F_Btrack',
                'D_Q_Btrack': 'Q_Btrack',
                'D_ItBt': 'IterBTrack',
                'D_L': 'L'
            }
            hdrtxt = [
                'Itn', 'Fnc', 'DFid',
                u('ℓ1'), 'Cnstr', 'r_X', 's_X',
                u('ρ_X'), 'F_D', 'Q_D', 'It_D', 'L_D'
            ]
            hdrmap = {
                'Itn': 'Iter',
                'Fnc': 'ObjFun',
                'DFid': 'DFid',
                u('ℓ1'): 'RegL1',
                'Cnstr': 'Cnstr',
                'r_X': 'XPrRsdl',
                's_X': 'XDlRsdl',
                u('ρ_X'): 'XRho',
                'F_D': 'D_F_Btrack',
                'Q_D': 'D_Q_Btrack',
                'It_D': 'D_ItBt',
                'L_D': 'D_L'
            }

        else:
            isfld = [
                'Iter', 'ObjFun', 'DFid', 'RegL1', 'Cnstr', 'XPrRsdl',
                'XDlRsdl', 'XRho', 'D_L', 'Time'
            ]
            isdmap = {'Cnstr': 'Cnstr', 'D_L': 'L'}
            hdrtxt = [
                'Itn', 'Fnc', 'DFid',
                u('ℓ1'), 'Cnstr', 'r_X', 's_X',
                u('ρ_X'), 'L_D'
            ]
            hdrmap = {
                'Itn': 'Iter',
                'Fnc': 'ObjFun',
                'DFid': 'DFid',
                u('ℓ1'): 'RegL1',
                'Cnstr': 'Cnstr',
                'r_X': 'XPrRsdl',
                's_X': 'XDlRsdl',
                u('ρ_X'): 'XRho',
                'L_D': 'D_L'
            }

        isc = dictlrn.IterStatsConfig(isfld=isfld,
                                      isxmap=isxmap,
                                      isdmap=isdmap,
                                      evlmap=evlmap,
                                      hdrtxt=hdrtxt,
                                      hdrmap=hdrmap)

        # Call parent constructor
        super(MixConvBPDNMaskDcplDictLearn,
              self).__init__(xstep, dstep, opt, isc)
예제 #6
0
    def __init__(self,
                 D0,
                 S,
                 lmbda=None,
                 opt=None,
                 xmethod=None,
                 dmethod=None,
                 dimK=1,
                 dimN=2):
        """

        |

        **Call graph**

        .. image:: ../_static/jonga/cbpdndl_init.svg
           :width: 20%
           :target: ../_static/jonga/cbpdndl_init.svg

        |


        Parameters
        ----------
        D0 : array_like
          Initial dictionary array
        S : array_like
          Signal array
        lmbda : float
          Regularisation parameter
        opt : :class:`ConvBPDNDictLearn.Options` object
          Algorithm options
        xmethod : string, optional (default 'admm')
          String selecting sparse coding solver. Valid values are
          documented in function :func:`.ConvBPDN`.
        dmethod : string, optional (default 'fista')
          String selecting dictionary update solver. Valid values are
          documented in function :func:`.ConvCnstrMOD`.
        dimK : int, optional (default 1)
          Number of signal dimensions. If there is only a single input
          signal (e.g. if `S` is a 2D array representing a single image)
          `dimK` must be set to 0.
        dimN : int, optional (default 2)
          Number of spatial/temporal dimensions
        """

        if opt is None:
            opt = ConvBPDNDictLearn.Options(xmethod=xmethod, dmethod=dmethod)
        if xmethod is None:
            xmethod = opt.xmethod
        if dmethod is None:
            dmethod = opt.dmethod
        if opt.xmethod != xmethod or opt.dmethod != dmethod:
            raise ValueError('Parameters xmethod and dmethod must have the '
                             'same values used to initialise the Options '
                             'object')
        self.opt = opt
        self.xmethod = xmethod
        self.dmethod = dmethod

        # Get dictionary size
        if self.opt['DictSize'] is None:
            dsz = D0.shape
        else:
            dsz = self.opt['DictSize']

        # Construct object representing problem dimensions
        cri = cr.CDU_ConvRepIndexing(dsz, S, dimK, dimN)

        # Normalise dictionary
        D0 = cr.Pcn(D0,
                    dsz,
                    cri.Nv,
                    dimN,
                    cri.dimCd,
                    crp=True,
                    zm=opt['CCMOD', 'ZeroMean'])

        # Modify D update options to include initial value for Y
        optname = 'X0' if dmethod == 'fista' else 'Y0'
        opt['CCMOD'].update(
            {optname: cr.zpad(cr.stdformD(D0, cri.Cd, cri.M, dimN), cri.Nv)})

        # Create X update object
        xstep = ConvBPDN(D0,
                         S,
                         lmbda,
                         opt['CBPDN'],
                         method=xmethod,
                         dimK=dimK,
                         dimN=dimN)

        # Create D update object
        dstep = ConvCnstrMOD(None,
                             S,
                             dsz,
                             opt['CCMOD'],
                             method=dmethod,
                             dimK=dimK,
                             dimN=dimN)

        # Configure iteration statistics reporting
        isc = dictlrn.IterStatsConfig(isfld=dc.isfld(xmethod, dmethod, opt),
                                      isxmap=dc.isxmap(xmethod, opt),
                                      isdmap=dc.isdmap(dmethod),
                                      evlmap=dc.evlmap(opt['AccurateDFid']),
                                      hdrtxt=dc.hdrtxt(xmethod, dmethod, opt),
                                      hdrmap=dc.hdrmap(xmethod, dmethod, opt),
                                      fmtmap={
                                          'It_X': '%4d',
                                          'It_D': '%4d'
                                      })

        # Call parent constructor
        super(ConvBPDNDictLearn, self).__init__(xstep, dstep, opt, isc)
예제 #7
0
파일: cbpdndl.py 프로젝트: bwohlberg/sporco
    def __init__(self, D0, S, lmbda=None, opt=None, xmethod=None,
                 dmethod=None, dimK=1, dimN=2):
        """

        |

        **Call graph**

        .. image:: ../_static/jonga/cbpdndl_init.svg
           :width: 20%
           :target: ../_static/jonga/cbpdndl_init.svg

        |


        Parameters
        ----------
        D0 : array_like
          Initial dictionary array
        S : array_like
          Signal array
        lmbda : float
          Regularisation parameter
        opt : :class:`ConvBPDNDictLearn.Options` object
          Algorithm options
        xmethod : string, optional (default 'admm')
          String selecting sparse coding solver. Valid values are
          documented in function :func:`.ConvBPDN`.
        dmethod : string, optional (default 'fista')
          String selecting dictionary update solver. Valid values are
          documented in function :func:`.ConvCnstrMOD`.
        dimK : int, optional (default 1)
          Number of signal dimensions. If there is only a single input
          signal (e.g. if `S` is a 2D array representing a single image)
          `dimK` must be set to 0.
        dimN : int, optional (default 2)
          Number of spatial/temporal dimensions
        """

        if opt is None:
            opt = ConvBPDNDictLearn.Options(xmethod=xmethod, dmethod=dmethod)
        if xmethod is None:
            xmethod = opt.xmethod
        if dmethod is None:
            dmethod = opt.dmethod
        if opt.xmethod != xmethod or opt.dmethod != dmethod:
            raise ValueError('Parameters xmethod and dmethod must have the '
                             'same values used to initialise the Options '
                             'object')
        self.opt = opt
        self.xmethod = xmethod
        self.dmethod = dmethod

        # Get dictionary size
        if self.opt['DictSize'] is None:
            dsz = D0.shape
        else:
            dsz = self.opt['DictSize']

        # Construct object representing problem dimensions
        cri = cr.CDU_ConvRepIndexing(dsz, S, dimK, dimN)

        # Normalise dictionary
        D0 = cr.Pcn(D0, dsz, cri.Nv, dimN, cri.dimCd, crp=True,
                    zm=opt['CCMOD', 'ZeroMean'])

        # Modify D update options to include initial value for Y
        optname = 'X0' if dmethod == 'fista' else 'Y0'
        opt['CCMOD'].update({optname: cr.zpad(
            cr.stdformD(D0, cri.Cd, cri.M, dimN), cri.Nv)})

        # Create X update object
        xstep = ConvBPDN(D0, S, lmbda, opt['CBPDN'], method=xmethod,
                         dimK=dimK, dimN=dimN)

        # Create D update object
        dstep = ConvCnstrMOD(None, S, dsz, opt['CCMOD'], method=dmethod,
                             dimK=dimK, dimN=dimN)

        # Configure iteration statistics reporting
        isc = dictlrn.IterStatsConfig(
            isfld=dc.isfld(xmethod, dmethod, opt),
            isxmap=dc.isxmap(xmethod, opt), isdmap=dc.isdmap(dmethod),
            evlmap=dc.evlmap(opt['AccurateDFid']),
            hdrtxt=dc.hdrtxt(xmethod, dmethod, opt),
            hdrmap=dc.hdrmap(xmethod, dmethod, opt),
            fmtmap={'It_X': '%4d', 'It_D': '%4d'})

        # Call parent constructor
        super(ConvBPDNDictLearn, self).__init__(xstep, dstep, opt, isc)
예제 #8
0
    def __init__(self, D0, S, lmbda=None, opt=None, dimK=1, dimN=2):
        """
        Initialise a ConvBPDNDictLearn object with problem size and options.


        Parameters
        ----------
        D0 : array_like
          Initial dictionary array
        S : array_like
          Signal array
        lmbda : float
          Regularisation parameter
        opt : :class:`ConvBPDNDictLearn.Options` object
          Algorithm options
        dimK : int, optional (default 1)
          Number of signal dimensions. If there is only a single input
          signal (e.g. if `S` is a 2D array representing a single image)
          `dimK` must be set to 0.
        dimN : int, optional (default 2)
          Number of spatial/temporal dimensions
        """

        if opt is None:
            opt = ConvBPDNDictLearn.Options()
        self.opt = opt

        # Get dictionary size
        if self.opt['DictSize'] is None:
            dsz = D0.shape
        else:
            dsz = self.opt['DictSize']

        # Construct object representing problem dimensions
        cri = cr.CDU_ConvRepIndexing(dsz, S, dimK, dimN)

        # Normalise dictionary
        D0 = cr.Pcn(D0,
                    dsz,
                    cri.Nv,
                    dimN,
                    cri.dimCd,
                    crp=True,
                    zm=opt['CCMOD', 'ZeroMean'])

        # Modify D update options to include initial values for X
        opt['CCMOD'].update(
            {'X0': cr.zpad(cr.stdformD(D0, cri.C, cri.M, dimN), cri.Nv)})

        # Create X update object
        xstep = Fcbpdn.ConvBPDN(D0,
                                S,
                                lmbda,
                                opt['CBPDN'],
                                dimK=dimK,
                                dimN=dimN)

        # Create D update object
        dstep = ccmod.ConvCnstrMOD(None,
                                   S,
                                   dsz,
                                   opt['CCMOD'],
                                   dimK=dimK,
                                   dimN=dimN)

        print("L xstep in cbpdndl: ", xstep.L)
        print("L dstep in cbpdndl: ", dstep.L)

        # Configure iteration statistics reporting
        isfld = ['Iter', 'ObjFun', 'DFid', 'RegL1', 'Cnstr']
        hdrtxt = ['Itn', 'Fnc', 'DFid', u('ℓ1'), 'Cnstr']
        hdrmap = {
            'Itn': 'Iter',
            'Fnc': 'ObjFun',
            'DFid': 'DFid',
            u('ℓ1'): 'RegL1',
            'Cnstr': 'Cnstr'
        }

        if self.opt['AccurateDFid']:
            isxmap = {
                'X_F_Btrack': 'F_Btrack',
                'X_Q_Btrack': 'Q_Btrack',
                'X_ItBt': 'IterBTrack',
                'X_L': 'L',
                'X_Rsdl': 'Rsdl'
            }
            evlmap = {'ObjFun': 'ObjFun', 'DFid': 'DFid', 'RegL1': 'RegL1'}
        else:
            isxmap = {
                'ObjFun': 'ObjFun',
                'DFid': 'DFid',
                'RegL1': 'RegL1',
                'X_F_Btrack': 'F_Btrack',
                'X_Q_Btrack': 'Q_Btrack',
                'X_ItBt': 'IterBTrack',
                'X_L': 'L',
                'X_Rsdl': 'Rsdl'
            }
            evlmap = {}

        # If Backtracking enabled in xstep display the BT variables also
        if xstep.opt['BackTrack', 'Enabled']:
            isfld.extend(
                ['X_F_Btrack', 'X_Q_Btrack', 'X_ItBt', 'X_L', 'X_Rsdl'])
            hdrtxt.extend(['F_X', 'Q_X', 'It_X', 'L_X'])
            hdrmap.update({
                'F_X': 'X_F_Btrack',
                'Q_X': 'X_Q_Btrack',
                'It_X': 'X_ItBt',
                'L_X': 'X_L'
            })
        else:  # Add just L value to xstep display
            isfld.extend(['X_L', 'X_Rsdl'])
            hdrtxt.append('L_X')
            hdrmap.update({'L_X': 'X_L'})

        isdmap = {
            'Cnstr': 'Cnstr',
            'D_F_Btrack': 'F_Btrack',
            'D_Q_Btrack': 'Q_Btrack',
            'D_ItBt': 'IterBTrack',
            'D_L': 'L',
            'D_Rsdl': 'Rsdl'
        }

        # If Backtracking enabled in dstep display the BT variables also
        if dstep.opt['BackTrack', 'Enabled']:
            isfld.extend([
                'D_F_Btrack', 'D_Q_Btrack', 'D_ItBt', 'D_L', 'D_Rsdl', 'Time'
            ])
            hdrtxt.extend(['F_D', 'Q_D', 'It_D', 'L_D'])
            hdrmap.update({
                'F_D': 'D_F_Btrack',
                'Q_D': 'D_Q_Btrack',
                'It_D': 'D_ItBt',
                'L_D': 'D_L'
            })
        else:  # Add just L value to dstep display
            isfld.extend(['D_L', 'D_Rsdl', 'Time'])
            hdrtxt.append('L_D')
            hdrmap.update({'L_D': 'D_L'})

        isc = dictlrn.IterStatsConfig(isfld=isfld,
                                      isxmap=isxmap,
                                      isdmap=isdmap,
                                      evlmap=evlmap,
                                      hdrtxt=hdrtxt,
                                      hdrmap=hdrmap)

        # Call parent constructor
        super(ConvBPDNDictLearn, self).__init__(xstep, dstep, opt, isc)
예제 #9
0
    def __init__(self,
                 D0,
                 S,
                 lmbda,
                 W,
                 opt=None,
                 method='cns',
                 dimK=1,
                 dimN=2):
        """
        Initialise a ConvBPDNMaskDcplDictLearn object with problem size and
        options.

        |

        **Call graph**

        .. image:: _static/jonga/cbpdnmddl_init.svg
           :width: 20%
           :target: _static/jonga/cbpdnmddl_init.svg

        |


        Parameters
        ----------
        D0 : array_like
          Initial dictionary array
        S : array_like
          Signal array
        lmbda : float
          Regularisation parameter
        W : array_like
          Mask array. The array shape must be such that the array is
          compatible for multiplication with the *internal* shape of
          input array S (see :class:`.cnvrep.CDU_ConvRepIndexing` for a
          discussion of the distinction between *external* and *internal*
          data layouts).
        opt : :class:`ConvBPDNMaskDcplDictLearn.Options` object
          Algorithm options
        method : string, optional (default 'cns')
          String selecting dictionary update solver. Valid values are
          documented in function :func:`.ConvCnstrMODMaskDcpl`.
        dimK : int, optional (default 1)
          Number of signal dimensions. If there is only a single input
          signal (e.g. if `S` is a 2D array representing a single image)
          `dimK` must be set to 0.
        dimN : int, optional (default 2)
          Number of spatial/temporal dimensions
        """

        if opt is None:
            opt = ConvBPDNMaskDcplDictLearn.Options(method=method)
        self.opt = opt

        # Get dictionary size
        if self.opt['DictSize'] is None:
            dsz = D0.shape
        else:
            dsz = self.opt['DictSize']

        # Construct object representing problem dimensions
        cri = cr.CDU_ConvRepIndexing(dsz, S, dimK, dimN)

        # Normalise dictionary
        D0 = cr.Pcn(D0,
                    dsz,
                    cri.Nv,
                    dimN,
                    cri.dimCd,
                    crp=True,
                    zm=opt['CCMOD', 'ZeroMean'])

        # Modify D update options to include initial values for Y and U
        if cri.C == cri.Cd:
            Y0b0 = np.zeros(cri.Nv + (cri.C, 1, cri.K))
        else:
            Y0b0 = np.zeros(cri.Nv + (1, 1, cri.C * cri.K))
        Y0b1 = cr.zpad(cr.stdformD(D0, cri.Cd, cri.M, dimN), cri.Nv)
        if method == 'cns':
            Y0 = Y0b1
        else:
            Y0 = np.concatenate((Y0b0, Y0b1), axis=cri.axisM)
        opt['CCMOD'].update({'Y0': Y0})

        # Create X update object
        xstep = cbpdn.ConvBPDNMaskDcpl(D0,
                                       S,
                                       lmbda,
                                       W,
                                       opt['CBPDN'],
                                       dimK=dimK,
                                       dimN=dimN)

        # Create D update object
        dstep = ccmodmd.ConvCnstrMODMaskDcpl(None,
                                             S,
                                             W,
                                             dsz,
                                             opt['CCMOD'],
                                             method=method,
                                             dimK=dimK,
                                             dimN=dimN)

        # Configure iteration statistics reporting
        if self.opt['AccurateDFid']:
            isxmap = {
                'XPrRsdl': 'PrimalRsdl',
                'XDlRsdl': 'DualRsdl',
                'XRho': 'Rho'
            }
            evlmap = {'ObjFun': 'ObjFun', 'DFid': 'DFid', 'RegL1': 'RegL1'}
        else:
            isxmap = {
                'ObjFun': 'ObjFun',
                'DFid': 'DFid',
                'RegL1': 'RegL1',
                'XPrRsdl': 'PrimalRsdl',
                'XDlRsdl': 'DualRsdl',
                'XRho': 'Rho'
            }
            evlmap = {}
        isc = dictlrn.IterStatsConfig(isfld=[
            'Iter', 'ObjFun', 'DFid', 'RegL1', 'Cnstr', 'XPrRsdl', 'XDlRsdl',
            'XRho', 'DPrRsdl', 'DDlRsdl', 'DRho', 'Time'
        ],
                                      isxmap=isxmap,
                                      isdmap={
                                          'Cnstr': 'Cnstr',
                                          'DPrRsdl': 'PrimalRsdl',
                                          'DDlRsdl': 'DualRsdl',
                                          'DRho': 'Rho'
                                      },
                                      evlmap=evlmap,
                                      hdrtxt=[
                                          'Itn', 'Fnc', 'DFid',
                                          u('ℓ1'), 'Cnstr', 'r_X', 's_X',
                                          u('ρ_X'), 'r_D', 's_D',
                                          u('ρ_D')
                                      ],
                                      hdrmap={
                                          'Itn': 'Iter',
                                          'Fnc': 'ObjFun',
                                          'DFid': 'DFid',
                                          u('ℓ1'): 'RegL1',
                                          'Cnstr': 'Cnstr',
                                          'r_X': 'XPrRsdl',
                                          's_X': 'XDlRsdl',
                                          u('ρ_X'): 'XRho',
                                          'r_D': 'DPrRsdl',
                                          's_D': 'DDlRsdl',
                                          u('ρ_D'): 'DRho'
                                      })

        # Call parent constructor
        super(ConvBPDNMaskDcplDictLearn, self).__init__(xstep, dstep, opt, isc)
예제 #10
0
    def __init__(self,
                 D0,
                 S,
                 lmbda=None,
                 opt=None,
                 method='cns',
                 dimK=1,
                 dimN=2,
                 stopping_pobj=None):
        """
        Initialise a ConvBPDNDictLearn object with problem size and options.

        |

        **Call graph**

        .. image:: _static/jonga/cbpdndl_init.svg
           :width: 20%
           :target: _static/jonga/cbpdndl_init.svg

        |


        Parameters
        ----------
        D0 : array_like
          Initial dictionary array
        S : array_like
          Signal array
        lmbda : float
          Regularisation parameter
        opt : :class:`ConvBPDNDictLearn.Options` object
          Algorithm options
        method : string, optional (default 'cns')
          String selecting dictionary update solver. Valid values are
          documented in function :func:`.ConvCnstrMOD`.
        dimK : int, optional (default 1)
          Number of signal dimensions. If there is only a single input
          signal (e.g. if `S` is a 2D array representing a single image)
          `dimK` must be set to 0.
        dimN : int, optional (default 2)
          Number of spatial/temporal dimensions
        """

        if opt is None:
            opt = ConvBPDNDictLearn.Options(method=method)
        self.opt = opt

        self.stopping_pobj = stopping_pobj

        # Get dictionary size
        if self.opt['DictSize'] is None:
            dsz = D0.shape
        else:
            dsz = self.opt['DictSize']

        # Construct object representing problem dimensions
        cri = cr.CDU_ConvRepIndexing(dsz, S, dimK, dimN)

        # Normalise dictionary
        D0 = cr.Pcn(D0,
                    dsz,
                    cri.Nv,
                    dimN,
                    cri.dimCd,
                    crp=True,
                    zm=opt['CCMOD', 'ZeroMean'])

        # Modify D update options to include initial values for Y and U
        opt['CCMOD'].update(
            {'Y0': cr.zpad(cr.stdformD(D0, cri.C, cri.M, dimN), cri.Nv)})

        # Create X update object
        xstep = cbpdn.ConvBPDN(D0,
                               S,
                               lmbda,
                               opt['CBPDN'],
                               dimK=dimK,
                               dimN=dimN)

        # Create D update object
        dstep = ccmod.ConvCnstrMOD(None,
                                   S,
                                   dsz,
                                   opt['CCMOD'],
                                   method=method,
                                   dimK=dimK,
                                   dimN=dimN)

        # Configure iteration statistics reporting
        if self.opt['AccurateDFid']:
            isxmap = {
                'XPrRsdl': 'PrimalRsdl',
                'XDlRsdl': 'DualRsdl',
                'XRho': 'Rho'
            }
            evlmap = {'ObjFun': 'ObjFun', 'DFid': 'DFid', 'RegL1': 'RegL1'}
        else:
            isxmap = {
                'ObjFun': 'ObjFun',
                'DFid': 'DFid',
                'RegL1': 'RegL1',
                'XPrRsdl': 'PrimalRsdl',
                'XDlRsdl': 'DualRsdl',
                'XRho': 'Rho'
            }
            evlmap = {}
        isc = dictlrn.IterStatsConfig(isfld=[
            'Iter', 'ObjFun', 'DFid', 'RegL1', 'Cnstr', 'XPrRsdl', 'XDlRsdl',
            'XRho', 'DPrRsdl', 'DDlRsdl', 'DRho', 'Time'
        ],
                                      isxmap=isxmap,
                                      isdmap={
                                          'Cnstr': 'Cnstr',
                                          'DPrRsdl': 'PrimalRsdl',
                                          'DDlRsdl': 'DualRsdl',
                                          'DRho': 'Rho'
                                      },
                                      evlmap=evlmap,
                                      hdrtxt=[
                                          'Itn', 'Fnc', 'DFid',
                                          u('ℓ1'), 'Cnstr', 'r_X', 's_X',
                                          u('ρ_X'), 'r_D', 's_D',
                                          u('ρ_D')
                                      ],
                                      hdrmap={
                                          'Itn': 'Iter',
                                          'Fnc': 'ObjFun',
                                          'DFid': 'DFid',
                                          u('ℓ1'): 'RegL1',
                                          'Cnstr': 'Cnstr',
                                          'r_X': 'XPrRsdl',
                                          's_X': 'XDlRsdl',
                                          u('ρ_X'): 'XRho',
                                          'r_D': 'DPrRsdl',
                                          's_D': 'DDlRsdl',
                                          u('ρ_D'): 'DRho'
                                      })

        # Call parent constructor
        super(ConvBPDNDictLearn, self).__init__(xstep, dstep, opt, isc)
예제 #11
0
            method='ism')


"""
Normalise dictionary according to dictionary Y update options.
"""

D0n = cnvrep.Pcn(D0, D0.shape, cri.Nv, dimN=2, dimC=0, crp=True,
                 zm=optd['ZeroMean'])


"""
Update D update options to include initial values for Y and U.
"""

optd.update({'Y0': cnvrep.zpad(cnvrep.stdformD(D0n, cri.Cd, cri.M), cri.Nv),
             'U0': np.zeros(cri.shpD)})


"""
Create X update object.
"""

xstep = cbpdn.ConvBPDNJoint(D0n, sh, lmbda, mu, optx)


"""
Create D update object.
"""

dstep = ccmod.ConvCnstrMOD(None, sh, D0.shape, optd, method='ism')
예제 #12
0
def nakashizuka_solve(
    cri, Dr0, Xr, Sr,
    final_sigma,
    maxitr = 40,
    param_mu = 1,
    param_lambda = 1e-2,
    debug_dir = None
):
    
    param_rho = 0.5

    Xr = Xr.copy()
    Sr = Sr.copy()
    Dr = Dr0.copy()
    Hr = np.zeros_like(cnvrep.zpad(Dr, cri.Nv))

    Sf = to_frequency(cri, Sr)

    # sigma set
    # sigma_list = []
    # sigma_list.append(Xr.max()*4)
    # for i in range(7):
    #     sigma_list.append(sigma_list[i]*0.5)
    first_sigma = Xr.max()*4
    c = (final_sigma / first_sigma) ** (1/(maxitr - 1))
    print("c = %.8f" % c)
    sigma_list = []
    sigma_list.append(first_sigma)
    for i in range(maxitr - 1):
        sigma_list.append(sigma_list[i]*c)
    
    crop_op = []
    for l in Dr.shape:
        crop_op.append(slice(0, l))
    crop_op = tuple(crop_op)
    Pcn = cnvrep.getPcn(Dr.shape, cri.Nv, cri.dimN, cri.dimCd, zm=False)

    updcnt = 0
    dictcnt = 0
    for sigma in sigma_list:
        print("sigma = %.8f" % sigma)
        # Xf_old = sl.rfftn(Xr, cri.Nv, cri.axisN)
        for l in range(1):
            # print("l0norm: %f" % l0norm(Xr, sigma_list[-1]))
            # print('error1: ', l2norm(Sr - reconstruct(cri, Dr, Xr)))
            # print("l2(Xr): %.6f, l2(delta): %.6f" % (l2norm(Xr), l2norm(delta)))
            delta = Xr * np.exp(-(Xr*Xr) / (2*sigma*sigma))
            Xr = Xr - param_mu*delta# + np.random.randn(*Xr.shape)*sigma*1e-1
            Xf = to_frequency(cri, Xr)

            # print('error2: ', l2norm(Sr - reconstruct(cri, Dr, Xr)))

            Df = to_frequency(cri, Dr)
            b = Xf / param_lambda + np.conj(Df) * Sf
            Xf = sl.solvedbi_sm(Df, 1/param_lambda, b, axis=cri.axisM)
            Xr = to_spatial(cri, Xf).astype(np.float32)
            
            # print('error3: ', l2norm(Sr - reconstruct(cri, Dr, Xr)))

            # save_reconstructed(cri, Dr, Xr, Sr, "./rec/%da.png" % reccnt)
            # saveXhist(Xr, "./hist/%da.png" % reccnt)

            Dr, Hr = update_dict(cri, Pcn, crop_op, Xr, Dr, Hr, Sf, param_rho)
            Df = to_frequency(cri, Dr)
            
            # print('error4: ', l2norm(Sr - reconstruct(cri, Dr, Xr)))

            # # project X to solution space
            # b = sl.inner(Df, Xf, axis=cri.axisM) - Sf
            # c = sl.inner(Df, np.conj(Df), axis=cri.axisM)
            # Xf = Xf - np.conj(Df) / c * b
            # Xr = sl.irfftn(Xf, s=cri.Nv, axes=cri.axisN)

            # print('error5: ', l2norm(Sr - reconstruct(cri, Dr, Xr)))
            
            if debug_dir is not None:
                saveimg(util.tiledict(Dr.squeeze()), debug_dir + "/dict/%d.png" % updcnt)

            updcnt += 1

        # saveXhist(Xr, "Xhist_sigma=" + str(sigma) + ".png")
    
    # print("l0 norm of final X: %d" % smoothedl0norm(Xr, 0.00001))
    plot.close()
    mplot.close()
    return Dr
예제 #13
0
Sh = S*2 - Smean

# TODO: explicitly zero-padding (for me, foolish)
D = np.random.randn(12, 12, 256)
# D = np.random.rand(12, 12, 64)*2 - 1
cri = cnvrep.CSC_ConvRepIndexing(D, S)
Dr0 = np.asarray(D.reshape(cri.shpD), dtype=S.dtype)
Slr = np.asarray(Sl.reshape(cri.shpS), dtype=S.dtype)
Shr = np.asarray(Sh.reshape(cri.shpS), dtype=S.dtype)
Shf = sl.rfftn(Shr, s=cri.Nv, axes=cri.axisN) # implicitly zero-padding

crop_op = []
for l in Dr0.shape:
    crop_op.append(slice(0, l))
crop_op = tuple(crop_op)
Dr0 = cnvrep.getPcn(Dr0.shape, cri.Nv, cri.dimN, cri.dimCd, zm=False)(cnvrep.zpad(Dr0, cri.Nv))[crop_op]
# Dr = normalize(Dr, axis=cri.axisM)

# Xr = l2norm_minimize(cri, Dr0, Shr)
# Dr = mysolve(cri, Dr0, Xr, Shr, 1e-4, maxitr=50, debug_dir='./debug')
# # Dr = nakashizuka_solve(cri, Dr0, Xr, Shr, debug_dir='./debug')
# # Dr = sporcosolve(cri, Dr, Shr)
# # fig = plot.figure(figsize=(7, 7))
# # plot.imview(util.tiledict(Dr.squeeze()), fig=fig)
# # fig.savefig('dict.png')
# # # evaluate_result(cri, Dr0, Dr, Shr, Sr_add=Slr)


exim1 = util.ExampleImages(scaled=True, zoom=0.5, pth='./')
S1_test = exim1.image('couple.tiff')
exim2 = util.ExampleImages(scaled=True, zoom=1, pth='./')