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

tonegas / nnodely / 13550104821

26 Feb 2025 05:45PM UTC coverage: 96.036% (+0.1%) from 95.922%
13550104821

push

github

tonegas
Revmoved all CHECK_NAMES = False in the tests and Fixed all the names replicated

273 of 273 new or added lines in 14 files covered. (100.0%)

4 existing lines in 2 files now uncovered.

10805 of 11251 relevant lines covered (96.04%)

0.96 hits per line

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

96.1
/nnodely/parameter.py
1
import copy, inspect, textwrap
1✔
2
import numpy as np
1✔
3

4
from collections.abc import Callable
1✔
5

6
from nnodely.relation import NeuObj, Relation
1✔
7
from nnodely.utils import check, enforce_types, NP_DTYPE
1✔
8

9

10
def is_numpy_float(var):
1✔
11
    return isinstance(var, (np.float16, np.float32, np.float64))
×
12

13
class Constant(NeuObj, Relation):
1✔
14
    """
15
    Represents a constant value in the neural network model.
16

17
    Parameters
18
    ----------
19
    name : str
20
        The name of the constant.
21
    values : list, float, int, or np.ndarray
22
        The values of the constant.
23
    tw : float or int, optional
24
        The time window for the constant. Default is None.
25
    sw : int, optional
26
        The sample window for the constant. Default is None.
27

28
    Attributes
29
    ----------
30
    name : str
31
        The name of the constant.
32
    dim : dict
33
        A dictionary containing the dimensions of the constant.
34
    json : dict
35
        A dictionary containing the configuration of the constant.
36

37
    Example
38
    -------
39
    Example - passing a custom scalar value -> g.dim = {'dim': 1}:
40

41
        >>> g = Constant('gravity',values=9.81)
42

43
    Example - passing a custom vector value -> n.dim = {'dim': 4}:
44

45
        >>> n = Constant('numbers', values=[1,2,3,4])
46

47
    Example - passing a custom vector value with single sample window -> n.dim = {'dim': 4, 'sw': 1}:
48

49
        >>> n = Constant('numbers', values=[[1,2,3,4]])
50

51
    Example - passing a custom vector value with double sample window -> n.dim = {'dim': 4, 'sw': 2}:
52

53
        >>> n = Constant('numbers', values=[[2,3,4],[1,2,3]])
54

55
    Example - passing a custom vector value with double sample window -> n.dim = {'dim': 4, 'sw': 2}.
56
    If the value of the sw is differnt from the dimension of shape[0] an error will be raised.
57

58
        >>> n = Constant('numbers', sw = 2, values=[[2,3,4],[1,2,3]])
59

60
    Example - passing a custom vector value with time window -> n.dim = {'dim': 4, 'tw': 4}.
61
    In this case the samplingtime must be 0.5 otherwise an error will be raised. If the Constant have a time dimension,
62
    the input must have a len(shape) == 2.
63

64
        >>> n = Constant('numbers', tw = 4, values=[[2,3,4],[1,2,3]])
65
    """
66
    @enforce_types
1✔
67
    def __init__(self, name:str,
1✔
68
                 values:list|float|int|np.ndarray,
69
                 tw:float|int|None = None,
70
                 sw:int|None = None):
71

72
        NeuObj.__init__(self, name)
1✔
73
        values = np.array(values, dtype=NP_DTYPE)
1✔
74
        shape = values.shape
1✔
75
        values = values.tolist()
1✔
76
        if len(shape) == 0:
1✔
77
            self.dim = {'dim': 1}
1✔
78
        else:
79
            check(len(shape) >= 2, ValueError,
1✔
80
              f"The shape of a Constant must have at least 2 dimensions or zero.")
81
            dimensions = shape[1] if len(shape[1:]) == 1 else list(shape[1:])
1✔
82
            self.dim = {'dim': dimensions}
1✔
83
            if tw is not None:
1✔
84
                check(sw is None, ValueError, "If tw is set sw must be None")
1✔
85
                self.dim['tw'] = tw
1✔
86
            elif sw is not None:
1✔
UNCOV
87
                self.dim['sw'] = sw
×
UNCOV
88
                check(shape[0] == self.dim['sw'],ValueError, f"The sw = {sw} is different from sw = {shape[0]} of the values.")
×
89
            else:
90
                self.dim['sw'] = shape[0]
1✔
91

92
        # deepcopy dimention information inside Parameters
93
        self.json['Constants'][self.name] = copy.deepcopy(self.dim)
1✔
94
        self.json['Constants'][self.name]['values'] = values
1✔
95

