Beispiel #1
0
def construct_ax(figsize=(10, 10), despine=True):
    """
    Construct a new pyplot fig, ax object pair and despine.

    Parameters
    ----------
    figsize : tuple of floats
        figure size for pyplot.plot.subplots call
    despine : bool (default True)
        whether or not to remove axes and spines

    Returns
    -------
    fig,ax : tuple
        fig, ax pair generated by pyplot.subplots
    """

    # Check sanity of figsize
    try:
        if len(figsize) != 2:
            raise TypeError
        for v in figsize:
            check.float_sanity(v, min_allowed=0)
    except (TypeError, ValueError):
        err = "figsize should be a length 2 tuple of floats. See documentation\n"
        err += "on matplotlib.pyplot.subplots"
        raise ValueError(err)

    fig, ax = plt.subplots(figsize=figsize)

    if despine:
        ax = despine_ax(ax)

    return fig, ax
Beispiel #2
0
def _parse_add_sizemap(data_column, vmin, vmax, size_min, size_max, df,
                       df_name):
    """
    Do standard checking and format selection for adding sizemap, either for
    nodes or edges.

    Parameters
    ----------
    data_column : str
        name of data column
    vmin, vmax : float, float
        minimum and maximum data values
    size_min, size_max, float, float
        minimum and maximum size values
    df : pandas DataFrame
        data frame to look for column in
    df_name : str
        name of dataframe for errors

    Returns
    -------
    "_gpm" : str
        indicates this should be interpreted in a special way by gpmap
    data_column : str
    vmin, vmax : float, float
    size_min, size_max : float, float
    """
    # Make sure the data column exists
    try:
        v = df.loc[:, data_column]
    except KeyError:
        err = f"GenotypePhenotypeMap {df_name} dataframe does not have column\n"
        err += f"'{data_column}'\n"
        raise KeyError(err)

    # Deal with minimum and maximum for color map
    if vmin is None:
        vmin = np.nanmin(v)
    if vmax is None:
        vmax = np.nanmax(v)

    # Check sanity of inputs
    check.float_sanity(vmin)
    check.float_sanity(vmax)
    check.float_sanity(size_min)
    check.float_sanity(size_max)

    # Make sure vmin <= than vmax
    if vmin > vmax:
        err = f"vmax ({vmax}) must be >= than vmin ({vmin})\n"
        raise ValueError(err)

    # make sure size_min is <= size_max
    if size_min > size_max:
        err = f"size_max ({size_max}) must be >= size_min ({size_min})\n"
        raise ValueError(err)

    # make sure size_min and size_max are both >= 0
    if size_min < 0 or size_max < 0:
        err = f"size_max ({size_max}) and size_min ({size_min}) must be >= 0\n"
        raise ValueError(err)

    return "_gpm", data_column, vmin, vmax, size_min, size_max
Beispiel #3
0
def test_float_sanity():
    """
    Test float sanity checker.
    """

    with pytest.raises(ValueError):
        check.int_sanity("stupid")

    with pytest.raises(ValueError):
        check.float_sanity([])

    # should not throw error
    check.float_sanity(11234521)
    check.float_sanity(1.0)
    check.float_sanity(-1)

    with pytest.raises(ValueError):
        check.float_sanity(0,min_allowed=0)
    check.float_sanity(100,min_allowed=0)

    with pytest.raises(ValueError):
        check.float_sanity(10,max_allowed=0)
    check.float_sanity(10,max_allowed=100)
Beispiel #4
0
def _parse_add_cmap(data_column, cmap, vmin, vmax, df, df_name):
    """
    Do standard checking and format selection for adding sizemap, either for
    nodes or edges.

    Parameters
    ----------
    data_column : str
        name of data column
    cmap : str or matplotlib.colors.Colormap
        color map to apply
    vmin, vmax : float, float
        minimum and maximum data values
    df : pandas DataFrame
        data frame to look for column in
    df_name : str
        name of dataframe for errors

    Returns
    -------
    "_gpm" : str
        indicates this should be interpreted in a special way by gpmap
    data_column : str
    cmap : matplotlib.colors.Colormap
    vmin, vmax : float, float
    """
    # Make sure the data column exists
    try:
        v = df.loc[:, data_column]
    except KeyError:
        err = f"GenotypePhenotypeMap {df_name} dataframe does not have column\n"
        err += f"'{data_column}'\n"
        raise KeyError(err)

    # Make sure the cmap is recognized
    if not isinstance(cmap, matplotlib.colors.Colormap):
        try:
            cmap = matplotlib.cm.get_cmap(cmap)
        except ValueError as msg:
            col = str(msg).split(",")
            err = f"cmap '{cmap}' not recognized. This should either be a\n"
            err += "matplotlib Colormap object or the name of one of the\n"
            err += "colormaps in matplotlib. Available colormaps on your\n"
            err += "system are:\n"
            col[0] = col[0].split(" ")[-1]
            for c in col:
                err += f"    {c.strip()}\n"
            err += "\n"

            raise ValueError(err)

    # Deal with minimum and maximum for color map
    if vmin is None:
        vmin = np.nanmin(v)
    if vmax is None:
        vmax = np.nanmax(v)

    check.float_sanity(vmin)
    check.float_sanity(vmax)

    # Make sure vmin <= than vmax
    if vmin > vmax:
        err = f"vmax ({vmax}) must be >= than vmin ({vmin})\n"
        raise ValueError(err)

    return "_gpm", data_column, cmap, vmin, vmax
Beispiel #5
0
def flattened(G, scale=1, vertical=False):
    """
    Get flattened positions for a genotype-phenotype graph.

    Parameters
    ----------
    G : GenotypePhenotypeGraph object
        A genotype-phenotype objects
    scale : float (default=1)
        density of the nodes. Must be > 0.
    vertical : bool (default=False)
        position nodes top-to-bottom (vertical) rather than left-to-right

    Returns
    -------
    positions: dict
        positions of all nodes in network (i.e. {index: [x,y]})

    """

    # Make sure this looks like a GenotypePhenotypeGraph that has a genotype
    # phenotype map loaded.
    try:
        if G.gpm is None:
            raise AttributeError
    except AttributeError:
        err = "G must be a GenotypePhenotypeGraph object with a loaded \n"
        err += "genotype map. (see the add_gpm method)."
        raise ValueError(err)

    # Make sure the scale is sane
    check.float_sanity(scale, min_allowed=0.0)

    # Get the binary genotypes from the GenotypePhenotypeGraph
    # Set level of nodes and begin calc offset on the fly
    graph = G
    offsets = {}
    positions = {}
    for n in range(len(list(G.nodes()))):
        node = graph.nodes[n]

        # Calculate the level of each node
        level = node["binary"].count("1")
        if level in offsets:
            offsets[level] += 1
        else:
            offsets[level] = 1
        positions[n] = [level]

    # Center the offsets on 0
    for key, val in offsets.items():
        offsets[key] = list(np.arange(val) - (val - 1) / 2.0)

    # Offset positions
    if vertical:
        for n in range(len(list(G.nodes()))):
            pos = offsets[positions[n][0]].pop(0)
            scaled = scale * pos
            positions[n].insert(0, scaled)
            positions[n][-1] *= -1
    else:
        for n in range(len(list(G.nodes()))):
            pos = offsets[positions[n][0]].pop(0)
            scaled = scale * pos
            positions[n].append(scaled)

    return positions