File: DefineUserScalarsModel.py

package info (click to toggle)
code-saturne 5.3.2%2Brepack-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 76,868 kB
  • sloc: ansic: 338,582; f90: 118,487; python: 65,227; makefile: 4,429; cpp: 3,826; xml: 3,078; sh: 1,205; lex: 170; yacc: 100
file content (1183 lines) | stat: -rw-r--r-- 46,520 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
# -*- coding: utf-8 -*-

#-------------------------------------------------------------------------------

# This file is part of Code_Saturne, a general-purpose CFD tool.
#
# Copyright (C) 1998-2018 EDF S.A.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
# Street, Fifth Floor, Boston, MA 02110-1301, USA.

#-------------------------------------------------------------------------------

"""
This module defines the 'Additional user's scalars' page.

This module defines the following classes:
- DefineUserScalarsModel
"""

#-------------------------------------------------------------------------------
# Library modules import
#-------------------------------------------------------------------------------

import unittest

#-------------------------------------------------------------------------------
# Application modules import
#-------------------------------------------------------------------------------

from code_saturne.Base.Common import *
import code_saturne.Base.Toolbox as Tool
from code_saturne.Base.XMLvariables import Variables
from code_saturne.Base.XMLvariables import Model
from code_saturne.Base.XMLmodel import XMLmodel, ModelTest

#-------------------------------------------------------------------------------
# Define User Scalars model class
#-------------------------------------------------------------------------------

