Read raster by GDAL.

        Args:
            raster_file: raster file path.

        Returns:
            Raster object.
760000
def read_raster(raster_file):
        
        ds = gdal_Open(raster_file)
        band = ds.GetRasterBand(1)
        data = band.ReadAsArray()
        xsize = band.XSize
        ysize = band.YSize

        nodata_value = band.GetNoDataValue()
        geotrans = ds.GetGeoTransform()
        dttype = band.DataType

        srs = osr_SpatialReference()
        srs.ImportFromWkt(ds.GetProjection())
        # print(srs.ExportToProj4())
        if nodata_value is None:
            nodata_value = DEFAULT_NODATA
        band = None
        ds = None
        return Raster(ysize, xsize, data, nodata_value, geotrans, srs, dttype)
397344
def read_yaml_file(self, file_name):
        
        with open(os.path.join(self.__path(), os.path.basename(file_name)),
                  'rt') as yamlfile:
            return yaml.load(yamlfile)
1273291
def _readFile(self, sldir, fileName, sep):
        '''
        

        '''

        if sldir.endswith(os.sep):
            fileName = str(sldir)+str(fileName)
        else:
            fileName = str(sldir)+os.sep+str(fileName)


        fileLines=[] #list of lines in the file
        header=[]    #list of Header lines
        dataCols=[]  #Dictionary of data column names
        data=[]      #List of Data lists
        cols=[]      #List of column names

        f=open(fileName,'r')
        fileLines=f.readlines()
        i=0
        if self.datatype != 'trajectory':

            while i<len(fileLines):
                if fileLines[i].startswith(self.header_char):
                    tmp=fileLines[i].lstrip(self.header_char)
                    header.append(tmp.strip())
                else:
                    break
                i+=1

            cols=fileLines[i].split(sep)

            tmp=[]
            tmp1=[]
            for j in range(len(cols)):
                tmp1=cols[j].strip()
                if tmp1 !='':
                    tmp.append(tmp1)
            cols=tmp
            i+=1
        else:
            header={}
            while fileLines[i].startswith('#') or '=' in fileLines[i]:
                if fileLines[i].startswith('#') and cols==[]:
                    cols=fileLines[i].strip('#')
                    cols=cols.strip()
                    cols=cols.split()
                elif fileLines[i].startswith('#'):
                    tmp1=fileLines[i].strip('#')
                    tmp1=tmp1.strip()
                    self.headerLines.append(tmp1)
                elif not fileLines[i].startswith('#'):
                    tmp=fileLines[i].split('=')
                    tmp[0]=tmp[0].strip()
                    tmp[1]=tmp[1].strip()
                    if header=={}:
                        header={str(tmp[0]):str(tmp[1])}
                    else:
                        header[str(tmp[0])]=str(tmp[1])
                i+=1
        while i<len(fileLines):
            if fileLines[i].startswith('#'):
                i=i+1
            else:
                tmp=fileLines[i].split()
                for j in range(len(tmp)):
                    tmp[j]=tmp[j].strip()
                data.append(tmp)
                i+=1
        tmp=[]
        tmp1=[]
        for j in range(len(data)):
            for k in range(len(data[j])):
                tmp1=data[j][k].strip()
                if tmp1 !='':
                    tmp.append(tmp1)
            data[j]=tmp
            tmp=[]
        tmp=[]

        for j in range(len(cols)):
            for k in range(len(data)):
                try:
                    a=float(data[k][j])
                    tmp.append(a)
                except ValueError:
                    tmp.append(data[k][j])
                #else:
                 #   tmp.append(float(data[k][j])) # previously tmp.append(float(data[k][j]))
            tmp=array(tmp)

            if j == 0:
                dataCols={cols[j]:tmp}
            else:
                dataCols[cols[j]]=tmp
            tmp=[]

        return header,dataCols
148865
def from_file(cls, filename_or_file_object):
        
        object_ = from_file(filename_or_file_object)
        if not isinstance(object_, cls):
            raise ValueError('Expected to read {0!r} object, but got {1!r} instead'.format(cls, type(object_)))

        return object_
