Esempio n. 1
0
    def test_multi(self):
        self.assertEqual(to_precision(500, 2, notation='std', delimiter='e'),
                         '500')

        self.assertEqual(to_precision(500, 2, notation='sci', delimiter='e'),
                         '5.0e2')

        self.assertEqual(to_precision(1100, 2, notation='eng', delimiter='e'),
                         '1.1e3')
Esempio n. 2
0
def _string_from_complex_sigfig(a, digits=2):
    """_string_from_complex_sigfig(a, digits=2)

    This function assumes that "a" is a complex number. It returns "a" as a string
    in which the real and imaginary parts have digits significant digits.
    """
    re = to_precision.to_precision(a.real, digits)
    im = to_precision.to_precision(np.abs(a.imag), digits)
    if a.imag >= 0:
        return '{:s}+{:s}j'.format(re, im)
    elif a.imag < 0:
        return '{:s}-{:s}j'.format(re, im)
Esempio n. 3
0
def _string_from_complex_sigfig(a, digits=2):
    """_string_from_complex_sigfig(a, digits=2)

    This function assumes that "a" is a complex number. It returns "a" as a string
    in which the real and imaginary parts have digits significant digits.
    """
    re = to_precision.to_precision(a.real, digits)
    im = to_precision.to_precision(np.abs(a.imag), digits)
    if a.imag >= 0:
        return '{:s}+{:s}j'.format(re, im)
    elif a.imag < 0:
        return '{:s}-{:s}j'.format(re, im)
Esempio n. 4
0
def numpy_to_matlab_sf(A, ndigits=2):
    """numpy_to_matlab(A, ndigits=2)

    This function assumes that A is one of these things:

        - a number (float or complex)
        - a 2D ndarray (float or complex)

    It returns A as a MATLAB-formatted string in which each number has
    ndigits significant digits.
    """
    if np.isscalar(A):
        if np.iscomplexobj(A):
            A_str = _string_from_complex_sigfig(A, ndigits)
        else:
            A_str = to_precision.to_precision(A, ndigits)
        return A_str
    elif A.ndim == 1:
        s = A.shape
        m = s[0]
        A_str = '['
        for i in range(0, m):
                if np.iscomplexobj(A[i]):
                    A_str += _string_from_complex_sigfig(A[i], ndigits)
                else:
                    A_str += to_precision.to_precision(A[i], ndigits)
                if i < m - 1:
                    A_str += ', '
        A_str += ']'
        return A_str
    else:
        s = A.shape
        m = s[0]
        n = s[1]
        A_str = '['
        for i in range(0, m):
            for j in range(0, n):
                if np.iscomplexobj(A[i, j]):
                    A_str += _string_from_complex_sigfig(A[i, j], ndigits)
                else:
                    A_str += to_precision.to_precision(A[i, j], ndigits)
                if j == n - 1:
                    if i == m - 1:
                        A_str += ']'
                    else:
                        A_str += '; '
                else:
                    A_str += ' '
        return A_str
Esempio n. 5
0
def numpy_to_matlab_sf(A, ndigits=2):
    """numpy_to_matlab(A, ndigits=2)

    This function assumes that A is one of these things:

        - a number (float or complex)
        - a 2D ndarray (float or complex)

    It returns A as a MATLAB-formatted string in which each number has
    ndigits significant digits.
    """
    if np.isscalar(A):
        if np.iscomplexobj(A):
            A_str = _string_from_complex_sigfig(A, ndigits)
        else:
            A_str = to_precision.to_precision(A, ndigits)
        return A_str
    elif A.ndim == 1:
        s = A.shape
        m = s[0]
        A_str = '['
        for i in range(0, m):
            if np.iscomplexobj(A[i]):
                A_str += _string_from_complex_sigfig(A[i], ndigits)
            else:
                A_str += to_precision.to_precision(A[i], ndigits)
            if i < m - 1:
                A_str += ', '
        A_str += ']'
        return A_str
    else:
        s = A.shape
        m = s[0]
        n = s[1]
        A_str = '['
        for i in range(0, m):
            for j in range(0, n):
                if np.iscomplexobj(A[i, j]):
                    A_str += _string_from_complex_sigfig(A[i, j], ndigits)
                else:
                    A_str += to_precision.to_precision(A[i, j], ndigits)
                if j == n - 1:
                    if i == m - 1:
                        A_str += ']'
                    else:
                        A_str += '; '
                else:
                    A_str += ' '
        return A_str
