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

aewallin / allantools / 6997134815

26 Nov 2023 05:57PM UTC coverage: 74.663% (-10.1%) from 84.742%
6997134815

push

github

aewallin
coverage workflow

1273 of 1705 relevant lines covered (74.66%)

2.17 hits per line

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

73.63
/allantools/dataset.py
1
"""
2
Allantools dataset object
3

4
**Authors:** Frederic Meynadier (frederic.meynadier "at" gmail.com),
5
    Mike DePalatis (http://mike.depalatis.net)
6

7
Version history
8
---------------
9

10
**2019.07**
11
- Initial release
12

13
License
14
-------
15

16
This program is free software: you can redistribute it and/or modify
17
it under the terms of the GNU Lesser General Public License as published by
18
the Free Software Foundation, either version 3 of the License, or
19
(at your option) any later version.
20

21
This program is distributed in the hope that it will be useful,
22
but WITHOUT ANY WARRANTY; without even the implied warranty of
23
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24
GNU Lesser General Public License for more details.
25

26
You should have received a copy of the GNU Lesser General Public License
27
along with this program.  If not, see <http://www.gnu.org/licenses/>.
28

29
"""
30

31
from . import allantools
2✔
32

33

34
class Dataset(object):
2✔
35
    """ Dataset class for Allantools
36

37
    :Example:
38
        ::
39

40
            import numpy as np
41
            # Load random data
42
            a = allantools.Dataset(data=np.random.rand(1000))
43
            # compute mdev
44
            a.compute("mdev")
45
            print(a.out["stat"])
46

47
    compute() returns the result of the computation and also stores it in the
48
    object's ``out`` member.
49

50
    """
51

52
    def __init__(self, data=None, rate=1.0, data_type="phase", taus=None):
3✔
53
        """ Initialize object with input data
54

55
        Parameters
56
        ----------
57
        data: np.array
58
            Input data. Provide either phase or frequency (fractional,
59
            adimensional)
60
        rate: float
61
            The sampling rate for data, in Hz. Defaults to 1.0
62
        data_type: {'phase', 'freq'}
63
            Data type, i.e. phase or frequency. Defaults to "phase".
64
        taus: np.array
65
            Array of tau values, in seconds, for which to compute statistic.
66
            Optionally set taus=["all"|"octave"|"decade"] for automatic
67
            calculation of taus list
68

69
        Returns
70
        -------
71
        Dataset()
72
            A Dataset() instance
73

74
        """
75
        #: input data Dict,
76
        self.inp = {"data": None,
3✔
77
                    "rate": None,
3✔
78
                    "data_type": None,
3✔
79
                    "taus": None}
3✔
80

81
        #: output data Dict, to be populated by compute()
82
        self.out = {"taus": None,
3✔
83
                    "stat": None,
3✔
84
                    "stat_err": None,
3✔
85
                    "stat_n": None,
3✔
86
                    "stat_unc": None,
3✔
87
                    "stat_id": None}
3✔
88
        self.inp["data"] = data
3✔
89
        self.inp["rate"] = rate
3✔
90
        self.inp["data_type"] = data_type
3✔
91
        self.inp["taus"] = taus
3✔
92

93
    def set_input(self, data,
2✔
94
                  rate=1.0, data_type="phase", taus=None):
1✔
95
        """ Optionnal method if you chose not to set inputs on init
×
96

97
        Parameters
×
98
        ----------
×
99
        data: np.array
×
100
            Input data. Provide either phase or frequency (fractional,
×
101
            adimensional)
×
102
        rate: float
×
103
            The sampling rate for data, in Hz. Defaults to 1.0
×
104
        data_type: {'phase', 'freq'}
×
105
            Data type, i.e. phase or frequency. Defaults to "phase".
×
106
        taus: np.array
×
107
            Array of tau values, in seconds, for which to compute statistic.
×
108
            Optionally set taus=["all"|"octave"|"decade"] for automatic
×
109
        """
×
110
        self.inp["data"] = data
3✔
111
        self.inp["rate"] = rate
3✔
112
        self.inp["data_type"] = data_type