571699
def load_image(file) -> DataAndMetadata.DataAndMetadata:
    
    if isinstance(file, str) or isinstance(file, str):
        with open(file, "rb") as f:
            return load_image(f)
    dmtag = parse_dm3.parse_dm_header(file)
    dmtag = fix_strings(dmtag)
    # display_keys(dmtag)
    img_index = -1
    image_tags = dmtag['ImageList'][img_index]
    data = imagedatadict_to_ndarray(image_tags['ImageData'])
    calibrations = []
    calibration_tags = image_tags['ImageData'].get('Calibrations', dict())
    for dimension in calibration_tags.get('Dimension', list()):
        origin, scale, units = dimension.get('Origin', 0.0), dimension.get('Scale', 1.0), dimension.get('Units', str())
        calibrations.append((-origin * scale, scale, units))
    calibrations = tuple(reversed(calibrations))
    if len(data.shape) == 3 and data.dtype != numpy.uint8:
        if image_tags['ImageTags'].get('Meta Data', dict()).get("Format", str()).lower() in ("spectrum", "spectrum image"):
            if data.shape[1] == 1:
                data = numpy.squeeze(data, 1)
                data = numpy.moveaxis(data, 0, 1)
                data_descriptor = DataAndMetadata.DataDescriptor(False, 1, 1)
                calibrations = (calibrations[2], calibrations[0])
            else:
                data = numpy.moveaxis(data, 0, 2)
                data_descriptor = DataAndMetadata.DataDescriptor(False, 2, 1)
                calibrations = tuple(calibrations[1:]) + (calibrations[0],)
        else:
            data_descriptor = DataAndMetadata.DataDescriptor(False, 1, 2)
    elif len(data.shape) == 4 and data.dtype != numpy.uint8:
        # data = numpy.moveaxis(data, 0, 2)
        data_descriptor = DataAndMetadata.DataDescriptor(False, 2, 2)
    elif data.dtype == numpy.uint8:
        data_descriptor = DataAndMetadata.DataDescriptor(False, 0, len(data.shape[:-1]))
    else:
        data_descriptor = DataAndMetadata.DataDescriptor(False, 0, len(data.shape))
    brightness = calibration_tags.get('Brightness', dict())
    origin, scale, units = brightness.get('Origin', 0.0), brightness.get('Scale', 1.0), brightness.get('Units', str())
    intensity = -origin * scale, scale, units
    timestamp = None
    timezone = None
    timezone_offset = None
    title = image_tags.get('Name')
    properties = dict()
    if 'ImageTags' in image_tags:
        voltage = image_tags['ImageTags'].get('ImageScanned', dict()).get('EHT', dict())
        if voltage:
            properties.setdefault("hardware_source", dict())["autostem"] = { "high_tension_v": float(voltage) }
        dm_metadata_signal = image_tags['ImageTags'].get('Meta Data', dict()).get('Signal')
        if dm_metadata_signal and dm_metadata_signal.lower() == "eels":
            properties.setdefault("hardware_source", dict())["signal_type"] = dm_metadata_signal
        if image_tags['ImageTags'].get('Meta Data', dict()).get("Format", str()).lower() in ("spectrum", "spectrum image"):
            data_descriptor.collection_dimension_count += data_descriptor.datum_dimension_count - 1
            data_descriptor.datum_dimension_count = 1
        if image_tags['ImageTags'].get('Meta Data', dict()).get("IsSequence", False) and data_descriptor.collection_dimension_count > 0:
            data_descriptor.is_sequence = True
            data_descriptor.collection_dimension_count -= 1
        timestamp_str = image_tags['ImageTags'].get("Timestamp")
        if timestamp_str:
            timestamp = get_datetime_from_timestamp_str(timestamp_str)
        timezone = image_tags['ImageTags'].get("Timezone")
        timezone_offset = image_tags['ImageTags'].get("TimezoneOffset")
        # to avoid having duplicate copies in Swift, get rid of these tags
        image_tags['ImageTags'].pop("Timestamp", None)
        image_tags['ImageTags'].pop("Timezone", None)
        image_tags['ImageTags'].pop("TimezoneOffset", None)
        # put the image tags into properties
        properties.update(image_tags['ImageTags'])
    dimensional_calibrations = [Calibration.Calibration(c[0], c[1], c[2]) for c in calibrations]
    while len(dimensional_calibrations) < data_descriptor.expected_dimension_count:
        dimensional_calibrations.append(Calibration.Calibration())
    intensity_calibration = Calibration.Calibration(intensity[0], intensity[1], intensity[2])
    return DataAndMetadata.new_data_and_metadata(data,
                                                 data_descriptor=data_descriptor,
                                                 dimensional_calibrations=dimensional_calibrations,
                                                 intensity_calibration=intensity_calibration,
                                                 metadata=properties,
                                                 timestamp=timestamp,
                                                 timezone=timezone,
                                                 timezone_offset=timezone_offset)
