-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDfsFile.py
1880 lines (1577 loc) · 74.7 KB
/
DfsFile.py
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
import os.path
from enum import IntEnum
import datetime
import ctypes
import numpy as np
from mikecore.eum import *
from mikecore.DfsDLL import DfsDLL
from typing import Union
from mikecore.eum import eumQuantity
class NotSupportedException(Exception):
pass
class ArgumentNullException(Exception):
pass
class DfsFileMode(IntEnum):
Read = 0
Edit = 1
Append = 2
Closed = 3
class TimeAxisType(IntEnum):
Undefined = 0
TimeEquidistant = 1
TimeNonEquidistant = 2
CalendarEquidistant = 3
CalendarNonEquidistant = 4
class DataValueType(IntEnum):
"""
Data value type defines how one value is interpreted in time:
Instantaneous : Value at current point in time, current time step.
Accumulated : Value accumulated from start of time series to current time step.
StepAccumulated : Value accumulated within time step, from last time step to current time step.
MeanStepBackward : Mean value from previous to current time step. Also called: mean step accumulated.
MeanStepForward : Mean value from current to next time step. Also called: reverse mean step accumulated.
"""
Instantaneous = 0
Accumulated = 1
StepAccumulated = 2
MeanStepBackward = 3
MeanStepForward = 4
class SpaceAxisType(IntEnum):
Undefined = 0
EqD0 = 1
EqD1 = 2
NeqD1 = 3
# TvarD1 = 4;
EqD2 = 5
NeqD2 = 6
# TvarD2 = 7;
EqD3 = 8
NeqD3 = 9
# TvarD3 = 10;
# EqD4 = 11;
CurveLinearD2 = 12
CurveLinearD3 = 13
class DfsSimpleType(IntEnum):
Float = 1
Double = 2
Byte = 3
Int = 4
UInt = 5
Short = 6
UShort = 7
class ProjectionType(IntEnum):
"""
Projection type, specifies whether file has projection or not.
All newer files has a projection defined, though there exists
older files which does not have a projection (Undefined).
"""
Undefined = 0
Projection = 1
class UnitConversionType(IntEnum):
"""
Type of unit conversion, when reading item
data and axis.
NoConversion : No conversion, default
UbgConversion : Convert to/from UBG (Unit Base Group), user defined.
FreeConversion : Convert to/from user defined unit, which must also be provided with this type.
FirstRegisteredUnitConversion : Converts to/from the first registered unit (default EUM unit) for the given item type.
"""
NoConversion = 0
UbgConversion = 1
FreeConversion = 2
FirstRegisteredUnitConversion = 3
class StatType(IntEnum):
Undefined = 0
NoStat = 1
RegularStat = 2
LargevalStat = 3
class DfsParameters:
"""Parameters that can be set for a dfs file."""
def __init__(self):
self.ModifyTimes = False
class DfsProjection:
"""
Defines a projection and its coordinate transforms.
You can use the <code>DHI.Projections</code> to handle the
difference coordinate systems involved in a dfs file. Also
see there for detailed documentation.
The `WKTString` is a WKT string for a spatial
reference system. A number of abbreviated strings also exists,
i.e., "UTM-33" for a WGS-84 UTM zone 33 projection,
and "LONG/LAT" for WGS-84 geographical coordinates.
There are 3 levels of coordinates:
- Geographical coordinates (longitude, latitude) in degrees,
- Projection coordinates (easting, northing), and
- Model/user defined coordinates (x,y).
All coordinates in a dfs file are stored in model coordinates.
The `WKTString` defines which ellipsoid the geographical coordinates use (example: WGS-84).
The `WKTString` defines the mapping from geographical coordinates to projection coordinates.
The `Longitude`, `Latitude` and `Orientation` defines the origin and the
orientation of the model coordinates. It is used to move and rotate
the model coordinates, i.e., a dfs2 file with a 2D equidistant axis
defines its model coordinate origin and orientation here (and not in
its axis definition, though that would also be possible).
`Orientation` is the rotation from true north to the model coordinate
y-axis in degrees, measured positive clockwise.
If `Orientation` is zero, and `Longitude` and `Latitude`
matches the origin of the projection coordinate system, then projection coordinates equals model
coordinates. Example: UTM-31 has projection origin at (lon,lat) = (3,0).
"""
def __init__(self, type, wktString: str, longitude: float = 0.0, latitude: float = 0.0, orientation: float = 0.0):
self.Type = type;
self.WKTString = wktString;
self.Longitude = longitude;
self.Latitude = latitude;
self.Orientation = orientation;
@staticmethod
def Create(wktString: str):
if (wktString is None or wktString == ""):
raise Exception("Projection string can not be null or empty");
return DfsProjection(ProjectionType.Projection, wktString, 0.0, 0.0, 0.0)
@staticmethod
def CreateWithGeoOrigin(wktString: str, lon0: float, lat0: float, orientation: float):
if (wktString is None or wktString == ""):
raise Exception("Projection string can not be null or empty");
return DfsProjection(ProjectionType.Projection, wktString, lon0, lat0, orientation)
class DfsTemporalAxis:
def __init__(
self, timeUnit, startTimeOffset, numberOfTimeSteps, firstTimeStepIndex
):
self.TimeAxisType = TimeAxisType.Undefined
self._TimeUnit = timeUnit
self._StartTimeOffset = startTimeOffset
self.NumberOfTimeSteps = numberOfTimeSteps
self._FirstTimeStepIndex = firstTimeStepIndex
self._OnUpdate = None;
self.__calcToSecFactor();
# Method that is invoked when ever the temporal axis is updated.
def _InvokeOnUpdate(self):
if self._OnUpdate != None:
self._OnUpdate()
def __getTimeUnit(self):
return self._TimeUnit;
def __setTimeUnit(self, timeUnit):
self._TimeUnit = timeUnit
self._InvokeOnUpdate();
self.__calcToSecFactor();
TimeUnit = property(__getTimeUnit, __setTimeUnit)
def __calcToSecFactor(self):
if self._TimeUnit == eumUnit.eumUmillisec: self._toSecondsFactor = 0.001; return;
if self._TimeUnit == eumUnit.eumUsec: self._toSecondsFactor = 1.0; return;
if self._TimeUnit == eumUnit.eumUminute: self._toSecondsFactor = 60.0; return;
if self._TimeUnit == eumUnit.eumUhour: self._toSecondsFactor = 3600.0; return;
if self._TimeUnit == eumUnit.eumUday: self._toSecondsFactor = 86400.0; return;
self._toSecondsFactor = 1.0;
if (eumWrapper.eumUnitsEqv(self._TimeUnit, eumUnit.eumUsec)):
res = eumWrapper.eumConvertUnit(self._TimeUnit, 1.0, eumUnit.eumUsec);
if res[0]:
self._toSecondsFactor = res[1]
else:
self._toSecondsFactor = 1.0;
def __getStartTimeOffset(self):
return self._StartTimeOffset;
def __setStartTimeOffset(self, startTimeOffset):
self._StartTimeOffset = startTimeOffset
self._InvokeOnUpdate();
StartTimeOffset = property(__getStartTimeOffset, __setStartTimeOffset)
def __getFirstTimeStepIndex(self):
return self._FirstTimeStepIndex;
def __setFirstTimeStepIndex(self, firstTimeStepIndex):
self._FirstTimeStepIndex = firstTimeStepIndex
self._InvokeOnUpdate();
FirstTimeStepIndex = property(__getFirstTimeStepIndex, __setFirstTimeStepIndex)
def IncrementNumberOfTimeSteps(self, time):
self.NumberOfTimeSteps += 1
def IsEquidistant(self):
return ( self.TimeAxisType == TimeAxisType.CalendarEquidistant
or self.TimeAxisType == TimeAxisType.TimeEquidistant)
def IsCalendar(self):
return ( self.TimeAxisType == TimeAxisType.CalendarEquidistant
or self.TimeAxisType == TimeAxisType.CalendarNonEquidistant)
def ToSeconds(self, relativeTime):
return relativeTime * self._toSecondsFactor;
def ToRelativeTime(self, relativeSeconds):
return relativeSeconds / self._toSecondsFactor;
class DfsEqTimeAxis(DfsTemporalAxis):
def __init__(
self, timeUnit, startTimeOffset, timeStep, numberOfTimeSteps, firstTimeStepIndex
):
super().__init__(
timeUnit, startTimeOffset, numberOfTimeSteps, firstTimeStepIndex
)
self.TimeAxisType = TimeAxisType.TimeEquidistant
self._TimeStep = timeStep
def __getTimeStep(self):
return self._TimeStep;
def __setTimeStep(self, timeStep):
self._TimeStep = timeStep
self._InvokeOnUpdate();
TimeStep = property(__getTimeStep, __setTimeStep)
def TimeStepInSeconds(self):
return self.TimeStep * self._toSecondsFactor;
class DfsNonEqTimeAxis(DfsTemporalAxis):
def __init__(
self, timeUnit, startTimeOffset, numberOfTimeSteps, timeSpan, firstTimeStepIndex
):
super().__init__(
timeUnit, startTimeOffset, numberOfTimeSteps, firstTimeStepIndex
)
self.TimeAxisType = TimeAxisType.TimeNonEquidistant
self.TimeSpan = timeSpan
def IncrementNumberOfTimeSteps(self, time):
self.NumberOfTimeSteps += 1
self.TimeSpan = time - self.StartTimeOffset;
class DfsEqCalendarAxis(DfsTemporalAxis):
def __init__(
self,
timeUnit,
startDateTime,
startTimeOffset,
timeStep,
numberOfTimeSteps,
firstTimeStepIndex,
):
super().__init__(
timeUnit, startTimeOffset, numberOfTimeSteps, firstTimeStepIndex
)
self.TimeAxisType = TimeAxisType.CalendarEquidistant
self._StartDateTime = startDateTime
self._TimeStep = timeStep
def __getStartDateTime(self):
return self._StartDateTime;
def __setStartDateTime(self, startDateTime):
self._StartDateTime = startDateTime;
self._InvokeOnUpdate();
StartDateTime = property(__getStartDateTime, __setStartDateTime)
def __getTimeStep(self):
return self._TimeStep;
def __setTimeStep(self, timeStep):
self._TimeStep = timeStep
self._InvokeOnUpdate();
TimeStep = property(__getTimeStep, __setTimeStep)
def TimeStepInSeconds(self):
return self.TimeStep * self._toSecondsFactor;
class DfsNonEqCalendarAxis(DfsTemporalAxis):
def __init__(
self,
timeUnit,
startDateTime,
startTimeOffset,
timeSpan,
numberOfTimeSteps,
firstTimeStepIndex,
):
super().__init__(
timeUnit, startTimeOffset, numberOfTimeSteps, firstTimeStepIndex
)
self.TimeAxisType = TimeAxisType.CalendarNonEquidistant
self._StartDateTime = startDateTime
self.TimeSpan = timeSpan
def __getStartDateTime(self):
return self._StartDateTime;
def __setStartDateTime(self, startDateTime):
self._StartDateTime = startDateTime;
self._InvokeOnUpdate();
StartDateTime = property(__getStartDateTime, __setStartDateTime)
def IncrementNumberOfTimeSteps(self, time):
self.NumberOfTimeSteps += 1
self.TimeSpan = time - self.StartTimeOffset;
class DfsSpatialAxis:
def __init__(self, axisType, shape, sizeOfData, axisUnit):
self.AxisType = axisType
self.Shape = shape
self.Dimension = len(shape)
self.SizeOfData = sizeOfData
self.AxisUnit = axisUnit
class DfsAxisEqD0(DfsSpatialAxis):
def __init__(self, axisUnit = eumUnit.eumUmeter):
super().__init__(SpaceAxisType.EqD0, (0,), 1, axisUnit)
@staticmethod
def Create():
return DfsAxisEqD0()
class DfsAxisEqD1(DfsSpatialAxis):
def __init__(self, axisUnit, xCount, x0, dx):
super().__init__(SpaceAxisType.EqD1, (xCount,), xCount, axisUnit)
self.XCount = xCount
self.X0 = x0
self.Dx = dx
@staticmethod
def CreateDummyAxis(xCount):
axis = DfsAxisEqD1(
eumUnit.eumUUnitUndefined,
xCount, 0.0, 1.0);
return (axis);
class DfsAxisEqD2(DfsSpatialAxis):
def __init__(self, axisUnit, xCount, x0, dx, yCount, y0, dy):
super().__init__(SpaceAxisType.EqD2, (xCount,yCount), xCount*yCount, axisUnit)
self.XCount = xCount
self.X0 = x0
self.Dx = dx
self.YCount = yCount
self.Y0 = y0
self.Dy = dy
class DfsAxisEqD3(DfsSpatialAxis):
def __init__(self, axisUnit, xCount, x0, dx, yCount, y0, dy, zCount, z0, dz):
super().__init__(SpaceAxisType.EqD3, (xCount,yCount,zCount), xCount*yCount*zCount, axisUnit)
self.XCount = xCount
self.X0 = x0
self.Dx = dx
self.YCount = yCount
self.Y0 = y0
self.Dy = dy
self.ZCount = zCount
self.Z0 = z0
self.Dz = dz
class DfsAxisNeqD1(DfsSpatialAxis):
def __init__(self, axisUnit, coords):
super().__init__(SpaceAxisType.NeqD1, (len(coords),), len(coords), axisUnit)
self.Coordinates = coords
class DfsAxisNeqD2(DfsSpatialAxis):
def __init__(self, axisUnit, xCoords, yCoords):
super().__init__(SpaceAxisType.NeqD2, ((len(xCoords)-1),(len(yCoords)-1)), (len(xCoords)-1)*(len(yCoords)-1), axisUnit)
self.XCoordinates = xCoords
self.YCoordinates = yCoords
class DfsAxisNeqD3(DfsSpatialAxis):
def __init__(self, axisUnit, xCoords, yCoords, zCoords):
super().__init__(SpaceAxisType.NeqD2, ((len(xCoords)-1),(len(yCoords)-1),(len(zCoords)-1)), (len(xCoords)-1)*(len(yCoords)-1)*(len(zCoords)-1), axisUnit)
self.XCoordinates = xCoords
self.YCoordinates = yCoords
self.ZCoordinates = zCoords
class DfsAxisCurveLinearD2(DfsSpatialAxis):
def __init__(self, axisUnit, xCount, yCount, xCoords, yCoords):
super().__init__(SpaceAxisType.CurveLinearD2, (xCount,yCount), xCount*yCount, axisUnit)
self.XCount = xCount
self.YCount = yCount
self.XCoordinates = xCoords
self.YCoordinates = yCoords
class DfsAxisCurveLinearD3(DfsSpatialAxis):
def __init__(self, axisUnit, xCount, yCount, zCount, xCoords, yCoords, zCoords):
super().__init__(SpaceAxisType.CurveLinearD3, (xCount,yCount,zCount), xCount*yCount*zCount, axisUnit)
self.XCount = xCount
self.YCount = yCount
self.ZCount = zCount
self.XCoordinates = xCoords
self.YCoordinates = yCoords
self.ZCoordinates = zCoords
class DfsDynamicItemInfo:
def __init__(self, itemPointer = None, itemNumber = 0):
self.ItemPointer = itemPointer
self.ItemNumber = itemNumber
self.DataType = DfsSimpleType.UShort
self.Name = ""
self.ElementCount = -1
self.Quantity = None
self.ReferenceCoordinateX = np.float32(-1e-35)
self.ReferenceCoordinateY = np.float32(-1e-35)
self.ReferenceCoordinateZ = np.float32(-1e-35)
self.OrientationAlpha = np.float32(-1e-35)
self.OrientationPhi = np.float32(-1e-35)
self.OrientationTheta = np.float32(-1e-35)
self.ConversionType = UnitConversionType.NoConversion
self.ConversionUnit = 0
self.AxisConversionType = UnitConversionType.NoConversion
self.AxisConversionUnit = 0
self.AssociatedStaticItemNumbers = []
self.SpatialAxis = None
def __repr__(self):
return (
'DfsItem("'
+ self.Name
+ '", ('
+ str(self.Quantity)
+ "), "
+ self.DataType.name
+ ")"
)
def init(self, itemName, eumQuantity):
self.Name = itemName
self.Quantity = eumQuantity
def SetReferenceCoordinates(self, x, y, z):
self.ReferenceCoordinateX = x
self.ReferenceCoordinateY = y
self.ReferenceCoordinateZ = z
def SetOrientation(self, alpha, phi, theta):
self.OrientationAlpha = alpha;
self.OrientationPhi = phi;
self.OrientationTheta = theta;
def SetUnitConversion(self, conversionType, conversionUnit):
self.ConversionType = conversionType
self.ConversionUnit = conversionUnit
def SetAxisUnitConversion(self, conversionType, conversionUnit):
self.AxisConversionType = conversionType
self.AxisConversionUnit = conversionUnit
def CreateEmptyItemData(self, reshape = False):
data = self.CreateEmptyItemDataData(reshape)
return DfsItemData(0, self.ItemNumber, 0.0, data)
def CreateEmptyItemDataData(self, reshape = False):
if self.DataType == DfsSimpleType.Float:
values = np.zeros(self.ElementCount, dtype=np.float32)
elif self.DataType == DfsSimpleType.Double:
values = np.zeros(self.ElementCount, dtype=np.float64)
elif self.DataType == DfsSimpleType.Int:
values = np.zeros(self.ElementCount, dtype=np.int32)
elif self.DataType == DfsSimpleType.UInt:
values = np.zeros(self.ElementCount, dtype=np.uint32)
elif self.DataType == DfsSimpleType.Byte:
values = np.zeros(self.ElementCount, dtype=np.int8)
elif self.DataType == DfsSimpleType.Short:
values = np.zeros(self.ElementCount, dtype=np.int16)
elif self.DataType == DfsSimpleType.UShort:
values = np.zeros(self.ElementCount, dtype=np.uint16)
else:
print("Ahhrrggg!!!!: {}-{}".format(self.DataType,self.ElementCount))
if (reshape):
values = values.reshape(self.SpatialAxis.Shape, order = 'F')
return values;
class DfsStaticItem(DfsDynamicItemInfo):
def __init__(self, dfsFile = None, vectorPointer = None, itemPointer = None, itemNumber = None):
super().__init__(itemPointer, itemNumber)
self.DfsFile = dfsFile
self.VectorPointer = vectorPointer
self.Data = None
@staticmethod
def Create(name, quantity, data, spatialAxis = None):
if (spatialAxis is None):
if (data.size == 1):
spatialAxis = DfsAxisEqD0.Create();
else:
spatialAxis = DfsAxisEqD1.CreateDummyAxis(data.size);
staticItem = DfsStaticItem()
staticItem.Name = name
staticItem.Quantity = quantity
staticItem.Data = data
staticItem.DataType = DfsDLLUtil.GetDfsType(data)
staticItem.SpatialAxis = spatialAxis
staticItem.ElementCount = spatialAxis.SizeOfData
return staticItem
class DfsItemData:
def __init__(self, timestepIndex, itemNumber, time, data):
self.TimeStepIndex = timestepIndex
self.ItemNumber = itemNumber
self.Time = time
self.Data = data
def __repr__(self):
return (
"DfsItemData("
+ str(self.TimeStepIndex)
+ ","
+ str(self.ItemNumber)
+ ","
+ str(self.Time)
+ ")"
)
class DfsFileInfo:
"""File info, containing header data."""
def __init__(self):
self.DfsFile = None
self.FileName = ""
self.FileTitle = ""
self.ApplicationTitle = "MIKE Core Python"
self.ApplicationVersion = int(1)
self.DataType = 0
# self.FileType = None;
self.StatsType = StatType.NoStat;
# TODO: Check which items are loaded and which delete value to store, and if only one, store in DeleteValue
self.DeleteValueFloat = DfsFile.DefaultDeleteValueFloat
self.DeleteValueDouble = DfsFile.DefaultDeleteValueDouble
self.DeleteValueByte = DfsFile.DefaultDeleteValueByte
self.DeleteValueInt = DfsFile.DefaultDeleteValueInt
self.DeleteValueUnsignedInt = DfsFile.DefaultDeleteValueUnsignedInt
self.Projection = None
self.TimeAxis = None
self.CustomBlocks = []
self.IsFileCompressed = False
self.xKey = None
self.yKey = None
self.zKey = None
def InitRead(self, dfsFile, headerPointer, parameters=DfsParameters()):
# header pointer is assigned before any other code is issued, in order to
# make sure that the destructor can destroy it in case of failures.
self.DfsFile = dfsFile
# The dfsParamModifyTimes must be called before getting the temporal axis.
DfsDLL.Wrapper.dfsParamModifyTimes(headerPointer, ctypes.c_int32(parameters.ModifyTimes))
self.FileName = dfsFile.FileName
self.FileTitle = DfsDLL.Wrapper.dfsGetFileTitle(headerPointer).decode("cp1252", "replace")
self.ApplicationTitle = DfsDLL.Wrapper.dfsGetAppTitle(headerPointer).decode("cp1252", "replace")
self.ApplicationVersion = DfsDLL.Wrapper.dfsGetAppVersionNo(headerPointer)
self.DataType = DfsDLL.Wrapper.dfsGetDataType(headerPointer)
# self.FileType = None;
# self.StatsType = None;
# TODO: Check which items are loaded and which delete value to store, and if only one, store in DeleteValue
self.DeleteValueFloat = DfsDLL.Wrapper.dfsGetDeleteValFloat(headerPointer)
self.DeleteValueByte = DfsDLL.Wrapper.dfsGetDeleteValByte(headerPointer)
self.DeleteValueDouble = DfsDLL.Wrapper.dfsGetDeleteValDouble(headerPointer)
self.DeleteValueInt = DfsDLL.Wrapper.dfsGetDeleteValInt(headerPointer)
self.DeleteValueUnsignedInt = DfsDLL.Wrapper.dfsGetDeleteValUnsignedInt(headerPointer)
# TODO: implement
self.Projection = DfsDLLUtil.GetProjection(headerPointer)
self.TimeAxis = DfsDLLUtil.GetTemporalAxis(headerPointer)
self.CustomBlocks = DfsDLLUtil.BuildCustomBlocks(headerPointer)
self.IsFileCompressed = (DfsDLL.Wrapper.dfsIsFileCompressed(headerPointer) != 0)
self.TimeAxis._OnUpdate = self.__UpdateTemporalAxis;
# TODO: Test on dfs3 file from MIKE SHE
if self.IsFileCompressed:
encodeKeySize = DfsDLL.Wrapper.dfsGetEncodeKeySize(headerPointer)
self.xKey = np.zeros(encodeKeySize, dtype=np.int32)
self.yKey = np.zeros(encodeKeySize, dtype=np.int32)
self.zKey = np.zeros(encodeKeySize, dtype=np.int32)
DfsDLL.Wrapper.dfsGetEncodeKey(
headerPointer,
self.xKey,
self.yKey,
self.zKey
)
def GetEncodeKey(self):
return self.xKey, self.yKey, self.zKey
def SetEncodingKey(self, xKey, yKey, zKey):
if xKey is None:
raise ArgumentNullException("xKey")
if yKey is None:
raise ArgumentNullException("yKey")
if zKey is None:
raise ArgumentNullException("zKey")
encodeKeySize = len(xKey)
if encodeKeySize != len(yKey) or encodeKeySize != len(zKey):
raise ValueError("Encoding key arguments must have same length")
if encodeKeySize > 0:
self.IsFileCompressed = True;
self.xKey = xKey
self.yKey = yKey
self.zKey = zKey
def __UpdateTemporalAxis(self):
DfsDLLUtil.dfsSetTemporalAxis(self.DfsFile.headPointer, self.TimeAxis)
class DfsCustomBlock():
def __init__(self, name, datatype, values):
self.Name = name
self.SimpleType = datatype
self.Values = values
self.Count = values.size
def __getitem__(self, key):
return self.Values[key]
def __setitem__(self, key, value):
self.Values[key] = value
class DfsFilePointerState(IntEnum):
StaticItem = 0
DynamicItem = 1
CreatingItems = 2
class DfsFile:
"""Class for reading DFS file data using the dfs C API"""
# Default values for DeleteValues
DefaultDeleteValueByte = 0
DefaultDeleteValueFloat = -1.0e-35
DefaultDeleteValueDouble = -1.0e-255
DefaultDeleteValueInt = 2147483647
DefaultDeleteValueUnsignedInt = 2147483647
def __init__(self):
DfsDLL.Init()
self.fpState = DfsFilePointerState.StaticItem
self.fpItemNumber = 1
self.fpTimeStepIndex = 0
self.headPointer = ctypes.c_void_p(0)
self.filePointer = ctypes.c_void_p(0)
def __del__(self):
self.Close()
def Open(self, filename, mode = DfsFileMode.Read, parameters=None):
"""
Open file
Parameters
---------
filename: name and path of file to open
"""
# Close file, if already open
if (self.filePointer.value != None):
self.Close()
if (not os.path.isfile(filename)):
raise FileNotFoundError("File not found {}".format(filename))
# Check if trying to edit a read-only file.
if ((mode == DfsFileMode.Edit or mode == DfsFileMode.Append)
and (not os.access(filename, os.W_OK))):
raise Exception("File is readonly and can not be opened for editing: " + filename);
if (parameters is None):
parameters = DfsParameters()
self.FileName = filename
self.FileMode = mode
self.filePointer = ctypes.c_void_p()
self.headPointer = ctypes.c_void_p()
# Marshal filename string to C char*
fnp = ctypes.c_char_p()
fnp.value = filename.encode("cp1252")
if mode is DfsFileMode.Read:
# Open file for reading
rok = DfsDLL.Wrapper.dfsFileRead(
fnp.value, ctypes.byref(self.headPointer), ctypes.byref(self.filePointer)
)
if mode is DfsFileMode.Edit:
rok = DfsDLL.Wrapper.dfsFileEdit(
fnp.value, ctypes.byref(self.headPointer), ctypes.byref(self.filePointer)
)
if mode is DfsFileMode.Append:
rok = DfsDLL.Wrapper.dfsFileAppend(
fnp.value, ctypes.byref(self.headPointer), ctypes.byref(self.filePointer)
)
if (rok != 0):
raise Exception("Could not load file {} (Error code {})".format(filename, rok))
self.FileInfo = DfsFileInfo()
self.FileInfo.InitRead(self, self.headPointer, parameters)
# Load Items
noOfItems = DfsDLL.Wrapper.dfsGetNoOfItems(self.headPointer)
self.ItemInfo = []
for i in range(noOfItems):
self.ItemInfo.append(self.__DynamicItemInfoReadAndCreate(i + 1, noOfItems))
if mode is DfsFileMode.Read:
# file pointer is after header part
self.fpState = DfsFilePointerState.StaticItem;
self.fpItemNumber = 1;
self.fpTimeStepIndex = 0;
if mode is DfsFileMode.Edit:
# file pointer is after header part
self.fpState = DfsFilePointerState.StaticItem;
self.fpItemNumber = 1;
self.fpTimeStepIndex = 0;
if mode is DfsFileMode.Append:
# file pointer is after last time step
self.fpState = DfsFilePointerState.DynamicItem;
self.fpItemNumber = 1;
self.fpTimeStepIndex = self.FileInfo.TimeAxis.NumberOfTimeSteps;
def Building(self, filename, headPointer, filePointer):
self.FileName = filename
self.FileMode = DfsFileMode.Append
self.headPointer = headPointer
self.filePointer = filePointer
self.fpState = DfsFilePointerState.CreatingItems;
self.fpItemNumber = 1;
self.fpTimeStepIndex = -1;
self.FileInfo = DfsFileInfo()
self.FileInfo.InitRead(self, headPointer)
# Load Items
self.ItemInfo = []
noOfItems = DfsDLL.Wrapper.dfsGetNoOfItems(headPointer)
for i in range(noOfItems):
self.ItemInfo.append(self.__DynamicItemInfoReadAndCreate(i + 1, noOfItems))
def Close(self):
"""
Close the file and release all ressources associated with it. The header information
is still valid (for reading) even though the file has been closed.
"""
if (self.filePointer.value != None):
DfsDLL.Wrapper.dfsFileClose(self.headPointer, ctypes.byref(self.filePointer))
if (self.headPointer.value != None):
DfsDLL.Wrapper.dfsHeaderDestroy(ctypes.byref(self.headPointer))
def GetNextItemNumber(self):
return self.fpItemNumber
def GetNextTimeStepIndex(self):
return self.fpTimeStepIndex
def ReadStaticItemNext(self):
"""
Reads the next static item. First time called it returns the first
static item.
If `ReadStaticItem` is called for example with argument
staticItemNo 3, the next call to this method will return static item number 4.
If one of the methods reading/writing dynamic item data is called, see
`IDfsFileIO`, the static item number is reset, and
the next call to this method again returns the first item number.
:returns: The next static item, null if no more items are present.
"""
self.__CheckIfOpen()
if (self.fpState == DfsFilePointerState.CreatingItems):
raise Exception("Can not read static items when file is being created.")
if (self.fpState != DfsFilePointerState.StaticItem):
DfsDLL.Wrapper.dfsFindBlockStatic(self.headPointer, self.filePointer)
self.fpState = DfsFilePointerState.StaticItem
self.fpItemNumber = 1
self.fpTimeStepIndex = -1
staticItem = self.__StaticItemReadAndCreate(self.fpItemNumber, False)
if (staticItem != None):
self.fpItemNumber += 1
return (staticItem)
def ReadStaticItem(self, staticItemNo):
"""
Read the number <paramref name="staticItemNo"/> static item from the file.
:param staticItemNo: Number of static item in the file to read. First static item has number 1
:returns: The static item number <paramref name="staticItemNo"/>, null if there are not that many static items.
"""
self.__CheckIfOpen();
if (self.fpState == DfsFilePointerState.CreatingItems):
raise Exception("Can not read static items when file is being created.");
if (self.fpState != DfsFilePointerState.StaticItem or self.fpItemNumber != staticItemNo):
DfsDLL.Wrapper.dfsFindItemStatic(self.headPointer, self.filePointer, staticItemNo);
self.fpState = DfsFilePointerState.StaticItem;
self.fpItemNumber = staticItemNo;
self.fpTimeStepIndex = -1;
return (self.ReadStaticItemNext());
def WriteStaticItemData(self, staticItem, data: np.ndarray):
"""
Write the static item back to the file. the <paramref name="staticItem"/> must
originate from this file. This will update and overwrite the static item information and
the data of the static item.
:param staticItem: Static item to update
:param data: New data to insert. Data length must match the data size of the static item.
"""
self.__CheckIfOpen();
stItem = staticItem
if (data is None):
raise Exception("data is not defined");
if (self.fpState != DfsFilePointerState.CreatingItems):
if (stItem.ItemNumber <= 0):
raise Exception("ItemNumber for static item is zero or negative.");
# We are updating an existing static vector, position file pointer
if (self.fpState != DfsFilePointerState.StaticItem or self.fpItemNumber != stItem.ItemNumber):
DfsDLL.Wrapper.dfsFindItemStatic(self.headPointer, self.filePointer, stItem.ItemNumber);
self.fpState = DfsFilePointerState.StaticItem;
self.fpItemNumber = stItem.ItemNumber;
self.fpTimeStepIndex = -1;
# Check length of data
# data.Length can be larger than the number of elements.
if (stItem.ElementCount > data.size):
raise Exception("Length of data does not match size of static vector.");
# Check type of data, and save to disc.
if (DfsDLLUtil.GetDfsType(data) != stItem.DataType):
raise Exception("Type of data defined in static item does not match type of data argument.");
rok = DfsDLL.Wrapper.dfsStaticWrite(stItem.VectorPointer, self.filePointer, data.ctypes.data);
DfsDLL.CheckReturnCode(rok);
self.fpItemNumber += 1;
def ReadItemTimeStepNext(self, itemData: DfsItemData = None, reshape: bool = False) -> DfsItemData:
"""
Reads the next dynamic item-timestep. First time called it returns the first
timestep of the first item. It cycles through each timestep, and each
item in the timestep. For a file with 3 items, it returns (itemnumber, timestepIndex)
in the following order:
(1,0), (2,0), (3,0), (1,1), (2,1), (3,1), (1,2), etc.
If one of the ReadItemTimeStep is called with for example (1,4)
the next call to this method will continue from there and return (2,4).
If one of the methods reading/writing static item data is called,
the iterator is reset, and the next call to this method again
returns the first item-timestep.
This is the most efficient way to iterate through all the items and timesteps in a file,
since it iterates exactly as the data is stored on the disk.
:param itemData DfsItemData: DfsItemData for item to store timestep values in, for reuse of memory.
:param reshape bool: Reshape data array to dimension of data, 2D or 3D depending on spatial axis.
:returns DfsIemData: The next dynamic item-timestep, None if no more items are present.
"""
self.__CheckIfOpen()
if (self.fpState == DfsFilePointerState.CreatingItems):
raise Exception("No dynamic items have been written to the file yet (file is being created).");
if self.fpState != DfsFilePointerState.DynamicItem:
# Position file pointer at first timestep and first item.
self.__FpFindBlockDynamic()
# TODO: size of item and hence the values array
item = self.ItemInfo[self.fpItemNumber - 1]
if (itemData is None):
values = item.CreateEmptyItemDataData()
else:
values = itemData.Data
if (values.size != item.ElementCount):
raise Exception("itemData.Data is of incorrect size")
timep = ctypes.c_double(0)
success = DfsDLL.Wrapper.dfsReadItemTimeStep(
self.headPointer, self.filePointer, ctypes.byref(timep), values.ctypes.data
)
if success != 0:
return None
time = self.__GetTime(timep.value, self.fpTimeStepIndex)
if (itemData is None):
res = DfsItemData(self.fpTimeStepIndex, self.fpItemNumber, time, values)
else:
res = itemData
res.Time = time
res.TimeStepIndex = self.fpTimeStepIndex
self.__FpDynamicIncrement()
return res
def ReadItemTimeStep(self, itemNumber: Union[int,DfsItemData], timestepIndex: int, reshape: bool = False) -> DfsItemData:
"""
Reads the dynamic item-timestep as specified from the file. It throws an
exception if itemNumber or timestepIndex
is out of range.
:param itemNumber Union[int,DfsItemData]: Item number (1-based), or DfsItemData for item
:param timestepIndex int: Time step index (0-based)
:param reshape bool: Reshape data array to dimension of data, 2D or 3D depending on spatial axis.
:return DfsItemData: The dynamic item-timestep as specified
"""
self.__CheckIfOpen();
if (self.fpState == DfsFilePointerState.CreatingItems):
raise Exception("No dynamic items have been written to the file yet (file is being created).");
if isinstance(itemNumber, DfsItemData):
itemData = itemNumber
itemNumber = itemNumber.ItemNumber
else:
itemData = None
itemInfoCount = len(self.ItemInfo);
# Check item number and timestep index ranges
if (itemInfoCount == 0):
raise Exception("File has no dynamic items.");
if (itemNumber <= 0 or itemNumber > itemInfoCount):
raise Exception("itemNumber","Must be within [1,NumberOfItems].");
if (timestepIndex < 0 or timestepIndex >= self.FileInfo.TimeAxis.NumberOfTimeSteps):
raise Exception("timestepIndex", "Must be within [0," + (self.FileInfo.TimeAxis.NumberOfTimeSteps-1) + "].");
# Position file pointer
self.__FpFindItemTimeStep(itemNumber, timestepIndex);
return (self.ReadItemTimeStepNext(itemData, reshape));
def __GetTime(self, time, timestepIndex):
# TODO: This assumes time in seconds?
timeaxis = self.FileInfo.TimeAxis
if timeaxis.TimeAxisType == TimeAxisType.TimeEquidistant:
return timeaxis.StartTimeOffset + timestepIndex * timeaxis.TimeStep
elif timeaxis.TimeAxisType == TimeAxisType.CalendarEquidistant:
return timeaxis.StartTimeOffset + timestepIndex * timeaxis.TimeStep
return time
def WriteItemTimeStep(self, itemNumber, timestepIndex, time, data):
"""
Writes data to the specified item and timestep in the file.