<commit_before>import logging
import os.path
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import pandas as pd
import seaborn as sns

from mpl_toolkits.mplot3d import Axes3D
from skimage import io, transform

from mia.utils import transform_2d

logger = logging.getLogger(__name__)


def plot_multiple_images(images):
    """Plot a list of images on horizontal subplots

    :param images: the list of images to plot
    """
    fig = plt.figure()

    num_images = len(images)
    for i, image in enumerate(images):
        fig.add_subplot(1, num_images, i+1)
        plt.imshow(image, cmap=cm.Greys_r)

    plt.show()


def plot_region_props(image, regions):
    """Plot the output of skimage.regionprops along with the image.

    Original code from
    http://scikit-image.org/docs/dev/auto_examples/plot_regionprops.html

    :param image: image to plot
    :param regions: the regions output from the regionprops function
    """
    fig, ax = plt.subplots()
    ax.imshow(image, cmap=plt.cm.gray)

    for props in regions:
        minr, minc, maxr, maxc = props
        bx = (minc, maxc, maxc, minc, minc)
        by = (minr, minr, maxr, maxr, minr)
        ax.plot(bx, by, '-b', linewidth=2.5)

    plt.show()


def plot_linear_structure(img, line_image):
    """Plot the line image generated from linear structure detection

    :param img: the image that structure was detected in
    :param line_image: the line image generated from img
    """
    line_image = np.ma.masked_where(line_image == 0, line_image)
    fig, ax = plt.subplots()
    ax.imshow(img, interpolation='nearest', cmap=plt.cm.gray)
    ax.imshow(line_image, cmap=plt.cm.autumn)
    plt.show()


def plot_blobs(img, blobs):
    """Plot the output of blob detection on an image.

    :param img: the image to plot
    :param blobs: list of blobs found in the image
    """

    fig, ax = plt.subplots(1, 1)
    ax.imshow(img, interpolation='nearest', cmap=plt.cm.gray)
    ax.set_axis_off()

    for blob in blobs:
        y, x, r = blob
        c = plt.Circle((x, y), r, color='red', linewidth=2, fill=False)
        ax.add_patch(c)

    plt.show()


def plot_image_orthotope(image_orthotope, titles=None):
    """ Plot an image orthotope

    :param image_orthotope: the orthotope of images to plot
    :param titles: titles for each of the images in orthotope
    """

    fig, ax = plt.subplots(*image_orthotope.shape[:2])

    if titles is not None:
        title_iter = titles.__iter__()

    for i in range(image_orthotope.shape[0]):
        for j in range(image_orthotope.shape[1]):
            if titles is not None:
                ax[i][j].set_title(title_iter.next())

            ax[i][j].imshow(image_orthotope[i][j], cmap=plt.cm.gray)
            ax[i][j].axis('off')

    plt.show()


def plot_risk_classes(data_frame, column_name):
    """ Plot a histogram of the selected column for each risk class

    :param data_frame: the data frame containing the features
    :param column_name: the column to use
    """
    groups = data_frame.groupby('class')

    fig, axs = plt.subplots(2, 2)

    axs = axs.flatten()
    for i, (index, frame) in enumerate(groups):
        frame.hist(column=column_name, ax=axs[i])

        axs[i].set_title("Risk %d" % (index))
        axs[i].set_xlabel(column_name)
        axs[i].set_ylabel('count')

    plt.subplots_adjust(wspace=0.75, hspace=0.75)


def plot_risk_classes_single(data_frame, column_name):
    """ Plot a histogram of the selected column for each risk class as a single
    histogram

    This is essentially the same as the plot_risk_classes function except that
    the all risk classes are plotted in the same subplot.

    :param data_frame: the data frame containing the features
    :param column_name: the column to use
    """
    blobs = data_frame.groupby('class')
    for index, b in blobs:
        b[column_name].hist(label=str(index))

    plt.legend(loc='upper right')


def plot_scatter_2d(data_frame, columns, labels=None, annotate=False, **kwargs):
    """ Create a scatter plot from a pandas data frame

    :param data_frame: data frame containing the data to plot
    :param columns: the columns to use for each axis. Must be exactly 2
    :param label_name: name of the column containing the class label for the
                       image
    :param annotate: whether to annotate the plot with the index
    """
    if len(columns) != 2:
        raise ValueError("Number of columns must be exactly 2")

    ax = data_frame.plot(kind='scatter', x=columns[0], y=columns[1],
                         c=labels, cmap=plt.cm.Spectral_r, **kwargs)

    if annotate:
        def annotate_df(row):
            ax.text(row.values[0], row.values[1], row.name, fontsize=10)
        data_frame.apply(annotate_df, axis=1)

    return ax


