Get the DICOM files from 'fpth' into an image with the affine transformation.
        fpth can be a list of DICOM files or a path (string) to the folder with DICOM files.
429992
def dcm2im(fpth):
    ''' 
    '''

    # possible DICOM file extensions
    ext = ('dcm', 'DCM', 'ima', 'IMA') 
    
    # case when given a folder path
    if isinstance(fpth, basestring) and os.path.isdir(fpth):
        SZ0 = len([d for d in os.listdir(fpth) if d.endswith(ext)])
        # list of DICOM files
        fdcms = os.listdir(fpth)
        fdcms = [os.path.join(fpth,f) for f in fdcms if f.endswith(ext)]
    
    # case when list of DICOM files is given
    elif isinstance(fpth, list) and os.path.isfile(os.path.join(fpth[0])):
        SZ0 = len(fpth)
        # list of DICOM files
        fdcms = fpth
        fdcms = [f for f in fdcms if f.endswith(ext)]
    else:
        raise NameError('Unrecognised input for DICOM files.')

    if SZ0<1:
        print 'e> no DICOM images in the specified path.'
        raise IOError('Input DICOM images not recognised')

    # pick single DICOM header
    dhdr = dcm.read_file(fdcms[0])

    #------------------------------------
    # some info, e.g.: patient position and series UID
    if [0x018, 0x5100] in dhdr:
        ornt = dhdr[0x18,0x5100].value
    else:
        ornt = 'unkonwn'
    # Series UID
    sruid = dhdr[0x0020, 0x000e].value
    #------------------------------------

    #------------------------------------
    # INIT
    # image position 
    P = np.zeros((SZ0,3), dtype=np.float64)
    #image orientation
    Orn = np.zeros((SZ0,6), dtype=np.float64)
    #xy resolution
    R = np.zeros((SZ0,2), dtype=np.float64)
    #slice thickness
    S = np.zeros((SZ0,1), dtype=np.float64)
    #slope and intercept
    SI = np.ones((SZ0,2), dtype=np.float64)
    SI[:,1] = 0

    #image data as an list of array for now
    IM = []
    #------------------------------------

    c = 0
    for d in fdcms:
        dhdr = dcm.read_file(d)
        if [0x20,0x32] in dhdr and [0x20,0x37] in dhdr and [0x28,0x30] in dhdr:
            P[c,:] = np.array([float(f) for f in dhdr[0x20,0x32].value])
            Orn[c,:] = np.array([float(f) for f in dhdr[0x20,0x37].value])
            R[c,:] = np.array([float(f) for f in dhdr[0x28,0x30].value])
            S[c,:] = float(dhdr[0x18,0x50].value)
        else:
            print 'e> could not read all the DICOM tags.'
            return {'im':[], 'affine':[], 'shape':[], 'orient':ornt, 'sruid':sruid}
            
        if [0x28,0x1053] in dhdr and [0x28,0x1052] in dhdr:
            SI[c,0] = float(dhdr[0x28,0x1053].value)
            SI[c,1] = float(dhdr[0x28,0x1052].value)
        IM.append(dhdr.pixel_array)
        c += 1


    #check if orientation/resolution is the same for all slices
    if np.sum(Orn-Orn[0,:]) > 1e-6:
        print 'e> varying orientation for slices'
    else:
        Orn = Orn[0,:]
    if np.sum(R-R[0,:]) > 1e-6:
        print 'e> varying resolution for slices'
    else:
        R = R[0,:]

    # Patient Position
    #patpos = dhdr[0x18,0x5100].value
    # Rows and Columns
    if [0x28,0x10] in dhdr and [0x28,0x11] in dhdr:
        SZ2 = dhdr[0x28,0x10].value
        SZ1 = dhdr[0x28,0x11].value
    # image resolution
    SZ_VX2 = R[0]
    SZ_VX1 = R[1]

    #now sort the images along k-dimension
    k = np.argmin(abs(Orn[:3]+Orn[3:]))
    #sorted indeces
    si = np.argsort(P[:,k])
    Pos = np.zeros(P.shape, dtype=np.float64)
    im = np.zeros((SZ0, SZ1, SZ2 ), dtype=np.float32)

    #check if the detentions are in agreement (the pixel array could be transposed...)
    if IM[0].shape[0]==SZ1:
        for i in range(SZ0):
            im[i,:,:] = IM[si[i]]*SI[si[i],0] + SI[si[i],1]
            Pos[i,:] = P[si[i]]
    else:
        for i in range(SZ0):
            im[i,:,:] = IM[si[i]].T * SI[si[i],0] + SI[si[i],1]
            Pos[i,:] = P[si[i]]

    # proper slice thickness
    Zz = (P[si[-1],2] - P[si[0],2])/(SZ0-1)
    Zy = (P[si[-1],1] - P[si[0],1])/(SZ0-1)
    Zx = (P[si[-1],0] - P[si[0],0])/(SZ0-1)
    

    # dictionary for affine and image size for the image
    A = {
        'AFFINE':np.array([[SZ_VX2*Orn[0], SZ_VX1*Orn[3], Zx, Pos[0,0]],
                           [SZ_VX2*Orn[1], SZ_VX1*Orn[4], Zy, Pos[0,1]],
                           [SZ_VX2*Orn[2], SZ_VX1*Orn[5], Zz, Pos[0,2]],
                           [0., 0., 0., 1.]]),
        'SHAPE':(SZ0, SZ1, SZ2)
    }

    #the returned image is already scaled according to the dcm header
    return {'im':im, 'affine':A['AFFINE'], 'shape':A['SHAPE'], 'orient':ornt, 'sruid':sruid}
