• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

sandialabs / toyplot / 9912662049

12 Jul 2024 06:45PM UTC coverage: 94.497% (-0.1%) from 94.629%
9912662049

Pull #214

github

web-flow
Merge cce091bb5 into 93ab5d60c
Pull Request #214: add as_float, change repr(x) -> str(x)

70 of 87 new or added lines in 10 files covered. (80.46%)

31 existing lines in 2 files now uncovered.

5409 of 5724 relevant lines covered (94.5%)

8.5 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

87.84
/toyplot/require.py
1
# Copyright 2014, Sandia Corporation. Under the terms of Contract
2
# DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain
3
# rights in this software.
4

5
"""Functions used by the Toyplot implementation to validate inputs.  These are not intended for end-users.
6
"""
7

8

9
import numbers
9✔
10
import numpy
9✔
11

12
def instance(value, types):
9✔
13
    """Raise an exception if a value isn't one of the given type(s)."""
14
    if not isinstance(value, types):
9✔
15
        raise ValueError("Expected %s, received %s." % (types, type(value))) # pragma: no cover
16
    return value
9✔
17

18

19
def value_in(value, choices):
9✔
20
    """Raise an exception if a value doesn't match one of the given choices."""
21
    if value not in choices:
9✔
22
        raise ValueError("Expected one of %s, received %r." % (", ".join([repr(choice) for choice in choices]), value)) # pragma: no cover
23
    return value
9✔
24

25

26
def table_keys(table, keys, length=None, min_length=None, modulus=None):
9✔
27
    """Raise an exception if any of the given keys fails to match the column keys in the given table."""
28
    keys = string_vector(keys, length=length, min_length=min_length, modulus=modulus)
9✔
29
    allowed = list(table.keys())
9✔
30
    for key in keys:
9✔
31
        if key not in allowed:
9✔
32
            raise ValueError("Table key must match one of %s, received %s." % (", ".join(allowed), key)) # pragma: no cover
33
    return keys
9✔
34

35

36
def scalar(value):
9✔
37
    """Raise an exception if a value isn't a number."""
38
    if not isinstance(value, numbers.Number):
9✔
39
        raise ValueError("Expected a number, received %s." % value) # pragma: no cover
40
    return value
9✔
41

42

43
def scalar_array(value):
9✔
44
    """Raise an exception if a value isn't convertable to an array of numbers."""
45
    array = numpy.ma.array(value).astype("float64")
9✔
46
    array.mask = numpy.ma.mask_or(array.mask, ~numpy.isfinite(array))
9✔
47
    return array
9✔
48

49

50
def vector(value, length=None, min_length=None, modulus=None):
9✔
51
    """Raise an exception if a value isn't convertable to a 1D array."""
52
    array = numpy.ma.array(value)
9✔
53
    if array.shape == ():
9✔
54
        array = numpy.ma.repeat(array, 1)
9✔
55
    if array.ndim != 1:
9✔
56
        raise ValueError("Expected a vector.") # pragma: no cover
57
    if length is not None:
9✔
58
        if len(array) != length:
9✔
59
            raise ValueError("Expected %s values, received %s" % (length, len(array))) # pragma: no cover
60
    if min_length is not None:
9✔
61
        if len(array) < min_length:
9✔
62
            raise ValueError("Expected %s or more values, received %s" % (min_length, len(array))) # pragma: no cover
63
    if modulus is not None:
9✔
64
        if len(array) % modulus != 0:
9✔
65
            raise ValueError("Expected a multiple of %s values, received %s" % (modulus, len(array))) # pragma: no cover
66
    return array
9✔
67

68

69
def integer_vector(value, length=None, min_length=None, modulus=None):
9✔
70
    """Raise an exception if a value isn't convertable to a 1D array of integers."""
71
    return vector(value, length=length, min_length=min_length, modulus=modulus).astype("int64")
9✔
72

73

74
def scalar_vector(value, length=None, min_length=None, modulus=None):
9✔
75
    """Raise an exception if a value isn't convertable to a 1D array of numbers."""
76
    return vector(value, length=length, min_length=min_length, modulus=modulus).astype("float64")
9✔
77

78

79
def string_vector(value, length=None, min_length=None, modulus=None):
9✔
80
    """Raise an exception if a value isn't convertable to a 1D array of numbers."""
81
    return vector(value, length=length, min_length=min_length, modulus=modulus).astype("unicode")
9✔
82

83

84
def scalar_matrix(value, rows=None, columns=None):
9✔
85
    """Raise an exception if a value isn't convertable to a 2D array of numbers."""
86
    array = scalar_array(value)
9✔
87
    if array.ndim != 2:
9✔
88
        raise ValueError("Expected a matrix.") # pragma: no cover
89
    if rows is not None:
9✔
90
        if array.shape[0] != rows:
9✔
91
            raise ValueError("Expected %s rows, received %s." % (rows, array.shape[0])) # pragma: no cover
92
    if columns is not None:
9✔
93
        if array.shape[1] != columns:
9✔
94
            raise ValueError("Expected %s columns, received %s." % (columns, array.shape[1])) # pragma: no cover
95
    return array
9✔
96

97

98
def optional_string(value):
9✔
99
    """Raise an exception if a value isn't a string, or None."""
100
    if not isinstance(value, (str, type(None))):
9✔
101
        raise ValueError("Expected a string value or None, received %s." % value) # pragma: no cover
102
    return value
9✔
103

104

105
def filename(value):
9✔
106
    """Raise an exception if a value isn't a valid string filename, or None."""
107
    return optional_string(value)
9✔
108

109

110
def hyperlink(value):
9✔
111
    """Raise an exception if a value isn't a valid string hyperlink, or None."""
112
    return optional_string(value)
9✔
113

114
def as_int(value,precision=None):
9✔
115
    """Raise an exception if a value cannot be converted to an int, or value 
116
    coerced to a python int. precision is optional but can be 8, 16, etc."""
117

118
    # Try simple conversion; if this fails, move on
NEW
119
    try:
×
NEW
120
        return int(value,precision)
×
NEW
121
    except ValueError:
×
NEW
122
        pass
×
123

124
    # If simple conversion failed, try to parse as a np.int64(value) string
NEW
125
    try:
×
NEW
126
        return int(value.split("(")[-1].split(")")[0],precision)
×
NEW
127
    except Exception as e:
×
NEW
128
        err = f"'{value}' could not be converted to a float."
×
NEW
129
        raise ValueError(err) from e
×
130

131

132
def as_float(value):
9✔
133
    """Raise an exception if a value cannot be converted to a float, or value 
134
    coerced to a python float."""
135

136
    # Try simple conversion; if this fails, move on
137
    try:
9✔
138
        return float(value)
9✔
139
    except ValueError:
9✔
140
        pass
9✔
141

142
    # If simple conversion failed, try to parse as a np.float64(value) string
143
    try:
9✔
144
        return float(value.split("(")[-1].split(")")[0])
9✔
145
    except Exception as e:
9✔
146
        err = f"'{value}' could not be converted to a float."
9✔
147
        raise ValueError(err) from e
9✔
148
                
149

150
            
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc