Beispiel #1
0
    def test_format_meta(self):
        mapper = KeplerMapper()
        data = np.random.rand(1000, 10)
        lens = mapper.fit_transform(data, projection=[0])
        graph = mapper.map(lens, data)

        assert ("<p>%s</p>" % (len(graph["nodes"])) in format_meta(graph))
        assert ("<h3>Description</h3>\n<p>A short description</p>"
                in format_meta(graph,
                               custom_meta=[("Description",
                                             "A short description")]))
    def test_format_meta_with_meta(self):
        mapper = KeplerMapper()
        data = np.random.rand(1000, 10)
        lens = mapper.fit_transform(data, projection=[0])
        graph = mapper.map(lens, data)

        cm = "My custom_meta"
        fmt = format_meta(graph, cm)
        assert fmt["custom_meta"] == cm
    def test_format_meta(self):
        mapper = KeplerMapper()
        data = np.random.rand(1000, 10)
        lens = mapper.fit_transform(data, projection=[0])
        graph = mapper.map(lens, data)

        fmt = format_meta(graph)
        assert fmt["n_nodes"] == len(graph["nodes"])

        assert "n_edges" in fmt.keys()
        assert "n_total" in fmt.keys()

        del fmt["custom_meta"]
        vals = fmt.values()
        for v in vals:
            assert isinstance(v, numbers.Number)
def visualize(graph,
              color_function=None,
              custom_tooltips=None,
              custom_meta=None,
              path_html="mapper_visualization_output.html",
              title="Kepler Mapper",
              save_file=True,
              X=None,
              X_names=[],
              lens=None,
              lens_names=[],
              show_tooltips=True,
              nbins=10,
              verbose=1,
              node_size_func="none"):
    """Generate a visualization of the simplicial complex mapper output. Turns the complex dictionary into a HTML/D3.js visualization
        Parameters
        ----------
        graph : dict
            Simplicial complex output from the `map` method.
        path_html : String
            file name for outputing the resulting html.
        custom_meta: dict
            Render (key, value) in the Mapper Summary pane. 
        custom_tooltip: list or array like
            Value to display for each entry in the node. The cluster data pane will display entry for all values in the node. Default is index of data.
        save_file: bool, default is True
            Save file to `path_html`.
        X: numpy arraylike
            If supplied, compute statistics information about the original data source with respect to each node.
        X_names: list of strings
            Names of each variable in `X` to be displayed. If None, then display names by index.
        lens: numpy arraylike
            If supplied, compute statistics of each node based on the projection/lens
        lens_name: list of strings
            Names of each variable in `lens` to be displayed. In None, then display names by index.
        show_tooltips: bool, default is True.
            If false, completely disable tooltips. This is useful when using output in space-tight pages or will display node data in custom ways.
        nbins: int, default is 10
            Number of bins shown in histogram of tooltip color distributions.
        Returns
        --------
        html: string
            Returns the same html that is normally output to `path_html`. Complete graph and data ready for viewing.
        Examples
        ---------
        >>> mapper.visualize(simplicial_complex, path_html="mapper_visualization_output.html",
                            custom_meta={'Data': 'MNIST handwritten digits', 
                                         'Created by': 'Franklin Roosevelt'
                            }, )
        """

    # TODO:
    #   - Make color functions more intuitive. How do they even work?
    #   - Allow multiple color functions that can be toggled on and off.

    if not len(graph["nodes"]) > 0:
        raise Exception(
            "Visualize requires a mapper with more than 0 nodes. \nIt is possible that the constructed mapper could have been constructed with bad parameters. This occasionally happens when using the default clustering algorithm. Try changing `eps` or `min_samples` in the DBSCAN clustering algorithm."
        )

    # Find the module absolute path and locate templates
    module_root = os.path.join(os.path.dirname(km.__file__), "templates")
    env = Environment(loader=FileSystemLoader(module_root))
    # Color function is a vector of colors?
    color_function = init_color_function(graph, color_function)

    mapper_data = format_mapper_data(graph, color_function, X, X_names, lens,
                                     lens_names, custom_tooltips, env, nbins,
                                     node_size_func)

    colorscale = km.visuals.colorscale_default

    histogram = graph_data_distribution(graph, color_function, colorscale)

    mapper_summary = format_meta(graph, custom_meta)

    # Find the absolute module path and the static files
    #js_path = os.path.join(os.path.dirname(km.__file__), "static", "kmapper.js")
    js_path = "kmapper.js"
    with open(js_path, "r") as f:
        js_text = f.read()

    css_path = os.path.join(os.path.dirname(km.__file__), "static",
                            "style.css")
    with open(css_path, "r") as f:
        css_text = f.read()

    # Render the Jinja template, filling fields as appropriate
    template = env.get_template("base.html").render(
        title=title,
        mapper_summary=mapper_summary,
        histogram=histogram,
        dist_label="Node",
        mapper_data=mapper_data,
        colorscale=colorscale,
        js_text=js_text,
        css_text=css_text,
        show_tooltips=True,
    )

    if save_file:
        with open(path_html, "wb") as outfile:
            if verbose > 0:
                print("Wrote visualization to: %s" % (path_html))
            outfile.write(template.encode("utf-8"))

    return template