def cli_graphEntropy(): """Command line interface for graphEntropy.""" info = 'Calculates the shanon entropy for the complete linkograph.' parser = argparse.ArgumentParser(description=info) parser.add_argument('linkograph', metavar='LINKOGRAPH.json', nargs=1, help='The linkograph.') parser.add_argument('-l', '--lowerBound', type=int, help='The lowest index to consider.') parser.add_argument('-u', '--upperBound', type=int, help='The highest index to consider.') args = parser.parse_args() # Read in the linkograph. linko = linkoCreate.readLinkoJson(args.linkograph[0]) print(graphEntropy(linko, args.lowerBound, args.upperBound))
def cli_percentageOfEntries(): """Command line interface for percentageOfEntries.""" info = 'Gives the percentage of entries that have each label.' parser = argparse.ArgumentParser(description=info) parser.add_argument('linkograph', metavar='LINKOGRAPH.json', nargs=1, help='The linkograph.') parser.add_argument('-l', '--lowerBound', type=int, help='The lowest index to consider.') parser.add_argument('-u', '--upperBound', type=int, help='The highest index to consider.') args = parser.parse_args() # Read in the linkograph. linko = linkoCreate.readLinkoJson(args.linkograph[0]) result = percentageOfEntries(linko, args.lowerBound, args.upperBound) print(json.dumps(result, indent=4))
def cli_percentageOfLinks(): """Command line interface for percentageOfLinks.""" info = 'The percentage of links out the total possible links.' parser = argparse.ArgumentParser(description=info) parser.add_argument('linkograph', metavar='LINKOGRAPH.json', nargs=1, help='The linkograph.') parser.add_argument('-l', '--lowerBound', type=int, help='The lowest index to consider.') parser.add_argument('-u', '--upperBound', type=int, help='The highest index to consider.') args = parser.parse_args() # Read in the linkograph. linko = linkoCreate.readLinkoJson(args.linkograph[0]) print(percentageOfLinks(linko, args.lowerBound, args.upperBound))
def cli_linkoDrawEPS(): """Draws the linkograph in eps format.""" info = 'Draws the linkograph in eps format.' parser = argparse.ArgumentParser(description=info) parser.add_argument('linkograph', metavar='LINKOGRAPH.json', nargs=1, help='The linkograph to draw.') parser.add_argument('out', metavar='OUTPUT_FILE', nargs=1, help='The output file.') parser.add_argument('-s', '--scale', metavar='SCALE', type=float, help='Scales the graph.') args = parser.parse_args() # Read in the linkograph. linko = linkoCreate.readLinkoJson(args.linkograph[0]) if args.scale is None: args.scale = 1 linkoDrawEPS(linko, args.out[0], args.scale)
def cli_subLinkographFrequency(): """ Command line interface for subLinkographFrequency. """ # Load the possible functions. functions, functionHelp = functionMap() info = ('Finds the frequency of the funtion value consider all' 'sublinkographs of a linkograph.\n{}'.format(functionHelp)) parser = argparse.ArgumentParser(description=info) parser.add_argument('linko', metavar='LINKOGRAPH.json', nargs=1, help='The linkograh.') parser.add_argument('size', metavar='SIZE', type=int, nargs=1, help='The number of nodes for the sublinkographs.') parser.add_argument('-o', '--overlap', action='store_true', help='The abstraction classes.') parser.add_argument('-f', '--function', metavar='FUNCTION', help=('The function to apply to each' ' linkograph.')) parser.add_argument('-j', '--json', action='store_true', help=('Use json format.')) args = parser.parse_args() if args.function is not None: choice = args.function else: choice = 'enum' # Read in the linkograph linko = linkoCreate.readLinkoJson(args.linko[0]) if linko is not None: # Note: the linkograph has to be passed as a list. freq = subLinkographFrequency([linko], args.size[0], args.overlap, functions[choice]) else: return if args.json: print(json.dumps(freq, indent=4)) else: for entry in freq.keys(): print('{}\t{}'.format(entry, freq[entry]))
def cli_linkoToEnum(): """ Command line interface for linkoToEnum. """ info = 'Converts linkograph to the associated linkograph enum.' parser = argparse.ArgumentParser(description=info) parser.add_argument('linko', metavar='LINKOGRAPH.json', help='The linkograph to convert.') args = parser.parse_args() linko = linkoCreate.readLinkoJson(args.linko) if linko is not None: enum = linkoToEnum(linko) print('{}'.format(enum))
def cli_linkoPrint(): """Draws the linkograph in text format.""" info = 'Draws the linkograph in SVG format.' parser = argparse.ArgumentParser(description=info) parser.add_argument('linkograph', metavar='LINKOGRAPH.json', nargs=1, help='The linkograph to draw.') parser.add_argument('--offset', type=int, default=None, help='Controls x offset.') args = parser.parse_args() # Read in the linkograph linko = linkoCreate.readLinkoJson(args.linkograph[0]) offset = args.offset linkoPrint(linko, offset)
def cli_subgraphMetric(): """Command line interface for subgraphMetric.""" info = 'Calculates the value of graph metrics on subgraphs.' parser = argparse.ArgumentParser(description=info) parser.add_argument('linkograph', metavar='LINKOGRAPH.json', nargs=1, help='The linkograph.') parser.add_argument('-e', '--entropy', action='store_true', help='Use Shannon entropy') parser.add_argument('-p', '--percentageOfLinks', action='store_true', help='Use percentage of links') parser.add_argument('-t', '--lowerThreshold', type=float, help='The lowest threshold value.') parser.add_argument('-T', '--upperThreshold', type=float, help='The highest threshold value.') parser.add_argument('-m', '--minSize', type=int, default=2, help='Minimum subgraph size.') parser.add_argument('-M', '--maxSize', type=int, help='Maximum subgraph size.') parser.add_argument('-s', '--step', type=int, default=1, help='Steps between the lower bounds considered.') parser.add_argument('-l', '--lowerBound', type=int, help='The lowest index to consider.') parser.add_argument('-u', '--upperBound', type=int, help='The highest index to consider.') args = parser.parse_args() # Read in the linkograph. linko = linkoCreate.readLinkoJson(args.linkograph[0]) if args.entropy: result = subgraphMetric(linko, graphEntropy, args.lowerThreshold, args.upperThreshold, args.minSize, args.maxSize, args.step, args.lowerBound, args.upperBound) else: result = subgraphMetric(linko, percentageOfLinks, args.lowerThreshold, args.upperThreshold, args.minSize, args.maxSize, args.step, args.lowerBound, args.upperBound) #print(json.dumps(result, indent=4)) for entry in result: print(entry, end='\n')
def cli_linkTComplexity(): """Command line interface for linkTComplexity.""" info = 'Calculates total link, backlink, and forelink T code Complexity.' parser = argparse.ArgumentParser(description=info) parser.add_argument('linkograph', metavar='LINKOGRAPH.json', nargs=1, help='The linkograph.') # parser.add_argument('linkNumber', metavar='LINKS', # help=(r'List of links to consider.\n' # r'[1] -> backlinks.' # r'[2] -> forelinks.' # r'[1,2] -> both backlinks and forelinks.')) parser.add_argument('-f', '--forelinks', action='store_true', help='Use forelinks') parser.add_argument('-b', '--backlinks', action='store_true', help='Use backlinks') parser.add_argument('-d', '--delta', type=int, help=('Maximum number of links to consider' ' forward or backward.')) parser.add_argument('-r', '--restrict', action='store_true', help='Restrict to subgraph.') parser.add_argument('-l', '--lowerBound', type=int, help='The lowest index to consider.') parser.add_argument('-u', '--upperBound', type=int, help='The highest index to consider.') parser.add_argument('-n', '--normalize', action='store_true', help=('Normalize against T complexity lower' 'bound')) parser.add_argument('-a', '--absolute', action='store_true', help=('Gives the absolute deference between' 'T complexity and the lower bound')) parser.add_argument('-m', '--lineNumbers', action='store_true', help='Print node number.') args = parser.parse_args() linkNumber = [] if (args.forelinks): linkNumber.append(2) if (args.backlinks): linkNumber.append(1) if len(linkNumber) == 0: linkNumber = [1, 2] # Read in the linkograph. linko = linkoCreate.readLinkoJson(args.linkograph[0]) result = linkTComplexity(linko, linkNumber, args.delta, args.restrict, args.lowerBound, args.upperBound, args.lineNumbers, args.absolute, args.normalize) if args.lineNumbers: for entry in result: print(entry, end='\n') else: print(json.dumps(result, indent=4))
def cli_markov(): """Command line interface for creating markov chains.""" info = 'Creates a transition matrix from a linkograph.' parser = argparse.ArgumentParser(description=info) parser.add_argument('linkograph', metavar='LINKOGRAPH.json', nargs=1, help='The linkograph') parser.add_argument('-o', '--out', metavar='OUTPUT_FILE', help='Prints the result to a file.') parser.add_argument('-m', '--method', help='The method used to create the model.') parser.add_argument('-f', '--forelinks', action='store_true', help='Use forelinks') parser.add_argument('-b', '--backlinks', action='store_true', help='Use backlinks') parser.add_argument('-d', '--dot', action='store_true', help='Create dot file.') parser.add_argument('-l', '--latex', action='store_true', help='Create latex file.') parser.add_argument('-t', '--transition', action='store_true', help='Use transition matrix') parser.add_argument('-p', '--precision', type=int, help='Number of digits retained.') args = parser.parse_args() linkNum = 1 # For forelinks. if args.backlinks: linkNum = 0 # For backlinks. if args.precision is None: args.precision = 2 if args.method is None: args.method = 'link_predictor' linko = linkoCreate.readLinkoJson(args.linkograph[0]) markovChain = createMarkov(linko, linkNum=linkNum, method=args.method, precision=args.precision) if args.out is not None: fh = open(args.out, 'w') else: fh = sys.stdout if args.transition: fh.write(str(linko.labels)) fh.write('\n') fh.write(str(markovChain)) fh.write('\n') elif args.latex: latexString = markovToLatex(markovChain, linko.labels, args.precision) fh.write(latexString) else: # markovToDot(markovChain, linko.labels, fh, # args.precision) dotString = markovToDot(markovChain, linko.labels, args.precision) fh.write(dotString) fh.close()
def cli_genModelFromLinko(): """Command line interface for genModelFromLinko.""" info = """Generates a Markov model from a linkograph. There are two methods for generating the model: link_predictor and behavioral. The link_predictor method generates the probabilities based on the links and the behavioral method generates the probabilities based on the following or preceeding event. """ parser = argparse.ArgumentParser(description=info) parser.add_argument('linko', metavar='LINKOGRAPH.json', help='The linkograph to learn from.') parser.add_argument('-m', '--model', metavar='MODEL.json', help='File name to store model to.') parser.add_argument('-o', '--ontology', metavar='ONTOLOGY.json', help='Add an associated ontology.') parser.add_argument('-p', '--precision', metavar='PRECISION', type=int, default=2, help=('Number of decimal places to use in' ' probabilities.')) parser.add_argument('-b', '--backward', action='store_true', help=('Consider back links or previous' ' steps')) parser.add_argument('--method', metavar='METHOD', default='link_predictor', help="Methods are 'link_predictor' or 'behavioral'") parser.add_argument('-s', '--seed', metavar='SEED', type=float, default=None, help=('Seeed for models internal random' ' number generator.')) args = parser.parse_args() linko = lc.readLinkoJson(args.linko) ont = None if args.ontology is not None: with open(args.ontology, 'r') as ontFile: ont = json.load(ontFile) linkNum = 1 if args.backward: linkNum = 0 model = genModelFromLinko(linko, precision=args.precision, ontology=ont, seed=args.seed, method=args.method, linkNum=linkNum) if args.model is not None: writeJson(model, args.model) else: print(model)
# If a path is provided, add it to the path import sys import os sys.path.append(args.path) # Import the linkograph packages. They are loaded here, to # provided the ability of adding the their path on the command # line. import linkograph.linkoCreate as llc # For manipulating linkographs import linkograph.stats as ls # For linkograph statistics # Set the max and min subgraph size to the specified size. minSize = maxSize = args.graphSize # Get the linkograph linko = llc.readLinkoJson(args.linko) # Calcualte the graph Shannon Entropy for the whole linkograph totalEntropy = ls.graphEntropy(linko) # Calcualte the graph Shannon Entropy for subgraphs. subEntropies = ls.subgraphMetric(linkograph=linko, metric=ls.graphEntropy, lowerThreshold=None, upperThreshold=None, minSize=minSize, maxSize=maxSize, step=args.step, lowerBound=args.lowerBound, upperBound=args.upperBound)
def cli_linkoDrawSVG(): """Draws the linkograph in SVG format.""" info = 'Draws the linkograph in SVG format.' parser = argparse.ArgumentParser(description=info) parser.add_argument('linkograph', metavar='LINKOGRAPH.json', nargs=1, help='The linkograph to draw.') parser.add_argument('out', metavar='OUTPUT_FILE', nargs=1, help='The output file.') parser.add_argument('-c', '--commands', metavar='COMMANDS.json', help='The commands json for the linkograph.') parser.add_argument('-s', '--suppress', action='store_false', help='Suppress the labels') parser.add_argument('-n', '--noNumbers', action='store_false', help='Suppress the line numbers.') parser.add_argument('--dotRadius', type=float, default=3, help='Controls the dot radius.') parser.add_argument('--circWidth', type=float, default=3, help='Controls the dot radius.') parser.add_argument('--step', type=float, default=10, help='Controls the length of the line segments.') parser.add_argument('--lineWidth', type=float, default=2, help='Controls the width of the line segments.') parser.add_argument('--leftOffset', type=float, default=2, help='Increase the left margin.') parser.add_argument('--labelDist', type=float, default=10, help=('Contols the label horizontal offset.')) parser.add_argument('--labelBase', type=float, default=5, help='Controls the label veritical offset.') args = parser.parse_args() # Read in the linkograph linko = linkoCreate.readLinkoJson(args.linkograph[0]) # Read in the commands if present. commands=None if args.commands is not None: with open(args.commands, 'r') as commandFile: commands = json.load(commandFile) svg = linkoDrawSVG(linko,labels= args.suppress, lineNumbers=args.noNumbers, commands=commands, dotRadius=args.dotRadius, circWidth=args.circWidth, step=args.step, lineWidth=args.lineWidth, leftOffset=args.leftOffset, labelDist=args.labelDist, labelBase=args.labelBase) with open(args.out[0], 'w') as svgFile: svgFile.write(svg)
lineNumbers=args.noNumbers, commands=commands, dotRadius=args.dotRadius, circWidth=args.circWidth, step=args.step, lineWidth=args.lineWidth, leftOffset=args.leftOffset, labelDist=args.labelDist, labelBase=args.labelBase) with open(args.out[0], 'w') as svgFile: svgFile.write(svg) ###################################################################### if __name__ == '__main__': import linkoCreate linko = linkoCreate.readLinkoJson('example.json') linkoDrawSVG(linko, 'example.html') print(linko) print('done')
sizes = range(args.delta_min, args.delta_max + 1, args.delta_step) ncols = min(len(args.linkos), args.graph_group_size) for first_link_index in range(0, len(args.linkos), args.graph_group_size): series = args.linkos[first_link_index:(first_link_index + args.graph_group_size)] step_mult = first_link_index / args.graph_group_size plt.figure(step_mult + 1, figsize=(20, 10)) for series_number, linko_name in enumerate(series): # Get the linkograph. linko = llc.readLinkoJson(linko_name) # Plot the values for the linkograph. _plot_metrics(linko=linko, linkNumber=linkNumber, sizes=sizes, restrict=args.restrict, lowerBound=args.lowerBound, upperBound=args.upperBound, series_name=linko_name, nrows=3, ncols=len(series), series_number=series_number + 1) plt.tight_layout()
def load(linkoNames): """Load the linkographs.""" # Load the data linkos = [lc.readLinkoJson(lName) for lName in linkoNames] return linkos
def cli_linkSlicePercents(): """Command line interface for linkSlicePercents.""" info = 'Calculates total link, backlink, and forelink T code Complexity.' parser = argparse.ArgumentParser(description=info) parser.add_argument('linkograph', metavar='LINKOGRAPH.json', nargs=1, help='The linkograph.') parser.add_argument('-f', '--forelinks', action='store_true', help='Use forelinks') parser.add_argument('-b', '--backlinks', action='store_true', help='Use backlinks') parser.add_argument('-d', '--delta', type=int, help=('Maximum number of links to consider' ' forward or backward.')) parser.add_argument('-r', '--restrict', action='store_true', help='Restrict to subgraph.') parser.add_argument('-l', '--lowerBound', type=int, help='The lowest index to consider.') parser.add_argument('-u', '--upperBound', type=int, help='The highest index to consider.') parser.add_argument('-m', '--lineNumbers', action='store_true', help='Print node number.') args = parser.parse_args() linkNumber = [] if (args.forelinks): linkNumber.append(2) if (args.backlinks): linkNumber.append(1) if len(linkNumber) == 0: linkNumber = [1, 2] # Read in the linkograph. linko = linkoCreate.readLinkoJson(args.linkograph[0]) result = linkSlicePercents(linko, linkNumber, args.delta, args.restrict, args.lowerBound, args.upperBound, args.lineNumbers) if args.lineNumbers: for entry in result: print(entry, end='\n') else: print(json.dumps(result, indent=4))