Shows the fields that differ between two DICOM images.

    Inspired by https://code.google.com/p/pydicom/source/browse/source/dicom/examples/DicomDiff.py
17943
def dicom_diff(file1, file2):
    

    datasets = compressed_dicom.read_file(file1), compressed_dicom.read_file(file2)

    rep = []

    for dataset in datasets:
        lines = (str(dataset.file_meta)+"\n"+str(dataset)).split('\n')
        lines = [line + '\n' for line in lines]  # add the newline to the end
        rep.append(lines)

    diff = difflib.Differ()
    for line in diff.compare(rep[0], rep[1]):
        if (line[0] == '+') or (line[0] == '-'):
            sys.stdout.write(line)
713932
def diff(self):
        """"""

        if not self.present:
            if self.existing:
                return DEL

            return NOOP

        is_diff = NOOP
        if self.present and self.existing:
            a_obj = self.config.copy()
            if self.config and diff_dict(a_obj, self.existing, True):
                is_diff = CHANGED

            if self.description != self.existing.get('description'):
                is_diff = CONFLICT

        elif self.present and not self.existing:
            is_diff = ADD

        return is_diff
387422
def compute_diff(dir_base, dir_cmp):
    
    data = {}
    data['deleted'] = list(set(dir_cmp['files']) - set(dir_base['files']))
    data['created'] = list(set(dir_base['files']) - set(dir_cmp['files']))
    data['updated'] = []
    data['deleted_dirs'] = list(set(dir_cmp['subdirs']) - set(dir_base['subdirs']))

    for f in set(dir_cmp['files']).intersection(set(dir_base['files'])):
        if dir_base['index'][f] != dir_cmp['index'][f]:
            data['updated'].append(f)

    return data
590291
def compare_dicts(d1, d2):
    
    a = json.dumps(d1, indent=4, sort_keys=True)
    b = json.dumps(d2, indent=4, sort_keys=True)
    # stolen from cpython
    # https://github.com/python/cpython/blob/01fd68752e2d2d0a5f90ae8944ca35df0a5ddeaa/Lib/unittest/case.py#L1091
    diff = ('\n' + '\n'.join(difflib.ndiff(
                   a.splitlines(),
                   b.splitlines())))
    return diff
864275
def highlight_differences(s1, s2, color):
    """"""
    ls1, ls2 = len(s1), len(s2)

    diff_indices = [i for i, (a, b) in enumerate(zip(s1, s2)) if a != b]

    print(s1)

    if ls2 > ls1:
        colorise.cprint('_' * (ls2-ls1), fg=color)
    else:
        print()

    colorise.highlight(s2, indices=diff_indices, fg=color, end='')

    if ls1 > ls2:
        colorise.cprint('_' * (ls1-ls2), fg=color)
    else:
        print()