585822
def to_pngs(pdf_path):
  ''' 
  '''
  pdf_list = split_pdf(pdf_path)
  pngs = []
  for pdf in pdf_list:
    pngs.append(to_png(pdf))
    os.remove(pdf)  # Clean up
  return pngs
333866
def _get_affine_transform(self):
        """"""
        # How big is the projected globe?
        # In the case of a stereonet, it's actually constant.
        xscale = yscale = self._scale
        # Create an affine transform to stretch the projection from 0-1
        return Affine2D() \
            .rotate(np.radians(self.rotation)) \
            .scale(0.5 / xscale, 0.5 / yscale) \
            .translate(0.5, 0.5)
287980
def file(suffix='', prefix='tmp', parent=None):
    '''
    
    '''
    fh_, tmp_ = tempfile.mkstemp(suffix, prefix, parent)
    os.close(fh_)
    return tmp_
1257748
def _image2array(filepath):
    '''
    
    '''
    im = Pimage.open(filepath).convert('RGB')
    (width, height) = im.size
    _r = np.array(list(im.getdata(0)))/255.0
    _g = np.array(list(im.getdata(1)))/255.0
    _b = np.array(list(im.getdata(2)))/255.0
    _r = _r.reshape((height, width))
    _g = _g.reshape((height, width))
    _b = _b.reshape((height, width))
    return _r, _g, _b
164874
def list_all_image(path, valid_exts=VALID_IMAGE_EXTS):
    
    for filename in os.listdir(path):
        bname, ext = os.path.splitext(filename)
        if ext.lower() not in VALID_IMAGE_EXTS:
            continue
        filepath = os.path.join(path, filename)
        yield strutils.decode(filepath)
359856
function mapImages(imageMap, srcFolder, destFolder) {
  return through.obj(function(file, enc, cb) {
    // find the relative path to image. If any pipe has changed the filename,
    // it's the original is set in orgRelative, so we look at that first.
    var relativeFrom = file.orgRelative || file.relative;
    var relativeTo = path.join(destFolder, file.relative);
    imageMap[relativeFrom] = relativeTo;
    cb(null, file);
  });
}
67424
def convert(files, **kwargs):
    

    if len(files) < 1:
        raise ValueError("Files needs to be a non-empty list")

    if len(files) == 1:
        if os.path.isfile(files[0]):
            return files_to_pif(files, **kwargs)
        else:
            return directory_to_pif(files[0], **kwargs)
    else:
        return files_to_pif([x for x in files if os.path.isfile(x)], **kwargs)
1027787
def get_files_by_path(path):
    '''
    '''
    if os.path.isfile(path):
        return [path]
    if os.path.isdir(path):
        return get_morph_files(path)

    raise IOError('Invalid data path %s' % path)
1292369
def _get_file_paths(cur):
    
    out = []
    if isinstance(cur, (list, tuple)):
        for x in cur:
            new = _get_file_paths(x)
            if new:
                out.extend(new)
    elif isinstance(cur, dict):
        if "class" in cur:
            out.append(cur["path"])
        else:
            for k, v in cur.items():
                new = _get_file_paths(v)
                if new:
                    out.extend(new)
    return out
