Review, update, evolutions for DFO, PSO, EOSG, IRM, MOP, SP...
__all__ = []
name = "ADAO"
-version = "9.11.0"
+version = "9.12.0"
year = "2023"
-date = "lundi 22 mai 2023, 22:22:22 (UTC+0100)"
+date = "mardi 12 décembre 2023, 22:22:22 (UTC+0100)"
longname = name + ", a module for Data Assimilation and Optimization"
cata = "V" + version.replace(".","_")
.. [WikipediaND] Wikipedia, *Nondimensionalization*, https://en.wikipedia.org/wiki/Nondimensionalization
+.. [WikipediaNM] Wikipedia, *Nelder–Mead method*, https://en.wikipedia.org/wiki/Nelder%E2%80%93Mead_method
+
.. [WikipediaPSO] Wikipedia, *Particle Swarm Optimization*, https://en.wikipedia.org/wiki/Particle_swarm_optimization
.. [WikipediaQR] Wikipedia, *Quantile regression*, https://en.wikipedia.org/wiki/Quantile_regression
#. :ref:`Examples with the "ExtendedBlue" algorithm<section_ref_algorithm_ExtendedBlue_examples>`
#. :ref:`Examples with the "KalmanFilter" algorithm<section_ref_algorithm_KalmanFilter_examples>`
#. :ref:`Examples with the "NonLinearLeastSquares" algorithm<section_ref_algorithm_NonLinearLeastSquares_examples>`
+#. :ref:`Examples with the "ParticleSwarmOptimization" algorithm<section_ref_algorithm_ParticleSwarmOptimization_examples>`
Checking algorithms uses
------------------------
- [Powell07]_
- [Powell09]_
- [Rowan90]_
+- [WikipediaNM]_
.. ------------------------------------ ..
.. include:: snippets/Header2Algo01.rst
-This algorithm allows to generate a set of results, of simulation or
+This algorithm allows to generate a set of physical results, of simulation or
observation type, using the :math:`H` operator for a design of experiment of
the :math:`\mathbf{x}` parametric state space. The result of this algorithm is
-a homogeneous collection of simulated vectors (available using the storable
-variable "*EnsembleOfSimulations*") corresponding directly to the chosen
-homogeneous collection of state vectors (available using the storable variable
-"*EnsembleOfStates*").
+a homogeneous collection of simulated vectors :math:`\mathbf{y}` (available
+using the storable variable "*EnsembleOfSimulations*") corresponding directly
+to the chosen homogeneous collection of state vectors :math:`\mathbf{x}`
+(available using the storable variable "*EnsembleOfStates*").
The sampling of the states :math:`\mathbf{x}` can be given explicitly or under
form of hyper-cubes, explicit or sampled according to classic distributions.
-Beware of the size of the hyper-cube (and then to the number of computations)
-that can be reached, it can grow quickly to be quite large.
+The computations are optimized according to the computer resources available
+and the options requested by the user. Beware of the size of the hyper-cube
+(and then to the number of computations) that can be reached, it can grow
+quickly to be quite large.
To be visible by the user while reducing the risk of storage difficulties, the
-results of sampling or simulations has to be **explicitly** asked for. One use
-for that, on the desired variable, the final saving through
-"*UserPostAnalysis*" or the treatment during the calculation by "*observer*".
+results of sampling or simulations has to be **explicitly** asked for using the
+required variable.
The results obtained with this algorithm can be used to feed an
:ref:`section_ref_algorithm_MeasurementsOptimalPositioningTask`. In a
--- /dev/null
+..
+ Copyright (C) 2008-2023 EDF R&D
+
+ This file is part of SALOME ADAO module.
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+ See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+
+ Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+.. index:: single: InterpolationByReducedModelTask
+.. index:: single: Measurements interpolation
+.. index:: single: Snapshots (Ensemble)
+.. _section_ref_algorithm_InterpolationByReducedModelTask:
+
+Task algorithm "*InterpolationByReducedModelTask*"
+--------------------------------------------------
+
+.. ------------------------------------ ..
+.. include:: snippets/Header2Algo00.rst
+
+.. warning::
+
+ This algorithm is only available in textual user interface (TUI) and not in
+ graphical user interface (GUI).
+
+.. ------------------------------------ ..
+.. include:: snippets/Header2Algo01.rst
+
+This algorithm enables highly efficient interpolation of physical measurements
+using a reduced representation of the model for that physics. The output, for
+each set of measurements supplied at the required positions, is a complete
+field :math:`\mathbf{y}` by interpolation.
+
+To interpolate these measurements, a method of Empirical Interpolation Method
+(EIM [Barrault04]_) type is used, which establishes a reduced model, with or
+without measurement positioning constraints.
+
+To use this algorithm, you need the optimally positioned measurements and the
+associated reduced basis for model representation. This can be achieved as
+described below, by means of a preliminary analysis using a MOP, which provides
+positions and base. Once the base has been constructed and the positions
+determined, it is possible to perform as many interpolations as there are sets
+of measurements at the required positions, without having to repeat the prior
+analysis.
+
+ .. _irm_determination:
+ .. image:: images/irm_determination.png
+ :align: center
+ :width: 95%
+ .. centered::
+ **General scheme for using the algorithm**
+
+.. ------------------------------------ ..
+.. include:: snippets/Header2Algo02.rst
+
+.. include:: snippets/Observation.rst
+
+.. ------------------------------------ ..
+.. include:: snippets/Header2Algo03Task.rst
+
+.. include:: snippets/ObservationsAlreadyRestrictedOnOptimalLocations.rst
+
+.. include:: snippets/OptimalLocations.rst
+
+.. include:: snippets/ReducedBasis.rst
+
+StoreSupplementaryCalculations
+ .. index:: single: StoreSupplementaryCalculations
+
+ *List of names*. This list indicates the names of the supplementary
+ variables, that can be available during or at the end of the algorithm, if
+ they are initially required by the user. Their avalability involves,
+ potentially, costly calculations or memory consumptions. The default is then
+ a void list, none of these variables being calculated and stored by default
+ (excepted the unconditionnal variables). The possible names are in the
+ following list (the detailed description of each named variable is given in
+ the following part of this specific algorithmic documentation, in the
+ sub-section "*Information and variables available at the end of the
+ algorithm*"): [
+ "Analysis",
+ ].
+
+ Example :
+ ``{"StoreSupplementaryCalculations":["CurrentState", "Residu"]}``
+
+.. ------------------------------------ ..
+.. include:: snippets/Header2Algo04.rst
+
+.. include:: snippets/Analysis.rst
+
+.. ------------------------------------ ..
+.. include:: snippets/Header2Algo05.rst
+
+.. include:: snippets/Analysis.rst
+
+.. ------------------------------------ ..
+.. _section_ref_algorithm_InterpolationByReducedModelTask_examples:
+
+.. include:: snippets/Header2Algo06.rst
+
+- :ref:`section_ref_algorithm_MeasurementsOptimalPositioningTask`
+
+.. ------------------------------------ ..
+.. include:: snippets/Header2Algo07.rst
+
+- [Barrault04]_
+- [Quarteroni16]_
.. ------------------------------------ ..
.. include:: snippets/Header2Algo01.rst
-This algorithm provides optimal positioning of measurement points by an EIM
-(Empirical Interpolation Method) analysis. These positions are determined in a
-iterative greedy way, from a pre-existing set of state vectors (usually called
-"snapshots" in reduced basis methodology) or obtained by a direct simulation
-during the algorithm. Each of these state vectors are usually (but not
-necessarily) the result :math:`\mathbf{y}` of a simulation or an observation
-using the operator :math:`H` for a given set of parameters :math:`\mathbf{x}`.
+This algorithm provides optimal positioning of measurements of an
+:math:`\mathbf{y}` physical field, in order to get the best possible
+interpolation. These optimal measurement positions are determined in an
+iterative greedy way, from a pre-existing set of state vectors
+:math:`\mathbf{y}` (usually called "snapshots*" in reduced basis methodology)
+or obtained by simulating the physical field(s) of interest during the course
+of the algorithm. Each of these state vectors is usually (but not necessarily)
+the result :math:`\mathbf{y}` of a simulation using the operator :math:`H` that
+returns the complete field(s) for a given set of parameters :math:`\mathbf{x}`,
+or of an explicit observation of the complete field(s) :math:`\mathbf{y}`.
+
+To determine the optimum positioning of measurements, an Empirical
+Interpolation Method (EIM [Barrault04]_) is used, with (variant "*lcEIM*") or
+without (variant "*EIM*") positioning constraints.
There are two ways to use this algorithm:
-#. In its simplest use, if the set of state vectors is pre-existing, it is only
- necessary to provide it by the algorithm option "*EnsembleOfSnapshots*". It
- is for example the case when set of states has been generated by an
+#. In its simplest use, if the set of physical state :math:`\mathbf{y}` vectors
+ is pre-existing, it is only necessary to provide it as an ordered collection
+ by the algorithm option "*EnsembleOfSnapshots*". This is the default
+ situation, for example, if the set of states has been generated by an
:ref:`section_ref_algorithm_EnsembleOfSimulationGenerationTask`.
-#. If the set of state vectors is to be obtained by simulations during the
- course of the algorithm, then one must provide the :math:`H` simulation or
- observation operator and the parametric :math:`\mathbf{x}` state space
- design of experiments.
-
-The sampling of the states :math:`\mathbf{x}` can be given explicitly or under
-form of hyper-cubes, explicit or sampled according to classic distributions.
-Beware of the size of the hyper-cube (and then to the number of computations)
-that can be reached, it can grow quickly to be quite large.
-
-It is possible to exclude a priori potential positions for optimal measurement
-points, using the analysis variant "*PositioningBylcEIM*" for a constrained
-positioning search.
+#. If the set of physical state :math:`\mathbf{y}` vectors is to be obtained by
+ explicit simulations during the course of the algorithm, then one must
+ provide both the simulation operator of the complete field, here identified
+ with the observation operator :math:`H` of the complete field, and the
+ design of experiment of the space of parametric states :math:`\mathbf{x}`.
+
+If the design of experiments is supplied, the sampling of the states
+:math:`\mathbf{x}` can be given as in the
+:ref:`section_ref_algorithm_EnsembleOfSimulationGenerationTask`, explicitly or
+under form of hyper-cubes, explicit or sampled according to classic
+distributions. The computations are optimized according to the computer
+resources available and the options requested by the user. Beware of the size
+of the hyper-cube (and then to the number of computations) that can be reached,
+it can grow quickly to be quite large.
+
+ .. _mop_determination:
+ .. image:: images/mop_determination.png
+ :align: center
+ :width: 95%
+ .. centered::
+ **General scheme for using the algorithm**
+
+It is possible to exclude a priori potential positions for measurement
+positioning, using the analysis variant "*lcEIM*" for a constrained positioning
+search.
.. ------------------------------------ ..
.. include:: snippets/Header2Algo02.rst
pair: Variant ; CanonicalPSO
pair: Variant ; OGCR
pair: Variant ; SPSO-2011
-
-- "CanonicalPSO" (Canonical Particule Swarm Optimisation, see [ZambranoBigiarini13]_), classical algorithm called "canonical" of particle swarm, robust and defining a reference for particle swarm algorithms,
-- "OGCR" (Simple Particule Swarm Optimisation), simplified algorithm of particle swarm with no bounds on insects or velocities, not recommanded because less robust, but sometimes a lot more efficient,
-- "SPSO-2011" (Standard Standard Particle Swarm Optimisation 2011, voir [ZambranoBigiarini13]_), 2011 reference algorithm of particule swarm, robust, efficient and defined as a reference for particle swarm algorithms.
+ pair: Variant ; AIS PSO
+ pair: Variant ; APSO
+
+- "CanonicalPSO" (Canonical Particule Swarm Optimisation, see
+ [ZambranoBigiarini13]_), classical algorithm called "canonical" of particle
+ swarm, robust and defining a reference for particle swarm algorithms,
+- "OGCR" (Simple Particule Swarm Optimisation), simplified algorithm of
+ particle swarm with no bounds on insects or velocities, not recommanded
+ because less robust, but sometimes a lot more efficient,
+- "SPSO-2011" (Standard Particle Swarm Optimisation 2011, voir
+ [ZambranoBigiarini13]_), 2011 reference algorithm of particule swarm, robust,
+ efficient and defined as a reference for particle swarm algorithms. This
+ algorithm is sometimes called ":math:`\omega`-PSO" or "Inertia PSO" because
+ it incorporates a so-called inertia contribution, or also called "AIS" (for
+ "Asynchronous Iteration Strategy") or "APSO" (for "Advanced Particle Swarm
+ Optimisation") because it incorporates evolutionary updating of the best
+ elements, leading to intrinsically improved convergence of the algorithm.
The following are a few practical suggestions for the effective use of these
algorithms:
- The recommended variant of this algorithm is the "SPSO-2011" even if the
- "CanonicalPSO" algorithm remains by default the more robust of the two.
+ "CanonicalPSO" algorithm remains by default the more robust one.
- The number of particles or insects usually recommended varies between 40 and
100 depending on the algorithm, more or less independently of the dimension
- of the state space.
+ of the state space. Usually, the best performances are obtained for
+ populations of 70 to 500 particles. Even if the default value for this
+ elementary parameter comes from extended knowledge on these algorithms, it is
+ recommanded to adapt it to the difficulty of the given problems.
- The recommended number of generations for population evolution is often
around 50, but it can easily vary between 25 and 500.
- The maximum number of evaluations of the simulation function should usually
dimension of the state space.
- The error functional usually decreases by levels (thus with a zero
progression of the value of the functional at each generation when we stay in
- the level), making it not recommended to stop on the criterion of decrease of
- the cost function. It is normally wiser to adapt the number of iterations or
- generations to accelerate the convergence of the algorithms.
+ the level), making it *not recommended* to stop on the criterion of decrease
+ of the cost function. It is normally wiser to adapt the number of iterations
+ or generations to accelerate the convergence of the algorithms.
- If the problem is constrained, it is necessary to define the bounds of the
variables (by the variable "*Bounds*"). If the problem is totally
unconstrained, it is essential to define increment bounds (by the variable
"CurrentIterationNumber",
"CurrentState",
"Innovation",
+ "InternalCostFunctionJ",
+ "InternalCostFunctionJb",
+ "InternalCostFunctionJo",
+ "InternalStates",
"OMA",
"OMB",
"SimulatedObservationAtBackground",
.. include:: snippets/Innovation.rst
+.. include:: snippets/InternalCostFunctionJ.rst
+
+.. include:: snippets/InternalCostFunctionJb.rst
+
+.. include:: snippets/InternalCostFunctionJo.rst
+
+.. include:: snippets/InternalStates.rst
+
.. include:: snippets/OMA.rst
.. include:: snippets/OMB.rst
.. ------------------------------------ ..
.. _section_ref_algorithm_ParticleSwarmOptimization_examples:
+.. include:: snippets/Header2Algo09.rst
+
+.. include:: scripts/simple_ParticleSwarmOptimization1.rst
+
+.. literalinclude:: scripts/simple_ParticleSwarmOptimization1.py
+
+.. include:: snippets/Header2Algo10.rst
+
+.. literalinclude:: scripts/simple_ParticleSwarmOptimization1.res
+ :language: none
+
+.. include:: snippets/Header2Algo11.rst
+
+.. _simple_ParticleSwarmOptimization1:
+.. image:: scripts/simple_ParticleSwarmOptimization1.png
+ :align: center
+ :width: 90%
+
+.. ------------------------------------ ..
.. include:: snippets/Header2Algo06.rst
- :ref:`section_ref_algorithm_DerivativeFreeOptimization`
that can be reached, it can grow quickly to be quite large. When a state is not
observable, a *"NaN"* value is returned.
+It is also possible to supply a set of simulations :math:`\mathbf{y}` already
+established elsewhere (so there's no explicit need for an operator
+:math:`\mathcal{H}`), which are implicitly associated with a set of state
+samples :math:`\mathbf{x}`. In this case where the set of simulations is
+provided, it is imperative to also provide the set of states :math:`\mathbf{x}`
+by explicit sampling, whose state order corresponds to the order of the
+simulations :math:`\mathbf{y}`.
+
To access the calculated information, the results of the sampling or
simulations must be requested **explicitly** to avoid storage difficulties (if
no results are requested, nothing is available). One use for that, on the
.. ------------------------------------ ..
.. include:: snippets/Header2Algo03Chck.rst
+.. include:: snippets/EnsembleOfSnapshots.rst
+
.. include:: snippets/QualityCriterion.rst
.. include:: snippets/SampleAsExplicitHyperCube.rst
:maxdepth: 1
ref_algorithm_EnsembleOfSimulationGenerationTask
+ ref_algorithm_InterpolationByReducedModelTask
ref_algorithm_MeasurementsOptimalPositioningTask
ref_task_keywords
adjusted coefficients coincides with the observations at the 5 control points.
To illustrate more clearly the recalibration performed, using the same
-information, we can plot the continuous version of the quadratic curves
+information, we can plot the "continuous" version of the quadratic curves
available for the background state of the coefficients, and for the optimal
state of the coefficients, together with the values obtained at the control
points. In addition, to improve readability, the lines joining the simulations
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+from numpy import array, ravel
+def QuadFunction( coefficients ):
+ """
+ Quadratic simulation in x: y = a x^2 + b x + c
+ """
+ a, b, c = list(ravel(coefficients))
+ x_points = (-5, 0, 1, 3, 10)
+ y_points = []
+ for x in x_points:
+ y_points.append( a*x*x + b*x + c )
+ return array(y_points)
+#
+Xb = array([1., 1., 1.])
+Yobs = array([57, 2, 3, 17, 192])
+#
+NumberOfInsects = 40
+#
+print("Resolution of the calibration problem")
+print("-------------------------------------")
+print("")
+from adao import adaoBuilder
+case = adaoBuilder.New()
+case.setBackground( Vector = Xb, Stored=True )
+case.setBackgroundError( ScalarSparseMatrix = 1.e6 )
+case.setObservation( Vector = Yobs, Stored=True )
+case.setObservationError( ScalarSparseMatrix = 1. )
+case.setObservationOperator( OneFunction = QuadFunction )
+case.setAlgorithmParameters(
+ Algorithm='ParticleSwarmOptimization',
+ Parameters={
+ 'NumberOfInsects':NumberOfInsects,
+ 'MaximumNumberOfIterations': 20,
+ 'StoreSupplementaryCalculations': [
+ 'CurrentState',
+ ],
+ 'Bounds':[[0,5],[-2,2],[0,5]],
+ 'SetSeed':123456789,
+ },
+ )
+case.setObserver(
+ Info=" Intermediate state at the current iteration:",
+ Template='ValuePrinter',
+ Variable='CurrentState',
+ )
+case.execute()
+print("")
+#
+#-------------------------------------------------------------------------------
+#
+print("Calibration of %i coefficients in a 1D quadratic function on %i measures"%(
+ len(case.get('Background')),
+ len(case.get('Observation')),
+ ))
+print("----------------------------------------------------------------------")
+print("")
+print("Observation vector.................:", ravel(case.get('Observation')))
+print("A priori background state..........:", ravel(case.get('Background')))
+print("")
+print("Expected theoretical coefficients..:", ravel((2,-1,2)))
+print("")
+print("Number of iterations...............:", len(case.get('CurrentState')))
+print("Number of simulations..............:", NumberOfInsects*len(case.get('CurrentState')))
+print("Calibration resulting coefficients.:", ravel(case.get('Analysis')[-1]))
+#
+Xa = case.get('Analysis')[-1]
+import matplotlib.pyplot as plt
+plt.rcParams['figure.figsize'] = (10, 4)
+#
+plt.figure()
+plt.plot((-5,0,1,3,10),QuadFunction(Xb),'b-',label="Simulation at background")
+plt.plot((-5,0,1,3,10),Yobs, 'kX',label='Observation',markersize=10)
+plt.plot((-5,0,1,3,10),QuadFunction(Xa),'r-',label="Simulation at optimum")
+plt.legend()
+plt.title('Coefficients calibration', fontweight='bold')
+plt.xlabel('Arbitrary coordinate')
+plt.ylabel('Observations')
+plt.savefig("simple_ParticleSwarmOptimization1.png")
--- /dev/null
+Resolution of the calibration problem
+-------------------------------------
+
+ Intermediate state at the current iteration: [ 1.76770856 -1.2054263 1.22625259]
+ Intermediate state at the current iteration: [ 2.04776518 -1.17449716 3.14493347]
+ Intermediate state at the current iteration: [ 2.04776518 -1.17449716 3.14493347]
+ Intermediate state at the current iteration: [ 2.01933291 -1. 3.15162067]
+ Intermediate state at the current iteration: [ 1.96384202 -0.74855119 3.40642058]
+ Intermediate state at the current iteration: [ 1.96384202 -0.74855119 3.40642058]
+ Intermediate state at the current iteration: [ 1.96384202 -0.74855119 3.40642058]
+ Intermediate state at the current iteration: [ 1.96384202 -0.74855119 3.40642058]
+ Intermediate state at the current iteration: [ 1.95417745 -0.73191939 3.14451887]
+ Intermediate state at the current iteration: [ 1.96217646 -0.7883895 2.91127919]
+ Intermediate state at the current iteration: [ 1.97610485 -1.00254825 2.89582746]
+ Intermediate state at the current iteration: [ 2.0007262 -1.06443275 2.69825603]
+ Intermediate state at the current iteration: [ 1.9934285 -1.02432071 2.39823319]
+ Intermediate state at the current iteration: [ 1.9934285 -1.02432071 2.39823319]
+ Intermediate state at the current iteration: [ 1.9942533 -0.99256953 2.30174702]
+ Intermediate state at the current iteration: [ 1.9942533 -0.99256953 2.30174702]
+ Intermediate state at the current iteration: [ 1.99742923 -0.99796085 2.1278678 ]
+ Intermediate state at the current iteration: [ 1.99742923 -0.99796085 2.1278678 ]
+ Intermediate state at the current iteration: [ 1.99742923 -0.99796085 2.1278678 ]
+ Intermediate state at the current iteration: [ 1.99742923 -0.99796085 2.1278678 ]
+ Intermediate state at the current iteration: [ 2.00166149 -1.0012696 2.02137857]
+
+Calibration of 3 coefficients in a 1D quadratic function on 5 measures
+----------------------------------------------------------------------
+
+Observation vector.................: [ 57. 2. 3. 17. 192.]
+A priori background state..........: [1. 1. 1.]
+
+Expected theoretical coefficients..: [ 2 -1 2]
+
+Number of iterations...............: 21
+Number of simulations..............: 840
+Calibration resulting coefficients.: [ 2.00166149 -1.0012696 2.02137857]
--- /dev/null
+.. index:: single: 3DVAR (example)
+
+This example describes the calibration of parameters :math:`\mathbf{x}` of a
+quadratic observation model :math:`H`. This model is here represented as a
+function named ``QuadFunction``. This function get as input the coefficients
+vector :math:`\mathbf{x}`, and return as output the evaluation vector
+:math:`\mathbf{y}` of the quadratic model at the predefined internal control
+points. The calibration is done using an initial coefficient set (background
+state specified by ``Xb`` in the code), and with the information
+:math:`\mathbf{y}^o` (specified by ``Yobs`` in the code) of 5 measures obtained
+in these same internal control points. We set twin experiments (see
+:ref:`section_methodology_twin`) and the measurements are supposed to be
+perfect. We choose to emphasize the observations versus the background by
+setting a great variance for the background error, here of :math:`10^{6}`.
+
+The adjustment is carried out by displaying intermediate results during
+iterative optimization.
Analysis
*List of vectors*. Each element of this variable is an optimal state
- :math:`\mathbf{x}^*` in optimization or an analysis :math:`\mathbf{x}^a` in
- data assimilation.
+ :math:`\mathbf{x}^*` in optimization, an interpolate or an analysis
+ :math:`\mathbf{x}^a` in data assimilation.
Example:
``Xa = ADD.get("Analysis")[-1]``
*Boolean value*. This variable define the level of trace and intermediary
debug information. The choices are limited between 0 (for False) and 1 (for
True).
+
+ Example :
+ ``{"Debug":False}``
.. index:: single: EnsembleOfSimulations
EnsembleOfSimulations
- *List of vectors or matrix*. This key contains a set of physical or simulated
- state vectors :math:`\mathbf{y}` (called "*snapshots*" in reduced basis
- terminology), with 1 state per column if it is a matrix, or 1 state per
- element if it is a list. Caution: the numbering of the points, to which a
- state value is given in each vector, is implicitly that of the natural order
- of numbering of the state vector, from 0 to the "size minus 1" of this
- vector.
+ *List of vectors or matrix*. This key contains an ordered collection of
+ physical or simulated state vectors :math:`\mathbf{y}` (called "*snapshots*"
+ in reduced basis terminology), with 1 state per column if it is a matrix, or
+ 1 state per element if it is a list. Caution: the numbering of the support or
+ points, on which or to which a state value is given in each vector, is
+ implicitly that of the natural order of numbering of the state vector, from 0
+ to the "size minus 1" of this vector.
Example :
``{"EnsembleOfSimulations":[y1, y2, y3...]}``
.. index:: single: EnsembleOfSnapshots
EnsembleOfSnapshots
- *List of vectors or matrix*. This key contains a set of physical state
- vectors :math:`\mathbf{y}` (called "*snapshots*" in reduced basis
- terminology), with 1 state per column if it is a matrix, or 1 state per
- element if it is a list. Caution: the numbering of the points, to which a
- state value is given in each vector, is implicitly that of the natural order
- of numbering of the state vector, from 0 to the "size minus 1" of this
- vector.
+ *List of vectors or matrix*. This key contains an ordered collection of
+ physical state vectors :math:`\mathbf{y}` (called "*snapshots*" in reduced
+ basis terminology), with one full state per column if it is a matrix, or one
+ full state per element if it is a list. Caution: the numbering of the support
+ or points, on which or to which a state value is given in each vector, is
+ implicitly that of the natural order of numbering of the state vector, from 0
+ to the "size minus 1" of this vector.
Example :
``{"EnsembleOfSnapshots":[y1, y2, y3...]}``
.. index:: single: EnsembleOfStates
EnsembleOfStates
- *List of vectors or matrix*. Each element is a set of physical or parameter
- state vectors :math:`\mathbf{x}`, with 1 state per column if it is a matrix,
- or 1 state per element if it is a list. Caution: the numbering of the points,
- to which a state value is given in each vector, is implicitly that of the
- natural order of numbering of the state vector, from 0 to the "size minus 1"
- of this vector.
+ *List of vectors or matrix*. Each element is an ordered collection of
+ physical or parameter state vectors :math:`\mathbf{x}`, with 1 state per
+ column if it is a matrix, or 1 state per element if it is a list. Caution:
+ the numbering of the support or points, on which or to which a state value is
+ given in each vector, is implicitly that of the natural order of numbering of
+ the state vector, from 0 to the "size minus 1" of this vector.
Example :
``{"EnsembleOfStates":[x1, x2, x3...]}``
variables of a state vector considered arbitrarily in one-dimensional form.
Example :
- ``mp = ADD.get("ExcludedPoints")[-1]``
+ ``ep = ADD.get("ExcludedPoints")[-1]``
"COBYLA" (minimization, with or without constraints, by linear approximation, see [Powell94]_ [Powell98]_).
"NEWUOA" (minimization, with or without constraints, by iterative quadratic approximation, see [Powell04]_),
"POWELL" (minimization, unconstrained, using conjugate directions, see [Powell64]_),
- "SIMPLEX" (minimization, with or without constraints, using Nelder-Mead simplex algorithm, see [Nelder65]_),
- "SUBPLEX" (minimization, with or without constraints, using Nelder-Mead on a sequence of subspaces, see [Rowan90]_).
+ "SIMPLEX" (minimization, with or without constraints, using Nelder-Mead simplex algorithm, see [Nelder65]_ and [WikipediaNM]_),
+ "SUBPLEX" (minimization, with or without constraints, using Nelder-Mead simplex algorithm on a sequence of subspaces, see [Rowan90]_).
Only the "POWELL" minimizer does not allow to deal with boundary constraints,
all the others take them into account if they are present in the case
definition.
:header: "Tool", "Minimal version", "Reached version"
:widths: 20, 10, 10
- Python, 3.6.5, 3.10.11
- Numpy, 1.14.3, 1.24.3
- Scipy, 0.19.1, 1.10.1
- MatplotLib, 2.2.2, 3.7.1
+ Python, 3.6.5, 3.11.5
+ Numpy, 1.14.3, 1.26.0
+ Scipy, 0.19.1, 1.11.2
+ MatplotLib, 2.2.2, 3.8.0
GnuplotPy, 1.8, 1.8
NLopt, 2.4.2, 2.7.1
ADAO, |release|
EFICAS, |release|
SALOME, |release|
- Python, 3.6.5
- Numpy, 1.16.4
- Scipy, 1.4.1
+ Python, 3.9.2
+ Numpy, 1.19.5
+ Scipy, 1.6.0
MatplotLib, 3.3.4
Gnuplot, 1.8
- NLopt, 2.5.0
+ NLopt, 2.4.2
--- /dev/null
+.. index:: single: ObservationsAlreadyRestrictedOnOptimalLocations
+
+ObservationsAlreadyRestrictedOnOptimalLocations
+ *Boolean value*. The variable defines whether measurements are supplied only
+ at the ideal positions or optimum points at which a measurement is required
+ ("True", default value), or whether they are supplied on a medium identical
+ to the complete field and must therefore be restricted to the required
+ positions ("False").
+
+ Example :
+ ``{"ObservationsAlreadyRestrictedOnOptimalLocations":False}``
--- /dev/null
+.. index:: single: OptimalLocations
+
+OptimalLocations
+ *List of integer series*. Each element is a series, containing the indices of
+ ideal positions or optimal points where a measurement is required, in the
+ order of the variables of a state vector considered arbitrarily in
+ one-dimensional form, and in the same order as the vectors of the reduced
+ basis found iteratively.
+
+ It is identical to a single output of the ideal positions or optimum points
+ of a :ref:`section_ref_algorithm_MeasurementsOptimalPositioningTask`.
.. index:: single: OptimalPoints
OptimalPoints
- *List of integer series*. Each element is a series, containing the ideal points
- determined by the optimal search, ordered by decreasing preference and in the
- same order as the reduced basis vectors found iteratively.
+ *List of integer series*. Each element is a series, containing the indices of
+ ideal positions or optimal points where a measurement is required, determined
+ by the optimal search, ordered by decreasing preference and in the same order
+ as the reduced basis vectors found iteratively.
Example :
- ``mp = ADD.get("OptimalPoints")[-1]``
+ ``op = ADD.get("OptimalPoints")[-1]``
decreasing preference and in the same order as the ideal points found
iteratively.
+ When it is an input, it is identical to a single output of a
+ :ref:`section_ref_algorithm_MeasurementsOptimalPositioningTask`.
+
Example :
``rb = ADD.get("ReducedBasis")[-1]``
.. [WikipediaND] Wikipedia, *Nondimensionalization*, https://en.wikipedia.org/wiki/Nondimensionalization
+.. [WikipediaNM] Wikipedia, *Nelder–Mead method*, https://en.wikipedia.org/wiki/Nelder%E2%80%93Mead_method
+
.. [WikipediaPSO] Wikipedia, *Particle Swarm Optimization*, https://en.wikipedia.org/wiki/Particle_swarm_optimization
.. [WikipediaQR] Wikipedia, *Quantile regression*, https://en.wikipedia.org/wiki/Quantile_regression
#. :ref:`Exemples avec l'algorithme de "ExtendedBlue"<section_ref_algorithm_ExtendedBlue_examples>`
#. :ref:`Exemples avec l'algorithme de "KalmanFilter"<section_ref_algorithm_KalmanFilter_examples>`
#. :ref:`Exemples avec l'algorithme de "NonLinearLeastSquares"<section_ref_algorithm_NonLinearLeastSquares_examples>`
+#. :ref:`Exemples avec l'algorithme de "ParticleSwarmOptimization"<section_ref_algorithm_ParticleSwarmOptimization_examples>`
Utilisations d'algorithmes de vérification
------------------------------------------
- [Powell07]_
- [Powell09]_
- [Rowan90]_
+- [WikipediaNM]_
.. ------------------------------------ ..
.. include:: snippets/Header2Algo01.rst
-Cet algorithme permet de générer un ensemble de résultats, de type simulation
-ou observation, à l'aide de l'opérateur :math:`H` pour un plan d'expérience de
-l'espace des états :math:`\mathbf{x}` paramétriques. Le résultat de cet
-algorithme est une collection homogène des vecteurs simulés (disponible à
-l'aide de la variable stockable "*EnsembleOfSimulations*") correspondants directement à
-la collection homogène choisie de vecteurs d'états (disponible à l'aide de la
+Cet algorithme permet de générer un ensemble de résultats physiques, de type
+simulation ou observation, à l'aide de l'opérateur :math:`H` pour un plan
+d'expérience de l'espace des états :math:`\mathbf{x}` paramétriques. Le
+résultat de cet algorithme est une collection homogène de vecteurs simulés
+:math:`\mathbf{y}` (disponible à l'aide de la variable stockable
+"*EnsembleOfSimulations*") correspondants directement à la collection homogène
+choisie de vecteurs d'états :math:`\mathbf{x}` (disponible à l'aide de la
variable stockable "*EnsembleOfStates*").
L'échantillonnage des états :math:`\mathbf{x}` peut être fourni explicitement
ou sous la forme d'hyper-cubes, explicites ou échantillonnés selon des
-distributions courantes. Attention à la taille de l'hyper-cube (et donc au
-nombre de calculs) qu'il est possible d'atteindre, elle peut rapidement devenir
-importante.
+distributions courantes. Les calculs sont optimisés selon les ressources
+informatiques disponibles et les options demandées par l'utilisateur. Attention
+à la taille de l'hyper-cube (et donc au nombre de calculs) qu'il est possible
+d'atteindre, elle peut rapidement devenir importante.
Pour apparaître pour l'utilisateur tout en réduisant les difficultés de
stockage, les résultats de l'échantillonnage ou des simulations doivent être
-demandés **explicitement**. On utilise pour cela, sur la variable désirée, la
-sauvegarde finale à l'aide du mot-clé "*UserPostAnalysis*" ou le traitement en
-cours de calcul à l'aide des "*observer*" adaptés.
+demandés **explicitement** à l'aide de la variable requise.
Les résultats obtenus avec cet algorithme peuvent être utilisés pour alimenter
un :ref:`section_ref_algorithm_MeasurementsOptimalPositioningTask`. De manière
--- /dev/null
+..
+ Copyright (C) 2008-2023 EDF R&D
+
+ This file is part of SALOME ADAO module.
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+ See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+
+ Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+.. index:: single: InterpolationByReducedModelTask
+.. index:: single: Interpolation de mesures
+.. index:: single: Snapshots (Ensemble)
+.. _section_ref_algorithm_InterpolationByReducedModelTask:
+
+Algorithme de tâche "*InterpolationByReducedModelTask*"
+-------------------------------------------------------
+
+.. ------------------------------------ ..
+.. include:: snippets/Header2Algo00.rst
+
+.. warning::
+
+ Cet algorithme n'est utilisable qu'en interface textuelle (TUI) et pas en
+ interface graphique (GUI).
+
+.. ------------------------------------ ..
+.. include:: snippets/Header2Algo01.rst
+
+Cet algorithme permet de réaliser une interpolation très efficace de mesures
+physiques à l'aide d'une représentation réduite du modèle pour cette physique.
+On obtient en sortie, pour chaque jeu de mesures fournies aux positions
+requises, un champ complet :math:`\mathbf{y}` par interpolation.
+
+Pour interpoler ces mesures, on utilise une méthode de type Empirical
+Interpolation Method (EIM [Barrault04]_), qui établit un modèle réduit, avec ou
+sans contraintes de positionnement de mesures.
+
+Pour utiliser cet algorithme, il faut disposer des mesures optimalement
+positionnées et de la base réduite associée pour la représentation du modèle.
+C'est réalisable selon le schéma suivant, par une analyse préalable à l'aide
+d'un :ref:`section_ref_algorithm_MeasurementsOptimalPositioningTask`, qui
+fournit positions et base. Une fois la base construite et les positions
+déterminées, il peut être réalisé autant d'interpolations que l'on a de jeu de
+mesures aux positions requises, sans devoir refaire l'analyse préalable.
+
+ .. _irm_determination:
+ .. image:: images/irm_determination.png
+ :align: center
+ :width: 95%
+ .. centered::
+ **Schéma général d'utilisation de l'algorithme**
+
+.. ------------------------------------ ..
+.. include:: snippets/Header2Algo02.rst
+
+.. include:: snippets/Observation.rst
+
+.. ------------------------------------ ..
+.. include:: snippets/Header2Algo03Task.rst
+
+.. include:: snippets/ObservationsAlreadyRestrictedOnOptimalLocations.rst
+
+.. include:: snippets/OptimalLocations.rst
+
+.. include:: snippets/ReducedBasis.rst
+
+StoreSupplementaryCalculations
+ .. index:: single: StoreSupplementaryCalculations
+
+ *Liste de noms*. Cette liste indique les noms des variables supplémentaires,
+ qui peuvent être disponibles au cours du déroulement ou à la fin de
+ l'algorithme, si elles sont initialement demandées par l'utilisateur. Leur
+ disponibilité implique, potentiellement, des calculs ou du stockage coûteux.
+ La valeur par défaut est donc une liste vide, aucune de ces variables n'étant
+ calculée et stockée par défaut (sauf les variables inconditionnelles). Les
+ noms possibles pour les variables supplémentaires sont dans la liste suivante
+ (la description détaillée de chaque variable nommée est donnée dans la suite
+ de cette documentation par algorithme spécifique, dans la sous-partie
+ "*Informations et variables disponibles à la fin de l'algorithme*") : [
+ "Analysis",
+ ].
+
+ Exemple :
+ ``{"StoreSupplementaryCalculations":["CurrentState", "Residu"]}``
+
+.. ------------------------------------ ..
+.. include:: snippets/Header2Algo04.rst
+
+.. include:: snippets/Analysis.rst
+
+.. ------------------------------------ ..
+.. include:: snippets/Header2Algo05.rst
+
+.. include:: snippets/Analysis.rst
+
+.. ------------------------------------ ..
+.. _section_ref_algorithm_InterpolationByReducedModelTask_examples:
+
+.. include:: snippets/Header2Algo06.rst
+
+- :ref:`section_ref_algorithm_MeasurementsOptimalPositioningTask`
+
+.. ------------------------------------ ..
+.. include:: snippets/Header2Algo07.rst
+
+- [Barrault04]_
+- [Quarteroni16]_
.. ------------------------------------ ..
.. include:: snippets/Header2Algo01.rst
-Cet algorithme permet d'établir la position de points de mesures optimaux par
-une analyse EIM (Empirical Interpolation Method). Ces positions sont
-déterminées de manière itérative, à partir d'un ensemble de vecteurs d'état
+Cet algorithme permet d'établir la position optimale de mesures d'un champ
+physique :math:`\mathbf{y}`, pour en assurer l'interpolation la meilleure
+possible. Ces positions optimales de mesure sont déterminées de manière
+itérative, à partir d'un ensemble de vecteurs d'état :math:`\mathbf{y}`
pré-existants (usuellement appelés "*snapshots*" en méthodologie de bases
-réduites) ou obtenus par une simulation directe au cours de l'algorithme.
-Chacun de ces vecteurs d'état est habituellement (mais pas obligatoirement) le
-résultat :math:`\mathbf{y}` d'une simulation ou d'une observation à l'aide de
-l'opérateur :math:`H` pour un jeu de paramètres donné :math:`\mathbf{x}`.
+réduites) ou obtenus par une simulation de ce(s) champ(s) physiqu(e) d'intérêt
+au cours de l'algorithme. Chacun de ces vecteurs d'état est habituellement
+(mais pas obligatoirement) le résultat :math:`\mathbf{y}` d'une simulation à
+l'aide de l'opérateur :math:`H` restituant le (ou les) champ(s) complet(s) pour
+un jeu de paramètres donné :math:`\mathbf{x}`, ou d'une observation explicite
+du (ou des) champ(s) complet(s) :math:`\mathbf{y}`.
-Il y a deux manières d'utiliser cet algorithme:
+Pour établir la position optimale de mesures, on utilise une méthode de type
+Empirical Interpolation Method (EIM [Barrault04]_), avec (variant "*lcEIM*") ou
+sans contraintes (variant "*EIM*") de positionnement.
-#. Dans son usage le plus simple, si l'ensemble des vecteurs d'état est
- pré-existant, il suffit de le fournir par l'option "*EnsembleOfSnapshots*"
- d'algorithme. C'est par exemple le cas si l'ensemble des états a été généré
- par un :ref:`section_ref_algorithm_EnsembleOfSimulationGenerationTask`.
-#. Si l'ensemble des vecteurs d'état doit être obtenu par des simulations au
- cours de l'algorithme, alors on doit fournir l'opérateur de simulation ou
- d'observation :math:`H` et le plan d'expérience de l'espace des états
- :math:`\mathbf{x}` paramétriques.
+Il y a deux manières d'utiliser cet algorithme:
-L'échantillonnage des états :math:`\mathbf{x}` peut être fourni explicitement
+#. Dans son usage le plus simple, si l'ensemble des vecteurs d'état physique
+ :math:`\mathbf{y}` est pré-existant, il suffit de le fournir sous la forme
+ d'une collection ordonnée par l'option "*EnsembleOfSnapshots*" de
+ l'algorithme. C'est par exemple ce que l'on obtient par défaut si l'ensemble
+ des états a été généré par un
+ :ref:`section_ref_algorithm_EnsembleOfSimulationGenerationTask`.
+#. Si l'ensemble des vecteurs d'état physique :math:`\mathbf{y}` doit être
+ obtenu par des simulations explicites au cours de l'algorithme, alors on
+ doit fournir à la fois l'opérateur de simulation du champ complet, ici
+ identifié à l'opérateur d'observation :math:`H` du champ complet, et le plan
+ d'expérience de l'espace des états :math:`\mathbf{x}` paramétriques.
+
+Dans le cas où l'on fournit le plan d'expérience, l'échantillonnage des états
+:math:`\mathbf{x}` peut être fourni comme pour un
+:ref:`section_ref_algorithm_EnsembleOfSimulationGenerationTask`, explicitement
ou sous la forme d'hyper-cubes, explicites ou échantillonnés selon des
-distributions courantes. Attention à la taille de l'hyper-cube (et donc au
-nombre de calculs) qu'il est possible d'atteindre, elle peut rapidement devenir
-importante.
-
-Il est possible d'exclure a priori des positions potentielles pour les points
-de mesures optimaux, en utilisant le variant "*PositioningBylcEIM*" d'analyse
-pour une recherche de positionnement contraint.
+distributions courantes. Les calculs sont optimisés selon les ressources
+informatiques disponibles et les options demandées par l'utilisateur. Attention
+à la taille de l'hyper-cube (et donc au nombre de calculs) qu'il est possible
+d'atteindre, elle peut rapidement devenir importante.
+
+ .. _mop_determination:
+ .. image:: images/mop_determination.png
+ :align: center
+ :width: 95%
+ .. centered::
+ **Schéma général d'utilisation de l'algorithme**
+
+Il est possible d'exclure a priori des positions potentielles pour le
+positionnement des mesures, en utilisant le variant "*lcEIM*" d'analyse pour
+une recherche de positionnement contraint.
.. ------------------------------------ ..
.. include:: snippets/Header2Algo02.rst
pair: Variant ; CanonicalPSO
pair: Variant ; OGCR
pair: Variant ; SPSO-2011
-
-- "CanonicalPSO" (Canonical Particule Swarm Optimisation, voir [ZambranoBigiarini13]_), algorithme classique dit "canonique" d'essaim particulaire, robuste et définissant une référence des algorithmes d'essaims particulaires,
-- "OGCR" (Simple Particule Swarm Optimisation), algorithme simplifié d'essaim particulaire sans bornes sur les insectes ou les vitesses, déconseillé car peu robuste, mais parfois beaucoup plus rapide,
-- "SPSO-2011" (Standard Standard Particle Swarm Optimisation 2011, voir [ZambranoBigiarini13]_), algorithme de référence 2011 d'essaim particulaire, robuste, performant et défini comme une référence des algorithmes d'essaims particulaires.
+ pair: Variant ; AIS PSO
+ pair: Variant ; APSO
+
+- "CanonicalPSO" (Canonical Particule Swarm Optimisation, voir
+ [ZambranoBigiarini13]_), algorithme classique dit "canonique" d'essaim
+ particulaire, robuste et définissant une référence des algorithmes d'essaims
+ particulaires,
+- "OGCR" (Simple Particule Swarm Optimisation), algorithme simplifié d'essaim
+ particulaire sans bornes sur les insectes ou les vitesses, déconseillé car
+ peu robuste, mais parfois beaucoup plus rapide,
+- "SPSO-2011" (Standard Particle Swarm Optimisation 2011, voir
+ [ZambranoBigiarini13]_), algorithme de référence 2011 d'essaim particulaire,
+ robuste, performant et défini comme une référence des algorithmes d'essaims
+ particulaires. Cet algorithme est parfois appelé ":math:`\omega`-PSO" ou
+ "Inertia PSO" car il intègre une contribution dite d'inertie, ou encore
+ appelé "AIS" (pour "Asynchronous Iteration Strategy") ou "APSO" (pour
+ "Advanced Particle Swarm Optimisation") car il intègre la mise à jour
+ évolutive des meilleurs éléments, conduisant à une convergence
+ intrinsèquement améliorée de l'algorithme.
Voici quelques suggestions pratiques pour une utilisation efficace de ces
algorithmes :
- La variante recommandée de cet algorithme est le "SPSO-2011" même si
- l'algorithme "CanonicalPSO" reste par défaut le plus robuste des deux.
+ l'algorithme "CanonicalPSO" reste par défaut le plus robuste.
- Le nombre de particules ou d'insectes usuellement recommandé varie entre 40
et 100 selon l'algorithme, à peu près indépendamment de la dimension de
- l'espace des états.
+ l'espace des états. En général, les meilleurs performances sont obtenues pour
+ des populations de 70 à 500 particules. Même si la valeur par défaut de ce
+ paramètre de base provient d'une expérience étendue sur ces algorithmes, il
+ est recommandé de l'adapter à la difficulté des problèmes traités.
- Le nombre recommandé de générations, lors de l'évolution de la population,
est souvent de l'ordre de 50, mais il peut facilement varier entre 25 et 500.
- Le nombre maximal d'évaluation de la fonction de simulation doit usuellement
la dimension de l'espace des états.
- La fonctionnelle d'erreur décroît usuellement par pallier (donc avec une
progression nulle de la valeur de fonctionnelle à chaque génération lorsque
- l'on reste dans le palier), rendant non recommandé un arrêt sur critère de
+ l'on reste dans le palier), rendant *non recommandé* un arrêt sur critère de
décroissance de la fonction-coût. Il est normalement plus judicieux d'adapter
le nombre d'itérations ou de générations pour accélérer la convergence des
algorithmes.
"CurrentIterationNumber",
"CurrentState",
"Innovation",
+ "InternalCostFunctionJ",
+ "InternalCostFunctionJb",
+ "InternalCostFunctionJo",
+ "InternalStates",
"OMA",
"OMB",
"SimulatedObservationAtBackground",
.. include:: snippets/Innovation.rst
+.. include:: snippets/InternalCostFunctionJ.rst
+
+.. include:: snippets/InternalCostFunctionJb.rst
+
+.. include:: snippets/InternalCostFunctionJo.rst
+
+.. include:: snippets/InternalStates.rst
+
.. include:: snippets/OMA.rst
.. include:: snippets/OMB.rst
.. ------------------------------------ ..
.. _section_ref_algorithm_ParticleSwarmOptimization_examples:
+.. include:: snippets/Header2Algo09.rst
+
+.. include:: scripts/simple_ParticleSwarmOptimization1.rst
+
+.. literalinclude:: scripts/simple_ParticleSwarmOptimization1.py
+
+.. include:: snippets/Header2Algo10.rst
+
+.. literalinclude:: scripts/simple_ParticleSwarmOptimization1.res
+ :language: none
+
+.. include:: snippets/Header2Algo11.rst
+
+.. _simple_ParticleSwarmOptimization1:
+.. image:: scripts/simple_ParticleSwarmOptimization1.png
+ :align: center
+ :width: 90%
+
+.. ------------------------------------ ..
.. include:: snippets/Header2Algo06.rst
- :ref:`section_ref_algorithm_DerivativeFreeOptimization`
importante. Lorsque un état n'est pas observable, une valeur *"NaN"* est
retournée.
+Il est aussi possible de fournir un ensemble de simulations :math:`\mathbf{y}`
+déjà établies par ailleurs (donc sans besoin explicite d'un opérateur
+:math:`\mathcal{H}`), qui sont implicitement associées à un ensemble
+d'échantillons d'états :math:`\mathbf{x}`. Dans ce cas où l'ensemble de
+simulations est fourni, il est impératif de fournir aussi l'ensemble des états
+:math:`\mathbf{x}` par un échantillonnage explicite, dont l'ordre des états
+correspond à l'ordre des simulations :math:`\mathbf{y}`.
+
Pour accéder aux informations calculées, les résultats de l'échantillonnage ou
des simulations doivent être demandés **explicitement** pour éviter les
difficultés de stockage (en l'absence de résultats demandés, rien n'est
.. ------------------------------------ ..
.. include:: snippets/Header2Algo03Chck.rst
+.. include:: snippets/EnsembleOfSnapshots.rst
+
.. include:: snippets/QualityCriterion.rst
.. include:: snippets/SampleAsExplicitHyperCube.rst
:maxdepth: 1
ref_algorithm_EnsembleOfSimulationGenerationTask
+ ref_algorithm_InterpolationByReducedModelTask
ref_algorithm_MeasurementsOptimalPositioningTask
ref_task_keywords
observations aux 5 points de contrôle.
Pour illustrer plus clairement le recalage effectué, en utilisant les mêmes
-informations, on peut tracer la version continue des courbes quadratiques dont
-on dispose pour l'état d'ébauche des coefficients, et pour l'état optimal des
-coefficients, en même temps que les valeurs obtenues aux points de contrôle. De plus,
-pour améliorer la lisibilité, on a retiré les traits qui joignent les
-simulations dans le graphique précédent.
+informations, on peut tracer la version "continue" des courbes quadratiques
+dont on dispose de l'état d'ébauche pour les coefficients, et de l'état optimal
+pour ces mêmes coefficients, en même temps que les valeurs obtenues aux points
+de contrôle. De plus, pour améliorer la lisibilité, on a retiré les traits qui
+joignent les simulations dans le graphique précédent.
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+from numpy import array, ravel
+def QuadFunction( coefficients ):
+ """
+ Simulation quadratique aux points x : y = a x^2 + b x + c
+ """
+ a, b, c = list(ravel(coefficients))
+ x_points = (-5, 0, 1, 3, 10)
+ y_points = []
+ for x in x_points:
+ y_points.append( a*x*x + b*x + c )
+ return array(y_points)
+#
+Xb = array([1., 1., 1.])
+Yobs = array([57, 2, 3, 17, 192])
+#
+NumberOfInsects = 40
+#
+print("Résolution du problème de calage")
+print("--------------------------------")
+print("")
+from adao import adaoBuilder
+case = adaoBuilder.New()
+case.setBackground( Vector = Xb, Stored=True )
+case.setBackgroundError( ScalarSparseMatrix = 1.e6 )
+case.setObservation( Vector = Yobs, Stored=True )
+case.setObservationError( ScalarSparseMatrix = 1. )
+case.setObservationOperator( OneFunction = QuadFunction )
+case.setAlgorithmParameters(
+ Algorithm='ParticleSwarmOptimization',
+ Parameters={
+ 'NumberOfInsects':NumberOfInsects,
+ 'MaximumNumberOfIterations': 20,
+ 'StoreSupplementaryCalculations': [
+ 'CurrentState',
+ ],
+ 'Bounds':[[0,5],[-2,2],[0,5]],
+ 'SetSeed':123456789,
+ },
+ )
+case.setObserver(
+ Info=" État intermédiaire en itération courante :",
+ Template='ValuePrinter',
+ Variable='CurrentState',
+ )
+case.execute()
+print("")
+#
+#-------------------------------------------------------------------------------
+#
+print("Calage de %i coefficients pour une forme quadratique 1D sur %i mesures"%(
+ len(case.get('Background')),
+ len(case.get('Observation')),
+ ))
+print("--------------------------------------------------------------------")
+print("")
+print("Vecteur d'observation.............:", ravel(case.get('Observation')))
+print("État d'ébauche a priori...........:", ravel(case.get('Background')))
+print("")
+print("Coefficients théoriques attendus..:", ravel((2,-1,2)))
+print("")
+print("Nombre d'itérations...............:", len(case.get('CurrentState')))
+print("Nombre de simulations.............:", NumberOfInsects*len(case.get('CurrentState')))
+print("Coefficients résultants du calage.:", ravel(case.get('Analysis')[-1]))
+#
+Xa = case.get('Analysis')[-1]
+import matplotlib.pyplot as plt
+plt.rcParams['figure.figsize'] = (10, 4)
+#
+plt.figure()
+plt.plot((-5,0,1,3,10),QuadFunction(Xb),'b-',label="Simulation à l'ébauche")
+plt.plot((-5,0,1,3,10),Yobs, 'kX',label='Observation',markersize=10)
+plt.plot((-5,0,1,3,10),QuadFunction(Xa),'r-',label="Simulation à l'optimum")
+plt.legend()
+plt.title('Calage de coefficients', fontweight='bold')
+plt.xlabel('Coordonnée arbitraire')
+plt.ylabel('Observations')
+plt.savefig("simple_ParticleSwarmOptimization1.png")
--- /dev/null
+Résolution du problème de calage
+--------------------------------
+
+ État intermédiaire en itération courante : [ 1.76770856 -1.2054263 1.22625259]
+ État intermédiaire en itération courante : [ 2.04776518 -1.17449716 3.14493347]
+ État intermédiaire en itération courante : [ 2.04776518 -1.17449716 3.14493347]
+ État intermédiaire en itération courante : [ 2.01933291 -1. 3.15162067]
+ État intermédiaire en itération courante : [ 1.96384202 -0.74855119 3.40642058]
+ État intermédiaire en itération courante : [ 1.96384202 -0.74855119 3.40642058]
+ État intermédiaire en itération courante : [ 1.96384202 -0.74855119 3.40642058]
+ État intermédiaire en itération courante : [ 1.96384202 -0.74855119 3.40642058]
+ État intermédiaire en itération courante : [ 1.95417745 -0.73191939 3.14451887]
+ État intermédiaire en itération courante : [ 1.96217646 -0.7883895 2.91127919]
+ État intermédiaire en itération courante : [ 1.97610485 -1.00254825 2.89582746]
+ État intermédiaire en itération courante : [ 2.0007262 -1.06443275 2.69825603]
+ État intermédiaire en itération courante : [ 1.9934285 -1.02432071 2.39823319]
+ État intermédiaire en itération courante : [ 1.9934285 -1.02432071 2.39823319]
+ État intermédiaire en itération courante : [ 1.9942533 -0.99256953 2.30174702]
+ État intermédiaire en itération courante : [ 1.9942533 -0.99256953 2.30174702]
+ État intermédiaire en itération courante : [ 1.99742923 -0.99796085 2.1278678 ]
+ État intermédiaire en itération courante : [ 1.99742923 -0.99796085 2.1278678 ]
+ État intermédiaire en itération courante : [ 1.99742923 -0.99796085 2.1278678 ]
+ État intermédiaire en itération courante : [ 1.99742923 -0.99796085 2.1278678 ]
+ État intermédiaire en itération courante : [ 2.00166149 -1.0012696 2.02137857]
+
+Calage de 3 coefficients pour une forme quadratique 1D sur 5 mesures
+--------------------------------------------------------------------
+
+Vecteur d'observation.............: [ 57. 2. 3. 17. 192.]
+État d'ébauche a priori...........: [1. 1. 1.]
+
+Coefficients théoriques attendus..: [ 2 -1 2]
+
+Nombre d'itérations...............: 21
+Nombre de simulations.............: 840
+Coefficients résultants du calage.: [ 2.00166149 -1.0012696 2.02137857]
--- /dev/null
+.. index:: single: 3DVAR (exemple)
+
+Cet exemple décrit le recalage des paramètres :math:`\mathbf{x}` d'un modèle
+d'observation :math:`H` quadratique. Ce modèle est représenté ici comme une
+fonction nommée ``QuadFunction``. Cette fonction accepte en entrée le vecteur
+de coefficients :math:`\mathbf{x}`, et fournit en sortie le vecteur
+:math:`\mathbf{y}` d'évaluation du modèle quadratique aux points de contrôle
+internes prédéfinis dans le modèle. Le calage s'effectue sur la base d'un jeu
+initial de coefficients (état d'ébauche désigné par ``Xb`` dans l'exemple), et
+avec l'information :math:`\mathbf{y}^o` (désignée par ``Yobs`` dans l'exemple)
+de 5 mesures obtenues à ces mêmes points de contrôle internes. On se place en
+expériences jumelles (voir :ref:`section_methodology_twin`) et les mesures sont
+parfaites. On privilégie les observations au détriment de l'ébauche par
+l'indication d'une très importante variance d'erreur d'ébauche, ici de
+:math:`10^{6}`.
+
+L'ajustement s'effectue en affichant des résultats intermédiaires lors de
+l'optimisation itérative.
Analysis
*Liste de vecteurs*. Chaque élément de cette variable est un état optimal
- :math:`\mathbf{x}^*` en optimisation ou une analyse :math:`\mathbf{x}^a` en
- assimilation de données.
+ :math:`\mathbf{x}^*` en optimisation, une interpolation ou une analyse
+ :math:`\mathbf{x}^a` en assimilation de données.
Exemple :
``Xa = ADD.get("Analysis")[-1]``
*Valeur booléenne*. La variable définit le niveau de sorties et
d'informations intermédiaires de débogage. Les choix sont limités entre 0
(pour False) et 1 (pour True).
+
+ Exemple :
+ ``{"Debug":False}``
.. index:: single: EnsembleOfSimulations
EnsembleOfSimulations
- *Liste de vecteurs ou matrice*. Chaque élément est un ensemble de vecteurs
- d'état physique ou d'état simulé :math:`\mathbf{y}` (nommés "*snapshots*" en
- terminologie de bases réduites), avec 1 état par colonne si c'est une
- matrice, ou 1 état par élément si c'est une liste. Important : la
- numérotation des points, auxquels sont fournis une valeur d'état dans chaque
- vecteur, est implicitement celle de l'ordre naturel de numérotation du
- vecteur d'état, de 0 à la "taille moins 1" de ce vecteur.
+ *Liste de vecteurs ou matrice*. Chaque élément est une collection ordonnée de
+ vecteurs d'état physique ou d'état simulé :math:`\mathbf{y}` (nommés
+ "*snapshots*" en terminologie de bases réduites), avec 1 état par colonne si
+ c'est une matrice, ou 1 état par élément si c'est une liste. Important : la
+ numérotation du support ou des points, sur lequel ou auxquels sont fournis
+ une valeur d'état dans chaque vecteur, est implicitement celle de l'ordre
+ naturel de numérotation du vecteur d'état, de 0 à la "taille moins 1" de ce
+ vecteur.
Exemple :
``{"EnsembleOfSimulations":[y1, y2, y3...]}``
.. index:: single: EnsembleOfSnapshots
EnsembleOfSnapshots
- *Liste de vecteurs ou matrice*. Cette clé contient un ensemble de vecteurs
- d'état physique :math:`\mathbf{y}` (nommés "*snapshots*" en terminologie de
- bases réduites), avec 1 état par colonne si c'est une matrice, ou 1 état par
- élément si c'est une liste. Important : la numérotation des points, auxquels
- sont fournis une valeur d'état dans chaque vecteur, est implicitement celle
- de l'ordre naturel de numérotation du vecteur d'état, de 0 à la "taille moins
- 1" de ce vecteur.
+ *Liste de vecteurs ou matrice*. Cette clé contient une collection ordonnée de
+ vecteurs d'état physique :math:`\mathbf{y}` (nommés "*snapshots*" en
+ terminologie de bases réduites), avec un état complet par colonne si c'est
+ une matrice, ou un état complet par élément si c'est une liste. Important :
+ la numérotation du support ou des points, sur lequel ou auxquels sont fournis
+ une valeur d'état dans chaque vecteur, est implicitement celle de l'ordre
+ naturel de numérotation du vecteur d'état, de 0 à la "taille moins 1" de ce
+ vecteur.
Exemple :
``{"EnsembleOfSnapshots":[y1, y2, y3...]}``
.. index:: single: EnsembleOfStates
EnsembleOfStates
- *Liste de vecteurs ou matrice*. Chaque élément est un ensemble de vecteurs
- d'état physique ou d'état paramétrique :math:`\mathbf{x}`, avec 1 état par
- colonne si c'est une matrice, ou 1 état par élément si c'est une liste.
- Important : la numérotation des points, auxquels sont fournis une valeur
- d'état dans chaque vecteur, est implicitement celle de l'ordre naturel de
- numérotation du vecteur d'état, de 0 à la "taille moins 1" de ce vecteur.
+ *Liste de vecteurs ou matrice*. Chaque élément est une collection ordonnée de
+ vecteurs d'état physique ou d'état paramétrique :math:`\mathbf{x}`, avec 1
+ état par colonne si c'est une matrice, ou 1 état par élément si c'est une
+ liste. Important : la numérotation du support ou des points, sur lequel ou
+ auxquels sont fournis une valeur d'état dans chaque vecteur, est
+ implicitement celle de l'ordre naturel de numérotation du vecteur d'état, de
+ 0 à la "taille moins 1" de ce vecteur.
Exemple :
``{"EnsembleOfStates":[x1, x2, x3...]}``
unidimensionnelle.
Exemple :
- ``mp = ADD.get("ExcludedPoints")[-1]``
+ ``ep = ADD.get("ExcludedPoints")[-1]``
"COBYLA" (minimisation, avec ou sans contraintes, par approximation linéaire, voir [Powell94]_ [Powell98]_).
"NEWUOA" (minimisation, avec ou sans contraintes, par approximation quadratique itérative, voir [Powell04]_),
"POWELL" (minimisation, sans contraintes, de type directions conjuguées, voir [Powell64]_),
- "SIMPLEX" (minimisation, avec ou sans contraintes, de type simplexe ou Nelder-Mead, voir [Nelder65]_),
- "SUBPLEX" (minimisation, avec ou sans contraintes, de type simplexe sur une suite de sous-espaces, voir [Rowan90]_).
+ "SIMPLEX" (minimisation, avec ou sans contraintes, de type Nelder-Mead utilisant le concept de simplexe, voir [Nelder65]_ et [WikipediaNM]_),
+ "SUBPLEX" (minimisation, avec ou sans contraintes, de type Nelder-Mead utilisant le concept de simplexe sur une suite de sous-espaces, voir [Rowan90]_).
Seul le minimiseur "POWELL" ne permet pas de traiter les contraintes de
bornes, tous les autres en tiennent compte si elles sont présentes dans la
définition du cas.
:header: "Outil", "Version minimale", "Version atteinte"
:widths: 20, 10, 10
- Python, 3.6.5, 3.10.11
- Numpy, 1.14.3, 1.24.3
- Scipy, 0.19.1, 1.10.1
- MatplotLib, 2.2.2, 3.7.1
+ Python, 3.6.5, 3.11.5
+ Numpy, 1.14.3, 1.26.0
+ Scipy, 0.19.1, 1.11.2
+ MatplotLib, 2.2.2, 3.8.0
GnuplotPy, 1.8, 1.8
NLopt, 2.4.2, 2.7.1
ADAO, |release|
EFICAS, |release|
SALOME, |release|
- Python, 3.6.5
- Numpy, 1.16.4
- Scipy, 1.4.1
+ Python, 3.9.2
+ Numpy, 1.19.5
+ Scipy, 1.6.0
MatplotLib, 3.3.4
Gnuplot, 1.8
- NLopt, 2.5.0
+ NLopt, 2.4.2
--- /dev/null
+.. index:: single: ObservationsAlreadyRestrictedOnOptimalLocations
+
+ObservationsAlreadyRestrictedOnOptimalLocations
+ *Valeur booléenne*. La variable définit le fait que les mesures sont fournies
+ uniquement aux positions idéales ou points optimaux auxquels une mesure est
+ requise ("True", valeur par défaut), ou qu'elles sont fournies avec sur un
+ support identique au champ complet et qu'elles doivent donc être restreintes
+ aux positions requises ("False").
+
+ Exemple :
+ ``{"ObservationsAlreadyRestrictedOnOptimalLocations":False}``
--- /dev/null
+.. index:: single: OptimalLocations
+
+OptimalLocations
+ *Liste de série d'entiers*. Chaque élément est une série, contenant les
+ indices des positions idéales ou points optimaux auxquels une mesure est
+ requise, selon l'ordre des variables d'un vecteur d'état considéré
+ arbitrairement sous forme unidimensionnelle, et dans le même ordre que les
+ vecteurs de la base réduite trouvés itérativement.
+
+ Elle est identique à une sortie unique des positions idéales ou points
+ optimaux d'un
+ :ref:`section_ref_algorithm_MeasurementsOptimalPositioningTask`.
OptimalPoints
*Liste de série d'entiers*. Chaque élément est une série, contenant les
- points idéaux déterminés par la recherche optimale, rangés par ordre de
- préférence décroissante et dans le même ordre que les vecteurs de base
- réduite trouvés itérativement.
+ indices des positions idéales ou points optimaux auxquels une mesure est
+ requise, déterminés par la recherche optimale, rangés par ordre de préférence
+ décroissante et dans le même ordre que les vecteurs de base réduite trouvés
+ itérativement.
Exemple :
- ``mp = ADD.get("OptimalPoints")[-1]``
+ ``op = ADD.get("OptimalPoints")[-1]``
ReducedBasis
*Liste de matrices*. Chaque élément est une matrice, contenant dans chaque
colonne un vecteur de la base réduite obtenue par la recherche optimale,
- rangés par ordre de préférence décroissante et dans le même ordre que les
+ rangés par ordre de préférence décroissante, et dans le même ordre que les
points idéaux trouvés itérativement.
+ Lorsque c'est une donnée d'entrée, elle est identique à une sortie unique
+ d'un :ref:`section_ref_algorithm_MeasurementsOptimalPositioningTask`.
+
Exemple :
``rb = ADD.get("ReducedBasis")[-1]``
<parameter name="icon" value="ADAO.png"/>
<parameter name="library" value="SalomePyQtGUI"/>
<parameter name="documentation" value="adao_help"/>
- <parameter name="version" value="9.11.0"/>
+ <parameter name="version" value="9.12.0"/>
<!-- parameter name="description" value="Calibrate numerical simulations, interpolate measurements, combine data and calculations, optimize trajectories, verify and validate models"/ -->
<!-- parameter name="description" value="Recaler les simulations numériques, interpoler des mesures, combiner des données et des calculs, optimiser des trajectoires, vérifier et valider des modèles"/ -->
</section>
"LBFGSB",
"TNC",
"CG",
- "NCG",
"BFGS",
],
+ listadv = [
+ "NCG",
+ ],
)
self.defineRequiredParameter(
name = "EstimationOf",
default = "LBFGSB",
typecast = str,
message = "Minimiseur utilisé",
- listval = ["LBFGSB","TNC", "CG", "NCG", "BFGS"],
+ listval = [
+ "LBFGSB",
+ "TNC",
+ "CG",
+ "BFGS",
+ ],
+ listadv = [
+ "NCG",
+ ],
)
self.defineRequiredParameter(
name = "MaximumNumberOfIterations",
# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
import numpy
-from daCore import BasicObjects, NumericObjects, PlatformInfo
-mpr = PlatformInfo.PlatformInfo().MachinePrecision()
-mfp = PlatformInfo.PlatformInfo().MaximumPrecision()
+from daCore import BasicObjects, NumericObjects
+from daCore.PlatformInfo import PlatformInfo, vfloat
+mpr = PlatformInfo().MachinePrecision()
+mfp = PlatformInfo().MaximumPrecision()
# ==============================================================================
class ElementaryAlgorithm(BasicObjects.Algorithm):
TangentFXdX = numpy.ravel( Ht( (X0,dX) ) )
AdjointFXY = numpy.ravel( Ha( (X0,Yn) ) )
#
- Residu = abs(float(numpy.dot( TangentFXdX, Yn ) - numpy.dot( dX, AdjointFXY )))
+ Residu = abs(vfloat(numpy.dot( TangentFXdX, Yn ) - numpy.dot( dX, AdjointFXY )))
#
self.StoredVariables["Residu"].store( Residu )
ttsep = __ms%(i,amplitude,NormeX,NormeY,NormedX,Residu)
import math, numpy, scipy
from daCore.NumericObjects import ApplyBounds, ForceNumericBounds
-from daCore.PlatformInfo import PlatformInfo
+from daCore.PlatformInfo import PlatformInfo, vfloat
mpr = PlatformInfo().MachinePrecision()
mfp = PlatformInfo().MaximumPrecision()
or selfA._toStore("CostFunctionJo") \
or selfA._toStore("CurrentOptimum") \
or selfA._toStore("APosterioriCovariance"):
- Jb = float( 0.5 * (Xa - Xb).T * (BI * (Xa - Xb)) )
- Jo = float( 0.5 * _Innovation.T * (RI * _Innovation) )
+ Jb = vfloat( 0.5 * (Xa - Xb).T * (BI * (Xa - Xb)) )
+ Jo = vfloat( 0.5 * _Innovation.T * (RI * _Innovation) )
J = Jb + Jo
selfA.StoredVariables["CostFunctionJb"].store( Jb )
selfA.StoredVariables["CostFunctionJo"].store( Jo )
import numpy
from daCore.NumericObjects import ApplyBounds, ForceNumericBounds
-from daCore.PlatformInfo import PlatformInfo
+from daCore.PlatformInfo import PlatformInfo, vfloat
mpr = PlatformInfo().MachinePrecision()
mfp = PlatformInfo().MaximumPrecision()
or selfA._toStore("CostFunctionJo") \
or selfA._toStore("CurrentOptimum") \
or selfA._toStore("APosterioriCovariance"):
- Jb = float( 0.5 * (Xa - Xb).T @ (BI @ (Xa - Xb)) )
- Jo = float( 0.5 * _Innovation.T @ (RI @ _Innovation) )
+ Jb = vfloat( 0.5 * (Xa - Xb).T @ (BI @ (Xa - Xb)) )
+ Jo = vfloat( 0.5 * _Innovation.T @ (RI @ _Innovation) )
J = Jb + Jo
selfA.StoredVariables["CostFunctionJb"].store( Jb )
selfA.StoredVariables["CostFunctionJo"].store( Jo )
import numpy
from daCore.NumericObjects import ApplyBounds, ForceNumericBounds
-from daCore.PlatformInfo import PlatformInfo
+from daCore.PlatformInfo import PlatformInfo, vfloat
mpr = PlatformInfo().MachinePrecision()
mfp = PlatformInfo().MaximumPrecision()
or selfA._toStore("CostFunctionJo") \
or selfA._toStore("CurrentOptimum") \
or selfA._toStore("APosterioriCovariance"):
- Jb = float( 0.5 * (Xa - Xb).T @ (BI @ (Xa - Xb)) )
- Jo = float( 0.5 * _Innovation.T @ (RI @ _Innovation) )
+ Jb = vfloat( 0.5 * (Xa - Xb).T @ (BI @ (Xa - Xb)) )
+ Jo = vfloat( 0.5 * _Innovation.T @ (RI @ _Innovation) )
J = Jb + Jo
selfA.StoredVariables["CostFunctionJb"].store( Jb )
selfA.StoredVariables["CostFunctionJo"].store( Jo )
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+__doc__ = """
+ Standard Particle Swarm Optimization 2011 (AIS)
+"""
+__author__ = "Jean-Philippe ARGAUD"
+
+import numpy, logging, copy, math
+from daCore.NumericObjects import ApplyBounds, VariablesAndIncrementsBounds
+from daCore.NumericObjects import GenerateRandomPointInHyperSphere
+from daCore.NumericObjects import GetNeighborhoodTopology
+from daCore.PlatformInfo import vfloat
+from numpy.random import uniform as rand
+
+# ==============================================================================
+def ecwapso(selfA, Xb, Y, HO, R, B):
+ #
+ Hm = HO["Direct"].appliedTo
+ #
+ BI = B.getI()
+ RI = R.getI()
+ #
+ Xini = selfA._parameters["InitializationPoint"]
+ #
+ Bounds, BoxBounds = VariablesAndIncrementsBounds(
+ selfA._parameters["Bounds"],
+ selfA._parameters["BoxBounds"],
+ Xini,
+ selfA._name,
+ 0.5,
+ )
+ #
+ def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
+ _X = numpy.asarray( x ).reshape((-1,1))
+ _HX = numpy.asarray( Hm( _X ) ).reshape((-1,1))
+ _Innovation = Y - _HX
+ #
+ if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","DA"]:
+ if BI is None or RI is None:
+ raise ValueError("Background and Observation error covariance matrices has to be properly defined!")
+ Jb = 0.5 * (_X - Xb).T @ (BI @ (_X - Xb))
+ Jo = 0.5 * _Innovation.T @ (RI @ _Innovation)
+ elif QualityMeasure in ["WeightedLeastSquares","WLS"]:
+ if RI is None:
+ raise ValueError("Observation error covariance matrix has to be properly defined!")
+ Jb = 0.
+ Jo = 0.5 * _Innovation.T @ (RI @ _Innovation)
+ elif QualityMeasure in ["LeastSquares","LS","L2"]:
+ Jb = 0.
+ Jo = 0.5 * _Innovation.T @ _Innovation
+ elif QualityMeasure in ["AbsoluteValue","L1"]:
+ Jb = 0.
+ Jo = numpy.sum( numpy.abs(_Innovation) )
+ elif QualityMeasure in ["MaximumError","ME", "Linf"]:
+ Jb = 0.
+ Jo = numpy.max( numpy.abs(_Innovation) )
+ #
+ J = vfloat( Jb ) + vfloat( Jo )
+ #
+ return J, vfloat( Jb ), vfloat( Jo )
+ #
+ def KeepRunningCondition(__step, __nbfct):
+ if __step >= selfA._parameters["MaximumNumberOfIterations"]:
+ logging.debug("%s Stopping search because the number %i of evolving iterations is exceeding the maximum %i."%(selfA._name, __step, selfA._parameters["MaximumNumberOfIterations"]))
+ return False
+ elif __nbfct >= selfA._parameters["MaximumNumberOfFunctionEvaluations"]:
+ logging.debug("%s Stopping search because the number %i of function evaluations is exceeding the maximum %i."%(selfA._name, __nbfct, selfA._parameters["MaximumNumberOfFunctionEvaluations"]))
+ return False
+ else:
+ return True
+ #
+ # Paramètres internes
+ # -------------------
+ __nbI = selfA._parameters["NumberOfInsects"]
+ __nbP = len(Xini) # Dimension ou nombre de paramètres
+ #
+ __iw = float( selfA._parameters["InertiaWeight"] )
+ __sa = float( selfA._parameters["SocialAcceleration"] )
+ __ca = float( selfA._parameters["CognitiveAcceleration"] )
+ __vc = float( selfA._parameters["VelocityClampingFactor"] )
+ logging.debug("%s Cognitive acceleration (recall to the best previously known value of the insect) = %s"%(selfA._name, str(__ca)))
+ logging.debug("%s Social acceleration (recall to the best insect value of the group) = %s"%(selfA._name, str(__sa)))
+ logging.debug("%s Inertial weight = %s"%(selfA._name, str(__iw)))
+ logging.debug("%s Velocity clamping factor = %s"%(selfA._name, str(__vc)))
+ #
+ # Initialisation de l'essaim
+ # --------------------------
+ LimitPlace = Bounds
+ LimitSpeed = BoxBounds
+ #
+ nbfct = 1 # Nb d'évaluations
+ JXini, JbXini, JoXini = CostFunction(Xini,selfA._parameters["QualityCriterion"])
+ #
+ Swarm = numpy.zeros((__nbI,4,__nbP)) # 4 car (x,v,gbest,lbest)
+ for __p in range(__nbP) :
+ Swarm[:,0,__p] = rand( low=LimitPlace[__p,0], high=LimitPlace[__p,1], size=__nbI) # Position
+ Swarm[:,1,__p] = rand( low=LimitSpeed[__p,0], high=LimitSpeed[__p,1], size=__nbI) # Velocity
+ logging.debug("%s Initialisation of the swarm with %i insects of size %i "%(selfA._name,Swarm.shape[0],Swarm.shape[2]))
+ #
+ __nbh = GetNeighborhoodTopology( selfA._parameters["SwarmTopology"], list(range(__nbI)) )
+ #
+ qSwarm = JXini * numpy.ones((__nbI,6)) # Qualités (J, Jb, Jo) par insecte + par voisinage
+ for __i in range(__nbI):
+ nbfct += 1
+ JTest, JbTest, JoTest = CostFunction(Swarm[__i,0,:],selfA._parameters["QualityCriterion"])
+ if JTest < JXini:
+ Swarm[__i,2,:] = Swarm[__i,0,:] # xBest
+ qSwarm[__i,:3] = (JTest, JbTest, JoTest)
+ else:
+ Swarm[__i,2,:] = Xini # xBest
+ qSwarm[__i,:3] = (JXini, JbXini, JoXini)
+ logging.debug("%s Initialisation of the best previous insects"%selfA._name)
+ #
+ iBest = numpy.argmin(qSwarm[:,0])
+ xBest = Swarm[iBest,2,:]
+ for __i in range(__nbI):
+ Swarm[__i,3,:] = xBest # lBest
+ qSwarm[__i,3:] = qSwarm[iBest,:3]
+ if selfA._parameters["StoreInternalVariables"] or selfA._toStore("CurrentState"):
+ selfA.StoredVariables["CurrentState"].store( xBest )
+ selfA.StoredVariables["CostFunctionJ" ].store( qSwarm[iBest,0] )
+ selfA.StoredVariables["CostFunctionJb"].store( qSwarm[iBest,1] )
+ selfA.StoredVariables["CostFunctionJo"].store( qSwarm[iBest,2] )
+ if selfA._parameters["StoreInternalVariables"] or selfA._toStore("InternalStates"):
+ selfA.StoredVariables["InternalStates"].store( Swarm[:,0,:].T )
+ if selfA._parameters["StoreInternalVariables"] or selfA._toStore("InternalCostFunctionJ"):
+ selfA.StoredVariables["InternalCostFunctionJ"].store( qSwarm[:,0] )
+ if selfA._parameters["StoreInternalVariables"] or selfA._toStore("InternalCostFunctionJb"):
+ selfA.StoredVariables["InternalCostFunctionJb"].store( qSwarm[:,1] )
+ if selfA._parameters["StoreInternalVariables"] or selfA._toStore("InternalCostFunctionJo"):
+ selfA.StoredVariables["InternalCostFunctionJo"].store( qSwarm[:,2] )
+ #
+ selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["CostFunctionJ"]) )
+ #
+ # Minimisation de la fonctionnelle
+ # --------------------------------
+ step = 0
+ while KeepRunningCondition(step, nbfct):
+ step += 1
+ for __i in range(__nbI):
+ __rct = rand(size=__nbP)
+ __rst = rand(size=__nbP)
+ __xPoint = Swarm[__i,0,:]
+ # Points
+ __pPoint = __xPoint + __ca * __rct * (Swarm[__i,2,:] - __xPoint)
+ __lPoint = __xPoint + __sa * __rst * (Swarm[__i,3,:] - __xPoint)
+ __gPoint = (__xPoint + __pPoint + __lPoint) / 3
+ __radius = numpy.linalg.norm(__gPoint - __xPoint)
+ __rPoint = GenerateRandomPointInHyperSphere( __gPoint, __radius )
+ # Maj vitesse
+ __value = __iw * Swarm[__i,1,:] + __rPoint - __xPoint
+ Swarm[__i,1,:] = ApplyBounds( __value, LimitSpeed )
+ # Maj position
+ __value = __xPoint + Swarm[__i,1,:]
+ Swarm[__i,0,:] = ApplyBounds( __value, LimitPlace )
+ #
+ nbfct += 1
+ # Évalue
+ JTest, JbTest, JoTest = CostFunction(__xPoint,selfA._parameters["QualityCriterion"])
+ # Maj lbest
+ if JTest < qSwarm[__i,0]:
+ Swarm[__i,2,:] = Swarm[__i,0,:]
+ qSwarm[__i,:3] = (JTest, JbTest, JoTest)
+ #
+ for __i in range(__nbI):
+ # Maj gbest
+ __im = numpy.argmin( [qSwarm[__v,0] for __v in __nbh[__i]] )
+ __il = __nbh[__i][__im] # Best in NB
+ if qSwarm[__il,0] < qSwarm[__i,3]:
+ Swarm[__i,3,:] = Swarm[__il,2,:] # lBest
+ qSwarm[__i,3:] = qSwarm[__il,:3]
+ #
+ iBest = numpy.argmin(qSwarm[:,0])
+ xBest = Swarm[iBest,2,:]
+ selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["CostFunctionJ"]) )
+ if selfA._parameters["StoreInternalVariables"] or selfA._toStore("CurrentState"):
+ selfA.StoredVariables["CurrentState"].store( xBest )
+ if selfA._toStore("SimulatedObservationAtCurrentState"):
+ selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( Hm( xBest ) )
+ selfA.StoredVariables["CostFunctionJ" ].store( qSwarm[iBest,0] )
+ selfA.StoredVariables["CostFunctionJb"].store( qSwarm[iBest,1] )
+ selfA.StoredVariables["CostFunctionJo"].store( qSwarm[iBest,2] )
+ if selfA._parameters["StoreInternalVariables"] or selfA._toStore("InternalStates"):
+ selfA.StoredVariables["InternalStates"].store( Swarm[:,0,:].T )
+ if selfA._parameters["StoreInternalVariables"] or selfA._toStore("InternalCostFunctionJ"):
+ selfA.StoredVariables["InternalCostFunctionJ"].store( qSwarm[:,0] )
+ if selfA._parameters["StoreInternalVariables"] or selfA._toStore("InternalCostFunctionJb"):
+ selfA.StoredVariables["InternalCostFunctionJb"].store( qSwarm[:,1] )
+ if selfA._parameters["StoreInternalVariables"] or selfA._toStore("InternalCostFunctionJo"):
+ selfA.StoredVariables["InternalCostFunctionJo"].store( qSwarm[:,2] )
+ logging.debug("%s Step %i: insect %i is the better one with J =%.7f"%(selfA._name,step,iBest,qSwarm[iBest,0]))
+ #
+ # Obtention de l'analyse
+ # ----------------------
+ Xa = xBest
+ #
+ selfA.StoredVariables["Analysis"].store( Xa )
+ #
+ # Calculs et/ou stockages supplémentaires
+ # ---------------------------------------
+ if selfA._toStore("OMA") or \
+ selfA._toStore("SimulatedObservationAtOptimum"):
+ HXa = Hm(Xa)
+ if selfA._toStore("Innovation") or \
+ selfA._toStore("OMB") or \
+ selfA._toStore("SimulatedObservationAtBackground"):
+ HXb = Hm(Xb)
+ Innovation = Y - HXb
+ if selfA._toStore("Innovation"):
+ selfA.StoredVariables["Innovation"].store( Innovation )
+ if selfA._toStore("OMB"):
+ selfA.StoredVariables["OMB"].store( Innovation )
+ if selfA._toStore("BMA"):
+ selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
+ if selfA._toStore("OMA"):
+ selfA.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
+ if selfA._toStore("SimulatedObservationAtBackground"):
+ selfA.StoredVariables["SimulatedObservationAtBackground"].store( HXb )
+ if selfA._toStore("SimulatedObservationAtOptimum"):
+ selfA.StoredVariables["SimulatedObservationAtOptimum"].store( HXa )
+ #
+ selfA._post_run(HO)
+ return 0
+
+# ==============================================================================
+if __name__ == "__main__":
+ print('\n AUTODIAGNOSTIC\n')
import logging, numpy
from daCore.NumericObjects import QuantilesEstimations
-from daCore.PlatformInfo import PlatformInfo
+from daCore.PlatformInfo import PlatformInfo, vfloat
mpr = PlatformInfo().MachinePrecision()
# ==============================================================================
selfA._toStore("CostFunctionJb") or selfA._toStore("CostFunctionJbAtCurrentOptimum") or \
selfA._toStore("CostFunctionJo") or selfA._toStore("CostFunctionJoAtCurrentOptimum") or \
selfA._toStore("MahalanobisConsistency"):
- Jb = float( 0.5 * (Xa - Xb).T @ (BI @ (Xa - Xb)) )
- Jo = float( 0.5 * oma.T * (RI * oma) )
+ Jb = vfloat( 0.5 * (Xa - Xb).T @ (BI @ (Xa - Xb)) )
+ Jo = vfloat( 0.5 * oma.T * (RI * oma) )
J = Jb + Jo
selfA.StoredVariables["CostFunctionJb"].store( Jb )
selfA.StoredVariables["CostFunctionJo"].store( Jo )
if min(A.shape) != max(A.shape):
raise ValueError("The %s a posteriori covariance matrix A is of shape %s, despites it has to be a squared matrix. There is an error in the observation operator, please check it."%(selfA._name,str(A.shape)))
if (numpy.diag(A) < 0).any():
- raise ValueError("The %s a posteriori covariance matrix A has at least one negative value on its diagonal. There is an error in the observation operator, please check it."%(selfA._name,))
+ raise ValueError("The %s a posteriori covariance matrix A has at least one negative value %.2e on its diagonal. There is an error in the observation operator or in the covariances, please check them."%(selfA._name,min(numpy.diag(A))))
if logging.getLogger().level < logging.WARNING: # La vérification n'a lieu qu'en debug
try:
numpy.linalg.cholesky( A )
selfA.StoredVariables["OMB"].store( Innovation )
if selfA._toStore("SigmaObs2"):
TraceR = R.trace(Y.size)
- selfA.StoredVariables["SigmaObs2"].store( float( Innovation.T @ oma ) / TraceR )
+ selfA.StoredVariables["SigmaObs2"].store( vfloat( Innovation.T @ oma ) / TraceR )
if selfA._toStore("SigmaBck2"):
- selfA.StoredVariables["SigmaBck2"].store( float( (Innovation.T @ (Hm @ (numpy.ravel(Xa) - numpy.ravel(Xb))))/(Hm * (B * Hm.T)).trace() ) )
+ selfA.StoredVariables["SigmaBck2"].store( vfloat( (Innovation.T @ (Hm @ (numpy.ravel(Xa) - numpy.ravel(Xb))))/(Hm * (B * Hm.T)).trace() ) )
if selfA._toStore("MahalanobisConsistency"):
selfA.StoredVariables["MahalanobisConsistency"].store( float( 2.*J/Innovation.size ) )
if selfA._toStore("SimulationQuantiles"):
# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
__doc__ = """
- EIM & lcEIM
+ Empirical Interpolation Method EIM & lcEIM
"""
__author__ = "Jean-Philippe ARGAUD"
-import numpy
+import numpy, logging
import daCore.Persistence
from daCore.NumericObjects import FindIndexesFromNames
# ==============================================================================
def EIM_offline(selfA, EOS = None, Verbose = False):
"""
- Établissement de base par Empirical Interpolation Method (EIM)
+ Établissement de la base
"""
#
# Initialisations
else:
raise ValueError("EnsembleOfSnapshots has to be an array/matrix (each column being a vector) or a list/tuple (each element being a vector).")
__dimS, __nbmS = __EOS.shape
+ logging.debug("%s Building a RB using a collection of %i snapshots of individual size of %i"%(selfA._name,__nbmS,__dimS))
#
if selfA._parameters["ErrorNorm"] == "L2":
MaxNormByColumn = MaxL2NormByColumn
else:
MaxNormByColumn = MaxLinfNormByColumn
#
- if selfA._parameters["Variant"] == "PositioningByEIM":
+ if selfA._parameters["Variant"] in ["EIM", "PositioningByEIM"]:
__LcCsts = False
else:
__LcCsts = True
#
__mu = []
__I = []
- __Q = numpy.empty(__dimS)
+ __Q = numpy.empty(__dimS).reshape((-1,1))
__errors = []
#
__M = 0
if __M > 1:
__Q = numpy.column_stack((__Q, __rhoM))
else:
- __Q = __rhoM
+ __Q = __rhoM.reshape((-1,1))
__I.append(__iM)
#
- __restrictedQi = __Q[__I]
+ __restrictedQi = __Q[__I,:]
if __M > 1:
__Qi_inv = numpy.linalg.inv(__restrictedQi)
else:
__Qi_inv = 1. / __restrictedQi
#
- __restrictedEOSi = __EOS[__I]
+ __restrictedEOSi = __EOS[__I,:]
#
__interpolator = numpy.empty(__EOS.shape)
if __M > 1:
__residuM = __dataForNextIter[:,__muM]
#
#--------------------------
+ if __eM < selfA._parameters["EpsilonEIM"]:
+ logging.debug("%s %s (%.1e)"%(selfA._name,"The convergence is obtained when reaching the required EIM tolerance",selfA._parameters["EpsilonEIM"]))
+ if __M >= __maxM:
+ logging.debug("%s %s (%i)"%(selfA._name,"The convergence is obtained when reaching the maximum number of RB dimension",__maxM))
+ logging.debug("%s The RB of size %i has been correctly build"%(selfA._name,__Q.shape[1]))
+ logging.debug("%s There are %i points that have been excluded from the potential optimal points"%(selfA._name,len(__ExcludedMagicPoints)))
if hasattr(selfA, "StoredVariables"):
selfA.StoredVariables["OptimalPoints"].store( __I )
if selfA._toStore("ReducedBasis"):
return __mu, __I, __Q, __errors
# ==============================================================================
-def EIM_online(selfA, QEIM, mu, iEIM):
- raise NotImplementedError()
+def EIM_online(selfA, QEIM, gJmu = None, mPoints = None, mu = None, PseudoInverse = True, rbDimension = None, Verbose = False):
+ """
+ Reconstruction du champ complet
+ """
+ if gJmu is None and mu is None:
+ raise ValueError("Either measurements or parameters has to be given as a list, both can not be None simultaneously.")
+ if mPoints is None:
+ raise ValueError("List of optimal locations for measurements has to be given.")
+ if gJmu is not None:
+ if len(gJmu) > len(mPoints):
+ raise ValueError("The number of measurements (%i) has to be less or equal to the number of optimal locations (%i)."%(len(gJmu),len(mPoints)))
+ if len(gJmu) > QEIM.shape[1]:
+ raise ValueError("The number of measurements (%i) in optimal locations has to be less or equal to the dimension of the RB (%i)."%(len(gJmu),QEIM.shape[1]))
+ __gJmu = numpy.ravel(gJmu)
+ if mu is not None:
+ # __gJmu = H(mu)
+ raise NotImplementedError()
+ if rbDimension is not None:
+ rbDimension = min(QEIM.shape[1], rbDimension)
+ else:
+ rbDimension = QEIM.shape[1]
+ __rbDim = min(QEIM.shape[1],len(mPoints),len(gJmu),rbDimension) # Modulation
+ #--------------------------
+ #
+ # Restriction aux mesures
+ if PseudoInverse:
+ __QJinv = numpy.linalg.pinv( QEIM[mPoints,0:__rbDim] )
+ __gammaMu = numpy.dot( __QJinv, __gJmu[0:__rbDim])
+ else:
+ __gammaMu = numpy.linalg.solve( QEIM[mPoints,0:__rbDim], __gJmu[0:__rbDim] )
+ #
+ # Interpolation du champ complet
+ __gMmu = numpy.dot( QEIM[:,0:__rbDim], __gammaMu )
+ #
+ #--------------------------
+ logging.debug("%s The full field of size %i has been correctly build"%(selfA._name,__gMmu.size))
+ if hasattr(selfA, "StoredVariables"):
+ selfA.StoredVariables["Analysis"].store( __gMmu )
+ #
+ return __gMmu
# ==============================================================================
def MaxL2NormByColumn(Ensemble, LcCsts = False, IncludedPoints = []):
import logging, numpy
from daCore.NumericObjects import QuantilesEstimations
-from daCore.PlatformInfo import PlatformInfo
+from daCore.PlatformInfo import PlatformInfo, vfloat
mpr = PlatformInfo().MachinePrecision()
# ==============================================================================
selfA._toStore("CostFunctionJb") or selfA._toStore("CostFunctionJbAtCurrentOptimum") or \
selfA._toStore("CostFunctionJo") or selfA._toStore("CostFunctionJoAtCurrentOptimum") or \
selfA._toStore("MahalanobisConsistency"):
- Jb = float( 0.5 * (Xa - Xb).T @ (BI @ (Xa - Xb)) )
- Jo = float( 0.5 * oma.T * (RI * oma) )
+ Jb = vfloat( 0.5 * (Xa - Xb).T @ (BI @ (Xa - Xb)) )
+ Jo = vfloat( 0.5 * oma.T * (RI * oma) )
J = Jb + Jo
selfA.StoredVariables["CostFunctionJb"].store( Jb )
selfA.StoredVariables["CostFunctionJo"].store( Jo )
if min(A.shape) != max(A.shape):
raise ValueError("The %s a posteriori covariance matrix A is of shape %s, despites it has to be a squared matrix. There is an error in the observation operator, please check it."%(selfA._name,str(A.shape)))
if (numpy.diag(A) < 0).any():
- raise ValueError("The %s a posteriori covariance matrix A has at least one negative value on its diagonal. There is an error in the observation operator, please check it."%(selfA._name,))
+ raise ValueError("The %s a posteriori covariance matrix A has at least one negative value %.2e on its diagonal. There is an error in the observation operator or in the covariances, please check them."%(selfA._name,min(numpy.diag(A))))
if logging.getLogger().level < logging.WARNING: # La vérification n'a lieu qu'en debug
try:
numpy.linalg.cholesky( A )
selfA.StoredVariables["OMB"].store( Innovation )
if selfA._toStore("SigmaObs2"):
TraceR = R.trace(Y.size)
- selfA.StoredVariables["SigmaObs2"].store( float( Innovation.T @ oma ) / TraceR )
+ selfA.StoredVariables["SigmaObs2"].store( vfloat( Innovation.T @ oma ) / TraceR )
if selfA._toStore("SigmaBck2"):
- selfA.StoredVariables["SigmaBck2"].store( float( (Innovation.T @ (Hm @ (numpy.ravel(Xa) - numpy.ravel(Xb))))/(Hm * (B * Hm.T)).trace() ) )
+ selfA.StoredVariables["SigmaBck2"].store( vfloat( (Innovation.T @ (Hm @ (numpy.ravel(Xa) - numpy.ravel(Xb))))/(Hm * (B * Hm.T)).trace() ) )
if selfA._toStore("MahalanobisConsistency"):
selfA.StoredVariables["MahalanobisConsistency"].store( float( 2.*J/Innovation.size ) )
if selfA._toStore("SimulationQuantiles"):
"""
__author__ = "Jean-Philippe ARGAUD"
+from daCore.PlatformInfo import vfloat
+
# ==============================================================================
def ecwlls(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False):
"""
selfA._toStore("CostFunctionJb") or selfA._toStore("CostFunctionJbAtCurrentOptimum") or \
selfA._toStore("CostFunctionJo") or selfA._toStore("CostFunctionJoAtCurrentOptimum"):
Jb = 0.
- Jo = float( 0.5 * oma.T * (RI * oma) )
+ Jo = vfloat( 0.5 * oma.T * (RI * oma) )
J = Jb + Jo
selfA.StoredVariables["CostFunctionJb"].store( Jb )
selfA.StoredVariables["CostFunctionJo"].store( Jo )
__author__ = "Jean-Philippe ARGAUD"
import numpy, scipy, scipy.optimize, scipy.version
-from daCore.PlatformInfo import vt
+from daCore.PlatformInfo import vt, vfloat
# ==============================================================================
def ecwnlls(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False):
selfA.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
#
Jb = 0.
- Jo = float( 0.5 * _Innovation.T * (RI * _Innovation) )
+ Jo = vfloat( 0.5 * _Innovation.T * (RI * _Innovation) )
J = Jb + Jo
#
selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["CostFunctionJ"]) )
_HX = Hm( _X ).reshape((-1,1))
_Innovation = Y - _HX
Jb = 0.
- Jo = float( 0.5 * _Innovation.T * (RI * _Innovation) )
+ Jo = vfloat( 0.5 * _Innovation.T * (RI * _Innovation) )
J = Jb + Jo
if selfA._parameters["StoreInternalVariables"] or \
selfA._toStore("CurrentState"):
import daAlgorithms.Atoms.lbfgsb18hlt as optimiseur
elif vt("1.9.0") <= vt(scipy.version.version) <= vt("1.10.99"):
import daAlgorithms.Atoms.lbfgsb19hlt as optimiseur
+ elif vt("1.11.0") <= vt(scipy.version.version) <= vt("1.11.99"):
+ import daAlgorithms.Atoms.lbfgsb111hlt as optimiseur
else:
import scipy.optimize as optimiseur
Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
import numpy, logging, copy
from daCore.NumericObjects import ApplyBounds, VariablesAndIncrementsBounds
+from daCore.PlatformInfo import vfloat
from numpy.random import uniform as rand
# ==============================================================================
Jb = 0.
Jo = numpy.max( numpy.abs(_Innovation) )
#
- J = float( Jb ) + float( Jo )
+ J = vfloat( Jb ) + vfloat( Jo )
#
- return J, float( Jb ), float( Jo )
+ return J, vfloat( Jb ), vfloat( Jo )
#
def KeepRunningCondition(__step, __nbfct):
if __step >= selfA._parameters["MaximumNumberOfIterations"]:
__vc = float( selfA._parameters["VelocityClampingFactor"] )
logging.debug("%s Cognitive acceleration (recall to the best previously known value of the insect) = %s"%(selfA._name, str(__ca)))
logging.debug("%s Social acceleration (recall to the best insect value of the group) = %s"%(selfA._name, str(__sa)))
+ logging.debug("%s Inertial weight = %s"%(selfA._name, str(__iw)))
logging.debug("%s Velocity clamping factor = %s"%(selfA._name, str(__vc)))
#
# Initialisation de l'essaim
import numpy, logging, copy
from daCore.NumericObjects import VariablesAndIncrementsBounds
+from daCore.PlatformInfo import vfloat
from numpy.random import uniform as rand
# ==============================================================================
Jb = 0.
Jo = numpy.max( numpy.abs(_Innovation) )
#
- J = float( Jb ) + float( Jo )
+ J = vfloat( Jb ) + vfloat( Jo )
#
- return J, float( Jb ), float( Jo )
+ return J, vfloat( Jb ), vfloat( Jo )
#
def KeepRunningCondition(__step, __nbfct):
if __step >= selfA._parameters["MaximumNumberOfIterations"]:
__vc = float( selfA._parameters["VelocityClampingFactor"] )
logging.debug("%s Cognitive acceleration (recall to the best previously known value of the insect) = %s"%(selfA._name, str(__ca)))
logging.debug("%s Social acceleration (recall to the best insect value of the group) = %s"%(selfA._name, str(__sa)))
+ logging.debug("%s Inertial weight = %s"%(selfA._name, str(__iw)))
logging.debug("%s Velocity clamping factor = %s"%(selfA._name, str(__vc)))
#
# Initialisation de l'essaim
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+__doc__ = """
+ Standard Particle Swarm Optimization 2011 (//SIS)
+"""
+__author__ = "Jean-Philippe ARGAUD"
+
+import numpy, logging, copy, math
+from daCore.NumericObjects import ApplyBounds, VariablesAndIncrementsBounds
+from daCore.NumericObjects import GenerateRandomPointInHyperSphere
+from daCore.NumericObjects import GetNeighborhoodTopology
+from daCore.PlatformInfo import vfloat
+from numpy.random import uniform as rand
+
+# ==============================================================================
+def ecwpspso(selfA, Xb, Y, HO, R, B):
+ #
+ Hm = HO["Direct"].appliedTo
+ #
+ BI = B.getI()
+ RI = R.getI()
+ #
+ Xini = selfA._parameters["InitializationPoint"]
+ #
+ Bounds, BoxBounds = VariablesAndIncrementsBounds(
+ selfA._parameters["Bounds"],
+ selfA._parameters["BoxBounds"],
+ Xini,
+ selfA._name,
+ 0.5,
+ )
+ #
+ def CostFunction(x, hm, QualityMeasure="AugmentedWeightedLeastSquares"):
+ _X = numpy.asarray( x ).reshape((-1,1))
+ _HX = numpy.asarray( hm ).reshape((-1,1))
+ _Innovation = Y - _HX
+ #
+ if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","DA"]:
+ if BI is None or RI is None:
+ raise ValueError("Background and Observation error covariance matrices has to be properly defined!")
+ Jb = 0.5 * (_X - Xb).T @ (BI @ (_X - Xb))
+ Jo = 0.5 * _Innovation.T @ (RI @ _Innovation)
+ elif QualityMeasure in ["WeightedLeastSquares","WLS"]:
+ if RI is None:
+ raise ValueError("Observation error covariance matrix has to be properly defined!")
+ Jb = 0.
+ Jo = 0.5 * _Innovation.T @ (RI @ _Innovation)
+ elif QualityMeasure in ["LeastSquares","LS","L2"]:
+ Jb = 0.
+ Jo = 0.5 * _Innovation.T @ _Innovation
+ elif QualityMeasure in ["AbsoluteValue","L1"]:
+ Jb = 0.
+ Jo = numpy.sum( numpy.abs(_Innovation) )
+ elif QualityMeasure in ["MaximumError","ME", "Linf"]:
+ Jb = 0.
+ Jo = numpy.max( numpy.abs(_Innovation) )
+ #
+ J = vfloat( Jb ) + vfloat( Jo )
+ #
+ return J, vfloat( Jb ), vfloat( Jo )
+ #
+ def KeepRunningCondition(__step, __nbfct):
+ if __step >= selfA._parameters["MaximumNumberOfIterations"]:
+ logging.debug("%s Stopping search because the number %i of evolving iterations is exceeding the maximum %i."%(selfA._name, __step, selfA._parameters["MaximumNumberOfIterations"]))
+ return False
+ elif __nbfct >= selfA._parameters["MaximumNumberOfFunctionEvaluations"]:
+ logging.debug("%s Stopping search because the number %i of function evaluations is exceeding the maximum %i."%(selfA._name, __nbfct, selfA._parameters["MaximumNumberOfFunctionEvaluations"]))
+ return False
+ else:
+ return True
+ #
+ # Paramètres internes
+ # -------------------
+ __nbI = selfA._parameters["NumberOfInsects"]
+ __nbP = len(Xini) # Dimension ou nombre de paramètres
+ #
+ __iw = float( selfA._parameters["InertiaWeight"] )
+ __sa = float( selfA._parameters["SocialAcceleration"] )
+ __ca = float( selfA._parameters["CognitiveAcceleration"] )
+ __vc = float( selfA._parameters["VelocityClampingFactor"] )
+ logging.debug("%s Cognitive acceleration (recall to the best previously known value of the insect) = %s"%(selfA._name, str(__ca)))
+ logging.debug("%s Social acceleration (recall to the best insect value of the group) = %s"%(selfA._name, str(__sa)))
+ logging.debug("%s Inertial weight = %s"%(selfA._name, str(__iw)))
+ logging.debug("%s Velocity clamping factor = %s"%(selfA._name, str(__vc)))
+ #
+ # Initialisation de l'essaim
+ # --------------------------
+ LimitPlace = Bounds
+ LimitSpeed = BoxBounds
+ #
+ nbfct = 1 # Nb d'évaluations
+ HX = Hm( Xini )
+ JXini, JbXini, JoXini = CostFunction(Xini,HX,selfA._parameters["QualityCriterion"])
+ #
+ Swarm = numpy.zeros((__nbI,4,__nbP)) # 4 car (x,v,gbest,lbest)
+ for __p in range(__nbP) :
+ Swarm[:,0,__p] = rand( low=LimitPlace[__p,0], high=LimitPlace[__p,1], size=__nbI) # Position
+ Swarm[:,1,__p] = rand( low=LimitSpeed[__p,0], high=LimitSpeed[__p,1], size=__nbI) # Velocity
+ logging.debug("%s Initialisation of the swarm with %i insects of size %i "%(selfA._name,Swarm.shape[0],Swarm.shape[2]))
+ #
+ __nbh = GetNeighborhoodTopology( selfA._parameters["SwarmTopology"], list(range(__nbI)) )
+ #
+ qSwarm = JXini * numpy.ones((__nbI,6)) # Qualités (J, Jb, Jo) par insecte + par voisinage
+ __EOS = Hm(
+ numpy.vsplit(Swarm[:,0,:], __nbI),
+ argsAsSerie = True,
+ returnSerieAsArrayMatrix = False,
+ )
+ for __i in range(__nbI):
+ nbfct += 1
+ JTest, JbTest, JoTest = CostFunction(Swarm[__i,0,:],__EOS[__i],selfA._parameters["QualityCriterion"])
+ if JTest < JXini:
+ Swarm[__i,2,:] = Swarm[__i,0,:] # xBest
+ qSwarm[__i,:3] = (JTest, JbTest, JoTest)
+ else:
+ Swarm[__i,2,:] = Xini # xBest
+ qSwarm[__i,:3] = (JXini, JbXini, JoXini)
+ logging.debug("%s Initialisation of the best previous insects"%selfA._name)
+ #
+ iBest = numpy.argmin(qSwarm[:,0])
+ xBest = Swarm[iBest,2,:]
+ for __i in range(__nbI):
+ Swarm[__i,3,:] = xBest # lBest
+ qSwarm[__i,3:] = qSwarm[iBest,:3]
+ if selfA._parameters["StoreInternalVariables"] or selfA._toStore("CurrentState"):
+ selfA.StoredVariables["CurrentState"].store( xBest )
+ selfA.StoredVariables["CostFunctionJ" ].store( qSwarm[iBest,0] )
+ selfA.StoredVariables["CostFunctionJb"].store( qSwarm[iBest,1] )
+ selfA.StoredVariables["CostFunctionJo"].store( qSwarm[iBest,2] )
+ if selfA._parameters["StoreInternalVariables"] or selfA._toStore("InternalStates"):
+ selfA.StoredVariables["InternalStates"].store( Swarm[:,0,:].T )
+ if selfA._parameters["StoreInternalVariables"] or selfA._toStore("InternalCostFunctionJ"):
+ selfA.StoredVariables["InternalCostFunctionJ"].store( qSwarm[:,0] )
+ if selfA._parameters["StoreInternalVariables"] or selfA._toStore("InternalCostFunctionJb"):
+ selfA.StoredVariables["InternalCostFunctionJb"].store( qSwarm[:,1] )
+ if selfA._parameters["StoreInternalVariables"] or selfA._toStore("InternalCostFunctionJo"):
+ selfA.StoredVariables["InternalCostFunctionJo"].store( qSwarm[:,2] )
+ #
+ selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["CostFunctionJ"]) )
+ #
+ # Minimisation de la fonctionnelle
+ # --------------------------------
+ step = 0
+ while KeepRunningCondition(step, nbfct):
+ step += 1
+ #
+ __EOS = Hm(
+ numpy.vsplit(Swarm[:,0,:], __nbI),
+ argsAsSerie = True,
+ returnSerieAsArrayMatrix = False,
+ )
+ for __i in range(__nbI):
+ # Évalue
+ JTest, JbTest, JoTest = CostFunction(Swarm[__i,0,:],__EOS[__i],selfA._parameters["QualityCriterion"])
+ # Maj lbest
+ if JTest < qSwarm[__i,0]:
+ Swarm[__i,2,:] = Swarm[__i,0,:]
+ qSwarm[__i,:3] = (JTest, JbTest, JoTest)
+ #
+ for __i in range(__nbI):
+ # Maj gbest
+ __im = numpy.argmin( [qSwarm[__v,0] for __v in __nbh[__i]] )
+ __il = __nbh[__i][__im] # Best in NB
+ if qSwarm[__il,0] < qSwarm[__i,3]:
+ Swarm[__i,3,:] = Swarm[__il,2,:]
+ qSwarm[__i,3:] = qSwarm[__il,:3]
+ #
+ for __i in range(__nbI-1,0-1,-1):
+ __rct = rand(size=__nbP)
+ __rst = rand(size=__nbP)
+ __xPoint = Swarm[__i,0,:]
+ # Points
+ __pPoint = __xPoint + __ca * __rct * (Swarm[__i,2,:] - __xPoint)
+ __lPoint = __xPoint + __sa * __rst * (Swarm[__i,3,:] - __xPoint)
+ __gPoint = (__xPoint + __pPoint + __lPoint) / 3
+ __radius = numpy.linalg.norm(__gPoint - __xPoint)
+ __rPoint = GenerateRandomPointInHyperSphere( __gPoint, __radius )
+ # Maj vitesse
+ __value = __iw * Swarm[__i,1,:] + __rPoint - __xPoint
+ Swarm[__i,1,:] = ApplyBounds( __value, LimitSpeed )
+ # Maj position
+ __value = __xPoint + Swarm[__i,1,:]
+ Swarm[__i,0,:] = ApplyBounds( __value, LimitPlace )
+ #
+ nbfct += 1
+ #
+ iBest = numpy.argmin(qSwarm[:,0])
+ xBest = Swarm[iBest,2,:]
+ selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["CostFunctionJ"]) )
+ if selfA._parameters["StoreInternalVariables"] or selfA._toStore("CurrentState"):
+ selfA.StoredVariables["CurrentState"].store( xBest )
+ if selfA._toStore("SimulatedObservationAtCurrentState"):
+ selfA.StoredVariables["SimulatedObservationAtCurrentState"].store( Hm( xBest ) )
+ selfA.StoredVariables["CostFunctionJ" ].store( qSwarm[iBest,0] )
+ selfA.StoredVariables["CostFunctionJb"].store( qSwarm[iBest,1] )
+ selfA.StoredVariables["CostFunctionJo"].store( qSwarm[iBest,2] )
+ if selfA._parameters["StoreInternalVariables"] or selfA._toStore("InternalStates"):
+ selfA.StoredVariables["InternalStates"].store( Swarm[:,0,:].T )
+ if selfA._parameters["StoreInternalVariables"] or selfA._toStore("InternalCostFunctionJ"):
+ selfA.StoredVariables["InternalCostFunctionJ"].store( qSwarm[:,0] )
+ if selfA._parameters["StoreInternalVariables"] or selfA._toStore("InternalCostFunctionJb"):
+ selfA.StoredVariables["InternalCostFunctionJb"].store( qSwarm[:,1] )
+ if selfA._parameters["StoreInternalVariables"] or selfA._toStore("InternalCostFunctionJo"):
+ selfA.StoredVariables["InternalCostFunctionJo"].store( qSwarm[:,2] )
+ logging.debug("%s Step %i: insect %i is the better one with J =%.7f"%(selfA._name,step,iBest,qSwarm[iBest,0]))
+ #
+ # Obtention de l'analyse
+ # ----------------------
+ Xa = xBest
+ #
+ selfA.StoredVariables["Analysis"].store( Xa )
+ #
+ # Calculs et/ou stockages supplémentaires
+ # ---------------------------------------
+ if selfA._toStore("OMA") or \
+ selfA._toStore("SimulatedObservationAtOptimum"):
+ HXa = Hm(Xa)
+ if selfA._toStore("Innovation") or \
+ selfA._toStore("OMB") or \
+ selfA._toStore("SimulatedObservationAtBackground"):
+ HXb = Hm(Xb)
+ Innovation = Y - HXb
+ if selfA._toStore("Innovation"):
+ selfA.StoredVariables["Innovation"].store( Innovation )
+ if selfA._toStore("OMB"):
+ selfA.StoredVariables["OMB"].store( Innovation )
+ if selfA._toStore("BMA"):
+ selfA.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
+ if selfA._toStore("OMA"):
+ selfA.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
+ if selfA._toStore("SimulatedObservationAtBackground"):
+ selfA.StoredVariables["SimulatedObservationAtBackground"].store( HXb )
+ if selfA._toStore("SimulatedObservationAtOptimum"):
+ selfA.StoredVariables["SimulatedObservationAtOptimum"].store( HXa )
+ #
+ selfA._post_run(HO)
+ return 0
+
+# ==============================================================================
+if __name__ == "__main__":
+ print('\n AUTODIAGNOSTIC\n')
# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
__doc__ = """
- Standard Particle Swarm Optimization 2011
+ Standard Particle Swarm Optimization 2011 (SIS)
"""
__author__ = "Jean-Philippe ARGAUD"
from daCore.NumericObjects import ApplyBounds, VariablesAndIncrementsBounds
from daCore.NumericObjects import GenerateRandomPointInHyperSphere
from daCore.NumericObjects import GetNeighborhoodTopology
+from daCore.PlatformInfo import vfloat
from numpy.random import uniform as rand
# ==============================================================================
Jb = 0.
Jo = numpy.max( numpy.abs(_Innovation) )
#
- J = float( Jb ) + float( Jo )
+ J = vfloat( Jb ) + vfloat( Jo )
#
- return J, float( Jb ), float( Jo )
+ return J, vfloat( Jb ), vfloat( Jo )
#
def KeepRunningCondition(__step, __nbfct):
if __step >= selfA._parameters["MaximumNumberOfIterations"]:
__vc = float( selfA._parameters["VelocityClampingFactor"] )
logging.debug("%s Cognitive acceleration (recall to the best previously known value of the insect) = %s"%(selfA._name, str(__ca)))
logging.debug("%s Social acceleration (recall to the best insect value of the group) = %s"%(selfA._name, str(__sa)))
+ logging.debug("%s Inertial weight = %s"%(selfA._name, str(__iw)))
logging.debug("%s Velocity clamping factor = %s"%(selfA._name, str(__vc)))
#
# Initialisation de l'essaim
step = 0
while KeepRunningCondition(step, nbfct):
step += 1
+ #
for __i in range(__nbI):
- rct = rand(size=__nbP)
- rst = rand(size=__nbP)
- rrt = rand(size=__nbP)
- # Points
+ # Évalue
+ JTest, JbTest, JoTest = CostFunction(Swarm[__i,0,:],selfA._parameters["QualityCriterion"])
+ # Maj lbest
+ if JTest < qSwarm[__i,0]:
+ Swarm[__i,2,:] = Swarm[__i,0,:]
+ qSwarm[__i,:3] = (JTest, JbTest, JoTest)
+ #
+ for __i in range(__nbI):
+ # Maj gbest
+ __im = numpy.argmin( [qSwarm[__v,0] for __v in __nbh[__i]] )
+ __il = __nbh[__i][__im] # Best in NB
+ if qSwarm[__il,0] < qSwarm[__i,3]:
+ Swarm[__i,3,:] = Swarm[__il,2,:]
+ qSwarm[__i,3:] = qSwarm[__il,:3]
+ #
+ for __i in range(__nbI-1,0-1,-1):
+ __rct = rand(size=__nbP)
+ __rst = rand(size=__nbP)
__xPoint = Swarm[__i,0,:]
- __pPoint = __xPoint \
- + __ca * rct * (Swarm[__i,2,:] - Swarm[__i,0,:])
- __lPoint = __xPoint \
- + __sa * rst * (Swarm[__i,3,:] - Swarm[__i,0,:])
+ # Points
+ __pPoint = __xPoint + __ca * __rct * (Swarm[__i,2,:] - __xPoint)
+ __lPoint = __xPoint + __sa * __rst * (Swarm[__i,3,:] - __xPoint)
__gPoint = (__xPoint + __pPoint + __lPoint) / 3
__radius = numpy.linalg.norm(__gPoint - __xPoint)
__rPoint = GenerateRandomPointInHyperSphere( __gPoint, __radius )
- # Vitesse
+ # Maj vitesse
__value = __iw * Swarm[__i,1,:] + __rPoint - __xPoint
Swarm[__i,1,:] = ApplyBounds( __value, LimitSpeed )
- # Position
- __value = Swarm[__i,0,:] + Swarm[__i,1,:]
+ # Maj position
+ __value = __xPoint + Swarm[__i,1,:]
Swarm[__i,0,:] = ApplyBounds( __value, LimitPlace )
#
nbfct += 1
- # Update gbest
- JTest, JbTest, JoTest = CostFunction(Swarm[__i,0,:],selfA._parameters["QualityCriterion"])
- if JTest < qSwarm[__i,0]:
- Swarm[__i,2,:] = Swarm[__i,0,:] # xBest
- qSwarm[__i,:3] = (JTest, JbTest, JoTest)
- #
- # Update lbest
- for __i in range(__nbI):
- __im = numpy.argmin( [qSwarm[__v,0] for __v in __nbh[__i]] )
- __il = __nbh[__i][__im] # Best in NB
- if qSwarm[__il,0] < qSwarm[__i,3]:
- Swarm[__i,3,:] = Swarm[__il,2,:] # lBest
- qSwarm[__i,3:] = qSwarm[__il,:3]
#
iBest = numpy.argmin(qSwarm[:,0])
xBest = Swarm[iBest,2,:]
__author__ = "Jean-Philippe ARGAUD"
import numpy
-from daCore.PlatformInfo import PlatformInfo
+from daCore.PlatformInfo import PlatformInfo, vfloat
mpr = PlatformInfo().MachinePrecision()
# ==============================================================================
or selfA._toStore("CostFunctionJb") \
or selfA._toStore("CostFunctionJo") \
or selfA._toStore("CurrentOptimum") or selfA._toStore("APosterioriCovariance"):
- Jb = float( 0.5 * (Xa - Xb).T @ (BI @ (Xa - Xb)) )
- Jo = float( 0.5 * Innovation.T @ (RI @ Innovation) )
+ Jb = vfloat( 0.5 * (Xa - Xb).T @ (BI @ (Xa - Xb)) )
+ Jo = vfloat( 0.5 * Innovation.T @ (RI @ Innovation) )
J = Jb + Jo
selfA.StoredVariables["CostFunctionJb"].store( Jb )
selfA.StoredVariables["CostFunctionJo"].store( Jo )
"""
__author__ = "Jean-Philippe ARGAUD"
-import numpy, logging
+import numpy, logging, copy
import daCore.NumericObjects
# ==============================================================================
Ensemble Of Simulations Generation
"""
#
- __seed = numpy.random.get_state()
sampleList = daCore.NumericObjects.BuildComplexSampleList(
selfA._parameters["SampleAsnUplet"],
selfA._parameters["SampleAsExplicitHyperCube"],
selfA._parameters["SampleAsIndependantRandomVariables"],
Xb,
)
+ if outputEOX or selfA._toStore("EnsembleOfStates"):
+ EOX = numpy.stack(tuple(copy.copy(sampleList)), axis=1)
#
# ----------
if selfA._parameters["SetDebug"]:
logging.getLogger().setLevel(CUR_LEVEL)
# ----------
#
- if outputEOX or selfA._toStore("EnsembleOfStates"):
- # Attention la liste s'épuise donc il faut la recréer
- numpy.random.set_state(__seed)
- sampleList = daCore.NumericObjects.BuildComplexSampleList(
- selfA._parameters["SampleAsnUplet"],
- selfA._parameters["SampleAsExplicitHyperCube"],
- selfA._parameters["SampleAsMinMaxStepHyperCube"],
- selfA._parameters["SampleAsIndependantRandomVariables"],
- Xb,
- )
- # Il faut passer la liste en tuple/list pour stack
- EOX = numpy.stack(tuple(sampleList), axis=1)
- assert EOX.shape[1] == EOS.shape[1], " Error of number of states in Ensemble Of Simulations Generation"
if selfA._toStore("EnsembleOfStates"):
+ assert EOX.shape[1] == EOS.shape[1], " Error of number of states in Ensemble Of Simulations Generation"
selfA.StoredVariables["EnsembleOfStates"].store( EOX )
if selfA._toStore("EnsembleOfSimulations"):
selfA.StoredVariables["EnsembleOfSimulations"].store( EOS )
#
if outputEOX:
+ assert EOX.shape[1] == EOS.shape[1], " Error of number of states in Ensemble Of Simulations Generation"
return EOX, EOS
else:
return EOS
from daCore.NumericObjects import EnsembleOfAnomalies
from daCore.NumericObjects import EnsembleOfBackgroundPerturbations
from daCore.NumericObjects import EnsemblePerturbationWithGivenCovariance
+from daCore.PlatformInfo import vfloat
# ==============================================================================
def etkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q,
_Jo = 0.5 * _A.T @ (RI * _A)
_Jb = 0.5 * (__m-1) * w.T @ w
_J = _Jo + _Jb
- return float(_J)
+ return vfloat(_J)
def GradientOfCostFunction(w):
_A = Ynpu - HXfm.reshape((__p,1)) - (EaHX @ w).reshape((__p,1))
_GardJo = - EaHX.T @ (RI * _A)
_Jo = 0.5 * _A.T @ (RI * _A)
_Jb = 0.5 * __m * math.log(1 + 1/__m + w.T @ w)
_J = _Jo + _Jb
- return float(_J)
+ return vfloat(_J)
def GradientOfCostFunction(w):
_A = Ynpu - HXfm.reshape((__p,1)) - (EaHX @ w).reshape((__p,1))
_GardJo = - EaHX.T @ (RI * _A)
_Jo = 0.5 * _A.T * (RI * _A)
_Jb = 0.5 * (__m+1) * math.log(1 + 1/__m + w.T @ w)
_J = _Jo + _Jb
- return float(_J)
+ return vfloat(_J)
def GradientOfCostFunction(w):
_A = Ynpu - HXfm.reshape((__p,1)) - (EaHX @ w).reshape((__p,1))
_GardJo = - EaHX.T @ (RI * _A)
_Jo = 0.5 * _A.T @ (RI * _A)
_Jb = 0.5 * (__m+1) * math.log(1 + 1/__m + w.T @ w / (__m-1))
_J = _Jo + _Jb
- return float(_J)
+ return vfloat(_J)
def GradientOfCostFunction(w):
_A = Ynpu - HXfm.reshape((__p,1)) - (EaHX @ w).reshape((__p,1))
_GardJo = - EaHX.T @ (RI * _A)
or selfA._toStore("CostFunctionJo") \
or selfA._toStore("CurrentOptimum") \
or selfA._toStore("APosterioriCovariance"):
- Jb = float( 0.5 * (Xa - Xb).T * (BI * (Xa - Xb)) )
- Jo = float( 0.5 * _Innovation.T * (RI * _Innovation) )
+ Jb = vfloat( 0.5 * (Xa - Xb).T * (BI * (Xa - Xb)) )
+ Jo = vfloat( 0.5 * _Innovation.T * (RI * _Innovation) )
J = Jb + Jo
selfA.StoredVariables["CostFunctionJb"].store( Jb )
selfA.StoredVariables["CostFunctionJo"].store( Jo )
__author__ = "Jean-Philippe ARGAUD"
import numpy
-from daCore.PlatformInfo import PlatformInfo
+from daCore.PlatformInfo import PlatformInfo, vfloat
mpr = PlatformInfo().MachinePrecision()
mfp = PlatformInfo().MaximumPrecision()
or selfA._toStore("CostFunctionJo") \
or selfA._toStore("CurrentOptimum") \
or selfA._toStore("APosterioriCovariance"):
- Jb = float( 0.5 * (Xa - Xb).T @ (BI @ (Xa - Xb)) )
- Jo = float( 0.5 * _Innovation.T @ (RI @ _Innovation) )
+ Jb = vfloat( 0.5 * (Xa - Xb).T @ (BI @ (Xa - Xb)) )
+ Jo = vfloat( 0.5 * _Innovation.T @ (RI @ _Innovation) )
J = Jb + Jo
selfA.StoredVariables["CostFunctionJb"].store( Jb )
selfA.StoredVariables["CostFunctionJo"].store( Jo )
__author__ = "Jean-Philippe ARGAUD"
import numpy
-from daCore.PlatformInfo import PlatformInfo
+from daCore.PlatformInfo import PlatformInfo, vfloat
mpr = PlatformInfo().MachinePrecision()
mfp = PlatformInfo().MaximumPrecision()
or selfA._toStore("CostFunctionJo") \
or selfA._toStore("CurrentOptimum") \
or selfA._toStore("APosterioriCovariance"):
- Jb = float( 0.5 * (Xa - Xb).T @ (BI @ (Xa - Xb)) )
- Jo = float( 0.5 * _Innovation.T @ (RI @ _Innovation) )
+ Jb = vfloat( 0.5 * (Xa - Xb).T @ (BI @ (Xa - Xb)) )
+ Jo = vfloat( 0.5 * _Innovation.T @ (RI @ _Innovation) )
J = Jb + Jo
selfA.StoredVariables["CostFunctionJb"].store( Jb )
selfA.StoredVariables["CostFunctionJo"].store( Jo )
from daCore.NumericObjects import CovarianceInflation
from daCore.NumericObjects import EnsembleMean
from daCore.NumericObjects import EnsembleErrorCovariance
-from daCore.PlatformInfo import PlatformInfo
+from daCore.PlatformInfo import PlatformInfo, vfloat
mpr = PlatformInfo().MachinePrecision()
mfp = PlatformInfo().MaximumPrecision()
or selfA._toStore("CostFunctionJo") \
or selfA._toStore("CurrentOptimum") \
or selfA._toStore("APosterioriCovariance"):
- Jb = float( 0.5 * (Xa - Xb).T * (BI * (Xa - Xb)) )
- Jo = float( 0.5 * _Innovation.T * (RI * _Innovation) )
+ Jb = vfloat( 0.5 * (Xa - Xb).T * (BI * (Xa - Xb)) )
+ Jo = vfloat( 0.5 * _Innovation.T * (RI * _Innovation) )
J = Jb + Jo
selfA.StoredVariables["CostFunctionJb"].store( Jb )
selfA.StoredVariables["CostFunctionJo"].store( Jo )
import numpy, scipy, scipy.optimize, scipy.version
from daCore.NumericObjects import HessienneEstimation, QuantilesEstimations
from daCore.NumericObjects import RecentredBounds
-from daCore.PlatformInfo import PlatformInfo, vt
+from daCore.PlatformInfo import PlatformInfo, vt, vfloat
mpr = PlatformInfo().MachinePrecision()
# ==============================================================================
if selfA._toStore("InnovationAtCurrentState"):
selfA.StoredVariables["InnovationAtCurrentState"].store( _dInnovation )
#
- Jb = float( 0.5 * _dX.T * (BI * _dX) )
- Jo = float( 0.5 * _dInnovation.T * (RI * _dInnovation) )
+ Jb = vfloat( 0.5 * _dX.T * (BI * _dX) )
+ Jo = vfloat( 0.5 * _dInnovation.T * (RI * _dInnovation) )
J = Jb + Jo
#
selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["CostFunctionJ"]) )
import daAlgorithms.Atoms.lbfgsb18hlt as optimiseur
elif vt("1.9.0") <= vt(scipy.version.version) <= vt("1.10.99"):
import daAlgorithms.Atoms.lbfgsb19hlt as optimiseur
+ elif vt("1.11.0") <= vt(scipy.version.version) <= vt("1.11.99"):
+ import daAlgorithms.Atoms.lbfgsb111hlt as optimiseur
else:
import scipy.optimize as optimiseur
Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
selfA.StoredVariables["OMB"].store( Innovation )
if selfA._toStore("SigmaObs2"):
TraceR = R.trace(Y.size)
- selfA.StoredVariables["SigmaObs2"].store( float( (Innovation.T @ oma) ) / TraceR )
+ selfA.StoredVariables["SigmaObs2"].store( vfloat( (Innovation.T @ oma) ) / TraceR )
if selfA._toStore("MahalanobisConsistency"):
selfA.StoredVariables["MahalanobisConsistency"].store( float( 2.*MinJ/Innovation.size ) )
if selfA._toStore("SimulationQuantiles"):
--- /dev/null
+# Modification de la version 1.11.0
+"""
+Functions
+---------
+.. autosummary::
+ :toctree: generated/
+
+ fmin_l_bfgs_b
+
+"""
+
+## License for the Python wrapper
+## ==============================
+
+## Copyright (c) 2004 David M. Cooke <cookedm@physics.mcmaster.ca>
+
+## Permission is hereby granted, free of charge, to any person obtaining a
+## copy of this software and associated documentation files (the "Software"),
+## to deal in the Software without restriction, including without limitation
+## the rights to use, copy, modify, merge, publish, distribute, sublicense,
+## and/or sell copies of the Software, and to permit persons to whom the
+## Software is furnished to do so, subject to the following conditions:
+
+## The above copyright notice and this permission notice shall be included in
+## all copies or substantial portions of the Software.
+
+## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+## FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+## DEALINGS IN THE SOFTWARE.
+
+## Modifications by Travis Oliphant and Enthought, Inc. for inclusion in SciPy
+
+import numpy as np
+from numpy import array, asarray, float64, zeros
+from scipy.optimize import _lbfgsb
+from scipy.optimize._optimize import (MemoizeJac, OptimizeResult, _call_callback_maybe_halt,
+ _wrap_callback, _check_unknown_options,
+ _prepare_scalar_function)
+from scipy.optimize._constraints import old_bound_to_new
+
+from scipy.sparse.linalg import LinearOperator
+
+__all__ = ['fmin_l_bfgs_b', 'LbfgsInvHessProduct']
+
+
+def fmin_l_bfgs_b(func, x0, fprime=None, args=(),
+ approx_grad=0,
+ bounds=None, m=10, factr=1e7, pgtol=1e-5,
+ epsilon=1e-8,
+ iprint=-1, maxfun=15000, maxiter=15000, disp=None,
+ callback=None, maxls=20):
+ """
+ Minimize a function func using the L-BFGS-B algorithm.
+
+ Parameters
+ ----------
+ func : callable f(x,*args)
+ Function to minimize.
+ x0 : ndarray
+ Initial guess.
+ fprime : callable fprime(x,*args), optional
+ The gradient of `func`. If None, then `func` returns the function
+ value and the gradient (``f, g = func(x, *args)``), unless
+ `approx_grad` is True in which case `func` returns only ``f``.
+ args : sequence, optional
+ Arguments to pass to `func` and `fprime`.
+ approx_grad : bool, optional
+ Whether to approximate the gradient numerically (in which case
+ `func` returns only the function value).
+ bounds : list, optional
+ ``(min, max)`` pairs for each element in ``x``, defining
+ the bounds on that parameter. Use None or +-inf for one of ``min`` or
+ ``max`` when there is no bound in that direction.
+ m : int, optional
+ The maximum number of variable metric corrections
+ used to define the limited memory matrix. (The limited memory BFGS
+ method does not store the full hessian but uses this many terms in an
+ approximation to it.)
+ factr : float, optional
+ The iteration stops when
+ ``(f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr * eps``,
+ where ``eps`` is the machine precision, which is automatically
+ generated by the code. Typical values for `factr` are: 1e12 for
+ low accuracy; 1e7 for moderate accuracy; 10.0 for extremely
+ high accuracy. See Notes for relationship to `ftol`, which is exposed
+ (instead of `factr`) by the `scipy.optimize.minimize` interface to
+ L-BFGS-B.
+ pgtol : float, optional
+ The iteration will stop when
+ ``max{|proj g_i | i = 1, ..., n} <= pgtol``
+ where ``pg_i`` is the i-th component of the projected gradient.
+ epsilon : float, optional
+ Step size used when `approx_grad` is True, for numerically
+ calculating the gradient
+ iprint : int, optional
+ Controls the frequency of output. ``iprint < 0`` means no output;
+ ``iprint = 0`` print only one line at the last iteration;
+ ``0 < iprint < 99`` print also f and ``|proj g|`` every iprint iterations;
+ ``iprint = 99`` print details of every iteration except n-vectors;
+ ``iprint = 100`` print also the changes of active set and final x;
+ ``iprint > 100`` print details of every iteration including x and g.
+ disp : int, optional
+ If zero, then no output. If a positive number, then this over-rides
+ `iprint` (i.e., `iprint` gets the value of `disp`).
+ maxfun : int, optional
+ Maximum number of function evaluations. Note that this function
+ may violate the limit because of evaluating gradients by numerical
+ differentiation.
+ maxiter : int, optional
+ Maximum number of iterations.
+ callback : callable, optional
+ Called after each iteration, as ``callback(xk)``, where ``xk`` is the
+ current parameter vector.
+ maxls : int, optional
+ Maximum number of line search steps (per iteration). Default is 20.
+
+ Returns
+ -------
+ x : array_like
+ Estimated position of the minimum.
+ f : float
+ Value of `func` at the minimum.
+ d : dict
+ Information dictionary.
+
+ * d['warnflag'] is
+
+ - 0 if converged,
+ - 1 if too many function evaluations or too many iterations,
+ - 2 if stopped for another reason, given in d['task']
+
+ * d['grad'] is the gradient at the minimum (should be 0 ish)
+ * d['funcalls'] is the number of function calls made.
+ * d['nit'] is the number of iterations.
+
+ See also
+ --------
+ minimize: Interface to minimization algorithms for multivariate
+ functions. See the 'L-BFGS-B' `method` in particular. Note that the
+ `ftol` option is made available via that interface, while `factr` is
+ provided via this interface, where `factr` is the factor multiplying
+ the default machine floating-point precision to arrive at `ftol`:
+ ``ftol = factr * numpy.finfo(float).eps``.
+
+ Notes
+ -----
+ License of L-BFGS-B (FORTRAN code):
+
+ The version included here (in fortran code) is 3.0
+ (released April 25, 2011). It was written by Ciyou Zhu, Richard Byrd,
+ and Jorge Nocedal <nocedal@ece.nwu.edu>. It carries the following
+ condition for use:
+
+ This software is freely available, but we expect that all publications
+ describing work using this software, or all commercial products using it,
+ quote at least one of the references given below. This software is released
+ under the BSD License.
+
+ References
+ ----------
+ * R. H. Byrd, P. Lu and J. Nocedal. A Limited Memory Algorithm for Bound
+ Constrained Optimization, (1995), SIAM Journal on Scientific and
+ Statistical Computing, 16, 5, pp. 1190-1208.
+ * C. Zhu, R. H. Byrd and J. Nocedal. L-BFGS-B: Algorithm 778: L-BFGS-B,
+ FORTRAN routines for large scale bound constrained optimization (1997),
+ ACM Transactions on Mathematical Software, 23, 4, pp. 550 - 560.
+ * J.L. Morales and J. Nocedal. L-BFGS-B: Remark on Algorithm 778: L-BFGS-B,
+ FORTRAN routines for large scale bound constrained optimization (2011),
+ ACM Transactions on Mathematical Software, 38, 1.
+
+ """
+ # handle fprime/approx_grad
+ if approx_grad:
+ fun = func
+ jac = None
+ elif fprime is None:
+ fun = MemoizeJac(func)
+ jac = fun.derivative
+ else:
+ fun = func
+ jac = fprime
+
+ # build options
+ if disp is None:
+ disp = iprint
+ callback = _wrap_callback(callback)
+ opts = {'disp': disp,
+ 'iprint': iprint,
+ 'maxcor': m,
+ 'ftol': factr * np.finfo(float).eps,
+ 'gtol': pgtol,
+ 'eps': epsilon,
+ 'maxfun': maxfun,
+ 'maxiter': maxiter,
+ 'callback': callback,
+ 'maxls': maxls}
+
+ res = _minimize_lbfgsb(fun, x0, args=args, jac=jac, bounds=bounds,
+ **opts)
+ d = {'grad': res['jac'],
+ 'task': res['message'],
+ 'funcalls': res['nfev'],
+ 'nit': res['nit'],
+ 'warnflag': res['status']}
+ f = res['fun']
+ x = res['x']
+
+ return x, f, d
+
+
+def _minimize_lbfgsb(fun, x0, args=(), jac=None, bounds=None,
+ disp=None, maxcor=10, ftol=2.2204460492503131e-09,
+ gtol=1e-5, eps=1e-8, maxfun=15000, maxiter=15000,
+ iprint=-1, callback=None, maxls=20,
+ finite_diff_rel_step=None, **unknown_options):
+ """
+ Minimize a scalar function of one or more variables using the L-BFGS-B
+ algorithm.
+
+ Options
+ -------
+ disp : None or int
+ If `disp is None` (the default), then the supplied version of `iprint`
+ is used. If `disp is not None`, then it overrides the supplied version
+ of `iprint` with the behaviour you outlined.
+ maxcor : int
+ The maximum number of variable metric corrections used to
+ define the limited memory matrix. (The limited memory BFGS
+ method does not store the full hessian but uses this many terms
+ in an approximation to it.)
+ ftol : float
+ The iteration stops when ``(f^k -
+ f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= ftol``.
+ gtol : float
+ The iteration will stop when ``max{|proj g_i | i = 1, ..., n}
+ <= gtol`` where ``pg_i`` is the i-th component of the
+ projected gradient.
+ eps : float or ndarray
+ If `jac is None` the absolute step size used for numerical
+ approximation of the jacobian via forward differences.
+ maxfun : int
+ Maximum number of function evaluations. Note that this function
+ may violate the limit because of evaluating gradients by numerical
+ differentiation.
+ maxiter : int
+ Maximum number of iterations.
+ iprint : int, optional
+ Controls the frequency of output. ``iprint < 0`` means no output;
+ ``iprint = 0`` print only one line at the last iteration;
+ ``0 < iprint < 99`` print also f and ``|proj g|`` every iprint iterations;
+ ``iprint = 99`` print details of every iteration except n-vectors;
+ ``iprint = 100`` print also the changes of active set and final x;
+ ``iprint > 100`` print details of every iteration including x and g.
+ callback : callable, optional
+ Called after each iteration, as ``callback(xk)``, where ``xk`` is the
+ current parameter vector.
+ maxls : int, optional
+ Maximum number of line search steps (per iteration). Default is 20.
+ finite_diff_rel_step : None or array_like, optional
+ If `jac in ['2-point', '3-point', 'cs']` the relative step size to
+ use for numerical approximation of the jacobian. The absolute step
+ size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``,
+ possibly adjusted to fit into the bounds. For ``method='3-point'``
+ the sign of `h` is ignored. If None (default) then step is selected
+ automatically.
+
+ Notes
+ -----
+ The option `ftol` is exposed via the `scipy.optimize.minimize` interface,
+ but calling `scipy.optimize.fmin_l_bfgs_b` directly exposes `factr`. The
+ relationship between the two is ``ftol = factr * numpy.finfo(float).eps``.
+ I.e., `factr` multiplies the default machine floating-point precision to
+ arrive at `ftol`.
+
+ """
+ _check_unknown_options(unknown_options)
+ m = maxcor
+ pgtol = gtol
+ factr = ftol / np.finfo(float).eps
+
+ x0 = asarray(x0).ravel()
+ n, = x0.shape
+
+ if bounds is None:
+ bounds = [(None, None)] * n
+ if len(bounds) != n:
+ raise ValueError('length of x0 != length of bounds')
+
+ # unbounded variables must use None, not +-inf, for optimizer to work properly
+ bounds = [(None if l == -np.inf else l, None if u == np.inf else u) for l, u in bounds]
+ # LBFGSB is sent 'old-style' bounds, 'new-style' bounds are required by
+ # approx_derivative and ScalarFunction
+ new_bounds = old_bound_to_new(bounds)
+
+ # check bounds
+ if (new_bounds[0] > new_bounds[1]).any():
+ raise ValueError("LBFGSB - one of the lower bounds is greater than an upper bound.")
+
+ # initial vector must lie within the bounds. Otherwise ScalarFunction and
+ # approx_derivative will cause problems
+ x0 = np.clip(x0, new_bounds[0], new_bounds[1])
+
+ if disp is not None:
+ if disp == 0:
+ iprint = -1
+ else:
+ iprint = disp
+
+ sf = _prepare_scalar_function(fun, x0, jac=jac, args=args, epsilon=eps,
+ bounds=new_bounds,
+ finite_diff_rel_step=finite_diff_rel_step)
+
+ func_and_grad = sf.fun_and_grad
+
+ fortran_int = _lbfgsb.types.intvar.dtype
+
+ nbd = zeros(n, fortran_int)
+ low_bnd = zeros(n, float64)
+ upper_bnd = zeros(n, float64)
+ bounds_map = {(None, None): 0,
+ (1, None): 1,
+ (1, 1): 2,
+ (None, 1): 3}
+ for i in range(0, n):
+ l, u = bounds[i]
+ if l is not None:
+ low_bnd[i] = l
+ l = 1
+ if u is not None:
+ upper_bnd[i] = u
+ u = 1
+ nbd[i] = bounds_map[l, u]
+
+ if not maxls > 0:
+ raise ValueError('maxls must be positive.')
+
+ x = array(x0, float64)
+ f = array(0.0, float64)
+ g = zeros((n,), float64)
+ wa = zeros(2*m*n + 5*n + 11*m*m + 8*m, float64)
+ iwa = zeros(3*n, fortran_int)
+ task = zeros(1, 'S60')
+ csave = zeros(1, 'S60')
+ lsave = zeros(4, fortran_int)
+ isave = zeros(44, fortran_int)
+ dsave = zeros(29, float64)
+
+ task[:] = 'START'
+
+ n_iterations = 0
+
+ while 1:
+ # x, f, g, wa, iwa, task, csave, lsave, isave, dsave = \
+ _lbfgsb.setulb(m, x, low_bnd, upper_bnd, nbd, f, g, factr,
+ pgtol, wa, iwa, task, iprint, csave, lsave,
+ isave, dsave, maxls)
+ task_str = task.tobytes()
+ if task_str.startswith(b'FG'):
+ # The minimization routine wants f and g at the current x.
+ # Note that interruptions due to maxfun are postponed
+ # until the completion of the current minimization iteration.
+ # Overwrite f and g:
+ f, g = func_and_grad(x)
+ if sf.nfev > maxfun:
+ task[:] = ('STOP: TOTAL NO. of f AND g EVALUATIONS '
+ 'EXCEEDS LIMIT')
+ elif task_str.startswith(b'NEW_X'):
+ # new iteration
+ n_iterations += 1
+
+ intermediate_result = OptimizeResult(x=x, fun=f)
+ if _call_callback_maybe_halt(callback, intermediate_result):
+ task[:] = 'STOP: CALLBACK REQUESTED HALT'
+ if n_iterations >= maxiter:
+ task[:] = 'STOP: TOTAL NO. of ITERATIONS REACHED LIMIT'
+ elif sf.nfev > maxfun:
+ task[:] = ('STOP: TOTAL NO. of f AND g EVALUATIONS '
+ 'EXCEEDS LIMIT')
+ else:
+ break
+
+ task_str = task.tobytes().strip(b'\x00').strip()
+ if task_str.startswith(b'CONV'):
+ warnflag = 0
+ elif sf.nfev > maxfun or n_iterations >= maxiter:
+ warnflag = 1
+ else:
+ warnflag = 2
+
+ # These two portions of the workspace are described in the mainlb
+ # subroutine in lbfgsb.f. See line 363.
+ s = wa[0: m*n].reshape(m, n)
+ y = wa[m*n: 2*m*n].reshape(m, n)
+
+ # See lbfgsb.f line 160 for this portion of the workspace.
+ # isave(31) = the total number of BFGS updates prior the current iteration;
+ n_bfgs_updates = isave[30]
+
+ n_corrs = min(n_bfgs_updates, maxcor)
+ hess_inv = LbfgsInvHessProduct(s[:n_corrs], y[:n_corrs])
+
+ task_str = task_str.decode()
+ return OptimizeResult(fun=f, jac=g, nfev=sf.nfev,
+ njev=sf.ngev,
+ nit=n_iterations, status=warnflag, message=task_str,
+ x=x, success=(warnflag == 0), hess_inv=hess_inv)
+
+
+class LbfgsInvHessProduct(LinearOperator):
+ """Linear operator for the L-BFGS approximate inverse Hessian.
+
+ This operator computes the product of a vector with the approximate inverse
+ of the Hessian of the objective function, using the L-BFGS limited
+ memory approximation to the inverse Hessian, accumulated during the
+ optimization.
+
+ Objects of this class implement the ``scipy.sparse.linalg.LinearOperator``
+ interface.
+
+ Parameters
+ ----------
+ sk : array_like, shape=(n_corr, n)
+ Array of `n_corr` most recent updates to the solution vector.
+ (See [1]).
+ yk : array_like, shape=(n_corr, n)
+ Array of `n_corr` most recent updates to the gradient. (See [1]).
+
+ References
+ ----------
+ .. [1] Nocedal, Jorge. "Updating quasi-Newton matrices with limited
+ storage." Mathematics of computation 35.151 (1980): 773-782.
+
+ """
+
+ def __init__(self, sk, yk):
+ """Construct the operator."""
+ if sk.shape != yk.shape or sk.ndim != 2:
+ raise ValueError('sk and yk must have matching shape, (n_corrs, n)')
+ n_corrs, n = sk.shape
+
+ super().__init__(dtype=np.float64, shape=(n, n))
+
+ self.sk = sk
+ self.yk = yk
+ self.n_corrs = n_corrs
+ self.rho = 1 / np.einsum('ij,ij->i', sk, yk)
+
+ def _matvec(self, x):
+ """Efficient matrix-vector multiply with the BFGS matrices.
+
+ This calculation is described in Section (4) of [1].
+
+ Parameters
+ ----------
+ x : ndarray
+ An array with shape (n,) or (n,1).
+
+ Returns
+ -------
+ y : ndarray
+ The matrix-vector product
+
+ """
+ s, y, n_corrs, rho = self.sk, self.yk, self.n_corrs, self.rho
+ q = np.array(x, dtype=self.dtype, copy=True)
+ if q.ndim == 2 and q.shape[1] == 1:
+ q = q.reshape(-1)
+
+ alpha = np.empty(n_corrs)
+
+ for i in range(n_corrs-1, -1, -1):
+ alpha[i] = rho[i] * np.dot(s[i], q)
+ q = q - alpha[i]*y[i]
+
+ r = q
+ for i in range(n_corrs):
+ beta = rho[i] * np.dot(y[i], r)
+ r = r + s[i] * (alpha[i] - beta)
+
+ return r
+
+ def todense(self):
+ """Return a dense array representation of this operator.
+
+ Returns
+ -------
+ arr : ndarray, shape=(n, n)
+ An array with the same shape and containing
+ the same data represented by this `LinearOperator`.
+
+ """
+ s, y, n_corrs, rho = self.sk, self.yk, self.n_corrs, self.rho
+ I = np.eye(*self.shape, dtype=self.dtype)
+ Hk = I
+
+ for i in range(n_corrs):
+ A1 = I - s[i][:, np.newaxis] * y[i][np.newaxis, :] * rho[i]
+ A2 = I - y[i][:, np.newaxis] * s[i][np.newaxis, :] * rho[i]
+
+ Hk = np.dot(A1, np.dot(Hk, A2)) + (rho[i] * s[i][:, np.newaxis] *
+ s[i][np.newaxis, :])
+ return Hk
from daCore.NumericObjects import EnsembleOfAnomalies
from daCore.NumericObjects import EnsembleOfBackgroundPerturbations
from daCore.NumericObjects import EnsemblePerturbationWithGivenCovariance
-from daCore.PlatformInfo import PlatformInfo
+from daCore.PlatformInfo import PlatformInfo, vfloat
mpr = PlatformInfo().MachinePrecision()
mfp = PlatformInfo().MaximumPrecision()
or selfA._toStore("CostFunctionJo") \
or selfA._toStore("CurrentOptimum") \
or selfA._toStore("APosterioriCovariance"):
- Jb = float( 0.5 * (Xa - Xb).T * (BI * (Xa - Xb)) )
- Jo = float( 0.5 * _Innovation.T * (RI * _Innovation) )
+ Jb = vfloat( 0.5 * (Xa - Xb).T * (BI * (Xa - Xb)) )
+ Jo = vfloat( 0.5 * _Innovation.T * (RI * _Innovation) )
J = Jb + Jo
selfA.StoredVariables["CostFunctionJb"].store( Jb )
selfA.StoredVariables["CostFunctionJo"].store( Jo )
residus = mesures - numpy.ravel( func(variables) )
surrogate = numpy.sum(residus**2 * poids) + (4.*quantile-2.) * numpy.sum(residus)
#
- increment = lastsurrogate-surrogate
+ increment = abs(lastsurrogate-surrogate)
poids = 1./(epsilon+numpy.abs(residus))
veps = 1. - 2. * quantile - residus * poids
lastsurrogate = -numpy.sum(residus * veps) - (1.-2.*quantile)*numpy.sum(residus)
import numpy, scipy, scipy.optimize, scipy.version
from daCore.NumericObjects import HessienneEstimation, QuantilesEstimations
-from daCore.PlatformInfo import vt
+from daCore.PlatformInfo import vt, vfloat
# ==============================================================================
def psas3dvar(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False):
if selfA._toStore("InnovationAtCurrentState"):
selfA.StoredVariables["InnovationAtCurrentState"].store( Innovation )
#
- Jb = float( 0.5 * _W.T @ (HBHTpR @ _W) )
- Jo = float( - _W.T @ Innovation )
+ Jb = vfloat( 0.5 * _W.T @ (HBHTpR @ _W) )
+ Jo = vfloat( - _W.T @ Innovation )
J = Jb + Jo
#
selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["CostFunctionJ"]) )
import daAlgorithms.Atoms.lbfgsb18hlt as optimiseur
elif vt("1.9.0") <= vt(scipy.version.version) <= vt("1.10.99"):
import daAlgorithms.Atoms.lbfgsb19hlt as optimiseur
+ elif vt("1.11.0") <= vt(scipy.version.version) <= vt("1.11.99"):
+ import daAlgorithms.Atoms.lbfgsb111hlt as optimiseur
else:
import scipy.optimize as optimiseur
Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
selfA.StoredVariables["OMB"].store( Innovation )
if selfA._toStore("SigmaObs2"):
TraceR = R.trace(Y.size)
- selfA.StoredVariables["SigmaObs2"].store( float( (Innovation.T @ oma) ) / TraceR )
+ selfA.StoredVariables["SigmaObs2"].store( vfloat( (Innovation.T @ oma) ) / TraceR )
if selfA._toStore("MahalanobisConsistency"):
selfA.StoredVariables["MahalanobisConsistency"].store( float( 2.*MinJ/Innovation.size ) )
if selfA._toStore("SimulationQuantiles"):
from daCore.NumericObjects import EnsembleOfBackgroundPerturbations
from daCore.NumericObjects import EnsembleOfCenteredPerturbations
from daCore.NumericObjects import EnsemblePerturbationWithGivenCovariance
-from daCore.PlatformInfo import PlatformInfo
+from daCore.PlatformInfo import PlatformInfo, vfloat
mpr = PlatformInfo().MachinePrecision()
mfp = PlatformInfo().MaximumPrecision()
or selfA._toStore("CostFunctionJo") \
or selfA._toStore("CurrentOptimum") \
or selfA._toStore("APosterioriCovariance"):
- Jb = float( 0.5 * (Xa - Xb).T * (BI * (Xa - Xb)) )
- Jo = float( 0.5 * _Innovation.T * (RI * _Innovation) )
+ Jb = vfloat( 0.5 * (Xa - Xb).T * (BI * (Xa - Xb)) )
+ Jo = vfloat( 0.5 * _Innovation.T * (RI * _Innovation) )
J = Jb + Jo
selfA.StoredVariables["CostFunctionJb"].store( Jb )
selfA.StoredVariables["CostFunctionJo"].store( Jo )
import numpy, scipy, scipy.optimize, scipy.version
from daCore.NumericObjects import HessienneEstimation, QuantilesEstimations
-from daCore.PlatformInfo import vt
+from daCore.PlatformInfo import vt, vfloat
# ==============================================================================
def std3dvar(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False):
if selfA._toStore("InnovationAtCurrentState"):
selfA.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
#
- Jb = float( 0.5 * (_X - Xb).T * (BI * (_X - Xb)) )
- Jo = float( 0.5 * _Innovation.T * (RI * _Innovation) )
+ Jb = vfloat( 0.5 * (_X - Xb).T * (BI * (_X - Xb)) )
+ Jo = vfloat( 0.5 * _Innovation.T * (RI * _Innovation) )
J = Jb + Jo
#
selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["CostFunctionJ"]) )
import daAlgorithms.Atoms.lbfgsb18hlt as optimiseur
elif vt("1.9.0") <= vt(scipy.version.version) <= vt("1.10.99"):
import daAlgorithms.Atoms.lbfgsb19hlt as optimiseur
+ elif vt("1.11.0") <= vt(scipy.version.version) <= vt("1.11.99"):
+ import daAlgorithms.Atoms.lbfgsb111hlt as optimiseur
else:
import scipy.optimize as optimiseur
Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
selfA.StoredVariables["OMB"].store( Innovation )
if selfA._toStore("SigmaObs2"):
TraceR = R.trace(Y.size)
- selfA.StoredVariables["SigmaObs2"].store( float( (Innovation.T @ oma) ) / TraceR )
+ selfA.StoredVariables["SigmaObs2"].store( vfloat( (Innovation.T @ oma) ) / TraceR )
if selfA._toStore("MahalanobisConsistency"):
selfA.StoredVariables["MahalanobisConsistency"].store( float( 2.*MinJ/Innovation.size ) )
if selfA._toStore("SimulationQuantiles"):
import numpy, scipy, scipy.optimize, scipy.version
from daCore.NumericObjects import ForceNumericBounds, ApplyBounds
-from daCore.PlatformInfo import PlatformInfo, vt
+from daCore.PlatformInfo import PlatformInfo, vt, vfloat
mpr = PlatformInfo().MachinePrecision()
mfp = PlatformInfo().MaximumPrecision()
selfA._toStore("CurrentState") or \
selfA._toStore("CurrentOptimum"):
selfA.StoredVariables["CurrentState"].store( _X )
- Jb = float( 0.5 * (_X - Xb).T * (BI * (_X - Xb)) )
+ Jb = vfloat( 0.5 * (_X - Xb).T * (BI * (_X - Xb)) )
selfA.DirectCalculation = [None,]
selfA.DirectInnovation = [None,]
Jo = 0.
selfA.DirectInnovation.append( _YmHMX )
#
# Ajout dans la fonctionnelle d'observation
- Jo = Jo + 0.5 * float( _YmHMX.T * (RI * _YmHMX) )
+ Jo = Jo + 0.5 * vfloat( _YmHMX.T * (RI * _YmHMX) )
J = Jb + Jo
#
selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["CostFunctionJ"]) )
import daAlgorithms.Atoms.lbfgsb18hlt as optimiseur
elif vt("1.9.0") <= vt(scipy.version.version) <= vt("1.10.99"):
import daAlgorithms.Atoms.lbfgsb19hlt as optimiseur
+ elif vt("1.11.0") <= vt(scipy.version.version) <= vt("1.11.99"):
+ import daAlgorithms.Atoms.lbfgsb111hlt as optimiseur
else:
import scipy.optimize as optimiseur
Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
__author__ = "Jean-Philippe ARGAUD"
import math, numpy, scipy
-from daCore.PlatformInfo import PlatformInfo
+from daCore.PlatformInfo import PlatformInfo, vfloat
mpr = PlatformInfo().MachinePrecision()
mfp = PlatformInfo().MaximumPrecision()
or selfA._toStore("CostFunctionJo") \
or selfA._toStore("CurrentOptimum") \
or selfA._toStore("APosterioriCovariance"):
- Jb = float( 0.5 * (Xa - Xb).T * (BI * (Xa - Xb)) )
- Jo = float( 0.5 * _Innovation.T * (RI * _Innovation) )
+ Jb = vfloat( 0.5 * (Xa - Xb).T * (BI * (Xa - Xb)) )
+ Jo = vfloat( 0.5 * _Innovation.T * (RI * _Innovation) )
J = Jb + Jo
selfA.StoredVariables["CostFunctionJb"].store( Jb )
selfA.StoredVariables["CostFunctionJo"].store( Jo )
import numpy, scipy, scipy.optimize, scipy.version
from daCore.NumericObjects import HessienneEstimation, QuantilesEstimations
from daCore.NumericObjects import RecentredBounds
-from daCore.PlatformInfo import PlatformInfo, vt
+from daCore.PlatformInfo import PlatformInfo, vt, vfloat
mpr = PlatformInfo().MachinePrecision()
# ==============================================================================
if selfA._toStore("InnovationAtCurrentState"):
selfA.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
#
- Jb = float( 0.5 * _V.T * (BT * _V) )
- Jo = float( 0.5 * _Innovation.T * (RI * _Innovation) )
+ Jb = vfloat( 0.5 * _V.T * (BT * _V) )
+ Jo = vfloat( 0.5 * _Innovation.T * (RI * _Innovation) )
J = Jb + Jo
#
selfA.StoredVariables["CurrentIterationNumber"].store( len(selfA.StoredVariables["CostFunctionJ"]) )
import daAlgorithms.Atoms.lbfgsb18hlt as optimiseur
elif vt("1.9.0") <= vt(scipy.version.version) <= vt("1.10.99"):
import daAlgorithms.Atoms.lbfgsb19hlt as optimiseur
+ elif vt("1.11.0") <= vt(scipy.version.version) <= vt("1.11.99"):
+ import daAlgorithms.Atoms.lbfgsb111hlt as optimiseur
else:
import scipy.optimize as optimiseur
Minimum, J_optimal, Informations = optimiseur.fmin_l_bfgs_b(
selfA.StoredVariables["OMB"].store( Innovation )
if selfA._toStore("SigmaObs2"):
TraceR = R.trace(Y.size)
- selfA.StoredVariables["SigmaObs2"].store( float( (Innovation.T @ oma) ) / TraceR )
+ selfA.StoredVariables["SigmaObs2"].store( vfloat( (Innovation.T @ oma) ) / TraceR )
if selfA._toStore("MahalanobisConsistency"):
selfA.StoredVariables["MahalanobisConsistency"].store( float( 2.*MinJ/Innovation.size ) )
if selfA._toStore("SimulationQuantiles"):
import numpy, logging, scipy.optimize
from daCore import BasicObjects, PlatformInfo
+from daCore.PlatformInfo import vfloat
# ==============================================================================
class ElementaryAlgorithm(BasicObjects.Algorithm):
if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","DA"]:
if BI is None or RI is None:
raise ValueError("Background and Observation error covariance matrices has to be properly defined!")
- Jb = 0.5 * (_X - Xb).T @ (BI @ (_X - Xb))
- Jo = 0.5 * _Innovation.T @ (RI @ _Innovation)
+ Jb = vfloat(0.5 * (_X - Xb).T @ (BI @ (_X - Xb)))
+ Jo = vfloat(0.5 * _Innovation.T @ (RI @ _Innovation))
elif QualityMeasure in ["WeightedLeastSquares","WLS"]:
if RI is None:
raise ValueError("Observation error covariance matrix has to be properly defined!")
Jb = 0.
- Jo = 0.5 * _Innovation.T @ (RI @ _Innovation)
+ Jo = vfloat(0.5 * _Innovation.T @ (RI @ _Innovation))
elif QualityMeasure in ["LeastSquares","LS","L2"]:
Jb = 0.
- Jo = 0.5 * _Innovation.T @ _Innovation
+ Jo = vfloat(0.5 * _Innovation.T @ _Innovation)
elif QualityMeasure in ["AbsoluteValue","L1"]:
Jb = 0.
- Jo = numpy.sum( numpy.abs(_Innovation) )
+ Jo = vfloat(numpy.sum( numpy.abs(_Innovation) ))
elif QualityMeasure in ["MaximumError","ME", "Linf"]:
Jb = 0.
- Jo = numpy.max( numpy.abs(_Innovation) )
+ Jo = vfloat(numpy.max( numpy.abs(_Innovation) ))
#
- J = float( Jb ) + float( Jo )
+ J = Jb + Jo
#
self.StoredVariables["CurrentIterationNumber"].store( len(self.StoredVariables["CostFunctionJ"]) )
self.StoredVariables["CostFunctionJb"].store( Jb )
import numpy, logging, scipy.optimize
from daCore import BasicObjects
+from daCore.PlatformInfo import vfloat
# ==============================================================================
class ElementaryAlgorithm(BasicObjects.Algorithm):
if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","DA"]:
if BI is None or RI is None:
raise ValueError("Background and Observation error covariance matrices has to be properly defined!")
- Jb = 0.5 * (_X - Xb).T @ (BI @ (_X - Xb))
- Jo = 0.5 * _Innovation.T @ (RI @ _Innovation)
+ Jb = vfloat(0.5 * (_X - Xb).T @ (BI @ (_X - Xb)))
+ Jo = vfloat(0.5 * _Innovation.T @ (RI @ _Innovation))
elif QualityMeasure in ["WeightedLeastSquares","WLS"]:
if RI is None:
raise ValueError("Observation error covariance matrix has to be properly defined!")
Jb = 0.
- Jo = 0.5 * _Innovation.T @ (RI @ _Innovation)
+ Jo = vfloat(0.5 * _Innovation.T @ (RI @ _Innovation))
elif QualityMeasure in ["LeastSquares","LS","L2"]:
Jb = 0.
- Jo = 0.5 * _Innovation.T @ _Innovation
+ Jo = vfloat(0.5 * _Innovation.T @ _Innovation)
elif QualityMeasure in ["AbsoluteValue","L1"]:
Jb = 0.
- Jo = numpy.sum( numpy.abs(_Innovation) )
+ Jo = vfloat(numpy.sum( numpy.abs(_Innovation) ))
elif QualityMeasure in ["MaximumError","ME", "Linf"]:
Jb = 0.
- Jo = numpy.max( numpy.abs(_Innovation) )
+ Jo = vfloat(numpy.max( numpy.abs(_Innovation) ))
#
- J = float( Jb ) + float( Jo )
+ J = Jb + Jo
#
self.StoredVariables["CurrentIterationNumber"].store( len(self.StoredVariables["CostFunctionJ"]) )
self.StoredVariables["CostFunctionJb"].store( Jb )
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import numpy
+from daCore import BasicObjects
+from daAlgorithms.Atoms import ecweim, eosg
+
+# ==============================================================================
+class ElementaryAlgorithm(BasicObjects.Algorithm):
+ def __init__(self):
+ # ModelInterpolationByROM
+ # ModelEvaluationByReducedInterpolation
+ # MeasuresInterpolationByReducedModel
+ #
+ BasicObjects.Algorithm.__init__(self, "INTERPOLATIONBYREDUCEDMODEL")
+ self.defineRequiredParameter(
+ name = "ReducedBasis",
+ default = [],
+ typecast = numpy.array,
+ message = "Base réduite, 1 vecteur par colonne",
+ )
+ self.defineRequiredParameter(
+ name = "OptimalLocations",
+ default = [],
+ typecast = tuple,
+ message = "Liste des indices ou noms de positions optimales de mesure selon l'ordre interne d'un vecteur de base",
+ )
+ self.defineRequiredParameter(
+ name = "ObservationsAlreadyRestrictedOnOptimalLocations",
+ default = True,
+ typecast = bool,
+ message = "Stockage des mesures restreintes a priori aux positions optimales de mesure ou non",
+ )
+ self.defineRequiredParameter(
+ name = "StoreSupplementaryCalculations",
+ default = [],
+ typecast = tuple,
+ message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
+ listval = [
+ "Analysis",
+ ]
+ )
+ self.requireInputArguments(
+ mandatory= ("Y",),
+ optional = (),
+ )
+ self.setAttributes(tags=(
+ "Reduction",
+ "Interpolation",
+ ))
+
+ def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
+ self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
+ #
+ #--------------------------
+ __rb = self._parameters["ReducedBasis"]
+ __ip = self._parameters["OptimalLocations"]
+ if len(__ip) != __rb.shape[1]:
+ raise ValueError("The number of optimal measurement locations (%i) and the dimension of the RB (%i) has to be the same."%(len(__ip),__rb.shape[1]))
+ #
+ # Nombre de pas identique au nombre de pas d'observations
+ if hasattr(Y,"stepnumber"):
+ duration = Y.stepnumber()
+ else:
+ duration = 2
+ #
+ for step in range(0,duration-1):
+ #
+ # La boucle sur les mesures permet une interpolation par jeu de mesure,
+ # sans qu'il y ait de lien entre deux jeux successifs de mesures.
+ #
+ # Important : les observations sont données sur tous les points
+ # possibles ou déjà restreintes aux points optimaux de mesure, mais
+ # ne sont utilisés qu'aux points optimaux
+ if hasattr(Y,"store"):
+ _Ynpu = numpy.ravel( Y[step+1] ).reshape((-1,1))
+ else:
+ _Ynpu = numpy.ravel( Y ).reshape((-1,1))
+ if self._parameters["ObservationsAlreadyRestrictedOnOptimalLocations"]:
+ __rm = _Ynpu
+ else:
+ __rm = _Ynpu[__ip]
+ #
+ # Interpolation
+ ecweim.EIM_online(self, __rb, __rm, __ip)
+ #--------------------------
+ #
+ self._post_run(HO)
+ return 0
+
+# ==============================================================================
+if __name__ == "__main__":
+ print('\n AUTODIAGNOSTIC\n')
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import numpy, math
+from daCore import BasicObjects
+from daCore.PlatformInfo import vfloat
+from daAlgorithms.Atoms import ecweim, eosg
+
+# ==============================================================================
+class ElementaryAlgorithm(BasicObjects.Algorithm):
+ def __init__(self):
+ #
+ BasicObjects.Algorithm.__init__(self, "INTERPOLATIONBYREDUCEDMODEL")
+ self.defineRequiredParameter(
+ name = "ReducedBasis",
+ default = [],
+ typecast = numpy.array,
+ message = "Base réduite, 1 vecteur par colonne",
+ )
+ self.defineRequiredParameter(
+ name = "MeasurementLocations",
+ default = [],
+ typecast = tuple,
+ message = "Liste des indices ou noms de positions optimales de mesure selon l'ordre interne d'un vecteur de base",
+ )
+ self.defineRequiredParameter(
+ name = "EnsembleOfSnapshots",
+ default = [],
+ typecast = numpy.array,
+ message = "Ensemble de vecteurs d'état physique (snapshots), 1 état par colonne (Test Set)",
+ )
+ self.defineRequiredParameter(
+ name = "ErrorNorm",
+ default = "L2",
+ typecast = str,
+ message = "Norme d'erreur utilisée pour le critère d'optimalité des positions",
+ listval = ["L2", "Linf"]
+ )
+ self.defineRequiredParameter(
+ name = "ShowElementarySummary",
+ default = True,
+ typecast = bool,
+ message = "Calcule et affiche un résumé à chaque évaluation élémentaire",
+ )
+ self.defineRequiredParameter(
+ name = "NumberOfPrintedDigits",
+ default = 5,
+ typecast = int,
+ message = "Nombre de chiffres affichés pour les impressions de réels",
+ minval = 0,
+ )
+ self.defineRequiredParameter(
+ name = "ResultTitle",
+ default = "",
+ typecast = str,
+ message = "Titre du tableau et de la figure",
+ )
+ self.requireInputArguments(
+ mandatory= (),
+ optional = (),
+ )
+ self.setAttributes(tags=(
+ "Reduction",
+ "Interpolation",
+ ))
+
+ def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
+ self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
+ #
+ __rb = self._parameters["ReducedBasis"]
+ __ip = self._parameters["MeasurementLocations"]
+ __eos = self._parameters["EnsembleOfSnapshots"]
+ __rdim, __nrb = __rb.shape
+ __fdim, __nsn = __eos.shape
+ #
+ if __fdim != __rdim:
+ raise ValueError("The dimension of each snapshot (%i) has to be equal to the dimension of each reduced basis vector."%(__fdim,__rdim))
+ if __fdim < len(__ip):
+ raise ValueError("The dimension of each snapshot (%i) has to be greater or equal to the number of optimal measurement locations (%i)."%(__fdim,len(__ip)))
+ #
+ #--------------------------
+ __s = self._parameters["ShowElementarySummary"]
+ __p = self._parameters["NumberOfPrintedDigits"]
+ #
+ __marge = 5*u" "
+ __flech = 3*"="+"> "
+ __ordre = int(math.log10(__nsn))+1
+ msgs = ("\n") # 1
+ if len(self._parameters["ResultTitle"]) > 0:
+ __rt = str(self._parameters["ResultTitle"])
+ msgs += (__marge + "====" + "="*len(__rt) + "====\n")
+ msgs += (__marge + " " + __rt + "\n")
+ msgs += (__marge + "====" + "="*len(__rt) + "====\n")
+ else:
+ msgs += (__marge + "%s\n"%self._name)
+ msgs += (__marge + "%s\n"%("="*len(self._name),))
+ #
+ msgs += ("\n")
+ msgs += (__marge + "This test allows to analyze the quality of the interpolation of states,\n")
+ msgs += (__marge + "using a reduced basis and measurements at specified points.\n")
+ msgs += ("\n")
+ msgs += (__marge + "The output shows simple statistics related to normalized errors of the\n")
+ msgs += (__marge + "interpolation with reduced basis using pseudo-measures coming from each\n")
+ msgs += (__marge + "snapshot included in the given test set.\n")
+ msgs += ("\n")
+ msgs += (__marge + "Warning: in order to be coherent, this test has to use the same norm\n")
+ msgs += (__marge + "than the one used to build the reduced basis. The user chosen norm in\n")
+ msgs += (__marge + "this test is presently \"%s\". Check the RB building one.\n"%(self._parameters["ErrorNorm"],))
+ msgs += (__marge + "\n")
+ msgs += ("\n")
+ msgs += (__flech + "Information before launching:\n")
+ msgs += (__marge + "-----------------------------\n")
+ msgs += ("\n")
+ msgs += (__marge + "Characteristics of input data:\n")
+ msgs += (__marge + " State dimension................: %i\n")%__fdim
+ msgs += (__marge + " Dimension of RB................: %i\n")%__nrb
+ msgs += (__marge + " Number of measures locations...: %i\n")%len(__ip)
+ msgs += (__marge + " Number of snapshots to test....: %i\n")%__nsn
+ msgs += ("\n")
+ msgs += (__marge + "%s\n\n"%("-"*75,))
+ #
+ msgs += (__flech + "Interpolation error test for all given states:\n")
+ msgs += (__marge + "----------------------------------------------\n")
+ msgs += ("\n")
+ for ns in range(__nsn):
+ __rm = __eos[__ip,ns]
+ __im = ecweim.EIM_online(self, __rb, __eos[__ip,ns], __ip)
+ #
+ if self._parameters["ErrorNorm"] == "L2":
+ __ecart = vfloat(numpy.linalg.norm( __eos[:,ns] - __im ) / numpy.linalg.norm( __eos[:,ns] ))
+ else:
+ __ecart = vfloat(numpy.linalg.norm( __eos[:,ns] - __im, ord=numpy.inf ) / numpy.linalg.norm( __eos[:,ns], ord=numpy.inf ))
+ if __s:
+ msgs += (__marge + "Normalized interpolation error (%s) for state number %0"+str(__ordre)+"i..: %."+str(__p)+"e\n")%(self._parameters["ErrorNorm"],ns,__ecart)
+ #
+ msgs += ("\n")
+ msgs += (__marge + "End of the \"%s\" verification\n\n"%self._name)
+ msgs += (__marge + "%s\n"%("-"*75,))
+ print(msgs) # 3
+ #
+ self._post_run(HO)
+ return 0
+
+# ==============================================================================
+if __name__ == "__main__":
+ print('\n AUTODIAGNOSTIC\n')
typecast = str,
message = "Variant ou formulation de la méthode",
listval = [
- "PositioningByEIM",
- "PositioningBylcEIM",
+ "EIM", "PositioningByEIM",
+ "lcEIM", "PositioningBylcEIM",
],
)
self.defineRequiredParameter(
name = "EnsembleOfSnapshots",
default = [],
typecast = numpy.array,
- message = "Ensemble de vecteurs d'état physique (snapshots), 1 état par colonne",
+ message = "Ensemble de vecteurs d'état physique (snapshots), 1 état par colonne (Training Set)",
)
self.defineRequiredParameter(
name = "MaximumNumberOfLocations",
self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
#
#--------------------------
- if self._parameters["Variant"] == "PositioningBylcEIM":
+ if self._parameters["Variant"] in ["lcEIM", "PositioningBylcEIM"]:
if len(self._parameters["EnsembleOfSnapshots"]) > 0:
if self._toStore("EnsembleOfSimulations"):
self.StoredVariables["EnsembleOfSimulations"].store( self._parameters["EnsembleOfSnapshots"] )
else:
raise ValueError("Snapshots or Operator have to be given in order to launch the analysis")
#
- elif self._parameters["Variant"] == "PositioningByEIM":
+ elif self._parameters["Variant"] in ["EIM", "PositioningByEIM"]:
if len(self._parameters["EnsembleOfSnapshots"]) > 0:
if self._toStore("EnsembleOfSimulations"):
self.StoredVariables["EnsembleOfSimulations"].store( self._parameters["EnsembleOfSnapshots"] )
"LBFGSB",
"TNC",
"CG",
- "NCG",
"BFGS",
"LM",
],
+ listadv = [
+ "NCG",
+ ],
)
self.defineRequiredParameter(
name = "EstimationOf",
# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
import numpy, copy, logging
-from daCore import BasicObjects, PlatformInfo
-mpr = PlatformInfo.PlatformInfo().MachinePrecision()
-mfp = PlatformInfo.PlatformInfo().MaximumPrecision()
+from daCore import BasicObjects
+from daCore.PlatformInfo import PlatformInfo, vfloat
+mpr = PlatformInfo().MachinePrecision()
+mfp = PlatformInfo().MaximumPrecision()
# ==============================================================================
class ElementaryAlgorithm(BasicObjects.Algorithm):
_HX = numpy.ravel( HmX )
_X0 = numpy.ravel( X0 )
_Y0 = numpy.ravel( Y0 )
- Jb = float( 0.5 * (_X - _X0).T * (BI * (_X - _X0)) )
- Jo = float( 0.5 * (_Y0 - _HX).T * (RI * (_Y0 - _HX)) )
+ Jb = vfloat( 0.5 * (_X - _X0).T * (BI * (_X - _X0)) )
+ Jo = vfloat( 0.5 * (_Y0 - _HX).T * (RI * (_Y0 - _HX)) )
J = Jb + Jo
self.StoredVariables["CostFunctionJb"].store( Jb )
self.StoredVariables["CostFunctionJo"].store( Jo )
import numpy, logging, copy
from daCore import BasicObjects
-from daAlgorithms.Atoms import ecwnpso, ecwopso, ecwspso
+from daAlgorithms.Atoms import ecwnpso, ecwopso, ecwapso, ecwspso, ecwpspso
# ==============================================================================
class ElementaryAlgorithm(BasicObjects.Algorithm):
"SPSO-2011",
],
listadv = [
+ "SPSO-2011-AIS",
+ "SPSO-2011-SIS",
+ "SPSO-2011-PSIS",
"PSO",
],
)
elif self._parameters["Variant"] in ["OGCR"]:
ecwopso.ecwopso(self, Xb, Y, HO, R, B)
#
- elif self._parameters["Variant"] in ["SPSO-2011"]:
+ elif self._parameters["Variant"] in ["SPSO-2011", "SPSO-2011-AIS"]:
+ ecwapso.ecwapso(self, Xb, Y, HO, R, B)
+ #
+ elif self._parameters["Variant"] in ["SPSO-2011-SIS"]:
ecwspso.ecwspso(self, Xb, Y, HO, R, B)
#
+ elif self._parameters["Variant"] in ["SPSO-2011-PSIS"]:
+ ecwpspso.ecwpspso(self, Xb, Y, HO, R, B)
+ #
#--------------------------
else:
raise ValueError("Error in Variant name: %s"%self._parameters["Variant"])
name = "Quantile",
default = 0.5,
typecast = float,
- message = "Quantile pour la regression de quantile",
+ message = "Quantile pour la régression de quantile",
minval = 0.,
maxval = 1.,
)
#
# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-import numpy, logging
+import numpy, logging, copy
from daCore import BasicObjects, NumericObjects, PlatformInfo
+from daCore.PlatformInfo import PlatformInfo, vfloat
from daAlgorithms.Atoms import eosg
-mfp = PlatformInfo.PlatformInfo().MaximumPrecision()
+mfp = PlatformInfo().MaximumPrecision()
# ==============================================================================
class ElementaryAlgorithm(BasicObjects.Algorithm):
def __init__(self):
BasicObjects.Algorithm.__init__(self, "SAMPLINGTEST")
+ self.defineRequiredParameter(
+ name = "EnsembleOfSnapshots",
+ default = [],
+ typecast = numpy.array,
+ message = "Ensemble de vecteurs d'état physique (snapshots), 1 état par colonne",
+ )
self.defineRequiredParameter(
name = "SampleAsnUplet",
default = [],
message = "Graine fixée pour le générateur aléatoire",
)
self.requireInputArguments(
- mandatory= ("Xb", "Y", "HO", "R", "B"),
+ mandatory= ("Xb", "Y", "R", "B"),
+ optional = ("HO"),
)
self.setAttributes(tags=(
"Checking",
if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","AugmentedPonderatedLeastSquares","APLS","DA"]:
if BI is None or RI is None:
raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
- Jb = float( 0.5 * (_X - Xb).T * (BI * (_X - Xb)) )
- Jo = float( 0.5 * _Innovation.T * (RI * _Innovation) )
+ Jb = vfloat( 0.5 * (_X - Xb).T * (BI * (_X - Xb)) )
+ Jo = vfloat( 0.5 * _Innovation.T * (RI * _Innovation) )
elif QualityMeasure in ["WeightedLeastSquares","WLS","PonderatedLeastSquares","PLS"]:
if RI is None:
raise ValueError("Observation error covariance matrix has to be properly defined!")
Jb = 0.
- Jo = float( 0.5 * _Innovation.T * (RI * _Innovation) )
+ Jo = vfloat( 0.5 * _Innovation.T * (RI * _Innovation) )
elif QualityMeasure in ["LeastSquares","LS","L2"]:
Jb = 0.
- Jo = float( 0.5 * _Innovation.T @ _Innovation )
+ Jo = vfloat( 0.5 * _Innovation.T @ _Innovation )
elif QualityMeasure in ["AbsoluteValue","L1"]:
Jb = 0.
- Jo = float( numpy.sum( numpy.abs(_Innovation), dtype=mfp ) )
+ Jo = vfloat( numpy.sum( numpy.abs(_Innovation), dtype=mfp ) )
elif QualityMeasure in ["MaximumError","ME", "Linf"]:
Jb = 0.
- Jo = numpy.max( numpy.abs(_Innovation) )
+ Jo = vfloat(numpy.max( numpy.abs(_Innovation) ))
#
J = Jb + Jo
if self._toStore("Innovation"):
return J, Jb, Jo
#
# ----------
- EOX, EOS = eosg.eosg(self, Xb, HO, True, False)
+ if len(self._parameters["EnsembleOfSnapshots"]) > 0:
+ sampleList = NumericObjects.BuildComplexSampleList(
+ self._parameters["SampleAsnUplet"],
+ self._parameters["SampleAsExplicitHyperCube"],
+ self._parameters["SampleAsMinMaxStepHyperCube"],
+ self._parameters["SampleAsIndependantRandomVariables"],
+ Xb,
+ )
+ EOX = numpy.stack(tuple(copy.copy(sampleList)), axis=1)
+ EOS = self._parameters["EnsembleOfSnapshots"]
+ #
+ if self._toStore("EnsembleOfStates"):
+ self.StoredVariables["EnsembleOfStates"].store( EOX )
+ if self._toStore("EnsembleOfSimulations"):
+ self.StoredVariables["EnsembleOfSimulations"].store( EOS )
+ else:
+ EOX, EOS = eosg.eosg(self, Xb, HO, True, False)
#
for i in range(EOS.shape[1]):
J, Jb, Jo = CostFunction( EOX[:,i], EOS[:,i], self._parameters["QualityCriterion"])
import numpy
from daCore import BasicObjects
+from daCore.PlatformInfo import vfloat
# ==============================================================================
class ElementaryAlgorithm(BasicObjects.Algorithm):
if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","DA"]:
if BI is None or RI is None:
raise ValueError("Background and Observation error covariance matrices has to be properly defined!")
- Jb = 0.5 * (_X - Xb).T @ (BI @ (_X - Xb))
- Jo = 0.5 * _Innovation.T @ (RI @ _Innovation)
+ Jb = vfloat(0.5 * (_X - Xb).T @ (BI @ (_X - Xb)))
+ Jo = vfloat(0.5 * _Innovation.T @ (RI @ _Innovation))
elif QualityMeasure in ["WeightedLeastSquares","WLS"]:
if RI is None:
raise ValueError("Observation error covariance matrix has to be properly defined!")
Jb = 0.
- Jo = 0.5 * _Innovation.T @ (RI @ _Innovation)
+ Jo = vfloat(0.5 * _Innovation.T @ (RI @ _Innovation))
elif QualityMeasure in ["LeastSquares","LS","L2"]:
Jb = 0.
- Jo = 0.5 * _Innovation.T @ _Innovation
+ Jo = vfloat(0.5 * _Innovation.T @ _Innovation)
elif QualityMeasure in ["AbsoluteValue","L1"]:
Jb = 0.
- Jo = numpy.sum( numpy.abs(_Innovation) )
+ Jo = vfloat(numpy.sum( numpy.abs(_Innovation) ))
elif QualityMeasure in ["MaximumError","ME", "Linf"]:
Jb = 0.
- Jo = numpy.max( numpy.abs(_Innovation) )
+ Jo = vfloat(numpy.max( numpy.abs(_Innovation) ))
#
- J = float( Jb ) + float( Jo )
+ J = Jb + Jo
#
return J
#
"""
Initialise un logging à la console pour TOUS les niveaux de messages.
"""
- logging.basicConfig(
- format = '%(levelname)-8s %(message)s',
- level = level,
- stream = sys.stdout,
- )
+ if sys.version_info.major <= 3 and sys.version_info.minor < 8:
+ if logging.getLogger().hasHandlers():
+ while logging.getLogger().hasHandlers():
+ logging.getLogger().removeHandler( logging.getLogger().handlers[-1] )
+ __sys_stdout = logging.StreamHandler(sys.stdout)
+ __sys_stdout.setFormatter(logging.Formatter('%(levelname)-8s %(message)s'))
+ logging.getLogger().addHandler(__sys_stdout)
+ else:
+ logging.basicConfig(
+ format = '%(levelname)-8s %(message)s',
+ level = level,
+ stream = sys.stdout,
+ )
+ else: # Actif lorsque Python > 3.7
+ logging.basicConfig(
+ format = '%(levelname)-8s %(message)s',
+ level = level,
+ stream = sys.stdout,
+ force = True,
+ )
self.__logfile = None
#
# Initialise l'affichage de logging
Permet de disposer des messages dans un fichier EN PLUS de la console.
"""
if self.__logfile is not None:
- # Supprime le précédent mode de stockage fichier s'il exsitait
+ # Supprime le précédent mode de stockage fichier s'il existait
logging.getLogger().removeHandler(self.__logfile)
self.__logfile = logging.FileHandler(filename, filemode)
self.__logfile.setLevel(level)
import os, copy, types, sys, logging, math, numpy, itertools
from daCore.BasicObjects import Operator, Covariance, PartialAlgorithm
-from daCore.PlatformInfo import PlatformInfo
+from daCore.PlatformInfo import PlatformInfo, vfloat
mpr = PlatformInfo().MachinePrecision()
mfp = PlatformInfo().MaximumPrecision()
# logging.getLogger().setLevel(logging.DEBUG)
assert __LMatrix[0].size == _Idwy.size, "Incorrect size of elements"
__Produit = numpy.zeros(len(__LMatrix))
for i, col in enumerate(__LMatrix):
- __Produit[i] = float( _Idwy @ col)
+ __Produit[i] = vfloat( _Idwy @ col)
return __Produit
else:
__Produit = None
if logging.getLogger().level < logging.WARNING: # La vérification n'a lieu qu'en debug
try:
numpy.linalg.cholesky( __A )
+ logging.debug("%s La matrice de covariance a posteriori A est bien symétrique définie positive."%(__selfA._name,))
except Exception:
raise ValueError(
"The %s a posteriori covariance matrix A"%(__selfA._name,)+\
__Bounds = ForceNumericBounds( __Bounds )
__BoxBounds = ForceNumericBounds( __BoxBounds )
if __Bounds is None and __BoxBounds is None:
- raise ValueError("Algorithm %s requires bounds on all variables (by Bounds), or on all variables increments (by BoxBounds), or both, to be explicitly given."%(__Name,))
+ raise ValueError("Algorithm %s requires bounds on all variables (by Bounds), or on all variable increments (by BoxBounds), or both, to be explicitly given."%(__Name,))
elif __Bounds is None and __BoxBounds is not None:
__Bounds = __BoxBounds
- logging.debug("%s Définition des bornes de paramètres à partir des bornes d'incréments courantes"%(__Name,))
+ logging.debug("%s Definition of parameter bounds from current parameter increment bounds"%(__Name,))
elif __Bounds is not None and __BoxBounds is None:
__BoxBounds = __Multiplier * (__Bounds - __Xini.reshape((-1,1))) # "M * [Xmin,Xmax]-Xini"
- logging.debug("%s Définition des bornes d'incréments de paramètres à partir des bornes courantes"%(__Name,))
+ logging.debug("%s Definition of parameter increment bounds from current parameter bounds"%(__Name,))
return __Bounds, __BoxBounds
# ==============================================================================
__msg += "\n%s%30s : %s" %(__prefix,"MatplotLib version",self.getMatplotlibVersion())
__msg += "\n%s%30s : %s" %(__prefix,"GnuplotPy version",self.getGnuplotVersion())
__msg += "\n%s%30s : %s" %(__prefix,"Sphinx version",self.getSphinxVersion())
+ __msg += "\n%s%30s : %s" %(__prefix,"Fmpy version",self.getFmpyVersion())
return __msg
#
def getAllInformation(self, __prefix="", __title="Whole system information"):
__version = "0.0.0"
return __version
#
+ def getFmpyVersion(self):
+ "Retourne la version de fmpy disponible"
+ if has_fmpy:
+ __version = fmpy.__version__
+ else:
+ __version = "0.0.0"
+ return __version
+ #
def getCurrentMemorySize(self):
"Retourne la taille mémoire courante utilisée"
return 1
except ImportError:
has_sdf = False
+try:
+ import fmpy
+ has_fmpy = True
+except ImportError:
+ has_fmpy = False
+
has_salome = bool( "SALOME_ROOT_DIR" in os.environ )
has_yacs = bool( "YACS_ROOT_DIR" in os.environ )
has_adao = bool( "ADAO_ROOT_DIR" in os.environ )
raise ValueError("Cannot convert \"%s\" as a D/M/Y H:M date"%d)
return __number
+def vfloat(__value :numpy.ndarray):
+ """
+ Conversion en flottant d'un vecteur de taille 1 et de dimensions quelconques
+ """
+ if hasattr(__value,"size") and __value.size == 1:
+ return float(__value.flat[0])
+ elif isinstance(__value, (float,int)):
+ return float(__value)
+ else:
+ raise ValueError("Error in converting multiple float values from array when waiting for only one")
+
def strvect2liststr( __strvect ):
"""
Fonction de secours, conversion d'une chaîne de caractères de
__all__ = []
name = "ADAO"
-version = "9.11.0"
+version = "9.12.0"
year = "2023"
-date = "lundi 22 mai 2023, 22:22:22 (UTC+0100)"
+date = "mardi 12 décembre 2023, 22:22:22 (UTC+0100)"
longname = name + ", a module for Data Assimilation and Optimization"
cata = "V" + version.replace(".","_")
__init__.py
${CMAKE_CURRENT_BINARY_DIR}/prefs_ADAO.py
prefs.py
- traduitADAOsansToV9_11_0.py
- traduitADAOV7_4_0ToV9_11_0.py
- traduitADAOV7_5_0ToV9_11_0.py
- traduitADAOV7_5_1ToV9_11_0.py
- traduitADAOV7_6_0ToV9_11_0.py
- traduitADAOV7_7_0ToV9_11_0.py
- traduitADAOV7_8_0ToV9_11_0.py
- traduitADAOV8_1_0ToV9_11_0.py
- traduitADAOV8_2_0ToV9_11_0.py
- traduitADAOV8_3_0ToV9_11_0.py
- traduitADAOV8_4_0ToV9_11_0.py
- traduitADAOV8_5_0ToV9_11_0.py
- traduitADAOV8_6_0ToV9_11_0.py
- traduitADAOV9_2_0ToV9_11_0.py
- traduitADAOV9_3_0ToV9_11_0.py
- traduitADAOV9_4_0ToV9_11_0.py
- traduitADAOV9_5_0ToV9_11_0.py
- traduitADAOV9_6_0ToV9_11_0.py
- traduitADAOV9_7_0ToV9_11_0.py
- traduitADAOV9_8_0ToV9_11_0.py
- traduitADAOV9_9_0ToV9_11_0.py
- traduitADAOV9_10_0ToV9_11_0.py
+ traduitADAOsansToV9_12_0.py
+ traduitADAOV7_4_0ToV9_12_0.py
+ traduitADAOV7_5_0ToV9_12_0.py
+ traduitADAOV7_5_1ToV9_12_0.py
+ traduitADAOV7_6_0ToV9_12_0.py
+ traduitADAOV7_7_0ToV9_12_0.py
+ traduitADAOV7_8_0ToV9_12_0.py
+ traduitADAOV8_1_0ToV9_12_0.py
+ traduitADAOV8_2_0ToV9_12_0.py
+ traduitADAOV8_3_0ToV9_12_0.py
+ traduitADAOV8_4_0ToV9_12_0.py
+ traduitADAOV8_5_0ToV9_12_0.py
+ traduitADAOV8_6_0ToV9_12_0.py
+ traduitADAOV9_2_0ToV9_12_0.py
+ traduitADAOV9_3_0ToV9_12_0.py
+ traduitADAOV9_4_0ToV9_12_0.py
+ traduitADAOV9_5_0ToV9_12_0.py
+ traduitADAOV9_6_0ToV9_12_0.py
+ traduitADAOV9_7_0ToV9_12_0.py
+ traduitADAOV9_8_0ToV9_12_0.py
+ traduitADAOV9_9_0ToV9_12_0.py
+ traduitADAOV9_10_0ToV9_12_0.py
+ traduitADAOV9_11_0ToV9_12_0.py
)
install(FILES ${DAEFICAS_FILES} DESTINATION "${ADAO_SCRIPT_PYTHON}/adao/daEficas")
__init__.py \
prefs_ADAO.py \
prefs.py \
- traduitADAOsansToV9_11_0.py \
- traduitADAOV7_4_0ToV9_11_0.py \
- traduitADAOV7_5_0ToV9_11_0.py \
- traduitADAOV7_5_1ToV9_11_0.py \
- traduitADAOV7_6_0ToV9_11_0.py \
- traduitADAOV7_7_0ToV9_11_0.py \
- traduitADAOV7_8_0ToV9_11_0.py \
- traduitADAOV8_1_0ToV9_11_0.py \
- traduitADAOV8_2_0ToV9_11_0.py \
- traduitADAOV8_3_0ToV9_11_0.py \
- traduitADAOV8_4_0ToV9_11_0.py \
- traduitADAOV8_5_0ToV9_11_0.py \
- traduitADAOV8_6_0ToV9_11_0.py \
- traduitADAOV9_2_0ToV9_11_0.py \
- traduitADAOV9_3_0ToV9_11_0.py \
- traduitADAOV9_4_0ToV9_11_0.py \
- traduitADAOV9_5_0ToV9_11_0.py \
- traduitADAOV9_6_0ToV9_11_0.py \
- traduitADAOV9_7_0ToV9_11_0.py \
- traduitADAOV9_8_0ToV9_11_0.py \
- traduitADAOV9_9_0ToV9_11_0.py \
- traduitADAOV9_10_0ToV9_11_0.py
+ traduitADAOsansToV9_12_0.py \
+ traduitADAOV7_4_0ToV9_12_0.py \
+ traduitADAOV7_5_0ToV9_12_0.py \
+ traduitADAOV7_5_1ToV9_12_0.py \
+ traduitADAOV7_6_0ToV9_12_0.py \
+ traduitADAOV7_7_0ToV9_12_0.py \
+ traduitADAOV7_8_0ToV9_12_0.py \
+ traduitADAOV8_1_0ToV9_12_0.py \
+ traduitADAOV8_2_0ToV9_12_0.py \
+ traduitADAOV8_3_0ToV9_12_0.py \
+ traduitADAOV8_4_0ToV9_12_0.py \
+ traduitADAOV8_5_0ToV9_12_0.py \
+ traduitADAOV8_6_0ToV9_12_0.py \
+ traduitADAOV9_2_0ToV9_12_0.py \
+ traduitADAOV9_3_0ToV9_12_0.py \
+ traduitADAOV9_4_0ToV9_12_0.py \
+ traduitADAOV9_5_0ToV9_12_0.py \
+ traduitADAOV9_6_0ToV9_12_0.py \
+ traduitADAOV9_7_0ToV9_12_0.py \
+ traduitADAOV9_8_0ToV9_12_0.py \
+ traduitADAOV9_9_0ToV9_12_0.py \
+ traduitADAOV9_10_0ToV9_12_0.py \
+ traduitADAOV9_11_0ToV9_12_0.py
EXTRA_DIST = prefs_ADAO.py.in
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- "ASSIMILATION_STUDY",
- "CHECKING_STUDY",
- )
-
-dict_erreurs = {
- "ASSIMILATION_STUDY":"Changements dans l'arbre et dans les noms",
- "CHECKING_STUDY":"Changements dans l'arbre et dans les noms",
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
-
- #Parse les mocles des commandes
- parseKeywords(jdc.root)
- genereErreurPourCommande(jdc,('Algorithm','AlgorithmParameters','FunctionDict'))
- # ==========================================================================
-
- for command in atraiter:
- # Insere le MC s'il n'existe pas
- chercheOperInsereFacteurSiRegle(jdc, command, "AlgorithmParameters",((("AlgorithmParameters",),"nexistepasMCFParmi"),))
- # Deplace le MC
- moveMotClefInOperToFact(jdc, command, "Algorithm", "AlgorithmParameters", plusieursFois=False)
- # Renomme le MC
- renameMotCleInFact(jdc, command, "AlgorithmParameters", "INPUT_TYPE", "Parameters")
- # Renomme le MC
- renameMotCle(jdc, command, "Study_name", "StudyName")
- renameMotCle(jdc, command, "Study_repertory", "StudyRepertory")
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "FunctionDict", "ScriptWithSwitch", fsrc )
- fsrc = re.sub( "FUNCTIONDICT_FILE", "SCRIPTWITHSWITCH_FILE", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ "ASSIMILATION_STUDY",
+ "CHECKING_STUDY",
+ )
+
+dict_erreurs = {
+ "ASSIMILATION_STUDY":"Changements dans l'arbre et dans les noms",
+ "CHECKING_STUDY":"Changements dans l'arbre et dans les noms",
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+
+ #Parse les mocles des commandes
+ parseKeywords(jdc.root)
+ genereErreurPourCommande(jdc,('Algorithm','AlgorithmParameters','FunctionDict'))
+ # ==========================================================================
+
+ for command in atraiter:
+ # Insere le MC s'il n'existe pas
+ chercheOperInsereFacteurSiRegle(jdc, command, "AlgorithmParameters",((("AlgorithmParameters",),"nexistepasMCFParmi"),))
+ # Deplace le MC
+ moveMotClefInOperToFact(jdc, command, "Algorithm", "AlgorithmParameters", plusieursFois=False)
+ # Renomme le MC
+ renameMotCleInFact(jdc, command, "AlgorithmParameters", "INPUT_TYPE", "Parameters")
+ # Renomme le MC
+ renameMotCle(jdc, command, "Study_name", "StudyName")
+ renameMotCle(jdc, command, "Study_repertory", "StudyRepertory")
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "FunctionDict", "ScriptWithSwitch", fsrc )
+ fsrc = re.sub( "FUNCTIONDICT_FILE", "SCRIPTWITHSWITCH_FILE", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- "ASSIMILATION_STUDY",
- "CHECKING_STUDY",
- )
-
-dict_erreurs = {
- "ASSIMILATION_STUDY":"Changements dans l'arbre et dans les noms",
- "CHECKING_STUDY":"Changements dans l'arbre et dans les noms",
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
-
- #Parse les mocles des commandes
- parseKeywords(jdc.root)
- genereErreurPourCommande(jdc,('Algorithm','AlgorithmParameters','FunctionDict'))
- # ==========================================================================
-
- for command in atraiter:
- # Insere le MC s'il n'existe pas
- chercheOperInsereFacteurSiRegle(jdc, command, "AlgorithmParameters",((("AlgorithmParameters",),"nexistepasMCFParmi"),))
- # Deplace le MC
- moveMotClefInOperToFact(jdc, command, "Algorithm", "AlgorithmParameters", plusieursFois=False)
- # Renomme le MC
- renameMotCleInFact(jdc, command, "AlgorithmParameters", "INPUT_TYPE", "Parameters")
- # Renomme le MC
- renameMotCle(jdc, command, "Study_name", "StudyName")
- renameMotCle(jdc, command, "Study_repertory", "StudyRepertory")
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "FunctionDict", "ScriptWithSwitch", fsrc )
- fsrc = re.sub( "FUNCTIONDICT_FILE", "SCRIPTWITHSWITCH_FILE", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ "ASSIMILATION_STUDY",
+ "CHECKING_STUDY",
+ )
+
+dict_erreurs = {
+ "ASSIMILATION_STUDY":"Changements dans l'arbre et dans les noms",
+ "CHECKING_STUDY":"Changements dans l'arbre et dans les noms",
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+
+ #Parse les mocles des commandes
+ parseKeywords(jdc.root)
+ genereErreurPourCommande(jdc,('Algorithm','AlgorithmParameters','FunctionDict'))
+ # ==========================================================================
+
+ for command in atraiter:
+ # Insere le MC s'il n'existe pas
+ chercheOperInsereFacteurSiRegle(jdc, command, "AlgorithmParameters",((("AlgorithmParameters",),"nexistepasMCFParmi"),))
+ # Deplace le MC
+ moveMotClefInOperToFact(jdc, command, "Algorithm", "AlgorithmParameters", plusieursFois=False)
+ # Renomme le MC
+ renameMotCleInFact(jdc, command, "AlgorithmParameters", "INPUT_TYPE", "Parameters")
+ # Renomme le MC
+ renameMotCle(jdc, command, "Study_name", "StudyName")
+ renameMotCle(jdc, command, "Study_repertory", "StudyRepertory")
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "FunctionDict", "ScriptWithSwitch", fsrc )
+ fsrc = re.sub( "FUNCTIONDICT_FILE", "SCRIPTWITHSWITCH_FILE", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- "ASSIMILATION_STUDY",
- "CHECKING_STUDY",
- )
-
-dict_erreurs = {
- "ASSIMILATION_STUDY":"Changements dans l'arbre et dans les noms",
- "CHECKING_STUDY":"Changements dans l'arbre et dans les noms",
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
-
- #Parse les mocles des commandes
- parseKeywords(jdc.root)
- genereErreurPourCommande(jdc,('Algorithm','AlgorithmParameters','FunctionDict'))
- # ==========================================================================
-
- for command in atraiter:
- # Insere le MC s'il n'existe pas
- chercheOperInsereFacteurSiRegle(jdc, command, "AlgorithmParameters",((("AlgorithmParameters",),"nexistepasMCFParmi"),))
- # Deplace le MC
- moveMotClefInOperToFact(jdc, command, "Algorithm", "AlgorithmParameters", plusieursFois=False)
- # Renomme le MC
- renameMotCleInFact(jdc, command, "AlgorithmParameters", "INPUT_TYPE", "Parameters")
- # Renomme le MC
- renameMotCle(jdc, command, "Study_name", "StudyName")
- renameMotCle(jdc, command, "Study_repertory", "StudyRepertory")
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "FunctionDict", "ScriptWithSwitch", fsrc )
- fsrc = re.sub( "FUNCTIONDICT_FILE", "SCRIPTWITHSWITCH_FILE", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ "ASSIMILATION_STUDY",
+ "CHECKING_STUDY",
+ )
+
+dict_erreurs = {
+ "ASSIMILATION_STUDY":"Changements dans l'arbre et dans les noms",
+ "CHECKING_STUDY":"Changements dans l'arbre et dans les noms",
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+
+ #Parse les mocles des commandes
+ parseKeywords(jdc.root)
+ genereErreurPourCommande(jdc,('Algorithm','AlgorithmParameters','FunctionDict'))
+ # ==========================================================================
+
+ for command in atraiter:
+ # Insere le MC s'il n'existe pas
+ chercheOperInsereFacteurSiRegle(jdc, command, "AlgorithmParameters",((("AlgorithmParameters",),"nexistepasMCFParmi"),))
+ # Deplace le MC
+ moveMotClefInOperToFact(jdc, command, "Algorithm", "AlgorithmParameters", plusieursFois=False)
+ # Renomme le MC
+ renameMotCleInFact(jdc, command, "AlgorithmParameters", "INPUT_TYPE", "Parameters")
+ # Renomme le MC
+ renameMotCle(jdc, command, "Study_name", "StudyName")
+ renameMotCle(jdc, command, "Study_repertory", "StudyRepertory")
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "FunctionDict", "ScriptWithSwitch", fsrc )
+ fsrc = re.sub( "FUNCTIONDICT_FILE", "SCRIPTWITHSWITCH_FILE", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- )
-
-dict_erreurs = {
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
- # ==========================================================================
-
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ )
+
+dict_erreurs = {
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+ # ==========================================================================
+
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- )
-
-dict_erreurs = {
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
- # ==========================================================================
-
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ )
+
+dict_erreurs = {
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+ # ==========================================================================
+
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- )
-
-dict_erreurs = {
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
- # ==========================================================================
-
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ )
+
+dict_erreurs = {
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+ # ==========================================================================
+
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- )
-
-dict_erreurs = {
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
- # ==========================================================================
-
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ )
+
+dict_erreurs = {
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+ # ==========================================================================
+
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- )
-
-dict_erreurs = {
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
- # ==========================================================================
-
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ )
+
+dict_erreurs = {
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+ # ==========================================================================
+
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- )
-
-dict_erreurs = {
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
- # ==========================================================================
-
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ )
+
+dict_erreurs = {
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+ # ==========================================================================
+
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- )
-
-dict_erreurs = {
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
- # ==========================================================================
-
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ )
+
+dict_erreurs = {
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+ # ==========================================================================
+
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- )
-
-dict_erreurs = {
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
- # ==========================================================================
-
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ )
+
+dict_erreurs = {
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+ # ==========================================================================
+
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- )
-
-dict_erreurs = {
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
- # ==========================================================================
-
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ )
+
+dict_erreurs = {
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+ # ==========================================================================
+
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- )
-
-dict_erreurs = {
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
- # ==========================================================================
-
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ )
+
+dict_erreurs = {
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+ # ==========================================================================
+
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ )
+
+dict_erreurs = {
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+ # ==========================================================================
+
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- )
-
-dict_erreurs = {
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
- # ==========================================================================
-
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ )
+
+dict_erreurs = {
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+ # ==========================================================================
+
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- )
-
-dict_erreurs = {
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
- # ==========================================================================
-
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ )
+
+dict_erreurs = {
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+ # ==========================================================================
+
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- )
-
-dict_erreurs = {
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
- # ==========================================================================
-
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ )
+
+dict_erreurs = {
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+ # ==========================================================================
+
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- )
-
-dict_erreurs = {
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
- # ==========================================================================
-
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ )
+
+dict_erreurs = {
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+ # ==========================================================================
+
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- )
-
-dict_erreurs = {
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
- # ==========================================================================
-
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ )
+
+dict_erreurs = {
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+ # ==========================================================================
+
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- )
-
-dict_erreurs = {
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
- # ==========================================================================
-
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ )
+
+dict_erreurs = {
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+ # ==========================================================================
+
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- )
-
-dict_erreurs = {
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
- # ==========================================================================
-
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ )
+
+dict_erreurs = {
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+ # ==========================================================================
+
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- )
-
-dict_erreurs = {
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
- # ==========================================================================
-
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ )
+
+dict_erreurs = {
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+ # ==========================================================================
+
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2008-2023 EDF R&D
-#
-# This file is part of SALOME ADAO module
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library 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
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-
-import argparse # optparse deprecated since Python version 3.2
-import sys
-import re
-
-import Traducteur.log as log
-from Traducteur.load import getJDC, getJDCFromTexte
-from Traducteur.mocles import parseKeywords
-from Traducteur.dictErreurs import genereErreurPourCommande
-from Traducteur.inseremocle import *
-from Traducteur.movemocle import *
-from Traducteur.renamemocle import *
-
-version_out = "V9_11_0"
-
-usage="""Usage: python %(prog)s [args]
-
-Typical use is:
- python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
-
-atraiter = (
- "ASSIMILATION_STUDY",
- "CHECKING_STUDY",
- )
-
-dict_erreurs = {
- "ASSIMILATION_STUDY":"Changements dans l'arbre et dans les noms",
- "CHECKING_STUDY":"Changements dans l'arbre et dans les noms",
- }
-
-sys.dict_erreurs=dict_erreurs
-
-def traduc(infile=None,outfile=None,texte=None,flog=None):
- hdlr = log.initialise(flog)
- if infile is not None:
- jdc = getJDC(infile,atraiter)
- elif texte is not None:
- jdc = getJDCFromTexte(texte,atraiter)
- else:
- raise ValueError("Traduction du JDC impossible")
-
- #Parse les mocles des commandes
- parseKeywords(jdc.root)
- genereErreurPourCommande(jdc,('Algorithm','AlgorithmParameters','FunctionDict'))
- # ==========================================================================
-
- for command in atraiter:
- # Insere le MC s'il n'existe pas
- chercheOperInsereFacteurSiRegle(jdc, command, "AlgorithmParameters",((("AlgorithmParameters",),"nexistepasMCFParmi"),))
- # Deplace le MC
- moveMotClefInOperToFact(jdc, command, "Algorithm", "AlgorithmParameters", plusieursFois=False)
- # Renomme le MC
- renameMotCleInFact(jdc, command, "AlgorithmParameters", "INPUT_TYPE", "Parameters")
- # Renomme le MC
- renameMotCle(jdc, command, "Study_name", "StudyName")
- renameMotCle(jdc, command, "Study_repertory", "StudyRepertory")
-
- # ==========================================================================
- fsrc = jdc.getSource()
- fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
- fsrc = re.sub( "FunctionDict", "ScriptWithSwitch", fsrc )
- fsrc = re.sub( "FUNCTIONDICT_FILE", "SCRIPTWITHSWITCH_FILE", fsrc )
- fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
- fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
- #
- log.ferme(hdlr)
- if outfile is not None:
- with open(outfile,'w') as f:
- f.write( fsrc )
- else:
- return fsrc
-
-class MonTraducteur:
- def __init__(self,texte):
- self.__texte = str(texte)
- def traduit(self):
- return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
-
-def main():
- parser = argparse.ArgumentParser(usage=usage)
-
- parser.add_argument('-i','--infile', dest="infile",
- help="Le fichier COMM en entree, a traduire")
- parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
- help="Le fichier COMM en sortie, traduit")
-
- args = parser.parse_args()
- if len(args.infile) == 0:
- print("")
- parser.print_help()
- print("")
- sys.exit(1)
-
- traduc(args.infile,args.outfile)
-
-if __name__ == '__main__':
- main()
--- /dev/null
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008-2023 EDF R&D
+#
+# This file is part of SALOME ADAO module
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
+
+import argparse # optparse deprecated since Python version 3.2
+import sys
+import re
+
+import Traducteur.log as log
+from Traducteur.load import getJDC, getJDCFromTexte
+from Traducteur.mocles import parseKeywords
+from Traducteur.dictErreurs import genereErreurPourCommande
+from Traducteur.inseremocle import *
+from Traducteur.movemocle import *
+from Traducteur.renamemocle import *
+
+version_out = "V9_12_0"
+
+usage="""Usage: python %(prog)s [args]
+
+Typical use is:
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
+
+atraiter = (
+ "ASSIMILATION_STUDY",
+ "CHECKING_STUDY",
+ )
+
+dict_erreurs = {
+ "ASSIMILATION_STUDY":"Changements dans l'arbre et dans les noms",
+ "CHECKING_STUDY":"Changements dans l'arbre et dans les noms",
+ }
+
+sys.dict_erreurs=dict_erreurs
+
+def traduc(infile=None,outfile=None,texte=None,flog=None):
+ hdlr = log.initialise(flog)
+ if infile is not None:
+ jdc = getJDC(infile,atraiter)
+ elif texte is not None:
+ jdc = getJDCFromTexte(texte,atraiter)
+ else:
+ raise ValueError("Traduction du JDC impossible")
+
+ #Parse les mocles des commandes
+ parseKeywords(jdc.root)
+ genereErreurPourCommande(jdc,('Algorithm','AlgorithmParameters','FunctionDict'))
+ # ==========================================================================
+
+ for command in atraiter:
+ # Insere le MC s'il n'existe pas
+ chercheOperInsereFacteurSiRegle(jdc, command, "AlgorithmParameters",((("AlgorithmParameters",),"nexistepasMCFParmi"),))
+ # Deplace le MC
+ moveMotClefInOperToFact(jdc, command, "Algorithm", "AlgorithmParameters", plusieursFois=False)
+ # Renomme le MC
+ renameMotCleInFact(jdc, command, "AlgorithmParameters", "INPUT_TYPE", "Parameters")
+ # Renomme le MC
+ renameMotCle(jdc, command, "Study_name", "StudyName")
+ renameMotCle(jdc, command, "Study_repertory", "StudyRepertory")
+
+ # ==========================================================================
+ fsrc = jdc.getSource()
+ fsrc = re.sub( "MaximumNumberOfSteps", "MaximumNumberOfIterations", fsrc )
+ fsrc = re.sub( "FunctionDict", "ScriptWithSwitch", fsrc )
+ fsrc = re.sub( "FUNCTIONDICT_FILE", "SCRIPTWITHSWITCH_FILE", fsrc )
+ fsrc = re.sub( "#VERSION_CATALOGUE:.*:FIN VERSION_CATALOGUE", "#VERSION_CATALOGUE:%s:FIN VERSION_CATALOGUE"%version_out, fsrc)
+ fsrc = re.sub( "#CHECKSUM.*FIN CHECKSUM", "", fsrc )
+ #
+ log.ferme(hdlr)
+ if outfile is not None:
+ with open(outfile,'w') as f:
+ f.write( fsrc )
+ else:
+ return fsrc
+
+class MonTraducteur:
+ def __init__(self,texte):
+ self.__texte = str(texte)
+ def traduit(self):
+ return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
+
+def main():
+ parser = argparse.ArgumentParser(usage=usage)
+
+ parser.add_argument('-i','--infile', dest="infile",
+ help="Le fichier COMM en entree, a traduire")
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
+ help="Le fichier COMM en sortie, traduit")
+
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
+ parser.print_help()
+ print("")
+ sys.exit(1)
+
+ traduc(args.infile,args.outfile)
+
+if __name__ == '__main__':
+ main()
__all__ = ["adaoBuilder"]
import os, sys, logging
-adao_py_dir = os.path.abspath(os.path.dirname(__file__))
+adao_py_dir = os.path.abspath(os.path.dirname(__file__)) # Variable témoin
sys.path.insert(0, adao_py_dir)
+from daCore import Persistence # PathManagement activé dans Persistence
from daCore.version import name, version, year, date, __version__
try:
from daYacsIntegration.daOptimizerLoop import *