49390
def diff_table(self, table1, table2):
        
        changes = 0
        table_differences = TableDiff(table1.get_name())
        table_differences.from_table = table1

        table1_columns = table1.get_columns()
        table2_columns = table2.get_columns()

        # See if all the fields in table1 exist in table2
        for column_name, column in table2_columns.items():
            if not table1.has_column(column_name):
                table_differences.added_columns[column_name] = column
                changes += 1

        # See if there are any removed fields in table2
        for column_name, column in table1_columns.items():
            if not table2.has_column(column_name):
                table_differences.removed_columns[column_name] = column
                changes += 1
                continue

            # See if column has changed properties in table2
            changed_properties = self.diff_column(
                column, table2.get_column(column_name)
            )

            if changed_properties:
                column_diff = ColumnDiff(
                    column.get_name(),
                    table2.get_column(column_name),
                    changed_properties,
                )
                column_diff.from_column = column
                table_differences.changed_columns[column.get_name()] = column_diff
                changes += 1

        self.detect_column_renamings(table_differences)

        table1_indexes = table1.get_indexes()
        table2_indexes = table2.get_indexes()

        # See if all the fields in table1 exist in table2
        for index_name, index in table2_indexes.items():
            if (
                index.is_primary() and not table1.has_primary_key()
            ) or table1.has_index(index_name):
                continue

            table_differences.added_indexes[index_name] = index
            changes += 1

        # See if there are any removed fields in table2
        for index_name, index in table1_indexes.items():
            if (index.is_primary() and not table2.has_primary_key()) or (
                not index.is_primary() and not table2.has_index(index_name)
            ):
                table_differences.removed_indexes[index_name] = index
                changes += 1
                continue

            # See if index has changed in table 2
            if index.is_primary():
                table2_index = table2.get_primary_key()
            else:
                table2_index = table2.get_index(index_name)

            if self.diff_index(index, table2_index):
                table_differences.changed_indexes[index_name] = index
                changes += 1

        self.detect_index_renamings(table_differences)

        from_fkeys = OrderedDict([(k, v) for k, v in table1.get_foreign_keys().items()])
        to_fkeys = OrderedDict([(k, v) for k, v in table2.get_foreign_keys().items()])

        for key1, constraint1 in table1.get_foreign_keys().items():
            for key2, constraint2 in table2.get_foreign_keys().items():
                if self.diff_foreign_key(constraint1, constraint2) is False:
                    del from_fkeys[key1]
                    del to_fkeys[key2]
                else:
                    if constraint1.get_name().lower() == constraint2.get_name().lower():
                        table_differences.changed_foreign_keys.append(constraint2)
                        changes += 1
                        del from_fkeys[key1]
                        del to_fkeys[key2]

        for constraint1 in from_fkeys.values():
            table_differences.removed_foreign_keys.append(constraint1)
            changes += 1

        for constraint2 in to_fkeys.values():
            table_differences.added_foreign_keys.append(constraint2)
            changes += 1

        if changes:
            return table_differences

        return False
377837
def _diff_internal(d1,d2):
    '''
        
    '''
    same =[]
    kdiff =[]
    vdiff = []
    for key in d1:
        value = d1[key]
        if(key in d2):
            if(value == d2[key]):
                same.append(key)
            else:
                vdiff.append(key)
        else:
            kdiff.append(key)
    return({'same':same,'kdiff':kdiff,'vdiff':vdiff})
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}
1117237
def _remove_duplicate_slices(dicoms):
    
    # Loop overall files and build dict

    dicoms_dict = {}
    filtered_dicoms = []
    for dicom_ in dicoms:
        if tuple(dicom_.ImagePositionPatient) not in dicoms_dict:
            dicoms_dict[tuple(dicom_.ImagePositionPatient)] = dicom_
            filtered_dicoms.append(dicom_)
        else:
            if numpy.array_equal(dicom_.pixel_array,
                                 dicoms_dict[tuple(dicom_.ImagePositionPatient)].pixel_array):
                logger.warning('Removing duplicate slice from series')
            else:
                filtered_dicoms.append(dicom_)
    return filtered_dicoms
273913
def is_valid_imaging_dicom(dicom_header):
    
    # if it is philips and multiframe dicom then we assume it is ok
    try:
        if is_philips([dicom_header]):
            if is_multiframe_dicom([dicom_header]):
                return True

        if "SeriesInstanceUID" not in dicom_header:
            return False

        if "InstanceNumber" not in dicom_header:
            return False

        if "ImageOrientationPatient" not in dicom_header or len(dicom_header.ImageOrientationPatient) < 6:
            return False

        if "ImagePositionPatient" not in dicom_header or len(dicom_header.ImagePositionPatient) < 3:
            return False

        # for all others if there is image position patient we assume it is ok
        if Tag(0x0020, 0x0037) not in dicom_header:
            return False

        return True
    except (KeyError, AttributeError):
        return False
297642
def raster_field(self):
        """"""
        for field in self.model._meta.fields:
            if isinstance(field, models.FileField):
                return field
        return False
1032235
def diff(
        cobertura_file1, cobertura_file2,
        color, format, output, source1, source2,
        source_prefix1, source_prefix2, source):
    """"""
    cobertura1 = Cobertura(
        cobertura_file1,
        source=source1,
        source_prefix=source_prefix1
    )
    cobertura2 = Cobertura(
        cobertura_file2,
        source=source2,
        source_prefix=source_prefix2
    )

    Reporter = delta_reporters[format]
    reporter_args = [cobertura1, cobertura2]
    reporter_kwargs = {'show_source': source}

    isatty = True if output is None else output.isatty()

    if format == 'text':
        color = isatty if color is None else color is True
        reporter_kwargs['color'] = color

    reporter = Reporter(*reporter_args, **reporter_kwargs)
    report = reporter.generate()

    if not isinstance(report, bytes):
        report = report.encode('utf-8')

    click.echo(report, file=output, nl=isatty, color=color)

    exit_code = get_exit_code(reporter.differ, source)
    raise SystemExit(exit_code)
