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

iprafols / SQUEzE / 20310179563

17 Dec 2025 04:38PM UTC coverage: 65.567% (+8.1%) from 57.439%
20310179563

Pull #84

gihtub

web-flow
Merge d656bc5ca into 741eeef2c
Pull Request #84: added new peak finder, optimized code

240 of 462 branches covered (51.95%)

Branch coverage included in aggregate %.

150 of 183 new or added lines in 11 files covered. (81.97%)

4 existing lines in 4 files now uncovered.

1032 of 1478 relevant lines covered (69.82%)

2.09 hits per line

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

79.17
/py/squeze/utils.py
1
"""
2
    SQUEzE
3
    ======
4

5
    This file provides useful functions that are used throughout SQUEzE to
6
    avoid duplicate code
7
    """
8
__author__ = "Ignasi Perez-Rafols (iprafols@gmail.com)"
3✔
9

10
import importlib
3✔
11
import os
3✔
12
import json
3✔
13
import pandas as pd
3✔
14
import numpy as np
3✔
15

16

17
def class_from_string(class_name, module_name):
3✔
18
    """Return a class from a string. The class must be saved in a module
19
    under squeze with the same name as the class but
20
    lowercase and with and underscore. For example class 'MyClass' should
21
    be in module squeze.my_class
22

23
    Arguments
24
    ---------
25
    class_name: str
26
    Name of the class to load
27

28
    module_name: str
29
    Name of the module containing the class
30

31
    Return
32
    ------
33
    class_object: Class
34
    The loaded class
35

36
    deafult_args: dict
37
    A dictionary with the default options (empty for no default options)
38

39
    accepted_options: list
40
    A list with the names of the accepted options
41

42
    Raise
43
    -----
44
    ImportError if module cannot be loaded
45
    AttributeError if class cannot be found
46
    """
47
    # load module
48
    module_object = importlib.import_module(module_name)
3✔
49
    # get the class
50
    class_object = getattr(module_object, class_name)
3✔
51
    # get the dictionary with the default arguments
52
    try:
3✔
53
        default_args = getattr(module_object, "defaults")
3✔
54
    except AttributeError:
×
55
        default_args = {}
×
56
    # get the list with the valid options
57
    try:
3✔
58
        accepted_options = getattr(module_object, "accepted_options")
3✔
59
    except AttributeError:
×
60
        accepted_options = []
×
61
    return class_object, default_args, accepted_options
3✔
62

63

64
def function_from_string(function_name, module_name):
3✔
65
    """Return a function from a string. The class must be saved in a module
66
    under squeze. For example squeze.utils
67

68
    Arguments
69
    ---------
70
    function_name: str
71
    Name of the function to load
72

73
    module_name: str
74
    Full name of the module containing the class. E.g. squeze.utils
75

76
    Return
77
    ------
78
    function_object: function
79
    The loaded function
80

81
    Raise
82
    -----
83
    ImportError if module cannot be loaded
84
    AttributeError if class cannot be found
85
    """
86
    # load module
87
    module_object = importlib.import_module(module_name)
3✔
88
    # get the class
89
    function_name = getattr(module_object, function_name)
3✔
90

91
    return function_name
3✔
92

93

94
def serialize(obj):
3✔
95
    """ Serializes complex objects. If the object type is not considered
96
        for this function, raise a TypeError (as per save_json documentation
97
        requirements)
98

99
        Parameters
100
        ----------
101
        obj : object
102
        Object to serialize
103

104
        Returns
105
        -------
106
        encodable_object: Object
107
        An encodable version of the object
108

109
        Raises
110
        ------
111
        TypeError upon unsuccesful serialization
112
        """
113
    encodable_object = None
3✔
114
    # deal with normal numpy arrays
115
    if isinstance(obj, np.ndarray):
3✔
116
        encodable_object = {
3✔
117
            "np.ndarray": {
118
                "data": obj.tolist(),
119
                "dtype": obj.dtype
120
            }
121
        }
122

123
    # deal with numpy ints
124
    elif isinstance(obj, np.int64):
3✔
125
        encodable_object = int(obj)
3✔
126
    elif isinstance(obj, np.int32):
3✔
127
        encodable_object = int(obj)
3✔
128
    elif isinstance(obj, np.int16):
3!
NEW
129
        encodable_object = int(obj)
×
130

131
    # deal with numpy floats
132
    elif isinstance(obj, np.float32):
3!
133
        encodable_object = float(obj)
×
134

135
    # deal with numpy bools
136
    elif isinstance(obj, np.bool_):
3!
137
        encodable_object = bool(obj)
×
138

139
    # deal with other numpy objects
140
    elif isinstance(obj, np.dtype):
3✔
141
        encodable_object = str(obj)
3✔
142

143
    # deal with pandas objects
144
    elif isinstance(obj, pd.DataFrame):
3!
145
        encodable_object = {"pd.DataFrame": obj.to_json()}
×
146

147
    # deal with complex objects
148
    elif hasattr(obj, "__dict__"):
3!
149
        encodable_object = obj.__dict__
3✔
150

151
    # raise error if the object serialization is not addressed by this class
152
    if encodable_object is None:
3!
153
        obj_type = str(type(obj))
×
154
        if obj_type.startswith("<class '"):
×
155
            obj_type = obj_type[8:-2]
×
156
        raise TypeError(f"Object of type {obj_type} is not JSON serializable")
×
157
    return encodable_object
3✔
158

159

160
def deserialize(json_dict):
3✔
161
    """ Deserializes json dictionary. The dictionary must contain only one item
162
        which has to be either an array or a pandas DataFrame. For serialization
163
        of more complex objects, prefer the class method from_json of the respective
164
        object
165

166
        Parameters
167
        ----------
168
        json_dict : dict
169
        Object to deserialize
170

171
        Returns
172
        -------
173
        my_object : Object
174
        The object
175
        """
176
    my_object = None
3✔
177
    if "np.ndarray" in json_dict:
3✔
178
        aux = json_dict.get("np.ndarray")
3✔
179
        my_object = np.array(aux.get("data"), dtype=aux.get("dtype"))
3✔
180
    if "pd.DataFrame" in json_dict:
3✔
181
        my_object = pd.read_json(json_dict.get("pd.DataFrame"))
3✔
182
    return my_object
3✔
183

184

185
def save_json(filename, user_object):
3✔
186
    """ Saves object into filename. Encoding file as a json object.
187
        Complex object are saved using their __dict__ property"""
188
    with open(os.path.expandvars(filename), 'w', encoding="UTF-8") as outfile:
3✔
189
        json.dump(user_object, outfile, indent=0, default=serialize)
3✔
190

191

192
def load_json(filename):
3✔
193
    """ Loads object from filename. File must be encoded as a json object
194

195
        Returns
196
        -------
197
        The loaded object
198
        """
199
    with open(os.path.expandvars(filename), encoding="UTF-8") as json_file:
3✔
200
        user_object = json.load(json_file)
3✔
201
    return user_object
3✔
202

203

204
def verboseprint(*args):
3✔
205
    """ Print each argument separately so caller doesn't need to
206
        stuff everything to be printed into a single string
207
        """
208
    for arg in args:
3✔
209
        print(arg, end=" ")
3✔
210
    print("")
3✔
211

212

213
def quietprint(*args):  # pylint: disable=unused-argument
3✔
214
    """ Don't print anything
215
        """
216

217

218
if __name__ == '__main__':
219
    pass
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

© 2026 Coveralls, Inc