142245
def transform(images, out_dir, fname):
        
        from PIL import Image as PILImage
        base = os.path.join(out_dir, "media", "images")
        width, height = images[0].image.size
        num_images_to_log = len(images)

        if num_images_to_log > Image.MAX_IMAGES:
            logging.warn(
                "The maximum number of images to store per step is %i." % Image.MAX_IMAGES)
            num_images_to_log = Image.MAX_IMAGES

        if width * num_images_to_log > Image.MAX_DIMENSION:
            max_images_by_dimension = Image.MAX_DIMENSION // width
            logging.warn("The maximum total width for all images in a collection is 65500, or {} images, each with a width of {} pixels. Only logging the first {} images.".format(max_images_by_dimension, width, max_images_by_dimension))
            num_images_to_log = max_images_by_dimension

        total_width = width * num_images_to_log
        sprite = PILImage.new(
            mode='RGB',
            size=(total_width, height),
            color=(0, 0, 0))
        for i, image in enumerate(images[:num_images_to_log]):
            location = width * i
            sprite.paste(image.image, (location, 0))
        util.mkdir_exists_ok(base)
        sprite.save(os.path.join(base, fname), transparency=0)
        meta = {"width": width, "height": height,
                "count": num_images_to_log, "_type": "images"}
        # TODO: hacky way to enable image grouping for now
        grouping = images[0].grouping
        if grouping:
            meta["grouping"] = grouping
        captions = Image.captions(images[:num_images_to_log])
        if captions:
            meta["captions"] = captions
        return meta
562862
def generate_images(self, pixmaps):
        
        new_images = []

        for image in pixmaps:
            tmp_image = {}
            for img_item in pixmaps[image]:
                if img_item == 'path':
                    path = os.path.join('images',
                                        os.path.basename(
                                            pixmaps[image][img_item]))
                    tmp_image['path'] = fix_path(path)
                    self.images.append(pixmaps[image][img_item])
                else:
                    tmp_image[img_item] = pixmaps[image][img_item]

            new_images.append(tmp_image)

        return new_images
686845
def gengraphs(pth, nopyfftw):
    

    srcmodflt = '^sporco.admm'
    srcqnmflt = r'^((?!<locals>|__new|_name_nested).)*$'
    dstqnmflt = r'^((?!<locals>|__new|_name_nested).)*$'

    fnmsub = ('^sporco.admm.', '')
    grpflt = r'^[^\.]*.[^\.]*'
    lnkpfx = '../../modules/'
    lnksub = (r'^([^\.]*).([^\.]*)(?:(.__init__|.__call__)|(.[^\.]*))',
              lnkpfx + r'sporco.admm.\1.html#sporco.admm.\1.\2\4')


    fntsz = 9
    fntfm = 'Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans'
    kwargs = {'fntsz': fntsz, 'fntfm': fntfm, 'rmsz': True}


    ct = jonga.CallTracer(srcmodflt=srcmodflt, srcqnmflt=srcqnmflt,
                          dstqnmflt=dstqnmflt, fnmsub=fnmsub,
                          grpflt=grpflt, lnksub=lnksub)


    # Make destination directory if it doesn't exist
    if not os.path.exists(pth):
        os.makedirs(pth, exist_ok=True)


    # Handle environment in which pyfftw is unavailable
    if nopyfftw:
        import numpy.fft as npfft
        import sporco.linalg as spl

        def empty(shape, dtype, order='C', n=None):
            return np.zeros(shape, dtype=dtype)
        empty.__doc__ = spl.pyfftw_empty_aligned.__doc__
        spl.pyfftw_empty_aligned = empty


        def rfftn_empty(shape, axes, dtype, order='C', n=None):
            ashp = list(shape)
            raxis = axes[-1]
            ashp[raxis] = ashp[raxis] // 2 + 1
            cdtype = spl.complex_dtype(dtype)
            return np.zeros(ashp, dtype=cdtype)
        rfftn_empty.__doc__ = spl.pyfftw_rfftn_empty_aligned.__doc__
        spl.pyfftw_rfftn_empty_aligned = rfftn_empty

        npfft.fftn.__doc__ = spl.fftn.__doc__
        spl.fftn = npfft.fftn
        npfft.ifftn.__doc__ = spl.ifftn.__doc__
        spl.ifftn = npfft.ifftn
        npfft.rfftn.__doc__ = spl.rfftn.__doc__
        spl.rfftn = npfft.rfftn
        npfft.irfftn.__doc__ = spl.irfftn.__doc__
        spl.irfftn = npfft.irfftn


    import numpy as np
    np.random.seed(12345)


    #### bpdn module
    from sporco.admm import bpdn
    mdnm = 'sporco.admm.bpdn'

    D = np.random.randn(8, 16)
    s = np.random.randn(8, 1)
    lmbda = 0.1

    ## BPDN class
    opt = bpdn.BPDN.Options({'Verbose': False, 'MaxMainIter': 1})

    with CallGraph(ct, mdnm, pth, 'bpdn_init.svg', **kwargs):
        b = bpdn.BPDN(D, s, lmbda, opt)

    with CallGraph(ct, mdnm, pth, 'bpdn_solve.svg', **kwargs):
        b.solve()


    ## BPDNJoint class
    opt = bpdn.BPDNJoint.Options({'Verbose': False, 'MaxMainIter': 1})
    mu = 0.01

    with CallGraph(ct, mdnm, pth, 'bpdnjnt_init.svg', **kwargs):
        b = bpdn.BPDNJoint(D, s, lmbda, mu, opt)

    with CallGraph(ct, mdnm, pth, 'bpdnjnt_solve.svg', **kwargs):
        b.solve()


    ## ElasticNet class
    opt = bpdn.ElasticNet.Options({'Verbose': False, 'MaxMainIter': 1})

    with CallGraph(ct, mdnm, pth, 'elnet_init.svg', **kwargs):
        b = bpdn.ElasticNet(D, s, lmbda, mu, opt)

    with CallGraph(ct, mdnm, pth, 'elnet_solve.svg', **kwargs):
        b.solve()


    # BPDNProjL1 class
    opt = bpdn.BPDNProjL1.Options({'Verbose': False, 'MaxMainIter': 1})
    gamma = 2.0

    with CallGraph(ct, mdnm, pth, 'bpdnprjl1_init.svg', **kwargs):
        b = bpdn.BPDNProjL1(D, s, gamma, opt)

    with CallGraph(ct, mdnm, pth, 'bpdnprjl1_solve.svg', **kwargs):
        b.solve()


    ## MinL1InL2Ball class
    opt = bpdn.MinL1InL2Ball.Options({'Verbose': False, 'MaxMainIter': 1})
    epsilon = 1.0

    with CallGraph(ct, mdnm, pth, 'bpdnml1l2_init.svg', **kwargs):
        b = bpdn.MinL1InL2Ball(D, s, epsilon, opt)

    with CallGraph(ct, mdnm, pth, 'bpdnml1l2_solve.svg', **kwargs):
        b.solve()




    #### cbpdn module
    from sporco.admm import cbpdn
    mdnm = 'sporco.admm.cbpdn'

    D = np.random.randn(4, 4, 16)
    s = np.random.randn(8, 8)
    lmbda = 0.1

    ## ConvBPDN class
    opt = cbpdn.ConvBPDN.Options({'Verbose': False, 'MaxMainIter': 1})

    with CallGraph(ct, mdnm, pth, 'cbpdn_init.svg', **kwargs):
        b = cbpdn.ConvBPDN(D, s, lmbda, opt)

    with CallGraph(ct, mdnm, pth, 'cbpdn_solve.svg', **kwargs):
        b.solve()


    ## ConvBPDNJoint class
    opt = cbpdn.ConvBPDNJoint.Options({'Verbose': False, 'MaxMainIter': 1})
    mu = 0.01

    with CallGraph(ct, mdnm, pth, 'cbpdnjnt_init.svg', **kwargs):
        b = cbpdn.ConvBPDNJoint(D, s, lmbda, mu, opt)

    with CallGraph(ct, mdnm, pth, 'cbpdnjnt_solve.svg', **kwargs):
        b.solve()


    ## ConvElasticNet class
    opt = cbpdn.ConvElasticNet.Options({'Verbose': False, 'MaxMainIter': 1})

    with CallGraph(ct, mdnm, pth, 'celnet_init.svg', **kwargs):
        b = cbpdn.ConvElasticNet(D, s, lmbda, mu, opt)

    with CallGraph(ct, mdnm, pth, 'celnet_solve.svg', **kwargs):
        b.solve()


    ## ConvBPDNGradReg class
    opt = cbpdn.ConvBPDNGradReg.Options({'Verbose': False, 'MaxMainIter': 1})

    with CallGraph(ct, mdnm, pth, 'cbpdngrd_init.svg', **kwargs):
        b = cbpdn.ConvBPDNGradReg(D, s, lmbda, mu, opt)

    with CallGraph(ct, mdnm, pth, 'cbpdngrd_solve.svg', **kwargs):
        b.solve()


    ## ConvBPDNProjL1 class
    opt = cbpdn.ConvBPDNProjL1.Options({'Verbose': False, 'MaxMainIter': 1})
    gamma = 0.5

    with CallGraph(ct, mdnm, pth, 'cbpdnprjl1_init.svg', **kwargs):
        b = cbpdn.ConvBPDNProjL1(D, s, gamma, opt)

    with CallGraph(ct, mdnm, pth, 'cbpdnprjl1_solve.svg', **kwargs):
        b.solve()


    ## ConvMinL1InL2Ball class
    opt = cbpdn.ConvMinL1InL2Ball.Options({'Verbose': False, 'MaxMainIter': 1})
    epsilon = 0.5

    with CallGraph(ct, mdnm, pth, 'cbpdnml1l2_init.svg', **kwargs):
        b = cbpdn.ConvMinL1InL2Ball(D, s, epsilon, opt)

    with CallGraph(ct, mdnm, pth, 'cbpdnml1l2_solve.svg', **kwargs):
        b.solve()


    ## ConvBPDNMaskDcpl class
    opt = cbpdn.ConvBPDNMaskDcpl.Options({'Verbose': False, 'MaxMainIter': 1})
    W = np.ones(s.shape)

    with CallGraph(ct, mdnm, pth, 'cbpdnmd_init.svg', **kwargs):
        b = cbpdn.ConvBPDNMaskDcpl(D, s, lmbda, W, opt)

    with CallGraph(ct, mdnm, pth, 'cbpdnmd_solve.svg', **kwargs):
        b.solve()


    ## ConvL1L1Grd class
    opt = cbpdn.ConvL1L1Grd.Options({'Verbose': False, 'MaxMainIter': 1})
    mu = 1e-2

    with CallGraph(ct, mdnm, pth, 'cl1l1grd_init.svg', **kwargs):
        b = cbpdn.ConvL1L1Grd(D, s, lmbda, mu, W, opt)

    with CallGraph(ct, mdnm, pth, 'cl1l1grd_solve.svg', **kwargs):
        b.solve()




    #### cbpdntv module
    from sporco.admm import cbpdntv
    mdnm = 'sporco.admm.cbpdntv'

    D = np.random.randn(4, 4, 16)
    s = np.random.randn(8, 8)
    lmbda = 0.1
    mu = 0.01

    ## ConvBPDNScalarTV class
    opt = cbpdntv.ConvBPDNScalarTV.Options({'Verbose': False, 'MaxMainIter': 1})

    with CallGraph(ct, mdnm, pth, 'cbpdnstv_init.svg', **kwargs):
        b = cbpdntv.ConvBPDNScalarTV(D, s, lmbda, mu, opt)

    with CallGraph(ct, mdnm, pth, 'cbpdnstv_solve.svg', **kwargs):
        b.solve()


    ## ConvBPDNVectorTV class
    opt = cbpdntv.ConvBPDNVectorTV.Options({'Verbose': False, 'MaxMainIter': 1})

    with CallGraph(ct, mdnm, pth, 'cbpdnvtv_init.svg', **kwargs):
        b = cbpdntv.ConvBPDNVectorTV(D, s, lmbda, mu, opt)

    with CallGraph(ct, mdnm, pth, 'cbpdnvtv_solve.svg', **kwargs):
        b.solve()


    ## ConvBPDNRecTV class
    opt = cbpdntv.ConvBPDNRecTV.Options({'Verbose': False, 'MaxMainIter': 1})

    with CallGraph(ct, mdnm, pth, 'cbpdnrtv_init.svg', **kwargs):
        b = cbpdntv.ConvBPDNRecTV(D, s, lmbda, mu, opt)

    with CallGraph(ct, mdnm, pth, 'cbpdnrtv_solve.svg', **kwargs):
        b.solve()




    #### cmod module
    from sporco.admm import cmod
    mdnm = 'sporco.admm.cmod'

    X = np.random.randn(8, 16)
    S = np.random.randn(8, 16)

    ## CnstrMOD class
    opt = cmod.CnstrMOD.Options({'Verbose': False, 'MaxMainIter': 1})

    with CallGraph(ct, mdnm, pth, 'cmod_init.svg', **kwargs):
        b = cmod.CnstrMOD(X, S, opt=opt)

    with CallGraph(ct, mdnm, pth, 'cmod_solve.svg', **kwargs):
        b.solve()




    #### ccmod module
    from sporco.admm import ccmod
    mdnm = 'sporco.admm.ccmod'

    X = np.random.randn(8, 8, 1, 2, 1)
    S = np.random.randn(8, 8, 2)
    dsz = (4, 4, 1)

    ## ConvCnstrMOD_IterSM class
    opt = ccmod.ConvCnstrMOD_IterSM.Options({'Verbose': False,
                                             'MaxMainIter': 1})

    with CallGraph(ct, mdnm, pth, 'ccmodism_init.svg', **kwargs):
        b = ccmod.ConvCnstrMOD_IterSM(X, S, dsz=dsz, opt=opt)

    with CallGraph(ct, mdnm, pth, 'ccmodism_solve.svg', **kwargs):
        b.solve()


    ## ConvCnstrMOD_CG class
    opt = ccmod.ConvCnstrMOD_CG.Options({'Verbose': False,
                                         'MaxMainIter': 1,
                                         'CG': {'MaxIter': 1}})

    with CallGraph(ct, mdnm, pth, 'ccmodcg_init.svg', **kwargs):
        b = ccmod.ConvCnstrMOD_CG(X, S, dsz=dsz, opt=opt)

    with CallGraph(ct, mdnm, pth, 'ccmodcg_solve.svg', **kwargs):
        b.solve()


    ## ConvCnstrMOD_Consensus class
    opt = ccmod.ConvCnstrMOD_Consensus.Options({'Verbose': False,
                                                'MaxMainIter': 1})

    with CallGraph(ct, mdnm, pth, 'ccmodcnsns_init.svg', **kwargs):
        b = ccmod.ConvCnstrMOD_Consensus(X, S, dsz=dsz, opt=opt)

    with CallGraph(ct, mdnm, pth, 'ccmodcnsns_solve.svg', **kwargs):
        b.solve()




    #### ccmodmd module
    from sporco.admm import ccmodmd
    mdnm = 'sporco.admm.ccmodmd'

    X = np.random.randn(8, 8, 1, 2, 1)
    S = np.random.randn(8, 8, 2)
    W = np.array([1.0])
    dsz = (4, 4, 1)

    ## ConvCnstrMODMaskDcpl_IterSM class
    opt = ccmodmd.ConvCnstrMODMaskDcpl_IterSM.Options({'Verbose': False,
                                             'MaxMainIter': 1})

    with CallGraph(ct, mdnm, pth, 'ccmodmdism_init.svg', **kwargs):
        b = ccmodmd.ConvCnstrMODMaskDcpl_IterSM(X, S, W, dsz=dsz, opt=opt)

    with CallGraph(ct, mdnm, pth, 'ccmodmdism_solve.svg', **kwargs):
        b.solve()


    ## ConvCnstrMODMaskDcpl_CG class
    opt = ccmodmd.ConvCnstrMODMaskDcpl_CG.Options({'Verbose': False,
                                         'MaxMainIter': 1,
                                         'CG': {'MaxIter': 1}})

    with CallGraph(ct, mdnm, pth, 'ccmodmdcg_init.svg', **kwargs):
        b = ccmodmd.ConvCnstrMODMaskDcpl_CG(X, S, W, dsz=dsz, opt=opt)

    with CallGraph(ct, mdnm, pth, 'ccmodmdcg_solve.svg', **kwargs):
        b.solve()


    ## ConvCnstrMODMaskDcpl_Consensus class
    opt = ccmodmd.ConvCnstrMODMaskDcpl_Consensus.Options({'Verbose': False,
                                                'MaxMainIter': 1})

    with CallGraph(ct, mdnm, pth, 'ccmodmdcnsns_init.svg', **kwargs):
        b = ccmodmd.ConvCnstrMODMaskDcpl_Consensus(X, S, W, dsz=dsz, opt=opt)

    with CallGraph(ct, mdnm, pth, 'ccmodmdcnsns_solve.svg', **kwargs):
        b.solve()




    #### tvl1 module
    from sporco.admm import tvl1
    mdnm = 'sporco.admm.tvl1'

    s = np.random.randn(16, 16)
    lmbda = 0.1

    ## TVL1Denoise class
    opt = tvl1.TVL1Denoise.Options({'Verbose': False, 'MaxMainIter': 1})

    with CallGraph(ct, mdnm, pth, 'tvl1den_init.svg', **kwargs):
        b = tvl1.TVL1Denoise(s, lmbda, opt)

    with CallGraph(ct, mdnm, pth, 'tvl1den_solve.svg', **kwargs):
        b.solve()


    ## TVL1Deconv class
    opt = tvl1.TVL1Deconv.Options({'Verbose': False, 'MaxMainIter': 1})
    h = np.random.randn(3, 3)

    with CallGraph(ct, mdnm, pth, 'tvl1dcn_init.svg', **kwargs):
        b = tvl1.TVL1Deconv(h, s, lmbda, opt)

    with CallGraph(ct, mdnm, pth, 'tvl1dcn_solve.svg', **kwargs):
        b.solve()




    #### tvl2 module
    from sporco.admm import tvl2
    mdnm = 'sporco.admm.tvl2'

    s = np.random.randn(16, 16)
    lmbda = 0.1

    ## TVL2Denoise class
    opt = tvl2.TVL2Denoise.Options({'Verbose': False, 'MaxMainIter': 1})

    with CallGraph(ct, mdnm, pth, 'tvl2den_init.svg', **kwargs):
        b = tvl2.TVL2Denoise(s, lmbda, opt)

    with CallGraph(ct, mdnm, pth, 'tvl2den_solve.svg', **kwargs):
        b.solve()


    ## TVL2Deconv class
    opt = tvl2.TVL2Deconv.Options({'Verbose': False, 'MaxMainIter': 1})
    h = np.random.randn(3, 3)

    with CallGraph(ct, mdnm, pth, 'tvl2dcn_init.svg', **kwargs):
        b = tvl2.TVL2Deconv(h, s, lmbda, opt)

    with CallGraph(ct, mdnm, pth, 'tvl2dcn_solve.svg', **kwargs):
        b.solve()



    srcmodflt = '^sporco.fista'
    fnmsub = ('^sporco.fista.', '')
    lnksub = (r'^([^\.]*).([^\.]*)(?:(.__init__|.__call__)|(.[^\.]*))',
              lnkpfx + r'sporco.fista.\1.html#sporco.fista.\1.\2\4')
    ct = jonga.CallTracer(srcmodflt=srcmodflt, srcqnmflt=srcqnmflt,
                          dstqnmflt=dstqnmflt, fnmsub=fnmsub,
                          grpflt=grpflt, lnksub=lnksub)


    #### fista.cbpdn module
    from sporco.fista import cbpdn
    mdnm = 'sporco.fista.cbpdn'

    D = np.random.randn(4, 4, 16)
    s = np.random.randn(8, 8)
    lmbda = 0.1

    ## ConvBPDN class
    opt = cbpdn.ConvBPDN.Options({'Verbose': False, 'MaxMainIter': 1})

    with CallGraph(ct, mdnm, pth, 'fista_cbpdn_init.svg', **kwargs):
        b = cbpdn.ConvBPDN(D, s, lmbda, opt)

    with CallGraph(ct, mdnm, pth, 'fista_cbpdn_solve.svg', **kwargs):
        b.solve()




    #### fista.ccmod module
    from sporco.fista import ccmod
    mdnm = 'sporco.fista.ccmod'

    X = np.random.randn(8, 8, 1, 2, 1)
    S = np.random.randn(8, 8, 2)
    dsz = (4, 4, 1)

    ## ConvCnstrMOD class
    opt = ccmod.ConvCnstrMOD.Options({'Verbose': False, 'MaxMainIter': 1})

    with CallGraph(ct, mdnm, pth, 'ccmodfista_init.svg', **kwargs):
        b = ccmod.ConvCnstrMOD(X, S, dsz=dsz, opt=opt)

    with CallGraph(ct, mdnm, pth, 'ccmodfista_solve.svg', **kwargs):
        b.solve()


    ## ConvCnstrMODMask class
    opt = ccmod.ConvCnstrMODMask.Options({'Verbose': False,
                                          'MaxMainIter': 1})

    with CallGraph(ct, mdnm, pth, 'ccmodmdfista_init.svg', **kwargs):
        b = ccmod.ConvCnstrMODMask(X, S, W, dsz=dsz, opt=opt)

    with CallGraph(ct, mdnm, pth, 'ccmodmdfista_solve.svg', **kwargs):
        b.solve()




    srcmodflt = '^sporco.dictlrn'
    fnmsub = ('^sporco.dictlrn.', '')
    lnksub = (r'^([^\.]*).([^\.]*)(?:(.__init__|.__call__)|(.[^\.]*))',
              lnkpfx + r'sporco.dictlrn.\1.html#sporco.dictlrn.\1.\2\4')
    ct = jonga.CallTracer(srcmodflt=srcmodflt, srcqnmflt=srcqnmflt,
                          dstqnmflt=dstqnmflt, fnmsub=fnmsub,
                          grpflt=grpflt, lnksub=lnksub)



    #### bpdndl module
    from sporco.dictlrn import bpdndl
    mdnm = 'sporco.dictlrn.bpdndl'

    D0 = np.random.randn(8, 8)
    S = np.random.randn(8, 16)
    lmbda = 0.1

    ## BPDNDictLearn class
    opt = bpdndl.BPDNDictLearn.Options({'Verbose': False, 'MaxMainIter': 1,
                                        'AccurateDFid': True})

    with CallGraph(ct, mdnm, pth, 'bpdndl_init.svg', **kwargs):
        b = bpdndl.BPDNDictLearn(D0, S, lmbda, opt)

    with CallGraph(ct, mdnm, pth, 'bpdndl_solve.svg', **kwargs):
        b.solve()




    #### cbpdndl module
    from sporco.dictlrn import cbpdndl
    mdnm = 'sporco.dictlrn.cbpdndl'

    D0 = np.random.randn(4, 4, 16)
    s = np.random.randn(8, 8, 10)
    lmbda = 0.1

    ## ConvBPDNDictLearn class
    opt = cbpdndl.ConvBPDNDictLearn.Options({'Verbose': False,
                    'MaxMainIter': 1, 'AccurateDFid': True})

    with CallGraph(ct, mdnm, pth, 'cbpdndl_init.svg', **kwargs):
        b = cbpdndl.ConvBPDNDictLearn(D0, s, lmbda, opt)

    with CallGraph(ct, mdnm, pth, 'cbpdndl_solve.svg', **kwargs):
        b.solve()




    #### cbpdndlmd module
    from sporco.dictlrn import cbpdndlmd
    mdnm = 'sporco.dictlrn.cbpdndlmd'

    ## ConvBPDNMaskDcplDictLearn class
    W = np.array([1.0])
    opt = cbpdndlmd.ConvBPDNMaskDictLearn.Options({'Verbose': False,
                    'MaxMainIter': 1, 'AccurateDFid': True})

    with CallGraph(ct, mdnm, pth, 'cbpdnmddl_init.svg', **kwargs):
        b = cbpdndlmd.ConvBPDNMaskDictLearn(D0, s, lmbda, W, opt)

    with CallGraph(ct, mdnm, pth, 'cbpdnmddl_solve.svg', **kwargs):
        b.solve()