class DefineUserScalarsModel(Variables, Model):
    """
    Useful methods for operation of the page.
    __method : private methods for the Model class.
    _method  : private methods for the View Class
    """
    def __init__(self, case):
        """
        Constructor
        """
        self.case = case

        self.scalar_node = self.case.xmlGetNode('additional_scalars')
        self.node_models = self.case.xmlGetNode('thermophysical_models')
        self.node_therm  = self.node_models.xmlGetNode('thermal_scalar')
        self.node_source = self.node_models.xmlGetNode('source_terms')
        self.node_bc     = self.case.xmlGetNode('boundary_conditions')
        self.node_ana    = self.case.xmlInitNode('analysis_control')
        self.node_prof   = self.node_ana.xmlInitNode('profiles')
        self.node_ava    = self.node_ana.xmlInitNode('time_averages')

    def defaultScalarValues(self):
        """Return the default values - Method also used by ThermalScalarModel"""
        default = {}
        default['scalar_label']          = "scalar"
        default['variance_label']        = "variance"
        default['coefficient_label']     = "Dscal"
        default['diffusion_coefficient'] = 1.83e-05
        default['diffusion_choice']      = 'constant'
        default['zone_id']               = 1
        from code_saturne.Pages.GroundwaterModel import GroundwaterModel
        if GroundwaterModel(self.case).getGroundwaterModel() == "groundwater":
            default['GGDH']                  = "OFF"
        else:
            default['GGDH']                  = "SGDH"
        del GroundwaterModel
        if self.getThermalScalarName():
            default['variance']          = self.getThermalScalarName()[0]
        else:
            if self.getScalarNameList():
                default['variance']          = self.getScalarNameList()[0]
            else:
                default['variance']          = "no scalar"

        return default


    def __removeScalarChildNode(self, name, tag):
        """
        Private method.
        Delete 'variance' or 'property' markup from scalar named I{name}
        """
        for node in self.scalar_node.xmlGetNodeList('variable'):
            if node['name'] == name:
                node.xmlRemoveChild(tag)


    def __deleteScalarBoundaryConditions(self, name):
        """
        Private method.
        Delete boundary conditions for scalar I{name}
        """
        for nature in ('inlet', 'outlet', 'wall'):
            for node in self.node_bc.xmlGetChildNodeList(nature):
                for n in node.xmlGetChildNodeList('scalar'):
                    if n['name'] == name:
                        n.xmlRemoveNode()


    def __defaultScalarNameAndDiffusivityLabel(self, scalar_name=None):
        """
        Private method.
        Return a default name and label for a new scalar.
        Create a default name for the associated diffusion coefficient to.
        """
        __coef = {}
        for l in self.getScalarNameList():
            __coef[l] = self.getScalarDiffusivityLabel(l)
        length = len(__coef)
        Lscal = self.defaultScalarValues()['scalar_label']
        Dscal = self.defaultScalarValues()['coefficient_label']

        # new scalar: default value for both scalar and diffusivity

        if not scalar_name:
            if length != 0:
                i = 1
                while (Dscal + str(i)) in list(__coef.values()):
                    i = i + 1
                num = str(i)
            else:
                num = str(1)
            scalar_name = Lscal + num
            __coef[scalar_name] = Dscal + num

        # existing scalar

        else:
            if scalar_name not in list(__coef.keys())or \
               (scalar_name in list(__coef.keys()) and __coef[scalar_name] == ''):

                __coef[scalar_name] = Dscal + str(length + 1)

        return scalar_name, __coef[scalar_name]


    def __defaultVarianceName(self, scalar_name=None):
        """
        Private method.
        Return a default name and label for a new variance.
        """
        __coef = {}
        for l in self.getScalarsVarianceList():
            __coef[l] = l
        length = len(__coef)
        Lscal = self.defaultScalarValues()['variance_label']

        # new scalar: default value for both scalar and diffusivity

        if not scalar_name:
            if length != 0:
                i = 1
                while (Lscal + str(i)) in list(__coef.values()):
                    i = i + 1
                num = str(i)
            else:
                num = str(1)
            scalar_name = Lscal + num
        return scalar_name


    def __updateScalarNameAndDiffusivityName(self):
        """
        Private method.
        Update suffix number for scalar name and diffusivity' name.
        """
        lst = []
        for node in self.scalar_node.xmlGetNodeList('variable'):
            nprop = node.xmlGetChildNode('property')
            if nprop:
                old_name = nprop['name']
                nprop['name'] = node['name'] + '_diffusivity'
                new_name = nprop['name']
                if old_name:
                    for no in self.case.xmlGetNodeList('formula'):
                        txt = no.xmlGetTextNode()
                        if txt != None:
                            f = txt.replace(old_name, new_name)
                            no.xmlSetTextNode(f)


    def __setScalarDiffusivity(self, scalar_name, coeff_label):
        """
        Private method.

        Input default initial value of property "diffusivity"
        for a new scalar I{scalar_name}
        """
        self.isNotInList(scalar_name, self.getScalarsVarianceList())
        self.isInList(scalar_name, self.getUserScalarNameList())

        n = self.scalar_node.xmlGetNode('variable', type='user', name=scalar_name)
        n.xmlInitChildNode('property', label=coeff_label)

        if not self.getScalarDiffusivityChoice(scalar_name):
            self.setScalarDiffusivityChoice(scalar_name, 'constant')

        if not self.getScalarDiffusivityInitialValue(scalar_name):
            ini = self.defaultScalarValues()['diffusion_coefficient']
            self.setScalarDiffusivityInitialValue(scalar_name, ini)


    def __deleteScalar(self, name):
        """
        Private method.

        Delete scalar I{name}.
        """
        node = self.scalar_node.xmlGetNode('variable', name=name)
        node.xmlRemoveNode()
        self.__deleteScalarBoundaryConditions(name)
        self.__updateScalarNameAndDiffusivityName()
        # delete scalar in profiles and time averages nodes
        for node in self.node_prof.xmlGetNodeList('profile'):
            node.xmlRemoveChild('var_prop', name=name)
        for node in self.node_ava.xmlGetNodeList('time_average'):
            node.xmlRemoveChild('var_prop', name=name)



    @Variables.noUndo
    def getThermalScalarName(self):
        """Public method.
        Return the thermal scalar name"""
        lst = []
        for node in self.node_therm.xmlGetNodeList('variable'):
            lst.append(node['name'])
        return lst


    @Variables.noUndo
    def getScalarNameList(self):
        """Public method.
        Return the User scalar name list (thermal scalar included)"""
        lst = []
        for node in self.scalar_node.xmlGetNodeList('variable'):
            lst.append(node['name'])
        return lst


    @Variables.noUndo
    def getMeteoScalarsNameList(self):
        node_list = []
        models = self.case.xmlGetNode('thermophysical_models')
        node = models.xmlGetNode('atmospheric_flows', 'model')
        if node == None:
            return

        model = node['model']
        if model != 'off':
            node_list = node.xmlGetNodeList('variable')
            list_scalar=[]
            for node_scalar in node_list:
                list_scalar.append(node_scalar['name'])
        else:
            return

        return list_scalar


    @Variables.noUndo
    def getElectricalScalarsNameList(self):
        node_list = []
        models = self.case.xmlGetNode('thermophysical_models')
        node = models.xmlGetNode('joule_effect', 'model')
        if node == None:
            return

        model = node['model']
        if model != 'off':
            node_list = node.xmlGetNodeList('variable')
            list_scalar=[]
            for node_scalar in node_list:
                list_scalar.append(node_scalar['name'])
        else:
            return

        return list_scalar


    @Variables.noUndo
    def getUserScalarNameList(self):
        """Public method.
        Return the user scalar name list (without thermal scalar).
        Method also used by UserScalarPropertiesView
        """
        lst = []
        for node in self.scalar_node.xmlGetNodeList('variable', type='user'):
            lst.append(node['name'])
        return lst


    @Variables.undoGlobal
    def setScalarBoundaries(self):
        """Public method.
        Input boundaries conditions for a scalar node. Method also used by ThermalScalarModel
        """
        from code_saturne.Pages.Boundary import Boundary

        for node in self.node_bc.xmlGetChildNodeList('inlet'):
            model = Boundary('inlet', node['name'], self.case)
            for name in self.getScalarNameList():
                model.setScalarValue(name, 'dirichlet', 0.0)

        for node in self.node_bc.xmlGetChildNodeList('outlet'):
            model = Boundary('outlet', node['name'], self.case)
            for name in self.getScalarNameList():
                model.setScalarValue(name, 'dirichlet', 0.0)


    @Variables.undoGlobal
    def addUserScalar(self, name=None):
        """Public method.
        Input a new user scalar I{name}"""

        l, c = self.__defaultScalarNameAndDiffusivityLabel(name)

        if l not in self.getScalarNameList() and l not in self.getThermalScalarName():
            self.scalar_node.xmlInitNode('variable', name=l, type="user", label=l)

            self.__setScalarDiffusivity(l, c)
            self.setScalarBoundaries()

        self.__updateScalarNameAndDiffusivityName()

        return l


    @Variables.undoGlobal
    def addVariance(self, name=None):
        """Public method.
        Input a new user scalar I{name}"""

        l= self.__defaultVarianceName(name)
        if l not in self.getScalarsVarianceList():
            self.scalar_node.xmlInitNode('variable', name=l, type="user", label=l)
            if (self.getThermalScalarName() != None) or (self.getScalarNameList() != None):
                self.setScalarVariance(l, self.defaultScalarValues()['variance'])

        self.__updateScalarNameAndDiffusivityName()

        return l


    @Variables.undoLocal
    def renameScalarLabel(self, old_name, new_name):
        """Public method.
        Modify old_name of scalar with new_name and put new name if variancy exists"""
        # fusion de cette methode avec OutputVolumicVariablesModel.setVariablesLabel
        self.isInList(old_name, self.getScalarNameList())

        name = new_name[:LABEL_LENGTH_MAX]
        if name not in self.getScalarNameList():
            for node in self.scalar_node.xmlGetNodeList('variable'):
                if node['name'] == old_name:
                    node['label'] = name
                    node['name']  = name

                if node.xmlGetString('variance') == old_name:
                    node.xmlSetData('variance', name)

        for nature in ('inlet', 'outlet', 'wall'):
            for node in self.node_bc.xmlGetChildNodeList(nature):
                for n in node.xmlGetChildNodeList('scalar'):
                    if n['name'] == old_name:
                        n['label'] = new_name
                        n['name']  = new_name

        for node in self.case.xmlGetNodeList('formula'):
            f = node.xmlGetTextNode().replace(old_name, new_name)
            node.xmlSetTextNode(f)

        node_gw = self.node_models.xmlGetNode('groundwater_model')
        if node_gw:
            for n in node_gw.xmlGetChildNodeList('scalar'):
                if n['name'] == old_name:
                    n['name']  = new_name


    @Variables.undoGlobal
    def setTurbulentFluxGlobalModel(self, TurbulenceModel):
        """Put turbulent flux model of an additional_scalar with name scalar_name"""
        lst = self.getScalarNameList() + self.getThermalScalarName()

        if TurbulenceModel not in ('Rij-epsilon', 'Rij-SSG', 'Rij-EBRSM'):
            mdl = self.defaultScalarValues()['GGDH']
            for var in lst:
                n = self.case.xmlGetNode('variable', name=var)
                n.xmlSetData('turbulent_flux_model', mdl)


    @Variables.noUndo
    def getTurbulentFluxModel(self, l):
        """
        Get turbulent flux model of an additional_scalar with name I{l}.
        """
        lst = self.getScalarNameList() + self.getThermalScalarName()
        self.isInList(l, lst)
        n = self.case.xmlGetNode('variable', name=l)
        mdl = n.xmlGetString('turbulent_flux_model')
        if not mdl:
            mdl = self.defaultScalarValues()['GGDH']
            self.setTurbulentFluxModel(l, mdl)

        return mdl


    @Variables.undoGlobal
    def setTurbulentFluxModel(self, scalar_name, TurbFlux):
        """Put turbulent flux model of an additional_scalar with name scalar_name"""
        lst = self.getScalarNameList() + self.getThermalScalarName()
        self.isInList(scalar_name, lst)

        n = self.case.xmlGetNode('variable', name=scalar_name)
        n.xmlSetData('turbulent_flux_model', TurbFlux)


    @Variables.noUndo
    def getScalarVariance(self, l):
        """
        Get variance of an additional_scalar with name I{l}.
        Method also used by UserScalarPropertiesView
        """
        self.isInList(l, self.getScalarNameList())

        return self.scalar_node.xmlGetNode('variable', name=l).xmlGetString('variance')


    @Variables.undoGlobal
    def setScalarVariance(self, scalar_name, variance_name):
        """Put variance of an additional_scalar with name scalar_name"""
        self.isInList(scalar_name, self.getUserScalarNameList())
        lst = self.getScalarNameList() + self.getThermalScalarName()
        self.isInList(variance_name, lst)

        n = self.scalar_node.xmlGetNode('variable', type='user', name=scalar_name)
        n.xmlSetData('variance', variance_name)

        self.__removeScalarChildNode(scalar_name, 'property')


    @Variables.noUndo
    def getScalarsWithVarianceList(self):
        """
        Return list of scalars which have a variance
        """
        lst = []
        for node in self.scalar_node.xmlGetNodeList('variable'):
            sca = node.xmlGetString('variance')
            if sca and sca not in lst:
                lst.append(sca)
        return lst


    @Variables.noUndo
    def getScalarsVarianceList(self):
        """
        Return list of scalars which are also a variance
        """
        lst = []
        for node in self.scalar_node.xmlGetNodeList('variable'):
            if node.xmlGetString('variance') and node['name'] not in lst:
                lst.append(node['name'])
        return lst


    @Variables.noUndo
    def getVarianceLabelFromScalarLabel(self, name):
        """
        Get the name of scalar with variancy's name: name
        """
        self.isInList(name, self.getScalarNameList())

        lab = ""
        for node in self.scalar_node.xmlGetNodeList('variable'):
            if node.xmlGetString('variance') == name:
                lab = node['name']
        return lab


    @Variables.noUndo
    def getScalarDiffusivityName(self, scalar_name):
        """
        Get name of diffusivity's property for an additional_scalar
        with name scalar_name
        """
        self.isInList(scalar_name, self.getScalarNameList())

        lab_diff = ""
        n = self.scalar_node.xmlGetNode('variable', name=scalar_name)
        n_diff = n.xmlGetChildNode('property')
        if n_diff:
            lab_diff = n_diff['name']

        return lab_diff


    @Variables.undoLocal
    def setScalarDiffusivityLabel(self, scalar_name, diff_label):
        """
        Set name of diffusivity's property for an additional_scalar
        """
        self.isInList(scalar_name, self.getScalarNameList())

        n = self.scalar_node.xmlGetNode('variable', name=scalar_name)
        n.xmlGetChildNode('property')['label'] = diff_label


    @Variables.noUndo
    def getScalarDiffusivityLabel(self, scalar_name):
        """
        Get name of diffusivity's property for an additional_scalar
        with name scalar_name
        """
        self.isInList(scalar_name, self.getScalarNameList())

        lab_diff = ""
        n = self.scalar_node.xmlGetNode('variable', name=scalar_name)
        n_diff = n.xmlGetChildNode('property')
        if n_diff:
            lab_diff = n_diff['label']

        return lab_diff


    @Variables.undoLocal
    def setScalarDiffusivityInitialValue(self, scalar_name, initial_value):
        """
        Set initial value of diffusivity's property for an additional_scalar
        with name scalar_name. Method also called by UserScalarPropertiesView.
        """
        self.isNotInList(scalar_name, self.getScalarsVarianceList())
        self.isInList(scalar_name, self.getUserScalarNameList())
        self.isFloat(initial_value)

        n = self.scalar_node.xmlGetNode('variable', name=scalar_name)
        n_diff = n.xmlInitChildNode('property')
        n_diff.xmlSetData('initial_value', initial_value)


    @Variables.noUndo
    def getScalarDiffusivityInitialValue(self, scalar_name):
        """
        Get initial value of diffusivity's property for an additional_scalar
        with name scalar_name. Method also called by UserScalarPropertiesView.
        """
        self.isNotInList(scalar_name, self.getScalarsVarianceList())
        self.isInList(scalar_name, self.getUserScalarNameList())

        n = self.scalar_node.xmlGetNode('variable', name=scalar_name)
        n_diff = n.xmlInitChildNode('property')
        diffu = n_diff.xmlGetDouble('initial_value')
        if diffu == None:
            diffu = self.defaultScalarValues()['diffusion_coefficient']
            self.setScalarDiffusivityInitialValue(scalar_name, diffu)

        return diffu


    @Variables.undoLocal
    def setScalarDiffusivityChoice(self, scalar_name, choice):
        """
        Set choice of diffusivity's property for an additional_scalar
        with name scalar_name
        """
        self.isNotInList(scalar_name, self.getScalarsVarianceList())
        self.isInList(scalar_name, self.getUserScalarNameList())
        self.isInList(choice, ('constant', 'variable'))

        n = self.scalar_node.xmlGetNode('variable', name=scalar_name)
        n_diff = n.xmlInitChildNode('property')
        n_diff['choice'] = choice


    @Variables.noUndo
    def getScalarDiffusivityChoice(self, scalar_name):
        """
        Get choice of diffusivity's property for an additional_scalar
        with name scalar_name
        """
        self.isNotInList(scalar_name, self.getScalarsVarianceList())
        self.isInList(scalar_name, self.getUserScalarNameList())

        n = self.scalar_node.xmlGetNode('variable', name=scalar_name)
        choice = n.xmlInitChildNode('property')['choice']
        if not choice:
            choice = self.defaultScalarValues()['diffusion_choice']
            self.setScalarDiffusivityChoice(scalar_name, choice)

        return choice


    @Variables.noUndo
    def getDiffFormula(self, scalar):
        """
        Return a formula for I{tag} 'density', 'molecular_viscosity',
        'specific_heat' or 'thermal_conductivity'
        """
        self.isNotInList(scalar, self.getScalarsVarianceList())
        self.isInList(scalar, self.getUserScalarNameList())
        n = self.scalar_node.xmlGetNode('variable', name = scalar)
        node = n.xmlGetNode('property')
        formula = node.xmlGetString('formula')
        if not formula:
            formula = self.getDefaultFormula(scalar)
            self.setDiffFormula(scalar, formula)
        return formula


    @Variables.noUndo
    def getDefaultFormula(self, scalar):
        """
        Return default formula
        """
        self.isNotInList(scalar, self.getScalarsVarianceList())
        self.isInList(scalar, self.getUserScalarNameList())

        name = scalar

        formula = str(name) + "_diffusivity = 1.e-5;"

        return formula


    @Variables.undoLocal
    def setDiffFormula(self, scalar, str):
        """
        Gives a formula for 'density', 'molecular_viscosity',
        'specific_heat'or 'thermal_conductivity'
        """
        self.isNotInList(scalar, self.getScalarsVarianceList())
        self.isInList(scalar, self.getUserScalarNameList())
        n = self.scalar_node.xmlGetNode('variable', name = scalar)
        node = n.xmlGetNode('property')
        node.xmlSetData('formula', str)


    @Variables.undoGlobal
    def setScalarValues(self, name, vari):
        """
        Put values to scalar with name I{name} for creating or replacing values.
        """
        l = self.getScalarNameList()
        l.append('no')
        self.isInList(vari, l)

        if vari != "no":
            self.setScalarVariance(name, vari)
        else:
            self.__removeScalarChildNode(name, 'variance')
            l, c = self.__defaultScalarNameAndDiffusivityLabel(name)
            self.__setScalarDiffusivity(l, c)

        self.__updateScalarNameAndDiffusivityName()


    @Variables.undoGlobal
    def deleteScalar(self, sname):
        """
        Public method.
        Delete scalar I{name}
        Warning: deleting a scalar may delete other scalar which are variances
        of previous deleting scalars.
        """
        self.isInList(sname, self.getScalarNameList())

        # First add the main scalar to delete
        lst = []
        lst.append(sname)

        # Then add variance scalar related to the main scalar
        for node in self.scalar_node.xmlGetNodeList('variable'):
            if node.xmlGetString('variance') == sname:
                lst.append(node['name'])

        # update scalar source term status
        if self.node_source != None:
            for node in self.node_source.xmlGetNodeList('scalar_formula'):
                if node.xmlGetString('name') == sname:
                   node.xmlRemoveNode()

        # Delete scalars in list
        for scalar in lst:
            self.__deleteScalar(scalar)

        if len(self.scalar_node.xmlGetNodeList('variable')) == 0:
            node_domain = self.case.xmlGetNode('solution_domain')
            node_vol = node_domain.xmlGetNode('volumic_conditions')
            for node in node_vol.xmlGetChildNodeList('zone'):
                node['scalar_source_term'] = 'off'

        return lst


    @Variables.undoGlobal
    def deleteThermalScalar(self, sname):
        """
        Public method.
        Delete scalar I{namel}. Called by ThermalScalarModel
        Warning: deleting a scalar may delete other scalar which are variances
        of previous deleting scalars.
        """
        self.isInList(sname, self.getThermalScalarName())

        # First add the main scalar to delete
        lst = []
        lst.append(sname)

        # Then add variance scalar related to the main scalar
        for node in self.scalar_node.xmlGetNodeList('variable'):
            if node.xmlGetString('variance') == sname:
                self.__deleteScalar(node['name'])

        # Delete scalars
        node = self.node_therm.xmlGetNode('variable', name=sname)
        node.xmlRemoveNode()
        self.__deleteScalarBoundaryConditions(sname)
        self.__updateScalarNameAndDiffusivityName()

        return lst


    @Variables.noUndo
    def getScalarTypeByName(self, scalarName):
        """
        Return type of scalar for choice of color (for view)
        """
        self.isInList(scalarName, self.getScalarNameList() + self.getThermalScalarName())
        if scalarName not in self.getScalarNameList():
            node = self.node_therm.xmlGetNode('variable', name = scalarName)
        else:
            node = self.scalar_node.xmlGetNode('variable', 'type', name = scalarName)
        Model().isInList(node['type'], ('user', 'thermal'))
        return node['type']


    @Variables.noUndo
    def getScalarType(self, scalar_name):
        """
        Return type of scalar for choice of color (for view)
        """
        self.isInList(scalar_name, self.getScalarNameList() + self.getThermalScalarName())
        if scalar_name not in self.getScalarNameList():
            node = self.node_therm.xmlGetNode('variable', name=scalar_name)
        else:
            node = self.scalar_node.xmlGetNode('variable', 'type', name=scalar_name)
        Model().isInList(node['type'], ('user', 'thermal'))
        return node['type']


    @Variables.noUndo
    def getScalarName(self, scalar_name):
        """
        Return type of scalar for choice of color (for view)
        """
        self.isInList(scalar_name, self.getScalarNameList() + self.getThermalScalarName())
        if scalar_name not in self.getScalarNameList():
            node = self.node_therm.xmlGetNode('variable', name=scalar_name)
        else:
            node = self.scalar_node.xmlGetNode('variable', name=scalar_name)
        return node['name']


    @Variables.noUndo
    def getMeteoScalarType(self, scalarName):
        """
        Return type of scalar for choice of color (for view)
        """
        self.isInList(scalarName, self.getMeteoScalarsNameList())
        models = self.case.xmlGetNode('thermophysical_models')
        node = models.xmlGetNode('atmospheric_flows', 'model')
        n = node.xmlGetNode('variable', 'type', name=scalarName)
        Model().isInList(n['type'], ('user', 'thermal', 'model'))
        return n['type']


    @Variables.noUndo
    def getElectricalScalarType(self, scalarName):
        """
        Return type of scalar for choice of color (for view)
        """
        self.isInList(scalarName, self.getElectricalScalarsNameList())
        models = self.case.xmlGetNode('thermophysical_models')
        node = models.xmlGetNode('joule_effect', 'model')
        n = node.xmlGetNode('variable', 'type', name=scalarName)
        Model().isInList(n['type'], ('user', 'thermal', 'model'))
        return n['type']


