示例#1
0
def plot_list(value_dict, ordered_param_range_dict, path, to_html=True, to_csv=False):
    """Plot the values in the dictionary value_dict in a html list and/or a csv file.

    :param value_dict: Dictionary (parameters tuple -> value) containing the values to be ploted.
    :type value_dict: dict(tuple -> int)
    :param ordered_param_range_dict: Ordered dictionary (parameter name -> range of the parameter).
    :type ordered_param_range_dict: Shared.OrderedDict(str -> range)
    :param path: Path to the plot file without suffix.
    :type path: path
    :param to_html: Option to plot a html list (Default: False).
    :type to_html: bool
    :param to_csv: Option to build a csv file (Default: False).
    :type to_csv: bool
    :param x_plots: Number of plots on the x-axis (Default: 2)
    :type x_plots: int
    """
    StoreLoad.generate_path(path)
    data_list = []
    for (key, value) in value_dict.items():
        if value is None:
            value = ' '
        elif value == '*':
            value = Parameters.zero_v_symbol
        data_list.append(list(key) + [value])
    data_list.sort()
    columns = list(ordered_param_range_dict.keys())+['dimension']
    data_frame = pandas.DataFrame(data=data_list, columns=columns)
    if to_html:
        html_path = path + '.html'
        data_frame.to_html(html_path)
    if to_csv:
        csv_path = path + '.csv'
        data_frame.to_csv(csv_path)
示例#2
0
def list_bipartite_graphs(n_vertices_1, n_vertices_2, deg_range_1, deg_range_2, n_edges):
    """Create a list of bipartite graphs, vertices of the first colour have degree in the range min_deg_1:max_deg_1,
    vertices of the second colour have degree in the range min_deg_2:max_deg_2.

    :param n_vertices_1: Number of vertices of the first colour.
    :type n_vertices_1: int
    :param n_vertices_2: Number of vertices of the second colour.
    :type n_vertices_2: int
    :param deg_range_1: (min, max) degree of the vertices of the first colour.
    :type deg_range_1: tuple(int, int)
    :param deg_range_2: (min, max) degree of the vertices of the second colour.
    :type deg_range_2: tuple(int, int)
    :param n_edges: Number of edges of the bipartite graph.
    :type n_edges: int
    :return: List of generated sage graphs.
    :rtype: list(Graph)
    """
    (min_deg_1, max_deg_1) = deg_range_1
    (min_deg_2, max_deg_2) = deg_range_2
    # z switch prevents multiple hairs and multiple edges
    StoreLoad.makedirs(Parameters.temp_folder)
    with tempfile.NamedTemporaryFile(dir=Parameters.temp_folder) as f:
        nauty_command = 'genbgL -czlq -d%d:%d -D%d:%d %d %d %d:%d %s' % \
            (min_deg_1, min_deg_2, max_deg_1, max_deg_2,
             n_vertices_1, n_vertices_2, n_edges, n_edges, f.name)
        #logger.warn('call nauty to generate bipartite graphs: ' + nauty_command)
        os.system(nauty_command)
        list_g6 = f.read().splitlines()
        # if len(list_g6) == 0:
        #print('Call nauty to generate bipartite graphs: ' + nauty_command)
        #print('List of bipartite graphs generated using nauty has zero length')
        #logger.warn('Call nauty to generate bipartite graphs: ' + nauty_command)
        #logger.warn('List of bipartite graphs generated using nauty has zero length')
    return [Graph(g6) for g6 in list_g6]
示例#3
0
文件: Profiling.py 项目: sibrun/GH
 def wrapper(*args, **kwargs):
     prof = cProfile.Profile()
     re = prof.runcall(func, *args, **kwargs)
     path = os.path.join(dir_name, func.__name__ + ".prof")
     SL.generate_path(path)
     prof.dump_stats(path)
     return re
示例#4
0
 def plot_all_graphs_to_file(self, skip_existing=False):
     """ Plots all graphs in the basis of this vector space and stores then into their repsective file paths.
     The respective filename is the index of the graph in the basis (plus .png).
     """
     ba = self.get_basis()
     for (j, G) in enumerate(ba):
         path = os.path.join(self.get_plot_path(), '%d.png' % (j))
         if (not skip_existing) or (not os.path.isfile(path)):
             StoreLoad.generate_path(path)
             P = self.plot_graph(G)
             P.save(path)
