def print_charts(dataset, title, weekday=False): """ Prints nice charts based on a dict {(key, value), ...} """ chart = [] keys = sorted(dataset.keys()) mean = numpy.mean(list(dataset.values())) median = numpy.median(list(dataset.values())) for key in keys: if (dataset[key] >= median * 1.33): displayed_key = "%s (\033[92m+\033[0m)" % (int_to_weekday(key) if weekday else key) elif (dataset[key] <= median * 0.66): displayed_key = "%s (\033[91m-\033[0m)" % (int_to_weekday(key) if weekday else key) else: displayed_key = (int_to_weekday(key) if weekday else key) chart.append((displayed_key, dataset[key])) thresholds = { int(mean): Gre, int(mean * 2): Yel, int(mean * 3): Red, } data = hcolor(chart, thresholds) graph = Pyasciigraph( separator_length=4, multivalue=False, human_readable='si', ) for line in graph.graph(title, data): print(line) print("")
def print_graph(dataset, title): graph = Pyasciigraph( separator_length=4, multivalue=False, human_readable='si', ) chart = [] keys = sorted(dataset.keys()) mean = np.mean(list(dataset.values())) # median = np.median(list(dataset.values())) for key in keys: chart.append((key, dataset[key])) if (not args.no_color): thresholds = { int(mean): Gre, int(mean * 2): Yel, int(mean * 3): Red, } data = hcolor(chart, thresholds) else: data = chart for line in graph.graph(title, data): print(line)
def show_index(self): graphArray = [] for coin in IndexedCoinModel.select(): graphArray.append((coin.Ticker, coin.DesiredPercentage)) pyGraph = Pyasciigraph(line_length=50, min_graph_length=50, separator_length=4, multivalue=False, human_readable='si', graphsymbol='*', float_format='{0:,.2f}') thresholds = { 15: Gre, 30: Blu, 50: Yel, 60: Red, } data = hcolor(graphArray, thresholds) sys.stdout.write("\n") for line in pyGraph.graph('Index Distribution', data=data): sys.stdout.write(line + "\n") sys.stdout.write("\n")
def print_charts(dataset, title, args, weekday=False): chart = [] keys = sorted(dataset.keys()) mean = numpy.mean(list(dataset.values())) median = numpy.median(list(dataset.values())) for key in keys: if dataset[key] >= median * 1.33: displayed_key = "%s (\033[92m+\033[0m)" % (int_to_weekday(key) if weekday else key) elif dataset[key] <= median * 0.66: displayed_key = "%s (\033[91m-\033[0m)" % (int_to_weekday(key) if weekday else key) else: displayed_key = (int_to_weekday(key) if weekday else key) chart.append((displayed_key, dataset[key])) thresholds = { int(mean): Gre, int(mean * 2): Yel, int(mean * 3): Red, } data = hcolor(chart, thresholds) graph = Pyasciigraph( separator_length=4, multivalue=False, human_readable='si', ) for line in graph.graph(title, data): if args.no_color: ansi_escape = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]') line = ansi_escape.sub('', line) print(line) print("")
def graph_thresholds(test_data): # H color test # Multicolor on one line print('\nMultiColor example:') # Color lines according to Thresholds thresholds = { 51: Gre, 100: Blu, 350: Yel, 500: Red, } data = hcolor(test_data, thresholds) # graph with colors, power of 1000, different graph symbol, # float formatting and a few tweaks graph = Pyasciigraph( line_length=120, min_graph_length=50, separator_length=4, multivalue=True, human_readable='si', graphsymbol='*', # comment out if you want to use solid bars float_format='{0:,.2f}', force_max_value=2000, ) for line in graph.graph(label='With Thresholds', data=data): print(line) return graph, data
def plot_bars(label, data, sym=None, threshs=None): # float formatting and a few tweaks graph = Pyasciigraph(line_length=100, min_graph_length=50, separator_length=10, multivalue=False, human_readable='si', graphsymbol=sym, float_format='{0:,.2f}') if threshs: data = hcolor(data, threshs) for line in graph.graph(label=label, data=data): print(line)
def print_charts(dataset, title, weekday=False): """ Prints nice charts based on a dict {(key, value), ...} """ chart = [] keys = sorted(dataset.keys()) mean = numpy.mean(list(dataset.values())) median = numpy.median(list(dataset.values())) if args.json is False: export_string(title) for key in keys: if (dataset[key] >= median * 1.33): displayed_key = "%s (\033[92m+\033[0m)" % (int_to_weekday(key) if weekday else key) elif (dataset[key] <= median * 0.66): displayed_key = "%s (\033[91m-\033[0m)" % (int_to_weekday(key) if weekday else key) else: displayed_key = (int_to_weekday(key) if weekday else key) if args.json is False: export_string("%s - %s" % (dataset[key], (int_to_weekday(key) if weekday else key))) chart.append((displayed_key, dataset[key])) thresholds = { int(mean): Gre, int(mean * 2): Yel, int(mean * 3): Red, } data = hcolor(chart, thresholds) graph = Pyasciigraph( separator_length=4, multivalue=False, human_readable='si', ) if args.json is False: for line in graph.graph(title, data): if not color_supported: ansi_escape = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]') line = ansi_escape.sub('', line) print(line) cprint("")
def xplot(NAMES, DATA, LABEL=None): thresholds = { .9: BIWhi, .6: BIBlu, .1: Blu, } graph = Pyasciigraph( line_length=50, min_graph_length=50, separator_length=5, multivalue=False, #graphsymbol='*' ) for line in graph.graph(label=LABEL, data=hcolor([(NAMES[i], DATA[i]) for i in np.arange(len(NAMES))], thresholds)): print(line)
def plotfi(MODELimp): sys.stdout.write(BOLD) thresholds = { 9: BIWhi, 8: BIBlu, 6: Blu, 4: Bla, 2: BIBla, } graph = Pyasciigraph( line_length=70, min_graph_length=50, separator_length=10, multivalue=False, #graphsymbol='*' ) for line in graph.graph( label='Feature Importance (GINI)', data=hcolor([(MODELimp.feature[i], MODELimp.MeanDecreaseGini[i]) for i in MODELimp.head(10).index], thresholds)): print(line) sys.stdout.write(RESET) return
graph = Pyasciigraph(line_length=55, min_graph_length=50, separator_length=4, multivalue=False, human_readable='si', graphsymbol='*', float_format='{0:,.2f}', force_max_value=90) pattern = [Gre, Yel, Red] thresholds = { 51: Gre, 60: Blu, 65: Yel, 70: Red, } if __name__ == "__main__": while True: timeNow = time.time() if timeNow - timeStart > 1: temps = getTemps() data = [('core1', temps[0]), ('core2', temps[1]), ('core3', temps[2]), ('core4', temps[3])] data = hcolor(data, thresholds) #data = vcolor(data, pattern) timeStart = time.time() subprocess.call("clear", shell=True) for line in graph.graph('Temps', data): print(line)
def stats(self): """ Print some useful stats about the database. """ if self.args.get('list'): print_notify( str(len(self.db.list_collection_names())) + ' collections found in database:\n') collstats_list = [] for name in self.db.list_collection_names(): collstats_list.append(self.db.command('collstats', name)) collstats_list[-1]['name'] = name collstats_list = sorted(collstats_list, key=lambda k: k['count'], reverse=True) print("\t{:^20}\t{:^20}".format('Name', 'Number of structures')) for collection in collstats_list: if not collection['name'].startswith('__'): print("\t{:<20}\t{:>20d}".format(collection['name'], collection['count'])) print('\n') elif self.args.get('delete'): target = self.args.get('db') if isinstance(target, list) and len(target) == 1: target = target[0] else: raise SystemExit( 'I will only delete one collection at a time...') if target is None: raise SystemExit('Please specify a collection to delete.') if target not in self.db.list_collection_names(): raise SystemExit( 'No collection named {} was found'.format(target)) from getpass import getuser user = getuser() if user not in target: raise SystemExit( 'I cannot delete a collection that\'s name does not start with ' 'your username, {}'.format(user)) stats = self.db.command('collstats', target) if self.args.get('no_quickstart'): answer = 'y' else: answer = input( 'Are you sure you want to delete collection {} containing {} ' 'structures? [y/n]\n'.format(target, stats['count'])) if answer.lower() == 'y': if target == 'repo': raise SystemExit( 'I\'m sorry Dave, I\'m afraid I can\'t do that...') print('Deleting collection {}...'.format(target)) self.db[target].drop() print('and its changelog...') self.db['__changelog_{}'.format(target)].drop() else: raise SystemExit('Nevermind then!') else: comp_list = dict() stats_dict = dict() stats_dict['count'] = 0 stats_dict['avgObjSize'] = 0 stats_dict['storageSize'] = 0 stats_dict['totalIndexSize'] = 0 for collection in self.collections: db_stats_dict = self.db.command('collstats', collection) stats_dict['count'] += db_stats_dict['count'] stats_dict['avgObjSize'] += db_stats_dict['avgObjSize'] stats_dict['storageSize'] += db_stats_dict['storageSize'] stats_dict['totalIndexSize'] += db_stats_dict['totalIndexSize'] print(( "The collection(s) queried in {} contain {} structures at {:.1f} kB each " "totalling {:.1f} MB with a further {:.1f} MB of indexes." ).format(self.db.name, stats_dict['count'], stats_dict['avgObjSize'] / (1024), stats_dict['storageSize'] / (1024**2), stats_dict['totalIndexSize'] / (1024**2))) for collname in self.collections: cursor = self.collections[collname].find() for doc in cursor: temp = '' for ind, elem in enumerate(sorted(doc['stoichiometry'])): temp += str(elem[0]) if ind != len(doc['stoichiometry']) - 1: temp += '+' if temp not in comp_list: comp_list[temp] = 0 comp_list[temp] += 1 keys = list(comp_list.keys()) vals = list(comp_list.values()) comp_list = list(zip(keys, vals)) comp_list.sort(key=lambda t: t[1], reverse=True) small_count = 0 first_ind = 1000 cutoff = 100 for ind, comp in enumerate(comp_list): if comp[1] < cutoff: if ind < first_ind: first_ind = ind small_count += comp[1] comp_list = comp_list[:first_ind] comp_list.append(['others < ' + str(cutoff), small_count]) comp_list.sort(key=lambda t: t[1], reverse=True) try: from ascii_graph import Pyasciigraph from ascii_graph.colors import Gre, Blu, Red from ascii_graph.colordata import hcolor except ImportError: print( "ascii_graph dependency not found, not creating histogram." ) else: graph = Pyasciigraph(line_length=80, multivalue=False) thresholds = { int(stats_dict['count'] / 40): Gre, int(stats_dict['count'] / 10): Blu, int(stats_dict['count'] / 4): Red } data = hcolor(comp_list, thresholds) for line in graph.graph(label=None, data=data): print(line) print('\n') for comp in comp_list: print(comp)
# Multicolor with all the values displayed graph = Pyasciigraph(separator_length=4, human_readable='cs') for line in graph.graph('test graph', test): print(line) # Multicolor with only the max value displayed graph = Pyasciigraph(separator_length=4, multivalue=False, human_readable='cs') for line in graph.graph('test graph mono value', test): print(line) # Coloring data according to thresholds from ascii_graph.colordata import hcolor test = [('testval0', 6003), ('testval1', 900), ('testval2', 4920), ('testval3', 400), ('testval4', 30), ('testval5', 200), ('testval6', 1025), ('testval7', 5023)] thresholds = { 51: Gre, 100: Blu, 350: Yel, 500: Red, } data = hcolor(test, thresholds) for line in graph.graph('hcolor test', data): print(line) exit(0)
# Multicolor with only the max value displayed graph = Pyasciigraph(separator_length=4, multivalue=False) for line in graph.graph('test graph mono value', test): print(line) # Coloring data according to thresholds from ascii_graph.colordata import hcolor test = [('testval0', 600), ('testval1', 500), ('testval2', 400), ('testval3', 400), ('testval4', 300), ('testval5', 200), ('testval6', 100), ('testval7', 50 )] thresholds = { 51: Gre, 100: Blu, 350: Yel, 500: Red, } data = hcolor(test, thresholds) for line in graph.graph('hcolor test', data): print(line) exit(0)
def top(podName, namespaceName, cmdString, isAllNamespaces=False, doAsciiGraph=False): output = getTop(podName, namespaceName, cmdString, isAllNamespaces) topOutput = output if doAsciiGraph == True: from ascii_graph import Pyasciigraph from ascii_graph.colors import Gre, Yel, Red from ascii_graph.colordata import vcolor from ascii_graph.colordata import hcolor graphSymbol = '*' titleBarSymbol = '-' graph = Pyasciigraph(titlebar=titleBarSymbol, graphsymbol=graphSymbol) output = "" #get data from top output cpuUsage = [] memoryUsage = [] cpuUsagePercentForNode = [] memoryUsagePercentForNode = [] lines = topOutput.split("\n")[1:] podName = None for line in lines: if (len(line) == 0): continue fields = line.split() if cmdString.find("-c") > -1: podName = fields[0] cpuUse = (fields[1], int(fields[2].replace("m", ""))) memUse = (fields[1], int(fields[3].replace("Mi", ""))) elif cmdString.find("-n") > -1: #nodes, must be before isAllNamespaces check cpuUse = (fields[0], int(fields[1].replace("m", ""))) memUse = (fields[0], int(fields[3].replace("Mi", ""))) cpuUsagePercentForNode.append( (fields[0], int(fields[2].replace("%", "")))) memoryUsagePercentForNode.append( (fields[0], int(fields[4].replace("%", "")))) elif isAllNamespaces == True: rowTitle = "%s/%s" % (fields[0], fields[1]) cpuUse = (rowTitle, int(fields[2].replace("m", ""))) memUse = (rowTitle, int(fields[3].replace("Mi", ""))) else: cpuUse = (fields[0], int(fields[1].replace("m", ""))) memUse = (fields[0], int(fields[2].replace("Mi", ""))) cpuUsage.append(cpuUse) memoryUsage.append(memUse) cpuTitle = 'CPU (millicores)' if podName != None: cpuTitle = "%s - %s" % (cpuTitle, podName) for line in graph.graph(cpuTitle, cpuUsage): output = output + line + "\n" memTitle = 'Memory (Mi bytes)' if podName != None: memTitle = "%s - %s" % (memTitle, podName) output = output + "\n" for line in graph.graph(memTitle, memoryUsage): output = output + line + "\n" if cmdString.find("-n") > -1: #add percents for nodes pattern = [Gre, Yel, Red] # Color lines according to Thresholds thresholds = {0: Gre, 50: Yel, 80: Red} data = hcolor(cpuUsagePercentForNode, thresholds) graph = Pyasciigraph(force_max_value=100, titlebar=titleBarSymbol, graphsymbol=graphSymbol) data = cpuUsagePercentForNode output = output + "\n" cpuTitle = 'CPU (%)' for line in graph.graph(cpuTitle, data): output = output + line + "\n" output = output + "\n" memTitle = 'Memory (%)' for line in graph.graph(memTitle, memoryUsagePercentForNode): output = output + line + "\n" return output