Last active
January 21, 2025 01:53
-
-
Save dgulino/3373d75bcfea56fd42346fc0404dd30c to your computer and use it in GitHub Desktop.
ncurses numerical plotter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# Copyright 2021 Drew Gulino | |
# #This program is free software; you can redistribute it and/or modify | |
# # it under the terms of the GNU General Public License as published by | |
# # the Free Software Foundation; either version 2 of the License, or | |
# # (at your option) any later version. | |
# # | |
# # This program is distributed in the hope that it will be useful, | |
# # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
# # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
# # GNU General Public License for more details. | |
# # | |
# # You should have received a copy of the GNU General Public License | |
# # along with this program; if not, write to the Free Software | |
# # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA | |
import sys | |
import os | |
import getopt | |
import time | |
import math | |
from getopt import GetoptError | |
from blessings import Terminal | |
example_output = ''' | |
./generate_random.py | ./ngraph.py -p -t 500 -m 1000 | |
20:51:23 139.7 ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ | |
20:51:24 289.0 ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ | |
20:51:24 197.7 ████████████████████████████████████████████████▉ | |
20:51:24 293.0 ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ | |
20:51:24 35.7 ███████▉ | |
20:51:24 468.0 ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ | |
20:51:25 288.7 ████████████████████████████████████████████ | |
20:51:25 662.0 ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ | |
20:51:25 91.3 █████████ | |
min:35 avg:273.89 max:662 | |
''' | |
class Ngraph: | |
def __init__(self, display_number, threshold, minimum, maximum, | |
timestamp, diff): | |
self.reset = os.popen('tput sgr0').read() | |
self.minimum = minimum | |
self.maximum = maximum | |
self.max_digits = 0 | |
self.displayed_max_digits = 0 | |
self.display_number = display_number | |
self.threshold = threshold | |
self.timestamp = timestamp | |
self.diff = diff | |
self.oldnum = 0.0 | |
self.first_num = True | |
self.term= Terminal() | |
self.full_block = '\u2588' #full block | |
self.medium_shade = '\u2592' | |
self.whole_char = self.full_block | |
self.ts_characters = 0 | |
def __del__(self): | |
sys.stdout.write(self.reset) | |
def partial_lookup(self,remainder): | |
code = { | |
1: '\u258F', | |
2: '\u258E', | |
3: '\u258D', | |
4: '\u258C', | |
5: '\u258B', | |
6: '\u258A', | |
7: '\u2589' | |
} | |
return code.get(remainder) | |
def graph(self, nums, avg): | |
for num in nums: | |
if self.diff: | |
new_oldnum = num | |
num = num - self.oldnum | |
self.oldnum = new_oldnum | |
if self.first_num: | |
self.first_num = False | |
continue | |
if not self.minimum: | |
self.minimum = num | |
else: | |
if num < self.minimum: | |
self.minimum = num | |
if num > self.maximum: | |
self.maximum = num | |
self.whole_char = self.medium_shade | |
else: | |
self.whole_char = self.full_block | |
with self.term.location(0, self.term.height - 2): | |
if num > 0.0: | |
digits = 0 | |
if type(num) is float: | |
digits = len(f"{num:.1f}") | |
elif type(num) is int: | |
digits = len(f"{num:d}") | |
if digits > self.max_digits: | |
self.max_digits = digits | |
if num > self.maximum: | |
bold = self.term.bold | |
else: | |
bold = '' | |
color = self.term.normal | |
if self.threshold > 0: | |
if num >= self.threshold: | |
color = self.term.red | |
else: | |
color = '' | |
if self.timestamp: | |
ts = time.strftime("%H:%M:%S ") | |
self.ts_characters = len(ts) | |
print(ts,end='') | |
scale = float( ((self.term.width - self.max_digits - self.ts_characters) * 8)/ self.maximum) | |
else: | |
scale = float( ((self.term.width - self.max_digits) * 8 )/ self.maximum) | |
scaled_num = float(num * scale) | |
displayed_max_digits = -1 | |
if self.display_number: | |
if type(num) is float: | |
print(bold + f"{num:>{self.max_digits}.1f} ",end='') | |
displayed_max_digits = self.max_digits | |
elif type(num) is int: | |
print(bold + f"{num:>{self.max_digits}d} ",end='') | |
displayed_max_digits = self.max_digits | |
num_whole_blocks = math.floor(scaled_num / 8) - 1 | |
remainder = int(scaled_num % 8) | |
for _ in range(0,num_whole_blocks): | |
print(bold + color + self.whole_char, end='') # bar chart | |
if remainder != 0: | |
partial_char = self.partial_lookup(remainder) | |
print(bold + color + str(partial_char), end='') | |
for _ in range(0,self.term.width - num_whole_blocks - displayed_max_digits - self.ts_characters - 2): | |
print(" ",end='') | |
else: | |
for _ in range(0,self.term.width - num_whole_blocks - displayed_max_digits - self.ts_characters - 1): | |
print(" ",end='') | |
else: | |
if self.timestamp: | |
ts = time.strftime("%H:%M:%S ") | |
print(self.term.normal + ts,end='') | |
if self.display_number: | |
sys.stdout.write(str(num)) | |
print(self.term.normal,flush=True) | |
if self.display_number: | |
with self.term.location(self.ts_characters + self.max_digits + 1, self.term.height - 1): | |
print(f"min:{int(self.minimum)}", end='') | |
else: | |
with self.term.location(self.ts_characters + 0, self.term.height - 1): | |
print(f"min:{int(self.minimum)}", end='') | |
with self.term.location(self.ts_characters + int(self.term.width / 2), self.term.height - 1): | |
print(f"avg:{avg:.2f}", end='') | |
with self.term.location(self.term.width - self.max_digits - 4, self.term.height - 1): | |
print(f"max:{int(self.maximum)}") | |
def usage(progname): | |
print("Usage: " + progname) | |
version() | |
print("[-h --help]") | |
print("[-v --version]") | |
print("[-n --no_number] Don't display number w/graph") | |
print("[-t --threshold=] Will color lines over this value") | |
print( | |
"[-m --maximum=] Presets the scale for this maximum value(default = 0)" | |
) | |
print( | |
"[-p --timestamp] Print local hour:min:sec timestamp per line (default = False)" | |
) | |
print( | |
"[-r --diff] subtract previous entry to track always increasing values" | |
) | |
print( | |
"[--numeric_type] Force how to display numbers: int or float (default = False)" | |
) | |
def version(): | |
print("version: 1.0") | |
def main(argv, stdout, environ): | |
progname = argv[0] | |
display_number = True | |
threshold = 0 | |
maximum = 0 | |
minimum = False | |
timestamp = False | |
delimiter = " " | |
diff = False | |
numeric_type = False | |
try: | |
arglist, args = getopt.getopt(argv[1:], "hvnpt:m:d:", [ | |
"help", "version", "no_number", "timestamp", "diff", | |
"threshold=", "maximum=", "minimum=", "delimiter=", "numeric_type=" | |
]) | |
except GetoptError: | |
print("Invalid Option!") | |
usage(progname) | |
return | |
# Parse command line arguments | |
for field, val in arglist: | |
if field in ("-h", "--help"): | |
usage(progname) | |
return | |
elif field in ("-v", "--version"): | |
version() | |
return | |
elif field in ("-n", "--number"): | |
display_number = False | |
elif field in ("-p", "--timestamp"): | |
timestamp = True | |
elif field in ("-r", "--diff"): | |
diff = True | |
elif field in ("-t", "--threshold"): | |
threshold = float(val) | |
elif field in ("-m", "--maximum"): | |
maximum = float(val) | |
elif field in ("-i", "--minimum"): | |
minimum = float(val) | |
elif field in ("-d", "--delimiter"): | |
delimiter = val | |
elif field in ("--numeric_type"): | |
if val == "int": | |
numeric_type = int | |
elif val == "float": | |
numeric_type = float | |
ngraph = Ngraph(display_number, threshold, maximum, minimum, | |
timestamp, diff) | |
main_loop(ngraph, delimiter, numeric_type=numeric_type) | |
def number_string(NumberString): | |
if NumberString.isdigit(): | |
Number = int(NumberString) | |
else: | |
Number = float(NumberString) | |
return Number | |
def convert_to_number(s): | |
"""Converts a string to an int or float if possible. | |
Args: | |
s: The string to convert. | |
Returns: | |
The converted number, or the original string if conversion is not possible. | |
""" | |
try: | |
return int(s) | |
except ValueError: | |
return float(s) | |
def average_generator(): | |
total = 0 | |
count = 0 | |
while True: | |
value = yield | |
if value is None: | |
break | |
total += value | |
count += 1 | |
yield total / count | |
def main_loop(ngraph, delimiter, numeric_type): | |
avg = 0.0 | |
avg_gen = average_generator() # Create a generator object | |
next(avg_gen) # Start the generator | |
while 1: | |
try: | |
numbers = sys.stdin.readline().split(delimiter) | |
if len(numbers) < 1: | |
break | |
if numeric_type: | |
numbers = [numeric_type(number.strip()) for number in numbers] | |
else: | |
numbers = [convert_to_number(number.strip()) for number in numbers] | |
# Append numbers and calculate the running average | |
for num in numbers: | |
avg = avg_gen.send(num) | |
except ValueError: | |
continue | |
except KeyboardInterrupt: | |
print("Stopped with keyboard input") | |
break | |
ngraph.graph(numbers, avg) | |
if len(numbers) > 1: | |
sys.stdout.write("\n") | |
sys.stdout.flush() | |
avg_gen.send(None) | |
if __name__ == "__main__": | |
main(sys.argv, sys.stdout, os.environ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment