Instruction:
Implement a Python 3 function for
writing numpy array and tags to TIFF file.

Response:
def save(self, data=None, shape=None, dtype=None, returnoffset=False,
             photometric=None, planarconfig=None, extrasamples=None, tile=None,
             contiguous=True, align=16, truncate=False, compress=0,
             rowsperstrip=None, predictor=False, colormap=None,
             description=None, datetime=None, resolution=None, subfiletype=0,
             software='tifffile.py', metadata={}, ijmetadata=None,
             extratags=()):
        """Write numpy array and tags to TIFF file.

        The data shape's last dimensions are assumed to be image depth,
        height (length), width, and samples.
        If a colormap is provided, the data's dtype must be uint8 or uint16
        and the data values are indices into the last dimension of the
        colormap.
        If 'shape' and 'dtype' are specified, an empty array is saved.
        This option cannot be used with compression or multiple tiles.
        Image data are written uncompressed in one strip per plane by default.
        Dimensions larger than 2 to 4 (depending on photometric mode, planar
        configuration, and SGI mode) are flattened and saved as separate pages.
        The SampleFormat and BitsPerSample tags are derived from the data type.

        Parameters
        ----------
        data : numpy.ndarray or None
            Input image array.
        shape : tuple or None
            Shape of the empty array to save. Used only if 'data' is None.
        dtype : numpy.dtype or None
            Data-type of the empty array to save. Used only if 'data' is None.
        returnoffset : bool
            If True and the image data in the file is memory-mappable, return
            the offset and number of bytes of the image data in the file.
        photometric : {'MINISBLACK', 'MINISWHITE', 'RGB', 'PALETTE', 'CFA'}
            The color space of the image data.
            By default, this setting is inferred from the data shape and the
            value of colormap.
            For CFA images, DNG tags must be specified in 'extratags'.
        planarconfig : {'CONTIG', 'SEPARATE'}
            Specifies if samples are stored interleaved or in separate planes.
            By default, this setting is inferred from the data shape.
            If this parameter is set, extra samples are used to store grayscale
            images.
            'CONTIG': last dimension contains samples.
            'SEPARATE': third last dimension contains samples.
        extrasamples : tuple of {'UNSPECIFIED', 'ASSOCALPHA', 'UNASSALPHA'}
            Defines the interpretation of extra components in pixels.
            'UNSPECIFIED': no transparency information (default).
            'ASSOCALPHA': single, true transparency with pre-multiplied color.
            'UNASSALPHA': independent transparency masks.
        tile : tuple of int
            The shape (depth, length, width) of image tiles to write.
            If None (default), image data are written in strips.
            The tile length and width must be a multiple of 16.
            If the tile depth is provided, the SGI ImageDepth and TileDepth
            tags are used to save volume data.
            Unless a single tile is used, tiles cannot be used to write
            contiguous files.
            Few software can read the SGI format, e.g. MeVisLab.
        contiguous : bool
            If True (default) and the data and parameters are compatible with
            previous ones, if any, the image data are stored contiguously after
            the previous one. In that case, 'photometric', 'planarconfig',
            'rowsperstrip', are ignored. Metadata such as 'description',
            'metadata', 'datetime', and 'extratags' are written to the first
            page of a contiguous series only.
        align : int
            Byte boundary on which to align the image data in the file.
            Default 16. Use mmap.ALLOCATIONGRANULARITY for memory-mapped data.
            Following contiguous writes are not aligned.
        truncate : bool
            If True, only write the first page including shape metadata if
            possible (uncompressed, contiguous, not tiled).
            Other TIFF readers will only be able to read part of the data.
        compress : int or str or (str, int)
            If 0 (default), data are written uncompressed.
            If 0-9, the level of ADOBE_DEFLATE compression.
            If a str, one of TIFF.COMPRESSION, e.g. 'LZMA' or 'ZSTD'.
            If a tuple, first item is one of TIFF.COMPRESSION and second item
            is compression level.
            Compression cannot be used to write contiguous files.
        rowsperstrip : int
            The number of rows per strip. By default strips will be ~64 KB
            if compression is enabled, else rowsperstrip is set to the image
            length. Bilevel images are always stored in one strip per plane.
        predictor : bool
            If True, apply horizontal differencing or floating-point predictor
            before compression.
        colormap : numpy.ndarray
            RGB color values for the corresponding data value.
            Must be of shape (3, 2**(data.itemsize*8)) and dtype uint16.
        description : str
            The subject of the image. Must be 7-bit ASCII. Cannot be used with
            the ImageJ format. Saved with the first page only.
        datetime : datetime, str, or bool
            Date and time of image creation in '%Y:%m:%d %H:%M:%S' format or
            datetime object. Else if True, the current date and time is used.
            Saved with the first page only.
        resolution : (float, float[, str]) or ((int, int), (int, int)[, str])
            X and Y resolutions in pixels per resolution unit as float or
            rational numbers. A third, optional parameter specifies the
            resolution unit, which must be None (default for ImageJ),
            'INCH' (default), or 'CENTIMETER'.
        subfiletype : int
            Bitfield to indicate the kind of data. Set bit 0 if the image
            is a reduced-resolution version of another image. Set bit 1 if
            the image is part of a multi-page image. Set bit 2 if the image
            is transparency mask for another image (photometric must be
            MASK, SamplesPerPixel and BitsPerSample must be 1).
        software : str
            Name of the software used to create the file. Must be 7-bit ASCII.
            Saved with the first page only.
        metadata : dict
            Additional metadata to be saved along with shape information
            in JSON or ImageJ formats in an ImageDescription tag.
            If None, do not write a second ImageDescription tag.
            Strings must be 7-bit ASCII. Saved with the first page only.
        ijmetadata : dict
            Additional metadata to be saved in application specific
            IJMetadata and IJMetadataByteCounts tags. Refer to the
            imagej_metadata_tag function for valid keys and values.
            Saved with the first page only.
        extratags : sequence of tuples
            Additional tags as [(code, dtype, count, value, writeonce)].

            code : int
                The TIFF tag Id.
            dtype : str
                Data type of items in 'value' in Python struct format.
                One of B, s, H, I, 2I, b, h, i, 2i, f, d, Q, or q.
            count : int
                Number of data values. Not used for string or byte string
                values.
            value : sequence
                'Count' values compatible with 'dtype'.
                Byte strings must contain count values of dtype packed as
                binary data.
            writeonce : bool
                If True, the tag is written to the first page only.

        """
        # TODO: refactor this function
        fh = self._fh
        byteorder = self._byteorder

        if data is None:
            if compress:
                raise ValueError('cannot save compressed empty file')
            datashape = shape
            datadtype = numpy.dtype(dtype).newbyteorder(byteorder)
            datadtypechar = datadtype.char
        else:
            data = numpy.asarray(data, byteorder+data.dtype.char, 'C')
            if data.size == 0:
                raise ValueError('cannot save empty array')
            datashape = data.shape
            datadtype = data.dtype
            datadtypechar = data.dtype.char

        returnoffset = returnoffset and datadtype.isnative
        bilevel = datadtypechar == '?'
        if bilevel:
            index = -1 if datashape[-1] > 1 else -2
            datasize = product(datashape[:index])
            if datashape[index] % 8:
                datasize *= datashape[index] // 8 + 1
            else:
                datasize *= datashape[index] // 8
        else:
            datasize = product(datashape) * datadtype.itemsize

        # just append contiguous data if possible
        self._truncate = bool(truncate)
        if self._datashape:
            if (not contiguous
                    or self._datashape[1:] != datashape
                    or self._datadtype != datadtype
                    or (compress and self._tags)
                    or tile
                    or not numpy.array_equal(colormap, self._colormap)):
                # incompatible shape, dtype, compression mode, or colormap
                self._write_remaining_pages()
                self._write_image_description()
                self._truncate = False
                self._descriptionoffset = 0
                self._descriptionlenoffset = 0
                self._datashape = None
                self._colormap = None
                if self._imagej:
                    raise ValueError(
                        'ImageJ does not support non-contiguous data')
            else:
                # consecutive mode
                self._datashape = (self._datashape[0] + 1,) + datashape
                if not compress:
                    # write contiguous data, write IFDs/tags later
                    offset = fh.tell()
                    if data is None:
                        fh.write_empty(datasize)
                    else:
                        fh.write_array(data)
                    if returnoffset:
                        return offset, datasize
                    return None

        input_shape = datashape
        tagnoformat = self._tagnoformat
        valueformat = self._valueformat
        offsetformat = self._offsetformat
        offsetsize = self._offsetsize
        tagsize = self._tagsize

        MINISBLACK = TIFF.PHOTOMETRIC.MINISBLACK
        MINISWHITE = TIFF.PHOTOMETRIC.MINISWHITE
        RGB = TIFF.PHOTOMETRIC.RGB
        CFA = TIFF.PHOTOMETRIC.CFA
        PALETTE = TIFF.PHOTOMETRIC.PALETTE
        CONTIG = TIFF.PLANARCONFIG.CONTIG
        SEPARATE = TIFF.PLANARCONFIG.SEPARATE

        # parse input
        if photometric is not None:
            photometric = enumarg(TIFF.PHOTOMETRIC, photometric)
        if planarconfig:
            planarconfig = enumarg(TIFF.PLANARCONFIG, planarconfig)
        if extrasamples is None:
            extrasamples_ = None
        else:
            extrasamples_ = tuple(enumarg(TIFF.EXTRASAMPLE, es)
                                  for es in sequence(extrasamples))
        if not compress:
            compress = False
            compresstag = 1
            # TODO: support predictors without compression
            predictor = False
            predictortag = 1
        else:
            if isinstance(compress, (tuple, list)):
                compress, compresslevel = compress
            elif isinstance(compress, int):
                compress, compresslevel = 'ADOBE_DEFLATE', int(compress)
                if not 0 <= compresslevel <= 9:
                    raise ValueError('invalid compression level %s' % compress)
            else:
                compresslevel = None
            compress = compress.upper()
            compresstag = enumarg(TIFF.COMPRESSION, compress)

        if predictor:
            if datadtype.kind in 'iu':
                predictortag = 2
                predictor = TIFF.PREDICTORS[2]
            elif datadtype.kind == 'f':
                predictortag = 3
                predictor = TIFF.PREDICTORS[3]
            else:
                raise ValueError('cannot apply predictor to %s' % datadtype)

        # prepare ImageJ format
        if self._imagej:
            # if predictor or compress:
            #     warnings.warn(
            #         'ImageJ cannot handle predictors or compression')
            if description:
                warnings.warn('not writing description to ImageJ file')
                description = None
            volume = False
            if datadtypechar not in 'BHhf':
                raise ValueError(
                    'ImageJ does not support data type %s' % datadtypechar)
            ijrgb = photometric == RGB if photometric else None
            if datadtypechar not in 'B':
                ijrgb = False
            ijshape = imagej_shape(datashape, ijrgb)
            if ijshape[-1] in (3, 4):
                photometric = RGB
                if datadtypechar not in 'B':
                    raise ValueError('ImageJ does not support data type %s '
                                     'for RGB' % datadtypechar)
            elif photometric is None:
                photometric = MINISBLACK
                planarconfig = None
            if planarconfig == SEPARATE:
                raise ValueError('ImageJ does not support planar images')
            planarconfig = CONTIG if ijrgb else None

        # define compress function
        if compress:
            compressor = TIFF.COMPESSORS[compresstag]
            if predictor:
                def compress(data, level=compresslevel):
                    data = predictor(data, axis=-2)
                    return compressor(data, level)
            else:
                def compress(data, level=compresslevel):
                    return compressor(data, level)

        # verify colormap and indices
        if colormap is not None:
            if datadtypechar not in 'BH':
                raise ValueError('invalid data dtype for palette mode')
            colormap = numpy.asarray(colormap, dtype=byteorder+'H')
            if colormap.shape != (3, 2**(datadtype.itemsize * 8)):
                raise ValueError('invalid color map shape')
            self._colormap = colormap

        # verify tile shape
        if tile:
            tile = tuple(int(i) for i in tile[:3])
            volume = len(tile) == 3
            if (len(tile) < 2 or tile[-1] % 16 or tile[-2] % 16 or
                    any(i < 1 for i in tile)):
                raise ValueError('invalid tile shape')
        else:
            tile = ()
            volume = False

        # normalize data shape to 5D or 6D, depending on volume:
        #   (pages, planar_samples, [depth,] height, width, contig_samples)
        datashape = reshape_nd(datashape, 3 if photometric == RGB else 2)
        shape = datashape
        ndim = len(datashape)

        samplesperpixel = 1
        extrasamples = 0
        if volume and ndim < 3:
            volume = False
        if colormap is not None:
            photometric = PALETTE
            planarconfig = None
        if photometric is None:
            photometric = MINISBLACK
            if bilevel:
                photometric = MINISWHITE
            elif planarconfig == CONTIG:
                if ndim > 2 and shape[-1] in (3, 4):
                    photometric = RGB
            elif planarconfig == SEPARATE:
                if volume and ndim > 3 and shape[-4] in (3, 4):
                    photometric = RGB
                elif ndim > 2 and shape[-3] in (3, 4):
                    photometric = RGB
            elif ndim > 2 and shape[-1] in (3, 4):
                photometric = RGB
            elif self._imagej:
                photometric = MINISBLACK
            elif volume and ndim > 3 and shape[-4] in (3, 4):
                photometric = RGB
            elif ndim > 2 and shape[-3] in (3, 4):
                photometric = RGB
        if planarconfig and len(shape) <= (3 if volume else 2):
            planarconfig = None
            if photometric not in (0, 1, 3, 4):
                photometric = MINISBLACK
        if photometric == RGB:
            if len(shape) < 3:
                raise ValueError('not a RGB(A) image')
            if len(shape) < 4:
                volume = False
            if planarconfig is None:
                if shape[-1] in (3, 4):
                    planarconfig = CONTIG
                elif shape[-4 if volume else -3] in (3, 4):
                    planarconfig = SEPARATE
                elif shape[-1] > shape[-4 if volume else -3]:
                    planarconfig = SEPARATE
                else:
                    planarconfig = CONTIG
            if planarconfig == CONTIG:
                datashape = (-1, 1) + shape[(-4 if volume else -3):]
                samplesperpixel = datashape[-1]
            else:
                datashape = (-1,) + shape[(-4 if volume else -3):] + (1,)
                samplesperpixel = datashape[1]
            if samplesperpixel > 3:
                extrasamples = samplesperpixel - 3
        elif photometric == CFA:
            if len(shape) != 2:
                raise ValueError('invalid CFA image')
            volume = False
            planarconfig = None
            datashape = (-1, 1) + shape[-2:] + (1,)
            if 50706 not in (et[0] for et in extratags):
                raise ValueError('must specify DNG tags for CFA image')
        elif planarconfig and len(shape) > (3 if volume else 2):
            if planarconfig == CONTIG:
                datashape = (-1, 1) + shape[(-4 if volume else -3):]
                samplesperpixel = datashape[-1]
            else:
                datashape = (-1,) + shape[(-4 if volume else -3):] + (1,)
                samplesperpixel = datashape[1]
            extrasamples = samplesperpixel - 1
        else:
            planarconfig = None
            while len(shape) > 2 and shape[-1] == 1:
                shape = shape[:-1]  # remove trailing 1s
            if len(shape) < 3:
                volume = False
            if extrasamples_ is None:
                datashape = (-1, 1) + shape[(-3 if volume else -2):] + (1,)
            else:
                datashape = (-1, 1) + shape[(-4 if volume else -3):]
                samplesperpixel = datashape[-1]
                extrasamples = samplesperpixel - 1

        if subfiletype & 0b100:
            # FILETYPE_MASK
            if not (bilevel and samplesperpixel == 1 and
                    photometric in (0, 1, 4)):
                raise ValueError('invalid SubfileType MASK')
            photometric = TIFF.PHOTOMETRIC.MASK

        # normalize shape to 6D
        assert len(datashape) in (5, 6)
        if len(datashape) == 5:
            datashape = datashape[:2] + (1,) + datashape[2:]
        if datashape[0] == -1:
            s0 = product(input_shape) // product(datashape[1:])
            datashape = (s0,) + datashape[1:]
        shape = datashape
        if data is not None:
            data = data.reshape(shape)

        if tile and not volume:
            tile = (1, tile[-2], tile[-1])

        if photometric == PALETTE:
            if (samplesperpixel != 1 or extrasamples or
                    shape[1] != 1 or shape[-1] != 1):
                raise ValueError('invalid data shape for palette mode')

        if photometric == RGB and samplesperpixel == 2:
            raise ValueError('not a RGB image (samplesperpixel=2)')

        if bilevel:
            if compresstag not in (1, 32773):
                raise ValueError('cannot compress bilevel image')
            if tile:
                raise ValueError('cannot save tiled bilevel image')
            if photometric not in (0, 1, 4):
                raise ValueError('cannot save bilevel image as %s' %
                                 str(photometric))
            datashape = list(datashape)
            if datashape[-2] % 8:
                datashape[-2] = datashape[-2] // 8 + 1
            else:
                datashape[-2] = datashape[-2] // 8
            datashape = tuple(datashape)
            assert datasize == product(datashape)
            if data is not None:
                data = numpy.packbits(data, axis=-2)
                assert datashape[-2] == data.shape[-2]

        bytestr = bytes if sys.version[0] == '2' else (
            lambda x: bytes(x, 'ascii') if isinstance(x, str) else x)
        tags = []  # list of (code, ifdentry, ifdvalue, writeonce)

        strip_or_tile = 'Tile' if tile else 'Strip'
        tagbytecounts = TIFF.TAG_NAMES[strip_or_tile + 'ByteCounts']
        tagoffsets = TIFF.TAG_NAMES[strip_or_tile + 'Offsets']
        self._tagoffsets = tagoffsets

        def pack(fmt, *val):
            return struct.pack(byteorder+fmt, *val)

        def addtag(code, dtype, count, value, writeonce=False):
            # Compute ifdentry & ifdvalue bytes from code, dtype, count, value
            # Append (code, ifdentry, ifdvalue, writeonce) to tags list
            code = int(TIFF.TAG_NAMES.get(code, code))
            try:
                tifftype = TIFF.DATA_DTYPES[dtype]
            except KeyError:
                raise ValueError('unknown dtype %s' % dtype)
            rawcount = count

            if dtype == 's':
                # strings
                value = bytestr(value) + b'\0'
                count = rawcount = len(value)
                rawcount = value.find(b'\0\0')
                if rawcount < 0:
                    rawcount = count
                else:
                    rawcount += 1  # length of string without buffer
                value = (value,)
            elif isinstance(value, bytes):
                # packed binary data
                dtsize = struct.calcsize(dtype)
                if len(value) % dtsize:
                    raise ValueError('invalid packed binary data')
                count = len(value) // dtsize
            if len(dtype) > 1:
                count *= int(dtype[:-1])
                dtype = dtype[-1]
            ifdentry = [pack('HH', code, tifftype),
                        pack(offsetformat, rawcount)]
            ifdvalue = None
            if struct.calcsize(dtype) * count <= offsetsize:
                # value(s) can be written directly
                if isinstance(value, bytes):
                    ifdentry.append(pack(valueformat, value))
                elif count == 1:
                    if isinstance(value, (tuple, list, numpy.ndarray)):
                        value = value[0]
                    ifdentry.append(pack(valueformat, pack(dtype, value)))
                else:
                    ifdentry.append(pack(valueformat,
                                         pack(str(count)+dtype, *value)))
            else:
                # use offset to value(s)
                ifdentry.append(pack(offsetformat, 0))
                if isinstance(value, bytes):
                    ifdvalue = value
                elif isinstance(value, numpy.ndarray):
                    assert value.size == count
                    assert value.dtype.char == dtype
                    ifdvalue = value.tostring()
                elif isinstance(value, (tuple, list)):
                    ifdvalue = pack(str(count)+dtype, *value)
                else:
                    ifdvalue = pack(dtype, value)
            tags.append((code, b''.join(ifdentry), ifdvalue, writeonce))

        def rational(arg, max_denominator=1000000):
            """"Return nominator and denominator from float or two integers."""
            from fractions import Fraction  # delayed import
            try:
                f = Fraction.from_float(arg)
            except TypeError:
                f = Fraction(arg[0], arg[1])
            f = f.limit_denominator(max_denominator)
            return f.numerator, f.denominator

        if description:
            # user provided description
            addtag('ImageDescription', 's', 0, description, writeonce=True)

        # write shape and metadata to ImageDescription
        self._metadata = {} if not metadata else metadata.copy()
        if self._imagej:
            description = imagej_description(
                input_shape, shape[-1] in (3, 4), self._colormap is not None,
                **self._metadata)
        elif metadata or metadata == {}:
            if self._truncate:
                self._metadata.update(truncated=True)
            description = json_description(input_shape, **self._metadata)
        # elif metadata is None and self._truncate:
        #     raise ValueError('cannot truncate without writing metadata')
        else:
            description = None
        if description:
            # add 64 bytes buffer
            # the image description might be updated later with the final shape
            description = str2bytes(description, 'ascii')
            description += b'\0' * 64
            self._descriptionlen = len(description)
            addtag('ImageDescription', 's', 0, description, writeonce=True)

        if software:
            addtag('Software', 's', 0, software, writeonce=True)
        if datetime:
            if isinstance(datetime, str):
                if len(datetime) != 19 or datetime[16] != ':':
                    raise ValueError('invalid datetime string')
            else:
                try:
                    datetime = datetime.strftime('%Y:%m:%d %H:%M:%S')
                except AttributeError:
                    datetime = self._now().strftime('%Y:%m:%d %H:%M:%S')
            addtag('DateTime', 's', 0, datetime, writeonce=True)
        addtag('Compression', 'H', 1, compresstag)
        if predictor:
            addtag('Predictor', 'H', 1, predictortag)
        addtag('ImageWidth', 'I', 1, shape[-2])
        addtag('ImageLength', 'I', 1, shape[-3])
        if tile:
            addtag('TileWidth', 'I', 1, tile[-1])
            addtag('TileLength', 'I', 1, tile[-2])
            if tile[0] > 1:
                addtag('ImageDepth', 'I', 1, shape[-4])
                addtag('TileDepth', 'I', 1, tile[0])
        addtag('NewSubfileType', 'I', 1, subfiletype)
        if not bilevel:
            sampleformat = {'u': 1, 'i': 2, 'f': 3, 'c': 6}[datadtype.kind]
            addtag('SampleFormat', 'H', samplesperpixel,
                   (sampleformat,) * samplesperpixel)
        addtag('PhotometricInterpretation', 'H', 1, photometric.value)
        if colormap is not None:
            addtag('ColorMap', 'H', colormap.size, colormap)
        addtag('SamplesPerPixel', 'H', 1, samplesperpixel)
        if bilevel:
            pass
        elif planarconfig and samplesperpixel > 1:
            addtag('PlanarConfiguration', 'H', 1, planarconfig.value)
            addtag('BitsPerSample', 'H', samplesperpixel,
                   (datadtype.itemsize * 8,) * samplesperpixel)
        else:
            addtag('BitsPerSample', 'H', 1, datadtype.itemsize * 8)
        if extrasamples:
            if extrasamples_ is not None:
                if extrasamples != len(extrasamples_):
                    raise ValueError('wrong number of extrasamples specified')
                addtag('ExtraSamples', 'H', extrasamples, extrasamples_)
            elif photometric == RGB and extrasamples == 1:
                # Unassociated alpha channel
                addtag('ExtraSamples', 'H', 1, 2)
            else:
                # Unspecified alpha channel
                addtag('ExtraSamples', 'H', extrasamples, (0,) * extrasamples)
        if resolution is not None:
            addtag('XResolution', '2I', 1, rational(resolution[0]))
            addtag('YResolution', '2I', 1, rational(resolution[1]))
            if len(resolution) > 2:
                unit = resolution[2]
                unit = 1 if unit is None else enumarg(TIFF.RESUNIT, unit)
            elif self._imagej:
                unit = 1
            else:
                unit = 2
            addtag('ResolutionUnit', 'H', 1, unit)
        elif not self._imagej:
            addtag('XResolution', '2I', 1, (1, 1))
            addtag('YResolution', '2I', 1, (1, 1))
            addtag('ResolutionUnit', 'H', 1, 1)
        if ijmetadata:
            for t in imagej_metadata_tag(ijmetadata, byteorder):
                addtag(*t)

        contiguous = not compress
        if tile:
            # one chunk per tile per plane
            tiles = ((shape[2] + tile[0] - 1) // tile[0],
                     (shape[3] + tile[1] - 1) // tile[1],
                     (shape[4] + tile[2] - 1) // tile[2])
            numtiles = product(tiles) * shape[1]
            databytecounts = [
                product(tile) * shape[-1] * datadtype.itemsize] * numtiles
            addtag(tagbytecounts, offsetformat, numtiles, databytecounts)
            addtag(tagoffsets, offsetformat, numtiles, [0] * numtiles)
            contiguous = contiguous and product(tiles) == 1
            if not contiguous:
                # allocate tile buffer
                chunk = numpy.empty(tile + (shape[-1],), dtype=datadtype)
        elif contiguous and (bilevel or rowsperstrip is None):
            # one strip per plane
            if bilevel:
                databytecounts = [product(datashape[2:])] * shape[1]
            else:
                databytecounts = [
                    product(datashape[2:]) * datadtype.itemsize] * shape[1]
            addtag(tagbytecounts, offsetformat, shape[1], databytecounts)
            addtag(tagoffsets, offsetformat, shape[1], [0] * shape[1])
            addtag('RowsPerStrip', 'I', 1, shape[-3])
        else:
            # use rowsperstrip
            rowsize = product(shape[-2:]) * datadtype.itemsize
            if rowsperstrip is None:
                # compress ~64 KB chunks by default
                rowsperstrip = 65536 // rowsize if compress else shape[-3]
            if rowsperstrip < 1:
                rowsperstrip = 1
            elif rowsperstrip > shape[-3]:
                rowsperstrip = shape[-3]
            addtag('RowsPerStrip', 'I', 1, rowsperstrip)

            numstrips1 = (shape[-3] + rowsperstrip - 1) // rowsperstrip
            numstrips = numstrips1 * shape[1]
            if compress:
                databytecounts = [0] * numstrips
            else:
                # TODO: save bilevel data with rowsperstrip
                stripsize = rowsperstrip * rowsize
                databytecounts = [stripsize] * numstrips
                stripsize -= rowsize * (numstrips1 * rowsperstrip - shape[-3])
                for i in range(numstrips1-1, numstrips, numstrips1):
                    databytecounts[i] = stripsize
            addtag(tagbytecounts, offsetformat, numstrips, databytecounts)
            addtag(tagoffsets, offsetformat, numstrips, [0] * numstrips)

        if data is None and not contiguous:
            raise ValueError('cannot write non-contiguous empty file')

        # add extra tags from user
        for t in extratags:
            addtag(*t)

        # TODO: check TIFFReadDirectoryCheckOrder warning in files containing
        #   multiple tags of same code
        # the entries in an IFD must be sorted in ascending order by tag code
        tags = sorted(tags, key=lambda x: x[0])

        fhpos = fh.tell()
        if not (self._bigtiff or self._imagej) and fhpos + datasize > 2**32-1:
            raise ValueError('data too large for standard TIFF file')

        # if not compressed or multi-tiled, write the first IFD and then
        # all data contiguously; else, write all IFDs and data interleaved
        for pageindex in range(1 if contiguous else shape[0]):

            ifdpos = fhpos
            if ifdpos % 2:
                # location of IFD must begin on a word boundary
                fh.write(b'\0')
                ifdpos += 1

            # update pointer at ifdoffset
            fh.seek(self._ifdoffset)
            fh.write(pack(offsetformat, ifdpos))
            fh.seek(ifdpos)

            # create IFD in memory
            if pageindex < 2:
                ifd = io.BytesIO()
                ifd.write(pack(tagnoformat, len(tags)))
                tagoffset = ifd.tell()
                ifd.write(b''.join(t[1] for t in tags))
                ifdoffset = ifd.tell()
                ifd.write(pack(offsetformat, 0))  # offset to next IFD
                # write tag values and patch offsets in ifdentries
                for tagindex, tag in enumerate(tags):
                    offset = tagoffset + tagindex * tagsize + offsetsize + 4
                    code = tag[0]
                    value = tag[2]
                    if value:
                        pos = ifd.tell()
                        if pos % 2:
                            # tag value is expected to begin on word boundary
                            ifd.write(b'\0')
                            pos += 1
                        ifd.seek(offset)
                        ifd.write(pack(offsetformat, ifdpos + pos))
                        ifd.seek(pos)
                        ifd.write(value)
                        if code == tagoffsets:
                            dataoffsetsoffset = offset, pos
                        elif code == tagbytecounts:
                            databytecountsoffset = offset, pos
                        elif code == 270 and value.endswith(b'\0\0\0\0'):
                            # image description buffer
                            self._descriptionoffset = ifdpos + pos
                            self._descriptionlenoffset = (
                                ifdpos + tagoffset + tagindex*tagsize + 4)
                    elif code == tagoffsets:
                        dataoffsetsoffset = offset, None
                    elif code == tagbytecounts:
                        databytecountsoffset = offset, None
                ifdsize = ifd.tell()
                if ifdsize % 2:
                    ifd.write(b'\0')
                    ifdsize += 1

            # write IFD later when strip/tile bytecounts and offsets are known
            fh.seek(ifdsize, 1)

            # write image data
            dataoffset = fh.tell()
            skip = align - dataoffset % align
            fh.seek(skip, 1)
            dataoffset += skip
            if contiguous:
                if data is None:
                    fh.write_empty(datasize)
                else:
                    fh.write_array(data)
            elif tile:
                if data is None:
                    fh.write_empty(numtiles * databytecounts[0])
                else:
                    stripindex = 0
                    for plane in data[pageindex]:
                        for tz in range(tiles[0]):
                            for ty in range(tiles[1]):
                                for tx in range(tiles[2]):
                                    c0 = min(tile[0], shape[2] - tz*tile[0])
                                    c1 = min(tile[1], shape[3] - ty*tile[1])
                                    c2 = min(tile[2], shape[4] - tx*tile[2])
                                    chunk[c0:, c1:, c2:] = 0
                                    chunk[:c0, :c1, :c2] = plane[
                                        tz*tile[0]:tz*tile[0]+c0,
                                        ty*tile[1]:ty*tile[1]+c1,
                                        tx*tile[2]:tx*tile[2]+c2]
                                    if compress:
                                        t = compress(chunk)
                                        fh.write(t)
                                        databytecounts[stripindex] = len(t)
                                        stripindex += 1
                                    else:
                                        fh.write_array(chunk)
                                        # fh.flush()
            elif compress:
                # write one strip per rowsperstrip
                assert data.shape[2] == 1  # not handling depth
                numstrips = (shape[-3] + rowsperstrip - 1) // rowsperstrip
                stripindex = 0
                for plane in data[pageindex]:
                    for i in range(numstrips):
                        strip = plane[0, i*rowsperstrip: (i+1)*rowsperstrip]
                        strip = compress(strip)
                        fh.write(strip)
                        databytecounts[stripindex] = len(strip)
                        stripindex += 1
            else:
                fh.write_array(data[pageindex])

            # update strip/tile offsets
            offset, pos = dataoffsetsoffset
            ifd.seek(offset)
            if pos:
                ifd.write(pack(offsetformat, ifdpos + pos))
                ifd.seek(pos)
                offset = dataoffset
                for size in databytecounts:
                    ifd.write(pack(offsetformat, offset))
                    offset += size
            else:
                ifd.write(pack(offsetformat, dataoffset))

            if compress:
                # update strip/tile bytecounts
                offset, pos = databytecountsoffset
                ifd.seek(offset)
                if pos:
                    ifd.write(pack(offsetformat, ifdpos + pos))
                    ifd.seek(pos)
                    for size in databytecounts:
                        ifd.write(pack(offsetformat, size))
                else:
                    ifd.write(pack(offsetformat, databytecounts[0]))

            fhpos = fh.tell()
            fh.seek(ifdpos)
            fh.write(iogetbuffer(ifd))
            fh.flush()
            fh.seek(fhpos)

            self._ifdoffset = ifdpos + ifdoffset

            # remove tags that should be written only once
            if pageindex == 0:
                tags = [tag for tag in tags if not tag[-1]]

        self._shape = shape
        self._datashape = (1,) + input_shape
        self._datadtype = datadtype
        self._dataoffset = dataoffset
        self._databytecounts = databytecounts

        if contiguous:
            # write remaining IFDs/tags later
            self._tags = tags
            # return offset and size of image data
            if returnoffset:
                return dataoffset, sum(databytecounts)
        return None


Instruction:
Can you write a function in Python 3 where it
writes out the remaining IFDs and tags to file.

Response:
def _write_remaining_pages(self):
        """Write outstanding IFDs and tags to file."""
        if not self._tags or self._truncate:
            return

        pageno = self._shape[0] * self._datashape[0] - 1
        if pageno < 1:
            self._tags = None
            self._datadtype = None
            self._dataoffset = None
            self._databytecounts = None
            return

        fh = self._fh
        fhpos = fh.tell()
        if fhpos % 2:
            fh.write(b'\0')
            fhpos += 1

        pack = struct.pack
        offsetformat = self._byteorder + self._offsetformat
        offsetsize = self._offsetsize
        tagnoformat = self._byteorder + self._tagnoformat
        tagsize = self._tagsize
        dataoffset = self._dataoffset
        pagedatasize = sum(self._databytecounts)

        # construct template IFD in memory
        # need to patch offsets to next IFD and data before writing to file
        ifd = io.BytesIO()
        ifd.write(pack(tagnoformat, len(self._tags)))
        tagoffset = ifd.tell()
        ifd.write(b''.join(t[1] for t in self._tags))
        ifdoffset = ifd.tell()
        ifd.write(pack(offsetformat, 0))  # offset to next IFD
        # tag values
        for tagindex, tag in enumerate(self._tags):
            offset = tagoffset + tagindex * tagsize + offsetsize + 4
            code = tag[0]
            value = tag[2]
            if value:
                pos = ifd.tell()
                if pos % 2:
                    # tag value is expected to begin on word boundary
                    ifd.write(b'\0')
                    pos += 1
                ifd.seek(offset)
                try:
                    ifd.write(pack(offsetformat, fhpos + pos))
                except Exception:  # struct.error
                    if self._imagej:
                        warnings.warn('truncating ImageJ file')
                        self._truncate = True
                        return
                    raise ValueError('data too large for non-BigTIFF file')
                ifd.seek(pos)
                ifd.write(value)
                if code == self._tagoffsets:
                    # save strip/tile offsets for later updates
                    dataoffsetsoffset = offset, pos
            elif code == self._tagoffsets:
                dataoffsetsoffset = offset, None

        ifdsize = ifd.tell()
        if ifdsize % 2:
            ifd.write(b'\0')
            ifdsize += 1

        # check if all IFDs fit in file
        if not self._bigtiff and fhpos + ifdsize * pageno > 2**32 - 32:
            if self._imagej:
                warnings.warn('truncating ImageJ file')
                self._truncate = True
                return
            raise ValueError('data too large for non-BigTIFF file')

        # assemble IFD chain in memory from IFD template
        ifds = io.BytesIO(bytes(ifdsize * pageno))
        ifdpos = fhpos
        for _ in range(pageno):
            # update strip/tile offsets in IFD
            dataoffset += pagedatasize  # offset to image data
            offset, pos = dataoffsetsoffset
            ifd.seek(offset)
            if pos:
                ifd.write(pack(offsetformat, ifdpos + pos))
                ifd.seek(pos)
                offset = dataoffset
                for size in self._databytecounts:
                    ifd.write(pack(offsetformat, offset))
                    offset += size
            else:
                ifd.write(pack(offsetformat, dataoffset))
            # update pointer at ifdoffset to point to next IFD in file
            ifdpos += ifdsize
            ifd.seek(ifdoffset)
            ifd.write(pack(offsetformat, ifdpos))
            # write IFD entry
            ifds.write(iogetbuffer(ifd))

        # terminate IFD chain
        ifdoffset += ifdsize * (pageno - 1)
        ifds.seek(ifdoffset)
        ifds.write(pack(offsetformat, 0))
        # write IFD chain to file
        fh.write(iogetbuffer(ifds))
        # update file to point to new IFD chain
        pos = fh.tell()
        fh.seek(self._ifdoffset)
        fh.write(pack(offsetformat, fhpos))
        fh.flush()
        fh.seek(pos)

        self._ifdoffset = fhpos + ifdoffset
        self._tags = None
        self._datadtype = None
        self._dataoffset = None
        self._databytecounts = None


Instruction:
Given the following Python 3 function, write the documentation
def _write_image_description(self):
        if (not self._datashape or self._datashape[0] == 1 or
                self._descriptionoffset <= 0):
            return

        colormapped = self._colormap is not None
        if self._imagej:
            isrgb = self._shape[-1] in (3, 4)
            description = imagej_description(
                self._datashape, isrgb, colormapped, **self._metadata)
        else:
            description = json_description(self._datashape, **self._metadata)

        # rewrite description and its length to file
        description = description.encode('utf-8')
        description = description[:self._descriptionlen-1]
        pos = self._fh.tell()
        self._fh.seek(self._descriptionoffset)
        self._fh.write(description)
        self._fh.seek(self._descriptionlenoffset)
        self._fh.write(struct.pack(self._byteorder+self._offsetformat,
                                   len(description)+1))
        self._fh.seek(pos)

        self._descriptionoffset = 0
        self._descriptionlenoffset = 0
        self._descriptionlen = 0

Response: Write metadata to ImageDescription tag.


Instruction:
Can you implement a function in Python 3 that
writes remaining pages and close file handle.

Response:
def close(self):
        """Write remaining pages and close file handle."""
        if not self._truncate:
            self._write_remaining_pages()
        self._write_image_description()
        self._fh.close()


Instruction:
How would you explain what the following Python 3 function does
def close(self):
        for tif in self._files.values():
            tif.filehandle.close()
        self._files = {}

Response: Close open file handle s.


Instruction:
Implement a Python 3 function for
returning image data from selected TIFF pages as numpy array.

Response:
def asarray(self, key=None, series=None, out=None, validate=True,
                maxworkers=None):
        """Return image data from selected TIFF page(s) as numpy array.

        By default, the data from the first series is returned.

        Parameters
        ----------
        key : int, slice, or sequence of indices
            Defines which pages to return as array.
            If None (default), data from a series (default 0) is returned.
            If not None, data from the specified pages in the whole file
            (if 'series' is None) or a specified series are returned as a
            stacked array.
            Requesting an array from multiple pages that are not compatible
            wrt. shape, dtype, compression etc is undefined, i.e. may crash
            or return incorrect values.
        series : int or TiffPageSeries
            Defines which series of pages to return as array.
        out : numpy.ndarray, str, or file-like object
            Buffer where image data will be saved.
            If None (default), a new array will be created.
            If numpy.ndarray, a writable array of compatible dtype and shape.
            If 'memmap', directly memory-map the image data in the TIFF file
            if possible; else create a memory-mapped array in a temporary file.
            If str or open file, the file name or file object used to
            create a memory-map to an array stored in a binary file on disk.
        validate : bool
            If True (default), validate various tags.
            Passed to TiffPage.asarray().
        maxworkers : int or None
            Maximum number of threads to concurrently get data from pages
            or tiles. If None (default), mutli-threading is enabled if data
            are compressed. If 0, up to half the CPU cores are used.
            If 1, mutli-threading is disabled.
            Reading data from file is limited to a single thread.
            Using multiple threads can significantly speed up this function
            if the bottleneck is decoding compressed data, e.g. in case of
            large LZW compressed LSM files or JPEG compressed tiled slides.
            If the bottleneck is I/O or pure Python code, using multiple
            threads might be detrimental.

        Returns
        -------
        numpy.ndarray
            Image data from the specified pages.
            See the TiffPage.asarray function for operations that are
            applied (or not) to the raw data stored in the file.

        """
        if not self.pages:
            return numpy.array([])
        if key is None and series is None:
            series = 0
        if series is None:
            pages = self.pages
        else:
            try:
                series = self.series[series]
            except (KeyError, TypeError):
                pass
            pages = series.pages

        if key is None:
            pass
        elif series is None:
            pages = self.pages._getlist(key)
        elif isinstance(key, inttypes):
            pages = [pages[key]]
        elif isinstance(key, slice):
            pages = pages[key]
        elif isinstance(key, Iterable):
            pages = [pages[k] for k in key]
        else:
            raise TypeError('key must be an int, slice, or sequence')

        if not pages:
            raise ValueError('no pages selected')

        if key is None and series and series.offset:
            typecode = self.byteorder + series.dtype.char
            if pages[0].is_memmappable and (isinstance(out, str) and
                                            out == 'memmap'):
                # direct mapping
                result = self.filehandle.memmap_array(
                    typecode, series.shape, series.offset)
            else:
                # read into output
                if out is not None:
                    out = create_output(out, series.shape, series.dtype)
                self.filehandle.seek(series.offset)
                result = self.filehandle.read_array(
                    typecode, product(series.shape), out=out)
        elif len(pages) == 1:
            result = pages[0].asarray(out=out, validate=validate,
                                      maxworkers=maxworkers)
        else:
            result = stack_pages(pages, out=out, maxworkers=maxworkers)

        if result is None:
            return None

        if key is None:
            try:
                result.shape = series.shape
            except ValueError:
                try:
                    log.warning('TiffFile.asarray: failed to reshape %s to %s',
                                result.shape, series.shape)
                    # try series of expected shapes
                    result.shape = (-1,) + series.shape
                except ValueError:
                    # revert to generic shape
                    result.shape = (-1,) + pages[0].shape
        elif len(pages) == 1:
            result.shape = pages[0].shape
        else:
            result.shape = (-1,) + pages[0].shape
        return result


Instruction:
Can you generate a brief explanation for the following Python 3 code
def series(self):
        if not self.pages:
            return []

        useframes = self.pages.useframes
        keyframe = self.pages.keyframe.index
        series = []
        for name in ('lsm', 'ome', 'imagej', 'shaped', 'fluoview', 'sis',
                     'uniform', 'mdgel'):
            if getattr(self, 'is_' + name, False):
                series = getattr(self, '_series_' + name)()
                break
        self.pages.useframes = useframes
        self.pages.keyframe = keyframe
        if not series:
            series = self._series_generic()

        # remove empty series, e.g. in MD Gel files
        series = [s for s in series if product(s.shape) > 0]

        for i, s in enumerate(series):
            s.index = i
        return series

Response: Return related pages as TiffPageSeries.


Instruction:
How would you implement a function in Python 3 that
returns image series in file.

Response:
def _series_generic(self):
        """Return image series in file.

        A series is a sequence of TiffPages with the same hash.

        """
        pages = self.pages
        pages._clear(False)
        pages.useframes = False
        if pages.cache:
            pages._load()

        result = []
        keys = []
        series = {}
        for page in pages:
            if not page.shape or product(page.shape) == 0:
                continue
            key = page.hash
            if key in series:
                series[key].append(page)
            else:
                keys.append(key)
                series[key] = [page]

        for key in keys:
            pages = series[key]
            page = pages[0]
            shape = page.shape
            axes = page.axes
            if len(pages) > 1:
                shape = (len(pages),) + shape
                axes = 'I' + axes
            result.append(TiffPageSeries(pages, shape, page.dtype, axes,
                                         kind='Generic'))

        self.is_uniform = len(result) == 1
        return result


Instruction:
How would you implement a function in Python 3 that
returns all images in file as single series.

Response:
def _series_uniform(self):
        """Return all images in file as single series."""
        page = self.pages[0]
        shape = page.shape
        axes = page.axes
        dtype = page.dtype
        validate = not (page.is_scanimage or page.is_nih)
        pages = self.pages._getlist(validate=validate)
        lenpages = len(pages)
        if lenpages > 1:
            shape = (lenpages,) + shape
            axes = 'I' + axes
        if page.is_scanimage:
            kind = 'ScanImage'
        elif page.is_nih:
            kind = 'NIHImage'
        else:
            kind = 'Uniform'
        return [TiffPageSeries(pages, shape, dtype, axes, kind=kind)]


Instruction:
Can you tell what is the following Python 3 function doing
def _series_shaped(self):
        pages = self.pages
        pages.useframes = True
        lenpages = len(pages)

        def append_series(series, pages, axes, shape, reshape, name,
                          truncated):
            page = pages[0]
            if not axes:
                shape = page.shape
                axes = page.axes
                if len(pages) > 1:
                    shape = (len(pages),) + shape
                    axes = 'Q' + axes
            size = product(shape)
            resize = product(reshape)
            if page.is_contiguous and resize > size and resize % size == 0:
                if truncated is None:
                    truncated = True
                axes = 'Q' + axes
                shape = (resize // size,) + shape
            try:
                axes = reshape_axes(axes, shape, reshape)
                shape = reshape
            except ValueError as exc:
                log.warning('Shaped series: %s: %s',
                            exc.__class__.__name__, exc)
            series.append(
                TiffPageSeries(pages, shape, page.dtype, axes, name=name,
                               kind='Shaped', truncated=truncated))

        keyframe = axes = shape = reshape = name = None
        series = []
        index = 0
        while True:
            if index >= lenpages:
                break
            # new keyframe; start of new series
            pages.keyframe = index
            keyframe = pages.keyframe
            if not keyframe.is_shaped:
                log.warning(
                    'Shaped series: invalid metadata or corrupted file')
                return None
            # read metadata
            axes = None
            shape = None
            metadata = json_description_metadata(keyframe.is_shaped)
            name = metadata.get('name', '')
            reshape = metadata['shape']
            truncated = metadata.get('truncated', None)
            if 'axes' in metadata:
                axes = metadata['axes']
                if len(axes) == len(reshape):
                    shape = reshape
                else:
                    axes = ''
                    log.warning('Shaped series: axes do not match shape')
            # skip pages if possible
            spages = [keyframe]
            size = product(reshape)
            npages, mod = divmod(size, product(keyframe.shape))
            if mod:
                log.warning(
                    'Shaped series: series shape does not match page shape')
                return None
            if 1 < npages <= lenpages - index:
                size *= keyframe._dtype.itemsize
                if truncated:
                    npages = 1
                elif (keyframe.is_final and
                      keyframe.offset + size < pages[index+1].offset):
                    truncated = False
                else:
                    # need to read all pages for series
                    truncated = False
                    for j in range(index+1, index+npages):
                        page = pages[j]
                        page.keyframe = keyframe
                        spages.append(page)
            append_series(series, spages, axes, shape, reshape, name,
                          truncated)
            index += npages

        self.is_uniform = len(series) == 1

        return series

Response: Return image series in shaped file.


Instruction:
Can you generate the documentation for the following Python 3 function
def _series_imagej(self):
        # ImageJ's dimension order is always TZCYXS
        # TODO: fix loading of color, composite, or palette images
        pages = self.pages
        pages.useframes = True
        pages.keyframe = 0
        page = pages[0]
        ij = self.imagej_metadata

        def is_hyperstack():
            # ImageJ hyperstack store all image metadata in the first page and
            # image data are stored contiguously before the second page, if any
            if not page.is_final:
                return False
            images = ij.get('images', 0)
            if images <= 1:
                return False
            offset, count = page.is_contiguous
            if (count != product(page.shape) * page.bitspersample // 8
                    or offset + count*images > self.filehandle.size):
                raise ValueError()
            # check that next page is stored after data
            if len(pages) > 1 and offset + count*images > pages[1].offset:
                return False
            return True

        try:
            hyperstack = is_hyperstack()
        except ValueError:
            log.warning('ImageJ series: invalid metadata or corrupted file')
            return None
        if hyperstack:
            # no need to read other pages
            pages = [page]
        else:
            pages = pages[:]

        shape = []
        axes = []
        if 'frames' in ij:
            shape.append(ij['frames'])
            axes.append('T')
        if 'slices' in ij:
            shape.append(ij['slices'])
            axes.append('Z')
        if 'channels' in ij and not (page.photometric == 2 and not
                                     ij.get('hyperstack', False)):
            shape.append(ij['channels'])
            axes.append('C')
        remain = ij.get('images', len(pages))//(product(shape) if shape else 1)
        if remain > 1:
            shape.append(remain)
            axes.append('I')
        if page.axes[0] == 'I':
            # contiguous multiple images
            shape.extend(page.shape[1:])
            axes.extend(page.axes[1:])
        elif page.axes[:2] == 'SI':
            # color-mapped contiguous multiple images
            shape = page.shape[0:1] + tuple(shape) + page.shape[2:]
            axes = list(page.axes[0]) + axes + list(page.axes[2:])
        else:
            shape.extend(page.shape)
            axes.extend(page.axes)

        truncated = (
            hyperstack and len(self.pages) == 1 and
            page.is_contiguous[1] != product(shape) * page.bitspersample // 8)

        self.is_uniform = True

        return [TiffPageSeries(pages, shape, page.dtype, axes, kind='ImageJ',
                               truncated=truncated)]

Response: Return image series in ImageJ file.


Instruction:
Can you implement a function in Python 3 that
returns image series in FluoView file.

Response:
def _series_fluoview(self):
        """Return image series in FluoView file."""
        pages = self.pages._getlist(validate=False)

        mm = self.fluoview_metadata
        mmhd = list(reversed(mm['Dimensions']))
        axes = ''.join(TIFF.MM_DIMENSIONS.get(i[0].upper(), 'Q')
                       for i in mmhd if i[1] > 1)
        shape = tuple(int(i[1]) for i in mmhd if i[1] > 1)
        self.is_uniform = True
        return [TiffPageSeries(pages, shape, pages[0].dtype, axes,
                               name=mm['ImageName'], kind='FluoView')]


Instruction:
Can you create a Python 3 function that
returns image series in MD Gel file.

Response:
def _series_mdgel(self):
        """Return image series in MD Gel file."""
        # only a single page, scaled according to metadata in second page
        self.pages.useframes = False
        self.pages.keyframe = 0
        md = self.mdgel_metadata
        if md['FileTag'] in (2, 128):
            dtype = numpy.dtype('float32')
            scale = md['ScalePixel']
            scale = scale[0] / scale[1]  # rational
            if md['FileTag'] == 2:
                # squary root data format
                def transform(a):
                    return a.astype('float32')**2 * scale
            else:
                def transform(a):
                    return a.astype('float32') * scale
        else:
            transform = None
        page = self.pages[0]
        self.is_uniform = False
        return [TiffPageSeries([page], page.shape, dtype, page.axes,
                               transform=transform, kind='MDGel')]


Instruction:
Make a summary of the following Python 3 code
def _series_sis(self):
        pages = self.pages._getlist(validate=False)
        page = pages[0]
        lenpages = len(pages)
        md = self.sis_metadata
        if 'shape' in md and 'axes' in md:
            shape = md['shape'] + page.shape
            axes = md['axes'] + page.axes
        elif lenpages == 1:
            shape = page.shape
            axes = page.axes
        else:
            shape = (lenpages,) + page.shape
            axes = 'I' + page.axes
        self.is_uniform = True
        return [TiffPageSeries(pages, shape, page.dtype, axes, kind='SIS')]

Response: Return image series in Olympus SIS file.


Instruction:
Here you have a function in Python 3, explain what it does
def _series_ome(self):
        from xml.etree import cElementTree as etree  # delayed import
        omexml = self.pages[0].description
        try:
            root = etree.fromstring(omexml)
        except etree.ParseError as exc:
            # TODO: test badly encoded OME-XML
            log.warning('OME series: %s: %s', exc.__class__.__name__, exc)
            try:
                # might work on Python 2
                omexml = omexml.decode('utf-8', 'ignore').encode('utf-8')
                root = etree.fromstring(omexml)
            except Exception:
                return None

        self.pages.cache = True
        self.pages.useframes = True
        self.pages.keyframe = 0
        self.pages._load(keyframe=None)

        uuid = root.attrib.get('UUID', None)
        self._files = {uuid: self}
        dirname = self._fh.dirname
        modulo = {}
        series = []
        for element in root:
            if element.tag.endswith('BinaryOnly'):
                # TODO: load OME-XML from master or companion file
                log.warning('OME series: not an ome-tiff master file')
                break
            if element.tag.endswith('StructuredAnnotations'):
                for annot in element:
                    if not annot.attrib.get('Namespace',
                                            '').endswith('modulo'):
                        continue
                    for value in annot:
                        for modul in value:
                            for along in modul:
                                if not along.tag[:-1].endswith('Along'):
                                    continue
                                axis = along.tag[-1]
                                newaxis = along.attrib.get('Type', 'other')
                                newaxis = TIFF.AXES_LABELS[newaxis]
                                if 'Start' in along.attrib:
                                    step = float(along.attrib.get('Step', 1))
                                    start = float(along.attrib['Start'])
                                    stop = float(along.attrib['End']) + step
                                    labels = numpy.arange(start, stop, step)
                                else:
                                    labels = [label.text for label in along
                                              if label.tag.endswith('Label')]
                                modulo[axis] = (newaxis, labels)

            if not element.tag.endswith('Image'):
                continue

            attr = element.attrib
            name = attr.get('Name', None)

            for pixels in element:
                if not pixels.tag.endswith('Pixels'):
                    continue
                attr = pixels.attrib
                # dtype = attr.get('PixelType', None)
                axes = ''.join(reversed(attr['DimensionOrder']))
                shape = idxshape = list(int(attr['Size'+ax]) for ax in axes)
                size = product(shape[:-2])
                ifds = None
                spp = 1  # samples per pixel
                for data in pixels:
                    if data.tag.endswith('Channel'):
                        attr = data.attrib
                        if ifds is None:
                            spp = int(attr.get('SamplesPerPixel', spp))
                            ifds = [None] * (size // spp)
                            if spp > 1:
                                # correct channel dimension for spp
                                idxshape = list((shape[i] // spp if ax == 'C'
                                                 else shape[i])
                                                for i, ax in enumerate(axes))
                        elif int(attr.get('SamplesPerPixel', 1)) != spp:
                            raise ValueError(
                                'cannot handle differing SamplesPerPixel')
                        continue
                    if ifds is None:
                        ifds = [None] * (size // spp)
                    if not data.tag.endswith('TiffData'):
                        continue
                    attr = data.attrib
                    ifd = int(attr.get('IFD', 0))
                    num = int(attr.get('NumPlanes', 1 if 'IFD' in attr else 0))
                    num = int(attr.get('PlaneCount', num))
                    idx = [int(attr.get('First'+ax, 0)) for ax in axes[:-2]]
                    try:
                        idx = numpy.ravel_multi_index(idx, idxshape[:-2])
                    except ValueError:
                        # ImageJ produces invalid ome-xml when cropping
                        log.warning('OME series: invalid TiffData index')
                        continue
                    for uuid in data:
                        if not uuid.tag.endswith('UUID'):
                            continue
                        if uuid.text not in self._files:
                            if not self._multifile:
                                # abort reading multifile OME series
                                # and fall back to generic series
                                return []
                            fname = uuid.attrib['FileName']
                            try:
                                tif = TiffFile(os.path.join(dirname, fname))
                                tif.pages.cache = True
                                tif.pages.useframes = True
                                tif.pages.keyframe = 0
                                tif.pages._load(keyframe=None)
                            except (IOError, FileNotFoundError, ValueError):
                                log.warning("OME series: failed to read '%s'",
                                            fname)
                                break
                            self._files[uuid.text] = tif
                            tif.close()
                        pages = self._files[uuid.text].pages
                        try:
                            for i in range(num if num else len(pages)):
                                ifds[idx + i] = pages[ifd + i]
                        except IndexError:
                            log.warning('OME series: index out of range')
                        # only process first UUID
                        break
                    else:
                        pages = self.pages
                        try:
                            for i in range(num if num else
                                           min(len(pages), len(ifds))):
                                ifds[idx + i] = pages[ifd + i]
                        except IndexError:
                            log.warning('OME series: index out of range')

                if all(i is None for i in ifds):
                    # skip images without data
                    continue

                # find a keyframe
                keyframe = None
                for i in ifds:
                    # try find a TiffPage
                    if i and i == i.keyframe:
                        keyframe = i
                        break
                if keyframe is None:
                    # reload a TiffPage from file
                    for i, keyframe in enumerate(ifds):
                        if keyframe:
                            keyframe.parent.pages.keyframe = keyframe.index
                            keyframe = keyframe.parent.pages[keyframe.index]
                            ifds[i] = keyframe
                            break

                # move channel axis to match PlanarConfiguration storage
                # TODO: is this a bug or a inconsistency in the OME spec?
                if spp > 1:
                    if keyframe.planarconfig == 1 and axes[-1] != 'C':
                        i = axes.index('C')
                        axes = axes[:i] + axes[i+1:] + axes[i:i+1]
                        shape = shape[:i] + shape[i+1:] + shape[i:i+1]

                # FIXME: this implementation assumes the last dimensions are
                # stored in TIFF pages. Apparently that is not always the case.
                # For now, verify that shapes of keyframe and series match
                # If not, skip series.
                if keyframe.shape != tuple(shape[-len(keyframe.shape):]):
                    log.warning('OME series: incompatible page shape %s; '
                                'expected %s', keyframe.shape,
                                tuple(shape[-len(keyframe.shape):]))
                    del ifds
                    continue

                # set a keyframe on all IFDs
                for i in ifds:
                    if i is not None:
                        i.keyframe = keyframe

                series.append(
                    TiffPageSeries(ifds, shape, keyframe.dtype, axes,
                                   parent=self, name=name, kind='OME'))
                del ifds

        for serie in series:
            shape = list(serie.shape)
            for axis, (newaxis, labels) in modulo.items():
                i = serie.axes.index(axis)
                size = len(labels)
                if shape[i] == size:
                    serie.axes = serie.axes.replace(axis, newaxis, 1)
                else:
                    shape[i] //= size
                    shape.insert(i+1, size)
                    serie.axes = serie.axes.replace(axis, axis+newaxis, 1)
            serie.shape = tuple(shape)

        # squeeze dimensions
        for serie in series:
            serie.shape, serie.axes = squeeze_axes(serie.shape, serie.axes)
        self.is_uniform = len(series) == 1
        return series

Response: Return image series in OME - TIFF file ( s ).


Instruction:
Write a Python 3 script to
return main and thumbnail series in LSM file.

Response:
def _series_lsm(self):
        """Return main and thumbnail series in LSM file."""
        lsmi = self.lsm_metadata
        axes = TIFF.CZ_LSMINFO_SCANTYPE[lsmi['ScanType']]
        if self.pages[0].photometric == 2:  # RGB; more than one channel
            axes = axes.replace('C', '').replace('XY', 'XYC')
        if lsmi.get('DimensionP', 0) > 1:
            axes += 'P'
        if lsmi.get('DimensionM', 0) > 1:
            axes += 'M'
        axes = axes[::-1]
        shape = tuple(int(lsmi[TIFF.CZ_LSMINFO_DIMENSIONS[i]]) for i in axes)
        name = lsmi.get('Name', '')
        pages = self.pages._getlist(slice(0, None, 2), validate=False)
        dtype = pages[0].dtype
        series = [TiffPageSeries(pages, shape, dtype, axes, name=name,
                                 kind='LSM')]

        if self.pages[1].is_reduced:
            pages = self.pages._getlist(slice(1, None, 2), validate=False)
            dtype = pages[0].dtype
            cp = 1
            i = 0
            while cp < len(pages) and i < len(shape)-2:
                cp *= shape[i]
                i += 1
            shape = shape[:i] + pages[0].shape
            axes = axes[:i] + 'CYX'
            series.append(TiffPageSeries(pages, shape, dtype, axes, name=name,
                                         kind='LSMreduced'))

        self.is_uniform = False
        return series


Instruction:
How would you explain what the following Python 3 function does
def _lsm_load_pages(self):
        # cache all pages to preserve corrected values
        pages = self.pages
        pages.cache = True
        pages.useframes = True
        # use first and second page as keyframes
        pages.keyframe = 1
        pages.keyframe = 0
        # load remaining pages as frames
        pages._load(keyframe=None)
        # fix offsets and bytecounts first
        self._lsm_fix_strip_offsets()
        self._lsm_fix_strip_bytecounts()
        # assign keyframes for data and thumbnail series
        keyframe = pages[0]
        for page in pages[::2]:
            page.keyframe = keyframe
        keyframe = pages[1]
        for page in pages[1::2]:
            page.keyframe = keyframe

Response: Load and fix all pages from LSM file.


Instruction:
Make a summary of the following Python 3 code
def _lsm_fix_strip_offsets(self):
        if self.filehandle.size < 2**32:
            return

        pages = self.pages
        npages = len(pages)
        series = self.series[0]
        axes = series.axes

        # find positions
        positions = 1
        for i in 0, 1:
            if series.axes[i] in 'PM':
                positions *= series.shape[i]

        # make time axis first
        if positions > 1:
            ntimes = 0
            for i in 1, 2:
                if axes[i] == 'T':
                    ntimes = series.shape[i]
                    break
            if ntimes:
                div, mod = divmod(npages, 2*positions*ntimes)
                assert mod == 0
                shape = (positions, ntimes, div, 2)
                indices = numpy.arange(product(shape)).reshape(shape)
                indices = numpy.moveaxis(indices, 1, 0)
        else:
            indices = numpy.arange(npages).reshape(-1, 2)

        # images of reduced page might be stored first
        if pages[0]._offsetscounts[0][0] > pages[1]._offsetscounts[0][0]:
            indices = indices[..., ::-1]

        # unwrap offsets
        wrap = 0
        previousoffset = 0
        for i in indices.flat:
            page = pages[int(i)]
            dataoffsets = []
            for currentoffset in page._offsetscounts[0]:
                if currentoffset < previousoffset:
                    wrap += 2**32
                dataoffsets.append(currentoffset + wrap)
                previousoffset = currentoffset
            page._offsetscounts = dataoffsets, page._offsetscounts[1]

Response: Unwrap strip offsets for LSM files greater than 4 GB.


Instruction:
Implement a function in Python 3 to
fix the bytecounts of compressed data in LSM files.

Response:
def _lsm_fix_strip_bytecounts(self):
        """Set databytecounts to size of compressed data.

        The StripByteCounts tag in LSM files contains the number of bytes
        for the uncompressed data.

        """
        pages = self.pages
        if pages[0].compression == 1:
            return
        # sort pages by first strip offset
        pages = sorted(pages, key=lambda p: p._offsetscounts[0][0])
        npages = len(pages) - 1
        for i, page in enumerate(pages):
            if page.index % 2:
                continue
            offsets, bytecounts = page._offsetscounts
            if i < npages:
                lastoffset = pages[i+1]._offsetscounts[0][0]
            else:
                # LZW compressed strips might be longer than uncompressed
                lastoffset = min(offsets[-1] + 2*bytecounts[-1], self._fh.size)
            for j in range(len(bytecounts) - 1):
                bytecounts[j] = offsets[j+1] - offsets[j]
            bytecounts[-1] = lastoffset - offsets[-1]


Instruction:
Create a Python 3 function to
check if the file has MD Gel format.

Response:
def is_mdgel(self):
        """File has MD Gel format."""
        # TODO: this likely reads the second page from file
        try:
            ismdgel = self.pages[0].is_mdgel or self.pages[1].is_mdgel
            if ismdgel:
                self.is_uniform = False
            return ismdgel
        except IndexError:
            return False


Instruction:
Implement a function in Python 3 to
return if file contains a uniform series of pages.

Response:
def is_uniform(self):
        """Return if file contains a uniform series of pages."""
        # the hashes of IFDs 0, 7, and -1 are the same
        pages = self.pages
        page = pages[0]
        if page.is_scanimage or page.is_nih:
            return True
        try:
            useframes = pages.useframes
            pages.useframes = False
            h = page.hash
            for i in (1, 7, -1):
                if pages[i].aspage().hash != h:
                    return False
        except IndexError:
            return False
        finally:
            pages.useframes = useframes
        return True


Instruction:
How would you explain what the following Python 3 function does
def is_appendable(self):
        # TODO: check other formats
        return not (self.is_lsm or self.is_stk or self.is_imagej or
                    self.is_fluoview or self.is_micromanager)

Response: Return if pages can be appended to file without corrupting.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def shaped_metadata(self):
        if not self.is_shaped:
            return None
        return tuple(json_description_metadata(s.pages[0].is_shaped)
                     for s in self.series if s.kind.lower() == 'shaped')

Response: Return tifffile metadata from JSON descriptions as dicts.


Instruction:
Make a summary of the following Python 3 code
def stk_metadata(self):
        if not self.is_stk:
            return None
        page = self.pages[0]
        tags = page.tags
        result = {}
        result['NumberPlanes'] = tags['UIC2tag'].count
        if page.description:
            result['PlaneDescriptions'] = page.description.split('\0')
            # result['plane_descriptions'] = stk_description_metadata(
            #    page.image_description)
        if 'UIC1tag' in tags:
            result.update(tags['UIC1tag'].value)
        if 'UIC3tag' in tags:
            result.update(tags['UIC3tag'].value)  # wavelengths
        if 'UIC4tag' in tags:
            result.update(tags['UIC4tag'].value)  # override uic1 tags
        uic2tag = tags['UIC2tag'].value
        result['ZDistance'] = uic2tag['ZDistance']
        result['TimeCreated'] = uic2tag['TimeCreated']
        result['TimeModified'] = uic2tag['TimeModified']
        try:
            result['DatetimeCreated'] = numpy.array(
                [julian_datetime(*dt) for dt in
                 zip(uic2tag['DateCreated'], uic2tag['TimeCreated'])],
                dtype='datetime64[ns]')
            result['DatetimeModified'] = numpy.array(
                [julian_datetime(*dt) for dt in
                 zip(uic2tag['DateModified'], uic2tag['TimeModified'])],
                dtype='datetime64[ns]')
        except ValueError as exc:
            log.warning('STK metadata: %s: %s', exc.__class__.__name__, exc)
        return result

Response: Return STK metadata from UIC tags as dict.


Instruction:
Implement a Python 3 function for
returning consolidated ImageJ metadata as dict.

Response:
def imagej_metadata(self):
        """Return consolidated ImageJ metadata as dict."""
        if not self.is_imagej:
            return None
        page = self.pages[0]
        result = imagej_description_metadata(page.is_imagej)
        if 'IJMetadata' in page.tags:
            try:
                result.update(page.tags['IJMetadata'].value)
            except Exception:
                pass
        return result


Instruction:
How would you explain what the following Python 3 function does
def fluoview_metadata(self):
        if not self.is_fluoview:
            return None
        result = {}
        page = self.pages[0]
        result.update(page.tags['MM_Header'].value)
        # TODO: read stamps from all pages
        result['Stamp'] = page.tags['MM_Stamp'].value
        # skip parsing image description; not reliable
        # try:
        #     t = fluoview_description_metadata(page.image_description)
        #     if t is not None:
        #         result['ImageDescription'] = t
        # except Exception as exc:
        #     log.warning('FluoView metadata: '
        #                 'failed to parse image description (%s)', str(exc))
        return result

Response: Return consolidated FluoView metadata as dict.


Instruction:
Write a Python 3 function for
returning FEI metadata from SFEG or HELIOS tags as dict.

Response:
def fei_metadata(self):
        """Return FEI metadata from SFEG or HELIOS tags as dict."""
        if not self.is_fei:
            return None
        tags = self.pages[0].tags
        if 'FEI_SFEG' in tags:
            return tags['FEI_SFEG'].value
        if 'FEI_HELIOS' in tags:
            return tags['FEI_HELIOS'].value
        return None


Instruction:
How would you explain what the following Python 3 function does
def sis_metadata(self):
        if not self.is_sis:
            return None
        tags = self.pages[0].tags
        result = {}
        try:
            result.update(tags['OlympusINI'].value)
        except Exception:
            pass
        try:
            result.update(tags['OlympusSIS'].value)
        except Exception:
            pass
        return result

Response: Return Olympus SIS metadata from SIS and INI tags as dict.


Instruction:
Given the following Python 3 function, write the documentation
def mdgel_metadata(self):
        for page in self.pages[:2]:
            if 'MDFileTag' in page.tags:
                tags = page.tags
                break
        else:
            return None
        result = {}
        for code in range(33445, 33453):
            name = TIFF.TAGS[code]
            if name not in tags:
                continue
            result[name[2:]] = tags[name].value
        return result

Response: Return consolidated metadata from MD GEL tags as dict.


Instruction:
Implement a Python 3 function for
returning consolidated MicroManager metadata as dict.

Response:
def micromanager_metadata(self):
        """Return consolidated MicroManager metadata as dict."""
        if not self.is_micromanager:
            return None
        # from file header
        result = read_micromanager_metadata(self._fh)
        # from tag
        result.update(self.pages[0].tags['MicroManagerMetadata'].value)
        return result


Instruction:
How would you code a function in Python 3 to
return ScanImage non - varying frame and ROI metadata as dict.

Response:
def scanimage_metadata(self):
        """Return ScanImage non-varying frame and ROI metadata as dict."""
        if not self.is_scanimage:
            return None
        result = {}
        try:
            framedata, roidata = read_scanimage_metadata(self._fh)
            result['FrameData'] = framedata
            result.update(roidata)
        except ValueError:
            pass
        # TODO: scanimage_artist_metadata
        try:
            result['Description'] = scanimage_description_metadata(
                self.pages[0].description)
        except Exception as exc:
            log.warning('ScanImage metadata: %s: %s',
                        exc.__class__.__name__, exc)
        return result


Instruction:
Create a Python 3 function for
enabling or disable caching of pages or frames. Clear cache if False.

Response:
def cache(self, value):
        """Enable or disable caching of pages/frames. Clear cache if False."""
        value = bool(value)
        if self._cache and not value:
            self._clear()
        self._cache = value


Instruction:
Here you have a function in Python 3, explain what it does
def keyframe(self, index):
        index = int(index)
        if index < 0:
            index %= len(self)
        if self._keyframe.index == index:
            return
        if index == 0:
            self._keyframe = self.pages[0]
            return
        if self._indexed or index < len(self.pages):
            page = self.pages[index]
            if isinstance(page, TiffPage):
                self._keyframe = page
                return
            if isinstance(page, TiffFrame):
                # remove existing TiffFrame
                self.pages[index] = page.offset
        # load TiffPage from file
        tiffpage = self._tiffpage
        self._tiffpage = TiffPage
        try:
            self._keyframe = self._getitem(index)
        finally:
            self._tiffpage = tiffpage
        # always cache keyframes
        self.pages[index] = self._keyframe

Response: Set current keyframe. Load TiffPage from file if necessary.


Instruction:
Create a Python 3 function for
reading all remaining pages from file.

Response:
def _load(self, keyframe=True):
        """Read all remaining pages from file."""
        if self._cached:
            return
        pages = self.pages
        if not pages:
            return
        if not self._indexed:
            self._seek(-1)
        if not self._cache:
            return
        fh = self.parent.filehandle
        if keyframe is not None:
            keyframe = self._keyframe
        for i, page in enumerate(pages):
            if isinstance(page, inttypes):
                fh.seek(page)
                page = self._tiffpage(self.parent, index=i, keyframe=keyframe)
                pages[i] = page
        self._cached = True


Instruction:
Make a summary of the following Python 3 code
def _clear(self, fully=True):
        pages = self.pages
        if not pages:
            return
        self._keyframe = pages[0]
        if fully:
            # delete all but first TiffPage/TiffFrame
            for i, page in enumerate(pages[1:]):
                if not isinstance(page, inttypes) and page.offset is not None:
                    pages[i+1] = page.offset
        elif TiffFrame is not TiffPage:
            # delete only TiffFrames
            for i, page in enumerate(pages):
                if isinstance(page, TiffFrame) and page.offset is not None:
                    pages[i] = page.offset
        self._cached = False

Response: Delete all but first page from cache. Set keyframe to first page.


Instruction:
Implement a function in Python 3 to
seek file to offset of page specified by index.

Response:
def _seek(self, index, maxpages=None):
        """Seek file to offset of page specified by index."""
        pages = self.pages
        lenpages = len(pages)
        if lenpages == 0:
            raise IndexError('index out of range')

        fh = self.parent.filehandle
        if fh.closed:
            raise ValueError('seek of closed file')

        if self._indexed or 0 <= index < lenpages:
            page = pages[index]
            offset = page if isinstance(page, inttypes) else page.offset
            fh.seek(offset)
            return

        tiff = self.parent.tiff
        offsetformat = tiff.ifdoffsetformat
        offsetsize = tiff.ifdoffsetsize
        tagnoformat = tiff.tagnoformat
        tagnosize = tiff.tagnosize
        tagsize = tiff.tagsize
        unpack = struct.unpack

        page = pages[-1]
        offset = page if isinstance(page, inttypes) else page.offset

        if maxpages is None:
            maxpages = 2**22
        while lenpages < maxpages:
            # read offsets to pages from file until index is reached
            fh.seek(offset)
            # skip tags
            try:
                tagno = unpack(tagnoformat, fh.read(tagnosize))[0]
                if tagno > 4096:
                    raise TiffFileError(
                        'suspicious number of tags: %i' % tagno)
            except Exception:
                log.warning('TiffPages: corrupted tag list of page %i @ %i',
                            lenpages, offset)
                del pages[-1]
                lenpages -= 1
                self._indexed = True
                break
            self._nextpageoffset = offset + tagnosize + tagno * tagsize
            fh.seek(self._nextpageoffset)

            # read offset to next page
            offset = unpack(offsetformat, fh.read(offsetsize))[0]
            if offset == 0:
                self._indexed = True
                break
            if offset >= fh.size:
                log.warning('TiffPages: invalid page offset (%i)', offset)
                self._indexed = True
                break

            pages.append(offset)
            lenpages += 1
            if 0 <= index < lenpages:
                break

            # detect some circular references
            if lenpages == 100:
                for p in pages[:-1]:
                    if offset == (p if isinstance(p, inttypes) else p.offset):
                        raise TiffFileError('invalid circular IFD reference')

        if index >= lenpages:
            raise IndexError('index out of range')

        page = pages[index]
        fh.seek(page if isinstance(page, inttypes) else page.offset)


Instruction:
Can you tell what is the following Python 3 function doing
def _getlist(self, key=None, useframes=True, validate=True):
        getitem = self._getitem
        _useframes = self.useframes

        if key is None:
            key = iter(range(len(self)))
        elif isinstance(key, Iterable):
            key = iter(key)
        elif isinstance(key, slice):
            start, stop, _ = key.indices(2**31-1)
            if not self._indexed and max(stop, start) > len(self.pages):
                self._seek(-1)
            key = iter(range(*key.indices(len(self.pages))))
        elif isinstance(key, inttypes):
            # return single TiffPage
            self.useframes = False
            if key == 0:
                return [self.pages[key]]
            try:
                return [getitem(key)]
            finally:
                self.useframes = _useframes
        else:
            raise TypeError('key must be an integer, slice, or iterable')

        # use first page as keyframe
        keyframe = self._keyframe
        self.keyframe = next(key)
        if validate:
            validate = self._keyframe.hash
        if useframes:
            self.useframes = True
        try:
            pages = [getitem(i, validate) for i in key]
            pages.insert(0, self._keyframe)
        finally:
            # restore state
            self._keyframe = keyframe
            if useframes:
                self.useframes = _useframes

        return pages

Response: Return specified pages as list of TiffPages or TiffFrames.


Instruction:
Can you generate the documentation for the following Python 3 function
def _getitem(self, key, validate=False):
        key = int(key)
        pages = self.pages

        if key < 0:
            key %= len(self)
        elif self._indexed and key >= len(pages):
            raise IndexError('index out of range')

        if key < len(pages):
            page = pages[key]
            if self._cache:
                if not isinstance(page, inttypes):
                    if validate and validate != page.hash:
                        raise RuntimeError('page hash mismatch')
                    return page
            elif isinstance(page, (TiffPage, self._tiffpage)):
                if validate and validate != page.hash:
                    raise RuntimeError('page hash mismatch')
                return page

        self._seek(key)
        page = self._tiffpage(self.parent, index=key, keyframe=self._keyframe)
        if validate and validate != page.hash:
            raise RuntimeError('page hash mismatch')
        if self._cache:
            pages[key] = page
        return page

Response: Return specified page from cache or file.