96
class Parameter(NeuObj, Relation):
1✔
97
    """
98
    Represents a parameter in the neural network model.
99

100
    Notes
101
    -----
102
    .. note::
103
        You can find some initialization functions for the 'init' and 'init_params' parameters inside the initializer module.
104

105
    Parameters
106
    ----------
107
    name : str
108
        The name of the parameter.
109
    dimensions : int, list, tuple, or None, optional
110
        The dimensions of the parameter. Default is None.
111
    tw : float or int, optional
112
        The time window for the parameter. Default is None.
113
    sw : int, optional
114
        The sample window for the parameter. Default is None.
115
    values : list, float, int, np.ndarray, or None, optional
116
        The values of the parameter. Default is None.
117
    init : Callable, optional
118
        A callable for initializing the parameter values. Default is None.
119
    init_params : dict, optional
120
        A dictionary of parameters for the initializer. Default is None.
121

122
    Attributes
123
    ----------
124
    name : str
125
        The name of the parameter.
126
    dim : dict
127
        A dictionary containing the dimensions of the parameter.
128
    json : dict
129
        A dictionary containing the configuration of the parameter.
130

131
    Examples
132
    --------
133

134
    Example - basic usage:
135
        >>> k = Parameter('k', dimensions=3, tw=4)
136

137
    Example - initialize a parameter with values:
138
        >>> x = Input('x')
139
        >>> gravity = Parameter('g', dimensions=(4,1),values=[[[1],[2],[3],[4]]])
140
        >>> out = Output('out', Linear(W=gravity)(x.sw(3)))
141

142
    Example - initialize a parameter with a function:
143
        >>> x = Input('x').last()
144
        >>> p = Parameter('param', dimensions=1, sw=1, init=init_constant, init_params={'value':1})
145
        >>> relation = Fir(parameter=param)(x)
146
    """
147
    @enforce_types
1✔
148
    def __init__(self, name:str,
1✔
149
                 dimensions:int|list|tuple|None = None,
150
                 tw:float|int|None = None,
151
                 sw:int|None = None,
152
                 values:list|float|int|np.ndarray|None = None,
153
                 init:Callable|None = None,
154
                 init_params:dict|None = None):
155

156
        NeuObj.__init__(self, name)
1✔
157
        dimensions = list(dimensions) if type(dimensions) is tuple else dimensions
1✔
158
        if values is None:
1✔
159
            if dimensions is None:
1✔
160
                dimensions = 1
1✔
161
            self.dim = {'dim': dimensions}
1✔
162
            if tw is not None:
1✔
163
                check(sw is None, ValueError, "If tw is set sw must be None")
1✔
164
                self.dim['tw'] = tw
1✔
165
            elif sw is not None:
1✔
166
                self.dim['sw'] = sw
1✔
167
            else:
168
                self.dim['sw'] = 1
1✔
169

170
            # deepcopy dimention information inside Parameters
171
            self.json['Parameters'][self.name] = copy.deepcopy(self.dim)
1✔
172
        else:
173
            values = np.array(values, dtype=NP_DTYPE)
1✔
174
            shape = values.shape
1✔
175
            values = values.tolist()
1✔
176
            check(len(shape) >= 2, ValueError,
1✔
177
                  f"The shape of a parameter must have at least 2 dimensions.")
178
            values_dimensions = shape[1] if len(shape[1:]) == 1 else list(shape[1:])
1✔
179
            if dimensions is None:
1✔
180
                dimensions = values_dimensions
1✔
181
            else:
182
                check(dimensions == values_dimensions, ValueError,
1✔
183
                      f"The dimensions = {dimensions} are different from dimensions = {values_dimensions} of the values.")
184
            self.dim = {'dim': dimensions}
1✔
185

186
            if tw is not None:
1✔
187
                check(sw is None, ValueError, "If tw is set sw must be None")
1✔
188
                self.dim['tw'] = tw
1✔
189
            elif sw is not None:
1✔
190
                self.dim['sw'] = sw
1✔
191
                check(shape[0] == self.dim['sw'],ValueError, f"The sw = {sw} is different from sw = {shape[0]} of the values.")
1✔
192
            else:
193
                self.dim['sw'] = shape[0]
1✔
194

195
            # deepcopy dimention information inside Parameters
196
            self.json['Parameters'][self.name] = copy.deepcopy(self.dim)
1✔
197
            self.json['Parameters'][self.name]['values'] = values
1✔
198

199
        if init is not None:
1✔
200
            check('values' not in self.json['Parameters'][self.name], ValueError, f"The parameter {self.name} is already initialized.")
1✔
201
            check(inspect.isfunction(init), ValueError,f"The init parameter must be a function.")
1✔
202
            code = textwrap.dedent(inspect.getsource(init)).replace('\"', '\'')
1✔
203
            self.json['Parameters'][self.name]['init_fun'] = { 'code' : code, 'name' : init.__name__}
1✔
204
            if init_params is not None:
1✔
205
                self.json['Parameters'][self.name]['init_fun']['params'] = init_params
1✔
206

207
class SampleTime():
1✔
208
    """
209
    Represents a constant that value is equal to the sample time.
210

211
    Attributes
212
    ----------
213
    name : str
214
        The name of the constant.
215
    dim : dict
216
        A dictionary containing the dimensions of the constant.
217
    json : dict
218
        A dictionary containing the configuration of the constant.
219

220
    Example
221
    -------
222
        >>> dt = SampleTime()
223
    """
224
    name = 'SampleTime'
1✔
225
    g = Constant(name, values=0)
1✔
226
    def __new__(cls):
1✔
227
        SampleTime.g.dim = {'dim': 1, 'sw': 1}
1✔
228
        SampleTime.g.json['Constants'][SampleTime.name] = copy.deepcopy(SampleTime.g.dim)
1✔
229
        SampleTime.g.json['Constants'][SampleTime.name]['values'] = SampleTime.name
1✔
230
        return SampleTime.g
1✔
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