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

tonegas / nnodely / 13056267505

30 Jan 2025 04:04PM UTC coverage: 94.525% (+0.6%) from 93.934%
13056267505

push

github

web-flow
Merge pull request #48 from tonegas/develop

Develop merge on main release 1.0.0

1185 of 1215 new or added lines in 21 files covered. (97.53%)

3 existing lines in 2 files now uncovered.

9426 of 9972 relevant lines covered (94.52%)

0.95 hits per line

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

88.46
/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, Stream, ToStream
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, Stream):
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
        >>> g = Constant('gravity',values=9.81)
40
    """
41
    @enforce_types
1✔
42
    def __init__(self, name:str,
1✔
43
                 values:list|float|int|np.ndarray,
44
                 tw:float|int|None = None,
45
                 sw:int|None = None):
46

47
        NeuObj.__init__(self, name)
1✔
48
        values = np.array(values, dtype=NP_DTYPE)
1✔
49
        shape = values.shape
1✔
50
        values = values.tolist()
1✔
51
        if len(shape) == 0:
1✔
52
            self.dim = {'dim': 1}
1✔
53
        else:
54
            check(len(shape) >= 2, ValueError,
1✔
55
              f"The shape of a Constant must have at least 2 dimensions or zero.")
56
            dimensions = shape[1] if len(shape[1:]) == 1 else list(shape[1:])
1✔
57
            self.dim = {'dim': dimensions}
1✔
58
            if tw is not None:
1✔
59
                check(sw is None, ValueError, "If tw is set sw must be None")
1✔
60
                self.dim['tw'] = tw
1✔
61
            elif sw is not None:
1✔
62
                self.dim['sw'] = sw
×
63
                check(shape[0] == self.dim['sw'],ValueError, f"The sw = {sw} is different from sw = {shape[0]} of the values.")
×
64
            else:
65
                self.dim['sw'] = shape[0]
1✔
66

67
        # deepcopy dimention information inside Parameters
68
        self.json['Constants'][self.name] = copy.deepcopy(self.dim)
1✔
69
        self.json['Constants'][self.name]['values'] = values
1✔
70
        Stream.__init__(self, name, self.json, self.dim)
1✔
71

72
class Parameter(NeuObj, Stream):
1✔
73
    """
74
    Represents a parameter in the neural network model.
75

76
    Notes
77
    -----
78
    .. note::
79
        You can find some initialization functions for the 'init' and 'init_params' parameters inside the initializer module.
80

81
    Parameters
82
    ----------
83
    name : str
84
        The name of the parameter.
85
    dimensions : int, list, tuple, or None, optional
86
        The dimensions of the parameter. Default is None.
87
    tw : float or int, optional
88
        The time window for the parameter. Default is None.
89
    sw : int, optional
90
        The sample window for the parameter. Default is None.
91
    values : list, float, int, np.ndarray, or None, optional
92
        The values of the parameter. Default is None.
93
    init : Callable, optional
94
        A callable for initializing the parameter values. Default is None.
95
    init_params : dict, optional
96
        A dictionary of parameters for the initializer. Default is None.
97

98
    Attributes
99
    ----------
100
    name : str
101
        The name of the parameter.
102
    dim : dict
103
        A dictionary containing the dimensions of the parameter.
104
    json : dict
105
        A dictionary containing the configuration of the parameter.
106

107
    Examples
108
    --------
109

110
    Example - basic usage:
111
        >>> k = Parameter('k', dimensions=3, tw=4)
112

113
    Example - initialize a parameter with values:
114
        >>> x = Input('x')
115
        >>> gravity = Parameter('g', dimensions=(4,1),values=[[[1],[2],[3],[4]]])
116
        >>> out = Output('out', Linear(W=gravity)(x.sw(3)))
117

118
    Example - initialize a parameter with a function:
119
        >>> x = Input('x').last()
120
        >>> p = Parameter('param', dimensions=1, sw=1, init=init_constant, init_params={'value':1})
121
        >>> relation = Fir(parameter=param)(x)