988650
def diffcolor(s1, s2):
    '''  '''
    string = ''
    for line in diff(s1, s2):
        if line[0] == '-':
            string += ' ' + TermColors.red(line[2:])
        elif line[0] == '+':
            string += ' ' + TermColors.green(line[2:])
        else:
            string += ' ' + line
    return string[1:]
821328
def _different(left, right, f):
    

    l = left.getinfo(f)
    r = right.getinfo(f)

    if (l.file_size == r.file_size) and (l.CRC == r.CRC):
        # ok, they seem passibly similar, let's deep check them.
        return _deep_different(left, right, f)

    else:
        # yup, they're different
        return True
772091
def fields(depth, Rp, Rm, Gam, lrec, lsrc, zsrc, TM):
    

    """
    # Booleans if src in first or last layer; swapped if up=True
    first_layer = lsrc == 0
    last_layer = lsrc == depth.size-1

    # Depths; dp and dm are swapped if up=True
    if lsrc != depth.size-1:
        ds = depth[lsrc+1]-depth[lsrc]
        dp = depth[lsrc+1]-zsrc
    dm = zsrc-depth[lsrc]

    # Rm and Rp; swapped if up=True
    Rmp = Rm
    Rpm = Rp

    # Boolean if plus or minus has to be calculated
    if TM:
        plus = False
    else:
        plus = True

    # Sign-switches
    pm = 1     # + if plus=True, - if plus=False
    if not plus:
        pm = -1

    # Calculate down- and up-going fields
    for up in [False, True]:

        # No upgoing field if rec is in last layer or below src
        if up and (lrec == depth.size-1 or lrec > lsrc):
            Puu = np.full_like(Gam[:, :, lsrc, :], 0+0j)
            Pud = np.full_like(Gam[:, :, lsrc, :], 0+0j)
            continue
        # No downgoing field if rec is in first layer or above src
        if not up and (lrec == 0 or lrec < lsrc):
            Pdu = np.full_like(Gam[:, :, lsrc, :], 0+0j)
            Pdd = np.full_like(Gam[:, :, lsrc, :], 0+0j)
            continue

        # Swaps if up=True
        if up:
            dp, dm = dm, dp
            Rmp, Rpm = Rpm, Rmp
            first_layer, last_layer = last_layer, first_layer

        # Calculate Pu+, Pu-, Pd+, Pd-; rec in src layer; Eqs  81/82, A-8/A-9
        iGam = Gam[:, :, lsrc, :]
        if last_layer:  # If src/rec are in top (up) or bottom (down) layer
            Pd = Rmp*np.exp(-iGam*dm)
            Pu = np.full_like(Gam[:, :, lsrc, :], 0+0j)
        else:           # If src and rec are in any layer in between
            Ms = 1 - Rmp*Rpm*np.exp(-2*iGam*ds)
            Pd = Rmp/Ms*np.exp(-iGam*dm)
            Pu = Rmp/Ms*pm*Rpm*np.exp(-iGam*(ds+dp))

        # Store P's
        if up:
            Puu = Pu
            Pud = Pd
        else:
            Pdu = Pd
            Pdd = Pu

    # Return fields (up- and downgoing)
    return Puu, Pud, Pdu, Pdd
657264
def are_imaging_dicoms(dicom_input):
    

    # if it is philips and multiframe dicom then we assume it is ok
    if common.is_philips(dicom_input):
        if common.is_multiframe_dicom(dicom_input):
            return True

    # for all others if there is image position patient we assume it is ok
    header = dicom_input[0]
    return Tag(0x0020, 0x0037) in header
822156
def diff_text2(self, diffs):
    
    text = []
    for (op, data) in diffs:
      if op != self.DIFF_DELETE:
        text.append(data)
    return "".join(text)