Example: generating a histogram

Illustrates reporting with histograms from the Python API.

The Python API also generates formatted reports that include histograms. These reports are available either interactively in a Python session or programmatically in a Python application.

To generate a histogram, use methods of the class Cplex. If you are interested in a histogram based on the rows (constraints) of your model, consider the method get_histogram of the LinearConstraintInterface. Similarly, if you are interested in a histogram based on the columns (variables) of your model, consider the method get_histogram of the VariablesInterface.

The method __str__ of the histogram object returns a string displaying the number of rows or columns with nonzeros in human readable form. The data member orientation of the histogram object specifies either columns (indicating that the histogram reflects the nonzero counts for the variables of the linear constraint matrix) or rows (indicating that the histogram reflects the nonzero counts for the constraints of the model).

Additionally, you can query the histogram object about the number of rows or columns with a given nonzero count. That is, how many rows have N nonzeros? Or, how many columns have K nonzeros? Here is a sample interactive session querying nonzero columns and generating a histogram of them:

>>> import cplex
    >>> c = cplex.Cplex("ind.lp")
    >>> histogram = c.variables.get_histogram()
    >>> print histogram
        Nonzero Count:   1   2    3
    Number of Columns:   1   6   36

    >>> histogram[2]
    6
    >>> histogram[0:4]
    [0, 1, 6, 36]

Continuing in the same session, the following lines use the histogram to report more elaborate information about nonzeros in that problem:

>>> maxh = max(histogram)
    >>> for i, count in histogram:
    >>>     if histogram[i] == maxh:
    >>>         print "most common nz count is", maxh, "appearing", count, "times"
    most common nz count is 3 appearing 36 times