def main():
    """Parse arguments and perform the computation."""

    # Parse arguments
    parser = argparse.ArgumentParser()
    parser.description = "Compute approximate betweenness centrality of all vertices in a graph using the algorihm by Brandes and Pich, and the time to compute them, and write them to file"
    parser.add_argument("epsilon", type=util.valid_interval_float,
            help="accuracy parameter")
    parser.add_argument("delta", type=util.valid_interval_float,
            help="confidence parameter")
    parser.add_argument("graph", help="graph file")
    parser.add_argument("output", help="output file")
    parser.add_argument("-m", "--maxconn", action="store_true", default=False,
            help="if the graph is not weakly connected, only save the largest connected component")
    parser.add_argument("-p", "--pickle", action="store_true", default=False,
            help="use pickle reader for input file")
    parser.add_argument("-s", "--samplesize", type=util.positive_int,
            default=0, help="use specified sample size. Overrides epsilon, delta, and diameter computation")
    parser.add_argument("-t", "--timeout", type=util.positive_int, default=3600,
            help="Timeout computation after specified number of seconds (default 3600 = 1h, 0 = no timeout)")
    parser.add_argument("-u", "--undirected", action="store_true", default=False,
            help="consider the graph as undirected ")
    parser.add_argument("-v", "--verbose", action="count", default=0, help="increase verbosity (use multiple times for more verbosity)")
    parser.add_argument("-w", "--write", nargs="?", default=False, const="auto",
            help="write graph (and computed attributes) to file.")

    args = parser.parse_args()

    # Set the desired level of logging
    util.set_verbosity(args.verbose)

    # Read graph
    if args.pickle:
        G = util.read_graph(args.graph)
    else:
        G = converter.convert(args.graph, not args.undirected, args.maxconn)

    # Compute betweenness
    if args.samplesize:
        (stats, betw) = betweenness_sample_size(G, args.samplesize, args.write,
                args.timeout)
    else:
        (stats, betw) = betweenness(G, args.epsilon, args.delta, args.write,
                args.timeout)

    # If specified, write betweenness as vertex attributes, and time as graph
    # attribute back to file
    if args.write:
        logging.info("Writing betweenness as vertex attributes and stats as graph attribute")
        if args.write == "auto":
            filename = os.path.splitext(args.graph)[0] + ("-undir" if args.undirected else "dir") + ".picklez"
            G.write(filename)
        else:
            G.write(args.write)

    # Write stats and betweenness to output
    util.write_to_output(stats, betw, args.output)
def write_line_to_output(count_step, x_matrix, e_matrix, f_ouput):
    write_to_output('%5d|' % count_step, f_ouput, end='')
    for el in x_matrix:
        write_to_output('%10.4f|' % el[0], f_ouput, end='')
    if e_matrix is not None:
        for el in e_matrix:
            write_to_output('%10.4f|' % el[0], f_ouput, end='')
    else:
        for _ in range(RANK_MATRIX):
            write_to_output('%10s|' % '---', f_ouput, end='')
    write_to_output('\n', f_ouput)
def write_heading_to_output(f_output):
    write_to_output('%5s|' % 'k', f_output, end='')
    for i in range(RANK_MATRIX):
        write_to_output('%10s|' % ('x' + str(i)), f_output, end='')
    for i in range(RANK_MATRIX):
        write_to_output('%10s|' % ('e' + str(i)), f_output, end='')
    write_to_output('\n', f_output)
def write_heading_for_ouput(rank, f_output):
    write_to_output('%3s|' % 'k', f_output, end='')
    for i in range(rank):
        x = 'x' + str(i + 1)
        write_to_output('%15s|' % x, f_output, end='')
    write_to_output('%15s|' % 'eigenvalue', f_output, end='')
    write_to_output('%15s|' % 'Precision', f_output, end='')
def write_output(array_dict):
    out_file = open(OUTPUT_FILE_NAME, 'w')

    for heading in array_dict.keys():
        write_to_output('%15s|' % heading, out_file, end='')
    write_to_output('\n', out_file)
    for i in range(RANK_LEFT_MATRIX):
        for array in array_dict.values():
            write_to_output('%15.10f|' % array[i], out_file, end='')
        write_to_output('\n', out_file)
    out_file.close()