282603
def _create_affine_multiframe(multiframe_dicom):
    
    first_frame = multiframe_dicom[Tag(0x5200, 0x9230)][0]
    last_frame = multiframe_dicom[Tag(0x5200, 0x9230)][-1]
    # Create affine matrix (http://nipy.sourceforge.net/nibabel/dicom/dicom_orientation.html#dicom-slice-affine)
    image_orient1 = numpy.array(first_frame.PlaneOrientationSequence[0].ImageOrientationPatient)[0:3].astype(float)
    image_orient2 = numpy.array(first_frame.PlaneOrientationSequence[0].ImageOrientationPatient)[3:6].astype(float)

    normal = numpy.cross(image_orient1, image_orient2)

    delta_r = float(first_frame[0x2005, 0x140f][0].PixelSpacing[0])
    delta_c = float(first_frame[0x2005, 0x140f][0].PixelSpacing[1])

    image_pos = numpy.array(first_frame.PlanePositionSequence[0].ImagePositionPatient).astype(float)
    last_image_pos = numpy.array(last_frame.PlanePositionSequence[0].ImagePositionPatient).astype(float)

    number_of_stack_slices = int(common.get_ss_value(multiframe_dicom[Tag(0x2001, 0x105f)][0][Tag(0x2001, 0x102d)]))
    delta_s = abs(numpy.linalg.norm(last_image_pos - image_pos)) / (number_of_stack_slices - 1)

    return numpy.array(
        [[-image_orient1[0] * delta_c, -image_orient2[0] * delta_r, -delta_s * normal[0], -image_pos[0]],
         [-image_orient1[1] * delta_c, -image_orient2[1] * delta_r, -delta_s * normal[1], -image_pos[1]],
         [image_orient1[2] * delta_c, image_orient2[2] * delta_r, delta_s * normal[2], image_pos[2]],
         [0, 0, 0, 1]])