Esempio n. 6
0
def _colorize_entries(entries):
    """
    Colorize table <entries>
    """

    data = []

    for rank, entry in enumerate(entries):
        code = entry['code']
        price = entry['price']
        change_24h = entry['change_24h']
        change_1h = entry['change_1h']
        cap = entry['cap']
        s_spark = spark.spark(entry['spark'])

        if change_24h != '-':
            change_24h = colorize_number("%.2f%%" % change_24h)

        if change_1h != '-':
            change_1h = colorize_number("%.2f%%" % change_1h)

        code = colored(code, 'cyan')
        price = colored(to_precision(price, 6), 'cyan')
        cap = human_format(cap)

        data.append(
            [rank + 1, code, price, change_24h, change_1h, cap, s_spark])

    return data
Esempio n. 7
0
def _format_value(value, precision=3, show_plus=False):
    value = str(to_precision(value, precision))

    plus = ''
    if show_plus and not value.startswith('-'):
        plus = '+'

    if 'e' in value:
        return plus + str(float(value)).lstrip('+')
    return plus + value.lstrip('+')
Esempio n. 8
0
def _format_value(value, precision=3, show_plus=False):
    value = str(to_precision(value, precision))

    plus = ''
    if show_plus and not value.startswith('-'):
        plus = '+'

    if 'e' in value:
        return plus + str(float(value)).lstrip('+')
    return plus + value.lstrip('+')
Esempio n. 9
0
def string_from_number_sigfig(a, digits=2):
    """_string_from_complex_sigfig(a, digits=2)

    This function assumes that "a" is of type float or complex. It returns "a"
    as a string in which the number, or both the real and imaginary parts of the
    number, have digits significant digits.
    """
    if np.iscomplexobj(a):
        return _string_from_complex_sigfig(a, digits=digits)
    else:
        return to_precision.to_precision(a, digits)
Esempio n. 10
0
def numpy_to_matlab_sf(A, ndigits=2):
    if np.isscalar(A):
        A_str = to_precision.to_precision(A, ndigits)
        return A_str
    else:
        s = A.shape
        m = s[0]
        n = s[1]
        A_str = '['
        for i in range(0, m):
            for j in range(0, n):
                A_str += to_precision.to_precision(A[i, j], ndigits)
                if j == n - 1:
                    if i == m - 1:
                        A_str += ']'
                    else:
                        A_str += '; '
                else:
                    A_str += ' '
        return A_str
Esempio n. 11
0
def string_from_number_sigfig(a, digits=2):
    """_string_from_complex_sigfig(a, digits=2)

    This function assumes that "a" is of type float or complex. It returns "a"
    as a string in which the number, or both the real and imaginary parts of the
    number, have digits significant digits.
    """
    if np.iscomplexobj(a):
        return _string_from_complex_sigfig(a, digits=digits)
    else:
        return to_precision.to_precision(a, digits)
Esempio n. 12
0
def string_from_2darray_sf(A, ndigits=2):
    if np.isscalar(A):
        A_str = to_precision.to_precision(A, ndigits)
        return A_str
    else:
        s = A.shape
        m = s[0]
        n = s[1]
        A_str = ''
        for i in range(0, m):
            row = ''
            for j in range(0, n):
                row += to_precision.to_precision(A[i, j], ndigits)
                if j != n - 1:
                    row += ', '
            A_str += '[' + row + ']'
            if i != m - 1:
                A_str += ', '
        A_str = '[' + A_str + ']'
        return A_str