Beispiel #6
0
def main():
    """Parse arguments and perform the computation."""

    # Parse arguments
    parser = argparse.ArgumentParser()
    parser.description = "Compute approximate betweenness centrality of all vertices in a graph using the algorihm by Brandes and Pich, and the time to compute them, and write them to file"
    parser.add_argument("epsilon",
                        type=util.valid_interval_float,
                        help="accuracy parameter")
    parser.add_argument("delta",
                        type=util.valid_interval_float,
                        help="confidence parameter")
    parser.add_argument("graph", help="graph file")
    parser.add_argument("output", help="output file")
    parser.add_argument(
        "-m",
        "--maxconn",
        action="store_true",
        default=False,
        help=
        "if the graph is not weakly connected, only save the largest connected component"
    )
    parser.add_argument("-p",
                        "--pickle",
                        action="store_true",
                        default=False,
                        help="use pickle reader for input file")
    parser.add_argument(
        "-s",
        "--samplesize",
        type=util.positive_int,
        default=0,
        help=
        "use specified sample size. Overrides epsilon, delta, and diameter computation"
    )
    parser.add_argument(
        "-t",
        "--timeout",
        type=util.positive_int,
        default=3600,
        help=
        "Timeout computation after specified number of seconds (default 3600 = 1h, 0 = no timeout)"
    )
    parser.add_argument("-u",
                        "--undirected",
                        action="store_true",
                        default=False,
                        help="consider the graph as undirected ")
    parser.add_argument(
        "-v",
        "--verbose",
        action="count",
        default=0,
        help="increase verbosity (use multiple times for more verbosity)")
    parser.add_argument("-w",
                        "--write",
                        nargs="?",
                        default=False,
                        const="auto",
                        help="write graph (and computed attributes) to file.")

    args = parser.parse_args()

    # Set the desired level of logging
    util.set_verbosity(args.verbose)

    # Read graph
    if args.pickle:
        G = util.read_graph(args.graph)
    else:
        G = converter.convert(args.graph, not args.undirected, args.maxconn)

    # Compute betweenness
    if args.samplesize:
        (stats, betw) = betweenness_sample_size(G, args.samplesize, args.write,
                                                args.timeout)
    else:
        (stats, betw) = betweenness(G, args.epsilon, args.delta, args.write,
                                    args.timeout)

    # If specified, write betweenness as vertex attributes, and time as graph
    # attribute back to file
    if args.write:
        logging.info(
            "Writing betweenness as vertex attributes and stats as graph attribute"
        )
        if args.write == "auto":
            filename = os.path.splitext(args.graph)[0] + (
                "-undir" if args.undirected else "dir") + ".picklez"
            G.write(filename)
        else:
            G.write(args.write)

    # Write stats and betweenness to output
    util.write_to_output(stats, betw, args.output)
def cal_norma(matrix):
    result = 0
    for row in matrix:
        for el in row:
            result += el**2
    return math.sqrt(result)