示例#5
0
    def get_rank(self):
        """Return the reference rank from the reference rank file.

        :return: Reference rank.
        :rtype: int
        :raise StoreLoad.FileNotFoundError: Raised if reference rank file not found.
        """
        if not self.exists_rank_file():
            raise StoreLoad.FileNotFoundError(
                "%s: Reference rank file not found" % str(self))
        return int(StoreLoad.load_line(self.rank_file_path))
示例#6
0
 def plot_graph_to_file(self, G):
     """ Plots a single graph and stores it into the standard file path.
     Does not canonize the graph before plot.
     The filename is the graphs g6 code.
     :param G: The graph to be drawn. Must belong to this vector space.
     :type G: Graph.
     """
     g6 = self.graph_to_ascii(G)
     path = os.path.join(self.get_plot_path(), g6 + '.png')
     StoreLoad.generate_path(path)
     P = self.plot_graph(G)
     P.save(path)
示例#7
0
    def _store_basis_g6(self, basis_list):
        """Store the basis to the basis file.

        The basis file contains a list of graph6 strings for canonically labeled graphs building a basis of the
        vector space.
        The first line of the basis file contains the dimension of the vector space.

        :param basis_list: List of graph6 strings representing the vector space basis.
        :type basis_list: list(str)
        """
        basis_list.insert(0, str(len(basis_list)))
        StoreLoad.store_string_list(basis_list, self.get_basis_file_path())
示例#8
0
    def _load_basis_g6(self):
        """Load the reference basis list from the reference file.

        :Note: The implementation depends on the reference data.

        :return: List of graph6 strings representing the reference basis.
        :rtype: list(str)
        :raise StoreLoad.FileNotFoundError: If the reference basis file is not found.
        """
        if not self.exists_basis_file():
            raise StoreLoad.FileNotFoundError(
                "%s: Reference basis file not found" % str(self))
        return StoreLoad.load_string_list(self.basis_file_path)
示例#9
0
    def get_dimension(self):
        """Return the Dimension of the vector space.

        :return: int: Dimension of the vector space
        :rtype: int

        :raise StoreLoad.FileNotFoundError: Raised if no basis file found.
        """
        if not self.is_valid():
            return 0
        try:
            header = StoreLoad.load_line(self.get_basis_file_path())
            return int(header)
        except StoreLoad.FileNotFoundError:
            raise StoreLoad.FileNotFoundError(
                "Dimension unknown for %s: No basis file" % str(self))
示例#10
0
def list_bipartite_graphs3(n_vertices_1, n_vertices_2, deg_range_1, deg_range_2, n_edges, n_maxneighbors):
    """
    Same as before, but with  n_maxcommon_neighbors many common neighbors ...
    Create a list of bipartite graphs, vertices of the first colour have degree in the range min_deg_1:max_deg_1,
    vertices of the second colour have degree in the range min_deg_2:max_deg_2.

    :param n_vertices_1: Number of vertices of the first colour.
    :type n_vertices_1: int
    :param n_vertices_2: Number of vertices of the second colour.
    :type n_vertices_2: int
    :param deg_range_1: (min, max) degree of the vertices of the first colour.
    :type deg_range_1: tuple(int, int)
    :param deg_range_2: (min, max) degree of the vertices of the second colour.
    :type deg_range_2: tuple(int, int)
    :param n_edges: Number of edges of the bipartite graph.
    :type n_edges: int
    :param n_maxneighbors: Maximum number of common neighbors of second color vertices
    :return: List of generated sage graphs.
    :rtype: list(Graph)
    """
    (min_deg_1, max_deg_1) = deg_range_1
    (min_deg_2, max_deg_2) = deg_range_2
    # z switch prevents multiple hairs and multiple edges

    StoreLoad.makedirs(Parameters.temp_folder)
    with tempfile.NamedTemporaryFile(dir=Parameters.temp_folder) as f:
        nauty_command = 'genbgL -clq -Z%d -d%d:%d -D%d:%d %d %d %d:%d %s' % \
            (n_maxneighbors, min_deg_1, min_deg_2, max_deg_1, max_deg_2,
             n_vertices_1, n_vertices_2, n_edges, n_edges, f.name)
        # print(nauty_command)
        #logger.warn('call nauty to generate bipartite graphs: ' + nauty_command)
        os.system(nauty_command)
        txt = f.read()
        if not type(txt) is str:
            txt = txt.decode("ascii")
        list_g6 = txt.splitlines()
        # list_g6 = f.read().decode("utf-8").splitlines()
        # print(list_g6)
        # if len(list_g6) == 0:
        #print('Call nauty to generate bipartite graphs: ' + nauty_command)
        #print('List of bipartite graphs generated using nauty has zero length')
        #logger.warn('Call nauty to generate bipartite graphs: ' + nauty_command)
        #logger.warn('List of bipartite graphs generated using nauty has zero length')
    return [Graph(g6) for g6 in list_g6]