Esempio n. 13
0
def string_from_2darray(A, language='python', presentation_type='f', digits=2):
    """string_from_2darray(A)

    This function assumes that A is one of these things:

        - a number (float or complex)
        - a 2D ndarray (float or complex)

    It returns A as a string.

    If language is 'python' and A is a 2D ndarray, the string looks like this:

        [[ ..., ... ], [ ..., ... ]]

    If language is 'matlab' and A is a 2D ndarray, the string looks like this:

        [ ... ... ; ... ... ]

    In either case, if A is not a 2D ndarray, the string is a single number,
    not wrapped in brackets.

    If presentation_type is 'sigfig', each number is formatted using the
    to_precision module to "digits" significant figures.

    Otherwise, each number is formatted as '{:.{digits}{presentation_type}}'.
    """

    # if A is a scalar
    if np.isscalar(A):
        if presentation_type == 'sigfig':
            return string_from_number_sigfig(A, digits=digits)
        else:
            return '{:.{digits}{presentation_type}}'.format(A, digits=digits, presentation_type=presentation_type)

    # if A is a 2D ndarray
    if language == 'python':
        if presentation_type == 'sigfig':
            formatter = {
                'float_kind': lambda x: to_precision.to_precision(x, digits),
                'complex_kind': lambda x: _string_from_complex_sigfig(x, digits)
            }
        else:
            formatter = {
                'float_kind': lambda x: '{:.{digits}{presentation_type}}'.format(x, digits=digits, presentation_type=presentation_type),
                'complex_kind': lambda x: '{:.{digits}{presentation_type}}'.format(x, digits=digits, presentation_type=presentation_type)
            }
        return np.array2string(A, formatter=formatter, separator=', ').replace('\n', '')
    elif language == 'matlab':
        if presentation_type == 'sigfig':
            return numpy_to_matlab_sf(A, ndigits=digits)
        else:
            return numpy_to_matlab(A, ndigits=digits, wtype=presentation_type)
    else:
        raise Exception('language "{:s}" must be either "python" or "matlab"'.format(language))
Esempio n. 14
0
def main():
    """
    Displays a table containing example conversions for to_precision()
    """

    # Build test values
    seed = [float(int(123456789. / 10**x)) for x in range(7, -1, -1)]
    test_values = ([0.0, 1.0, 10.0, 100.0, -1.0] + [x for x in seed] +
                   [x / 10**int(log10(x))
                    for x in seed] + [x / 10**9 for x in seed])

    option_cases = (
        ('Default (Auto Notation)', dict()),
        ('Standard Notation', dict(notation='std')),
        ('Engineering Notation', dict(notation='eng')),
        ('Scientific Notation', dict(notation='sci')),
        ('Standard Notation with zero stripping',
         dict(notation='std', strip_zeros=True)),
        ('Scientific Notation with zero stripping',
         dict(notation='sci', strip_zeros=True)),
        ('Standard Notation with integer preservation',
         dict(notation='std', preserve_integer=True)),
        ('Auto Notation with exponent limit of 5', dict(auto_limit=5)),
    )

    precisions = tuple(range(1, 6))

    # prints out the label, function call, and precision table
    for options_description, options_dict in option_cases:
        '''
        Prints label for table.
        Ex:
        Default (Auto Notation):
            to_precision(value, precision)
        '''
        print(options_description + ':')
        options_string = ', '.join(['value', 'precision'] + [
            note + '=' + repr(inputs) for note, inputs in options_dict.items()
        ])
        print('to_precision({inputs})'.format(inputs=options_string),
              end='\n' * 2)

        table = []
        for val in test_values:
            table_row = ['{:0.10f}'.format(val).rstrip('0').rstrip('.')]
            for precision in precisions:
                result_string = to_precision(val, precision, **options_dict)
                table_row.append(result_string)
            table.append(table_row)

        headers = ['value'] + ['precision={}'.format(x) for x in precisions]

        print(tabulate(table, headers, disable_numparse=True), end='\n' * 3)
