#!/usr/bin/env python
# ==============================================================
#
#  Abs:   Utility script for mgnt_poly_compare.py
#
#  Name:  mgnt_get_poly.py
#
#  Facility: SLAC Controls (Development)
#
#  Auth:  08-Jul-2020, A. Le (anle)
# --------------------------------------------------------------
#  Mods: (Latest to oldest)
#     08-Dec-2022, A. Le (anle)
#         Reformat code
#         Add docstrings
#     17-Jun-2022, A. Le (anle)
#         Trim nones instead of zeros
#     31-May-2022, A. Le (anle)
#         Make code compatible with Python 2 and 3
#     01-Oct-2021, A. Le (anle)
#         Prevent floating-point rounding error
#     23-Aug-2021, A. Le (anle)
#         Rename to mgnt_get_poly.py
#     31-Aug-2020, A. Le (anle)
#         Add ability for trim_zeros to trim blanks
#         Move round_sig_figs function here
#     09-Jul-2020, A. Le (anle)
#         -List device name and operational status
#         -Group devices by area
#         -Report devices missing by area
#         -Take magnets from Oracle Infrastructure database
#         -Add table of missing magnets
#
# ==============================================================
#
from __future__ import print_function

from decimal import ROUND_HALF_UP, Decimal
from math import floor, log10


def trim_nones(coeff):
    """Removes `None`s from the end of a list of polynomial coefficients.

    Args:
        coeff (list[float]): The polynomial coefficients.

    Returns:
        list[float]: The same list of coefficients without `None`s at the end.
    """
    if None not in coeff:
        return coeff

    right_index = coeff.index(None)
    return coeff[:right_index]


def round_dec_places(x, desired_places):
    """Rounds a number as if it were in scientific notation.

    Examples:
        >>> round_dec_places(3.14159, 3)
        3.142

        >>> round_dec_places(1.23456789e-7, 6)
        1.234568e-07

    Args:
        x (float): The number to be rounded.
        desired_places (int): The number of decimal places to which to round.

    Returns:
        float: The rounded number.
    """
    if x == 0:
        return 0

    expon = int(floor(log10(abs(x))))
    places = desired_places - expon
    prec = Decimal(10)**-places

    # Utilize decimal library to prevent floating-point rounding error
    rounded = Decimal(str(x)).quantize(prec, rounding=ROUND_HALF_UP)
    return float(rounded)
