# -*- coding: iso-8859-1 -*-
#
#-------------------------------------------------------------------------------
#                    Code_Saturne version 1.3
#                    ------------------------
#
#
#     This file is part of the Code_Saturne User Interface, element of the
#     Code_Saturne CFD tool.
#
#     Copyright (C) 1998-2007 EDF S.A., France
#
#     contact: saturne-support@edf.fr
#
#     The Code_Saturne User Interface 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.
#
#     The Code_Saturne User Interface 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 the Code_Saturne Kernel; if not, write to the
#     Free Software Foundation, Inc.,
#     51 Franklin St, Fifth Floor,
#     Boston, MA  02110-1301  USA
#
#-------------------------------------------------------------------------------


"""
This module initialize model dynamics variables and model scalars

This module contents the following classes:
- InitializationModel
- Multiselect
- InitializationView
- PageText
- InitializationTestCase
"""


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


import sys, string, unittest
from xml.dom.minidom import parse
import Tix
from Tkconstants import *
from math import pow


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


from Base.Common import *
import Base.Toolbox as Tool
import Base.Dialog as Dialog
import Base.TkPage as TkPage
from Turbulence import TurbulenceModel
from ThermalScalar import ThermalScalarModel
from Lagrangian import LagrangianModel
from GasCombustion import GasCombustionModel
from CoalCombustion import CoalCombustionModel
from ElectricalModels import ElectricalModel


#-------------------------------------------------------------------------------
# Multi-selection string
#-------------------------------------------------------------------------------


MULTISEL = "*****"


#-------------------------------------------------------------------------------
# Variables and Scalar model initialization modelling class
#-------------------------------------------------------------------------------


class InitializationModel:
    """
    Class for Variables and Scalar model initialization.
    """
    def __init__(self, case):
        """
        Constructor
        """
        self.case = case
	
	# TODO: the InitZoneView class !
	zone_label = "1"
	self.zone = zone_label

        models = self.case.xmlGetNode('thermophysical_models')
        self.node_veloce = models.xmlGetNode('velocity_pressure')
        self.node_turb   = models.xmlGetNode('turbulence', 'model')
        self.node_therm  = models.xmlGetNode('thermal_scalar', 'model')
# FIXME
        self.node_gas  = models.xmlGetNode('gas_combustion', 'model')
        self.node_coal = models.xmlGetNode('pulverized_coal', 'model')
        #self.node_coal = models.xmlGetNode('joule_effect', 'model')
# FIXME

        self.turb = TurbulenceModel(self.case)
        self.initialTurbulenceMode = ('values',
                                      'reference_velocity',
                                      'reference_velocity_length')


    def defaultInitialValues(self):
        """
        Return in a dictionnary which contains default values.
        """
        default = {}
        default['init_mode']  = "reference_velocity"
        default['velocity']   = 1.0
        default['length']     = -1e+12

    # pour l'initialisation de k, eps, phi, fb, omega, R11, R22, R33, 
    # on utilise  les formules standards avec Uref=1 m/s et ALMAX=1 m
    
        Uref  = float(1.)
        Almax = float(1.)
        Cmu   = 0.09
#   temp = "%.4E" %(1.5 * pow((0.02*Uref), 2))
#   print temp
#   default['turb_k']    = 1.5 * pow((0.02*Uref), 2)
#   default['turb_eps']  = pow(default['turb_k'], 1.5) / Cmu / Almax
#   default['turb_phi']  = float(2/3)
#   default['turb_fb']   = '0'
#   default['turb_omega']    = default['turb_eps'] / default['turb_k'] / Cmu
#   default['component_R11'] = pow((0.02*Uref), 2) 
#   default['component_R22'] = pow((0.02*Uref), 2)
#   default['component_R33'] = pow((0.02*Uref), 2)
#   default['component_R12'] = '0.0'
#   default['component_R23'] = '0.0'
#   default['component_R13'] = '0.0'
        default['turb_k']    = 6e-4
        default['turb_eps']  = 1.633e-4
        default['turb_phi']  = 0.6666
        default['turb_fb']   = 0
        default['turb_omega']    = 3.024
        default['component_R11'] = 0.04
        default['component_R22'] = 0.04
        default['component_R33'] = 0.04
        default['component_R12'] = 0.0
        default['component_R23'] = 0.0
        default['component_R13'] = 0.0
        default['temperature'] = 0.0
        default['pressure'] = 0.0

        return default


    def setInitialVelocity(self, var_name, var_init):
        """
        Set values for initialization of velocity.
        """
        node = self.node_veloce.xmlGetNode('variable', name=var_name)
        if not node:
            print "Error in setInitialVelocity method"
            sys.exit(1)
        if var_init:
            node.xmlInitChildNode('initial_value', zone=self.zone)
            node.xmlSetData('initial_value', var_init)
        else:
            node.xmlRemoveChild('initial_value')


    def getInitialVelocity(self):
        """
        Return values for initialization of velocity in a list.
        """
        velocity_list = []

        for var_name in ('velocity_U', 'velocity_V', 'velocity_W'):
            node = self.node_veloce.xmlGetNode('variable', name=var_name)
            if not node:
                print "Error in getInitialVelocity method"
                sys.exit(1)
            v = node.xmlGetDouble('initial_value', zone=self.zone)
            if not v: v = 0.0
            velocity_list.append(v)

        return velocity_list


    def getVelocityLabel(self):
        """
        Return the velocity users label list.
        """
        label_list = []

        for var_name in ('velocity_U', 'velocity_V', 'velocity_W'):
            node = self.node_veloce.xmlGetNode('variable', name=var_name)
            if not node: sys.exit(1)
            label_list.append(node['label'])

        return label_list


    def setInitialTurbulenceChoice(self, init_mode):
        """
        Set the initialization mode in the attribute choice.
        """
        if init_mode not in self.initialTurbulenceMode: sys.exit(1)

        node_init = self.node_turb.xmlInitNode('initialization', 'choice')
        node_init['choice'] = init_mode


    def getInitialTurbulenceChoice(self):
        """
        Return the turbulence initialization mode.
        """
        node_init = self.node_turb.xmlInitNode('initialization', 'choice')
        if not node_init: sys.exit(1)

        if node_init['choice'] not in self.initialTurbulenceMode:
            node_init['choice'] = self.defaultInitialValues()['init_mode']
            if node_init['choice'] == 'reference_velocity':
                self.getReferenceVelocity()
            elif node_init['choice'] == 'reference_velocity_length':
                self.getReferenceVelocityLength()

        return node_init['choice']


    def setReferenceVelocity(self, velocity):
        """
        Set UREF.
        """
        node_init = self.node_turb.xmlGetNode('initialization', 'choice')
        if not node_init: sys.exit(1)
        if node_init['choice'] not in \
           ('reference_velocity','reference_velocity_length'):
            sys.exit(1)

        node_init.xmlSetData('reference_velocity', velocity)


    def getReferenceVelocity(self):
        """
        Return the reference velocity.
        """
        node_init = self.node_turb.xmlGetNode('initialization',
                                                choice='reference_velocity')
        if not node_init: sys.exit(1)

        v = node_init.xmlGetDouble('reference_velocity')
        if not v:
            v = self.defaultInitialValues()['velocity']
            self.setReferenceVelocity(v)

        return v


    def setReferenceLength(self, length):
        """
        Set ALMAX.
        """
        node_init = self.node_turb.xmlGetNode('initialization',
                                                choice='reference_velocity_length')
        if not node_init: sys.exit(1)
        node_init.xmlSetData('reference_length', length)


    def getReferenceVelocityLength(self):
        """
        Return the reference velocity and length.
        """
        node_init = self.node_turb.xmlGetNode('initialization',
                                                choice='reference_velocity_length')
        if not node_init: sys.exit(1)

        v = node_init.xmlGetDouble('reference_velocity')
        l = node_init.xmlGetDouble('reference_length')
        if not v and l:
            v = self.defaultInitialValues()['velocity']
            self.setReferenceVelocity(v)
            self.setReferenceLength(l)
        elif not l and v:
            l = self.defaultInitialValues()['length']
            self.setReferenceVelocity(v)
            self.setReferenceLength(l)
        elif not v and not l:
            v = self.defaultInitialValues()['velocity']
            l = self.defaultInitialValues()['length']
            self.setReferenceVelocity(v)
            self.setReferenceLength(l)

        return v, l


    def getTurbVariableLabel(self, var_name):
        """
        Return the label of the turbulence variables.
        """
        label = Tool.dicoLabel(var_name)
        node = self.node_turb.xmlGetNode('variable', name=var_name)
        if node: label = node['label']

        return label


    def setTurbulenceInitialValue(self, var_name, var_init):
        """
        Set values for initialization of turbulence variables.
        """
        node = self.node_turb.xmlGetNode('variable', name=var_name)
        if not node:
            print "Error in setTurbulenceInitialValue method"
            sys.exit(1)
        if var_init:
            node.xmlInitNode('initial_value', zone=self.zone)
            node.xmlSetData('initial_value', var_init)
        else:
            node.xmlRemoveChild('initial_value')


    def getTurbulenceInitialValue(self, var_name):
        """
        Return values for initialization of turbulence variable.
        """
        node = self.node_turb.xmlGetNode('variable', name=var_name)
        if not node:
            print "Error in getTurbulenceInitialValue method"
            sys.exit(1)
        init = node.xmlGetDouble('initial_value', zone=self.zone)
        if not init:
            init = self.defaultInitialValues()[var_name]
            self.setTurbulenceInitialValue(var_name, init)

        return init


    def getScalarNodeList(self):
        """
        Return list of thermal scalar's nodes.
        """
        nodeList = self.node_therm.xmlGetNodeList('scalar')
        return nodeList


    def getNameThermalScalar(self, node):
        """
        Return thermal scalar node's name
        """
        return node['name']

    def getLabelInitMinMaxThScalar(self, node):
        """
        Return thermal scalar node's name, init, min and max values
        """
