コード例 #1
0
ファイル: dx_status.py プロジェクト: praveen8735/awsrun
def _print_conn_metrics(
    conn, metrics, height=1, prefix="", auto_yaxis=True, file=sys.stdout
):
    colors = [Fore.RED, Fore.CYAN, Fore.CYAN]

    for name, get_values in metrics.items():
        values = [value for timestamp, value in get_values()]

        if name == "ConnectionState":
            max_yaxis = 1
        elif auto_yaxis:
            max_yaxis = None
        else:
            max_yaxis = bps(conn["bandwidth"])

        if height == 1:
            chart = sparkify(values, minimum=0, maximum=max_yaxis)
            print(prefix, end=" ", file=file)

        elif height > 1:
            opts = {
                "minimum": 0,
                "height": height,
                "format": "{:14,.0f} ",
            }
            # The asciichartpy module is a bit wonky and not really idiomatic
            # python as they just pass a giant dictionary of options (typical of
            # javascript land). Do not provide a "maximum" key with a value of
            # None. If use wants auto-scaling, don't provide the key at all.
            if max_yaxis is not None:
                opts["maximum"] = max_yaxis

            chart = plot(values, opts)
        print(_format_metric(name, chart, color=colors.pop()), file=file)
    print(file=file)
コード例 #2
0
def get_risk_graph(id: str) -> None:
    """Prints a graph of an extension's risk scores over time.

    Args:
        id: An extension identifier string.

    Returns:
        None.
    """
    results = get_report(id)

    if len(results) == 0:
        error(f"No results were found for {id}.", True)

    data = []
    for item in results:
        data.append(item["data"]["risk"]["total"])

    print(
        asciichartpy.plot(
            data,
            {
                "min": min(data) - 5,
                "max": max(data) + 5,
                "height": 25,
                "format": "{:8.0f}",
            },
        ))
コード例 #3
0
def main():
    final_games = []
    archives = get_archives()
    for archive in archives:
        final_games += get_filtered_games(archive)
        if len(final_games) >= NGAMES:
            break
    final_games = final_games[:NGAMES]
    ratings_list = get_ratings_from_games(final_games)
    return (ac.plot(ratings_list, {'height': 15}))
コード例 #4
0
    def gui(self, scr):
        scr.clear()
        rows, columns = os.popen('stty size', 'r').read().split()
        rows = int(rows)
        columns = int(columns)

        plot_width = int(columns * 0.8)
        deque_dir = collections.deque([0] * plot_width, maxlen=plot_width)
        deque_speed = collections.deque([0] * plot_width, maxlen=plot_width)

        while (True):
            value = self.tmp.value * 5.0
            direction = self.map_direction(value)
            deque_dir.popleft()
            deque_speed.popleft()
            deque_dir.append(direction)
            deque_speed.append(self.speed)
            scr.addstr(0, 0, 'DIRECTION')
            scr.addstr(
                2, 0,
                plot(deque_dir, {
                    'minimum': 0.0,
                    'maximum': 360.0,
                    'height': 16
                }))
            scr.addstr(20, 0, 'SPEED')
            scr.addstr(
                22, 0,
                plot(deque_speed, {
                    'minimum': 0.0,
                    'maximum': 20,
                    'height': 20
                }))
            scr.refresh()
            publish.single(self.mqtt_path,
                           self.build_json_package(direction, self.speed),
                           hostname=self.mqtt_server)
            sleep(self.send_sleep)
コード例 #5
0
ファイル: debugger.py プロジェクト: ri0t/isomer
    def cli_mem_chart(self, *args):
        """Output memory consumption chart"""

        # Subtract 11 columns for the chart axis
        width = shutil.get_terminal_size().columns - 11

        config = {
            'colors': [
                asciichartpy.blue,
                asciichartpy.red
            ],
            'height': 10,
            'format': '{:6.0f}kB'
        }

        total_length = len(self.size_diffs)

        try:
            count = int(args[-1])
        except (TypeError, ValueError, IndexError):
            count = total_length

        if count > total_length:
            self.log('Only %i measurements available!' % total_length, lvl=warn)
            count = total_length

        if count > width:
            self.log('Clipping %i values due to terminal width of only '
                     '%i columns!' % (count - width, width), lvl=warn)
            count = width

        size_k = [x / 1024.0 for x in islice(
            self.size_diffs, len(self.size_diffs) - count, len(self.size_diffs)
        )]

        if len(args) > 0:
            if "-o" in args:
                size_k.pop(0)

        length = len(size_k)

        self.log(
            "Memory consumption (%i measurements, "
            "%i seconds interval, %3.0f minutes total)" % (
                length,
                self.interval,
                (length * self.interval / 60.0)
            )
        )
        self.log("\n%s" % asciichartpy.plot(size_k, config), nc=True)
