Use this function to detect if a dicom series is a GE dataset

    :param dicom_input: list with dicom objects
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
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
658197
def _canonize_input(self, dataset):
        
        unpack = lambda x: x
        if isinstance(dataset, _tc.SArray):
            dataset = _tc.SFrame({self.feature: dataset})
        elif isinstance(dataset, _tc.Image):
            dataset = _tc.SFrame({self.feature: [dataset]})
            unpack = lambda x: x[0]
        return dataset, unpack
942078
def _getInputImage (input,group=None):
    
    # extract primary header and SCI,1 header from input image
    sci_ext = 'SCI'
    if group in [None,'']:
        exten = '[sci,1]'
        phdu = fits.getheader(input, memmap=False)
    else:
        # change to use fits more directly here?
        if group.find(',') > 0:
            grp = group.split(',')
            if grp[0].isalpha():
                grp = (grp[0],int(grp[1]))
            else:
                grp = int(grp[0])
        else:
            grp = int(group)
        phdu = fits.getheader(input, memmap=False)
        phdu.extend(fits.getheader(input, ext=grp, memmap=False))

    # Extract the instrument name for the data that is being processed by Multidrizzle
    _instrument = phdu['INSTRUME']

    # Determine the instrument detector in use.  NICMOS is a special case because it does
    # not use the 'DETECTOR' keyword.  It instead used 'CAMERA' to identify which of it's
    # 3 camera's is in use.  All other instruments support the 'DETECTOR' keyword.
    if _instrument == 'NICMOS':
        _detector = phdu['CAMERA']
    else:
        try:
            _detector = phdu['DETECTOR']
        except KeyError:
            # using the phdu as set above (fits.getheader) is MUCH faster and
            # works for the majority of data; but fileutil handles waivered fits
            phdu = fileutil.getHeader(input+exten)
            _detector = phdu['DETECTOR'] # if this fails, let it throw

    del phdu # just to keep clean
    # Match up the instrument and detector with the right class
    # only importing the instrument modules as needed.
    try:
        if _instrument == 'ACS':
            from . import acsData
            if _detector == 'HRC': return acsData.HRCInputImage(input,group=group)
            if _detector == 'WFC': return acsData.WFCInputImage(input,group=group)
            if _detector == 'SBC': return acsData.SBCInputImage(input,group=group)
        if _instrument == 'NICMOS':
            from . import nicmosData
            if _detector == 1: return nicmosData.NIC1InputImage(input)
            if _detector == 2: return nicmosData.NIC2InputImage(input)
            if _detector == 3: return nicmosData.NIC3InputImage(input)


        if _instrument == 'WFPC2':
            from . import wfpc2Data
            return wfpc2Data.WFPC2InputImage(input,group=group)
        """
            if _detector == 1: return wfpc2Data.PCInputImage(input)
            if _detector == 2: return wfpc2Data.WF2InputImage(input)
            if _detector == 3: return wfpc2Data.WF3InputImage(input)
            if _detector == 4: return wfpc2Data.WF4InputImage(input)
        """
        if _instrument == 'STIS':
            from . import stisData
            if _detector == 'CCD': return stisData.CCDInputImage(input,group=group)
            if _detector == 'FUV-MAMA': return stisData.FUVInputImage(input,group=group)
            if _detector == 'NUV-MAMA': return stisData.NUVInputImage(input,group=group)
        if _instrument == 'WFC3':
            from . import wfc3Data
            if _detector == 'UVIS': return wfc3Data.WFC3UVISInputImage(input,group=group)
            if _detector == 'IR': return wfc3Data.WFC3IRInputImage(input,group=group)

    except ImportError:
        msg = 'No module implemented for '+str(_instrument)+'!'
        raise ValueError(msg)
    # If a supported instrument is not detected, print the following error message
    # and raise an exception.
    msg = 'Instrument: ' + str(_instrument) + '/' + str(_detector) + ' not yet supported!'
    raise ValueError(msg)
137630
def data_type(data, grouped=False, columns=None, key_on='idx', iter_idx=None):
    ''''''
    if iter_idx:
        return Data.from_mult_iters(idx=iter_idx, **data)
    if pd:
        if isinstance(data, (pd.Series, pd.DataFrame)):
            return Data.from_pandas(data, grouped=grouped, columns=columns,
                                    key_on=key_on)
    if isinstance(data, (list, tuple, dict)):
            return Data.from_iter(data)
    else:
        raise ValueError('This data type is not supported by Vincent.')
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
1006089
def filter_set(input, **params):
    
    PARAM_WHERE = 'where'

    return Converter.df2list(pd.DataFrame.from_records(input).query(params.get(PARAM_WHERE)))
1362846
def by_grp(self):
        
        dic = {}  # grp -> [(gsim_idx, rlzis), ...]
        for sm in self.csm_info.source_models:
            for sg in sm.src_groups:
                if not sg.eff_ruptures:
                    continue
                rlzs_by_gsim = self.get_rlzs_by_gsim(sg.trt, sm.ordinal)
                if not rlzs_by_gsim:
                    continue
                dic['grp-%02d' % sg.id] = numpy.array(
                    list(rlzs_by_gsim.values()))
        return dic
1217277
def specify_data_set(self, x_input, y_input):
        
        self.x = x_input
        self.y = y_input