def plot_scatter_3d(data_frame, columns, labels=None):
    """ Create a 3D scatter plot from a pandas data frame

    :param data_frame: data frame containing the data to plot<commit_msg>Remove PEP8 warning.<commit_after>import logging
import os.path
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import pandas as pd
import seaborn as sns

from mpl_toolkits.mplot3d import Axes3D
from skimage import io, transform

from mia.utils import transform_2d

logger = logging.getLogger(__name__)


def plot_multiple_images(images):
    """Plot a list of images on horizontal subplots

    :param images: the list of images to plot
    """
    fig = plt.figure()

    num_images = len(images)
    for i, image in enumerate(images):
        fig.add_subplot(1, num_images, i+1)
        plt.imshow(image, cmap=cm.Greys_r)

    plt.show()


def plot_region_props(image, regions):
    """Plot the output of skimage.regionprops along with the image.

    Original code from
    http://scikit-image.org/docs/dev/auto_examples/plot_regionprops.html

    :param image: image to plot
    :param regions: the regions output from the regionprops function
    """
    fig, ax = plt.subplots()
    ax.imshow(image, cmap=plt.cm.gray)

    for props in regions:
        minr, minc, maxr, maxc = props
        bx = (minc, maxc, maxc, minc, minc)
        by = (minr, minr, maxr, maxr, minr)
        ax.plot(bx, by, '-b', linewidth=2.5)

    plt.show()


def plot_linear_structure(img, line_image):
    """Plot the line image generated from linear structure detection

    :param img: the image that structure was detected in
    :param line_image: the line image generated from img
    """
    line_image = np.ma.masked_where(line_image == 0, line_image)
    fig, ax = plt.subplots()
    ax.imshow(img, interpolation='nearest', cmap=plt.cm.gray)
    ax.imshow(line_image, cmap=plt.cm.autumn)
    plt.show()


def plot_blobs(img, blobs):
    """Plot the output of blob detection on an image.

    :param img: the image to plot
    :param blobs: list of blobs found in the image
    """

    fig, ax = plt.subplots(1, 1)
    ax.imshow(img, interpolation='nearest', cmap=plt.cm.gray)
    ax.set_axis_off()

    for blob in blobs:
        y, x, r = blob
        c = plt.Circle((x, y), r, color='red', linewidth=2, fill=False)
        ax.add_patch(c)

    plt.show()


def plot_image_orthotope(image_orthotope, titles=None):
    """ Plot an image orthotope

    :param image_orthotope: the orthotope of images to plot
    :param titles: titles for each of the images in orthotope
    """

    fig, ax = plt.subplots(*image_orthotope.shape[:2])

    if titles is not None:
        title_iter = titles.__iter__()

    for i in range(image_orthotope.shape[0]):
        for j in range(image_orthotope.shape[1]):
            if titles is not None:
                ax[i][j].set_title(title_iter.next())

            ax[i][j].imshow(image_orthotope[i][j], cmap=plt.cm.gray)
            ax[i][j].axis('off')

    plt.show()


def plot_risk_classes(data_frame, column_name):
    """ Plot a histogram of the selected column for each risk class

    :param data_frame: the data frame containing the features
    :param column_name: the column to use
    """
    groups = data_frame.groupby('class')

    fig, axs = plt.subplots(2, 2)

    axs = axs.flatten()
    for i, (index, frame) in enumerate(groups):
        frame.hist(column=column_name, ax=axs[i])

        axs[i].set_title("Risk %d" % (index))
        axs[i].set_xlabel(column_name)
        axs[i].set_ylabel('count')

    plt.subplots_adjust(wspace=0.75, hspace=0.75)


def plot_risk_classes_single(data_frame, column_name):
    """ Plot a histogram of the selected column for each risk class as a single
    histogram

    This is essentially the same as the plot_risk_classes function except that
    the all risk classes are plotted in the same subplot.

    :param data_frame: the data frame containing the features
    :param column_name: the column to use
    """
    blobs = data_frame.groupby('class')
    for index, b in blobs:
        b[column_name].hist(label=str(index))

    plt.legend(loc='upper right')


def plot_scatter_2d(data_frame, columns, labels=None, annotate=False,
                    **kwargs):
    """ Create a scatter plot from a pandas data frame

    :param data_frame: data frame containing the data to plot
    :param columns: the columns to use for each axis. Must be exactly 2
    :param label_name: name of the column containing the class label for the
                       image
    :param annotate: whether to annotate the plot with the index
    """
    if len(columns) != 2:
        raise ValueError("Number of columns must be exactly 2")

    ax = data_frame.plot(kind='scatter', x=columns[0], y=columns[1],
                         c=labels, cmap=plt.cm.Spectral_r, **kwargs)

    if annotate:
        def annotate_df(row):
            ax.text(row.values[0], row.values[1], row.name, fontsize=10)
        data_frame.apply(annotate_df, axis=1)

    return ax


def plot_scatter_3d(data_frame, columns, labels=None):
    """ Create a 3D scatter plot from a pandas data frame

    :param data_frame: data frame containing the data to plot
{'fraction_non_alphanumeric': 0.1027349577324714, 'fraction_numerical': 0.007061163600198906, 'mean_word_length': 3.0256204963971176, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1027890', 'n_tokens_mistral': 3388, 'n_tokens_neox': 3212, 'n_words': 1015}