# FIXME: faire un method dans XMLvariable qui renvoie tout ça
        label = node['label']
        ini = node.xmlGetString('initial_value', zone=self.zone)
        min = node.xmlGetString('min_value')
        max = node.xmlGetString('max_value')

        return label, ini, min, max


    def checkModelNameLabel(self, node, model):
        """
        Return label of thermal scalar node
        """
        label = ""
        if node['name'] == model:
            label = node['label']
        return label


    def setThermalScalValues(self, node, ini, min, max):
        """
        Set initial, min and max values into thermal scalar node
        """
	node.xmlInitChildNode('initial_value', zone=self.zone)
        node.xmlSetData('initial_value', ini)
        node.xmlSetData('min_value', min)
        node.xmlSetData('max_value', max)



#-------------------------------------------------------------------------------
# Hlist multi-selection class
#-------------------------------------------------------------------------------


class MultiSelect:
    """
    This class is design in order to manage the storage
    of the selected items in the Hlist.
    """
    def __init__(self, Hlist):
        """
        Constructor
        """
        self.Hlist = Hlist


    def _initList(self):
        """
        For each mouse selection we reinitialize all lists.
        """
        self.nameL = []
        self.initL = []
        self.miniL = []
        self.maxiL = []


    def scalarInfo(self, entry):
        """
        Return info from the argument entry.
        """
        # Here we must call the tk function directly without passing in
        # Tix.py, because of a bug in tix8.1 in the Hlist.item_cget function
        #
        t = PageText()
        h = self.Hlist
        name = h.tk.call(h, 'item', 'cget', entry, 0, '-text')
        init = h.tk.call(h, 'item', 'cget', entry, 1, '-text')
        mini = h.tk.call(h, 'item', 'cget', entry, 2, '-text')
        maxi = h.tk.call(h, 'item', 'cget', entry, 3, '-text')
    

        return name, float(init), float(mini), float(maxi)


    def setItems(self, entriesL):
        """
        Store values when a new selection is done.
        """
        self._initList()

        for entry in entriesL:
            name, init, mini, maxi = self.scalarInfo(entry)
            self.nameL.append(name)
            self.initL.append(init)
            self.miniL.append(mini)
            self.maxiL.append(maxi)


    def getItems(self):
        """
        Return all the lists.
        """
        return self.nameL, self.initL, self.miniL, self.maxiL


    def widgetText(self):
        """
        Find the right texts for the widget layout.
        """
        name, init = self.nameL[0], self.initL[0]
        mini, maxi = self.miniL[0], self.maxiL[0]

        for i in self.nameL:
            if name != i: 
                name = MULTISEL

        for i in self.initL:
            if init != i: 
                init = MULTISEL

        for i in self.miniL:
            if mini != i: 
                mini = MULTISEL

        for i in self.maxiL:
            if maxi != i: 
                maxi = MULTISEL

        if init != MULTISEL: init = "%g" % (init)
        if mini != MULTISEL: mini = "%g" % (mini)
        if maxi != MULTISEL: maxi = "%g" % (maxi)

        return name, init, mini, maxi


#-------------------------------------------------------------------------------
# Variables and Scalar model initialization view class
#-------------------------------------------------------------------------------