#-------------------------------------------------------------------------------
# DefineUsersScalars test case
#-------------------------------------------------------------------------------


class UserScalarTestCase(ModelTest):
    """
    Unittest.
    """
    def checkDefineUserScalarsModelInstantiation(self):
        """Check whether the DefineUserScalarsModel class could be instantiated."""
        model = None
        model = DefineUserScalarsModel(self.case)

        assert model != None, 'Could not instantiate DefineUserScalarsModel'


    def checkAddNewUserScalar(self):
        """Check whether the DefineUserScalarsModel class could add a scalar."""
        model = DefineUserScalarsModel(self.case)
        zone = '1'
        model.addUserScalar(zone, 'toto')

        doc = '''<additional_scalars>
                    <variable label="toto" name="user_1" type="user">
                            <initial_value zone_id="1">0.0 </initial_value>
                            <min_value>-1e+12</min_value>
                            <max_value>1e+12</max_value>
                            <property choice="constant" label="Dscal1" name="diffusion_coefficient_1">
                                    <initial_value>1.83e-05</initial_value>
                            </property>
                    </variable>
                </additional_scalars>'''

        assert model.scalar_node == self.xmlNodeFromString(doc),\
           'Could not add a user scalar'

    def checkRenameScalarLabel(self):
        """Check whether the DefineUserScalarsModel class could set a label."""
        model = DefineUserScalarsModel(self.case)
        zone = '1'
        model.addUserScalar(zone, 'toto')
        model.addUserScalar(zone,'titi')
        model.renameScalarLabel('titi', 'MACHIN')

        doc = '''<additional_scalars>
                    <variable label="toto" name="user_1" type="user">
                            <initial_value zone_id="1">0.0</initial_value>
                            <min_value>-1e+12</min_value>
                            <max_value>1e+12</max_value>
                            <property choice="constant" label="Dscal1" name="diffusion_coefficient_1">
                                    <initial_value>1.83e-05</initial_value>
                            </property>
                    </variable>
                    <variable label="MACHIN" name="user_2" type="user">
                            <initial_value zone_id="1">0.0</initial_value>
                            <min_value>-1e+12</min_value>
                            <max_value>1e+12</max_value>
                            <property choice="constant" label="Dscal2" name="diffusion_coefficient_2">
                                    <initial_value>1.83e-05</initial_value>
                            </property>
                    </variable>
                </additional_scalars>'''

        assert model.scalar_node == self.xmlNodeFromString(doc),\
           'Could not rename a label to one scalar'

    def checkGetThermalScalarLabel(self):
        """Check whether the DefineUserScalarsModel class could be get label of thermal scalar."""
        model = DefineUserScalarsModel(self.case)
        zone = '1'
        model.addUserScalar(zone, 'usersca1')
        from code_saturne.Pages.ThermalScalarModel import ThermalScalarModel
        ThermalScalarModel(self.case).setThermalModel('temperature_celsius')
        del ThermalScalarModel

        doc = '''<additional_scalars>
                    <variable label="usersca1" name="user_1" type="user">
                            <initial_value zone_id="1">0.0</initial_value>
                            <min_value>-1e+12</min_value>
                            <max_value>1e+12</max_value>
                            <property choice="constant" label="Dscal1" name="diffusion_coefficient_1">
                                    <initial_value>1.83e-05</initial_value>
                            </property>
                    </variable>
                    <variable label="TempC" name="temperature_celsius" type="thermal">
                            <initial_value zone_id="1">20.0</initial_value>
                            <min_value>-1e+12</min_value>
                            <max_value>1e+12</max_value>
                    </variable>
                </additional_scalars>'''

        model.renameScalarLabel("TempC", "Matemperature")

        assert model.getThermalScalarLabel() == "Matemperature",\
           'Could not get label of thermal scalar'

    def checkSetAndGetScalarInitialValue(self):
        """Check whether the DefineUserScalarsModel class could be set and get initial value."""
        model = DefineUserScalarsModel(self.case)
        zone = '1'
        model.addUserScalar(zone, 'toto')
        model.setScalarInitialValue(zone, 'toto', 0.05)

        doc = '''<additional_scalars>
                    <variable label="toto" name="user_1" type="user">
                            <initial_value zone_id="1">0.05</initial_value>
                            <min_value>-1e+12</min_value>
                            <max_value>1e+12</max_value>
                            <property choice="constant" label="Dscal1" name="diffusion_coefficient_1">
                                    <initial_value>1.83e-05</initial_value>
                            </property>
                    </variable>
                </additional_scalars>'''

        assert model.scalar_node == self.xmlNodeFromString(doc),\
            'Could not set initial value to user scalar'
        assert model.getScalarInitialValue(zone, 'toto') == 0.05,\
            'Could not get initial value to user scalar'

    def checkSetAndGetScalarMinMaxValue(self):
        """Check whether the DefineUserScalarsModel class could be set and get min and max value."""
        model = DefineUserScalarsModel(self.case)
        zone = '1'
        model.addUserScalar(zone, 'toto')
        model.addUserScalar(zone, 'titi')
        model.setScalarInitialValue(zone, 'toto', 0.05)
        model.setScalarMinValue('toto',0.01)
        model.setScalarMaxValue('titi',100.)

        doc = '''<additional_scalars>
                    <variable label="toto" name="user_1" type="user">
                            <initial_value zone_id="1">0.05</initial_value>
                            <min_value>0.01</min_value>
                            <max_value>1e+12</max_value>
                            <property choice="constant" label="Dscal1" name="diffusion_coefficient_1">
                                    <initial_value>1.83e-05</initial_value>
                            </property>
                    </variable>
                    <variable label="titi" name="user_2" type="user">
                            <initial_value zone_id="1">0.0</initial_value>
                            <min_value>-1e+12</min_value>
                            <max_value>100.</max_value>
                            <property choice="constant" label="Dscal2" name="diffusion_coefficient_2">
                                    <initial_value>1.83e-05</initial_value>
                            </property>
                    </variable>
                </additional_scalars>'''

        assert model.scalar_node == self.xmlNodeFromString(doc),\
            'Could not set minimal or maximal value to user scalar'
        assert model.getScalarMinValue('toto') == 0.01,\
            'Could not get minimal value from user scalar'
        assert model.getScalarMaxValue('titi') == 100.,\
            'Could not get maximal value from user scalar'

    def checkSetAndGetScalarVariance(self):
        """Check whether the DefineUserScalarsModel class could be set and get variance of scalar."""
        model = DefineUserScalarsModel(self.case)
        zone = '1'
        model.addUserScalar(zone, 'toto')
        model.addUserScalar(zone, 'titi')
        model.setScalarVariance('toto', 'titi')

        doc = '''<additional_scalars>
                    <variable label="toto" name="user_1" type="user">
                            <initial_value zone_id="1">0.0</initial_value>
                            <min_value>0</min_value>
                            <max_value>1e+12</max_value>
                            <variance>titi</variance>
                    </variable>
                    <variable label="titi" name="user_2" type="user">
                            <initial_value zone_id="1">0.0</initial_value>
                            <min_value>-1e+12</min_value>
                            <max_value>1e+12</max_value>
                            <property choice="constant" label="Dscal2" name="diffusion_coefficient_2">
                                    <initial_value>1.83e-05</initial_value>
                            </property>
                    </variable>
                </additional_scalars>'''

        assert model.scalar_node == self.xmlNodeFromString(doc),\
            'Could not set variance to user scalar'
        assert model.getScalarVariance('toto') == 'titi',\
            'Could not get variance of user scalar'

    def checkGetVarianceLabelFromScalarLabel(self):
        """
        Check whether the DefineUserScalarsModel class could be get label of
        the scalar which has variancy.
        """
        model = DefineUserScalarsModel(self.case)
        zone = '1'
        model.addUserScalar(zone, 'toto')
        model.addUserScalar(zone, 'titi')
        model.setScalarVariance('toto', 'titi')

        assert model.getVarianceLabelFromScalarLabel('titi') == 'toto',\
            'Could not get label of scalar whiwh has a variancy'

    def checkGetScalarDiffusivityLabel(self):
        """
        Check whether the DefineUserScalarsModel class could be get label of
        diffusivity of user scalar.
        """
        model = DefineUserScalarsModel(self.case)
        zone = '1'
        model.addUserScalar(zone, 'premier')
        model.addUserScalar(zone, 'second')

        doc = '''<additional_scalars>
                    <variable label="premier" name="user_1" type="user">
                            <initial_value zone_id="1">0.0</initial_value>
                            <min_value>0</min_value>
                            <max_value>1e+12</max_value>
                            <property choice="constant" label="Dscal1" name="diffusion_coefficient_1">
                                    <initial_value>1.83e-05</initial_value>
                            </property>
                    </variable>
                    <variable label="second" name="user_2" type="user">
                            <initial_value zone_id="1">0.0</initial_value>
                            <min_value>-1e+12</min_value>
                            <max_value>1e+12</max_value>
                            <property choice="constant" label="Dscal2" name="diffusion_coefficient_2">
                                    <initial_value>1.83e-05</initial_value>
                            </property>
                    </variable>
                </additional_scalars>'''

        assert model.getScalarDiffusivityLabel('second') == "Dscal2",\
            'Could not get label of diffusivity of one scalar'

    def checkSetandGetScalarDiffusivityInitialValue(self):
        """
        Check whether the DefineUserScalarsModel class could be set
        and get initial value of diffusivity.
        """
        model = DefineUserScalarsModel(self.case)
        zone = '1'
        model.addUserScalar(zone, 'premier')
        model.addUserScalar(zone, 'second')
        model.setScalarDiffusivityInitialValue('premier', 0.555)

        doc = '''<additional_scalars>
                    <variable label="premier" name="user_1" type="user">
                            <initial_value zone_id="1">0.0</initial_value>
                            <min_value>-1e+12</min_value>
                            <max_value>1e+12</max_value>
                            <property choice="constant" label="Dscal1" name="diffusion_coefficient_1">
                                    <initial_value>0.555</initial_value>
                            </property>
                    </variable>
                    <variable label="second" name="user_2" type="user">
                            <initial_value zone_id="1">0.0</initial_value>
                            <min_value>-1e+12</min_value>
                            <max_value>1e+12</max_value>
                            <property choice="constant" label="Dscal2" name="diffusion_coefficient_2">
                                    <initial_value>1.83e-05</initial_value>
                            </property>
                    </variable>
                </additional_scalars>'''

        assert model.scalar_node == self.xmlNodeFromString(doc),\
            'Could not set initial value of property of one user scalar'
        assert model.getScalarDiffusivityInitialValue('premier') == 0.555,\
            'Could not get initial value of property of one user scalar '

    def checkSetandGetScalarDiffusivityChoice(self):
        """Check whether the DefineUserScalarsModel class could be set and get diffusivity's choice."""
        model = DefineUserScalarsModel(self.case)
        zone = '1'
        model.addUserScalar(zone, 'premier')
        model.addUserScalar(zone, 'second')
        model.setScalarDiffusivityChoice('premier', 'variable')
        doc = '''<additional_scalars>
                    <variable label="premier" name="user_1" type="user">
                            <initial_value zone_id="1">0.0</initial_value>
                            <min_value>-1e+12</min_value>
                            <max_value>1e+12</max_value>
                            <property choice="variable" label="Dscal1" name="diffusion_coefficient_1">
                                    <initial_value>1.83e-05</initial_value>
                            </property>
                    </variable>
                    <variable label="second" name="user_2" type="user">
                            <initial_value zone_id="1">0.0</initial_value>
                            <min_value>-1e+12</min_value>
                            <max_value>1e+12</max_value>
                            <property choice="constant" label="Dscal2" name="diffusion_coefficient_2">
                                    <initial_value>1.83e-05</initial_value>
                            </property>
                    </variable>
                </additional_scalars>'''

        assert model.scalar_node == self.xmlNodeFromString(doc),\
            'Could not set choice of property of one user scalar'
        assert model.getScalarDiffusivityChoice('premier') == "variable",\
            'Could not get choice of property of one user scalar'

    def checkDeleteScalarandGetScalarType(self):
        """
        Check whether the DefineUserScalarsModel class could be
        delete a user scalar and get type of the scalar.
        """
        model = DefineUserScalarsModel(self.case)
        zone = '1'
        model.addUserScalar(zone, 'premier')

        from code_saturne.Pages.ThermalScalarModel import ThermalScalarModel
        ThermalScalarModel(self.case).setThermalModel('temperature_celsius')
        del ThermalScalarModel

        model.addUserScalar(zone, 'second')
        model.addUserScalar(zone, 'troisieme')
        model.addUserScalar(zone, 'quatrieme')

        assert model.getScalarType('premier') == 'user',\
            'Could not get type of one scalar'

        model.deleteScalar('second')

        doc = '''<additional_scalars>
                    <variable label="premier" name="user_1" type="user">
                            <initial_value zone_id="1">0.0</initial_value>
                            <min_value>-1e+12</min_value>
                            <max_value>1e+12</max_value>
                            <property choice="constant" label="Dscal1" name="diffusion_coefficient_1">
                                    <initial_value>1.83e-05</initial_value>
                            </property>
                    </variable>
                    <variable label="TempC" name="temperature_celsius" type="thermal">
                            <initial_value zone_id="1">20.0</initial_value>
                            <min_value>-1e+12</min_value>
                            <max_value>1e+12</max_value>
                    </variable>
                    <variable label="troisieme" name="user_3" type="user">
                            <initial_value zone_id="1">0.0</initial_value>
                            <min_value>-1e+12</min_value>
                            <max_value>1e+12</max_value>
                            <property choice="constant" label="Dscal4" name="diffusion_coefficient_3">
                                    <initial_value>1.83e-05</initial_value>
                            </property>
                    </variable>
                    <variable label="quatrieme" name="user_4" type="user">
                            <initial_value zone_id="1">0.0</initial_value>
                            <min_value>-1e+12</min_value>
                            <max_value>1e+12</max_value>
                            <property choice="constant" label="Dscal5" name="diffusion_coefficient_4">
                                    <initial_value>1.83e-05</initial_value>
                            </property>
                    </variable>
                </additional_scalars>'''

        assert model.scalar_node == self.xmlNodeFromString(doc),\
            'Could not delete one scalar'



def suite():
    """unittest function"""
    testSuite = unittest.makeSuite(UserScalarTestCase, "check")
    return testSuite


def runTest():
    """unittest function"""
    print("UserScalarTestTestCase")
    runner = unittest.TextTestRunner()
    runner.run(suite())


#-------------------------------------------------------------------------------
# End DefineUsersScalars
#-------------------------------------------------------------------------------