54209
def affine(self, func:AffineFunc, *args, **kwargs)->'Image':
        ""
        m = tensor(func(*args, **kwargs)).to(self.device)
        self.affine_mat = self.affine_mat @ m
        return self
996310
def get_file_list(path):
    
    f_list = []
    def recur_dir(path, newpath = os.path.sep):
        files = os.listdir(path)
        for fle in files:
            f_path = cpjoin(path, fle)
            if os.path.isdir(f_path): recur_dir(f_path, cpjoin(newpath, fle))
            elif os.path.isfile(f_path): f_list.append(get_single_file_info(f_path, cpjoin(newpath, fle)))

    recur_dir(path)
    return f_list
519639
def _get_file_lists(self):
        """"""
        self.cam0_files = sorted(glob.glob(
            os.path.join(self.sequence_path, 'image_0',
                         '*.{}'.format(self.imtype))))
        self.cam1_files = sorted(glob.glob(
            os.path.join(self.sequence_path, 'image_1',
                         '*.{}'.format(self.imtype))))
        self.cam2_files = sorted(glob.glob(
            os.path.join(self.sequence_path, 'image_2',
                         '*.{}'.format(self.imtype))))
        self.cam3_files = sorted(glob.glob(
            os.path.join(self.sequence_path, 'image_3',
                         '*.{}'.format(self.imtype))))
        self.velo_files = sorted(glob.glob(
            os.path.join(self.sequence_path, 'velodyne',
                         '*.bin')))

        # Subselect the chosen range of frames, if any
        if self.frames is not None:
            self.cam0_files = utils.subselect_files(
                self.cam0_files, self.frames)
            self.cam1_files = utils.subselect_files(
                self.cam1_files, self.frames)
            self.cam2_files = utils.subselect_files(
                self.cam2_files, self.frames)
            self.cam3_files = utils.subselect_files(
                self.cam3_files, self.frames)
            self.velo_files = utils.subselect_files(
                self.velo_files, self.frames)