class InitializationView(TkPage.Page):
    """
    Class to open Turbulence Page.
    """
    def _dependsPages(self, name):
        """
        Construction of the list of dependencies Pages.
        """
        self.case[name]['depends'] = ['models/turbul',
                                    'models/therma',
                                    'models/flame',
                                    'models/pucoal',
                                    'models/joule',
                                    'models/radiat']


    def _tkControlVariables(self):
        """
        Tkinter variables declaration.
        """
        self.U           = Tix.DoubleVar()
        self.V           = Tix.DoubleVar()
        self.W           = Tix.DoubleVar()
        self.choice      = Tix.StringVar()
        self.k           = Tix.DoubleVar()
        self.eps         = Tix.DoubleVar()
        self.UREF        = Tix.DoubleVar()
        self.long        = Tix.DoubleVar()
        self.R11         = Tix.DoubleVar()
        self.R12         = Tix.DoubleVar()
        self.R13         = Tix.DoubleVar()
        self.R22         = Tix.DoubleVar()
        self.R23         = Tix.DoubleVar()
        self.R33         = Tix.DoubleVar()
        self.phi         = Tix.DoubleVar()
        self.fb          = Tix.DoubleVar()
        self.omega       = Tix.DoubleVar()

        self.valini      = Tix.StringVar()
        self.valmin      = Tix.StringVar()
        self.valmax      = Tix.StringVar()


    def _pageControl(self):
        """
        Default value settings.
        """
        self.init  = InitializationModel(self.case)
        self.turb  = TurbulenceModel(self.case)
        self.therm = ThermalScalarModel(self.case)

        self.entriesNumber = 0
        self.selectedEntry = None
        self.currentEntry  = None        


    def getVelocity(self, i, txt, var, event=None):
        """
        INPUT values for initialization of velocity
        """
        self.stbar.busy()
        if self.check2.hasType(self.e[i], var):
            self.init.setInitialVelocity(txt, var.get())
        self.stbar.idle()


    def getChoice(self, event=None):
        """
        INPUT choice of method of initialization
        """
        self.stbar.busy()

        self.w1.pack_forget()
        self.w2.pack_forget()
        self.w3.pack_forget()
        self.w4.pack_forget()
        self.wvref.pack_forget()
        self.wvlref.pack_forget()

        choice  = self.choice.get()
        self.init.setInitialTurbulenceChoice(choice)
        turb_model = self.turb.getTurbulenceModel()

        if choice == 'values':
            if turb_model in ('k-epsilon', 'k-epsilon-PL'):
                self.w1.pack(side=TOP, fill=X, pady=10)
                for txt, var in [('turb_k',   self.k  ),
                                 ('turb_eps', self.eps)]:
                    v = self.init.getTurbulenceInitialValue(txt)
                    var.set(v)
            elif turb_model in ('Rij-epsilon', 'Rij-SSG'):
                self.w2.pack(side=TOP, fill=X, pady=10)
                for txt, var in [('component_R11', self.R11),
                                 ('component_R22', self.R22),
                                 ('component_R33', self.R33),
                                 ('component_R12', self.R12),
                                 ('component_R13', self.R13),
                                 ('component_R23', self.R23),
                                 ('turb_eps',      self.eps)]:
                    v = self.init.getTurbulenceInitialValue(txt)
                    var.set(v)
            elif turb_model == 'v2f-phi':
                self.w3.pack(side=TOP, fill=X, pady=10)
                for txt, var in [('turb_k',   self.k  ),
                                 ('turb_eps', self.eps),
                                 ('turb_phi', self.phi),
                                 ('turb_fb',  self.fb) ]:
                    v = self.init.getTurbulenceInitialValue(txt)
                    var.set(v)
            elif turb_model == 'k-omega-SST':
                self.w4.pack(side=TOP, fill=X, pady=10)
                for txt, var in [('turb_k',   self.k  ),
                                 ('turb_omega', self.omega)]:
                    v = self.init.getTurbulenceInitialValue(txt)
                    var.set(v)

        elif choice == 'reference_velocity':
            self.wvref.pack(side=TOP, fill=X, pady=15)
            v = self.init.getReferenceVelocity()
            self.UREF.set(v)

        elif choice == 'reference_velocity_length':
            self.wvlref.pack(side=TOP, fill=X, pady=10)
            v, l = self.init.getReferenceVelocityLength()
            self.UREF.set(v)
            self.long.set(l)

        self.stbar.idle()


    def getKeps(self, n, attr, var, event=None):
        """
        INPUT values for K-epsilon's initialization by values
        """
        self.stbar.busy()
        if self.check2.isPositive(self.Ke[n], var):
            self.init.setTurbulenceInitialValue(attr, var.get())
        self.stbar.idle()


    def getRijeps(self, i, attr, var, event=None):
        """
        INPUT values for Rij-epsilon's initialization by values
        """
        self.stbar.busy()

        if self.check2.isPositive(self.Rent[i], var):
            self.init.setTurbulenceInitialValue(attr, var.get())

    def getv2f(self, n, attr, var, event=None):
        """
        INPUT values for v2f's initialization by values
        """
        self.stbar.busy()
        if self.check2.isPositive(self.Kv[n], var):
            self.init.setTurbulenceInitialValue(attr, var.get())
        self.stbar.idle()


    def getkomega(self, n, attr, var, event=None):
        """
        INPUT values for k-omega's initialization by values
        """
        self.stbar.busy()
        if self.check2.isPositive(self.Ko[n], var):
            self.init.setTurbulenceInitialValue(attr, var.get())
        self.stbar.idle()


    def getReferenceVelocity(self, entry, event=None):
        """
        INPUT values for initialization by reference velocity or
        length and velocity of reference.
        """
        self.stbar.busy()
        if self.check2.hasType(entry, self.UREF):
            self.init.setReferenceVelocity(self.UREF.get())
        self.stbar.idle()


    def getReferenceLength(self, event=None):
        """
        INPUT values for initialization by reference length.
        """
        self.stbar.busy()
        self.check2.begin(self.lrefe)
        t = PageText()

        if self.long.get() < 0.0:
            if self.long.get() != -1e+12:
                self.stbar.set(t.MSG_POSITIV)
                self.check2.error(self.lrefe)
            else:
                self.stbar.clear()
                self.init.setReferenceLength(self.long.get())
        else:
            self.stbar.clear()
            self.init.setReferenceLength(self.long.get())

        self.stbar.idle()


    def getModelVariables(self, event=None):
        """
        Define the type of model is used.
        """
        self.stbar.busy()

#FIXME : self.namesca ne sert à rien a priori...donc a suprimer ?
        self.namesca, self.unit = self.therm.getThermalScalarLabel()
#FIXME

# FIXME
#   modeltype = self.node_gas.xmlGetAttribute('model')
#   if modeltype == 'ebu':
#       self.node_sca = self.node_gas.xmlGetNodeList('scalar')[0]
#       scal = self.node_sca.xmlGetAttribute('name')
#       self.namesca = scal
#       self.unit = "kg/kg"
#       if self.namesca == "enthalpie_melange": self.unit = "Kelvin"
# FIXME

        self.stbar.idle()



    def isFloat(self, entry, var):
        """
        Verify if the 'entry' contents a float. If not, signal an error
        and return None.
        """
        try:
            double = float(var.get())
        except:
            self.check2.error(entry)
            double = None

        return double


    def string2float(self, entry, var):
        """
        If the StringVar() 'var' associated to the 'entry', is not a 'MULTISEL',
        convert it to a float.
        """
        self.check2.begin(entry)

        # Several selections in Hlist
        #
        if self.currentEntry and len(self.currentEntry) > 1:
            if var.get() != MULTISEL:
                double = self.isFloat(entry, var)
            else:
                double = MULTISEL

        # Only one selection in Hlist
        #
        else:
            double = self.isFloat(entry, var)

        return double


    def checkInitMinMax(self, name, init, mini, maxi):
        """
        Verify the coherence between init, mini and maxi
        """
        OK = 1

        if mini > maxi:
            t = PageText()
            Dialog.ShowInfo(self.master, title=t.INFO, text=t.MSG_CLIPPING+name)

        elif init < mini or init > maxi:
            t = PageText()
            Dialog.ShowInfo(self.master, title=t.WARNING, text=t.MSG_INIT+name)
            OK = 0

        return OK


    def getValIni(self, event=None):
        """
        Define the type of model is used
        """

        if not self.valini.get(): self.valini.set('0.0')
        return self.string2float(self.ent[0], self.valini)


    def getValMin(self, event=None):
        """
        Define the type of model is used
        """

        if not self.valmin.get(): self.valmin.set(SMGRAND)
        return self.string2float(self.ent[1], self.valmin)


    def getValMax(self, event=None):
        """
        Define the type of model is used
        """

        if not self.valmax.get(): self.valmax.set(SPGRAND)
        return self.string2float(self.ent[2], self.valmax)


    def replaceHlist(self, num, name, ini, min, max):
        """
        Kill the line of tke Hlist.
        """
        self.stbar.busy()

        if self.therm.getThermalScalar() != 'off': num = 'item1'

        self.tab.hlist.item_configure(num, 0, itemtype=Tix.TEXT, text=name, style=self.style['styleVb'])
        self.tab.hlist.item_configure(num, 1, itemtype=Tix.TEXT, text=ini,  style=self.style['styleV'])
        self.tab.hlist.item_configure(num, 2, itemtype=Tix.TEXT, text=min,  style=self.style['styleV'])
        self.tab.hlist.item_configure(num, 3, itemtype=Tix.TEXT, text=max,  style=self.style['styleV'])

        self.stbar.idle()


    def insertHlist(self, name, ini, min, max):
        """
        Put on list values relative of model variables.
        """
        self.stbar.busy()

        self.entriesNumber = self.entriesNumber + 1
        num = 'item' + str(self.entriesNumber)

        self.tab.hlist.add(num,            itemtype=Tix.TEXT, text=name, style=self.style['styleVb'])
        self.tab.hlist.item_create(num, 1, itemtype=Tix.TEXT, text=ini,  style=self.style['styleV'])
        self.tab.hlist.item_create(num, 2, itemtype=Tix.TEXT, text=min,  style=self.style['styleV'])
        self.tab.hlist.item_create(num, 3, itemtype=Tix.TEXT, text=max,  style=self.style['styleV'])

        self.stbar.idle()


    def selectHlist(self, entry=None):
        """
        Browsecmd:
        Every single Clik on the Button1 of the mouse send TWO signal to the GUI
        the first one when man push the button, and the second one when the
        button gets back.
        Command:
        Every double-Click and Return send only ONE signal to the GUI.
        """

        self.selectedEntry = self.tab.hlist.info_selection()

        if not self.selectedEntry:
            self.namlab.config(state=NORMAL)
            self.namlabb.config(state=NORMAL)
            self.ent[0].config(state=NORMAL)
            self.ent[1].config(state=NORMAL)
            self.ent[2].config(state=NORMAL)

        elif self.currentEntry != self.selectedEntry:
            self.currentEntry = self.selectedEntry
            self.select.setItems(self.currentEntry)

            name, ini, min, max = self.select.widgetText()

            self.ent[0].delete(0,END)
            self.ent[0].insert(0,ini)
            self.ent[0].icursor(END)

            self.ent[1].delete(0,END)
            self.ent[1].insert(0,min)
            self.ent[1].icursor(END)

            self.ent[2].delete(0,END)
            self.ent[2].insert(0,max)
            self.ent[2].icursor(END)
            if len(self.currentEntry) >1:
                self.namesca = MULTISEL
            else:
                self.namlab.config(state=NORMAL)
                self.namlabb.config(text=name)

        else:
            name, ini, min, max = self.select.widgetText()
            self.namesca = name
            self.namlabb.config(text=name)
