Use this function to detect if a dicom series is a philips singleframe 4D dataset
346556
def _is_singleframe_4d(dicom_input):
    
    header = dicom_input[0]

    # check if there are stack information
    slice_number_mr_tag = Tag(0x2001, 0x100a)
    if slice_number_mr_tag not in header:
        return False

    # check if there are multiple timepoints
    grouped_dicoms = _get_grouped_dicoms(dicom_input)
    if len(grouped_dicoms) <= 1:
        return False

    return True
963635
def get_pandasframe(self):
        """"""
        if self.dataset:
            self._load_dimensions()
            return self._get_pandasframe_one_dataset()
        return self._get_pandasframe_across_datasets()
205060
def get_wcs(self, data_x, data_y):
        
        img = self.fitsimage.get_image()
        ra, dec = img.pixtoradec(data_x, data_y)
        return ra, dec
652725
def asrgb(self, uint8=False, alpha=None, colormap=None,
              dmin=None, dmax=None, **kwargs):
        
        data = self.asarray(**kwargs)
        self = self.keyframe  # self or keyframe
        photometric = self.photometric
        PHOTOMETRIC = TIFF.PHOTOMETRIC

        if photometric == PHOTOMETRIC.PALETTE:
            colormap = self.colormap
            if (colormap.shape[1] < 2**self.bitspersample or
                    self.dtype.char not in 'BH'):
                raise ValueError('cannot apply colormap')
            if uint8:
                if colormap.max() > 255:
                    colormap >>= 8
                colormap = colormap.astype('uint8')
            if 'S' in self.axes:
                data = data[..., 0] if self.planarconfig == 1 else data[0]
            data = apply_colormap(data, colormap)

        elif photometric == PHOTOMETRIC.RGB:
            if 'ExtraSamples' in self.tags:
                if alpha is None:
                    alpha = TIFF.EXTRASAMPLE
                extrasamples = self.extrasamples
                if self.tags['ExtraSamples'].count == 1:
                    extrasamples = (extrasamples,)
                for i, exs in enumerate(extrasamples):
                    if exs in alpha:
                        if self.planarconfig == 1:
                            data = data[..., [0, 1, 2, 3+i]]
                        else:
                            data = data[:, [0, 1, 2, 3+i]]
                        break
            else:
                if self.planarconfig == 1:
                    data = data[..., :3]
                else:
                    data = data[:, :3]
            # TODO: convert to uint8?

        elif photometric == PHOTOMETRIC.MINISBLACK:
            raise NotImplementedError()
        elif photometric == PHOTOMETRIC.MINISWHITE:
            raise NotImplementedError()
        elif photometric == PHOTOMETRIC.SEPARATED:
            raise NotImplementedError()
        else:
            raise NotImplementedError()
        return data
725856
def validate_slice_increment(dicoms):
    
    first_image_position = numpy.array(dicoms[0].ImagePositionPatient)
    previous_image_position = numpy.array(dicoms[1].ImagePositionPatient)

    increment = first_image_position - previous_image_position
    for dicom_ in dicoms[2:]:
        current_image_position = numpy.array(dicom_.ImagePositionPatient)
        current_increment = previous_image_position - current_image_position
        if not numpy.allclose(increment, current_increment, rtol=0.05, atol=0.1):
            logger.warning('Slice increment not consistent through all slices')
            logger.warning('---------------------------------------------------------')
            logger.warning('%s %s' % (previous_image_position, increment))
            logger.warning('%s %s' % (current_image_position, current_increment))
            if 'InstanceNumber' in dicom_:
                logger.warning('Instance Number: %s' % dicom_.InstanceNumber)
            logger.warning('---------------------------------------------------------')
            raise ConversionValidationError('SLICE_INCREMENT_INCONSISTENT')
        previous_image_position = current_image_position
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]])
1228793
def _sigmaclip_noaxis(self, data, masked=True, return_bounds=False,
                          copy=True):
        

        filtered_data = data.ravel()

        # remove masked values and convert to ndarray
        if isinstance(filtered_data, np.ma.MaskedArray):
            filtered_data = filtered_data.data[~filtered_data.mask]

        # remove invalid values
        good_mask = np.isfinite(filtered_data)
        if np.any(~good_mask):
            filtered_data = filtered_data[good_mask]
            warnings.warn('Input data contains invalid values (NaNs or '
                          'infs), which were automatically clipped.',
                          AstropyUserWarning)

        nchanged = 1
        iteration = 0
        while nchanged != 0 and (iteration < self.maxiters):
            iteration += 1
            size = filtered_data.size
            self._compute_bounds(filtered_data, axis=None)
            filtered_data = filtered_data[(filtered_data >= self._min_value) &
                                          (filtered_data <= self._max_value)]
            nchanged = size - filtered_data.size

        self._niterations = iteration

        if masked:
            # return a masked array and optional bounds
            filtered_data = np.ma.masked_invalid(data, copy=copy)

            # update the mask in place, ignoring RuntimeWarnings for
            # comparisons with NaN data values
            with np.errstate(invalid='ignore'):
                filtered_data.mask |= np.logical_or(data < self._min_value,
                                                    data > self._max_value)

        if return_bounds:
            return filtered_data, self._min_value, self._max_value
        else:
            return filtered_data