Esempio n. 15
0
def latex_from_2darray(A, presentation_type='f', digits=2):
    r"""latex_from_2darray
    This function assumes that A is one of these things:
            - a number (float or complex)
            - a 2D ndarray (float or complex)

    If A is a scalar, the string is a single number, not wrapped in brackets.

    It A is a numpy 2D array, it returns a string with the format:
        '\begin{bmatrix} ... & ... \\ ... & ... \end{bmatrix}'

    If presentation_type is 'sigfig', each number is formatted using the
    to_precision module to "digits" significant figures.

    Otherwise, each number is formatted as '{:.{digits}{presentation_type}}'.
    """
    # if A is a scalar
    if np.isscalar(A):
        if presentation_type == 'sigfig':
            return string_from_number_sigfig(A, digits=digits)
        else:
            return '{:.{digits}{presentation_type}}'.format(
                A, digits=digits, presentation_type=presentation_type)

    if presentation_type == 'sigfig':
        formatter = {
            'float_kind': lambda x: to_precision.to_precision(x, digits),
            'complex_kind': lambda x: _string_from_complex_sigfig(x, digits)
        }
    else:
        formatter = {
            'float_kind':
            lambda x: '{:.{digits}{presentation_type}}'.format(
                x, digits=digits, presentation_type=presentation_type),
            'complex_kind':
            lambda x: '{:.{digits}{presentation_type}}'.format(
                x, digits=digits, presentation_type=presentation_type)
        }

    if A.ndim != 2:
        raise ValueError('input should be a 2D numpy array')
    lines = np.array2string(A, formatter=formatter).replace('[', '').replace(
        ']', '').splitlines()
    rv = [r'\begin{bmatrix}']
    rv += ['  ' + ' & '.join(l.split()) + r'\\' for l in lines]
    rv += [r'\end{bmatrix}']
    return ''.join(rv)
Esempio n. 16
0
def parse_data(text):

    lines = text.splitlines()[3:]
    header = [
        'Rank', 'Coin', 'Price (USD)', 'Change (24H)', 'Change (1H)',
        'Market Cap (USD)', 'Spark (1H)'
    ]
    header_c = [colored(x, 'yellow') for x in header]

    data = [header_c]
    rank = 0
    for line in lines:
        if '----' in line:
            continue
        parts = line.strip().split()
        code = parts[3]
        price = float(parts[5])
        change_24h = float(parts[7][:-1])
        change_1h = float(parts[9][:-1])
        cap = parts[11]
        if cap[-1] == 'B':
            cap = float(cap[:-1])
        else:
            cap = float(cap[:-1])

        entry = {
            'code': code,
            'price': price,
            'change_24h': change_24h,
            'change_1h': change_1h,
            'cap': cap,
        }
        save_data(entry)
        spark = generate_spark(code)

        change_24h = colorize_number("%.2f%%" % change_24h)
        change_1h = colorize_number("%.2f%%" % change_1h)
        code = colored(code, 'cyan')
        price = colored(to_precision(price, 6), 'cyan')
        cap = str(cap) + 'B'

        rank += 1
        data.append([rank, code, price, change_24h, change_1h, cap, spark])

    return data
Esempio n. 17
0
def latex_from_2darray(A, presentation_type='f', digits=2):

    r"""latex_from_2darray
    This function assumes that A is one of these things:
            - a number (float or complex)
            - a 2D ndarray (float or complex)

    If A is a scalar, the string is a single number, not wrapped in brackets.

    It A is a numpy 2D array, it returns a string with the format:
        '\begin{bmatrix} ... & ... \\ ... & ... \end{bmatrix}'

    If presentation_type is 'sigfig', each number is formatted using the
    to_precision module to "digits" significant figures.

    Otherwise, each number is formatted as '{:.{digits}{presentation_type}}'.
    """
    # if A is a scalar
    if np.isscalar(A):
        if presentation_type == 'sigfig':
            return string_from_number_sigfig(A, digits=digits)
        else:
            return '{:.{digits}{presentation_type}}'.format(A, digits=digits, presentation_type=presentation_type)

    if presentation_type == 'sigfig':
        formatter = {
            'float_kind': lambda x: to_precision.to_precision(x, digits),
            'complex_kind': lambda x: _string_from_complex_sigfig(x, digits)
        }
    else:
        formatter = {
            'float_kind': lambda x: '{:.{digits}{presentation_type}}'.format(x, digits=digits, presentation_type=presentation_type),
            'complex_kind': lambda x: '{:.{digits}{presentation_type}}'.format(x, digits=digits, presentation_type=presentation_type)
        }

    if A.ndim != 2:
        raise ValueError('input should be a 2D numpy array')
    lines = np.array2string(A, formatter=formatter).replace('[', '').replace(']', '').splitlines()
    rv = [r'\begin{bmatrix}']
    rv += ['  ' + ' & '.join(l.split()) + r'\\' for l in lines]
    rv += [r'\end{bmatrix}']
    return ''.join(rv)