if __name__ == "__main__":
    f_output = open(OUTPUT_FILE_NAME, 'w')

    matrix_aplha, matrix_beta = read_input()

    norma = cal_norma(matrix_aplha)
    if norma < 1:
        write_to_output('norma = {} < 1 \n'.format(norma), f_output)
    else:
        write_to_output('Norma > 1', f_output)
        import sys
        sys.exit(-1)

    dif = PRECISION + 1
    x = init_x(RANK_MATRIX)
    count_step = 0
    write_heading_to_output(f_output)
    write_line_to_output(count_step, x, None, f_output)
    while dif > PRECISION:
        count_step += 1
        new_x = matrix_aplha.dot(x) + matrix_beta
        dif = cal_dif(new_x, x)
        write_line_to_output(count_step, new_x, cal_precision_matrix(new_x, x),
Beispiel #8
0
def main():
    """Parse arguments, call betweenness(), write to file."""

    # Parse arguments
    parser = argparse.ArgumentParser()
    parser.description = "Compute approximate betweenness centrality of all vertices in a graph using sampling and VC-dimension, and the time to compute them, and write them to file"
    parser.add_argument("epsilon",
                        type=util.valid_interval_float,
                        help="accuracy parameter")
    parser.add_argument("delta",
                        type=util.valid_interval_float,
                        help="confidence parameter")
    parser.add_argument("graph", help="graph file")
    parser.add_argument("output", help="output file")
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-a",
                       "--approximate",
                       action="store_true",
                       default=True,
                       help="use approximate diameter (default)")
    group.add_argument("-d",
                       "--diameter",
                       type=util.positive_int,
                       default=0,
                       help="value to use for the diameter")
    group.add_argument("-e",
                       "--exact",
                       action="store_true",
                       default=False,
                       help="use exact diameter")
    parser.add_argument(
        "-m",
        "--maxconn",
        action="store_true",
        default=False,
        help=
        "if the graph is not weakly connected, only save the largest connected component"
    )
    parser.add_argument("-p",
                        "--pickle",
                        action="store_true",
                        default=False,
                        help="use pickle reader for input file")
    parser.add_argument(
        "-s",
        "--samplesize",
        type=util.positive_int,
        default=0,
        help=
        "use specified sample size. Overrides epsilon, delta, and diameter computation"
    )
    parser.add_argument(
        "-t",
        "--timeout",
        type=util.positive_int,
        default=3600,
        help=
        "Timeout computation after specified number of seconds (default 3600 = 1h, 0 = no timeout)"
    )
    parser.add_argument("-u",
                        "--undirected",
                        action="store_true",
                        default=False,
                        help="consider the graph as undirected ")
    parser.add_argument(
        "-v",
        "--verbose",
        action="count",
        default=0,
        help="increase verbosity (use multiple times for more verbosity)")
    parser.add_argument("-w",
                        "--write",
                        nargs="?",
                        default=False,
                        const="auto",
                        help="write graph (and computed attributes) to file.")
    parser.add_argument(
        "-l",
        "--weightFile",
        default="-",
        help=
        "random weights within the interval 0 to 1, must have as many entries as the number of edges"
    )

    args = parser.parse_args()

    # Set the desired level of logging
    util.set_verbosity(args.verbose)

    # Seed the random number generator
    random.seed()

    # Read graph
    if args.pickle:
        G = util.read_graph(args.graph)
    else:
        G = converter.convert(args.graph, not args.undirected, args.maxconn)

    if args.exact:
        args.approximate = False

    # Read the weights
    weights_list = []
    if args.weightFile != "-":
        with open(args.weightFile, 'r') as weight_file:
            for line in weight_file:
                weights_list.append(float(line.strip()))

    # Compute betweenness
    if args.samplesize:
        (stats, betw) = betweenness_sample_size(G, args.samplesize, args.write)
    else:
        if args.diameter > 0:
            (stats, betw) = betweenness(G, args.epsilon, args.delta,
                                        weights_list, args.diameter,
                                        args.write)
        else:
            (stats, betw) = betweenness(G, args.epsilon, args.delta,
                                        weights_list, args.approximate,
                                        args.write)

    # If specified, write betweenness as vertex attributes, and time as graph
    # attribute back to file
    if args.write:
        logging.info(
            "Writing betweenness as vertex attributes and stats as graph attribute"
        )
        if args.write == "auto":
            filename = os.path.splitext(args.graph)[0] + (
                "-undir" if args.undirected else "dir") + ".picklez"
            G.write(filename)
        else:
            G.write(args.write)

    # Write stats and betweenness to output
    util.write_to_output(stats, betw, args.output)