コード例 #6
0
def updateChart(exchange, symbol, tf, height):
    store = Arctic('localhost')
    library = store[exchange.upper()]

    startDate = pd.to_datetime('today') - timedelta(days=5)
    endDate = startDate + timedelta(days=7)
    startDate = startDate.strftime("%Y-%m-%d")
    endDate = endDate.strftime("%Y-%m-%d")
    readStr = 'trades-' + str(symbol)

    item = library.read(readStr, chunk_range=pd.date_range(startDate,
                                                           endDate)).copy()

    df = item.price.resample(tf).agg({
        'open': 'first',
        'high': 'max',
        'low': 'min',
        'close': 'last'
    })
    df = df.fillna(method='ffill')
    chart = plot(df.close.tail(60), {'height': height})

    priceStr = str(item.price.iat[-1])
    if (item.price.iat[-1] < item.price.iat[-2]):
        priceStr = Fore.RED + priceStr
    else:
        priceStr = Fore.GREEN + priceStr
    priceStr = priceStr + Style.RESET_ALL

    exchangeStr = exchange
    if (exchangeStr == "Bitfinex"):
        exchangeStr = Fore.GREEN + exchangeStr
    elif (exchangeStr == "Coinbase"):
        exchangeStr = Fore.BLUE + exchangeStr
    exchangeStr = exchangeStr + Style.RESET_ALL
    exchangeStr = exchange
    if (exchangeStr == "Bitfinex"):
        exchangeStr = Fore.GREEN + exchangeStr
    elif (exchangeStr == "Coinbase"):
        exchangeStr = Fore.BLUE + exchangeStr
    exchangeStr = exchangeStr + Style.RESET_ALL

    os.system('clear')
    print(f'Exchange: {exchangeStr}')
    print(f'Symbol: {symbol}')
    print(f'Timeframe: {tf}')
    print(f'Price: {priceStr}')
    print(f'{chart}')
    time.sleep(15)
コード例 #7
0
ファイル: basic-chart.py プロジェクト: mukedian0/homiex-ccxt
def print_chart(exchange, symbol, timeframe):

    print("\n" + exchange.name + ' ' + symbol + ' ' + timeframe + ' chart:')

    # get a list of ohlcv candles
    ohlcv = exchange.fetch_ohlcv(symbol, timeframe)

    # get the ohlCv (closing price, index == 4)
    series = [x[index] for x in ohlcv]

    # print the chart
    print("\n" + plot(series[-120:], {'height': 20}))  # print the chart

    last = ohlcv[len(ohlcv) - 1][index]  # last closing price
    return last
コード例 #8
0
def analyze_file(service, file_id, file_name, dt):
    groupby_freq = '10s'
    seconds = (dt.index.max() - dt.index.min()).total_seconds()
    if seconds > 90 * 60:
        groupby_freq = '1 min'
    if seconds > 30 * 60:
        groupby_freq = '30s'
    elif seconds > 30 * 60:
        groupby_freq = '10s'

    print("Data grouped in %s intervals" % groupby_freq)

    print("Speeds (mph):")
    speeds_mph = (dt.speed / 1.609).groupby(
        pandas.Grouper(freq=groupby_freq)).max().fillna(0)
    print(asciichartpy.plot(speeds_mph, {"height": 10}))
    print("\n")

    print("System Temp (F):")
    system_temp = ((dt.system_temp * 9 / 5) + 32).groupby(
        pandas.Grouper(freq=groupby_freq)).max().fillna(0)
    print(asciichartpy.plot(system_temp, {"height": 10}))
    print("\n")

    print("CPU Temp (F):")
    cpu_temp = ((dt.cpu_temp * 9 / 5) + 32).groupby(
        pandas.Grouper(freq=groupby_freq)).max().fillna(0)
    print(asciichartpy.plot(cpu_temp, {"height": 10}))
    print("\n")

    print("Power")
    power = dt.power.groupby(pandas.Grouper(freq=groupby_freq)).max().fillna(0)
    print(asciichartpy.plot(power, {"height": 10, "max": 2000}))
    print("\n")

    print("Current")
    current = dt.current.groupby(
        pandas.Grouper(freq=groupby_freq)).max().fillna(0)
    print(asciichartpy.plot(current, {"height": 10}))
    print("\n")

    print("Tilt")
    tilt = dt.tilt.groupby(pandas.Grouper(freq=groupby_freq)).mean().fillna(0)
    print(asciichartpy.plot(tilt, {"height": 10}))
    print("\n")

    print("Roll")
    roll = dt.roll.groupby(pandas.Grouper(freq=groupby_freq)).mean().fillna(0)
    print(asciichartpy.plot(roll, {"height": 10}))
    print("\n")
コード例 #9
0
    def __rich_console__(self, console: Console,
                         options: ConsoleOptions) -> RenderResult:
        def _slice(items, max_items):
            items = list(items)
            items_len = min(len(items), max_items)
            return items[-items_len:]

        height = (options.height or options.size.height) - 1
        graph = asciichartpy.plot(
            series=[_slice(s, options.max_width - 10) for s in self.series],
            cfg={
                "min": 0,
                "max": self.max,
                "height": height,
                "colors": self.colors,
            },
        )
        yield Text("\n").join(self.decoder.decode(graph))
コード例 #10
0
def print_chart(exchange, symbol):

    print("\n" + exchange + ' ' + symbol + ' chart:')

    # get a list of ohlcv candles
    ohlcv = pd.read_csv('market_data/BINANCE_BTC_USDT_SMALL.csv')
    close = ohlcv.Close.iloc[:150].values
    # get the ohlCv (closing price, index == 4)
    # series = [x for x in close]

    # print the chart
    print("\n" + plot(close[-120:-1], {'height': 10}))  # print the chart
    try:

        last = ohlcv.Close.iloc[-1]  # last closing price
    except Exception as e:
        print(e)
    return last
コード例 #11
0
ファイル: ticket.py プロジェクト: chetnuy/ticket.py
    def graph_format(self, reply):
        timestamp = reply['chart']['result'][0]['timestamp']
        ticket = reply['chart']['result'][0]['meta']
        price = reply['chart']['result'][0]['indicators']['quote'][0]['open']
        mass = [x for x in price if x is not None]

        while len(mass) >= 70:
            for x in range(len(mass)):
                if x % 3 == 0 and x < len(mass):
                    del mass[x]

        print(ticket.get("symbol"), "timestamp:", ''.join(args.t))
        time_tuple1 = time.localtime(timestamp[0])
        time_tuple2 = time.localtime(timestamp[-1])
        print("START:", (time.strftime("%D %H:%M", time_tuple1)), "     ",
              "END:", (time.strftime("%D %H:%M", time_tuple2)))
        print(asciichartpy.plot(mass, {'height': 10}))
        print("-----------------------------------------------")
コード例 #12
0
def print_chart(exchange, symbol, timeframe):

    # get a list of ohlcv candles
    ohlcv = exchange.fetch_ohlcv(symbol, timeframe)

    # get the ohlCv (closing price, index == 4)
    series = [x[index] for x in ohlcv]

    # print datetime and other values
    for x in ohlcv:
        print(exchange.iso8601(x[0]), x)

    print("\n" + exchange.name + ' ' + symbol + ' ' + timeframe + ' chart:')

    # print the chart
    print("\n" + asciichartpy.plot(series[-length:],
                                   {'height': height}))  # print the chart

    last = ohlcv[len(ohlcv) - 1][index]  # last closing price
    return last
コード例 #13
0
def asciichart(series, cfg=None, maxlines=100):
    """Wraps asciichart.plot() to fix y-axis numbers alignment and warn of too great a height."""

    def fix_asciichart(lines):
        dotidx = max([line.index(".") for line in lines if "." in line])
        lines_ = []
        for line in lines:
            try:
                idx = line.index(".")
                lines_.append(" "*(dotidx-idx)+line)
            except ValueError:
                lines_.append(line)
        return "\n".join(lines_)

    text = asciichartpy.plot(series, cfg)
    lines = text.split("\n")
    if len(lines) > maxlines:
        raise ValueError(f"Your chart has more than {maxlines} of text; maybe you would like to specify cfg['height']?")
    text = fix_asciichart(lines)
    return text
コード例 #14
0
ファイル: test_freqs.py プロジェクト: ekwan/cctk
    def draw_qho(self):
        from asciichartpy import plot

        path = "test/static/methane_normal.out"
        file = cctk.GaussianFile.read_file(path)
        mol = file.get_molecule()

        mode = mol.vibrational_modes[-1]

        for level in range(10):
            tp = mode.classical_turning_point(level=level)
            print(
                f"LEVEL {level} ({mode.energy(level):.2f} kcal.mol, turning point = {tp:.2f} Å)"
            )
            tp = 5
            print(
                plot([
                    mode.quantum_distribution_value(x, level=level)
                    for x in np.linspace(-1 * tp, tp, 100)
                ], {"height": 10}))