示例#11
0
    def _load_basis_g6(self):
        """Load the basis from the basis file.

        Raises an exception if no basis file found or if the dimension in the header of the basis file doesn't
        correspond to the dimension of the basis.

        :return: List of graph6 strings of canonically labeled graphs building a basis of the
            vector space.
        :rtype: list(str)
        :raise StoreLoad.FileNotFoundError: Raised if no basis file found.
        :raise ValueError: Raised if dimension in header doesn't correspond to the basis dimension.
        """
        if not self.exists_basis_file():
            raise StoreLoad.FileNotFoundError(
                "Cannot load basis, No basis file found for %s: " % str(self))
        basis_list = StoreLoad.load_string_list(self.get_basis_file_path())
        dim = int(basis_list.pop(0))
        if len(basis_list) != dim:
            raise ValueError("Basis read from file %s has wrong dimension" %
                             str(self.get_basis_file_path()))
        return basis_list
示例#12
0
文件: DisplayInfo.py 项目: sibrun/GH
def plot_info(data_list, header_list, path, to_html=True, to_csv=False):
    """Write a data list to a html or csv file.

    :param data_list:
    :type data_list: list(list)
    :param header_list: List with the parameter and property names.
    :type header_list: list(str)
    :param path: Path to the file without suffix.
    :type path: path
    :param to_html: Option to write data to a html file (Default: True).
    :type to_html: bool
    :param to_csv: Option to write data to a csv file (Default: False).
    :type to_csv: bool
    :return:
    """
    StoreLoad.generate_path(path)
    data_frame = pandas.DataFrame(data=data_list, columns=header_list)
    if to_html:
        html_path = path + '.html'
        data_frame.to_html(html_path)
    if to_csv:
        csv_path = path + '.csv'
        data_frame.to_csv(csv_path)
示例#13
0
    def _load_matrix(self):
        """ Load the reference matrix list from the reference file.

        The implementation depends on the reference data.

        :return: (matrix_list = list((domain index, target index, value), shape = (domain dimension, target dimension))
        :rtype: tuple(list(tuple(int, int, int)), tuple(int, int))
        :raise StoreLoad.FileNotFoundError: If the reference matrix file is not found.
        :raise: ValueError: Raised in the following cases:
                End line missing.
                Negative matrix index.
                Matrix index too large.
        """
        if not self.exists_matrix_file():
            raise StoreLoad.FileNotFoundError(
                "%s: Reference basis file not found" % str(self))
        stringList = StoreLoad.load_string_list(self.matrix_file_path)
        entriesList = []
        if len(stringList) == 0:
            return ([], None)
        else:
            (d, t, z) = map(int, stringList.pop().split(" "))
            if z != 0:
                raise ValueError("End line in reference file %s is missing" %
                                 str(self))
            shape = (d, t)
            for line in stringList:
                (i, j, v) = map(int, line.split(" "))
                if i < 0 or j < 0:
                    raise ValueError("%s: Negative matrix index" % str(self))
                if i > d or j > t:
                    raise ValueError("%s Matrix index outside matrix size" %
                                     str(self))
                if i == 0 or j == 0:
                    continue
                entriesList.append((i - 1, j - 1, v))
        return (entriesList, shape)