1069996
def _read_bands(self):
        
        bands = []

        try:
            for i, band in enumerate(self.bands):
                bands.append(rasterio.open(self.bands_path[i]).read_band(1))
        except IOError as e:
            exit(e.message, 1)

        return bands
896481
def read(*files, &block)
      Kernel.raise ArgumentError, 'no files given' if files.length.zero?
      files.each do |f|
        Magick::Image.read(f, &block).each { |n| @images << n }
      end
      @scene = length - 1
      self
    end
1230640
public static String readFileToString(String _file) {
        List<String> localText = getTextfileFromUrl(_file);
        if (localText == null) {
            return null;
        }

        return StringUtil.join(guessLineTerminatorOfFile(_file), localText);
    }
332931
def read(self, log_file):
        
        if os.path.isdir(os.path.dirname(log_file)) and os.path.isfile(log_file):
            with open(log_file, 'r') as LogFile:
                data = LogFile.readlines()
                data = "".join(line for line in data)
        else:
            data = ''
        return data
956520
def _read_from_file(self):
        
        # test if we can read the given file
        if not gf.file_can_be_read(self.file_path):
            self.log_exc(u"File '%s' cannot be read" % (self.file_path), None, True, OSError)

        if self.file_format not in TextFileFormat.ALLOWED_VALUES:
            self.log_exc(u"Text file format '%s' is not supported." % (self.file_format), None, True, ValueError)

        # read the contents of the file
        self.log([u"Reading contents of file '%s'", self.file_path])
        with io.open(self.file_path, "r", encoding="utf-8") as text_file:
            lines = text_file.readlines()

        # clear text fragments
        self.clear()

        # parse the contents
        map_read_function = {
            TextFileFormat.MPLAIN: self._read_mplain,
            TextFileFormat.MUNPARSED: self._read_munparsed,
            TextFileFormat.PARSED: self._read_parsed,
            TextFileFormat.PLAIN: self._read_plain,
            TextFileFormat.SUBTITLES: self._read_subtitles,
            TextFileFormat.UNPARSED: self._read_unparsed
        }
        map_read_function[self.file_format](lines)

        # log the number of fragments
        self.log([u"Parsed %d fragments", len(self.fragments)])
103859
def read_file(rel_path, paths=None, raw=False, as_list=False, as_iter=False,
              *args, **kwargs):
    '''
        
    '''
    if not rel_path:
        raise ValueError("rel_path can not be null!")
    paths = str2list(paths)
    # try looking the file up in a directory called static relative
    # to SRC_DIR, eg assuming metrique git repo is in ~/metrique
    # we'd look in ~/metrique/static
    paths.extend([STATIC_DIR, os.path.join(SRC_DIR, 'static')])
    paths = [os.path.expanduser(p) for p in set(paths)]
    for path in paths:
        path = os.path.join(path, rel_path)
        logger.debug("trying to read: %s " % path)
        if os.path.exists(path):
            break
    else:
        raise IOError("path %s does not exist!" % rel_path)
    args = args if args else ['rU']
    fd = open(path, *args, **kwargs)
    if raw:
        return fd

    if as_iter:
        return read_in_chunks(fd)
    else:
        fd_lines = fd.readlines()

    if as_list:
        return fd_lines
    else:
        return ''.join(fd_lines)
1070527
def getRastersAsPngs(self, session, tableName, rasterIds, postGisRampString, rasterField='raster', rasterIdField='id',  cellSize=None, resampleMethod='NearestNeighbour'):
        
        # Validate
        VALID_RESAMPLE_METHODS = ('NearestNeighbour', 'Bilinear', 'Cubic', 'CubicSpline', 'Lanczos')

        # Validate
        if resampleMethod not in VALID_RESAMPLE_METHODS:
            print('RASTER CONVERSION ERROR: {0} is not a valid resampleMethod.'
                  ' Please use either {1}'.format(resampleMethod,
                                                  ', '.join(VALID_RESAMPLE_METHODS)))

        if cellSize is not None:
            if not self.isNumber(cellSize):
                raise ValueError('RASTER CONVERSION ERROR: cellSize must be a number or None.')

        # Convert raster ids into formatted string
        rasterIdsString = '({0})'.format(', '.join(rasterIds))

        if cellSize is not None:
            statement = '''
                        SELECT ST_AsPNG(ST_Transform(ST_ColorMap(ST_Rescale({0}, {5}, '{6}'), 1, '{4}'), 4326, 'Bilinear')) As png
                        FROM {1}
                        WHERE {2} IN {3};
                        '''.format(rasterField, tableName, rasterIdField, rasterIdsString, postGisRampString, cellSize,
                                   resampleMethod)
        else:
            statement = '''
                        SELECT ST_AsPNG(ST_Transform(ST_ColorMap({0}, 1, '{4}'), 4326, 'Bilinear')) As png
                        FROM {1}
                        WHERE {2} IN {3};
                        '''.format(rasterField, tableName, rasterIdField, rasterIdsString, postGisRampString)
        result = session.execute(statement)
        return result
1199012
def get_raster_array(image):
    
    if isinstance(image, RGB):
        rgb = image.rgb
        data = np.dstack([np.flipud(rgb.dimension_values(d, flat=False))
                          for d in rgb.vdims])
    else:
        data = image.dimension_values(2, flat=False)
        if type(image) is Raster:
            data = data.T
        else:
            data = np.flipud(data)
    return data
701898
def parse_checksum_file(self, file):
        
        checksums = dict()
        file_path = '/'.join((self.rawdir, file))
        with open(file_path, 'rt') as tsvfile:
            reader = csv.reader(tsvfile, delimiter=' ')
            for row in reader:
                (checksum, whitespace, file_name) = row
                checksums[checksum] = file_name

        return checksums
499569
def _read_buckets_cache_file(cache_file):
    '''
    
    '''

    log.debug('Reading buckets cache file')

    with salt.utils.files.fopen(cache_file, 'rb') as fp_:
        data = pickle.load(fp_)

    return data
594123
def _read_mesafile(filename,data_rows=0,only='all'):
    
    f=open(filename,'r')
    vv=[]
    v=[]
    lines = []
    line  = ''
    for i in range(0,6):
        line = f.readline()
        lines.extend([line])

    hval  = lines[2].split()
    hlist = lines[1].split()
    header_attr = {}
    for a,b in zip(hlist,hval):
        header_attr[a] = float(b)
    if only is 'header_attr':
        return header_attr

    cols    = {}
    colnum  = lines[4].split()
    colname = lines[5].split()
    for a,b in zip(colname,colnum):
        cols[a] = int(b)

    data = []

    old_percent = 0
    for i in range(data_rows):
        # writing reading status
        percent = int(i*100/np.max([1, data_rows-1]))
        if percent >= old_percent + 5:
            sys.stdout.flush()
            sys.stdout.write("\r reading " + "...%d%%" % percent)
            old_percent = percent
        line = f.readline()
        v=line.split()
        try:
            vv=np.array(v,dtype='float64')
        except ValueError:
            for item in v:
                if item.__contains__('.') and not item.__contains__('E'):
                    v[v.index(item)]='0'
        data.append(vv)

    print(' \n')
    f.close()
    a=np.array(data)
    data = []
    return header_attr, cols, a
1235062
def _load_shader(filename):
    """"""
    curdir = op.dirname(op.realpath(__file__))
    glsl_path = op.join(curdir, 'glsl')
    path = op.join(glsl_path, filename)
    with open(path, 'r') as f:
        return f.read()