# FIXME
#       if self.node_gas.xmlGetAttribute('model') == 'ebu':
#           for i in range(0,3):
#               self.un[i].config(text= "kg/kg")
#               if self.namesca == "enthalpie_melange": 
#                   self.un[i].config(text= "Kelvin")
# FIXME


    def reloadHlist(self):
        """
        Destroy the contents of the Hlist, and reload the scalar data
        from the XMLdoc.
        """
        t = PageText()
        self.entriesNumber = 0

        try:
            self.tab.hlist.delete_all()
        except:
            pass

# FIXME: faire un objet dans XMLmodel qui renvoie un model thermique global

        model = self.therm.getThermalScalar()
# FIXME:
#   if self.gas.getGasCombustionModel != 'off':
#       model = self.gas.getGasCombustionModel()
# FIXME

        if model == 'off': 
            self.un[0].config(text=t.NOMODEL0, fg='blue')
            self.un[1].config(text=t.NOMODEL1, fg='blue')
            self.un[2].config(text=t.NOMODEL2, fg='blue')
            return

        nodeList = self.init.getScalarNodeList()
        for scalar in nodeList:
            if self.init.getNameThermalScalar(scalar) == model: 
                name, ini, min, max = self.init.getLabelInitMinMaxThScalar(scalar)
                if not (ini, min, max): name = ""

                # Default initialization value
                #
#              if not ini: 
#                 if   model == 'temperature_celsius':
#                     ini = TCINIT
#                 elif model == 'temperature_kelvin':
#                     ini = TKINIT
#                 elif model == 'enthalpy':
#                     ini = EHINIT

#              if not min: min = SMGRAND
#              if not max: max = SPGRAND

                self.insertHlist(name, ini, min, max)



    def ModifyList(self, event=None):
        """
        Modify previous selected entries. 
        A new node is created with
        the new specifications and the previous ChildNodes are cloned
        in order to taking into account the user's boundary condition
        if they exist.
        """
        if not self.currentEntry: return

        self.stbar.busy()

        name, ini, min, max = self.select.getItems()

        # Search of the nodes to modify

# FIXME: Initialization ??
        model = self.therm.getThermalScalar()
        if model != 'off':
            nodeList = self.init.getScalarNodeList()

    #if self.node_therm.xmlGetAttribute('model') != 'off':
    #   node_mod = self.node_therm
# FIXME
#   elif self.node_gas.xmlGetAttribute('model') == 'ebu':
#       node_mod = self.node_gas
# FIXME

        for i in range(len(self.currentEntry)):
            entry = self.currentEntry[i]
            for node in nodeList:
                # Modify the node's properties one by one
                #if self.dicoLabel(node['name']) == name[i]:
                if self.init.checkModelNameLabel(node, model) == name[i]:
                    self.setEditedValueHlist(node, entry, name[i], ini[i], min[i], max[i])

        self.selectHlist()

        self.stbar.idle()



    def setEditedValueHlist(self, node, entry, old_name, old_init, 
                             old_mini, old_maxi):
        """
        Checking consistency of values and interpreting
        complexe entry for reference if necessary.
        """
        # Get back data from entries
        #

        new_name = old_name
        new_init = self.getValIni()
        new_mini = self.getValMin() 
        new_maxi = self.getValMax()

        # Verify if everything is OK
        #
        if new_name == old_name and \
               new_init != None and \
               new_mini != None and new_maxi != None:

            if new_init == MULTISEL: new_init = old_init
            if new_mini == MULTISEL: new_mini = old_mini
            if new_maxi == MULTISEL: new_maxi = old_maxi
            if new_name == MULTISEL: new_name = old_name

            if self.checkInitMinMax(old_name, new_init, new_mini, new_maxi): 

                # Update the Hlist
                #
                self.replaceHlist(entry, new_name, new_init, new_mini, new_maxi)
                # we set values in xml file                                   
                self.init.setThermalScalValues(node, new_init, new_mini, new_maxi)
            else:
                labl, ini, min, max = self.init.getLabelInitMinMaxThScalar(node)
                self.valini.set(ini)
                self.valmin.set(min)
                self.valmax.set(max)

        self.stbar.idle()


    def _make_style(self):
        """
        Define beautiful style in order to display columns in teh Hlist
        """
        self.style={}

        self.style['header'] = Tix.DisplayStyle(Tix.TEXT,
                                                refwindow=self.ftab,
                                                justify=CENTER,
                                                anchor=CENTER,
                                                padx=5, pady=2, font=fB)
       
        self.style['styleV'] = Tix.DisplayStyle(Tix.TEXT,
                                                refwindow=self.ftab,
                                                anchor=CENTER,
                                                padx=5, fg='brown', font=fN)

        self.style['styleVb'] = Tix.DisplayStyle(Tix.TEXT,
                                                 refwindow=self.ftab,
                                                 anchor=CENTER,
                                                 padx=5, fg='brown', font=fB)

                
    def selectHlistAll(self):
        """
        Fonction for the Popup Menu.
        Select everything in the Hlist.
        """
        self.reloadHlist()

        first = 'item' + str(1)
        last  = 'item' + str(self.entriesNumber)
        self.tab.hlist.selection_set(first, last)
        self.currentEntry = None
        self.selectHlist()


    def cancelSelection(self):
        """
        Fonction for the Popup Menu.
        Blank the selection.
        """
        self.tab.hlist.selection_clear()
        self.eraseEntries()
        self.currentEntry = None
        self.selectHlist()


    def eraseEntries(self, event=None):
        """
        Delete all caracters in the entries.
        """
        t = PageText()
        self.namlabb.config(state=NORMAL)
        self.ent[0].delete(0, END)
        self.ent[1].delete(0, END)
        self.ent[2].delete(0, END)


    def _createWidgets(self):
        """
        Create the Page layout.
        """
        t = PageText()

        # NoteBook and tabs layout
        #
        nb = Tix.NoteBook(self.myPage)
        nb.pack(expand=1, side=TOP, fill=BOTH)
    
        nb.nbframe.config(background=self.bg, backpagecolor=self.bg)
        nb.nbframe.config(focuscolor=self.bg,
                            inactivebackground=wm['inactivebackground'])
        nb.nbframe.config(relief=RAISED)
        nb.nbframe.config(font=fT, tabpadx='10', tabpady='2')
        nb.add('page1', anchor='center', label=t.VARIABLE_TITLE)
        nb.add('page2', anchor='center', label=t.SCALAR_TITLE)


        ########################################################
        # NoteBook Page 1
        ########################################################
        
        # Velocity
        #
        l  = [0]*3
        self.e  = [0]*3

        f1 = Tix.LabelFrame(nb.page1, label=t.VELOCITY, relief=FLAT)
        f1.label.config(font=fT)
        f1.pack(side=TOP, fill=X, padx=10, pady=10, ipady=5)

        for (i, attr, var) in [(0, 'velocity_U', self.U),
                               (1, 'velocity_V', self.V),
                               (2, 'velocity_W', self.W)]:
            l[i] = Tix.Label(f1.frame, text=self.init.getVelocityLabel()[i])
            l[i].grid(row=i, column=0, padx=2, pady=5, sticky=W)

            self.e[i] = Tix.Entry(f1.frame, width=10, textvariable=var)
            self.e[i].grid(row=i, column=1, padx=3, pady=5)
            self.e[i].event_add("<<Event>>", "<Return>", "<Leave>", "<FocusOut>")
            self.e[i].bind("<<Event>>",TkPage.Callback(self.getVelocity, i, attr, var))

            Tix.Label(f1.frame, text="m/s").grid(row=i, column=2, pady=5, sticky=E)

        # Turbulence
        #
        self.f2 = Tix.LabelFrame(nb.page1, label=t.TURBULENCE, relief=FLAT)
        self.f2.label.config(font=fT)
        self.f2.pack(side=TOP, fill=X, padx=10, pady=10)

        w1 = Tix.Frame(self.f2.frame, relief=FLAT)
        w1.pack(side=TOP, fill=X)

        self.c = Tix.OptionMenu(w1)
        self.c.menubutton.config(width=45, bd=2, relief=RAISED)
        self.c.grid(row=0, column=1, padx=10, pady=15)

        self.c.add_command('values', label=t.INI_VAL)
        self.c.add_command('reference_velocity', label=t.INI_REF)
        self.c.add_command('reference_velocity_length', label=t.INI_VetLREF)
        self.c.config(variable=self.choice, command=self.getChoice)

        # Separator
        #
        Tix.Frame(self.f2.frame, height=2, bd=2, relief=SUNKEN).pack(side=TOP, fill=X)

        # Initialization by values for k-eps
        #
        self.w1 = Tix.Frame(self.f2.frame ,relief=FLAT)
        self.w1.pack(side=TOP, fill=X, pady=10)

        self.Ke = [0]*2
        for (n, attr, var, unit) in [(0, 'turb_k',  self.k,   'm2/s2'),
                                     (1, 'turb_eps', self.eps,'m2/s3')]:
            Tix.Label(self.w1, text=self.init.getTurbVariableLabel(attr))\
            .grid(row=n+1, column=0, padx=2, pady=5, sticky=W)

            self.Ke[n] = Tix.Entry(self.w1, width=10, textvariable=var)
            self.Ke[n].grid(row=n+1, column=1, padx=3, pady=5)
            self.Ke[n].event_add("<<Event>>", "<Return>", "<Leave>", "<FocusOut>")
            self.Ke[n].bind("<<Event>>",TkPage.Callback(self.getKeps, n, attr, var))

            Tix.Label(self.w1, text=unit).grid(row=n+1, column=2, padx=3, pady=5, sticky=E)

        # Initialization by values for Rij-eps
        #
        self.w2 = Tix.Frame(self.f2.frame, relief=FLAT)
        self.w2.pack(side=TOP, fill=X, pady=10)

        Tix.Label(self.w2, text=t.REYNOLDS_STRESS).grid(row=0, column=0, columnspan=4, pady=5, sticky=W)

        self.Rent = [0]*7
        for (j, r, c, txt, attr, var, unit) in [(0, 1, 0, 'R11', 'component_R11', self.R11, 'm2/s2'),
                                                (1, 2, 0, 'R22', 'component_R22', self.R22, 'm2/s2'),
                                                (2, 3, 0, 'R33', 'component_R33', self.R33, 'm2/s2'),
                                                (3, 1, 4, 'R12', 'component_R12', self.R12, 'm2/s2'),
                                                (4, 2, 4, 'R13', 'component_R13', self.R13, 'm2/s2'),
                                                (5, 3, 4, 'R23', 'component_R23', self.R23, 'm2/s2')]:
            tt = self.init.getTurbVariableLabel(attr)
            Tix.Label(self.w2, text=tt).grid(row=r, column=1+c, padx=2, pady=5)

            self.Rent[j] = Tix.Entry(self.w2, width=10, textvariable=var)
            self.Rent[j].grid(row=r, column=2+c, padx=3, pady=5)
            self.Rent[j].event_add("<<Event>>", "<Return>", "<Leave>", "<FocusOut>")
            self.Rent[j].bind("<<Event>>",TkPage.Callback(self.getRijeps, j, attr, var))

            Tix.Label(self.w2, text=unit).grid(row=r, column=3+c, pady=5, sticky=W)

        #Tix.Label(self.w2, text=t.DISSIP).grid(row=4, column=0, columnspan=3, padx=2, pady=5)
        tt = self.init.getTurbVariableLabel('turb_eps')
        Tix.Label(self.w2, text=tt).grid(row=4, column=0, columnspan=3, padx=2, pady=5)
        self.Rent[6] = Tix.Entry(self.w2, width=10, textvariable=self.eps)
        self.Rent[6].grid(row=4, column=3, padx=3, pady=5)
        self.Rent[6].event_add("<<Event>>", "<Return>", "<Leave>", "<FocusOut>")
        self.Rent[6].bind("<<Event>>", TkPage.Callback(self.getRijeps, 6, 'turb_eps', self.eps))
        Tix.Label(self.w2, text='m2/s3').grid(row=4, column=5, pady=5, sticky=W)

        # Initialization by values for v2f
        #
        self.Kv = [0]*4
        self.w3 = Tix.Frame(self.f2.frame, relief=FLAT)
        self.w3.pack(side=TOP, fill=X, pady=10)

        for (n, r, c, attr, var, unit) in [(0, 1, 0, 'turb_k',   self.k,   'm2/s2'),
                       (1, 2, 0, 'turb_eps', self.eps, 'm2/s3'),
                       (2, 1, 4, 'turb_phi', self.phi, ''),
                       (3, 2, 4, 'turb_fb',  self.fb,  '1/s')]:
            Tix.Label(self.w3, text=self.init.getTurbVariableLabel(attr))\
            .grid(row=r, column=1+c, padx=10, pady=5, sticky=W)

            self.Kv[n] = Tix.Entry(self.w3, width=10, textvariable=var)
            self.Kv[n].grid(row=r, column=2+c, padx=3, pady=5)
            self.Kv[n].event_add("<<Event>>", "<Return>", "<Leave>", "<FocusOut>")
            self.Kv[n].bind("<<Event>>",TkPage.Callback(self.getv2f, n, attr, var))

            Tix.Label(self.w3, text=unit).grid(row=r, column=3+c, padx=10, pady=5, sticky=W)

        # Initialization by values for k-omega
        #
        self.Ko = [0]*2
        self.w4 = Tix.Frame(self.f2.frame, relief=FLAT)
        self.w4.pack(side=TOP, fill=X, pady=10)

        for (n, attr, var, unit) in [(0, 'turb_k',    self.k,    'm2/s2'),
                                     (1, 'turb_omega',self.omega,'1/s')]:
            Tix.Label(self.w4, text=self.init.getTurbVariableLabel(attr))\
            .grid(row=n, column=0, padx=2, pady=5, sticky=W)

            self.Ko[n] = Tix.Entry(self.w4, width=10, textvariable=var)
            self.Ko[n].grid(row=n, column=1, padx=3, pady=5)
            self.Ko[n].event_add("<<Event>>", "<Return>", "<Leave>", "<FocusOut>")
            self.Ko[n].bind("<<Event>>",TkPage.Callback(self.getkomega, n, attr, var))

            Tix.Label(self.w4, text=unit).grid(row=n, column=3, padx=10, pady=5, sticky=W)

        # Initialization by reference velocity for k-eps or Rij-eps
        #
        self.wvref = Tix.Frame(self.f2.frame, relief=FLAT)
        self.wvref.pack(side=TOP, fill=X, pady=15)

        Tix.Label(self.wvref, text=t.VITREF).grid(row=1, column=0, padx=3)

        self.vrefe = Tix.Entry(self.wvref, width=10, textvariable=self.UREF)
        self.vrefe.grid(row=1 ,column=1, padx=3)
        self.vrefe.event_add("<<Event>>", "<Return>", "<Leave>", "<FocusOut>")
        self.vrefe.bind("<<Event>>", TkPage.Callback(self.getReferenceVelocity, self.vrefe))
        self.balloon.bind_widget(self.vrefe,balloonmsg=t.KEYWORD+'UREF')

        Tix.Label(self.wvref, text='m/s').grid(row=1, column=2, padx=3, sticky=W)

        # Initialization by reference velocity and reference length for k-eps or Rij-eps
        #
        self.wvlref = Tix.Frame(self.f2.frame, relief=FLAT)
        self.wvlref.pack(side=TOP, fill=X, pady=10)

        l1 = Tix.Label(self.wvlref, text=t.VITREF)
        l1.grid(row=1, column=0, padx=2, pady=5, sticky=W)

        self.vrefe2 = Tix.Entry(self.wvlref, width=10, textvariable=self.UREF)
        self.vrefe2.grid(row=1, column=1, padx=3, pady=5)
        self.vrefe2.event_add("<<Event>>", "<Return>", "<Leave>", "<FocusOut>")
        self.vrefe2.bind("<<Event>>", TkPage.Callback(self.getReferenceVelocity, self.vrefe2))

        self.balloon.bind_widget(l1,balloonmsg=t.KEYWORD+'UREF')
        self.balloon.bind_widget(self.vrefe2,balloonmsg=t.KEYWORD+'UREF')

        Tix.Label(self.wvlref, text='m/s').grid(row=1, column=2, padx=3, sticky=W)
    
        l2 = Tix.Label(self.wvlref, text=t.LONGREF)
        l2.grid(row=2, column=0, padx=2, pady=5, sticky=W)

        self.lrefe = Tix.Entry(self.wvlref, width=10, textvariable=self.long)
        self.lrefe.grid(row=2, column=1, padx=3, pady=5)
        self.lrefe.event_add("<<Event>>", "<Return>", "<Leave>", "<FocusOut>")
        self.lrefe.bind("<<Event>>", self.getReferenceLength)

        self.balloon.bind_widget(l2,balloonmsg=t.KEYWORD+'ALMAX')
        self.balloon.bind_widget(self.lrefe,balloonmsg=t.KEYWORD+'ALMAX')

        Tix.Label(self.wvlref, text='m').grid(row=2, column=2, padx=3, sticky=W)



        ########################################################
        # NoteBook Page 2 - Scalars page
        ########################################################

        self.ftab = Tix.Frame(nb.page2, relief=FLAT)
        self.ftab.pack(side=TOP, fill=X)

        self.tab = Tix.ScrolledHList(self.ftab, options='hlist.columns 5 hlist.header 1')
        self.tab.config(scrollbar="auto +y +x")

        self.tab.hlist.config(selectmode='extended',
                                browsecmd=self.selectHlist,
                                bg=wm['hlistbackground'])
        self.tab.hsb.config(width=10, bd=1)
        self.tab.vsb.config(width=10, bd=1)
        self.tab.pack(expand=1, padx=10, pady=10, side=TOP)

        self.balloon.bind_widget(self.tab.hlist, statusmsg=t.MSG_HLIST)

        #  labels of colums
        #
        self._make_style()

        self.tab.hlist.header_create(0, itemtype=Tix.TEXT, text=t.NAME, style=self.style['header'])
        self.tab.hlist.header_create(1, itemtype=Tix.TEXT, text=t.VALINI, style=self.style['header'])
        self.tab.hlist.header_create(2, itemtype=Tix.TEXT, text=t.VALMIN, style=self.style['header'])
        self.tab.hlist.header_create(3, itemtype=Tix.TEXT, text=t.VALMAX, style=self.style['header'])

        self.tab.hlist.column_width(4,0)

        # Let configure the appearance of the Hlist subwidget 
        #
        self.tab.hlist.config(width=52, height=11)

        self.tab.hlist.column_width(0, chars=14)
        self.tab.hlist.column_width(1, chars=14)
        self.tab.hlist.column_width(2, chars=12)
        self.tab.hlist.column_width(3, chars=12)

        # Create the mouse selection instance
        #
        self.select = MultiSelect(self.tab.hlist)

        # Popup Menu
        #
        pm = Tix.PopupMenu(self.tab.hlist, title=t.POPUP, state=NORMAL)
        pm.bind_widget(self.tab.hlist)
        pm.menu.add_separator()
        pm.menu.add_command(label=t.SELECT_ALL, command=self.selectHlistAll)
        pm.menu.add_command(label=t.UNSELECT, command=self.cancelSelection)
        pm.menu.m1 = Tix.Menu(pm.menu)


        # widgets for label of model scalar
        #
        f4 = Tix.LabelFrame(nb.page2, label=t.SCALARS, relief=FLAT)
        f4.label.config(font=fT)
        f4.pack(side=TOP, fill=X, padx=10, pady=10)

        self.wn1 = Tix.Frame(f4.frame, relief=FLAT)
        self.wn1.pack(side=TOP, fill=X, padx=10, pady=10)

        self.namlab = Tix.Label(self.wn1, text=t.NAMESCA)
        self.namlab.grid(row=0, column=0)

        namfen = Tix.Frame(self.wn1, bd=2)
        namfen.grid(row=0, column=1)

        self.namlabb = Tix.Label(namfen, width=12, bg='lightblue')
        self.namlabb.pack()

        self.getModelVariables()

        # widgets for entry of variables
        #
        self.lb  = [0]*3
        self.ent = [0]*3
        self.un  = [0]*3

        for (i, lab, var, cmd, tx, wi) in \
            [(0, t.VALINI, self.valini, self.getValIni, '',       12),
             (1, t.MINSCA, self.valmin, self.getValMin, 'SCAMIN', 12),
             (2, t.MAXSCA, self.valmax, self.getValMax, 'SCAMAX', 12)]:

            self.lb[i] = Tix.Label(self.wn1, text=lab)
            self.lb[i].grid(row=i+1, column=0, padx=0, pady=2, sticky=E)

            self.ent[i] = Tix.Entry(self.wn1, bd=2, width=wi, textvariable=var)
            self.ent[i].grid(row=i+1, column=1, padx=5, pady=2, sticky=W)
    
            if i == 1 or i ==2 :
                self.balloon.bind_widget(self.lb[i],  balloonmsg=t.KEYWORD+tx)
                self.balloon.bind_widget(self.ent[i], balloonmsg=t.KEYWORD+tx)

            self.un[i] = Tix.Label(self.wn1, text=self.unit)
            self.un[i].grid(row=i+1, column=2, padx=0, sticky=W)

        utd = Tix.Button(self.wn1, text=t.MODIFY, underline=0, width=10,
                        command=self.ModifyList)
        utd.grid(row=2,column=3,padx=15)


    def _initializeWidgets(self):
        """
        Extract resquested informations from XML document.
        This informations are used to initialize the widgets.
        For this page default values of all widgets are necessary
        included in the XML file.
        Method used in the Popup Menu to.
        """
        # Velocity initialization
        #
        velocity_list = self.init.getInitialVelocity()
        for i, var in [(0, self.U), (1, self.V), (2, self.W)]:
            var.set(velocity_list[i])

        # Initialisation of Turbulence
        #
        turb_model = self.turb.getTurbulenceModel()

        if turb_model not in ('k-epsilon',   'k-epsilon-PL',
                              'Rij-epsilon', 'Rij-SSG',
                              'v2f-phi',     'k-omega-SST'):
            self.f2.pack_forget()
        else:
            self.f2.pack(side=TOP, fill=X, padx=10, pady=10)

            # Select the initialization's choice
            #
            choice = self.init.getInitialTurbulenceChoice()
            self.c.config(value=choice)

            if choice == 'reference_velocity':
                v = self.init.getReferenceVelocity()
                self.UREF.set(v)

            elif choice == 'reference_velocity_length':
                v,l = self.init.getReferenceVelocityLength()
                self.UREF.set(v)
                self.long.set(l)

            elif choice == 'values':

                if turb_model in ('k-epsilon', 'k-epsilon-PL'):
                    for txt, var in [('turb_k',   self.k  ),
                                     ('turb_eps', self.eps)]:
                        v = self.init.getTurbulenceInitialValue(txt)
                        var.set(v)

                elif turb_model in ('Rij-epsilon', 'Rij-epsilon-SSG'):
                    for txt, var in [('component_R11', self.R11),
                                     ('component_R22', self.R22),
                                     ('component_R33', self.R33),
                                     ('component_R12', self.R12),
                                     ('component_R13', self.R13),
                                     ('component_R23', self.R23),
                                     ('turb_eps',      self.eps)]:
                        v = self.init.getTurbulenceInitialValue(txt)
                        var.set(v)
                elif turb_model == 'v2f-phi':
                    for txt, var in [('turb_k',   self.k  ),
                                     ('turb_eps', self.eps),
                                     ('turb_phi', self.phi),
                                     ('turb_fb',  self.fb)  ]:
                        v = self.init.getTurbulenceInitialValue(txt)
                        var.set(v)
                elif turb_model == 'k-omega-SST':
                    for txt, var in [('turb_k',     self.k  ),
                                     ('turb_omega', self.omega)]:
                        v = self.init.getTurbulenceInitialValue(txt)
                        var.set(v)

        # Initialisation of Model Variables if thermal model is selectionned
        #
        self.entriesNumber = 0
        self.reloadHlist()