示例#14
0
def set_log_file(log_file):
    log_path = os.path.join(Parameters.log_dir, log_file)
    SL.generate_path(log_path)
    logger.addHandler(logging.FileHandler(log_path))
示例#15
0
def plot_2d_array(value_dict, ordered_param_range_dict, path, parameter_order=(0, 1)):
    """Plot a 2 dimensional array given by the value_dict.

    :param value_dict: Dictionary (parameters tuple -> value) containing the values to be ploted.
    :type value_dict: dict(tuple -> int)
    :param ordered_param_range_dict: Ordered dictionary (parameter name -> range of the parameter).
    :type ordered_param_range_dict: Shared.OrderedDict(str -> range)
    :param path: Path to the plot file without suffix.
    :type path: path
    :param parameter_order: Permutation of the parameter indices, to specify the order of
           the parameters (Default: None/given ordering). Example: (1, 0) to plot the second parameter on the x-axis
           and the first on the y-axis.
    :type parameter_order: list(int)
    """
    path += '.png'
    if parameter_order in {(0, 1), (1, 0)}:
        (x_idx, y_idx) = parameter_order
    else:
        raise ValueError('invalid parameter order')
    inverse_order = tuple(Shared.Perm(list(parameter_order)).inverse())

    (x_label, x_range) = list(ordered_param_range_dict.items())[x_idx]
    (y_label, y_range) = list(ordered_param_range_dict.items())[y_idx]
    if len(list(x_range)) == 0 or len(list(y_range)) == 0:
        logging.warn('empty parameter range: nothing to plot')
        return

    x_min = min(x_range)
    x_max = max(x_range)
    x_size = (x_max + 1 - x_min) * Parameters.x_width
    y_min = min(y_range)
    y_max = max(y_range)
    y_size = (y_max + 1 - y_min) * Parameters.y_width

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

    plt.xlabel(x_label)
    plt.ylabel(y_label)

    plt.xlim(x_min, x_max)
    plt.ylim(y_min, y_max)

    for coordinates in itertools.product(x_range, y_range):
        old_coordinates = tuple(coordinates[i] for i in inverse_order)
        v = value_dict.get(old_coordinates)
        if v is not None:
            if v == '*':
                v = Parameters.zero_v_symbol
            elif v == 0:
                v = Parameters.zero_symbol
            (x, y) = coordinates
            ax.text(x, y, str(v), va='center', ha='center')

    x_ticks_grid = np.arange(x_min - 0.5, x_max + 1, 1)
    y_ticks_grid = np.arange(y_min - 0.5, y_max + 1, 1)

    x_ticks = np.arange(x_min, x_max + 1, 1)
    y_ticks = np.arange(y_min, y_max + 1, 1)

    ax.set_xticks(x_ticks)
    ax.set_yticks(y_ticks)
    ax.set_xticks(x_ticks_grid, minor=True)
    ax.set_yticks(y_ticks_grid, minor=True)
    ax.grid(which='minor')

    plt.tight_layout()

    StoreLoad.generate_path(path)
    plt.savefig(path)
