LotSizingDataModel.Core 2.1.0
Core domain model, shared abstractions and XML-serializable entities.
Loading...
Searching...
No Matches
DoubleTimeSeries.cs
Go to the documentation of this file.
1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.Linq;
5using System.Xml.Serialization;
6
8
9/// <summary>
10/// Represents a sequence of finite double values indexed by planning period.
11///
12/// Period numbers are one-based:
13/// period 1 corresponds to the first value,
14/// period 2 to the second value, and so on.
15/// </summary>
16[Serializable]
17[XmlType(TypeName = "doubleTimeSeries")]
18public sealed class DoubleTimeSeries :
20 IEnumerable<double>
21{
22 private double[] _values = Array.Empty<double>();
23
24 /// <summary>
25 /// Initializes an empty time series.
26 ///
27 /// This constructor is required by XmlSerializer.
28 /// </summary>
30 {
31 }
32
33 /// <summary>
34 /// Initializes a time series with the specified number of periods.
35 /// </summary>
36 /// <param name="periodCount">
37 /// Number of periods in the planning horizon.
38 /// </param>
39 /// <param name="defaultValue">
40 /// Initial value assigned to every period.
41 /// </param>
43 int periodCount,
44 double defaultValue = 0.0)
45 {
46 Resize(periodCount, defaultValue);
47 }
48
49 /// <summary>
50 /// Gets or replaces all values of the time series.
51 ///
52 /// Each XML element corresponds to one planning period.
53 /// The first value corresponds to period 1.
54 /// </summary>
55 [XmlElement("value")]
56 public double[] Values
57 {
58 get => (double[])_values.Clone();
59 set => ReplaceValues(value ?? Array.Empty<double>());
60 }
61
62 /// <summary>
63 /// Gets the number of periods currently represented.
64 /// </summary>
65 [XmlIgnore]
66 public int PeriodCount => _values.Length;
67
68 /// <summary>
69 /// Gets or sets the value for a planning period.
70 ///
71 /// The period number starts at 1, not 0.
72 /// </summary>
73 /// <param name="period">
74 /// Planning period between 1 and <see cref="PeriodCount"/>.
75 /// </param>
76 [XmlIgnore]
77 public double this[int period]
78 {
79 get
80 {
81 int index = ConvertPeriodToIndex(period);
82 return _values[index];
83 }
84 set
85 {
86 ValidateFiniteValue(value, nameof(value));
87 SetPeriodValue(period, value);
88 }
89 }
90
91 // Reserved for resource capacity, whose XML contract also permits positive infinity.
92 internal void SetUnboundedCapacityPeriod(int period) =>
93 SetPeriodValue(period, double.PositiveInfinity);
94
95 private void SetPeriodValue(int period, double value)
96 {
97 int index = ConvertPeriodToIndex(period);
98 if (_values[index].Equals(value))
99 {
100 return;
101 }
102
103 _values[index] = value;
104 OnPropertyChanged(nameof(Values));
105 OnPropertyChanged("Item[]");
106 }
107
108 /// <summary>
109 /// Resizes the time series.
110 ///
111 /// Existing values are preserved. When the horizon grows,
112 /// new periods receive <paramref name="defaultValue"/>.
113 /// When the horizon shrinks, values beyond the new horizon
114 /// are removed.
115 /// </summary>
116 /// <param name="periodCount">
117 /// New number of periods.
118 /// </param>
119 /// <param name="defaultValue">
120 /// Value assigned to newly created periods.
121 /// </param>
122 public void Resize(
123 int periodCount,
124 double defaultValue = 0.0)
125 {
126 if (periodCount < 0)
127 {
128 throw new ArgumentOutOfRangeException(
129 nameof(periodCount),
130 periodCount,
131 "The number of periods cannot be negative.");
132 }
133
134 ValidateFiniteValue(defaultValue, nameof(defaultValue));
135
136 // No change necessary if the size is the same
137 if (periodCount == _values.Length)
138 {
139 return;
140 }
141
142 int previousPeriodCount = _values.Length;
143 var resizedValues = new double[periodCount];
144
145 // Copy existing values (the minimum between old and new size)
146 int copiedValueCount = Math.Min(
147 previousPeriodCount,
148 periodCount);
149
150 if (copiedValueCount > 0)
151 {
152 Array.Copy(
153 _values,
154 resizedValues,
155 copiedValueCount);
156 }
157
158 // Initialize new periods with the default value when expanding
159 if (periodCount > previousPeriodCount)
160 {
161 Array.Fill(
162 resizedValues,
163 defaultValue,
164 previousPeriodCount,
165 periodCount - previousPeriodCount);
166 }
167
168 _values = resizedValues;
169
170 OnPropertyChanged(nameof(Values));
172 OnPropertyChanged("Item[]");
173 }
174
175 /// <summary>
176 /// Assigns the same value to every planning period.
177 /// </summary>
178 public void Fill(double value)
179 {
180 ValidateFiniteValue(value, nameof(value));
181
182 // Avoid unnecessary notifications if all values are already equal
183 if (_values.All(currentValue => currentValue.Equals(value)))
184 {
185 return;
186 }
187
188 Array.Fill(_values, value);
189
190 OnPropertyChanged(nameof(Values));
191 OnPropertyChanged("Item[]");
192 }
193
194 /// <summary>
195 /// Gets the value associated with a planning period.
196 /// </summary>
197 public double GetValue(int period)
198 {
199 return this[period];
200 }
201
202 /// <summary>
203 /// Sets the value associated with a planning period.
204 /// </summary>
205 public void SetValue(int period, double value)
206 {
207 this[period] = value;
208 }
209
210 /// <summary>
211 /// Appends a value to the end of the time series.
212 /// </summary>
213 /// <param name="value">
214 /// Finite value to append.
215 /// </param>
216 /// <remarks>
217 /// This public method is required by <see cref="XmlSerializer"/>
218 /// because this type implements <see cref="IEnumerable{T}"/>.
219 /// During XML deserialization, the serializer calls this method
220 /// once for each serialized period value.
221 /// </remarks>
222 public void Add(double value)
223 {
224 ValidateFiniteValue(value, nameof(value));
225
226 int previousPeriodCount = _values.Length;
227
228 Array.Resize(
229 ref _values,
230 previousPeriodCount + 1);
231
232 _values[previousPeriodCount] = value;
233
234 OnPropertyChanged(nameof(Values));
236 OnPropertyChanged("Item[]");
237 }
238
239 /// <summary>
240 /// Removes all values from the time series.
241 /// </summary>
242 public void Clear()
243 {
244 if (_values.Length == 0)
245 {
246 return;
247 }
248
249 _values = Array.Empty<double>();
250
251 OnPropertyChanged(nameof(Values));
253 OnPropertyChanged("Item[]");
254 }
255
256 /// <summary>
257 /// Creates an independent copy of this time series.
258 /// </summary>
260 {
261 return new DoubleTimeSeries
262 {
263 Values = Values
264 };
265 }
266
267 /// <summary>
268 /// Returns an enumerator over the period values.
269 /// </summary>
270 public IEnumerator<double> GetEnumerator()
271 {
272 return ((IEnumerable<double>)_values).GetEnumerator();
273 }
274
275 IEnumerator IEnumerable.GetEnumerator()
276 {
277 return GetEnumerator();
278 }
279
280 /// <summary>
281 /// Replaces the internal values of the time series with a new array.
282 /// Validates all values before assignment.
283 /// </summary>
284 /// <param name="values">The new array of values to assign.</param>
285 private void ReplaceValues(double[] values)
286 {
287 // Validate that all values are finite (neither NaN nor Infinity)
288 foreach (double value in values)
289 {
290 ValidateFiniteValue(value, nameof(values));
291 }
292
293 // Avoid unnecessary notifications if the values are identical
294 if (_values.SequenceEqual(values))
295 {
296 return;
297 }
298
299 // Detect if the period count changes to notify PropertyChanged
300 bool periodCountChanged =
301 _values.Length != values.Length;
302
303 // Clone the array to ensure encapsulation
304 _values = (double[])values.Clone();
305
306 OnPropertyChanged(nameof(Values));
307 OnPropertyChanged("Item[]");
308
309 if (periodCountChanged)
310 {
312 }
313 }
314
315 /// <summary>
316 /// Converts a period number (1-based) to an array index (0-based).
317 /// </summary>
318 /// <param name="period">The period number (starts at 1).</param>
319 /// <returns>The corresponding index in the array (starts at 0).</returns>
320 /// <exception cref="ArgumentOutOfRangeException">
321 /// If the period is outside the valid range [1, PeriodCount].
322 /// </exception>
323 private int ConvertPeriodToIndex(int period)
324 {
325 if (period < 1 || period > _values.Length)
326 {
327 throw new ArgumentOutOfRangeException(
328 nameof(period),
329 period,
330 $"The period must be between 1 and {_values.Length}.");
331 }
332
333 // Conversion: period 1 -> index 0, period 2 -> index 1, etc.
334 return period - 1;
335 }
336
337 /// <summary>
338 /// Validates that a double value is finite (neither NaN nor infinite).
339 /// </summary>
340 /// <param name="value">The value to validate.</param>
341 /// <param name="parameterName">The parameter name for the error message.</param>
342 /// <exception cref="ArgumentOutOfRangeException">
343 /// If the value is NaN or infinite.
344 /// </exception>
345 private static void ValidateFiniteValue(
346 double value,
347 string parameterName)
348 {
349 if (double.IsNaN(value) ||
350 double.IsInfinity(value))
351 {
352 throw new ArgumentOutOfRangeException(
353 parameterName,
354 value,
355 "A time-series value must be a finite number.");
356 }
357 }
358}
void Clear()
Removes all values from the time series.
double GetValue(int period)
Gets the value associated with a planning period.
void Resize(int periodCount, double defaultValue=0.0)
Resizes the time series.
double[] Values
Gets or replaces all values of the time series.
IEnumerator< double > GetEnumerator()
Returns an enumerator over the period values.
DoubleTimeSeries Clone()
Creates an independent copy of this time series.
DoubleTimeSeries(int periodCount, double defaultValue=0.0)
Initializes a time series with the specified number of periods.
int PeriodCount
Gets the number of periods currently represented.
void SetValue(int period, double value)
Sets the value associated with a planning period.
DoubleTimeSeries()
Initializes an empty time series.
void Add(double value)
Appends a value to the end of the time series.
void Fill(double value)
Assigns the same value to every planning period.
Base class for model objects that notify listeners when one of their properties changes.
virtual void OnPropertyChanged([CallerMemberName] string? propertyName=null)
Raises the PropertyChanged event.