1284381
def select_catalogue_events(self, id0):
        '''
        
        '''
        for key in self.data.keys():
            if isinstance(
                    self.data[key], np.ndarray) and len(self.data[key]) > 0:
                # Dictionary element is numpy array - use logical indexing
                self.data[key] = self.data[key][id0]
            elif isinstance(
                    self.data[key], list) and len(self.data[key]) > 0:
                # Dictionary element is list
                self.data[key] = [self.data[key][iloc] for iloc in id0]
            else:
                continue

        if len(self.gcmts) > 0:
            self.gcmts = [self.gcmts[iloc] for iloc in id0]
            self.number_gcmts = self.get_number_tensors()
400979
def get_list_from_model(learn:Learner, ds_type:DatasetType, batch:Tuple)->[]:
        ""
        image_sets = []
        x,y = batch[0],batch[1]
        preds = learn.pred_batch(ds_type=ds_type, batch=(x,y), reconstruct=True)  
        for orig_px, real_px, gen in zip(x,y,preds):
            orig, real = Image(px=orig_px), Image(px=real_px)
            image_set = ModelImageSet(orig=orig, real=real, gen=gen)
            image_sets.append(image_set)
        return image_sets
1052033
def is_dataset(ds):
  """"""
  import tensorflow as tf
  from tensorflow_datasets.core.utils import py_utils
  dataset_types = [tf.data.Dataset]
  v1_ds = py_utils.rgetattr(tf, "compat.v1.data.Dataset", None)
  v2_ds = py_utils.rgetattr(tf, "compat.v2.data.Dataset", None)
  if v1_ds is not None:
    dataset_types.append(v1_ds)
  if v2_ds is not None:
    dataset_types.append(v2_ds)
  return isinstance(ds, tuple(dataset_types))
387729
def _is_compressed(dicom_file, force=False):
    
    header = pydicom.read_file(dicom_file,
                               defer_size="1 KB",
                               stop_before_pixels=True,
                               force=force)

    uncompressed_types = ["1.2.840.10008.1.2",
                          "1.2.840.10008.1.2.1",
                          "1.2.840.10008.1.2.1.99",
                          "1.2.840.10008.1.2.2"]

    if 'TransferSyntaxUID' in header.file_meta and header.file_meta.TransferSyntaxUID in uncompressed_types:
        return False
    return True
1294264
def read_ascii_series(input_, array_type=Series, unpack=True, **kwargs):
    
    xarr, yarr = loadtxt(input_, unpack=unpack, **kwargs)
    return array_type(yarr, xindex=xarr)
463332
def run(self):
        '''
        
        '''
        self._log('Converting DICOM image.\n')
        try:
            self._log('PatientName:                                %s\n' % self._dcm.PatientName)
        except AttributeError:
            self._log('PatientName:                                %s\n' % 'PatientName not found in DCM header.')
            error.warn(self, 'PatientNameTag')
        try:
            self._log('PatientAge:                                 %s\n' % self._dcm.PatientAge)
        except AttributeError:
            self._log('PatientAge:                                 %s\n' % 'PatientAge not found in DCM header.')
            error.warn(self, 'PatientAgeTag')
        try:
            self._log('PatientSex:                                 %s\n' % self._dcm.PatientSex)
        except AttributeError:
            self._log('PatientSex:                                 %s\n' % 'PatientSex not found in DCM header.')
            error.warn(self, 'PatientSexTag')
        try:
            self._log('PatientID:                                  %s\n' % self._dcm.PatientID)
        except AttributeError:
            self._log('PatientID:                                  %s\n' % 'PatientID not found in DCM header.')
            error.warn(self, 'PatientIDTag')
        try:
            self._log('SeriesDescription:                          %s\n' % self._dcm.SeriesDescription)
        except AttributeError:
            self._log('SeriesDescription:                          %s\n' % 'SeriesDescription not found in DCM header.')
            error.warn(self, 'SeriesDescriptionTag')
        try:
            self._log('ProtocolName:                               %s\n' % self._dcm.ProtocolName)
        except AttributeError:
            self._log('ProtocolName:                               %s\n' % 'ProtocolName not found in DCM header.')
            error.warn(self, 'ProtocolNameTag')

        if self._b_convertMiddleSlice:
            self._log('Converting middle slice in DICOM series:    %d\n' % self._sliceToConvert)

        l_rot90 = [ True, True, False ]
        misc.mkdir(self._str_outputDir)
        if not self._b_3D:
            str_outputFile = '%s/%s.%s' % (self._str_outputDir,
                                        self._str_outputFileStem,
                                        self._str_outputFileType)
            self.process_slice()
            self.slice_save(str_outputFile)
        if self._b_3D:
            rotCount = 0
            if self._b_reslice:
                for dim in ['x', 'y', 'z']:
                    self.dim_save(dimension = dim, makeSubDir = True, rot90 = l_rot90[rotCount], indexStart = 0, indexStop = -1)
                    rotCount += 1
            else:
                self.dim_save(dimension = 'z', makeSubDir = False, rot90 = False, indexStart = 0, indexStop = -1)
1038171
def _col_type_set(self, col, df):
        
        type_set = set()
        if df[col].dtype == np.dtype(object):
            unindexed_col = list(df[col])
            for i in range(0, len(df[col])):
                if unindexed_col[i] == np.nan:
                    continue
                else:
                    type_set.add(type(unindexed_col[i]))
            return type_set
        else:
            type_set.add(df[col].dtype)
            return type_set
757401
def is_dataset_on_gcs(dataset_name):
  """"""
  dir_name = posixpath.join(GCS_DATASETS_DIR, dataset_name)
  return len(gcs_files(prefix_filter=dir_name)) > 2