Esempio n. 18
0
def colorize_entries(entries, f_currency):

    data = []

    for rank, entry in enumerate(entries):
        code = entry['code']
        price = f_currency(entry['price'])
        change_24h = entry['change_24h']
        change_1h = entry['change_1h']
        cap = f_currency(entry['cap'])

        spark = generate_spark(code)

        change_24h = colorize_number("%.2f%%" % change_24h)
        change_1h = colorize_number("%.2f%%" % change_1h)
        code = colored(code, 'cyan')
        price = colored(to_precision(price, 6), 'cyan')
        cap = human_format(cap)

        data.append([rank + 1, code, price, change_24h, change_1h, cap, spark])

    return data
Esempio n. 19
0
def string_from_numpy(A, language='python', presentation_type='f', digits=2):
    """string_from_numpy(A)

    This function assumes that A is one of these things:

        - a number (float or complex)
        - a 1D ndarray (float or complex)
        - a 2D ndarray (float or complex)

    It returns A as a string.

    If language is 'python' and A is a 2D ndarray, the string looks like this:

        [[ ..., ... ], [ ..., ... ]]

    If A is a 1D ndarray, the string looks like this:

        [ ..., ..., ... ]

    If language is 'matlab' and A is a 2D ndarray, the string looks like this:

        [ ... ... ; ... ... ]

    If A is a 1D ndarray, the string looks like this:

        [ ..., ..., ... ]

    If language is 'mathematica' and A is a 2D ndarray, the string looks like this:

        {{ ..., ... },{ ..., ... }}

    If A is a 1D ndarray, the string looks like this:

        { ..., ..., ... }

    If language is 'r' and A is a 2D ndarray, the string looks like this:

        matrix(c(., ., .), nrow=NUM_ROWS, ncol=NUM_COLS, byrow = TRUE)

    If A is a 1D ndarray, the string looks like this:

        c(., ., .)

    In either case, if A is not a 1D or 2D ndarray, the string is a single number,
    not wrapped in brackets.

    If presentation_type is 'sigfig', each number is formatted using the
    to_precision module to "digits" significant figures.

    Otherwise, each number is formatted as '{:.{digits}{presentation_type}}'.
    """

    # if A is a scalar
    if np.isscalar(A):
        if presentation_type == 'sigfig':
            return string_from_number_sigfig(A, digits=digits)
        else:
            return '{:.{digits}{presentation_type}}'.format(
                A, digits=digits, presentation_type=presentation_type)

    # if A is a 1D or 2D ndarray
    if language == 'python':
        if presentation_type == 'sigfig':
            formatter = {
                'float_kind': lambda x: to_precision.to_precision(x, digits),
                'complex_kind':
                lambda x: _string_from_complex_sigfig(x, digits)
            }
        else:
            formatter = {
                'float_kind':
                lambda x: '{:.{digits}{presentation_type}}'.format(
                    x, digits=digits, presentation_type=presentation_type),
                'complex_kind':
                lambda x: '{:.{digits}{presentation_type}}'.format(
                    x, digits=digits, presentation_type=presentation_type)
            }
        return np.array2string(A, formatter=formatter,
                               separator=', ').replace('\n', '')
    elif language == 'matlab':
        if presentation_type == 'sigfig':
            return numpy_to_matlab_sf(A, ndigits=digits)
        else:
            return numpy_to_matlab(A, ndigits=digits, wtype=presentation_type)
    elif language == 'mathematica':
        if presentation_type == 'sigfig':
            formatter = {
                'float_kind': lambda x: to_precision.to_precision(x, digits),
                'complex_kind':
                lambda x: _string_from_complex_sigfig(x, digits)
            }
        else:
            formatter = {
                'float_kind':
                lambda x: '{:.{digits}{presentation_type}}'.format(
                    x, digits=digits, presentation_type=presentation_type),
                'complex_kind':
                lambda x: '{:.{digits}{presentation_type}}'.format(
                    x, digits=digits, presentation_type=presentation_type)
            }
        result = np.array2string(A, formatter=formatter,
                                 separator=', ').replace('\n', '')
        result = result.replace('[', '{')
        result = result.replace(']', '}')
        return result
    elif language == 'r':
        if presentation_type == 'sigfig':
            formatter = {
                'float_kind': lambda x: to_precision.to_precision(x, digits),
                'complex_kind':
                lambda x: _string_from_complex_sigfig(x, digits)
            }
        else:
            formatter = {
                'float_kind':
                lambda x: '{:.{digits}{presentation_type}}'.format(
                    x, digits=digits, presentation_type=presentation_type),
                'complex_kind':
                lambda x: '{:.{digits}{presentation_type}}'.format(
                    x, digits=digits, presentation_type=presentation_type)
            }
        result = np.array2string(A, formatter=formatter,
                                 separator=', ').replace('\n', '')
        # Given as: [[1, 2, 3], [4, 5, 6]]
        result = result.replace('[', '')
        result = result.replace(']', '')
        # Cast to a vector: c(1, 2, 3, 4, 5, 6)
        result = f'c({result})'
        if A.ndim == 2:
            nrow = A.shape[0]
            ncol = A.shape[1]
            result = f'matrix({result}, nrow = {nrow}, ncol = {ncol}, byrow = TRUE)'
        return result
    else:
        raise Exception(
            'language "{:s}" must be either "python", "matlab", "mathematica", or "r"'
            .format(language))