122
    """
123
    @enforce_types
1✔
124
    def __init__(self, name:str,
1✔
125
                 dimensions:int|list|tuple|None = None,
126
                 tw:float|int|None = None,
127
                 sw:int|None = None,
128
                 values:list|float|int|np.ndarray|None = None,
129
                 init:Callable|None = None,
130
                 init_params:dict|None = None):
131

132
        NeuObj.__init__(self, name)
1✔
133
        dimensions = list(dimensions) if type(dimensions) is tuple else dimensions
1✔
134
        if values is None:
1✔
135
            if dimensions is None:
1✔
136
                dimensions = 1
1✔
137
            self.dim = {'dim': dimensions}
1✔
138
            if tw is not None:
1✔
139
                check(sw is None, ValueError, "If tw is set sw must be None")
1✔
140
                self.dim['tw'] = tw
1✔
141
            elif sw is not None:
1✔
142
                self.dim['sw'] = sw
1✔
143

144
            # deepcopy dimention information inside Parameters
145
            self.json['Parameters'][self.name] = copy.deepcopy(self.dim)
1✔
146
        else:
147
            values = np.array(values, dtype=NP_DTYPE)
1✔
148
            shape = values.shape
1✔
149
            values = values.tolist()
1✔
150
            check(len(shape) >= 2, ValueError,
1✔
151
                  f"The shape of a parameter must have at least 2 dimensions.")
152
            values_dimensions = shape[1] if len(shape[1:]) == 1 else list(shape[1:])
1✔
153
            if dimensions is None:
1✔
154
                dimensions = values_dimensions
1✔
155
            else:
156
                check(dimensions == values_dimensions, ValueError,
1✔
157
                      f"The dimensions = {dimensions} are different from dimensions = {values_dimensions} of the values.")
158
            self.dim = {'dim': dimensions}
1✔
159

160
            if tw is not None:
1✔
161
                check(sw is None, ValueError, "If tw is set sw must be None")
1✔
162
                self.dim['tw'] = tw
1✔
163
            elif sw is not None:
1✔
164
                self.dim['sw'] = sw
1✔
165
                check(shape[0] == self.dim['sw'],ValueError, f"The sw = {sw} is different from sw = {shape[0]} of the values.")
1✔
166
            else:
167
                self.dim['sw'] = shape[0]
1✔
168

169
            # deepcopy dimention information inside Parameters
170
            self.json['Parameters'][self.name] = copy.deepcopy(self.dim)
1✔
171
            self.json['Parameters'][self.name]['values'] = values
1✔
172

173
        if init is not None:
1✔
174
            check('values' not in self.json['Parameters'][self.name], ValueError, f"The parameter {self.name} is already initialized.")
1✔
175
            check(inspect.isfunction(init), ValueError,f"The init parameter must be a function.")
1✔
176
            code = textwrap.dedent(inspect.getsource(init)).replace('\"', '\'')
1✔
177
            self.json['Parameters'][self.name]['init_fun'] = { 'code' : code, 'name' : init.__name__}
1✔
178
            if init_params is not None:
1✔
179
                self.json['Parameters'][self.name]['init_fun']['params'] = init_params
1✔
180

181
        Stream.__init__(self, name, self.json, self.dim)
1✔
182

183
class SampleTime(NeuObj, Stream, ToStream):
1✔
184
    """
185
    Represents a constant that value is equal to the sample time.
186

187
    Attributes
188
    ----------
189
    name : str
190
        The name of the constant.
191
    dim : dict
192
        A dictionary containing the dimensions of the constant.
193
    json : dict
194
        A dictionary containing the configuration of the constant.
195

196
    Example
197
    -------
198
        >>> dt = SampleTime()
199
    """
200
    def __init__(self):
1✔
NEW
201
        name = 'SampleTime'
×
NEW
202
        NeuObj.__init__(self, name)
×
NEW
203
        self.dim = {'dim': 1, 'sw': 1}
×
204
        # deepcopy dimention information inside Parameters
NEW
205
        self.json['Constants'][self.name] = copy.deepcopy(self.dim)
×
NEW
206
        self.json['Constants'][self.name]['values'] = name
×
NEW
207
        Stream.__init__(self, name, self.json, self.dim)
×
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