コード例 #15
0
    def handle(self, *args, **options):
        refresh_seconds = options['refresh']
        width = options['width']
        height = options['height']

        jctl = JobStatusController(width)

        conf = {
            'colors': [chart_color_lookup(p.color) for p in jctl.plots],
            'height': height,
        }

        while True:
            jctl.tick()

            draw = chart.plot(jctl.series(), conf)
            status_line = jctl.generate_status()
            clear_screen()
            print(draw)
            sys.stdout.write(status_line)
            time.sleep(refresh_seconds)
コード例 #16
0
    def report(self,
               groundTruth: Union[np.ndarray, pd.core.frame.DataFrame],
               predicted: Union[np.ndarray, pd.core.frame.DataFrame],
               ascii_chart_config: dict = {}):
        _pred = predicted.copy() * 128
        _gt = groundTruth.copy() * 128
        error = (predicted - groundTruth) * 128

        self.log.info('Linear regression evaluation report:')
        self.log.info(' |- Max error: {}'.format(np.max(error)))
        self.log.info(' |- Min error: {}'.format(np.min(error)))
        self.log.info(' |- Average error: {}'.format(np.mean(error)))
        self.log.info(' |- Average absolute error: {}'.format(
            np.mean(np.abs(error))))
        self.log.debug(
            ' |- Loss value between ground truth and prediction: {}'.format(
                error))
        #
        config = {
            'colors': [chart.red, chart.green, chart.blue],
            'height': 15,
            'max': 128,
            'display_width': 100
        }
        config.update(ascii_chart_config)
        #
        legend = "+{:=^20}+\n|{:^20}|\n|{:^20}|\n|{:^20}|\n+{:=^20}+" \
            .format('Legend', 'Green: Prediction', 'Red: Ground Truth', 'Blue: Error value', '')
        #
        _display = config['display_width']
        #
        out_chart = chart.plot(series=[
            _gt.tolist()[:_display],
            _pred.tolist()[:_display], (_pred - _gt).tolist()[:_display]
        ],
                               cfg=config)
        log_msg = "\nKernel type: {:=^20}".format(self.model_name) + "\n" + \
                  "\n" + legend + "\n" + "+===[Performance report on evaluation data]===+" + "\n" + out_chart
        self.log.info(log_msg)
コード例 #17
0
    def _cnn_stats(self, input_size):
        layers = self._get_layer_stats()

        _print_tabular = []
        _receptive_field = []
        for i in range(len(layers)):
            layer = layers[i]

            if i > 0:
                prev_layer = layers[i - 1]
                layer.prev_layer = prev_layer
                layer.input_size = prev_layer.output_size()
            else:
                layer.prev_layer = None
                layer.input_size = input_size

            _print_tabular.append([
                i,
                type(layer).__name__, layer.kernel_size, layer.stride,
                layer.dilation, layer.padding, layer.input_size,
                layer.output_size(),
                layer.receptive_field()
            ])
            _receptive_field.append(layer.receptive_field())
        print(
            tabulate(_print_tabular,
                     headers=("Layer #", "Name", "Kernel Size", "Stride",
                              "Dilation", "Padding", "Input Size",
                              "Output Size", "Receptive Field")))

        print(
            asciichartpy.plot(list(
                itertools.chain.from_iterable(
                    itertools.repeat(x, 5) for x in _receptive_field)),
                              cfg={"height": 10}))

        return layer.output_size()
コード例 #18
0
def plotData(data, bins, params):
    large_pixels = [pixel % 16 not in [0, 1, 14, 15] for pixel in range(256)]
    print(params)
    for slot in range(1, 3 + 1):
        d = np.asarray(data['Slot%d' % slot])

        p = params['Slot%d' % slot]
        if p is None:
            d = d[:, large_pixels].flatten()
            d = d[d > 0]
        else:
            d = np.asarray([
                ToTtoEnergySimple(d.T[pixel], p[str(pixel)]['a'],
                                  p[str(pixel)]['b'], p[str(pixel)]['c'],
                                  p[str(pixel)]['t']) for pixel in range(256)
            ])
            d = d[large_pixels].flatten()
        h, b = np.histogram(d, bins=bins)

        # Ascii plot
        res = asciichartpy.plot(h / np.max(h) * 30)
        print(res)

        # Matplotlib
        if MATPLOTLIB:
            plt.step(b[:-1],
                     h,
                     where='post',
                     color='C%d' % (slot - 1),
                     label='Slot%d' % slot)
    if MATPLOTLIB:
        plt.legend()
        plt.xlabel('Energy (keV)')
        plt.ylabel('Counts')
        plt.grid()
        plt.show()