#-------------------------------------------------------------------------------
# Text and messages for this page
#-------------------------------------------------------------------------------


class PageText:
    """
    Storage of all texts and messages for this page.
    """
    def __init__(self):
        
        # 1) Texts
        #
        if Tool.GuiParam.lang == 'fr':
            self.CREATE          = "Créer"
            self.DISSIP          = "Dissipation turbulente"
            self.ENTHAL_MEL      = "Enthalpie de mélange"
            self.ERASE           = "Effacer"
            self.FRAC_MASS       = "Fraction massique"
            self.FRAC_MEL        = "Fraction de mélange"
            self.INFO            = "Information"
            self.INI_REF         = "Initialisation par vitesse de référence"
            self.INI_VAL         = "Initialisation par valeurs"
            self.INI_VetLREF     = "Initialisation par vitesse et longueur de référence"
            self.KEYWORD         = "Mot clé Code_Saturne : "
            self.LONGREF         = "Longueur de référence"
            self.MAXSCA          = "Valeur\nmaximale"
            self.MINSCA          = "Valeur\nminimale"
            self.MODIFY          = "Modifier"
            self.NAME            = "Nom du\nscalaire"
            self.NAMESCA         = "Nom du scalaire"
            self.NOMODEL0        = "AUCUN"
            self.NOMODEL1        = "MODELE"
            self.NOMODEL2        = "DEFINI"
            self.OUTLET          = "sortie"
            self.POPUP           = "Menu popup"
            self.REYNOLDS_STRESS = "Contraintes de Reynolds :"
            self.SCALAR_TITLE    = "SCALAIRES MODELE"
            self.SCALARS         = "Initialisation des scalaires modèle"
            self.SELECT_ALL      = "Tout sélectionner"
            self.SELECT_TYPE     = "Sélection par type"
            self.SORT_OUT        = "Trier par"
            self.SYMMETRY        = "symétrie"
            self.TITLE           = "Définition des zones frontières"
            self.TURBULENCE      = "Initialisation de la turbulence"
            self.TYPE            = "Type"
            self.UNDEFINED       = "indéfini"
            self.UNIT_SCA        = "Unité du scalaire"
            self.UNITY           = "Unité"
            self.UNSELECT        = "Désélectionner"
            self.VALINI          = "Valeur\ninitiale"
            self.VALMAX          = "Max"
            self.VALMIN          = "Min"
            self.VARIABLE_TITLE  = "VARIABLES DYNAMIQUES"
            self.VELOCITY        = "Initialisation de la vitesse"
            self.VITREF          = "Vitesse de référence"
            self.WARNING         = "Attention"
        else:
            self.CREATE          = "Create"
            self.DISSIP          = "Turbulent dissipation"
            self.ENTHAL_MEL      = "Mixing enthalpy"
            self.ERASE           = "Delete"
            self.FRAC_MASS       = "Mass ratio"
            self.FRAC_MEL        = "Mixing_ratio"
            self.INFO            = "Information"
            self.INI_REF         = "Initialization by reference velocity"
            self.INI_VAL         = "Initialization by values"
            self.INI_VetLREF     = "Initialization by reference velocity and reference length"
            self.KEYWORD         = "Code_Saturne key word: "
            self.LONGREF         = "Reference length"
            self.MAXSCA          = "Maximal\nvalue"
            self.MINSCA          = "Minimal\nvalue"
            self.MODIFY          = "Modify"
            self.NAME            = "Scalar\nname"
            self.NAMESCA         = "Scalar name"
            self.NOMODEL0        = "NO"
            self.NOMODEL1        = "MODEL"
            self.NOMODEL2        = "DEFINED"
            self.OUTLET          = "outlet"
            self.POPUP           = "Menu popup"
            self.REYNOLDS_STRESS = "Reynolds stress components:"
            self.SCALAR_TITLE    = "MODEL'S SCALARS"
            self.SCALARS         = "Model's scalars initialization"
            self.SELECT_ALL      = "Select all"
            self.SELECT_TYPE     = "Selection by type"
            self.SORT_OUT        = "Sort out by"
            self.SYMMETRY        = "symmetry"
            self.TITLE           = "Define boundary regions"
            self.TURBULENCE      = "Turbulence initialization"
            self.TYPE            = "Type"
            self.UNDEFINED       = "undefined"
            self.UNIT_SCA        = "Unity of scalar"
            self.UNITY           = "Unity"
            self.UNSELECT        = "Unselect"
            self.MODIFY          = "Modify"
            self.VALINI          = "Initial\nvalue"
            self.VALMAX          = "Max"
            self.VALMIN          = "Min"
            self.VARIABLE_TITLE  = "DYNAMICS VARIABLES"
            self.VELOCITY        = "Velocity initialization"
            self.VITREF          = "Reference velocity"
            self.WARNING         = "Warning"

        # 2) Messages
        #
        if Tool.GuiParam.lang == 'fr':
            self.MSG_CLIPPING = "La valeur minimale est supérieure à la valeur "\
                                "maximale. Il n'y aura donc pas de clipping "\
                                "pour le scalaire :\n\n"
            self.MSG_ERR_VIT  = "Votre fichier xml a été 'trafiqué'"
            self.MSG_HLIST    = "Cliquer le bouton droit pour "       +\
                               "le menu contextuel."
            self.MSG_INIT     = "La valeur initial doit être comprise entre les "\
                                "valeurs minimale et maximale du scalaire :\n\n"
            self.MSG_POSITIV  = "LA SEULE VALEUR NEGATIVE PERMISE EST  : -1e+12"
        else:
            self.MSG_CLIPPING = "The minimal value is greater than the maximal "\
                                "value. Therefore it will be no clipping for the "\
                                "scalar named:\n\n"
            self.MSG_ERR_VIT  = "Your xmlfile has been corrupted"
            self.MSG_HLIST    = "Click right button for popup menu."
            self.MSG_INIT     = "The initial value must be set between the "\
                                "minimal and the maximal value of the scalar "\
                                "named:\n\n"
            self.MSG_POSITIV  = "THE ONLY AUTHORIZED NEGATIVE VALUE IS : -1e+12"