Esempio n. 20
0
def render(element_html, element_index, data):
    element = lxml.html.fragment_fromstring(element_html)
    name = pl.get_string_attrib(element, 'answers_name')
    label = pl.get_string_attrib(element, 'label', None)
    suffix = pl.get_string_attrib(element, 'suffix', None)
    display = pl.get_string_attrib(element, 'display', 'inline')

    if data['panel'] == 'question':
        editable = data['editable']
        raw_submitted_answer = data['raw_submitted_answers'].get(name, None)

        # Get comparison parameters and info strings
        comparison = pl.get_string_attrib(element, 'comparison', 'relabs')
        if comparison == 'relabs':
            rtol = pl.get_float_attrib(element, 'rtol', 1e-5)
            atol = pl.get_float_attrib(element, 'atol', 1e-8)
            info_params = {
                'format': True,
                'relabs': True,
                'rtol': rtol,
                'atol': atol
            }
        elif comparison == 'sigfig':
            digits = pl.get_integer_attrib(element, 'digits', 2)
            info_params = {'format': True, 'sigfig': True, 'digits': digits}
        elif comparison == 'decdig':
            digits = pl.get_integer_attrib(element, 'digits', 2)
            info_params = {'format': True, 'decdig': True, 'digits': digits}
        else:
            raise ValueError(
                'method of comparison "%s" is not valid (must be "relabs", "sigfig", or "decdig")'
                % comparison)
        with open('pl_number_input.mustache', 'r') as f:
            info = chevron.render(f, info_params).strip()
        with open('pl_number_input.mustache', 'r') as f:
            info_params.pop('format', None)
            info_params['shortformat'] = True
            shortinfo = chevron.render(f, info_params).strip()

        html_params = {
            'question': True,
            'name': name,
            'label': label,
            'suffix': suffix,
            'editable': editable,
            'info': info,
            'shortinfo': shortinfo
        }

        partial_score = data['partial_scores'].get(name, {'score': None})
        score = partial_score.get('score', None)
        if score is not None:
            try:
                score = float(score)
                if score >= 1:
                    html_params['correct'] = True
                elif score > 0:
                    html_params['partial'] = math.floor(score * 100)
                else:
                    html_params['incorrect'] = True
            except:
                raise ValueError('invalid score' + score)

        if display == 'inline':
            html_params['inline'] = True
        elif display == 'block':
            html_params['block'] = True
        else:
            raise ValueError(
                'method of display "%s" is not valid (must be "inline", "block", or "display")'
                % display)
        if raw_submitted_answer is not None:
            html_params['raw_submitted_answer'] = escape(raw_submitted_answer)
        with open('pl_number_input.mustache', 'r') as f:
            html = chevron.render(f, html_params).strip()

    elif data['panel'] == 'submission':
        parse_error = data['format_errors'].get(name, None)
        html_params = {
            'submission': True,
            'label': label,
            'parse_error': parse_error
        }
        if parse_error is None:
            a_sub = data['submitted_answers'][name]
            html_params['suffix'] = suffix
            html_params['a_sub'] = '{:.12g}'.format(a_sub)
        else:
            raw_submitted_answer = data['raw_submitted_answers'].get(
                name, None)
            if raw_submitted_answer is not None:
                html_params['raw_submitted_answer'] = escape(
                    raw_submitted_answer)

        partial_score = data['partial_scores'].get(name, {'score': None})
        score = partial_score.get('score', None)
        if score is not None:
            try:
                score = float(score)
                if score >= 1:
                    html_params['correct'] = True
                elif score > 0:
                    html_params['partial'] = math.floor(score * 100)
                else:
                    html_params['incorrect'] = True
            except:
                raise ValueError('invalid score' + score)

        with open('pl_number_input.mustache', 'r') as f:
            html = chevron.render(f, html_params).strip()
    elif data['panel'] == 'answer':
        a_tru = data['correct_answers'].get(name, None)
        if a_tru is not None:

            # Get comparison parameters
            comparison = pl.get_string_attrib(element, 'comparison', 'relabs')
            if comparison == 'relabs':
                rtol = pl.get_float_attrib(element, 'rtol', 1e-5)
                atol = pl.get_float_attrib(element, 'atol', 1e-8)
                # FIXME: render correctly with respect to rtol and atol
                a_tru = '{:.12g}'.format(a_tru)
            elif comparison == 'sigfig':
                digits = pl.get_integer_attrib(element, 'digits', 2)
                a_tru = to_precision.to_precision(a_tru, digits)
            elif comparison == 'decdig':
                digits = pl.get_integer_attrib(element, 'digits', 2)
                a_tru = '{:.{ndigits}f}'.format(a_tru, ndigits=digits)
            else:
                raise ValueError(
                    'method of comparison "%s" is not valid (must be "relabs", "sigfig", or "decdig")'
                    % comparison)

            # FIXME: render correctly with respect to method of comparison
            html_params = {
                'answer': True,
                'label': label,
                'a_tru': a_tru,
                'suffix': suffix
            }
            with open('pl_number_input.mustache', 'r') as f:
                html = chevron.render(f, html_params).strip()
        else:
            html = ''
    else:
        raise Exception('Invalid panel type: %s' % data['panel'])

    return html
