[docs]defanndata_to_image_array(adata:AnnData,layer:Optional[str]=None)->np.ndarray:""" Extracts an array of ion images from an AnnData object (that has been generated through the ``metaspace_to_anndata`` function). Args: adata: An AnnData object. layer: ``AnnData.layer`` that should be extracted to an image array. Default is None, which means that ``adata.X`` will be used. Returns: A three-dimensional Numpy array in the following shape * Dimension 0: Number of ion images in the order of ``adata.var_names`` * Dimension 1: Image height ``adata.uns["metaspace"]["image_size"]["y"]`` * Dimension 2: Image width ``adata.uns["metaspace"]["image_size"]["x"]`` Raises: ValueError: If the AnnData object has been modified. E.g. Pixel have been removed/added and the number of pixels and their coordinates do not match the original image dimensions. """iflayerisNone:pixel_array=np.array(adata.X).transpose().copy()eliflayerinadata.layers.keys():pixel_array=np.array(adata.layers[layer]).transpose().copy()else:raiseValueError(f"Layer `{layer}` not found in adata.layers.")img_size=adata.uns[METASPACE_KEY]["image_size"]# Check if image dimensions are okayifimg_size[X]*img_size[Y]!=pixel_array.shape[1]:raiseValueError("Number of observations does not match the original image dimensions")# Check if all pixels are availableifnot_check_pixel_coordinates(adata):raiseValueError("Not all pixels for ion images are available")# Sort indices, in case of modified order of pixels (obs)image_sorting=adata.obs.sort_values([COL.ion_image_pixel_y,COL.ion_image_pixel_x]).index.values.astype(int)pixel_array=pixel_array[:,image_sorting]image_array=pixel_array.reshape((pixel_array.shape[0],adata.obs[COL.ion_image_pixel_y].max()+1,adata.obs[COL.ion_image_pixel_x].max()+1,))returnimage_array