-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathitkWasmTransformIO.cxx
993 lines (915 loc) · 37.8 KB
/
itkWasmTransformIO.cxx
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
/*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#define ITK_TEMPLATE_EXPLICIT_WasmTransformIO
#include "itkWasmTransformIO.h"
#include "itkCompositeTransform.h"
#include "itkCompositeTransformIOHelper.h"
#include "itkVersion.h"
#include "itkMakeUniqueForOverwrite.h"
#include <sstream>
#include "itkWasmIOCommon.h"
#include "itktransformParameterizationString.h"
#include "itkMetaDataDictionaryJSON.h"
#include "itkTransformFactoryBase.h"
#include "itkMetaDataObject.h"
#include "itkIOCommon.h"
#include "itksys/SystemTools.hxx"
#include "itksys/SystemTools.hxx"
#include "cbor.h"
namespace itk
{
template <typename TParametersValueType>
WasmTransformIOTemplate<TParametersValueType>::WasmTransformIOTemplate() = default;
template <typename TParametersValueType>
WasmTransformIOTemplate<TParametersValueType>::~WasmTransformIOTemplate() = default;
template <typename TParametersValueType>
void
WasmTransformIOTemplate<TParametersValueType>::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
}
template <typename TParametersValueType>
bool
WasmTransformIOTemplate<TParametersValueType>::CanReadFile(const char * filename)
{
// Check the extension first to avoid opening files that do not
// look like JSON. The file must have an appropriate extension to be
// recognized.
std::string fname = filename;
//
bool extensionFound = false;
std::string::size_type extensionPos = fname.rfind(".iwt");
if (extensionPos != std::string::npos)
{
extensionFound = true;
}
if (!extensionFound)
{
itkDebugMacro(<< "The filename extension is not recognized");
return false;
}
return true;
}
template <typename TParametersValueType>
void
WasmTransformIOTemplate<TParametersValueType>::ReadCBOR( void *buffer, unsigned char * cborBuffer, size_t cborBufferLength )
{
bool cborBufferAllocated = false;
size_t length = cborBufferLength;
if (cborBuffer == nullptr)
{
FILE* file = fopen(this->GetFileName(), "rb");
if (file == NULL) {
itkExceptionMacro("Could not read file: " << this->GetFileName());
}
fseek(file, 0, SEEK_END);
length = (size_t)ftell(file);
fseek(file, 0, SEEK_SET);
cborBuffer = static_cast< unsigned char *>(malloc(length));
cborBufferAllocated = true;
if (!fread(cborBuffer, length, 1, file))
{
itkExceptionMacro("Could not successfully read " << this->GetFileName());
}
fclose(file);
}
if (this->m_CBORRoot != nullptr)
{
cbor_decref(&(this->m_CBORRoot));
}
struct cbor_load_result result;
this->m_CBORRoot = cbor_load(cborBuffer, length, &result);
if (cborBufferAllocated)
{
free(cborBuffer);
}
if (result.error.code != CBOR_ERR_NONE)
{
std::string errorDescription;
switch (result.error.code)
{
case CBOR_ERR_MALFORMATED:
{
errorDescription = "Malformed data\n";
break;
}
case CBOR_ERR_MEMERROR:
{
errorDescription = "Memory error -- perhaps the input is too large?\n";
break;
}
case CBOR_ERR_NODATA:
{
errorDescription = "The input is empty\n";
break;
}
case CBOR_ERR_NOTENOUGHDATA:
{
errorDescription = "Data seem to be missing -- is the input complete?\n";
break;
}
case CBOR_ERR_SYNTAXERROR:
{
errorDescription = "Syntactically malformed data -- see https://tools.ietf.org/html/rfc7049\n";
break;
}
case CBOR_ERR_NONE:
{
break;
}
}
itkExceptionMacro("" << errorDescription << "There was an error while reading the input near byte "
<< result.error.position << " (read " << result.read << " bytes in total): ");
}
TransformListJSON transformListJSON;
cbor_item_t * index = this->m_CBORRoot;
const size_t transformCount = cbor_array_size(index);
for (size_t ii = 0; ii < transformCount; ++ii)
{
const cbor_item_t * transformItem = cbor_array_get(index, ii);
const size_t transformPropertyCount = cbor_map_size(transformItem);
const struct cbor_pair * transformHandle = cbor_map_handle(transformItem);
TransformJSON transformJSON;
for (size_t jj = 0; jj < transformPropertyCount; ++jj)
{
const std::string_view key(reinterpret_cast<char *>(cbor_string_handle(transformHandle[jj].key)),
cbor_string_length(transformHandle[jj].key));
if (key == "transformType")
{
const cbor_item_t * transformTypeItem = transformHandle[jj].value;
const size_t transformTypePropertyCount = cbor_map_size(transformTypeItem);
const struct cbor_pair * transformTypeHandle = cbor_map_handle(transformTypeItem);
for (size_t kk = 0; kk < transformTypePropertyCount; ++kk)
{
const std::string_view transformTypeKey(
reinterpret_cast<char *>(cbor_string_handle(transformTypeHandle[kk].key)),
cbor_string_length(transformTypeHandle[kk].key));
if (transformTypeKey == "transformParameterization")
{
const std::string transformParameterization(
reinterpret_cast<char *>(cbor_string_handle(transformTypeHandle[kk].value)),
cbor_string_length(transformTypeHandle[kk].value));
if (transformParameterization == "Composite")
{
transformJSON.transformType.transformParameterization = JSONTransformParameterizationEnum::Composite;
}
else if (transformParameterization == "Identity")
{
transformJSON.transformType.transformParameterization = JSONTransformParameterizationEnum::Identity;
}
else if (transformParameterization == "Translation")
{
transformJSON.transformType.transformParameterization = JSONTransformParameterizationEnum::Translation;
}
else if (transformParameterization == "Euler2D")
{
transformJSON.transformType.transformParameterization = JSONTransformParameterizationEnum::Euler2D;
}
else if (transformParameterization == "Euler3D")
{
transformJSON.transformType.transformParameterization = JSONTransformParameterizationEnum::Euler3D;
}
else if (transformParameterization == "Rigid2D")
{
transformJSON.transformType.transformParameterization = JSONTransformParameterizationEnum::Rigid2D;
}
else if (transformParameterization == "Rigid3D")
{
transformJSON.transformType.transformParameterization = JSONTransformParameterizationEnum::Rigid3D;
}
else if (transformParameterization == "Rigid3DPerspective")
{
transformJSON.transformType.transformParameterization =
JSONTransformParameterizationEnum::Rigid3DPerspective;
}
else if (transformParameterization == "Versor")
{
transformJSON.transformType.transformParameterization = JSONTransformParameterizationEnum::Versor;
}
else if (transformParameterization == "VersorRigid3D")
{
transformJSON.transformType.transformParameterization = JSONTransformParameterizationEnum::VersorRigid3D;
}
else if (transformParameterization == "Scale")
{
transformJSON.transformType.transformParameterization = JSONTransformParameterizationEnum::Scale;
}
else if (transformParameterization == "ScaleLogarithmic")
{
transformJSON.transformType.transformParameterization =
JSONTransformParameterizationEnum::ScaleLogarithmic;
}
else if (transformParameterization == "ScaleSkewVersor3D")
{
transformJSON.transformType.transformParameterization =
JSONTransformParameterizationEnum::ScaleSkewVersor3D;
}
else if (transformParameterization == "Similarity2D")
{
transformJSON.transformType.transformParameterization = JSONTransformParameterizationEnum::Similarity2D;
}
else if (transformParameterization == "Similarity3D")
{
transformJSON.transformType.transformParameterization = JSONTransformParameterizationEnum::Similarity3D;
}
else if (transformParameterization == "QuaternionRigid")
{
transformJSON.transformType.transformParameterization =
JSONTransformParameterizationEnum::QuaternionRigid;
}
else if (transformParameterization == "Affine")
{
transformJSON.transformType.transformParameterization = JSONTransformParameterizationEnum::Affine;
}
else if (transformParameterization == "ScalableAffine")
{
transformJSON.transformType.transformParameterization = JSONTransformParameterizationEnum::ScalableAffine;
}
else if (transformParameterization == "AzimuthElevationToCartesian")
{
transformJSON.transformType.transformParameterization =
JSONTransformParameterizationEnum::AzimuthElevationToCartesian;
}
else if (transformParameterization == "BSpline")
{
transformJSON.transformType.transformParameterization = JSONTransformParameterizationEnum::BSpline;
}
else if (transformParameterization == "BSplineSmoothingOnUpdateDisplacementField")
{
transformJSON.transformType.transformParameterization =
JSONTransformParameterizationEnum::BSplineSmoothingOnUpdateDisplacementField;
}
else if (transformParameterization == "ConstantVelocityField")
{
transformJSON.transformType.transformParameterization =
JSONTransformParameterizationEnum::ConstantVelocityField;
}
else if (transformParameterization == "DisplacementField")
{
transformJSON.transformType.transformParameterization =
JSONTransformParameterizationEnum::DisplacementField;
}
else if (transformParameterization == "GaussianSmoothingOnUpdateDisplacementField")
{
transformJSON.transformType.transformParameterization =
JSONTransformParameterizationEnum::GaussianSmoothingOnUpdateDisplacementField;
}
else if (transformParameterization == "GaussianExponentialDiffeomorphic")
{
transformJSON.transformType.transformParameterization =
JSONTransformParameterizationEnum::GaussianExponentialDiffeomorphic;
}
else if (transformParameterization == "VelocityField")
{
transformJSON.transformType.transformParameterization = JSONTransformParameterizationEnum::VelocityField;
}
else if (transformParameterization == "TimeVaryingVelocityField")
{
transformJSON.transformType.transformParameterization =
JSONTransformParameterizationEnum::TimeVaryingVelocityField;
}
else if (transformParameterization == "GaussianSmoothingOnUpdateTimeVaryingVelocityField")
{
transformJSON.transformType.transformParameterization =
JSONTransformParameterizationEnum::GaussianSmoothingOnUpdateTimeVaryingVelocityField;
}
else
{
itkExceptionMacro("Unexpected transformParameterization: " << transformParameterization);
}
}
else if (transformTypeKey == "parametersValueType")
{
const std::string parametersValueType(
reinterpret_cast<char *>(cbor_string_handle(transformTypeHandle[kk].value)),
cbor_string_length(transformTypeHandle[kk].value));
if (parametersValueType == "float32")
{
transformJSON.transformType.parametersValueType = JSONFloatTypesEnum::float32;
}
else if (parametersValueType == "float64")
{
transformJSON.transformType.parametersValueType = JSONFloatTypesEnum::float64;
}
else
{
itkExceptionMacro("Unexpected parametersValueType: " << parametersValueType);
}
}
else if (transformTypeKey == "inputDimension")
{
const auto inputDimension = cbor_get_uint32(transformTypeHandle[kk].value);
transformJSON.transformType.inputDimension = inputDimension;
}
else if (transformTypeKey == "outputDimension")
{
const auto outputDimension = cbor_get_uint32(transformTypeHandle[kk].value);
transformJSON.transformType.outputDimension = outputDimension;
}
else
{
itkExceptionMacro("Unexpected transformType cbor map key: " << transformTypeKey);
}
}
}
else if (key == "numberOfFixedParameters")
{
const auto numberOfFixedParameters = cbor_get_uint64(transformHandle[jj].value);
transformJSON.numberOfFixedParameters = numberOfFixedParameters;
}
else if (key == "numberOfParameters")
{
const auto numberOfParameters = cbor_get_uint64(transformHandle[jj].value);
transformJSON.numberOfParameters = numberOfParameters;
}
else if (key == "name")
{
const std::string name(reinterpret_cast<char *>(cbor_string_handle(transformHandle[jj].value)),
cbor_string_length(transformHandle[jj].value));
transformJSON.name = name;
}
else if (key == "inputSpaceName")
{
const std::string inputSpaceName(reinterpret_cast<char *>(cbor_string_handle(transformHandle[jj].value)),
cbor_string_length(transformHandle[jj].value));
transformJSON.inputSpaceName = inputSpaceName;
}
else if (key == "outputSpaceName")
{
const std::string outputSpaceName(reinterpret_cast<char *>(cbor_string_handle(transformHandle[jj].value)),
cbor_string_length(transformHandle[jj].value));
transformJSON.outputSpaceName = outputSpaceName;
}
}
transformListJSON.push_back(transformJSON);
}
this->SetJSON(transformListJSON);
auto readTransformList = this->GetReadTransformList();
unsigned int count = 0;
for (auto [transformIt, jsonIt] = std::tuple{ readTransformList.begin(), transformListJSON.begin() };
transformIt != readTransformList.end();
++transformIt, ++jsonIt)
{
const auto transformJSON = *jsonIt;
if (transformJSON.transformType.transformParameterization == JSONTransformParameterizationEnum::Composite)
{
++count;
continue;
}
FixedParametersType fixedParams(transformJSON.numberOfFixedParameters);
const SizeValueType numberOfFixedBytes = transformJSON.numberOfFixedParameters * sizeof(FixedParametersValueType);
ParametersType params(transformJSON.numberOfParameters);
const SizeValueType numberOfBytes = transformJSON.numberOfParameters * sizeof(ParametersValueType);
const auto valueBytes = sizeof(ParametersValueType);
const cbor_item_t * transformItem = cbor_array_get(index, count);
const size_t transformPropertyCount = cbor_map_size(transformItem);
const struct cbor_pair * transformHandle = cbor_map_handle(transformItem);
for (size_t jj = 0; jj < transformPropertyCount; ++jj)
{
const std::string_view key(reinterpret_cast<char *>(cbor_string_handle(transformHandle[jj].key)),
cbor_string_length(transformHandle[jj].key));
if (key == "fixedParameters")
{
readCBORBuffer(transformItem, "fixedParameters", fixedParams.data_block(), numberOfFixedBytes);
(*transformIt)->SetFixedParameters(fixedParams);
}
else if (key == "parameters")
{
if (transformJSON.transformType.parametersValueType == JSONFloatTypesEnum::float32)
{
if (valueBytes != sizeof(float))
{
std::vector<float> floatParams(transformJSON.numberOfParameters);
readCBORBuffer(transformItem, "parameters", floatParams.data(), numberOfBytes);
for (SizeValueType i = 0; i < transformJSON.numberOfParameters; ++i)
{
params[i] = static_cast<ParametersValueType>(floatParams[i]);
}
}
else
{
readCBORBuffer(transformItem, "parameters", params.data_block(), numberOfBytes);
}
}
else if (transformJSON.transformType.parametersValueType == JSONFloatTypesEnum::float64)
{
if (valueBytes != sizeof(double))
{
std::vector<double> doubleParams(transformJSON.numberOfParameters);
readCBORBuffer(transformItem, "parameters", doubleParams.data(), numberOfBytes);
for (SizeValueType i = 0; i < transformJSON.numberOfParameters; ++i)
{
params[i] = static_cast<ParametersValueType>(doubleParams[i]);
}
}
else
{
readCBORBuffer(transformItem, "parameters", params.data_block(), numberOfBytes);
}
}
(*transformIt)->SetParameters(params);
}
}
++count;
}
}
template <typename TParametersValueType>
auto
WasmTransformIOTemplate<TParametersValueType>::GetJSON(bool inMemory) -> TransformListJSON
{
ConstTransformListType & transformList = this->GetWriteTransformList();
TransformListJSON transformListJSON = transformListToTransformListJSON<TransformType>(transformList, inMemory);
return transformListJSON;
}
template <typename TParametersValueType>
void
WasmTransformIOTemplate<TParametersValueType>::SetJSON(const TransformListJSON & json, bool inMemory)
{
// iterate over the JSON and set the transform list
TransformListType transformList;
for (const auto & transformJSON : json)
{
std::string transformPrecision;
switch (transformJSON.transformType.parametersValueType)
{
case JSONFloatTypesEnum::float32:
{
transformPrecision = "float";
break;
}
case JSONFloatTypesEnum::float64:
{
transformPrecision = "double";
break;
}
default:
{
itkExceptionMacro("Unknown parameters value type");
}
}
const std::string transformParameterization = transformParameterizationString(transformJSON.transformType);
// itk::Transform<TParametersValueType, VInputDimension, VOutputDimension>::GetTransformTypeAsString() returns the
// transform type string Note: non-cubic B-Splines not supported
std::string transformType = transformParameterization + "Transform_" + transformPrecision + "_" +
std::to_string(transformJSON.transformType.inputDimension) + "_" +
std::to_string(transformJSON.transformType.outputDimension);
// Transform name should be modified to have the output precision type.
Superclass::CorrectTransformPrecisionType(transformType);
TransformPointer transform;
this->CreateTransform(transform, transformType);
transform->SetObjectName(transformJSON.name);
// todo: ITK 5.4.1
// transform->SetInputSpaceName(transformJSON.inputSpaceName);
// transform->SetOutputSpaceName(transformJSON.outputSpaceName);
auto dictionary = transform->GetMetaDataDictionary();
jsonToMetaDataDictionary(transformJSON.metadata, dictionary);
if (inMemory)
{
if (transformJSON.transformType.transformParameterization == JSONTransformParameterizationEnum::Composite)
{
continue;
}
using ParametersValueType = TParametersValueType;
FixedParametersValueType * fixedPtr = reinterpret_cast< FixedParametersValueType * >( std::strtoull(transformJSON.fixedParameters.substr(35).c_str(), nullptr, 10) );
transform->CopyInFixedParameters(fixedPtr, fixedPtr + transformJSON.numberOfFixedParameters);
ParametersValueType * paramsPtr = reinterpret_cast< ParametersValueType * >( std::strtoull(transformJSON.parameters.substr(35).c_str(), nullptr, 10) );
transform->CopyInParameters(paramsPtr, paramsPtr + transformJSON.numberOfParameters);
auto dictionary = transform->GetMetaDataDictionary();
jsonToMetaDataDictionary(transformJSON.metadata, dictionary);
}
this->GetReadTransformList().push_back(transform);
}
}
template <typename TParametersValueType>
size_t
WasmTransformIOTemplate<TParametersValueType>
::WriteCBOR(const void *buffer, unsigned char ** cborBufferPtr, bool allocateCBORBuffer )
{
auto transformListJSON = this->GetJSON();
if (this->m_CBORRoot != nullptr)
{
cbor_decref(&(this->m_CBORRoot));
}
// create a container for a javascript array
this->m_CBORRoot = cbor_new_definite_array(transformListJSON.size());
unsigned int count = 0;
cbor_item_t * index = this->m_CBORRoot;
// write the transformListJSON into the cbor array
ConstTransformListType & writeTransformList = this->GetWriteTransformList();
const std::string compositeTransformType = writeTransformList.front()->GetTransformTypeAsString();
CompositeTransformIOHelperTemplate<TParametersValueType> helper;
//
// if the first transform in the list is a
// composite transform, use its internal list
// instead of the IO
if (compositeTransformType.find("CompositeTransform") != std::string::npos)
{
writeTransformList = helper.GetTransformList(writeTransformList.front().GetPointer());
}
for (auto [transformIt, jsonIt] = std::tuple{ writeTransformList.begin(), transformListJSON.begin() };
transformIt != writeTransformList.end();
++transformIt, ++jsonIt)
{
const auto & transformJSON = *jsonIt;
cbor_item_t * transformItem = cbor_new_definite_map(8);
cbor_item_t * transformTypeItem = cbor_new_definite_map(4);
const std::string transformParameterization = transformParameterizationString(transformJSON.transformType);
cbor_map_add(transformTypeItem,
cbor_pair{ cbor_move(cbor_build_string("transformParameterization")),
cbor_move(cbor_build_string(transformParameterization.c_str())) });
switch (transformJSON.transformType.parametersValueType)
{
case JSONFloatTypesEnum::float32:
{
cbor_map_add(
transformTypeItem,
cbor_pair{ cbor_move(cbor_build_string("parametersValueType")), cbor_move(cbor_build_string("float32")) });
break;
}
case JSONFloatTypesEnum::float64:
{
cbor_map_add(
transformTypeItem,
cbor_pair{ cbor_move(cbor_build_string("parametersValueType")), cbor_move(cbor_build_string("float64")) });
break;
}
default:
{
itkExceptionMacro("Unknown parameters value type");
}
}
cbor_map_add(transformTypeItem,
cbor_pair{ cbor_move(cbor_build_string("inputDimension")),
cbor_move(cbor_build_uint32(transformJSON.transformType.inputDimension)) });
cbor_map_add(transformTypeItem,
cbor_pair{ cbor_move(cbor_build_string("outputDimension")),
cbor_move(cbor_build_uint32(transformJSON.transformType.outputDimension)) });
cbor_map_add(transformItem,
cbor_pair{ cbor_move(cbor_build_string("transformType")), cbor_move(transformTypeItem) });
cbor_map_add(transformItem,
cbor_pair{ cbor_move(cbor_build_string("numberOfFixedParameters")),
cbor_move(cbor_build_uint64(transformJSON.numberOfFixedParameters)) });
cbor_map_add(transformItem,
cbor_pair{ cbor_move(cbor_build_string("numberOfParameters")),
cbor_move(cbor_build_uint64(transformJSON.numberOfParameters)) });
cbor_map_add(
transformItem,
cbor_pair{ cbor_move(cbor_build_string("name")), cbor_move(cbor_build_string(transformJSON.name.c_str())) });
cbor_map_add(transformItem,
cbor_pair{ cbor_move(cbor_build_string("inputSpaceName")),
cbor_move(cbor_build_string(transformJSON.inputSpaceName.c_str())) });
cbor_map_add(transformItem,
cbor_pair{ cbor_move(cbor_build_string("outputSpaceName")),
cbor_move(cbor_build_string(transformJSON.outputSpaceName.c_str())) });
if (transformJSON.transformType.transformParameterization == JSONTransformParameterizationEnum::Composite)
{
cbor_array_push(index, cbor_move(transformItem));
++count;
continue;
}
const auto fixedNumberOfBytes = transformJSON.numberOfFixedParameters * sizeof(FixedParametersValueType);
const auto fixedParams = (*transformIt)->GetFixedParameters();
writeCBORBuffer(transformItem,
"fixedParameters",
reinterpret_cast<const void *>(fixedParams.data_block()),
fixedNumberOfBytes,
IOComponentEnum::DOUBLE);
const auto numberOfBytes = transformJSON.numberOfParameters * sizeof(ParametersValueType);
const auto params = (*transformIt)->GetParameters();
if (transformJSON.transformType.parametersValueType == JSONFloatTypesEnum::float32)
{
writeCBORBuffer(transformItem,
"parameters",
reinterpret_cast<const void *>(params.data_block()),
numberOfBytes,
IOComponentEnum::FLOAT);
}
else if (transformJSON.transformType.parametersValueType == JSONFloatTypesEnum::float64)
{
writeCBORBuffer(transformItem,
"parameters",
reinterpret_cast<const void *>(params.data_block()),
numberOfBytes,
IOComponentEnum::DOUBLE);
}
cbor_array_push(index, cbor_move(transformItem));
++count;
}
size_t cborBufferSize;
size_t length;
unsigned char * cborBuffer;
if (allocateCBORBuffer)
{
length = cbor_serialize_alloc(index, cborBufferPtr, &cborBufferSize);
}
else
{
length = cbor_serialize_alloc(index, &cborBuffer, &cborBufferSize);
FILE* file = fopen(this->GetFileName(), "wb");
fwrite(cborBuffer, 1, length, file);
free(cborBuffer);
fclose(file);
}
cbor_decref(&(this->m_CBORRoot));
return length;
}
template <typename TParametersValueType>
auto
WasmTransformIOTemplate<TParametersValueType>::ReadTransformInformation() -> const TransformListJSON
{
const std::string path = this->GetFileName();
const auto indexPath = path + "/index.json";
const auto dataPath = path + "/data";
std::ifstream inputStream;
openFileForReading(inputStream, indexPath.c_str(), true);
std::string str((std::istreambuf_iterator<char>(inputStream)), std::istreambuf_iterator<char>());
auto deserializedAttempt = glz::read_json<itk::TransformListJSON>(str);
if (!deserializedAttempt)
{
const std::string descriptiveError = glz::format_error(deserializedAttempt, str);
itkExceptionMacro("Failed to deserialize TransformListJSON: " << descriptiveError);
}
auto transformListJSON = deserializedAttempt.value();
this->SetJSON(transformListJSON);
return transformListJSON;
}
template <typename TParametersValueType>
void
WasmTransformIOTemplate<TParametersValueType>::ReadFixedParameters(const TransformListJSON & json)
{
auto readTransformList = this->GetReadTransformList();
unsigned int count = 0;
for (auto [transformIt, jsonIt] = std::tuple{ readTransformList.begin(), json.begin() };
transformIt != readTransformList.end();
++transformIt, ++jsonIt)
{
const auto transformJSON = *jsonIt;
if ((*jsonIt).transformType.transformParameterization == itk::JSONTransformParameterizationEnum::Composite)
{
++count;
continue;
}
FixedParametersType fixedParams(transformJSON.numberOfFixedParameters);
const SizeValueType numberOfBytes = transformJSON.numberOfFixedParameters * sizeof(FixedParametersValueType);
std::string path(this->GetFileName());
path = path + "/data/" + std::to_string(count);
const std::string filePath = path + "/fixed-parameters.raw";
std::ifstream dataStream;
openFileForReading(dataStream, filePath.c_str());
dataStream.read(reinterpret_cast<char *>(fixedParams.data_block()), numberOfBytes);
const auto readBytes = dataStream.gcount();
if (readBytes != numberOfBytes)
{
itkExceptionMacro(<< "Read failed: Wanted " << numberOfBytes << " bytes, but read " << readBytes << " bytes.");
}
(*transformIt)->SetFixedParameters(fixedParams);
++count;
}
}
template <typename TParametersValueType>
void
WasmTransformIOTemplate<TParametersValueType>::ReadParameters(const TransformListJSON & json)
{
auto readTransformList = this->GetReadTransformList();
unsigned int count = 0;
for (auto [transformIt, jsonIt] = std::tuple{ readTransformList.begin(), json.begin() };
transformIt != readTransformList.end();
++transformIt, ++jsonIt)
{
if ((*jsonIt).transformType.transformParameterization == itk::JSONTransformParameterizationEnum::Composite)
{
++count;
continue;
}
const auto transformJSON = *jsonIt;
ParametersType params(transformJSON.numberOfParameters);
const auto valueBytes = sizeof(ParametersValueType);
const SizeValueType numberOfBytes = transformJSON.numberOfParameters * valueBytes;
std::string path(this->GetFileName());
path = path + "/data/" + std::to_string(count);
const std::string filePath = path + "/parameters.raw";
std::ifstream dataStream;
openFileForReading(dataStream, filePath.c_str());
if (transformJSON.transformType.parametersValueType == JSONFloatTypesEnum::float32)
{
if (valueBytes != sizeof(float))
{
std::vector<float> floatParams(transformJSON.numberOfParameters);
dataStream.read(reinterpret_cast<char *>(floatParams.data()), numberOfBytes);
for (SizeValueType i = 0; i < transformJSON.numberOfParameters; ++i)
{
params[i] = static_cast<ParametersValueType>(floatParams[i]);
}
}
else
{
dataStream.read(reinterpret_cast<char *>(params.data_block()), numberOfBytes);
}
}
else if (transformJSON.transformType.parametersValueType == JSONFloatTypesEnum::float64)
{
if (valueBytes != sizeof(double))
{
std::vector<double> doubleParams(transformJSON.numberOfParameters);
dataStream.read(reinterpret_cast<char *>(doubleParams.data()), numberOfBytes);
for (SizeValueType i = 0; i < transformJSON.numberOfParameters; ++i)
{
params[i] = static_cast<ParametersValueType>(doubleParams[i]);
}
}
else
{
dataStream.read(reinterpret_cast<char *>(params.data_block()), numberOfBytes);
}
}
else
{
itkExceptionMacro("Unknown parameters value type");
}
(*transformIt)->SetParameters(params);
++count;
}
}
template <typename TParametersValueType>
void
WasmTransformIOTemplate<TParametersValueType>::Read()
{
if (fileNameIsCBOR(this->GetFileName()))
{
this->ReadCBOR();
return;
}
const auto json = this->ReadTransformInformation();
this->ReadFixedParameters(json);
this->ReadParameters(json);
}
template <typename TParametersValueType>
bool
WasmTransformIOTemplate<TParametersValueType>::CanWriteFile(const char * name)
{
std::string filename = name;
if (filename == "")
{
return false;
}
bool extensionFound = false;
std::string::size_type extensionPos = filename.rfind(".iwt");
if (extensionPos != std::string::npos)
{
extensionFound = true;
}
if (!extensionFound)
{
itkDebugMacro(<< "The filename extension is not recognized");
return false;
}
return true;
}
template <typename TParametersValueType>
void
WasmTransformIOTemplate<TParametersValueType>::WriteTransformInformation()
{
const std::string path = this->GetFileName();
const auto indexPath = path + "/index.json";
const auto dataPath = path + "/data";
if (!itksys::SystemTools::FileExists(path, false))
{
itksys::SystemTools::MakeDirectory(path);
}
if (!itksys::SystemTools::FileExists(dataPath, false))
{
itksys::SystemTools::MakeDirectory(dataPath);
}
auto transformListJSON = this->GetJSON();
std::string serialized{};
auto ec = glz::write<glz::opts{ .prettify = true }>(transformListJSON, serialized);
if (ec)
{
itkExceptionMacro("Failed to serialize TransformListJSON");
}
std::ofstream outputStream;
openFileForWriting(outputStream, indexPath.c_str(), true, true);
outputStream << serialized;
outputStream.close();
}
template <typename TParametersValueType>
void
WasmTransformIOTemplate<TParametersValueType>::WriteFixedParameters()
{
ConstTransformListType & transformList = this->GetWriteTransformList();
std::string compositeTransformType = transformList.front()->GetTransformTypeAsString();
CompositeTransformIOHelperTemplate<TParametersValueType> helper;
//
// if the first transform in the list is a
// composite transform, use its internal list
// instead of the IO
if (compositeTransformType.find("CompositeTransform") != std::string::npos)
{
transformList = helper.GetTransformList(transformList.front().GetPointer());
}
unsigned int count = 0;
typename ConstTransformListType::const_iterator end = transformList.end();
for (typename ConstTransformListType::const_iterator it = transformList.begin(); it != end; ++it, ++count)
{
const TransformType * currentTransform = it->GetPointer();
if (currentTransform->GetTransformTypeAsString().find("CompositeTransform") != std::string::npos)
{
continue;
}
auto fixedParams = currentTransform->GetFixedParameters();
// Fixed parameters are always double per itk::TransformBaseTemplate
const SizeValueType numberOfBytes = fixedParams.Size() * sizeof(FixedParametersValueType);
std::string path(this->GetFileName());
path = path + "/data/" + std::to_string(count);
const std::string filePath = path + "/fixed-parameters.raw";
if (!itksys::SystemTools::FileExists(path, false))
{
itksys::SystemTools::MakeDirectory(path);
}
std::ofstream outputStream;
openFileForWriting(outputStream, filePath, true, false);
outputStream.write(reinterpret_cast<const char *>(fixedParams.data_block()), numberOfBytes);
if (outputStream.tellp() != numberOfBytes)
{
itkExceptionMacro(<< "Write failed: Wanted to write " << numberOfBytes << " bytes, but wrote "
<< outputStream.tellp() << " bytes.");
}
}
}
template <typename TParametersValueType>
void
WasmTransformIOTemplate<TParametersValueType>::WriteParameters()
{
ConstTransformListType & transformList = this->GetWriteTransformList();
std::string compositeTransformType = transformList.front()->GetTransformTypeAsString();
CompositeTransformIOHelperTemplate<TParametersValueType> helper;
//
// if the first transform in the list is a
// composite transform, use its internal list
// instead of the IO
if (compositeTransformType.find("CompositeTransform") != std::string::npos)
{
transformList = helper.GetTransformList(transformList.front().GetPointer());
}
unsigned int count = 0;
typename ConstTransformListType::const_iterator end = transformList.end();
for (typename ConstTransformListType::const_iterator it = transformList.begin(); it != end; ++it, ++count)
{
const TransformType * currentTransform = it->GetPointer();
if (currentTransform->GetTransformTypeAsString().find("CompositeTransform") != std::string::npos)
{
continue;
}
auto params = currentTransform->GetParameters();
const SizeValueType numberOfBytes = params.Size() * sizeof(ParametersValueType);
std::string path(this->GetFileName());
path = path + "/data/" + std::to_string(count);
const std::string filePath = path + "/parameters.raw";
if (!itksys::SystemTools::FileExists(path, false))
{
itksys::SystemTools::MakeDirectory(path);
}
std::ofstream outputStream;
openFileForWriting(outputStream, filePath, true, false);
outputStream.write(reinterpret_cast<const char *>(params.data_block()), numberOfBytes);
if (outputStream.tellp() != numberOfBytes)
{
itkExceptionMacro(<< "Write failed: Wanted to write " << numberOfBytes << " bytes, but wrote "
<< outputStream.tellp() << " bytes.");
}
}
}
template <typename TParametersValueType>
void
WasmTransformIOTemplate<TParametersValueType>::Write()
{
if (fileNameIsCBOR(this->GetFileName()))
{
this->WriteCBOR();
return;
}
this->WriteTransformInformation();
this->WriteFixedParameters();
this->WriteParameters();
}
ITK_GCC_PRAGMA_DIAG_PUSH()
ITK_GCC_PRAGMA_DIAG(ignored "-Wattributes")
template class WebAssemblyInterface_EXPORT WasmTransformIOTemplate<double>;
template class WebAssemblyInterface_EXPORT WasmTransformIOTemplate<float>;
ITK_GCC_PRAGMA_DIAG_POP()
} // end namespace itk