#-------------------------------------------------------------------------------
# InitializationModel test case
#-------------------------------------------------------------------------------


class InitializationTestCase(unittest.TestCase):
    """
    """
    def setUp(self):
        """This method is executed before all "check" methods."""
        from Base.XMLengine import Case, XMLDocument
        from Base.XMLinitialize import XMLinit
        Tool.GuiParam.lang = 'en'
        self.case = Case()
        XMLinit(self.case)
        self.doc = XMLDocument()

    def tearDown(self):
        """This method is executed after all "check" methods."""
        del self.case
        del self.doc

    def xmlNodeFromString(self, string):
        """Private method to return a xml node from string"""
        return self.doc.parseString(string).root()

    def checkInitializationInstantiation(self):
        """Check whether the InitializationModel class could be instantiated."""
        model = None
        model = InitializationModel(self.case)
        assert model != None, 'Could not instantiate InitializationModel'

    def checkSetInitialVelocity(self):
        """Check whether the velocity initial value could be set."""
        mdl = InitializationModel(self.case)
        mdl.node_veloce.xmlRemoveChild('initialization')

        for var_name, label in [('velocity_U', 'U'),
                                ('velocity_V', 'V'),
                                ('velocity_W', 'W'),
                                ('pressure', 'P')]:
            node = mdl.node_veloce.xmlGetNode('variable', name=var_name)
            node['label'] = label

        mdl.setInitialVelocity('velocity_U', 123)
        mdl.setInitialVelocity('velocity_V', 1.e+2)
        mdl.setInitialVelocity('velocity_W', 0)
        doc = '<velocity_pressure>'\
                 '<variable label="U" name="velocity_U">'\
                   '<initial_value zone="1">123</initial_value>'\
                 '</variable>'\
                 '<variable label="V" name="velocity_V">'\
                   '<initial_value zone="1">100</initial_value>'\
                 '</variable>'\
                 '<variable label="W" name="velocity_W"/>'\
                 '<property label="total_pressure" name="total_pressure"/>'\
                 '<variable label="P" name="pressure"/>'\
              '</velocity_pressure>'
        assert mdl.node_veloce == self.xmlNodeFromString(doc), \
          'Could not set the velocity initial values'

        assert mdl.getInitialVelocity() == [123.0, 100.0, 0.0], \
          'Could not get the initial velocity values'

        assert mdl.getVelocityLabel() == ['U', 'V', 'W'], \
          'Could not get the velocity variable label'

    def checkSetTurbulenceInitializationChoice(self):
        """Check whether the velocity initial value choice could be set."""
        mdl = InitializationModel(self.case)
        mdl.turb.setTurbulenceModel('k-epsilon')
        mdl.node_turb.xmlRemoveChild('variable')
        mdl.node_turb.xmlRemoveChild('property')
        mdl.setInitialTurbulenceChoice('values')
        doc = '<turbulence model="k-epsilon">'\
                   '<initialization choice="values">'\
                      '<reference_velocity>1</reference_velocity>'\
                    '</initialization>'\
             '</turbulence>'
        assert mdl.node_turb == self.xmlNodeFromString(doc),\
           'Could not set the turbulence initialization choice'

    def checkGetTurbulenceInitializationChoice(self):
        """Check whether the velocity initial value choice could be get."""
        mdl = InitializationModel(self.case)
        mdl.turb.setTurbulenceModel('k-epsilon')
        mdl.node_turb.xmlRemoveChild('variable')
        mdl.node_turb.xmlRemoveChild('property')
        choice = mdl.getInitialTurbulenceChoice()
        default = mdl.defaultInitialValues()['init_mode']
        assert  choice == default, \
            'Could not get the turbulence default initialization choice'

        mdl.setInitialTurbulenceChoice('values')
        choice = mdl.getInitialTurbulenceChoice()
        assert  choice == 'values', \
            'Could not get the turbulence initialization choice'

    def checkSetReferenceVelocity(self):
        """Check whether the reference velocity could be set."""
        mdl = InitializationModel(self.case)
        mdl.turb.setTurbulenceModel('k-epsilon')
        mdl.node_turb.xmlRemoveChild('variable')
        mdl.node_turb.xmlRemoveChild('property')
        mdl.setInitialTurbulenceChoice('reference_velocity')
        mdl.setReferenceVelocity(123e-2)

        truc = mdl.node_turb.toString()

        doc = '<turbulence model="k-epsilon">'\
                 '<initialization choice="reference_velocity">'\
                    '<reference_velocity>1.23</reference_velocity>'\
                 '</initialization>'\
              '</turbulence>'
        assert doc == truc, 'Could not set the reference velocity'

    def checkGetReferenceVelocity(self):
        """Check whether the reference velocity could be get."""
        mdl = InitializationModel(self.case)
        mdl.turb.setTurbulenceModel('k-epsilon')
        mdl.node_turb.xmlRemoveChild('variable')
        mdl.node_turb.xmlRemoveChild('property')
        mdl.setInitialTurbulenceChoice('reference_velocity')
        default = mdl.defaultInitialValues()['velocity']
        assert mdl.getReferenceVelocity() == default, \
            'Could not get the default turbulence velocity scale'

        v = 456e-2
        mdl.setReferenceVelocity(v)
        assert mdl.getReferenceVelocity() == v,\
            'Could not get the reference velocity scale'

    def checkSetReferenceVelocityLength(self):
        """Check whether the reference velocity and length could be set."""
        mdl = InitializationModel(self.case)
        mdl.turb.setTurbulenceModel('k-epsilon')
        mdl.node_turb.xmlRemoveChild('variable')
        mdl.node_turb.xmlRemoveChild('property')
        mdl.setInitialTurbulenceChoice('reference_velocity_length')
        mdl.setReferenceVelocity(123e-2)
        mdl.setReferenceLength(456e-3)

        truc = mdl.node_turb.toString()
        doc = '<turbulence model="k-epsilon">'\
                 '<initialization choice="reference_velocity_length">'\
                   '<reference_velocity>1.23</reference_velocity>'\
                   '<reference_length>0.456</reference_length>'\
                 '</initialization>'\
              '</turbulence>'
        assert doc == truc, 'Could not set the reference velocity and length'

    def checkGetReferenceVelocityLength(self):
        """Check whether the reference velocity and length could be get."""
        mdl = InitializationModel(self.case)
        mdl.turb.setTurbulenceModel('k-epsilon')
        mdl.node_turb.xmlRemoveChild('variable')
        mdl.node_turb.xmlRemoveChild('property')
        mdl.setInitialTurbulenceChoice('reference_velocity_length')
        v_default = mdl.defaultInitialValues()['velocity']
        l_default = mdl.defaultInitialValues()['length']
        v, l = mdl.getReferenceVelocityLength()
        assert (v, l) == (v_default, l_default),\
           'Could not get the default reference velocity and length scale'

        set_v, set_l = 123e-2, 456e-3
        mdl.setReferenceVelocity(set_v)
        mdl.setReferenceLength(set_l)
        v, l = mdl.getReferenceVelocityLength()
        assert (v, l) == (set_v, set_l),\
            'Could not get the reference velocity and length scale'

    def checkSetTurbulenceInitialValue(self):
        """Check whether the turbulence variable initial value could be set."""
        mdl = InitializationModel(self.case)
        mdl.turb.setTurbulenceModel('k-epsilon')
        mdl.node_turb.xmlRemoveChild('property')
        mdl.node_turb.xmlRemoveChild('initialization')
        for var_name, value in [('turb_k', 123e-5),
                                ('turb_eps', 3e-6)]:
            mdl.setTurbulenceInitialValue(var_name, value)

        truc = mdl.node_turb.toString()

        doc = '<turbulence model="k-epsilon">'\
                  '<variable label="TurbEner" name="turb_k">'\
                      '<initial_value zone="1">0.00123</initial_value>'\
                  '</variable>'\
                  '<variable label="Dissip" name="turb_eps">'\
                      '<initial_value zone="1">3e-06</initial_value>'\
                  '</variable>'\
              '</turbulence>'
        assert doc == truc, 'Could not set the turbulence variable initial value'

        value = []
        for var_name in ('turb_k', 'turb_eps'):
            value.append( mdl.getTurbulenceInitialValue(var_name) )

        assert value == [0.00123, 3e-06], \
            'Could not get the turbulence variable initial value'

        assert mdl.getTurbVariableLabel('turb_k') == "TurbEner", \
            'Could not get the turbulence variable label'

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

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

#-------------------------------------------------------------------------------
# End
#-------------------------------------------------------------------------------


syntax highlighted by Code2HTML, v. 0.9.1