-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathutils.py
86 lines (71 loc) · 2.57 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# Copyright 2024 The PyMC Labs Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Utility functions
"""
from typing import Union
import numpy as np
import pandas as pd
import xarray as xr
def _is_variable_dummy_coded(series: pd.Series) -> bool:
"""Check if a data in the provided Series is dummy coded. It should be 0 or 1
only."""
return len(set(series).difference(set([0, 1]))) == 0
def _series_has_2_levels(series: pd.Series) -> bool:
"""Check that the variable in the provided Series has 2 levels"""
return len(pd.Categorical(series).categories) == 2
def round_num(n, round_to):
"""
Return a string representing a number with `round_to` significant figures.
Parameters
----------
n : float
number to round
round_to : int
number of significant figures
"""
sig_figs = _format_sig_figs(n, round_to)
return f"{n:.{sig_figs}g}"
def _format_sig_figs(value, default=None):
"""Get a default number of significant figures.
Gives the integer part or `default`, whichever is bigger.
Examples
--------
0.1234 --> 0.12
1.234 --> 1.2
12.34 --> 12
123.4 --> 123
"""
if default is None:
default = 2
if value == 0:
return 1
return max(int(np.log10(np.abs(value))) + 1, default)
def convert_to_string(x: Union[float, xr.DataArray], round_to: int = 2) -> str:
"""Utility function which takes in numeric inputs and returns a string."""
if isinstance(x, float):
# In the case of a float, we return the number rounded to 2 decimal places
return f"{x:.2f}"
elif isinstance(x, xr.DataArray):
# In the case of an xarray object, we return the mean and 94% CI
percentiles = x.quantile([0.03, 1 - 0.03]).values
ci = (
r"$CI_{94\%}$"
+ f"[{round_num(percentiles[0], round_to)}, {round_num(percentiles[1], round_to)}]"
)
return f"{x.mean().values:.2f}" + ci
else:
raise ValueError(
"Type not supported. Please provide a float or an xarray object."
)