Esempio n. 21
0
    def test_auto(self):
        # Automatic conversion of input type to float
        self.assertEqual(to_precision("1.2", 2), '1.2')

        # within limit
        self.assertEqual(to_precision(-552, 2, notation='auto', delimiter='e'),
                         '-550')

        self.assertEqual(to_precision(552, 2, notation='auto', delimiter='e'),
                         '550')

        # over limit
        self.assertEqual(to_precision(1001, 2, notation='auto', delimiter='e'),
                         '1.0e3')

        self.assertEqual(
            to_precision(-1001, 2, notation='auto', delimiter='e'), '-1.0e3')

        self.assertEqual(
            to_precision(0.0009, 2, notation='auto', delimiter='e'), '9.0e-4')

        self.assertEqual(
            to_precision(-0.0009, 2, notation='auto', delimiter='e'),
            '-9.0e-4')

        # Auto limit
        self.assertEqual(to_precision(1234, 4, notation='auto', delimiter='e'),
                         '1.234e3')
        self.assertEqual(
            to_precision(1234, 4, notation='auto', delimiter='e',
                         auto_limit=4), '1234')

        self.assertEqual(to_precision(.001, 3, notation='auto', delimiter='e'),
                         '1.00e-3')
        self.assertEqual(
            to_precision(.001, 3, notation='auto', delimiter='e',
                         auto_limit=4), '0.00100')

        self.assertEqual(
            to_precision(12345,
                         5,
                         notation='auto',
                         delimiter='e',
                         auto_limit=4), '1.2345e4')
        self.assertEqual(
            to_precision(12345,
                         5,
                         notation='auto',
                         delimiter='e',
                         auto_limit=5), '12345')

        self.assertEqual(
            to_precision(.000123,
                         3,
                         notation='auto',
                         delimiter='e',
                         auto_limit=4), '1.23e-4')
        self.assertEqual(
            to_precision(.000123,
                         3,
                         notation='auto',
                         delimiter='e',
                         auto_limit=5), '0.000123')

        # preserve_integer
        self.assertEqual(
            to_precision(12345,
                         2,
                         notation='auto',
                         preserve_integer=False,
                         auto_limit=5), '12000')
        self.assertEqual(
            to_precision(12345,
                         2,
                         notation='auto',
                         preserve_integer=True,
                         auto_limit=5), '12345')

        # Zero stripping
        self.assertEqual(
            to_precision(12000000, 5, notation='auto', strip_zeros=False),
            '1.2000e7')
        self.assertEqual(
            to_precision(12000000, 5, notation='auto', strip_zeros=True),
            '1.2e7')
        self.assertEqual(
            to_precision(12000000, 5, notation='sci', strip_zeros=False),
            '1.2000e7')
        self.assertEqual(
            to_precision(12000000, 5, notation='sci', strip_zeros=True),
            '1.2e7')
        self.assertEqual(
            to_precision(12000000, 5, notation='eng', strip_zeros=False),
            '12.000e6')
        self.assertEqual(
            to_precision(12000000, 5, notation='eng', strip_zeros=True),
            '12e6')
        self.assertEqual(
            to_precision(12, 5, notation='std', strip_zeros=False), '12.000')
        self.assertEqual(to_precision(12, 5, notation='std', strip_zeros=True),
                         '12')
 def as_2sf(number):
     return to_precision.to_precision(number,
                                      2,
                                      notation='std',
                                      preserve_integer=True).strip(".")
