/
vtkSlicerTerminologiesModuleLogic.cxx
2192 lines (1951 loc) · 91.8 KB
/
vtkSlicerTerminologiesModuleLogic.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
994
995
996
997
998
999
1000
/*==============================================================================
Program: 3D Slicer
Copyright (c) Laboratory for Percutaneous Surgery (PerkLab)
Queen's University, Kingston, ON, Canada. All Rights Reserved.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
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.
This file was originally developed by Csaba Pinter, PerkLab, Queen's University
and was supported through the Applied Cancer Research Unit program of Cancer Care
Ontario with funds provided by the Ontario Ministry of Health and Long-Term Care
==============================================================================*/
// Terminologies includes
#include "vtkSlicerTerminologiesModuleLogic.h"
#include "vtkSlicerTerminologyEntry.h"
#include "vtkSlicerTerminologyCategory.h"
#include "vtkSlicerTerminologyType.h"
// MRMLLogic includes
#include <vtkMRMLScene.h>
// Slicer includes
#include "vtkLoggingMacros.h"
// VTK includes
#include <vtkNew.h>
#include <vtkSmartPointer.h>
#include <vtkObjectFactory.h>
#include <vtkStringArray.h>
#include <vtkVariant.h>
#include <vtksys/SystemTools.hxx>
#include <vtkDirectory.h>
// STD includes
#include <algorithm>
#include "rapidjson/document.h" // rapidjson's DOM-style API
#include "rapidjson/prettywriter.h" // for stringify JSON
#include "rapidjson/filereadstream.h"
static rapidjson::Value JSON_EMPTY_VALUE;
static std::string ANATOMIC_CONTEXT_SCHEMA = "https://raw.githubusercontent.com/qiicr/dcmqi/master/doc/anatomic-context-schema.json#";
static std::string ANATOMIC_CONTEXT_SCHEMA_1 = "https://raw.githubusercontent.com/qiicr/dcmqi/master/doc/schemas/anatomic-context-schema.json#";
static std::string TERMINOLOGY_CONTEXT_SCHEMA = "https://raw.githubusercontent.com/qiicr/dcmqi/master/doc/segment-context-schema.json#";
static std::string TERMINOLOGY_CONTEXT_SCHEMA_1 = "https://raw.githubusercontent.com/qiicr/dcmqi/master/doc/schemas/segment-context-schema.json#";
//----------------------------------------------------------------------------
vtkStandardNewMacro(vtkSlicerTerminologiesModuleLogic);
//---------------------------------------------------------------------------
class vtkSlicerTerminologiesModuleLogic::vtkInternal
{
public:
// rapidjson document object cannot be stored in an STL map (there are build errors
// on Linux and Mac), therefore we store a simple pointer and create/delete
// the document object manually
typedef std::map<std::string, rapidjson::Document* > TerminologyMap;
vtkInternal();
~vtkInternal();
/// Utility function to get code in Json array
/// \param foundIndex Output parameter for index of found object in input array. -1 if not found
/// \return Json object if found, otherwise null Json object
rapidjson::Value& GetCodeInArray(CodeIdentifier codeId, rapidjson::Value& jsonArray, int &foundIndex);
/// Get root Json value for the terminology with given name
rapidjson::Value& GetTerminologyRootByName(std::string terminologyName);
/// Get category array Json value for a given terminology
/// \return Null Json value on failure, the array object otherwise
rapidjson::Value& GetCategoryArrayInTerminology(std::string terminologyName);
/// Get category Json object from terminology with given category name
/// \return Null Json value on failure, the category Json object otherwise
rapidjson::Value& GetCategoryInTerminology(std::string terminologyName, CodeIdentifier categoryId);
/// Populate \sa vtkSlicerTerminologyCategory from Json terminology
bool PopulateTerminologyCategoryFromJson(rapidjson::Value& categoryObject, vtkSlicerTerminologyCategory* category);
/// Get type array Json value for a given terminology and category
/// \return Null Json value on failure, the array object otherwise
rapidjson::Value& GetTypeArrayInTerminologyCategory(std::string terminologyName, CodeIdentifier categoryId);
/// Get type Json object from a terminology category with given type name
/// \return Null Json value on failure, the type Json object otherwise
rapidjson::Value& GetTypeInTerminologyCategory(std::string terminologyName, CodeIdentifier categoryId, CodeIdentifier typeId);
/// Populate \sa vtkSlicerTerminologyType from Json terminology
bool PopulateTerminologyTypeFromJson(rapidjson::Value& typeObject, vtkSlicerTerminologyType* type);
/// Get type modifier array Json value for a given terminology, category, and type
/// \return Null Json value on failure, the array object otherwise
rapidjson::Value& GetTypeModifierArrayInTerminologyType(std::string terminologyName, CodeIdentifier categoryId, CodeIdentifier typeId);
/// Get type modifier Json object from a terminology, category, and type with given modifier name
/// \return Null Json value on failure, the type Json object otherwise
rapidjson::Value& GetTypeModifierInTerminologyType(std::string terminologyName, CodeIdentifier categoryId, CodeIdentifier typeId, CodeIdentifier modifierId);
/// Get root Json value for the anatomic context with given name
rapidjson::Value& GetAnatomicContextRootByName(std::string anatomicContextName);
/// Get region array Json value for a given anatomic context
/// \return Null Json value on failure, the array object otherwise
rapidjson::Value& GetRegionArrayInAnatomicContext(std::string anatomicContextName);
/// Get type Json object from an anatomic context with given region name
/// \return Null Json value on failure, the type Json object otherwise
rapidjson::Value& GetRegionInAnatomicContext(std::string anatomicContextName, CodeIdentifier regionId);
/// Populate \sa vtkSlicerTerminologyType from Json anatomic region
bool PopulateRegionFromJson(rapidjson::Value& anatomicRegionObject, vtkSlicerTerminologyType* region);
/// Get region modifier array Json value for a given anatomic context and region
/// \return Null Json value on failure, the array object otherwise
rapidjson::Value& GetRegionModifierArrayInRegion(std::string anatomicContextName, CodeIdentifier regionId);
/// Get type modifier Json object from an anatomic context and region with given modifier name
/// \return Null Json value on failure, the type Json object otherwise
rapidjson::Value& GetRegionModifierInRegion(std::string anatomicContextName, CodeIdentifier regionId, CodeIdentifier modifierId);
/// Convert a segmentation descriptor Json structure to a terminology context one
/// \param descriptorDoc Input segmentation descriptor json document
/// \param convertedDoc Output terminology context json document
/// \return Success flag
bool ConvertSegmentationDescriptorToTerminologyContext(rapidjson::Document& descriptorDoc, rapidjson::Document& convertedDoc, std::string contextName);
/// Convert a segmentation descriptor Json structure to an anatomic context one
/// \param descriptorDoc Input segmentation descriptor json document
/// \param convertedDoc Output anatomic context json document
/// \return Success flag
bool ConvertSegmentationDescriptorToAnatomicContext(rapidjson::Document& descriptorDoc, rapidjson::Document& convertedDoc, std::string contextName);
/// Copy basic identifier members from an identifier object into a Json object
/// Note: Allocator specifies the owner of the created object, so it is important to set the allocator
/// of the document where the object will be added
/// \param code Json object into which the code information is added a members
void GetJsonCodeFromIdentifier(rapidjson::Value& code, CodeIdentifier identifier, rapidjson::Document::AllocatorType& allocator);
/// Utility function for safe (memory-leak-free) setting of a document pointer in map
static void SetDocumentInTerminologyMap(TerminologyMap& terminologyMap, const std::string& name, rapidjson::Document* doc)
{
if (terminologyMap.find(name) != terminologyMap.end())
{
if (doc == terminologyMap[name])
{
// The two objects are the same, there is nothing to do
return;
}
// Make sure the previous document object is deleted
delete terminologyMap[name];
}
// Set new document object
terminologyMap[name] = doc;
}
public:
/// Loaded terminologies. Key is the context name, value is the root item.
TerminologyMap LoadedTerminologies;
/// Loaded anatomical region contexts. Key is the context name, value is the root item.
TerminologyMap LoadedAnatomicContexts;
};
//---------------------------------------------------------------------------
// vtkInternal methods
//---------------------------------------------------------------------------
vtkSlicerTerminologiesModuleLogic::vtkInternal::vtkInternal()
= default;
//---------------------------------------------------------------------------
vtkSlicerTerminologiesModuleLogic::vtkInternal::~vtkInternal()
{
for (TerminologyMap::iterator termIt = this->LoadedTerminologies.begin();
termIt != this->LoadedTerminologies.end(); ++termIt)
{
delete termIt->second;
}
for (TerminologyMap::iterator anIt = this->LoadedAnatomicContexts.begin();
anIt != this->LoadedAnatomicContexts.end(); ++anIt)
{
delete anIt->second;
}
}
//---------------------------------------------------------------------------
rapidjson::Value& vtkSlicerTerminologiesModuleLogic::vtkInternal::GetCodeInArray(CodeIdentifier codeId, rapidjson::Value &jsonArray, int &foundIndex)
{
if (!jsonArray.IsArray())
{
return JSON_EMPTY_VALUE;
}
// Traverse array and try to find the object with given identifier
rapidjson::SizeType index = 0;
while (index<jsonArray.Size())
{
rapidjson::Value& currentObject = jsonArray[index];
if (currentObject.IsObject())
{
rapidjson::Value& codingSchemeDesignator = currentObject["CodingSchemeDesignator"];
rapidjson::Value& codeValue = currentObject["CodeValue"];
if ( codingSchemeDesignator.IsString() && !codeId.CodingSchemeDesignator.compare(codingSchemeDesignator.GetString())
&& codeValue.IsString() && !codeId.CodeValue.compare(codeValue.GetString()) )
{
foundIndex = index;
return currentObject;
}
}
++index;
}
// Not found
foundIndex = -1;
return JSON_EMPTY_VALUE;
}
//---------------------------------------------------------------------------
rapidjson::Value& vtkSlicerTerminologiesModuleLogic::vtkInternal::GetTerminologyRootByName(std::string terminologyName)
{
TerminologyMap::iterator termIt = this->LoadedTerminologies.find(terminologyName);
if (termIt != this->LoadedTerminologies.end() && termIt->second != nullptr)
{
return *(termIt->second);
}
return JSON_EMPTY_VALUE;
}
//---------------------------------------------------------------------------
rapidjson::Value& vtkSlicerTerminologiesModuleLogic::vtkInternal::GetCategoryArrayInTerminology(std::string terminologyName)
{
if (terminologyName.empty())
{
return JSON_EMPTY_VALUE;
}
rapidjson::Value& root = this->GetTerminologyRootByName(terminologyName);
if (root.IsNull())
{
vtkGenericWarningMacro("GetCategoryArrayInTerminology: Failed to find terminology root for context name '" << terminologyName << "'");
return JSON_EMPTY_VALUE;
}
rapidjson::Value& segmentationCodes = root["SegmentationCodes"];
if (segmentationCodes.IsNull())
{
vtkGenericWarningMacro("GetCategoryArrayInTerminology: Failed to find SegmentationCodes member in terminology '" << terminologyName << "'");
return JSON_EMPTY_VALUE;
}
rapidjson::Value& categoryArray = segmentationCodes["Category"];
if (!categoryArray.IsArray())
{
vtkGenericWarningMacro("GetCategoryArrayInTerminology: Failed to find Category array member in terminology '" << terminologyName << "'");
return JSON_EMPTY_VALUE;
}
return categoryArray;
}
//---------------------------------------------------------------------------
rapidjson::Value& vtkSlicerTerminologiesModuleLogic::vtkInternal::GetCategoryInTerminology(std::string terminologyName, CodeIdentifier categoryId)
{
if (categoryId.CodingSchemeDesignator.empty() || categoryId.CodeValue.empty())
{
return JSON_EMPTY_VALUE;
}
rapidjson::Value& categoryArray = this->GetCategoryArrayInTerminology(terminologyName);
if (categoryArray.IsNull())
{
vtkGenericWarningMacro("GetCategoryInTerminology: Failed to find category array in terminology '" << terminologyName << "'");
return JSON_EMPTY_VALUE;
}
int index = -1;
return this->GetCodeInArray(categoryId, categoryArray, index);
}
//---------------------------------------------------------------------------
bool vtkSlicerTerminologiesModuleLogic::vtkInternal::PopulateTerminologyCategoryFromJson(
rapidjson::Value& categoryObject, vtkSlicerTerminologyCategory* category)
{
if (!categoryObject.IsObject() || !category)
{
return false;
}
rapidjson::Value::MemberIterator codeMeaning = categoryObject.FindMember("CodeMeaning"); // e.g. "Tissue" (mandatory)
rapidjson::Value::MemberIterator codingScheme = categoryObject.FindMember("CodingSchemeDesignator"); // e.g. "SRT" (mandatory)
rapidjson::Value::MemberIterator SNOMEDCTConceptID = categoryObject.FindMember("SNOMEDCTConceptID"); // e.g. "85756007"
rapidjson::Value::MemberIterator UMLSConceptUID = categoryObject.FindMember("UMLSConceptUID"); // e.g. "C0040300"
rapidjson::Value::MemberIterator cid = categoryObject.FindMember("cid"); // e.g. "7051"
rapidjson::Value::MemberIterator codeValue = categoryObject.FindMember("CodeValue"); // e.g. "T-D0050" (mandatory)
rapidjson::Value::MemberIterator contextGroupName = categoryObject.FindMember("contextGroupName"); // e.g. "Segmentation Property Categories"
rapidjson::Value::MemberIterator showAnatomy = categoryObject.FindMember("showAnatomy");
if (codingScheme == categoryObject.MemberEnd() || codeValue == categoryObject.MemberEnd() || codeMeaning == categoryObject.MemberEnd())
{
vtkGenericWarningMacro("PopulateTerminologyCategoryFromJson: Unable to access mandatory category member");
return false;
}
category->SetCodeMeaning(codeMeaning->value.GetString());
category->SetCodingSchemeDesignator(codingScheme->value.GetString());
category->SetSNOMEDCTConceptID(SNOMEDCTConceptID != categoryObject.MemberEnd() ? SNOMEDCTConceptID->value.GetString() : nullptr);
category->SetUMLSConceptUID(UMLSConceptUID != categoryObject.MemberEnd() ? UMLSConceptUID->value.GetString() : nullptr);
category->SetCid(cid != categoryObject.MemberEnd() ? cid->value.GetString() : nullptr);
category->SetCodeValue(codeValue->value.GetString());
category->SetContextGroupName(contextGroupName != categoryObject.MemberEnd() ? contextGroupName->value.GetString() : nullptr);
if (showAnatomy == categoryObject.MemberEnd())
{
category->SetShowAnatomy(true); // Default
}
else
{
if (showAnatomy->value.IsString())
{
std::string showAnatomyStr = showAnatomy->value.GetString();
std::transform(showAnatomyStr.begin(), showAnatomyStr.end(), showAnatomyStr.begin(), ::tolower); // Make it lowercase for case-insensitive comparison
category->SetShowAnatomy( showAnatomyStr.compare("true") ? false : true );
}
else if (showAnatomy->value.IsBool())
{
category->SetShowAnatomy(showAnatomy->value.GetBool());
}
else
{
category->SetShowAnatomy(true); // Default
}
}
return true;
}
//---------------------------------------------------------------------------
rapidjson::Value& vtkSlicerTerminologiesModuleLogic::vtkInternal::GetTypeArrayInTerminologyCategory(std::string terminologyName, CodeIdentifier categoryId)
{
if (categoryId.CodingSchemeDesignator.empty() || categoryId.CodeValue.empty())
{
return JSON_EMPTY_VALUE;
}
rapidjson::Value& categoryObject = this->GetCategoryInTerminology(terminologyName, categoryId);
if (categoryObject.IsNull())
{
vtkGenericWarningMacro("GetTypeArrayInTerminologyCategory: Failed to find category '" << categoryId.CodeMeaning << "' in terminology '" << terminologyName << "'");
return JSON_EMPTY_VALUE;
}
rapidjson::Value& typeArray = categoryObject["Type"];
if (!typeArray.IsArray())
{
vtkGenericWarningMacro("GetTypeArrayInTerminologyCategory: Failed to find Type array member in category '"
<< categoryId.CodeMeaning << "' in terminology '" << terminologyName << "'");
return JSON_EMPTY_VALUE;
}
return typeArray;
}
//---------------------------------------------------------------------------
rapidjson::Value& vtkSlicerTerminologiesModuleLogic::vtkInternal::GetTypeInTerminologyCategory(
std::string terminologyName, CodeIdentifier categoryId, CodeIdentifier typeId)
{
if (typeId.CodingSchemeDesignator.empty() || typeId.CodeValue.empty())
{
return JSON_EMPTY_VALUE;
}
rapidjson::Value& typeArray = this->GetTypeArrayInTerminologyCategory(terminologyName, categoryId);
if (typeArray.IsNull())
{
vtkGenericWarningMacro("GetTypeInTerminologyCategory: Failed to find type array for category '"
<< categoryId.CodeMeaning << "' in terminology '" << terminologyName << "'");
return JSON_EMPTY_VALUE;
}
int index = -1;
return this->GetCodeInArray(typeId, typeArray, index);
}
//---------------------------------------------------------------------------
bool vtkSlicerTerminologiesModuleLogic::vtkInternal::PopulateTerminologyTypeFromJson(rapidjson::Value& typeObject, vtkSlicerTerminologyType* type)
{
if (!typeObject.IsObject() || !type)
{
return false;
}
rapidjson::Value::MemberIterator recommendedDisplayRGBValue = typeObject.FindMember("recommendedDisplayRGBValue");
// e.g. "Artery" (mandatory)
rapidjson::Value::MemberIterator codeMeaning = typeObject.FindMember("CodeMeaning");
// e.g. "SRT" (mandatory)
rapidjson::Value::MemberIterator codingScheme = typeObject.FindMember("CodingSchemeDesignator");
// e.g. "artery"
rapidjson::Value::MemberIterator slicerLabel = typeObject.FindMember("3dSlicerLabel");
// e.g. "85756007"
rapidjson::Value::MemberIterator SNOMEDCTConceptID = typeObject.FindMember("SNOMEDCTConceptID");
// e.g. "C0040300"
rapidjson::Value::MemberIterator UMLSConceptUID = typeObject.FindMember("UMLSConceptUID");
// e.g. "7051"
rapidjson::Value::MemberIterator cid = typeObject.FindMember("cid");
// e.g. "T-D0050" (mandatory)
rapidjson::Value::MemberIterator codeValue = typeObject.FindMember("CodeValue");
// e.g. "Segmentation Property Categories"
rapidjson::Value::MemberIterator contextGroupName = typeObject.FindMember("contextGroupName");
// Modifier array, containing modifiers of this type, e.g. "Left"
rapidjson::Value::MemberIterator modifier = typeObject.FindMember("Modifier");
if (codingScheme == typeObject.MemberEnd() || codeValue == typeObject.MemberEnd() || codeMeaning == typeObject.MemberEnd())
{
vtkGenericWarningMacro("PopulateTerminologyTypeFromJson: Unable to access mandatory type member");
return false;
}
type->SetCodeMeaning(codeMeaning->value.GetString());
type->SetCodingSchemeDesignator(codingScheme->value.GetString());
type->SetSlicerLabel(slicerLabel != typeObject.MemberEnd() ? slicerLabel->value.GetString() : nullptr);
type->SetSNOMEDCTConceptID(SNOMEDCTConceptID != typeObject.MemberEnd() ? SNOMEDCTConceptID->value.GetString() : nullptr);
type->SetUMLSConceptUID(UMLSConceptUID != typeObject.MemberEnd() ? UMLSConceptUID->value.GetString() : nullptr);
type->SetCid(cid != typeObject.MemberEnd() ? cid->value.GetString() : nullptr);
type->SetCodeValue(codeValue->value.GetString());
type->SetContextGroupName(contextGroupName != typeObject.MemberEnd() ? contextGroupName->value.GetString() : nullptr);
if (recommendedDisplayRGBValue != typeObject.MemberEnd()
&& (recommendedDisplayRGBValue->value).IsArray() && (recommendedDisplayRGBValue->value).Size() == 3)
{
if (recommendedDisplayRGBValue->value[0].IsString())
{
type->SetRecommendedDisplayRGBValue( // Note: Casting directly to unsigned char fails
(unsigned char)vtkVariant(recommendedDisplayRGBValue->value[0].GetString()).ToInt(),
(unsigned char)vtkVariant(recommendedDisplayRGBValue->value[1].GetString()).ToInt(),
(unsigned char)vtkVariant(recommendedDisplayRGBValue->value[2].GetString()).ToInt());
}
else if (recommendedDisplayRGBValue->value[0].IsInt())
{
type->SetRecommendedDisplayRGBValue(
(unsigned char)recommendedDisplayRGBValue->value[0].GetInt(),
(unsigned char)recommendedDisplayRGBValue->value[1].GetInt(),
(unsigned char)recommendedDisplayRGBValue->value[2].GetInt() );
}
else
{
vtkGenericWarningMacro("PopulateTerminologyTypeFromJson: Unsupported data type for recommendedDisplayRGBValue");
}
}
else
{
type->SetRecommendedDisplayRGBValue( vtkSlicerTerminologyType::INVALID_COLOR[0],
vtkSlicerTerminologyType::INVALID_COLOR[1],
vtkSlicerTerminologyType::INVALID_COLOR[2] ); // 'Invalid' gray
}
type->SetHasModifiers((modifier->value).IsArray());
return true;
}
//---------------------------------------------------------------------------
rapidjson::Value& vtkSlicerTerminologiesModuleLogic::vtkInternal::GetTypeModifierArrayInTerminologyType(
std::string terminologyName, CodeIdentifier categoryId, CodeIdentifier typeId)
{
if (typeId.CodingSchemeDesignator.empty() || typeId.CodeValue.empty())
{
return JSON_EMPTY_VALUE;
}
rapidjson::Value& categoryObject = this->GetCategoryInTerminology(terminologyName, categoryId);
if (categoryObject.IsNull())
{
vtkGenericWarningMacro("GetTypeModifierArrayInTerminologyType: Failed to find category '" <<
categoryId.CodeMeaning << "' in terminology '" << terminologyName << "'");
return JSON_EMPTY_VALUE;
}
rapidjson::Value& typeObject = this->GetTypeInTerminologyCategory(terminologyName, categoryId, typeId);
if (typeObject.IsNull())
{
vtkGenericWarningMacro("GetTypeModifierArrayInTerminologyType: Failed to find type '" << typeId.CodeMeaning << "' in category '"
<< categoryId.CodeMeaning << "' in terminology '" << terminologyName << "'");
return JSON_EMPTY_VALUE;
}
rapidjson::Value::MemberIterator typeModifierIt = typeObject.FindMember("Modifier");
if (typeModifierIt == typeObject.MemberEnd() || !typeModifierIt->value.IsArray())
{
return JSON_EMPTY_VALUE;
}
return typeModifierIt->value;
}
//---------------------------------------------------------------------------
rapidjson::Value& vtkSlicerTerminologiesModuleLogic::vtkInternal::GetTypeModifierInTerminologyType(
std::string terminologyName, CodeIdentifier categoryId, CodeIdentifier typeId, CodeIdentifier modifierId)
{
if (modifierId.CodingSchemeDesignator.empty() || modifierId.CodeValue.empty())
{
return JSON_EMPTY_VALUE;
}
rapidjson::Value& typeModifierArray = this->GetTypeModifierArrayInTerminologyType(terminologyName, categoryId, typeId);
if (typeModifierArray.IsNull())
{
vtkGenericWarningMacro("GetTypeModifierInTerminologyType: Failed to find type modifier array for type '" << typeId.CodeMeaning << "' in category '"
<< categoryId.CodeMeaning << "' in terminology '" << terminologyName << "'");
return JSON_EMPTY_VALUE;
}
int index = -1;
return this->GetCodeInArray(modifierId, typeModifierArray, index);
}
//---------------------------------------------------------------------------
rapidjson::Value& vtkSlicerTerminologiesModuleLogic::vtkInternal::GetAnatomicContextRootByName(std::string anatomicContextName)
{
TerminologyMap::iterator anIt = this->LoadedAnatomicContexts.find(anatomicContextName);
if (anIt != this->LoadedAnatomicContexts.end() && anIt->second != nullptr)
{
return *(anIt->second);
}
return JSON_EMPTY_VALUE;
}
//---------------------------------------------------------------------------
rapidjson::Value& vtkSlicerTerminologiesModuleLogic::vtkInternal::GetRegionArrayInAnatomicContext(std::string anatomicContextName)
{
if (anatomicContextName.empty())
{
return JSON_EMPTY_VALUE;
}
rapidjson::Value& root = this->GetAnatomicContextRootByName(anatomicContextName);
if (root.IsNull())
{
vtkGenericWarningMacro("GetRegionArrayInAnatomicContext: Failed to find anatomic context root for context name '" << anatomicContextName << "'");
return JSON_EMPTY_VALUE;
}
rapidjson::Value& anatomicCodes = root["AnatomicCodes"];
if (anatomicCodes.IsNull())
{
vtkGenericWarningMacro("GetRegionArrayInAnatomicContext: Failed to find AnatomicCodes member in anatomic context '" << anatomicContextName << "'");
return JSON_EMPTY_VALUE;
}
rapidjson::Value& anatomicRegionArray = anatomicCodes["AnatomicRegion"];
if (!anatomicRegionArray.IsArray())
{
vtkGenericWarningMacro("GetRegionArrayInAnatomicContext: Failed to find AnatomicRegion array member in anatomic context '" << anatomicContextName << "'");
return JSON_EMPTY_VALUE;
}
return anatomicRegionArray;
}
//---------------------------------------------------------------------------
rapidjson::Value& vtkSlicerTerminologiesModuleLogic::vtkInternal::GetRegionInAnatomicContext(std::string anatomicContextName, CodeIdentifier regionId)
{
if (regionId.CodingSchemeDesignator.empty() || regionId.CodeValue.empty())
{
return JSON_EMPTY_VALUE;
}
rapidjson::Value& regionArray = this->GetRegionArrayInAnatomicContext(anatomicContextName);
if (regionArray.IsNull())
{
vtkGenericWarningMacro("GetRegionInAnatomicContext: Failed to find region array for anatomic context '" << anatomicContextName << "'");
return JSON_EMPTY_VALUE;
}
int index = -1;
return this->GetCodeInArray(regionId, regionArray, index);
}
//---------------------------------------------------------------------------
bool vtkSlicerTerminologiesModuleLogic::vtkInternal::PopulateRegionFromJson(rapidjson::Value& anatomicRegionObject, vtkSlicerTerminologyType* region)
{
return this->PopulateTerminologyTypeFromJson(anatomicRegionObject, region);
}
//---------------------------------------------------------------------------
rapidjson::Value& vtkSlicerTerminologiesModuleLogic::vtkInternal::GetRegionModifierArrayInRegion(std::string anatomicContextName, CodeIdentifier regionId)
{
if (regionId.CodingSchemeDesignator.empty() || regionId.CodeValue.empty())
{
return JSON_EMPTY_VALUE;
}
rapidjson::Value& regionObject = this->GetRegionInAnatomicContext(anatomicContextName, regionId);
if (regionObject.IsNull())
{
vtkGenericWarningMacro("GetRegionModifierArrayInAnatomicRegion: Failed to find region '" <<
regionId.CodeMeaning << "' in anatomic context '" << anatomicContextName << "'");
return JSON_EMPTY_VALUE;
}
rapidjson::Value& regionModifierArray = regionObject["Modifier"];
if (!regionModifierArray.IsArray())
{
vtkGenericWarningMacro("GetRegionModifierArrayInAnatomicRegion: Failed to find Modifier array member in region '" <<
regionId.CodeMeaning << "' in anatomic context '" << anatomicContextName << "'");
return JSON_EMPTY_VALUE;
}
return regionModifierArray;
}
//---------------------------------------------------------------------------
rapidjson::Value& vtkSlicerTerminologiesModuleLogic::vtkInternal::GetRegionModifierInRegion(
std::string anatomicContextName, CodeIdentifier regionId, CodeIdentifier modifierId )
{
if (modifierId.CodingSchemeDesignator.empty() || modifierId.CodeValue.empty())
{
return JSON_EMPTY_VALUE;
}
rapidjson::Value& regionModifierArray = this->GetRegionModifierArrayInRegion(anatomicContextName, regionId);
if (regionModifierArray.IsNull())
{
vtkGenericWarningMacro("GetRegionModifierInRegion: Failed to find region modifier array for region '" <<
regionId.CodeMeaning << "' in anatomic context '" << anatomicContextName << "'");
return JSON_EMPTY_VALUE;
}
int index = -1;
return this->GetCodeInArray(modifierId, regionModifierArray, index);
}
//---------------------------------------------------------------------------
bool vtkSlicerTerminologiesModuleLogic::vtkInternal::ConvertSegmentationDescriptorToTerminologyContext(
rapidjson::Document& descriptorDoc, rapidjson::Document& convertedDoc, std::string contextName )
{
if (!descriptorDoc.IsObject() || contextName.empty())
{
return false;
}
// Get segment attributes
rapidjson::Value& segmentAttributesArray = descriptorDoc["segmentAttributes"];
if (!segmentAttributesArray.IsArray())
{
vtkGenericWarningMacro("ConvertSegmentationDescriptorToTerminologyContext: Invalid segmentAttributes member");
return false;
}
rapidjson::Document::AllocatorType& allocator = convertedDoc.GetAllocator();
// Use terminology with context name if exists
rapidjson::Value segmentationCodes;
rapidjson::Value categoryArray;
if (convertedDoc.IsObject() && convertedDoc.HasMember("SegmentationCodes"))
{
segmentationCodes = convertedDoc["SegmentationCodes"];
categoryArray = segmentationCodes["Category"];
}
else
{
// If terminology was not found in the map, then initialize it and its members
convertedDoc.SetObject();
convertedDoc.AddMember("SegmentationCategoryTypeContextName", rapidjson::StringRef(contextName.c_str()), allocator);
segmentationCodes.SetObject();
categoryArray.SetArray();
}
// Parse segment attributes
bool entryAdded = false;
rapidjson::SizeType index = 0;
while (index < segmentAttributesArray.Size())
{
rapidjson::Value& segmentAttributes = segmentAttributesArray[index];
if (!segmentAttributes.IsArray())
{
++index;
continue;
}
// Note: "The reason for the inner list is that we have one single schema both for input and output. When we provide input metafile,
// we can have multiple input files, and each file can have multiple labels, that is why we need to have list of lists"
segmentAttributes = segmentAttributes[0]; // Enter "innerList"
if ( !segmentAttributes.HasMember("SegmentedPropertyCategoryCodeSequence")
|| !segmentAttributes.HasMember("SegmentedPropertyTypeCodeSequence")
|| !segmentAttributes.HasMember("recommendedDisplayRGBValue") )
{
vtkGenericWarningMacro("ConvertSegmentationDescriptorToTerminologyContext: Invalid segment terminology entry at index " << index);
++index;
continue;
}
rapidjson::Value& segmentCategory = segmentAttributes["SegmentedPropertyCategoryCodeSequence"];
rapidjson::Value& segmentType = segmentAttributes["SegmentedPropertyTypeCodeSequence"];
rapidjson::Value& segmentRecommendedDisplayRGBValue = segmentAttributes["recommendedDisplayRGBValue"];
// Get type array if category already exists, create empty otherwise
vtkSlicerTerminologiesModuleLogic::CodeIdentifier categoryId(
segmentCategory["CodingSchemeDesignator"].GetString(), segmentCategory["CodeValue"].GetString(), segmentCategory["CodeMeaning"].GetString() );
int foundCategoryIndex = -1;
rapidjson::Value category(this->GetCodeInArray(categoryId, categoryArray, foundCategoryIndex), allocator);
rapidjson::Value typeArray;
if (category.IsObject() && category.HasMember("Type"))
{
typeArray = category["Type"];
if (!typeArray.IsArray())
{
vtkGenericWarningMacro("ConvertSegmentationDescriptorToTerminologyContext: Failed to find Type array in category '" << categoryId.CodeMeaning);
++index;
continue;
}
}
else
{
// If category was not found in context, then initialize it as object and initialize empty type array
category.SetObject();
typeArray.SetArray();
}
// Get type from type array, create empty type if not found
vtkSlicerTerminologiesModuleLogic::CodeIdentifier typeId(
segmentType["CodingSchemeDesignator"].GetString(), segmentType["CodeValue"].GetString(), segmentType["CodeMeaning"].GetString() );
int foundTypeIndex = -1;
rapidjson::Value type(this->GetCodeInArray(typeId, typeArray, foundTypeIndex), allocator);
rapidjson::Value typeModifierArray;
if (type.IsObject())
{
if (type.HasMember("Modifier"))
{
typeModifierArray = type["Modifier"];
}
}
else
{
// If type was not found in category, then initialize it as object and initialize empty modifier array
type.SetObject();
typeModifierArray.SetArray();
}
// Make a copy of the recommended color array so that it's allocated using the allocator of
// convertedDoc and not descriptorDoc (which will be deleted soon after exiting this function)
if (!segmentRecommendedDisplayRGBValue.IsArray() || segmentRecommendedDisplayRGBValue.Size() != 3 || !segmentRecommendedDisplayRGBValue[0].IsInt())
{
vtkGenericWarningMacro("ConvertSegmentationDescriptorToTerminologyContext: Invalid recommended color in type '" << typeId.CodeMeaning);
++index;
continue;
}
rapidjson::Value recommendedDisplayRGBValueArray(rapidjson::kArrayType);
recommendedDisplayRGBValueArray.PushBack(segmentRecommendedDisplayRGBValue[0].GetInt(), allocator);
recommendedDisplayRGBValueArray.PushBack(segmentRecommendedDisplayRGBValue[1].GetInt(), allocator);
recommendedDisplayRGBValueArray.PushBack(segmentRecommendedDisplayRGBValue[2].GetInt(), allocator);
// Add modifier if specified in descriptor and does not yet exist in terminology
if (segmentAttributes.HasMember("SegmentedPropertyTypeModifierCodeSequence"))
{
rapidjson::Value& segmentTypeModifier = segmentAttributes["SegmentedPropertyTypeModifierCodeSequence"];
vtkSlicerTerminologiesModuleLogic::CodeIdentifier typeModifierId(
segmentTypeModifier["CodingSchemeDesignator"].GetString(),
segmentTypeModifier["CodeValue"].GetString(),
segmentTypeModifier["CodeMeaning"].GetString() );
int foundTypeModifierIndex = -1;
rapidjson::Value typeModifier(this->GetCodeInArray(typeModifierId, typeModifierArray, foundTypeModifierIndex), allocator);
// Modifier already exists, nothing to do
if (typeModifier.IsObject())
{
++index;
continue;
}
else
{
typeModifier.SetObject();
}
// Create and populate modifier
this->GetJsonCodeFromIdentifier(typeModifier, typeModifierId, allocator);
if (typeModifier.HasMember("recommendedDisplayRGBValue"))
{
typeModifier.EraseMember("recommendedDisplayRGBValue");
}
typeModifier.AddMember("recommendedDisplayRGBValue", recommendedDisplayRGBValueArray, allocator); // Add color to type modifier
// Set modifier to type
typeModifierArray.PushBack(typeModifier, allocator);
if (type.HasMember("Modifier"))
{
type.EraseMember("Modifier");
}
type.AddMember("Modifier", typeModifierArray, allocator);
}
else
{
// Add color to type if there is no modifier
if (type.HasMember("recommendedDisplayRGBValue"))
{
type.EraseMember("recommendedDisplayRGBValue");
}
type.AddMember("recommendedDisplayRGBValue", recommendedDisplayRGBValueArray, allocator);
}
// Add type if has not been added yet
this->GetJsonCodeFromIdentifier(type, typeId, allocator);
if (foundTypeIndex == -1)
{
typeArray.PushBack(type, allocator);
}
else
{
typeArray[foundTypeIndex] = type;
}
// Set type array category
if (category.HasMember("Type"))
{
category.EraseMember("Type");
}
category.AddMember("Type", typeArray, allocator);
// Add category if has not been added yet
this->GetJsonCodeFromIdentifier(category, categoryId, allocator);
if (foundCategoryIndex == -1)
{
categoryArray.PushBack(category, allocator);
}
else
{
categoryArray[foundCategoryIndex] = category;
}
entryAdded = true;
++index;
} // For all segments
// Set objects back to terminology Json object
if (entryAdded)
{
if (segmentationCodes.HasMember("Category"))
{
segmentationCodes.EraseMember("Category");
}
segmentationCodes.AddMember("Category", categoryArray, allocator);
if (convertedDoc.HasMember("SegmentationCodes"))
{
convertedDoc.EraseMember("SegmentationCodes");
}
convertedDoc.AddMember("SegmentationCodes", segmentationCodes, allocator);
return true;
}
return false;
}
//---------------------------------------------------------------------------
bool vtkSlicerTerminologiesModuleLogic::vtkInternal::ConvertSegmentationDescriptorToAnatomicContext(
rapidjson::Document& descriptorDoc, rapidjson::Document& convertedDoc, std::string contextName)
{
if (!descriptorDoc.IsObject() || contextName.empty())
{
return false;
}
// Get segment attributes
rapidjson::Value& segmentAttributesArray = descriptorDoc["segmentAttributes"];
if (!segmentAttributesArray.IsArray())
{
vtkGenericWarningMacro("ConvertSegmentationDescriptorToAnatomicContext: Invalid segmentAttributes member");
return false;
}
rapidjson::Document::AllocatorType& allocator = convertedDoc.GetAllocator();
// Use terminology with context name if exists
rapidjson::Value anatomicCodes;
rapidjson::Value regionArray;
if (convertedDoc.IsObject() && convertedDoc.HasMember("AnatomicCodes"))
{
anatomicCodes = convertedDoc["AnatomicCodes"];
regionArray = anatomicCodes["AnatomicRegion"];
}
else
{
// If anatomic context was not found in the map, then initialize it and its members
convertedDoc.SetObject();
convertedDoc.AddMember("AnatomicContextName", rapidjson::StringRef(contextName.c_str()), allocator);
anatomicCodes.SetObject();
regionArray.SetArray();
}
// Parse segment attributes
bool entryAdded = false;
rapidjson::SizeType index = 0;
while (index < segmentAttributesArray.Size())
{
rapidjson::Value& segmentAttributes = segmentAttributesArray[index];
if (!segmentAttributes.IsArray())
{
++index;
continue;
}
// Note: "The reason for the inner list is that we have one single schema both for input and output. When we provide input metafile,
// we can have multiple input files, and each file can have multiple labels, that is why we need to have list of lists"
segmentAttributes = segmentAttributes[0]; // Enter "innerList"
if (!segmentAttributes.HasMember("AnatomicRegionSequence"))
{
// Anatomic context is optional in the descriptor file
++index;
continue;
}
rapidjson::Value& segmentRegion = segmentAttributes["AnatomicRegionSequence"];
// Get region modifier array if region already exists, create empty otherwise
vtkSlicerTerminologiesModuleLogic::CodeIdentifier regionId(
segmentRegion["CodingSchemeDesignator"].GetString(), segmentRegion["CodeValue"].GetString(), segmentRegion["CodeMeaning"].GetString() );
int foundRegionIndex = -1;
rapidjson::Value region(this->GetCodeInArray(regionId, regionArray, foundRegionIndex), allocator);
rapidjson::Value regionModifierArray;
if (region.IsObject())
{
if (region.HasMember("Modifier"))
{
regionModifierArray = region["Modifier"];
}
}
else
{
// If region was not found in context, then initialize it as object and initialize empty modifier array
region.SetObject();
regionModifierArray.SetArray();
}
// Add modifier if specified in descriptor and does not yet exist in anatomic context
if (segmentAttributes.HasMember("AnatomicRegionModifierSequence"))
{
rapidjson::Value& segmentRegionModifier = segmentAttributes["AnatomicRegionModifierSequence"];
vtkSlicerTerminologiesModuleLogic::CodeIdentifier regionModifierId(
segmentRegionModifier["CodingSchemeDesignator"].GetString(),
segmentRegionModifier["CodeValue"].GetString(),
segmentRegionModifier["CodeMeaning"].GetString() );
int foundRegionModifierIndex = -1;
rapidjson::Value regionModifier(this->GetCodeInArray(regionModifierId, regionModifierArray, foundRegionModifierIndex), allocator);
// Modifier already exists, nothing to do
if (regionModifier.IsObject())
{
++index;
continue;
}
// Create and populate modifier
regionModifier.SetObject();
this->GetJsonCodeFromIdentifier(regionModifier, regionModifierId, allocator);
// Set modifier to region
regionModifierArray.PushBack(regionModifier, allocator);
if (region.HasMember("Modifier"))
{
region.EraseMember("Modifier");
}
region.AddMember("Modifier", regionModifierArray, allocator);
}
// Add region if has not been added yet, overwrite otherwise
this->GetJsonCodeFromIdentifier(region, regionId, allocator);
if (foundRegionIndex == -1)
{
regionArray.PushBack(region, allocator);
}
else
{
regionArray[foundRegionIndex] = region;
}
entryAdded = true;
++index;
}
// Set objects back to anatomic context Json object
if (entryAdded)
{
if (anatomicCodes.HasMember("AnatomicRegion"))
{
anatomicCodes.EraseMember("AnatomicRegion");
}
anatomicCodes.AddMember("AnatomicRegion", regionArray, allocator);
if (convertedDoc.HasMember("AnatomicCodes"))
{
convertedDoc.EraseMember("AnatomicCodes");
}
convertedDoc.AddMember("AnatomicCodes", anatomicCodes, allocator);
return true;
}
return false;
}
//---------------------------------------------------------------------------
void vtkSlicerTerminologiesModuleLogic::vtkInternal::GetJsonCodeFromIdentifier(
rapidjson::Value& code, CodeIdentifier identifier, rapidjson::Document::AllocatorType& allocator)
{
code.AddMember("CodingSchemeDesignator", rapidjson::Value().SetString(identifier.CodingSchemeDesignator.c_str(), allocator), allocator);
code.AddMember("CodeValue", rapidjson::Value().SetString(identifier.CodeValue.c_str(), allocator), allocator);
code.AddMember("CodeMeaning", rapidjson::Value().SetString(identifier.CodeMeaning.c_str(), allocator), allocator);
}
//---------------------------------------------------------------------------
// vtkSlicerTerminologiesModuleLogic methods
//----------------------------------------------------------------------------
vtkSlicerTerminologiesModuleLogic::vtkSlicerTerminologiesModuleLogic()
: UserContextsPath(nullptr)
{
this->Internal = new vtkInternal();
}