コード例 #19
0
def draw_screen(msg_buf, price_buf):
    print(chr(27) + "[2H" + chr(27) + "[2J")  # CLS
    if len(price_buf) > 1:
        print(asciichartpy.plot(list(price_buf), {"height": 25}))
    for msg in reversed(msg_buf):
        print(msg)
コード例 #20
0
ファイル: analyze.py プロジェクト: msh-yi/presto
temps = np.array([f.temperature() for f in traj.frames])
energies = np.array([f.energy for f in traj.frames][:-1])
rel_energies = energies - np.min(energies)
rel_energies = energies * 627.509

max_width = 100
scale = math.ceil(len(energies) / max_width)
if scale < 1:
    scale == 1

height = 16

print(f"TEMPERATURE:\t\t{np.mean(temps):.2f} K (± {np.std(temps):.2f})")
print(
    plot(
        np.mean(temps[:(len(temps) // scale) * scale].reshape(-1, scale),
                axis=1), {"height": height}))
print(
    f"ENERGY:\t\t\t{np.mean(energies):.2f} (± {np.std(energies)*627.509:.2f} kcal/mol)"
)
print(
    plot(
        np.mean(rel_energies[:(len(rel_energies) // scale) * scale].reshape(
            -1, scale),
                axis=1), {"height": height}))

if args["movie"]:
    movie_path = re.sub("chk$", "pdb", args["checkpoint_filename"])
    print(f"writing movie to {movie_path}...")
    traj.write_movie(movie_path, idxs=args["movie"])
コード例 #21
0
def go():
    global CLIARGS, global_vars
    site_id = global_vars['site_id']

    ####CODE GOES BELOW HERE#########
    days_ago = CLIARGS['days']  ###How many days ago to look
    statistics_period = CLIARGS['period']
    hours_ago = days_ago * 24
    today = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)
    #start_time = str((datetime.today() - timedelta(hours=hours_ago)).isoformat())
    #end_time = str((datetime.today() - timedelta(hours=(hours_ago-statistics_period))).isoformat())
    start_time = str((today - timedelta(hours=hours_ago)).isoformat())
    end_time = str(
        (today - timedelta(hours=(hours_ago - statistics_period))).isoformat())

    topology_filter = '{"type":"basenet","nodes":["' + site_id + '"]}'
    resp = cgx_session.post.topology(topology_filter)
    phy_link_array = []
    link_count = 0
    print("LINKS at SITE", global_vars['site_name'])
    if resp.cgx_status:
        topology_list = resp.cgx_content.get("links", None)
        for links in topology_list:
            if ((links['type'] == 'internet-stub')):
                link_count += 1
                print(str(link_count) + ") " + str(links['network']))
                phy_link_array.append(links)
                ###path_id in LINKS is path in JSON

    if len(phy_link_array) == 1:
        global_vars['link'] = phy_link_array[0]
        print(
            "Only one Physical Link found at site. Implicitly selecting LINK 1 above..."
        )

    elif len(phy_link_array) > 1:
        user_input = 0
        while not (0 < user_input <= len(phy_link_array)):
            user_input = int(
                input("Please Select the Physical link above (1 - " +
                      str(len(phy_link_array)) + "):"))
        global_vars['link'] = phy_link_array[user_input]
    else:
        print("Error! No Physical Interfaces at site found!")
        return False
    print("")
    global_vars['path_id'] = global_vars['link']['path_id']
    path_id = global_vars['path_id']

    json_request = '{"start_time":"' + start_time + 'Z","end_time":"' + end_time + 'Z","interval":"5min","view":{"summary":false,"individual":"direction"},"filter":{"site":["' + site_id + '"],"path":["' + path_id + '"]},"metrics":[{"name":"PathCapacity","statistics":["average"],"unit":"Mbps"}]}'
    print("Displaying Graphs for Time Period from", start_time, " ---- ",
          end_time)
    bw_capacity_result = cgx_session.post.metrics_monitor(json_request)
    cgx_bw_results = bw_capacity_result.cgx_content.get("metrics")

    bw_metrics = {}
    bw_metrics['egress'] = []
    bw_metrics['ingress'] = []
    direction = ""
    for directions in cgx_bw_results[0]['series']:
        if directions['view']['direction'] == "Ingress":
            direction = 'ingress'
        if directions['view']['direction'] == "Egress":
            direction = 'egress'
        for datapoint in directions['data'][0]['datapoints']:
            if datapoint['value'] is not None:
                bw_metrics[direction].append(datapoint['value'])

    ascii_chart_config = {}
    ascii_chart_config['height'] = CLIARGS['graphheight']  #Default 15
    ascii_chart_config['min'] = 10
    hrow = [0] * len(bw_metrics['egress'])
    print("")
    print("EGRESS BANDWIDTH STATISTICS from", days_ago, "days ago for",
          statistics_period, "hour period at site", global_vars['site_name'],
          "for interface", global_vars['link']['network'])
    print(plot([bw_metrics['egress']], ascii_chart_config))
    print(plot(hrow))
    print("")
    hrow = [0] * len(bw_metrics['ingress'])
    print("INGRESS BANDWIDTH STATISTICS from", days_ago, "days ago for",
          statistics_period, "hour period at site", global_vars['site_name'],
          "for interface", global_vars['link']['network'])
    print(plot([bw_metrics['ingress']], ascii_chart_config))
    print(plot(hrow))
コード例 #22
0
ファイル: test.py プロジェクト: smktest/smktest
# -*- coding: utf-8 -*-

# ------------------------------------------------------------------------------

from math import cos
from math import pi

# ------------------------------------------------------------------------------

from asciichartpy import plot

# ------------------------------------------------------------------------------

width = 90
series = [7 * round(cos(i * ((pi * 4) / width)), 2) for i in range(width)]

print(plot(series))

series = [2.0] * width

print(plot(series))
print(plot(series, {'height':5}))

series = [0.0] * width

print(plot(series))
print(plot(series, {'height':5}))
コード例 #23
0
# -*- coding: utf-8 -*-

# ------------------------------------------------------------------------------

from math import cos
from math import pi

# ------------------------------------------------------------------------------

from asciichartpy import plot

# ------------------------------------------------------------------------------

width = 90
series = [7 * round(cos(i * ((pi * 4) / width)), 2) for i in range(width)]
print(plot(series))
コード例 #24
0
print(f"{output_file.num_imaginaries()} imaginary frequencies")
if output_file.num_imaginaries():
    freqs = [f"{f:.1f} cm-1" for f in output_file.imaginaries()]
    for f in freqs:
        print(f"\t{f}")

print("\n\033[3manalysis:\033[0m")
print(f"{len(output_file.ensemble)} iterations completed")
property_names = [
    "scf_iters", "energy", "quasiharmonic_gibbs_free_energy", "rms_force",
    "rms_displacement", "rms_gradient"
]

properties = output_file.ensemble[:, property_names]
if len(output_file.ensemble) == 1:
    properties = [properties]
df = pd.DataFrame(properties, columns=property_names).fillna(0)
df["rel_energy"] = (df.energy - df.energy.min()) * 627.509469

print("\n\033[1mENERGY (kcal/mol):\033[0m")
print(plot(df["rel_energy"], {"height": 12, "format": " {:8.2f} "}))

print("\n\033[1mRMS GRADIENT:\033[0m")
print(plot(df["rms_gradient"], {"height": 12, "format": " {:8.6f} "}))

print("\n\033[1mRMS FORCE:\033[0m")
print(plot(df["rms_force"], {"height": 12, "format": " {:8.6f} "}))

print("\n\033[1mRMS DISPLACEMENT:\033[0m")
print(plot(df["rms_displacement"], {"height": 12, "format": " {:8.4f} "}))
コード例 #25
0
ファイル: TryGridBot.py プロジェクト: TREVO786/pyjuque
def populateScreen(bot, open_orders, buy_orders, sell_orders):

    df = bot.exchange.getOHLCV(bot.symbol, '5m', 100)

    buys_plots = []
    sells_plots = []
    plot_colors = [asciichartpy.white]

    min_price = float(min(df['close'].tolist()))
    max_price = float(max(df['close'].tolist()))

    for order in buy_orders:
        p = [float('nan') for i in range(90)]
        p.extend([float(order.price) for i in range(10)])

        if min_price > float(order.price):
            min_price = float(order.price)

        buys_plots.append(p)
        plot_colors.append(asciichartpy.green)

    for order in sell_orders:
        p = [float('nan') for i in range(90)]
        p.extend([float(order.price) for i in range(10)])

        if max_price < float(order.price):
            max_price = float(order.price)

        sells_plots.append(p)
        plot_colors.append(asciichartpy.red)

    plots = [df['close'].tolist()]
    if len(buys_plots) > 0:
        plots.extend(buys_plots)
    if len(sells_plots) > 0:
        plots.extend(sells_plots)

    max_price = max_price * 1.005
    min_price = min_price * 0.995

    # print(len(plots), len(plot_colors), len(buys_plots), len(sells_plots))
    bot.screen.clear()
    bot.screen.refresh()
    # curses.endwin()

    bot.screen.addstr(
        1, 1, bot.symbol +
        ' price chart (last price: {})'.format(df['close'][len(df) - 1]))

    plot_config = {'height': 40, 'min': min_price, 'max': max_price}
    price_plot = asciichartpy.plot(df['close'].tolist(), plot_config)
    buy_plot = asciichartpy.plot([df['close'].tolist(), *buys_plots],
                                 plot_config)
    sell_plot = asciichartpy.plot([df['close'].tolist(), *sells_plots],
                                  plot_config)

    k = 3
    for line in price_plot.split('\n'):
        bot.screen.addstr(k, 0, line, curses.color_pair(1))
        k += 1

    k = 3
    for line in buy_plot.split('\n'):
        q = 0
        for char in line:
            if char != chr(bot.screen.inch(k, q)):
                bot.screen.addch(k, q, char, curses.color_pair(2))
            q += 1
        k += 1

    k = 3
    for line in sell_plot.split('\n'):
        q = 0
        for char in line:
            if char != chr(bot.screen.inch(k, q)):
                bot.screen.addch(k, q, char, curses.color_pair(3))
            q += 1
        k += 1

    bot.screen.refresh()
コード例 #26
0
def main(stdscr):
    # Clear screen
    stdscr.clear()  # clear the screen
    stdscr.nodelay(True)  # don't wait for input
    curses.curs_set(0)  # hide the cursor

    # this will be hardware dependent and might need to be changed for different systems to find the CPU
    # the following is very helpful!
    # paste <(cat /sys/class/thermal/thermal_zone*/type) <(cat /sys/class/thermal/thermal_zone*/temp) | column -s $'\t' -t | sed 's/\(.\)..$/.\1°C/'
    thermal_zone_number = 1
    if len(sys.argv) > 1:
        thermal_zone_number = sys.argv[1]

    quit_key = 'q'

    # in characters
    plot_width = 100
    plot_height = 30
    # TODO: read the terminal size with curses and use that

    average_window_length = round(plot_width /
                                  5)  # length of running average window
    downsample_by = 30  # factor for downsampling

    display = deque([], plot_width)  # what we'll be displaying

    cache = deque()  # used in calculating the rolling mean
    cum_sum = 0  # used for calculating rolling mean
    ds = Downsampler(downsample_by)

    # try to get type string
    try:
        tmp_type = get_type(zone=thermal_zone_number)
    except Exception:
        tmp_type = "CPU"
    while True:
        stdscr.erase()

        #this_data = get_datapoint()
        raw_data = get_datapoint(
            zone=thermal_zone_number)  # get a new datapoint
        while (
                this_data := ds.feed(raw_data)
        ) is None:  # feed the downsampler with raw data until it gives us a data point
            raw_data = get_datapoint(
                zone=thermal_zone_number)  # get a new datapoint

        # do rolling average computation
        cache.append(this_data)
        cum_sum += this_data
        if len(cache) < average_window_length:
            pass
        else:
            cum_sum -= cache.popleft()
        this_avg = cum_sum / float(len(cache))

        # draw the plot
        to_display = this_avg
        #to_display = this_data
        stdscr.addstr(
            0, 0,
            f"{tmp_type} Temperature = {to_display:.2f}°C     ===== press {quit_key} to quit ====="
        )
        display.append(to_display)
        stdscr.addstr(1, 0, asciichartpy.plot(display,
                                              {'height': plot_height}))
        stdscr.refresh()

        ch = stdscr.getch()
        if ch == ord(quit_key):  # q key ends the program
            break
        elif ch == ord('r'):  # r key does nothing
            pass
コード例 #27
0
ファイル: CNN_utils.py プロジェクト: pfriesch/PhnKWS
    for i in range(len(layers)):
        layer = layers[i]

        if i > 0:
            prev_layer = layers[i - 1]
            layer.prev_layer = prev_layer
            layer.input_size = prev_layer.output_size()
        else:
            layer.prev_layer = None
            layer.input_size = input_size

        print_tabular.append([
            i, layer.name, layer.kernel_size, layer.stride, layer.dilation,
            layer.padding(), layer.input_size,
            layer.output_size(),
            layer.receptive_field()
        ])
        receptive_field.append(layer.receptive_field())

    print(
        tabulate(print_tabular,
                 headers=("Layer #", "Name", "Kernel Size", "Stride",
                          "Dilation", "Padding", "Input Size", "Output Size",
                          "Receptive Field")))

    print(
        asciichartpy.plot(list(
            itertools.chain.from_iterable(
                itertools.repeat(x, 3) for x in receptive_field)),
                          cfg={"height": 20}))
コード例 #28
0
ファイル: wham2d.py プロジェクト: msh-yi/presto
        new_filename = name.rsplit('/',1)[-1] + ".csv"
        if os.path.exists(new_filename):
            raise ValueError(f"Can't write to {new_filename} -- file already exists!")
        with open(new_filename, "w") as timeseries:
            timeseries.write(timeseries_text)

        x_file_hist, bin_edges = np.histogram(x_dists, bins=100, range=(min_x, max_x))
        y_file_hist, bin_edges = np.histogram(y_dists, bins=100, range=(min_y, max_y))
        return x_file_hist, y_file_hist, len(x_dists), f"{new_filename}\t{dx:.4f}\t{dy:.4f}\t{kx:.4f}\t{ky:.4f}\n"

    # reading is slow, do it in parallel
    pool = mp.Pool(processes=1)
    for (x_file_hist, y_file_hist, file_count, file_metadata_text) in tqdm.tqdm(pool.imap(read_chk, files), total=len(files)):
        x_histogram += x_file_hist
        y_histogram += y_file_hist
        count += file_count
        if file_count > 0:
            metadata_text += file_metadata_text

    print(f"\nX histogram ({min_x:.2f} to {max_x:.2f}, n={count}):")
    print(plot(x_histogram, {"height": 10}))
    print(f"\nY histogram ({min_y:.2f} to {max_y:.2f}, n={count}):")
    print(plot(y_histogram, {"height": 10}))

    with open("metadata.txt", "w") as metadata:
        metadata.write(metadata_text)

else:
    raise ValueError(f"invalid type {args['type']} - need either ``run`` or ``analyze``!")

コード例 #29
0
ファイル: wham.py プロジェクト: msh-yi/presto
            dist = mol.get_distance(int(args['atom1']), int(args['atom2']))
            dists.append(dist)
            timeseries_text += f"{idx}\t{dist:.4f}\n"

        if len(dists):
            with open(f"{name}.csv", "w") as timeseries:
                timeseries.write(timeseries_text)
        else:
            print(f"skipping {file}")

        file_hist, bin_edges = np.histogram(dists, bins=100, range=(min_x, max_x))
        return file_hist, len(dists), f"{name}.csv\t{d:.4f}\t{k:.4f}\n"

    # reading is slow, do it in parallel
    pool = mp.Pool(processes=16)
    for (file_hist, file_count, file_metadata_text) in tqdm.tqdm(pool.imap(read_chk, files), total=len(files)):
        if file_count:
            histogram += file_hist
            count += file_count
            metadata_text += file_metadata_text

    print(f"\nhistogram ({min_x:.2f} to {max_x:.2f}, n={count}):")
    print(plot(histogram, {"height": 10}))

    with open("metadata.txt", "w") as metadata:
        metadata.write(metadata_text)

else:
    raise ValueError(f"invalid type {args['type']} - need either ``run`` or ``analyze``!")

コード例 #30
0
                    for f in traj.frames
                ]
            elif coord[0] == "angle":
                Y = [
                    f.molecule().get_angle(int(coord[1]), int(coord[2]),
                                           int(coord[3])) for f in traj.frames
                ]
            elif coord[0] == "dihedral":
                Y = [
                    f.molecule().get_dihedral(int(coord[1]), int(coord[2]),
                                              int(coord[3]), int(coord[4]))
                    for f in traj.frames
                ]
            else:
                print(f"Unrecognized coordinate type {coord[0]}!")
                break

            Y = np.asarray(Y)

            print(f"\033[3m{' '.join(coord)}\033[0m")
            print(
                plot(
                    np.mean(Y[:(len(Y) // scale) * scale].reshape(-1, scale),
                            axis=1), {"height": 10}))
            print("\n")

    if args["movie"]:
        assert os.path.exists(
            args["movie"]), f"can't write to directory {args['movie']}"
        traj.write_movie(f"{args['movie']}/{filename}.pdb")