Beispiel #9
0
def main():
    """Parse arguments, call betweenness(), write to file."""

    # Parse arguments
    parser = argparse.ArgumentParser()
    parser.description = "Compute approximate betweenness centrality of all vertices in a graph using sampling and VC-dimension, and the time to compute them, and write them to file"
    parser.add_argument("epsilon", type=util.valid_interval_float,
            help="accuracy parameter")
    parser.add_argument("delta", type=util.valid_interval_float,
            help="confidence parameter")
    parser.add_argument("graph", help="graph file")
    parser.add_argument("output", help="output file")
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-a", "--approximate", action="store_true",
            default=True, help="use approximate diameter (default)")
    group.add_argument("-d", "--diameter", type=util.positive_int, default=0,
            help="value to use for the diameter")
    group.add_argument("-e", "--exact", action="store_true", default=False,
            help="use exact diameter")
    parser.add_argument("-m", "--maxconn", action="store_true", default=False,
            help="if the graph is not weakly connected, only save the largest connected component")
    parser.add_argument("-p", "--pickle", action="store_true", default=False,
            help="use pickle reader for input file")
    parser.add_argument("-s", "--samplesize", type=util.positive_int,
            default=0, help="use specified sample size. Overrides epsilon, delta, and diameter computation")
    parser.add_argument("-t", "--timeout", type=util.positive_int, default=3600,
            help="Timeout computation after specified number of seconds (default 3600 = 1h, 0 = no timeout)")
    parser.add_argument("-u", "--undirected", action="store_true", default=False,
            help="consider the graph as undirected ")
    parser.add_argument("-v", "--verbose", action="count", default=0,
            help="increase verbosity (use multiple times for more verbosity)")
    parser.add_argument("-w", "--write", nargs="?", default=False, const="auto",
            help="write graph (and computed attributes) to file.")
    parser.add_argument("-l", "--weightFile", default="-",
            help="random weights within the interval 0 to 1, must have as many entries as the number of edges")

    args = parser.parse_args()

    # Set the desired level of logging
    util.set_verbosity(args.verbose)

    # Seed the random number generator
    random.seed()

    # Read graph
    if args.pickle:
        G = util.read_graph(args.graph)
    else:
        G = converter.convert(args.graph, not args.undirected, args.maxconn)

    if args.exact:
        args.approximate = False

    # Read the weights    
    weights_list=[]
    if args.weightFile != "-":
        with open(args.weightFile,'r') as weight_file:
            for line in weight_file:
                weights_list.append(float(line.strip()))

    # Compute betweenness
    if args.samplesize:
        (stats, betw) = betweenness_sample_size(G, args.samplesize, args.write)
    else:
        if args.diameter > 0:
            (stats, betw) = betweenness(G, args.epsilon, args.delta,
                    weights_list, args.diameter, args.write)
        else:
            (stats, betw) = betweenness(G, args.epsilon, args.delta,
                    weights_list, args.approximate, args.write)

    # If specified, write betweenness as vertex attributes, and time as graph
    # attribute back to file
    if args.write:
        logging.info("Writing betweenness as vertex attributes and stats as graph attribute")
        if args.write == "auto":
            filename = os.path.splitext(args.graph)[0] + ("-undir" if args.undirected else "dir") + ".picklez"
            G.write(filename)
        else:
            G.write(args.write)

    # Write stats and betweenness to output
    util.write_to_output(stats, betw, args.output)
def write_line_to_output(step_count, x, eigenvalue, precision, f_output):
    write_to_output('\n', f_output)
    write_to_output('%3d|' % step_count, f_output, end='')
    for row in x:
        write_to_output('%15.4f|' % row[0], f_output, end='')
    if eigenvalue:
        write_to_output('%15.4f|' % eigenvalue, f_output, end='')
    else:
        write_to_output('%15s|' % '---', f_output, end='')
    if precision:
        write_to_output('%15.4f|' % precision, f_output, end='')
    else:
        write_to_output('%15s|' % '---', f_output, end='')
    write_to_output('\n', f_output)
def write_eigenvector(x, f_output):
    l = max(x)
    write_to_output('\nEigenvector: \n{}'.format(str(x / l)), f_output)
if __name__ == "__main__":
    f_output = open(OUTPUT_FILE_NAME, 'w')

    raw_matrix = read_raw_input(INPUT_FILE_NAME)
    matrix_a = np.array(raw_matrix)

    rank = len(raw_matrix)
    write_heading_for_ouput(rank, f_output)

    x = init_x(rank)
    dif = PRECISION + 1
    previous_eigenvalue = None
    count_step = 0
    write_line_to_output(count_step, x, None, None, f_output)
    while dif > PRECISION:
        count_step += 1
        new_x = matrix_a.dot(x)
        new_eigenvalue = sum([new_x[i][0] / x[i][0]
                              for i in range(rank)]) / rank
        dif = cal_dif(new_eigenvalue, previous_eigenvalue)
        write_line_to_output(count_step, new_x, new_eigenvalue, dif, f_output)
        x = new_x
        previous_eigenvalue = new_eigenvalue
        if dif is None:
            dif = PRECISION + 1

    write_to_output('EigenValue={}'.format(new_eigenvalue), f_output)
    write_eigenvector(x, f_output)
    f_output.close()