Esempio n. 23
0
def string_from_numpy(A, language='python', presentation_type='f', digits=2):
    """string_from_numpy(A)

    This function assumes that A is one of these things:

        - a number (float or complex)
        - a 1D ndarray (float or complex)
        - a 2D ndarray (float or complex)

    It returns A as a string.

    If language is 'python' and A is a 2D ndarray, the string looks like this:

        [[ ..., ... ], [ ..., ... ]]

    If A is a 1D ndarray, the string looks like this:

        [ ..., ..., ... ]

    If language is 'matlab' and A is a 2D ndarray, the string looks like this:

        [ ... ... ; ... ... ]

    If A is a 1D ndarray, the string looks like this:

        [ ..., ..., ... ]

    If language is 'mathematica' and A is a 2D ndarray, the string looks like this:

        {{ ..., ... },{ ..., ... }}

    If A is a 1D ndarray, the string looks like this:

        { ..., ..., ... }

    In either case, if A is not a 1D or 2D ndarray, the string is a single number,
    not wrapped in brackets.

    If presentation_type is 'sigfig', each number is formatted using the
    to_precision module to "digits" significant figures.

    Otherwise, each number is formatted as '{:.{digits}{presentation_type}}'.
    """

    # if A is a scalar
    if np.isscalar(A):
        if presentation_type == 'sigfig':
            return string_from_number_sigfig(A, digits=digits)
        else:
            return '{:.{digits}{presentation_type}}'.format(A, digits=digits, presentation_type=presentation_type)

    # if A is a 1D or 2D ndarray
    if language == 'python':
        if presentation_type == 'sigfig':
            formatter = {
                'float_kind': lambda x: to_precision.to_precision(x, digits),
                'complex_kind': lambda x: _string_from_complex_sigfig(x, digits)
            }
        else:
            formatter = {
                'float_kind': lambda x: '{:.{digits}{presentation_type}}'.format(x, digits=digits, presentation_type=presentation_type),
                'complex_kind': lambda x: '{:.{digits}{presentation_type}}'.format(x, digits=digits, presentation_type=presentation_type)
            }
        return np.array2string(A, formatter=formatter, separator=', ').replace('\n', '')
    elif language == 'matlab':
        if presentation_type == 'sigfig':
            return numpy_to_matlab_sf(A, ndigits=digits)
        else:
            return numpy_to_matlab(A, ndigits=digits, wtype=presentation_type)
    elif language == 'mathematica':
        if presentation_type == 'sigfig':
            formatter = {
                'float_kind': lambda x: to_precision.to_precision(x, digits),
                'complex_kind': lambda x: _string_from_complex_sigfig(x, digits)
            }
        else:
            formatter = {
                'float_kind': lambda x: '{:.{digits}{presentation_type}}'.format(x, digits=digits, presentation_type=presentation_type),
                'complex_kind': lambda x: '{:.{digits}{presentation_type}}'.format(x, digits=digits, presentation_type=presentation_type)
            }
        result = np.array2string(A, formatter=formatter, separator=', ').replace('\n', '')
        result = result.replace('[', '{')
        result = result.replace(']', '}')
        return result
    else:
        raise Exception('language "{:s}" must be either "python", "matlab", or "mathematica"'.format(language))