示例#16
0
def plot_3d_array(value_dict, ordered_param_range_dict, path, parameter_order=(0, 1, 2), x_plots=2):
    """Plot a 3 dimensional array given by the value_dict as a list of 2 dimensional plots with
    x_plots per line.

    :param value_dict: Dictionary (parameters tuple -> value) containing the values to be ploted.
    :type value_dict: dict(tuple -> int)
    :param ordered_param_range_dict: Ordered dictionary (parameter name -> range of the parameter).
    :type ordered_param_range_dict: Shared.OrderedDict(str -> range)
    :param path: Path to the plot file without suffix.
    :type path: path
    :param x_plots: Number of plots on the x-axis (Default: 2)
    :type x_plots: int
    :param parameter_order: tuple(non-negative int), optional: Permutation of the parameter indices, to specify the order of
           the parameters (Default: None/given ordering). Only for plots. Example: (1, 2, 0) to plot the second parameter
           on the x-axis, the third on the y-axis and the first on the z-axis.
    :type parameter_order: list(int)
    """
    path += '.png'
    if parameter_order in {(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)}:
        (x_idx, y_idx, z_idx) = parameter_order
    else:
        raise ValueError('invalid parameter order')
    inverse_order = tuple(Shared.Perm(list(parameter_order)).inverse())

    (x_label, x_range) = ordered_param_range_dict.items()[x_idx]
    (y_label, y_range) = ordered_param_range_dict.items()[y_idx]
    (z_label, z_range) = ordered_param_range_dict.items()[z_idx]
    if len(list(x_range)) == 0 or len(list(y_range)) == 0 or len(list(z_range)) == 0:
        logging.warn('empty parameter range: nothing to plot')
        return

    x_min = min(x_range)
    x_max = max(x_range)
    x_size = (x_max + 1 - x_min) * Parameters.x_width
    y_min = min(y_range)
    y_max = max(y_range)
    y_size = (y_max + 1 - y_min) * Parameters.y_width
    z_min = min(z_range)
    z_max = max(z_range)
    z_size = z_max + 1 - z_min

    if z_size % x_plots:
        y_plots = int(round(float(z_size)/x_plots + 0.5))
    else:
        y_plots = z_size / x_plots

    fig, axarr = plt.subplots(
        y_plots, x_plots, figsize=(x_plots*x_size, y_plots*y_size))

    for z in z_range:
        ax = _get_ax(axarr, x_plots, y_plots, z, z_min)
        ax.set_xlabel(x_label)
        ax.set_ylabel(y_label)
        ax.set_title(str(z)+' '+z_label)
        ax.set_xlim(x_min, x_max)
        ax.set_ylim(y_min, y_max)

    for coordinates in itertools.product(x_range, y_range, z_range):
        old_coordinates = tuple(coordinates[i] for i in inverse_order)
        v = value_dict.get(old_coordinates)
        if v is not None:
            if v == '*':
                v = Parameters.zero_v_symbol
            elif v == 0:
                v = Parameters.zero_symbol
            (x, y, z) = coordinates
            _get_ax(axarr, x_plots, y_plots, z, z_min).text(
                x, y, str(v), va='center', ha='center')

    x_ticks_grid = np.arange(x_min - 0.5, x_max + 1, 1)
    y_ticks_grid = np.arange(y_min - 0.5, y_max + 1, 1)

    x_ticks = np.arange(x_min, x_max + 1, 1)
    y_ticks = np.arange(y_min, y_max + 1, 1)

    for z in z_range:
        ax = _get_ax(axarr, x_plots, y_plots, z, z_min)
        ax.set_xticks(x_ticks)
        ax.set_yticks(y_ticks)
        ax.set_xticks(x_ticks_grid, minor=True)
        ax.set_yticks(y_ticks_grid, minor=True)
        ax.grid(which='minor')

    plt.tight_layout()

    if z_size % x_plots:
        for z in range(z_max + 1, z_min + x_plots*y_plots):
            ax = _get_ax(axarr, x_plots, y_plots, z, z_min)
            fig.delaxes(ax)

    StoreLoad.generate_path(path)
    plt.savefig(path)
示例#17
0
"""Generate sample images of graphs to be used on the webpage."""

import SpecialGraphs
import Parameters
import OrdinaryGraphComplex
import HairyGraphComplex
import StoreLoad

imgdir = Parameters.web_dir + "/img/"
StoreLoad.makedirs(imgdir)

# Commutatie graph complex
G = SpecialGraphs.wheel_graph(7)
VS = OrdinaryGraphComplex.OrdinaryGVS(8, 7, False)
# p = VS.plot_graph(G)
p = G.plot(vertex_labels=False, transparent=True)
p.save(imgdir + "wheel7.png")


# hairy graph complex
G = SpecialGraphs.hedgehog_graph(5)
VS = HairyGraphComplex.HairyGraphVS(5, 1, 5, False, False)
p = G.plot(vertex_labels=False, transparent=True)
p.save(imgdir + "hedgehog5.png")