/
ModelicaStandardTables.c
4102 lines (3801 loc) · 162 KB
/
ModelicaStandardTables.c
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Implementation of external functions for table computation
in the Modelica Standard Library:
Modelica.Blocks.Sources.CombiTimeTable
Modelica.Blocks.Tables.CombiTable1D
Modelica.Blocks.Tables.CombiTable1Ds
Modelica.Blocks.Tables.CombiTable2D
The following #define's are available.
NO_FILE_SYSTEM : A file system is not present (e.g. on dSPACE or xPC).
DEBUG_TIME_EVENTS : Trace time events of CombiTimeTable
DUMMY_FUNCTION_USERTAB: Use a dummy function "usertab"
NO_TABLE_COPY : Do not copy table data passed to _init functions
This is a potentially unsafe optimization (ticket #1143).
If compiled as C++ and NO_FILE_SYTEM is not defined then common/shared table arrays
are stored in a global std::map in order to avoid superfluous file input access and
to decrease the utilized memory (ticket #1110).
Release Notes:
Jan. 02, 2015: by Thomas Beutlich, ITI GmbH.
Fixed event detection of CombiTimeTable with non-zero start time
(ticket #1619)
Aug. 22, 2014: by Thomas Beutlich, ITI GmbH.
Fixed multi-threaded access of common/shared table arrays
(ticket #1556)
May 21, 2014: by Thomas Beutlich, ITI GmbH.
Fixed bivariate Akima-spline extrapolation (ticket #1465)
Apr. 09, 2013: by Thomas Beutlich, ITI GmbH.
Implemented a first version
Copyright (C) 2013-2015, Modelica Association, DLR and ITI GmbH
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Modelica Association nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if defined(__gnu_linux__) && !defined(NO_FILE_SYSTEM)
#define _GNU_SOURCE 1
#endif
#include "ModelicaStandardTables.h"
#include "ModelicaUtilities.h"
#if !defined(NO_FILE_SYSTEM)
#include <stdio.h>
#include <locale.h>
#include "ModelicaMatIO.h"
#endif
#include <float.h>
#include <math.h>
#include <string.h>
#if defined(__cplusplus) && !defined(NO_FILE_SYSTEM)
#include <map>
#include <string>
#endif
/* ----- Interface enumerations ----- */
enum Smoothness {
LINEAR_SEGMENTS = 1,
CONTINUOUS_DERIVATIVE,
CONSTANT_SEGMENTS
};
enum Extrapolation {
HOLD_LAST_POINT = 1,
LAST_TWO_POINTS,
PERIODIC,
NO_EXTRAPOLATION
};
/* ----- Internal enumerations ----- */
enum PointInterval {
LEFT = -1,
IN_TABLE = 0,
RIGHT = 1
};
enum TableSource {
TABLESOURCE_MODEL,
TABLESOURCE_FILE,
TABLESOURCE_FUNCTION,
TABLESOURCE_FUNCTION_TRANSPOSE
};
/* ----- Internal table memory ----- */
/* 3 (of 4) 1D-spline coefficients (per interval) */
typedef double Akima1D[3];
/* 15 (of 16) 2D-spline coefficients (per grid) */
typedef double Akima2D[15];
/* Left and right interval indices (per interval) */
typedef size_t Interval[2];
typedef struct CombiTimeTable {
char* fileName; /* Name of table file */
char* tableName; /* Name of table */
double* table; /* Table values */
size_t nRow; /* Number of rows of table */
size_t nCol; /* Number of columns of table */
size_t last; /* Last accessed row index of table */
enum Smoothness smoothness; /* Smoothness kind */
enum Extrapolation extrapolation; /* Extrapolation kind */
enum TableSource source; /* Source kind */
int* cols; /* Columns of table to be interpolated */
size_t nCols; /* Number of columns of table to be interpolated */
double startTime; /* Start time of interpolation */
Akima1D* spline; /* Pre-calculated Akima-spline coefficients, only used if
smoothness is CONTINUOUS_DERIVATIVE */
size_t nEvent; /* Time event counter, discrete */
double preNextTimeEvent; /* Time of previous time event, discrete */
double preNextTimeEventCalled; /* Time of previous call of
ModelicaStandardTables_CombiTimeTable_nextTimeEvent, discrete */
size_t maxEvents; /* Maximum number of time events (per period/cycle) */
size_t eventInterval; /* Event interval marker, discrete,
In case of periodic extrapolation this is the current event interval,
otherwise it is the next event interval. */
double tOffset; /* Time offset, calculated by floor function, discrete,
only used if extrapolation is PERIODIC */
Interval* intervals; /* Event interval indices */
} CombiTimeTable;
typedef struct CombiTable1D {
char* fileName; /* Name of table file */
char* tableName; /* Name of table */
double* table; /* Table values */
size_t nRow; /* Number of rows of table */
size_t nCol; /* Number of columns of table */
size_t last; /* Last accessed row index of table */
enum Smoothness smoothness; /* Smoothness kind */
enum TableSource source; /* Source kind */
int* cols; /* Columns of table to be interpolated */
size_t nCols; /* Number of columns of table to be interpolated */
Akima1D* spline; /* Pre-calculated Akima-spline coefficients, only used if
smoothness is CONTINUOUS_DERIVATIVE */
} CombiTable1D;
typedef struct CombiTable2D {
char* fileName; /* Name of table file */
char* tableName; /* Name of table */
double* table; /* Table values */
size_t nRow; /* Number of rows of table */
size_t nCol; /* Number of columns of table */
size_t last1; /* Last accessed row index of table */
size_t last2; /* Last accessed column index of table */
enum Smoothness smoothness; /* Smoothness kind */
enum TableSource source; /* Source kind */
Akima2D* spline; /* Pre-calculated Akima-spline coefficients, only used if
smoothness is CONTINUOUS_DERIVATIVE */
} CombiTable2D;
/* ----- Internal constants ----- */
#define _EPSILON (1e-10)
#if !defined(MAX_TABLE_DIMENSIONS)
#define MAX_TABLE_DIMENSIONS (3)
#endif
#define LINE_BUFFER_LENGTH (64)
/* ----- Internal shortcuts ----- */
#define IDX(i, j, n) ((i)*(n) + (j))
#define TABLE(i, j) table[IDX(i, j, nCol)]
#define TABLE_ROW0(j) table[j]
#define TABLE_COL0(i) table[(i)*nCol]
#define LINEAR(u, u0, u1, y0, y1) \
y = (y0) + ((y1) - (y0))*((u) - (u0))/((u1) - (u0));
/*
LINEAR(u0, ...) -> y0
LINEAR(u1, ...) -> y1
*/
#define LINEAR_SLOPE(y0, dy_du, du) ((y0) + (dy_du)*(du))
#define BILINEAR(u1, u2, u10, u11, u20, u21, y00, y01, y10, y11) {\
const double tmp = ((u2) - (u20))/((u20) - (u21)); \
y = (y00) + tmp*((y00) - (y01)) + ((u1) - (u10))/((u10) - (u11))* \
((1 + tmp)*((y00) - (y10)) + tmp*((y11) - (y01))); \
}
/*
BILINEAR(u10, u20, ...) -> y00
BILINEAR(u10, u21, ...) -> y01
BILINEAR(u11, u20, ...) -> y10
BILINEAR(u11, u21, ...) -> y11
*/
#if defined(__cplusplus)
#define STATIC_CAST(T, E) static_cast<T>(E)
#else
#define STATIC_CAST(T, E) E
#endif
#if defined(__cplusplus) && !defined(NO_FILE_SYSTEM)
typedef std::pair<std::string, std::string> TableKey;
typedef std::pair<size_t, double*> TableData;
typedef std::pair<size_t, size_t> TableDim;
typedef std::pair<TableData, TableDim> TableVal;
typedef std::map<TableKey, TableVal> TableShareMap;
#endif
/* ----- Static variables ----- */
#if defined(__cplusplus) && !defined(NO_FILE_SYSTEM)
static TableShareMap tableShare;
#if defined(_WIN32)
#include <Windows.h>
struct CriticalSection : CRITICAL_SECTION {
CriticalSection() {
InitializeCriticalSection(this);
}
~CriticalSection() {
DeleteCriticalSection(this);
}
};
static CriticalSection cs;
struct CriticalSectionHandler {
CriticalSectionHandler() {
EnterCriticalSection(&cs);
}
~CriticalSectionHandler() {
LeaveCriticalSection(&cs);
}
};
#elif defined(__linux__) && !defined(LABCAR)
#include <pthread.h>
static pthread_mutex_t m;
struct Mutex {
Mutex() {
pthread_mutexattr_t mAttr;
pthread_mutexattr_settype(&mAttr, PTHREAD_MUTEX_NORMAL);
pthread_mutex_init(&m, &mAttr);
pthread_mutexattr_destroy(&mAttr);
}
~Mutex() {
pthread_mutex_destroy(&m);
}
};
static Mutex _m;
struct CriticalSectionHandler {
CriticalSectionHandler() {
pthread_mutex_lock(&m);
}
~CriticalSectionHandler() {
pthread_mutex_unlock(&m);
}
};
#endif
#endif
/* ----- Function declarations ----- */
#if defined(__cplusplus)
extern "C"
#else
extern
#endif
int usertab(char* tableName, int nipo, int dim[], int* colWise,
double** table);
/* Define tables by statically storing them in function usertab.
This function can be adapted by the user to his/her needs.
-> tableName: Name of table
-> nipo : = 0: time-table required (time interpolation)
= 1: 1D-table required
= 2: 2D-table required
<- dim: Actual values of dimensions
<- colWise: = 0: table stored row-wise (row_1, row_2, ..., row_n)
= 1: table stored column-wise (column_1, column_2, ...)
<- table: Pointer to vector containing a matrix with dimensions "dim"
<- RETURN: = 0: No error
= 1: An error occured. An error message is printed from usertab.
*/
static int isNearlyEqual(double x, double y);
/* Compare two floating-point numbers by threshold _EPSILON */
static size_t findRowIndex(const double* table, size_t nRow, size_t nCol,
size_t last, double x);
/* Find the row index i using binary search such that
* i + 1 < nRow
* table[i*nCol] <= x
* table[(i + 1)*nCol] > x for i + 2 < nRow
*/
static size_t findColIndex(const double* table, size_t nCol, size_t last,
double x);
/* Same as findRowIndex but works on rows */
static size_t findPreRowIndex(const CombiTimeTable* tableID, size_t last);
/* Find the row index i of the previous event interval where last is in
the current event interval
*/
static int isValidName(const char* name);
/* Check, whether a file or table name is valid */
static int isValidCombiTimeTable(const CombiTimeTable* tableID);
/* Check, whether a CombiTimeTable is well parameterized */
static int isValidCombiTable1D(const CombiTable1D* tableID);
/* Check, whether a CombiTable1D is well parameterized */
static int isValidCombiTable2D(const CombiTable2D* tableID);
/* Check, whether a CombiTable2D is well parameterized */
static enum TableSource getTableSource(const char *tableName,
const char *fileName);
/* Determine table source (file, model or "usertab" function) from table
and file names
*/
static double* readTable(const char* tableName, const char* fileName,
size_t* nRow, size_t* nCol, int verbose, int force);
/* Read a table from an ASCII text or MATLAB MAT-file
<- RETURN: Pointer to array (row-wise storage) of table values
*/
static double* readMatTable(const char* tableName, const char* fileName,
size_t* nRow, size_t* nCol);
/* Read a table from a MATLAB MAT-file using MatIO functions
<- RETURN: Pointer to array (row-wise storage) of table values
*/
static double* readTxtTable(const char* tableName, const char* fileName,
size_t* nRow, size_t* nCol);
/* Read a table from an ASCII text file
<- RETURN: Pointer to array (row-wise storage) of table values
*/
static Akima1D* spline1DInit(const double* table, size_t nRow, size_t nCol,
const int* cols, size_t nCols);
/* Calculate the spline coefficients for univariate Akima-spline interpolation
<- RETURN: Pointer to array of coefficients
*/
static void spline1DClose(Akima1D* spline);
/* Free allocated memory of the Akima-spline coefficients */
static Akima2D* spline2DInit(const double* table, size_t nRow, size_t nCol);
/* Calculate the spline coefficients for bivariate Akima-spline interpolation
<- RETURN: Pointer to array of coefficients
*/
static void spline2DClose(Akima2D* spline);
/* Free allocated memory of the Akima-spline coefficients */
#if !defined(NO_FILE_SYSTEM)
static int readLine(char** buf, int* bufLen, FILE* fp);
/* Read line (of unknown and arbitrary length) from an ASCII text file */
#endif
/* ----- Interface functions ----- */
DYMOLA_STATIC void* ModelicaStandardTables_CombiTimeTable_init(const char* tableName,
const char* fileName, const double* table,
size_t nRow, size_t nColumn,
double startTime, const int* cols,
size_t nCols, int smoothness,
int extrapolation) {
CombiTimeTable* tableID;
tableID = STATIC_CAST(CombiTimeTable*, calloc(1, sizeof(CombiTimeTable)));
if (tableID) {
tableID->smoothness = (enum Smoothness)smoothness;
tableID->extrapolation = (enum Extrapolation)extrapolation;
tableID->nCols = nCols;
if (nCols > 0) {
tableID->cols = STATIC_CAST(int*, malloc(tableID->nCols*sizeof(int)));
if (tableID->cols) {
memcpy(tableID->cols, cols, tableID->nCols*sizeof(int));
}
else {
free(tableID);
ModelicaError("Memory allocation error\n");
return NULL;
}
}
tableID->startTime = startTime;
tableID->source = getTableSource(tableName, fileName);
switch (tableID->source) {
case TABLESOURCE_FILE:
tableID->tableName =
STATIC_CAST(char*, malloc((strlen(tableName) + 1)*sizeof(char)));
if (tableID->tableName) {
strcpy(tableID->tableName, tableName);
}
else {
if (nCols > 0) {
free(tableID->cols);
}
free(tableID);
tableID = NULL;
ModelicaError("Memory allocation error\n");
break;
}
tableID->fileName =
STATIC_CAST(char*, malloc((strlen(fileName) + 1)*sizeof(char)));
if (tableID->fileName) {
strcpy(tableID->fileName, fileName);
}
else {
free(tableID->tableName);
if (nCols > 0) {
free(tableID->cols);
}
free(tableID);
tableID = NULL;
ModelicaError("Memory allocation error\n");
}
break;
case TABLESOURCE_MODEL:
tableID->nRow = nRow;
tableID->nCol = nColumn;
tableID->table = (double*) table;
if (tableID->smoothness == CONTINUOUS_DERIVATIVE &&
tableID->nRow == 2) {
tableID->smoothness = LINEAR_SEGMENTS;
}
if (isValidCombiTimeTable((const CombiTimeTable*)tableID)) {
if (tableID->smoothness == CONTINUOUS_DERIVATIVE) {
/* Initialization of the Akima-spline coefficients */
tableID->spline = spline1DInit(table, tableID->nRow,
tableID->nCol, (const int*)cols, tableID->nCols);
}
#ifndef NO_TABLE_COPY
tableID->table = STATIC_CAST(double*, malloc(
tableID->nRow*tableID->nCol*sizeof(double)));
if (tableID->table) {
memcpy(tableID->table, table, tableID->nRow*
tableID->nCol*sizeof(double));
}
else {
if (nCols > 0) {
free(tableID->cols);
}
free(tableID);
tableID = NULL;
ModelicaError("Memory allocation error\n");
}
#endif
}
else {
tableID->table = NULL;
}
break;
case TABLESOURCE_FUNCTION: {
int colWise;
int dim[MAX_TABLE_DIMENSIONS];
if (usertab((char*)tableName, 0 /* Time-interpolation */, dim,
&colWise, &tableID->table) == 0) {
tableID->nRow = (size_t)dim[0];
tableID->nCol = (size_t)dim[1];
if (colWise) {
/* Need to transpose */
size_t dims[2];
double* tableT;
dims[0] = tableID->nRow;
dims[1] = tableID->nCol;
tableT = STATIC_CAST(double*, malloc(
dims[0]*dims[1]*sizeof(double)));
if (tableT) {
size_t i;
size_t j;
for (i = 0; i < dims[1]; i++) {
for (j = 0; j < dims[0]; j++) {
tableT[IDX(i, j, dims[0])] =
tableID->table[IDX(j, i, dims[1])];
}
}
tableID->table = tableT;
tableID->nRow = dims[1];
tableID->nCol = dims[0];
tableID->source = TABLESOURCE_FUNCTION_TRANSPOSE;
}
else {
if (nCols > 0) {
free(tableID->cols);
}
free(tableID);
tableID = NULL;
ModelicaError("Memory allocation error\n");
break;
}
}
if (tableID->smoothness == CONTINUOUS_DERIVATIVE &&
tableID->nRow == 2) {
tableID->smoothness = LINEAR_SEGMENTS;
}
if (isValidCombiTimeTable((const CombiTimeTable*)tableID)) {
if (tableID->smoothness == CONTINUOUS_DERIVATIVE) {
/* Initialization of Akima-spline coefficients */
tableID->spline = spline1DInit(tableID->table,
tableID->nRow, tableID->nCol, (const int*)cols,
tableID->nCols);
}
}
}
break;
}
case TABLESOURCE_FUNCTION_TRANSPOSE:
/* Should not be possible to get here */
break;
default:
ModelicaError("Table source error\n");
break;
}
}
else {
ModelicaError("Memory allocation error\n");
}
return (void*)tableID;
}
DYMOLA_STATIC void ModelicaStandardTables_CombiTimeTable_close(void* _tableID) {
CombiTimeTable* tableID = (CombiTimeTable*)_tableID;
if (tableID) {
if (tableID->table && tableID->source == TABLESOURCE_FILE) {
#if defined(__cplusplus) && !defined(NO_FILE_SYSTEM)
if (tableID->tableName && tableID->fileName) {
TableKey key = std::make_pair(tableID->fileName,
tableID->tableName);
#if defined(_WIN32) || defined(__linux__)
CriticalSectionHandler csh;
#endif
TableShareMap::iterator iter = tableShare.find(key);
if (iter != tableShare.end()) {
/* Share hit */
TableVal& val = iter->second;
TableData& data = val.first;
data.first--;
if (data.first == 0) {
free(data.second);
tableShare.erase(iter);
}
}
}
else {
/* Should not be possible to get here */
free(tableID->table);
}
#else
free(tableID->table);
#endif
tableID->table = NULL;
}
else if (tableID->table && (
#ifndef NO_TABLE_COPY
tableID->source == TABLESOURCE_MODEL ||
#endif
tableID->source == TABLESOURCE_FUNCTION_TRANSPOSE)) {
free(tableID->table);
tableID->table = NULL;
}
if (tableID->nCols > 0 && tableID->cols) {
free(tableID->cols);
tableID->cols = NULL;
}
if (tableID->tableName) {
free(tableID->tableName);
tableID->tableName = NULL;
}
if (tableID->fileName) {
free(tableID->fileName);
tableID->fileName = NULL;
}
if (tableID->intervals) {
free(tableID->intervals);
tableID->intervals = NULL;
}
spline1DClose(tableID->spline);
free(tableID);
tableID = NULL;
}
}
DYMOLA_STATIC double ModelicaStandardTables_CombiTimeTable_getValue(void* _tableID, int iCol,
double t, double nextTimeEvent,
double preNextTimeEvent) {
double y = 0.;
CombiTimeTable* tableID = (CombiTimeTable*)_tableID;
if (tableID && tableID->table && tableID->cols) {
/* Shift time by start time */
const double tOld = t;
t -= tableID->startTime;
if (t >= 0 && nextTimeEvent < DBL_MAX &&
nextTimeEvent == preNextTimeEvent &&
tableID->startTime >= nextTimeEvent) {
/* Before start time event iteration: need to return zero */
return 0.;
}
else if (t >= 0) {
const double* table = tableID->table;
const size_t nRow = tableID->nRow;
const size_t nCol = tableID->nCol;
const size_t col = (size_t)tableID->cols[iCol - 1] - 1;
if (nRow == 1) {
/* Single row */
y = TABLE_ROW0(col);
}
else {
enum PointInterval extrapolate = IN_TABLE;
/* Periodic extrapolation */
if (tableID->extrapolation == PERIODIC) {
const double tMin = TABLE_ROW0(0);
const double tMax = TABLE_COL0(nRow - 1);
const double T = tMax - tMin;
/* Event handling for periodic extrapolation */
if (nextTimeEvent == preNextTimeEvent &&
tOld >= nextTimeEvent) {
/* Before event iteration: Return previous
interval value */
size_t i;
if (tableID->smoothness == CONSTANT_SEGMENTS) {
i = tableID->intervals[
tableID->eventInterval - 1][0];
}
else {
i = tableID->intervals[
tableID->eventInterval - 1][1];
}
y = TABLE(i, col);
return y;
}
else if (nextTimeEvent > preNextTimeEvent &&
tOld >= preNextTimeEvent &&
tableID->startTime < preNextTimeEvent) {
/* In regular (= not start time) event iteration:
Return left interval value */
size_t i = tableID->intervals[
tableID->eventInterval - 1][0];
y = TABLE(i, col);
return y;
}
else {
/* After event iteration */
const size_t i0 = tableID->intervals[
tableID->eventInterval - 1][0];
const size_t i1 = tableID->intervals[
tableID->eventInterval - 1][1];
t -= tableID->tOffset;
if (t < tMin) {
t += T;
}
else if (t > tMax) {
t -= T;
}
tableID->last = findRowIndex(
table, nRow, nCol, tableID->last, t);
/* Event interval correction */
if (tableID->last < i0) {
t = TABLE_COL0(i0);
}
if (tableID->last >= i1) {
if (tableID->eventInterval == 1) {
t = TABLE_COL0(i0);
}
else {
t = TABLE_COL0(i1);
}
}
}
}
else if (t < TABLE_ROW0(0)) {
extrapolate = LEFT;
}
else if (t > TABLE_COL0(nRow - 1)) {
extrapolate = RIGHT;
if (tableID->extrapolation != PERIODIC) {
/* Event handling for non-periodic extrapolation */
if (nextTimeEvent == preNextTimeEvent &&
nextTimeEvent < DBL_MAX && tOld >= nextTimeEvent) {
/* Before event iteration */
extrapolate = IN_TABLE;
}
}
}
if (extrapolate == IN_TABLE) {
size_t last = findRowIndex(table, nRow, nCol, tableID->last,
t);
tableID->last = last;
if (tableID->extrapolation != PERIODIC) {
/* Event handling for non-periodic extrapolation */
if (nextTimeEvent == preNextTimeEvent &&
nextTimeEvent < DBL_MAX && tOld >= nextTimeEvent) {
/* Before event iteration */
size_t i;
if (t >= TABLE_COL0(nRow - 1)) {
last = nRow - 1;
}
i = findPreRowIndex(tableID, last);
y = TABLE(i, col);
return y;
}
}
/* Interpolation */
switch (tableID->smoothness) {
case CONSTANT_SEGMENTS:
if (t >= TABLE_COL0(last + 1)) {
last += 1;
}
y = TABLE(last, col);
break;
case LINEAR_SEGMENTS: {
const double t0 = TABLE_COL0(last);
const double t1 = TABLE_COL0(last + 1);
const double y0 = TABLE(last, col);
const double y1 = TABLE(last + 1, col);
if (isNearlyEqual(t0, t1)) {
y = y1;
}
else {
LINEAR(t, t0, t1, y0, y1)
}
break;
}
case CONTINUOUS_DERIVATIVE:
if (tableID->spline) {
const double* c = tableID->spline[
IDX(last, iCol - 1, tableID->nCols)];
t -= TABLE_COL0(last);
y = TABLE(last, col); /* c[3] = y0 */
y += ((c[0]*t + c[1])*t + c[2])*t;
}
break;
default:
ModelicaError("Unknown smoothness kind\n");
break;
}
}
else {
/* Extrapolation */
switch (tableID->extrapolation) {
case NO_EXTRAPOLATION:
ModelicaError("Extrapolation error\n");
break;
case HOLD_LAST_POINT:
y = (extrapolate == RIGHT) ? TABLE(nRow - 1, col) :
TABLE_ROW0(col);
break;
case LAST_TWO_POINTS: {
const size_t last =
(extrapolate == RIGHT) ? nRow - 2 : 0;
const double t0 = TABLE_COL0(last);
const double y0 = TABLE(last, col);
if (tableID->smoothness == CONTINUOUS_DERIVATIVE) {
if (tableID->spline) {
const double* c = tableID->spline[
IDX(last, iCol - 1, tableID->nCols)];
if (extrapolate == LEFT) {
y = LINEAR_SLOPE(y0, c[2], t - t0);
}
else /* if (extrapolate == RIGHT) */ {
const double t1 = TABLE_COL0(last + 1);
const double v = t1 - t0;
y = LINEAR_SLOPE(TABLE(last + 1, col),
(3*c[0]*v + 2*c[1])*v + c[2],
t - t1);
}
}
}
else {
const double t1 = TABLE_COL0(last + 1);
const double y1 = TABLE(last + 1, col);
if (isNearlyEqual(t0, t1)) {
y = y1;
}
else {
LINEAR(t, t0, t1, y0, y1)
}
}
break;
}
case PERIODIC:
/* Should not be possible to get here */
break;
default:
ModelicaError("Unknown extrapolation kind\n");
break;
}
}
}
}
}
return y;
}
DYMOLA_STATIC double ModelicaStandardTables_CombiTimeTable_getDerValue(void* _tableID, int iCol,
double t,
double nextTimeEvent,
double preNextTimeEvent,
double der_t) {
double der_y = 0.;
CombiTimeTable* tableID = (CombiTimeTable*)_tableID;
if (tableID && tableID->table && tableID->cols) {
/* Shift time by start time */
const double tOld = t;
t -= tableID->startTime;
if (t >= 0 && nextTimeEvent < DBL_MAX &&
nextTimeEvent == preNextTimeEvent &&
tableID->startTime >= nextTimeEvent) {
/* Before start time event iteration: need to return zero */
return 0.;
}
else if (t >= 0) {
const double* table = tableID->table;
const size_t nRow = tableID->nRow;
const size_t nCol = tableID->nCol;
const size_t col = (size_t)tableID->cols[iCol - 1] - 1;
if (nRow > 1) {
enum PointInterval extrapolate = IN_TABLE;
size_t last = 0;
int haveLast = 0;
/* Periodic extrapolation */
if (tableID->extrapolation == PERIODIC) {
const double tMin = TABLE_ROW0(0);
const double tMax = TABLE_COL0(nRow - 1);
const double T = tMax - tMin;
/* Event handling for periodic extrapolation */
if (nextTimeEvent == preNextTimeEvent &&
tOld >= nextTimeEvent) {
/* Before event iteration: Return previous
interval value */
last = tableID->intervals[
tableID->eventInterval - 1][1] - 1;
haveLast = 1;
}
else if (nextTimeEvent > preNextTimeEvent &&
tOld >= preNextTimeEvent &&
tableID->startTime < preNextTimeEvent) {
/* In regular (= not start time) event iteration:
Return left interval value */
last = tableID->intervals[
tableID->eventInterval - 1][0];
haveLast = 1;
}
else {
/* After event iteration */
const size_t i0 = tableID->intervals[
tableID->eventInterval - 1][0];
const size_t i1 = tableID->intervals[
tableID->eventInterval - 1][1];
t -= tableID->tOffset;
if (t < tMin) {
t += T;
}
else if (t > tMax) {
t -= T;
}
tableID->last = findRowIndex(
table, nRow, nCol, tableID->last, t);
/* Event interval correction */
if (tableID->last < i0) {
t = TABLE_COL0(i0);
}
if (tableID->last >= i1) {
if (tableID->eventInterval == 1) {
t = TABLE_COL0(i0);
}
else {
t = TABLE_COL0(i1);
}
}
}
}
else if (t < TABLE_ROW0(0)) {
extrapolate = LEFT;
}
else if (t > TABLE_COL0(nRow - 1)) {
extrapolate = RIGHT;
if (tableID->extrapolation != PERIODIC) {
/* Event handling for non-periodic extrapolation */
if (nextTimeEvent == preNextTimeEvent &&
nextTimeEvent < DBL_MAX && tOld >= nextTimeEvent) {
/* Before event iteration */
extrapolate = IN_TABLE;
}
}
}
if (extrapolate == IN_TABLE) {
if (!haveLast) {
last = findRowIndex(table, nRow, nCol, tableID->last, t);
tableID->last = last;
}
if (tableID->extrapolation != PERIODIC) {
/* Event handling for non-periodic extrapolation */
if (nextTimeEvent == preNextTimeEvent &&
nextTimeEvent < DBL_MAX && tOld >= nextTimeEvent) {
/* Before event iteration */
if (t >= TABLE_COL0(nRow - 1)) {
last = nRow - 1;
}
last = findPreRowIndex(tableID, last);
if (last == 0 && tableID->nEvent == 1) {
extrapolate = LEFT;
}
else if (last > 0) {
last--;
}
}
}
}
if (extrapolate == IN_TABLE) {
/* Interpolation */
switch (tableID->smoothness) {
case CONSTANT_SEGMENTS:
break;
case LINEAR_SEGMENTS: {
const double t0 = TABLE_COL0(last);
const double t1 = TABLE_COL0(last + 1);
if (!isNearlyEqual(t0, t1)) {
der_y = (TABLE(last + 1, col) - TABLE(last, col))/
(t1 - t0);
der_y *= der_t;
}
break;
}
case CONTINUOUS_DERIVATIVE:
if (tableID->spline) {
const double* c = tableID->spline[
IDX(last, iCol - 1, tableID->nCols)];
t -= TABLE_COL0(last);
der_y = (3*c[0]*t + 2*c[1])*t + c[2];
der_y *= der_t;
}
break;
default:
ModelicaError("Unknown smoothness kind\n");
break;
}
}