3✔
113
        self.inp["taus"] = taus
3✔
114

115
    def compute(self, function):
3✔
116
        """Evaluate the passed function with the supplied data.
117

118
        Stores result in self.out.
119

120
        Parameters
121
        ----------
122
        function: str
123
            Name of the :mod:`allantools` function to evaluate
124

125
        Returns
126
        -------
127
        result: dict
128
            The results of the calculation.
129

130
        """
131
        try:
3✔
132
            func = getattr(allantools, function)
3✔
133
        except AttributeError:
3✔
134
            raise AttributeError("function must be defined in allantools")
3✔
135

136
        whitelisted = ["theo1", "mtie", "tierms"]
3✔
137

138
        if function[-3:] != "dev" and function not in whitelisted:
3✔
139
            # this should probably raise a custom exception type so
140
            # it's easier to distinguish from other bad things
141
            raise RuntimeError("function must be one of the 'dev' functions")
3✔
142
        result = func(self.inp["data"], rate=self.inp["rate"],
3✔
143
                      data_type=self.inp["data_type"], taus=self.inp["taus"])
3✔
144
        keys = ["taus", "stat", "stat_err", "stat_n"]
3✔
145
        result = {key: result[i] for i, key in enumerate(keys)}
3✔
146
        self.out = result.copy()
3✔
147
        self.out["stat_id"] = function
3✔
148
        return result
3✔
149

150
    def write_results(self, filename, digits=5, header_params={}):
3✔
151
        """ Output result to text
152

153
        Save calculation results to disk. Will overwrite any existing file.
154

155
        Parameters
156
        ----------
157
        filename: str
158
            Path to the output file
159
        digits: int
160
            Number of significant digits in output
161
        header_params: dict
162
            Arbitrary dict of params to be included in header
163

164
        Returns
165
        -------
166
        None
167
        """
168

169
        with open(filename, 'w') as fp:
3✔
170
            fp.write("# Generated by Allantools {}\n".format(
3✔
171
                allantools.__version__))
3✔
172
            fp.write("# Input data type: {}\n".format(self.inp["data_type"]))
3✔
173
            fp.write("# Input data rate: {}\n".format(self.inp["rate"]))
3✔
174
            for key, val in header_params.items():
3✔
175
                fp.write("# {}: {}\n".format(key, val))
3✔
176
            # Fields
177
            fp.write(("{af:>5s} {tau:>{width}s} {n:>10s} {alpha:>5s} "
3✔
178
                      "{minsigma:>{width}} "
×
179
                      "{sigma:>{width}} "
×
180
                      "{maxsigma:>{width}} "
×
181
                      "\n").format(
×
182
                          af="AF",
3✔
183
                          tau="Tau",
3✔
184
                          n="N",
3✔
185
                          alpha="alpha",
3✔
186
                          minsigma="min_" + self.out["stat_id"],
3✔
187
                          sigma=self.out["stat_id"],
3✔
188
                          maxsigma="max_" + self.out["stat_id"],
3✔
189
                          width=digits + 5
3✔
190
                      )
×
191
                     )
×
192
            out_fmt = ("{af:5d} {tau:.{prec}e} {n:10d} {alpha:5s} "
3✔
193
                       "{minsigma:.{prec}e} "
×
194
                       "{sigma:.{prec}e} "
×
195
                       "{maxsigma:.{prec}e} "
×
196
                       "\n")
×
197
            for i in range(len(self.out["taus"])):
3✔
198
                fp.write(out_fmt.format(
3✔
199
                    af=int(self.out["taus"][i] / self.out["taus"][0]),
3✔
200
                    tau=self.out["taus"][i],
3✔
201
                    n=int(self.out["stat_n"][i]),
3✔
202
                    alpha="NaN",  # Not implemented yet
3✔
203
                    minsigma=self.out["stat"][i] - self.out["stat_err"][i]/2,
3✔
204
                    sigma=self.out["stat"][i],
3✔
205
                    maxsigma=(self.out["stat"][i] +
3✔
206
                              self.out["stat_err"][i]/2),
3✔
207
                    prec=digits-1,
3✔
208
                ))
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