937937
def _is_valid_imaging_dicom(dicom_header):
    
    # if it is philips and multiframe dicom then we assume it is ok
    try:
        if common.is_philips([dicom_header]):
            if common.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
608116
def _is_bval_type_b(grouped_dicoms):
    
    bval_tag = Tag(0x0018, 0x9087)
    bvec_tag = Tag(0x0018, 0x9089)
    for group in grouped_dicoms:
        if bvec_tag in group[0] and bval_tag in group[0]:
            bvec = common.get_fd_array_value(group[0][bvec_tag], 3)
            bval = common.get_fd_value(group[0][bval_tag])
            if _is_float(bvec[0]) and _is_float(bvec[1]) and _is_float(bvec[2]) and _is_float(bval) and bval != 0:
                return True
    return False
434040
def _singleframe_to_block(grouped_dicoms):
    
    # For each slice / mosaic create a data volume block
    data_blocks = []
    for index in range(0, len(grouped_dicoms)):
        logger.info('Creating block %s of %s' % (index + 1, len(grouped_dicoms)))
        current_block = _stack_to_block(grouped_dicoms[index])
        current_block = current_block[:, :, :, numpy.newaxis]
        data_blocks.append(current_block)

    try:
        full_block = numpy.concatenate(data_blocks, axis=3)
    except:
        traceback.print_exc()
        raise ConversionError("MISSING_DICOM_FILES")

    # Apply the rescaling if needed
    common.apply_scaling(full_block, grouped_dicoms[0][0])

    return full_block
952213
def numpy(self):
        
        # load GDCM's image reading functionality
        image_reader = gdcm.ImageReader()
        image_reader.SetFileName(self.fname)
        if not image_reader.Read():
            raise IOError("Could not read DICOM image")
        pixel_array = self._gdcm_to_numpy(image_reader.GetImage())
        return pixel_array
1260084
def data_class(self):
        
        x_grid, y_grid, ra_at_xy_0, dec_at_xy_0, x_at_radec_0, y_at_radec_0, Mpix2coord, Mcoord2pix = util.make_grid_with_coordtransform(
            numPix=self.numpix, deltapix=self.pixel_scale, subgrid_res=1, left_lower=False, inverse=False)
        kwargs_data = {'numPix': self.numpix, 'ra_at_xy_0': ra_at_xy_0, 'dec_at_xy_0': dec_at_xy_0,
                       'transform_pix2angle': Mpix2coord,
                       'background_rms': self.background_noise,
                       'exp_time': self.scaled_exposure_time}
        data_class = Data(kwargs_data)
        return data_class
736935
def get_fc_dimensions(self, strides, kernel_sizes):
    """"""
    output_height, output_width, _ = self.hparams.problem.frame_shape
    output_steps = self.hparams.video_num_target_frames
    output_shape = np.array([output_steps, output_height, output_width])
    for curr_stride, kernel_size in zip(strides, kernel_sizes):
      output_shape = self.expected_output_shape(
          output_shape, np.array(curr_stride), 1, kernel_size)
    return np.prod(output_shape) * self.hparams.num_discriminator_filters * 8
384084
private void CheckYCbCr(IfdTags metadata, int n) {
    // Samples per pixel
    if (!metadata.containsTagId(TiffTags.getTagId("SamplesPerPixel"))) {
      validation.addErrorLoc("Missing Samples Per Pixel", "IFD" + n);
    } else {
      long spp = metadata.get(TiffTags.getTagId("SamplesPerPixel")).getFirstNumericValue();
      if (spp != 3) {
        validation.addError("Invalid Samples Per Pixel", "IFD" + n, spp);
      }
    }

    // BitsPerSample
    if (!metadata.containsTagId(TiffTags.getTagId("BitsPerSample"))) {
      validation.addErrorLoc("Missing BitsPerSample", "IFD" + n);
    } else {
      for (abstractTiffType vi : metadata.get(TiffTags.getTagId("BitsPerSample")).getValue()) {
        if (vi.toInt() != 8) {
          validation.addError("Invalid BitsPerSample", "IFD" + n, vi.toInt());
          break;
        }
      }
    }

    // Compression
    // long comp = metadata.get(TiffTags.getTagId("Compression")).getFirstNumericValue();
    // if (comp != 1 && comp != 5 && comp != 6)
    // validation.addError("Invalid Compression", comp);

    // if (!metadata.containsTagId(TiffTags.getTagId("ReferenceBlackWhite")))
    // validation.addError("Missing ReferenceBlackWhite");

    // if (!metadata.containsTagId(TiffTags.getTagId("YCbCrCoefficients")))
    // validation.addError("Missing YCbCr Coefficients");

    // if (!metadata.containsTagId(TiffTags.getTagId("YCbCrSubSampling")))
    // validation.addError("Missing YCbCr SubSampling");

    // if (!metadata.containsTagId(TiffTags.getTagId("YCbCrPositioning")))
    // validation.addError("Missing YCbCr Positioning");
  }
346166
def is_ge(dicom_input):
    
    # read dicom header
    header = dicom_input[0]

    if 'Manufacturer' not in header or 'Modality' not in header:
        return False  # we try generic conversion in these cases

    # check if Modality is mr
    if header.Modality.upper() != 'MR':
        return False

    # check if manufacturer is GE
    if 'GE MEDICAL SYSTEMS' not in header.Manufacturer.upper():
        return False

    return True
909279
def is_dicom_dir(datapath):
    
    # Second tries open files
    # with dicom module.

    retval = False
    datapath = op.expanduser(datapath)
    for f in os.listdir(datapath):
        if f.endswith((".dcm", ".DCM")):
            retval = True
            return True
        # @todo not working and I dont know why
        try:
            pydicom.read_file(os.path.join(datapath, f))

            retval = True
        # except pydicom.errors.InvalidDicomError:
        #     logger.debug("Invalid Dicom while reading file " + str(f))
        except Exception as e:
            logger.warning("Unable to read dicom file " + str(f))
            logger.warning(e)
            # import traceback
            # traceback.print_exc()

        if retval:
            return True
    return False
974240
def calibrate(self,
                  dataset_id,
                  pre_launch_coeffs=False,
                  calib_coeffs=None):
        
        tic = datetime.now()

        if calib_coeffs is None:
            calib_coeffs = {}

        units = {'reflectance': '%',
                 'brightness_temperature': 'K',
                 'counts': '',
                 'radiance': 'W*m-2*sr-1*cm ?'}

        if dataset_id.name in ("3a", "3b") and self._is3b is None:
            # Is it 3a or 3b:
            is3b = np.expand_dims(
                np.bitwise_and(
                    np.right_shift(self._data['scnlinbit'], 0), 1) == 1, 1)
            self._is3b = np.repeat(is3b,
                                   self._data['hrpt'][0].shape[0], axis=1)

        try:
            vis_idx = ['1', '2', '3a'].index(dataset_id.name)
            ir_idx = None
        except ValueError:
            vis_idx = None
            ir_idx = ['3b', '4', '5'].index(dataset_id.name)

        if vis_idx is not None:
            coeffs = calib_coeffs.get('ch' + dataset_id.name)
            ds = create_xarray(
                _vis_calibrate(self._data,
                               vis_idx,
                               dataset_id.calibration,
                               pre_launch_coeffs,
                               coeffs,
                               mask=(dataset_id.name == '3a' and self._is3b)))
        else:
            ds = create_xarray(
                _ir_calibrate(self._header,
                              self._data,
                              ir_idx,
                              dataset_id.calibration,
                              mask=(dataset_id.name == '3b' and
                                    np.logical_not(self._is3b))))

        if dataset_id.name == '3a' and np.all(np.isnan(ds)):
            raise ValueError("Empty dataset for channel 3A")
        if dataset_id.name == '3b' and np.all(np.isnan(ds)):
            raise ValueError("Empty dataset for channel 3B")

        ds.attrs['units'] = units[dataset_id.calibration]
        ds.attrs.update(dataset_id._asdict())

        logger.debug("Calibration time %s", str(datetime.now() - tic))

        return ds