From: Jean-Philippe ARGAUD Date: Fri, 22 Sep 2023 14:04:17 +0000 (+0200) Subject: Update for advancement of 9.12 code and documentation X-Git-Tag: V9_12_0a1~7 X-Git-Url: http://git.salome-platform.org/gitweb/?a=commitdiff_plain;h=c3e19161c483288f9c9df57525b0bd70ffa5e71e;p=modules%2Fadao.git Update for advancement of 9.12 code and documentation Review, update, evolutions for DFO, PSO, EOSG, IRM, MOP, SP... --- diff --git a/bin/module_version.py b/bin/module_version.py index b75c6d0..315d494 100644 --- a/bin/module_version.py +++ b/bin/module_version.py @@ -29,9 +29,9 @@ __author__ = "Jean-Philippe ARGAUD" __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(".","_") diff --git a/doc/en/bibliography.rst b/doc/en/bibliography.rst index 836a900..17551ed 100644 --- a/doc/en/bibliography.rst +++ b/doc/en/bibliography.rst @@ -161,6 +161,8 @@ exhaustive bibliography. .. [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 diff --git a/doc/en/examples.rst b/doc/en/examples.rst index 556e239..114af16 100644 --- a/doc/en/examples.rst +++ b/doc/en/examples.rst @@ -49,6 +49,7 @@ Calculation algorithms uses #. :ref:`Examples with the "ExtendedBlue" algorithm` #. :ref:`Examples with the "KalmanFilter" algorithm` #. :ref:`Examples with the "NonLinearLeastSquares" algorithm` +#. :ref:`Examples with the "ParticleSwarmOptimization" algorithm` Checking algorithms uses ------------------------ diff --git a/doc/en/images/irm_determination.png b/doc/en/images/irm_determination.png new file mode 100644 index 0000000..d531169 Binary files /dev/null and b/doc/en/images/irm_determination.png differ diff --git a/doc/en/images/mop_determination.png b/doc/en/images/mop_determination.png new file mode 100644 index 0000000..65bcd73 Binary files /dev/null and b/doc/en/images/mop_determination.png differ diff --git a/doc/en/ref_algorithm_DerivativeFreeOptimization.rst b/doc/en/ref_algorithm_DerivativeFreeOptimization.rst index b737c8b..20d11d0 100644 --- a/doc/en/ref_algorithm_DerivativeFreeOptimization.rst +++ b/doc/en/ref_algorithm_DerivativeFreeOptimization.rst @@ -207,3 +207,4 @@ StoreSupplementaryCalculations - [Powell07]_ - [Powell09]_ - [Rowan90]_ +- [WikipediaNM]_ diff --git a/doc/en/ref_algorithm_EnsembleOfSimulationGenerationTask.rst b/doc/en/ref_algorithm_EnsembleOfSimulationGenerationTask.rst index d45d313..909dd09 100644 --- a/doc/en/ref_algorithm_EnsembleOfSimulationGenerationTask.rst +++ b/doc/en/ref_algorithm_EnsembleOfSimulationGenerationTask.rst @@ -43,23 +43,24 @@ Task algorithm "*EnsembleOfSimulationGenerationTask*" .. ------------------------------------ .. .. 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 diff --git a/doc/en/ref_algorithm_InterpolationByReducedModelTask.rst b/doc/en/ref_algorithm_InterpolationByReducedModelTask.rst new file mode 100644 index 0000000..99e4228 --- /dev/null +++ b/doc/en/ref_algorithm_InterpolationByReducedModelTask.rst @@ -0,0 +1,121 @@ +.. + 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]_ diff --git a/doc/en/ref_algorithm_MeasurementsOptimalPositioningTask.rst b/doc/en/ref_algorithm_MeasurementsOptimalPositioningTask.rst index 78ca51c..e68f61c 100644 --- a/doc/en/ref_algorithm_MeasurementsOptimalPositioningTask.rst +++ b/doc/en/ref_algorithm_MeasurementsOptimalPositioningTask.rst @@ -45,33 +45,53 @@ Task algorithm "*MeasurementsOptimalPositioningTask*" .. ------------------------------------ .. .. 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 diff --git a/doc/en/ref_algorithm_ParticleSwarmOptimization.rst b/doc/en/ref_algorithm_ParticleSwarmOptimization.rst index 189c013..5f0eaee 100644 --- a/doc/en/ref_algorithm_ParticleSwarmOptimization.rst +++ b/doc/en/ref_algorithm_ParticleSwarmOptimization.rst @@ -57,19 +57,35 @@ robust formulations are proposed here: 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 @@ -77,9 +93,9 @@ algorithms: 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 @@ -162,6 +178,10 @@ StoreSupplementaryCalculations "CurrentIterationNumber", "CurrentState", "Innovation", + "InternalCostFunctionJ", + "InternalCostFunctionJb", + "InternalCostFunctionJo", + "InternalStates", "OMA", "OMB", "SimulatedObservationAtBackground", @@ -208,6 +228,14 @@ StoreSupplementaryCalculations .. 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 @@ -221,6 +249,25 @@ StoreSupplementaryCalculations .. ------------------------------------ .. .. _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` diff --git a/doc/en/ref_algorithm_SamplingTest.rst b/doc/en/ref_algorithm_SamplingTest.rst index 6da602a..7f13cca 100644 --- a/doc/en/ref_algorithm_SamplingTest.rst +++ b/doc/en/ref_algorithm_SamplingTest.rst @@ -46,6 +46,14 @@ 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. 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 @@ -68,6 +76,8 @@ treatment during the calculation by well suited "*observer*". .. ------------------------------------ .. .. include:: snippets/Header2Algo03Chck.rst +.. include:: snippets/EnsembleOfSnapshots.rst + .. include:: snippets/QualityCriterion.rst .. include:: snippets/SampleAsExplicitHyperCube.rst diff --git a/doc/en/reference.rst b/doc/en/reference.rst index 12fd3cc..ab5f655 100644 --- a/doc/en/reference.rst +++ b/doc/en/reference.rst @@ -168,5 +168,6 @@ section for the underlying algorithmic details. :maxdepth: 1 ref_algorithm_EnsembleOfSimulationGenerationTask + ref_algorithm_InterpolationByReducedModelTask ref_algorithm_MeasurementsOptimalPositioningTask ref_task_keywords diff --git a/doc/en/scripts/simple_3DVAR1Plus.png b/doc/en/scripts/simple_3DVAR1Plus.png index cb3ac04..5cf726a 100644 Binary files a/doc/en/scripts/simple_3DVAR1Plus.png and b/doc/en/scripts/simple_3DVAR1Plus.png differ diff --git a/doc/en/scripts/simple_3DVAR1Plus.rst b/doc/en/scripts/simple_3DVAR1Plus.rst index 77f4191..8052ad7 100644 --- a/doc/en/scripts/simple_3DVAR1Plus.rst +++ b/doc/en/scripts/simple_3DVAR1Plus.rst @@ -7,7 +7,7 @@ for the twin experiment. Naturally, the final simulation obtained with the 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 diff --git a/doc/en/scripts/simple_ParticleSwarmOptimization1.png b/doc/en/scripts/simple_ParticleSwarmOptimization1.png new file mode 100644 index 0000000..e29ee4d Binary files /dev/null and b/doc/en/scripts/simple_ParticleSwarmOptimization1.png differ diff --git a/doc/en/scripts/simple_ParticleSwarmOptimization1.py b/doc/en/scripts/simple_ParticleSwarmOptimization1.py new file mode 100644 index 0000000..5aa924a --- /dev/null +++ b/doc/en/scripts/simple_ParticleSwarmOptimization1.py @@ -0,0 +1,79 @@ +# -*- 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") diff --git a/doc/en/scripts/simple_ParticleSwarmOptimization1.res b/doc/en/scripts/simple_ParticleSwarmOptimization1.res new file mode 100644 index 0000000..6a1d330 --- /dev/null +++ b/doc/en/scripts/simple_ParticleSwarmOptimization1.res @@ -0,0 +1,36 @@ +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] diff --git a/doc/en/scripts/simple_ParticleSwarmOptimization1.rst b/doc/en/scripts/simple_ParticleSwarmOptimization1.rst new file mode 100644 index 0000000..cb47c74 --- /dev/null +++ b/doc/en/scripts/simple_ParticleSwarmOptimization1.rst @@ -0,0 +1,17 @@ +.. 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. diff --git a/doc/en/snippets/Analysis.rst b/doc/en/snippets/Analysis.rst index 8d19e6a..7054b5c 100644 --- a/doc/en/snippets/Analysis.rst +++ b/doc/en/snippets/Analysis.rst @@ -2,8 +2,8 @@ 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]`` diff --git a/doc/en/snippets/Debug.rst b/doc/en/snippets/Debug.rst index c6f323c..c932f1a 100644 --- a/doc/en/snippets/Debug.rst +++ b/doc/en/snippets/Debug.rst @@ -4,3 +4,6 @@ Debug *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}`` diff --git a/doc/en/snippets/EnsembleOfSimulations.rst b/doc/en/snippets/EnsembleOfSimulations.rst index f63aa0e..5adc14e 100644 --- a/doc/en/snippets/EnsembleOfSimulations.rst +++ b/doc/en/snippets/EnsembleOfSimulations.rst @@ -1,13 +1,13 @@ .. 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...]}`` diff --git a/doc/en/snippets/EnsembleOfSnapshots.rst b/doc/en/snippets/EnsembleOfSnapshots.rst index 8ec3555..03869a4 100644 --- a/doc/en/snippets/EnsembleOfSnapshots.rst +++ b/doc/en/snippets/EnsembleOfSnapshots.rst @@ -1,13 +1,13 @@ .. 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...]}`` diff --git a/doc/en/snippets/EnsembleOfStates.rst b/doc/en/snippets/EnsembleOfStates.rst index ebcf826..5fb1e4b 100644 --- a/doc/en/snippets/EnsembleOfStates.rst +++ b/doc/en/snippets/EnsembleOfStates.rst @@ -1,12 +1,12 @@ .. 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...]}`` diff --git a/doc/en/snippets/ExcludedPoints.rst b/doc/en/snippets/ExcludedPoints.rst index 5a9a6ad..d053dcc 100644 --- a/doc/en/snippets/ExcludedPoints.rst +++ b/doc/en/snippets/ExcludedPoints.rst @@ -6,4 +6,4 @@ ExcludedPoints variables of a state vector considered arbitrarily in one-dimensional form. Example : - ``mp = ADD.get("ExcludedPoints")[-1]`` + ``ep = ADD.get("ExcludedPoints")[-1]`` diff --git a/doc/en/snippets/InternalCostFunctionJ.rst b/doc/en/snippets/InternalCostFunctionJ.rst new file mode 100644 index 0000000..e69de29 diff --git a/doc/en/snippets/InternalCostFunctionJb.rst b/doc/en/snippets/InternalCostFunctionJb.rst new file mode 100644 index 0000000..e69de29 diff --git a/doc/en/snippets/InternalCostFunctionJo.rst b/doc/en/snippets/InternalCostFunctionJo.rst new file mode 100644 index 0000000..e69de29 diff --git a/doc/en/snippets/InternalStates.rst b/doc/en/snippets/InternalStates.rst new file mode 100644 index 0000000..e69de29 diff --git a/doc/en/snippets/Minimizer_DFO.rst b/doc/en/snippets/Minimizer_DFO.rst index 5724737..77cc307 100644 --- a/doc/en/snippets/Minimizer_DFO.rst +++ b/doc/en/snippets/Minimizer_DFO.rst @@ -14,8 +14,8 @@ Minimizer "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. diff --git a/doc/en/snippets/ModuleCompatibility.rst b/doc/en/snippets/ModuleCompatibility.rst index a7f1831..2dfcf87 100644 --- a/doc/en/snippets/ModuleCompatibility.rst +++ b/doc/en/snippets/ModuleCompatibility.rst @@ -14,9 +14,9 @@ versions within the range described below. :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 diff --git a/doc/en/snippets/ModuleValidation.rst b/doc/en/snippets/ModuleValidation.rst index 0f39a12..2eef5e5 100644 --- a/doc/en/snippets/ModuleValidation.rst +++ b/doc/en/snippets/ModuleValidation.rst @@ -12,9 +12,9 @@ purposes only, knowing that, in case of doubt, the SALOME version sheet 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 diff --git a/doc/en/snippets/ObservationsAlreadyRestrictedOnOptimalLocations.rst b/doc/en/snippets/ObservationsAlreadyRestrictedOnOptimalLocations.rst new file mode 100644 index 0000000..be03983 --- /dev/null +++ b/doc/en/snippets/ObservationsAlreadyRestrictedOnOptimalLocations.rst @@ -0,0 +1,11 @@ +.. 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}`` diff --git a/doc/en/snippets/OptimalLocations.rst b/doc/en/snippets/OptimalLocations.rst new file mode 100644 index 0000000..e3ef486 --- /dev/null +++ b/doc/en/snippets/OptimalLocations.rst @@ -0,0 +1,11 @@ +.. 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`. diff --git a/doc/en/snippets/OptimalPoints.rst b/doc/en/snippets/OptimalPoints.rst index 6e381bf..5c8166d 100644 --- a/doc/en/snippets/OptimalPoints.rst +++ b/doc/en/snippets/OptimalPoints.rst @@ -1,9 +1,10 @@ .. 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]`` diff --git a/doc/en/snippets/ReducedBasis.rst b/doc/en/snippets/ReducedBasis.rst index d5f08e8..d17b4b4 100644 --- a/doc/en/snippets/ReducedBasis.rst +++ b/doc/en/snippets/ReducedBasis.rst @@ -6,5 +6,8 @@ ReducedBasis 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]`` diff --git a/doc/fr/bibliography.rst b/doc/fr/bibliography.rst index e4305e2..8b2cf92 100644 --- a/doc/fr/bibliography.rst +++ b/doc/fr/bibliography.rst @@ -161,6 +161,8 @@ néanmoins d'intention de constituer une bibliographie exhaustive. .. [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 diff --git a/doc/fr/examples.rst b/doc/fr/examples.rst index 7774381..0471405 100644 --- a/doc/fr/examples.rst +++ b/doc/fr/examples.rst @@ -50,6 +50,7 @@ Utilisations d'algorithmes de calcul #. :ref:`Exemples avec l'algorithme de "ExtendedBlue"` #. :ref:`Exemples avec l'algorithme de "KalmanFilter"` #. :ref:`Exemples avec l'algorithme de "NonLinearLeastSquares"` +#. :ref:`Exemples avec l'algorithme de "ParticleSwarmOptimization"` Utilisations d'algorithmes de vérification ------------------------------------------ diff --git a/doc/fr/images/irm_determination.png b/doc/fr/images/irm_determination.png new file mode 100644 index 0000000..0fc73cb Binary files /dev/null and b/doc/fr/images/irm_determination.png differ diff --git a/doc/fr/images/mop_determination.png b/doc/fr/images/mop_determination.png new file mode 100644 index 0000000..9ce4cd0 Binary files /dev/null and b/doc/fr/images/mop_determination.png differ diff --git a/doc/fr/ref_algorithm_DerivativeFreeOptimization.rst b/doc/fr/ref_algorithm_DerivativeFreeOptimization.rst index bb2b905..ad81858 100644 --- a/doc/fr/ref_algorithm_DerivativeFreeOptimization.rst +++ b/doc/fr/ref_algorithm_DerivativeFreeOptimization.rst @@ -208,3 +208,4 @@ StoreSupplementaryCalculations - [Powell07]_ - [Powell09]_ - [Rowan90]_ +- [WikipediaNM]_ diff --git a/doc/fr/ref_algorithm_EnsembleOfSimulationGenerationTask.rst b/doc/fr/ref_algorithm_EnsembleOfSimulationGenerationTask.rst index 902a88d..f19be04 100644 --- a/doc/fr/ref_algorithm_EnsembleOfSimulationGenerationTask.rst +++ b/doc/fr/ref_algorithm_EnsembleOfSimulationGenerationTask.rst @@ -43,25 +43,25 @@ Algorithme de tâche "*EnsembleOfSimulationGenerationTask*" .. ------------------------------------ .. .. 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 diff --git a/doc/fr/ref_algorithm_InterpolationByReducedModelTask.rst b/doc/fr/ref_algorithm_InterpolationByReducedModelTask.rst new file mode 100644 index 0000000..8dc334b --- /dev/null +++ b/doc/fr/ref_algorithm_InterpolationByReducedModelTask.rst @@ -0,0 +1,121 @@ +.. + 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]_ diff --git a/doc/fr/ref_algorithm_MeasurementsOptimalPositioningTask.rst b/doc/fr/ref_algorithm_MeasurementsOptimalPositioningTask.rst index 876e515..037bc68 100644 --- a/doc/fr/ref_algorithm_MeasurementsOptimalPositioningTask.rst +++ b/doc/fr/ref_algorithm_MeasurementsOptimalPositioningTask.rst @@ -45,35 +45,55 @@ Algorithme de tâche "*MeasurementsOptimalPositioningTask*" .. ------------------------------------ .. .. 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 diff --git a/doc/fr/ref_algorithm_ParticleSwarmOptimization.rst b/doc/fr/ref_algorithm_ParticleSwarmOptimization.rst index 760dff2..c45ad74 100644 --- a/doc/fr/ref_algorithm_ParticleSwarmOptimization.rst +++ b/doc/fr/ref_algorithm_ParticleSwarmOptimization.rst @@ -58,19 +58,37 @@ stables et robustes suivantes : 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 @@ -78,7 +96,7 @@ algorithmes : 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. @@ -165,6 +183,10 @@ StoreSupplementaryCalculations "CurrentIterationNumber", "CurrentState", "Innovation", + "InternalCostFunctionJ", + "InternalCostFunctionJb", + "InternalCostFunctionJo", + "InternalStates", "OMA", "OMB", "SimulatedObservationAtBackground", @@ -211,6 +233,14 @@ StoreSupplementaryCalculations .. 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 @@ -224,6 +254,25 @@ StoreSupplementaryCalculations .. ------------------------------------ .. .. _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` diff --git a/doc/fr/ref_algorithm_SamplingTest.rst b/doc/fr/ref_algorithm_SamplingTest.rst index 4b3ec3f..6d58807 100644 --- a/doc/fr/ref_algorithm_SamplingTest.rst +++ b/doc/fr/ref_algorithm_SamplingTest.rst @@ -48,6 +48,14 @@ nombre de calculs) qu'il est possible d'atteindre, elle peut rapidement devenir 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 @@ -71,6 +79,8 @@ calcul à l'aide des "*observer*" adaptés. .. ------------------------------------ .. .. include:: snippets/Header2Algo03Chck.rst +.. include:: snippets/EnsembleOfSnapshots.rst + .. include:: snippets/QualityCriterion.rst .. include:: snippets/SampleAsExplicitHyperCube.rst diff --git a/doc/fr/reference.rst b/doc/fr/reference.rst index b5df59c..5ff8ab2 100644 --- a/doc/fr/reference.rst +++ b/doc/fr/reference.rst @@ -172,5 +172,6 @@ sous-jacents. :maxdepth: 1 ref_algorithm_EnsembleOfSimulationGenerationTask + ref_algorithm_InterpolationByReducedModelTask ref_algorithm_MeasurementsOptimalPositioningTask ref_task_keywords diff --git a/doc/fr/scripts/simple_3DVAR1Plus.png b/doc/fr/scripts/simple_3DVAR1Plus.png index 78b62f0..010dd98 100644 Binary files a/doc/fr/scripts/simple_3DVAR1Plus.png and b/doc/fr/scripts/simple_3DVAR1Plus.png differ diff --git a/doc/fr/scripts/simple_3DVAR1Plus.rst b/doc/fr/scripts/simple_3DVAR1Plus.rst index c655224..783fb56 100644 --- a/doc/fr/scripts/simple_3DVAR1Plus.rst +++ b/doc/fr/scripts/simple_3DVAR1Plus.rst @@ -8,8 +8,8 @@ finale obtenue avec les coefficients recalés coïncide donc avec les 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. diff --git a/doc/fr/scripts/simple_ParticleSwarmOptimization1.png b/doc/fr/scripts/simple_ParticleSwarmOptimization1.png new file mode 100644 index 0000000..4b11578 Binary files /dev/null and b/doc/fr/scripts/simple_ParticleSwarmOptimization1.png differ diff --git a/doc/fr/scripts/simple_ParticleSwarmOptimization1.py b/doc/fr/scripts/simple_ParticleSwarmOptimization1.py new file mode 100644 index 0000000..da88aa5 --- /dev/null +++ b/doc/fr/scripts/simple_ParticleSwarmOptimization1.py @@ -0,0 +1,79 @@ +# -*- 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") diff --git a/doc/fr/scripts/simple_ParticleSwarmOptimization1.res b/doc/fr/scripts/simple_ParticleSwarmOptimization1.res new file mode 100644 index 0000000..7d61537 --- /dev/null +++ b/doc/fr/scripts/simple_ParticleSwarmOptimization1.res @@ -0,0 +1,36 @@ +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] diff --git a/doc/fr/scripts/simple_ParticleSwarmOptimization1.rst b/doc/fr/scripts/simple_ParticleSwarmOptimization1.rst new file mode 100644 index 0000000..c2c2c29 --- /dev/null +++ b/doc/fr/scripts/simple_ParticleSwarmOptimization1.rst @@ -0,0 +1,18 @@ +.. 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. diff --git a/doc/fr/snippets/Analysis.rst b/doc/fr/snippets/Analysis.rst index e3a5f2e..df397eb 100644 --- a/doc/fr/snippets/Analysis.rst +++ b/doc/fr/snippets/Analysis.rst @@ -2,8 +2,8 @@ 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]`` diff --git a/doc/fr/snippets/Debug.rst b/doc/fr/snippets/Debug.rst index 9f5a558..1da99e1 100644 --- a/doc/fr/snippets/Debug.rst +++ b/doc/fr/snippets/Debug.rst @@ -4,3 +4,6 @@ Debug *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}`` diff --git a/doc/fr/snippets/EnsembleOfSimulations.rst b/doc/fr/snippets/EnsembleOfSimulations.rst index 1b50a57..b473816 100644 --- a/doc/fr/snippets/EnsembleOfSimulations.rst +++ b/doc/fr/snippets/EnsembleOfSimulations.rst @@ -1,13 +1,14 @@ .. 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...]}`` diff --git a/doc/fr/snippets/EnsembleOfSnapshots.rst b/doc/fr/snippets/EnsembleOfSnapshots.rst index 94bec10..b25d135 100644 --- a/doc/fr/snippets/EnsembleOfSnapshots.rst +++ b/doc/fr/snippets/EnsembleOfSnapshots.rst @@ -1,13 +1,14 @@ .. 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...]}`` diff --git a/doc/fr/snippets/EnsembleOfStates.rst b/doc/fr/snippets/EnsembleOfStates.rst index af4b991..6445d3d 100644 --- a/doc/fr/snippets/EnsembleOfStates.rst +++ b/doc/fr/snippets/EnsembleOfStates.rst @@ -1,12 +1,13 @@ .. 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...]}`` diff --git a/doc/fr/snippets/ExcludedPoints.rst b/doc/fr/snippets/ExcludedPoints.rst index 280c8a2..9a25ba1 100644 --- a/doc/fr/snippets/ExcludedPoints.rst +++ b/doc/fr/snippets/ExcludedPoints.rst @@ -7,4 +7,4 @@ ExcludedPoints unidimensionnelle. Exemple : - ``mp = ADD.get("ExcludedPoints")[-1]`` + ``ep = ADD.get("ExcludedPoints")[-1]`` diff --git a/doc/fr/snippets/InternalCostFunctionJ.rst b/doc/fr/snippets/InternalCostFunctionJ.rst new file mode 100644 index 0000000..e69de29 diff --git a/doc/fr/snippets/InternalCostFunctionJb.rst b/doc/fr/snippets/InternalCostFunctionJb.rst new file mode 100644 index 0000000..e69de29 diff --git a/doc/fr/snippets/InternalCostFunctionJo.rst b/doc/fr/snippets/InternalCostFunctionJo.rst new file mode 100644 index 0000000..e69de29 diff --git a/doc/fr/snippets/InternalStates.rst b/doc/fr/snippets/InternalStates.rst new file mode 100644 index 0000000..e69de29 diff --git a/doc/fr/snippets/Minimizer_DFO.rst b/doc/fr/snippets/Minimizer_DFO.rst index 7803f77..0a710ea 100644 --- a/doc/fr/snippets/Minimizer_DFO.rst +++ b/doc/fr/snippets/Minimizer_DFO.rst @@ -14,8 +14,8 @@ Minimizer "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. diff --git a/doc/fr/snippets/ModuleCompatibility.rst b/doc/fr/snippets/ModuleCompatibility.rst index 65e897f..9bfbe23 100644 --- a/doc/fr/snippets/ModuleCompatibility.rst +++ b/doc/fr/snippets/ModuleCompatibility.rst @@ -15,9 +15,9 @@ l'étendue décrite ci-dessous. :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 diff --git a/doc/fr/snippets/ModuleValidation.rst b/doc/fr/snippets/ModuleValidation.rst index 1e46ca8..aaa7cbb 100644 --- a/doc/fr/snippets/ModuleValidation.rst +++ b/doc/fr/snippets/ModuleValidation.rst @@ -12,9 +12,9 @@ uniquement sachant que, en cas de doute, c'est la fiche de version de SALOME 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 diff --git a/doc/fr/snippets/ObservationsAlreadyRestrictedOnOptimalLocations.rst b/doc/fr/snippets/ObservationsAlreadyRestrictedOnOptimalLocations.rst new file mode 100644 index 0000000..bc5f498 --- /dev/null +++ b/doc/fr/snippets/ObservationsAlreadyRestrictedOnOptimalLocations.rst @@ -0,0 +1,11 @@ +.. 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}`` diff --git a/doc/fr/snippets/OptimalLocations.rst b/doc/fr/snippets/OptimalLocations.rst new file mode 100644 index 0000000..0a2386f --- /dev/null +++ b/doc/fr/snippets/OptimalLocations.rst @@ -0,0 +1,12 @@ +.. 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`. diff --git a/doc/fr/snippets/OptimalPoints.rst b/doc/fr/snippets/OptimalPoints.rst index 1cd50f6..86bf56c 100644 --- a/doc/fr/snippets/OptimalPoints.rst +++ b/doc/fr/snippets/OptimalPoints.rst @@ -2,9 +2,10 @@ 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]`` diff --git a/doc/fr/snippets/ReducedBasis.rst b/doc/fr/snippets/ReducedBasis.rst index 105a41f..4977501 100644 --- a/doc/fr/snippets/ReducedBasis.rst +++ b/doc/fr/snippets/ReducedBasis.rst @@ -3,8 +3,11 @@ 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]`` diff --git a/resources/SalomeApp.xml.in b/resources/SalomeApp.xml.in index 9c56f4e..bce6874 100644 --- a/resources/SalomeApp.xml.in +++ b/resources/SalomeApp.xml.in @@ -28,7 +28,7 @@ - + diff --git a/src/daComposant/daAlgorithms/3DVAR.py b/src/daComposant/daAlgorithms/3DVAR.py index 7ca2140..10c1fe4 100644 --- a/src/daComposant/daAlgorithms/3DVAR.py +++ b/src/daComposant/daAlgorithms/3DVAR.py @@ -54,9 +54,11 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): "LBFGSB", "TNC", "CG", - "NCG", "BFGS", ], + listadv = [ + "NCG", + ], ) self.defineRequiredParameter( name = "EstimationOf", diff --git a/src/daComposant/daAlgorithms/4DVAR.py b/src/daComposant/daAlgorithms/4DVAR.py index 958c70d..514a0dd 100644 --- a/src/daComposant/daAlgorithms/4DVAR.py +++ b/src/daComposant/daAlgorithms/4DVAR.py @@ -59,7 +59,15 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): default = "LBFGSB", typecast = str, message = "Minimiseur utilisé", - listval = ["LBFGSB","TNC", "CG", "NCG", "BFGS"], + listval = [ + "LBFGSB", + "TNC", + "CG", + "BFGS", + ], + listadv = [ + "NCG", + ], ) self.defineRequiredParameter( name = "MaximumNumberOfIterations", diff --git a/src/daComposant/daAlgorithms/AdjointTest.py b/src/daComposant/daAlgorithms/AdjointTest.py index 5a6623e..5962ee0 100644 --- a/src/daComposant/daAlgorithms/AdjointTest.py +++ b/src/daComposant/daAlgorithms/AdjointTest.py @@ -21,9 +21,10 @@ # 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): @@ -199,7 +200,7 @@ 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) diff --git a/src/daComposant/daAlgorithms/Atoms/c2ukf.py b/src/daComposant/daAlgorithms/Atoms/c2ukf.py index d736544..1329435 100644 --- a/src/daComposant/daAlgorithms/Atoms/c2ukf.py +++ b/src/daComposant/daAlgorithms/Atoms/c2ukf.py @@ -27,7 +27,7 @@ __author__ = "Jean-Philippe ARGAUD" 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() @@ -233,8 +233,8 @@ def c2ukf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q): 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 ) diff --git a/src/daComposant/daAlgorithms/Atoms/cekf.py b/src/daComposant/daAlgorithms/Atoms/cekf.py index 67932dc..2090c19 100644 --- a/src/daComposant/daAlgorithms/Atoms/cekf.py +++ b/src/daComposant/daAlgorithms/Atoms/cekf.py @@ -27,7 +27,7 @@ __author__ = "Jean-Philippe ARGAUD" 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() @@ -197,8 +197,8 @@ def cekf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q): 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 ) diff --git a/src/daComposant/daAlgorithms/Atoms/ceks.py b/src/daComposant/daAlgorithms/Atoms/ceks.py index 3198600..edf2f2c 100644 --- a/src/daComposant/daAlgorithms/Atoms/ceks.py +++ b/src/daComposant/daAlgorithms/Atoms/ceks.py @@ -27,7 +27,7 @@ __author__ = "Jean-Philippe ARGAUD" 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() @@ -223,8 +223,8 @@ def ceks(selfA, Xb, Y, U, HO, EM, CM, R, B, Q): 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 ) diff --git a/src/daComposant/daAlgorithms/Atoms/ecwapso.py b/src/daComposant/daAlgorithms/Atoms/ecwapso.py new file mode 100644 index 0000000..32851d6 --- /dev/null +++ b/src/daComposant/daAlgorithms/Atoms/ecwapso.py @@ -0,0 +1,247 @@ +# -*- 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') diff --git a/src/daComposant/daAlgorithms/Atoms/ecwblue.py b/src/daComposant/daAlgorithms/Atoms/ecwblue.py index a40c53b..c3c30ac 100644 --- a/src/daComposant/daAlgorithms/Atoms/ecwblue.py +++ b/src/daComposant/daAlgorithms/Atoms/ecwblue.py @@ -27,7 +27,7 @@ __author__ = "Jean-Philippe ARGAUD" import logging, numpy from daCore.NumericObjects import QuantilesEstimations -from daCore.PlatformInfo import PlatformInfo +from daCore.PlatformInfo import PlatformInfo, vfloat mpr = PlatformInfo().MachinePrecision() # ============================================================================== @@ -111,8 +111,8 @@ def ecwblue(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") 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 ) @@ -133,7 +133,7 @@ def ecwblue(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False): 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 ) @@ -159,9 +159,9 @@ def ecwblue(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False): 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"): diff --git a/src/daComposant/daAlgorithms/Atoms/ecweim.py b/src/daComposant/daAlgorithms/Atoms/ecweim.py index 6f5dadf..b0c3525 100644 --- a/src/daComposant/daAlgorithms/Atoms/ecweim.py +++ b/src/daComposant/daAlgorithms/Atoms/ecweim.py @@ -21,18 +21,18 @@ # 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 @@ -45,13 +45,14 @@ def EIM_offline(selfA, EOS = None, Verbose = False): 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 @@ -93,7 +94,7 @@ def EIM_offline(selfA, EOS = None, Verbose = False): # __mu = [] __I = [] - __Q = numpy.empty(__dimS) + __Q = numpy.empty(__dimS).reshape((-1,1)) __errors = [] # __M = 0 @@ -127,16 +128,16 @@ def EIM_offline(selfA, EOS = None, Verbose = False): 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: @@ -151,6 +152,12 @@ def EIM_offline(selfA, EOS = None, Verbose = False): __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"): @@ -163,8 +170,46 @@ def EIM_offline(selfA, EOS = None, Verbose = False): 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 = []): diff --git a/src/daComposant/daAlgorithms/Atoms/ecwexblue.py b/src/daComposant/daAlgorithms/Atoms/ecwexblue.py index c554e47..e15e39b 100644 --- a/src/daComposant/daAlgorithms/Atoms/ecwexblue.py +++ b/src/daComposant/daAlgorithms/Atoms/ecwexblue.py @@ -27,7 +27,7 @@ __author__ = "Jean-Philippe ARGAUD" import logging, numpy from daCore.NumericObjects import QuantilesEstimations -from daCore.PlatformInfo import PlatformInfo +from daCore.PlatformInfo import PlatformInfo, vfloat mpr = PlatformInfo().MachinePrecision() # ============================================================================== @@ -112,8 +112,8 @@ def ecwexblue(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") 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 ) @@ -134,7 +134,7 @@ def ecwexblue(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False): 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 ) @@ -160,9 +160,9 @@ def ecwexblue(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False): 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"): diff --git a/src/daComposant/daAlgorithms/Atoms/ecwlls.py b/src/daComposant/daAlgorithms/Atoms/ecwlls.py index af2c086..def72c4 100644 --- a/src/daComposant/daAlgorithms/Atoms/ecwlls.py +++ b/src/daComposant/daAlgorithms/Atoms/ecwlls.py @@ -25,6 +25,8 @@ __doc__ = """ """ __author__ = "Jean-Philippe ARGAUD" +from daCore.PlatformInfo import vfloat + # ============================================================================== def ecwlls(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False): """ @@ -71,7 +73,7 @@ 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 ) diff --git a/src/daComposant/daAlgorithms/Atoms/ecwnlls.py b/src/daComposant/daAlgorithms/Atoms/ecwnlls.py index 4ddfa11..c090c92 100644 --- a/src/daComposant/daAlgorithms/Atoms/ecwnlls.py +++ b/src/daComposant/daAlgorithms/Atoms/ecwnlls.py @@ -26,7 +26,7 @@ __doc__ = """ __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): @@ -72,7 +72,7 @@ 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"]) ) @@ -113,7 +113,7 @@ def ecwnlls(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False): _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"): @@ -141,6 +141,8 @@ def ecwnlls(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False): 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( diff --git a/src/daComposant/daAlgorithms/Atoms/ecwnpso.py b/src/daComposant/daAlgorithms/Atoms/ecwnpso.py index fd097fa..1336c85 100644 --- a/src/daComposant/daAlgorithms/Atoms/ecwnpso.py +++ b/src/daComposant/daAlgorithms/Atoms/ecwnpso.py @@ -27,6 +27,7 @@ __author__ = "Jean-Philippe ARGAUD" import numpy, logging, copy from daCore.NumericObjects import ApplyBounds, VariablesAndIncrementsBounds +from daCore.PlatformInfo import vfloat from numpy.random import uniform as rand # ============================================================================== @@ -72,9 +73,9 @@ def ecwnpso(selfA, Xb, Y, HO, R, B): 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"]: @@ -97,6 +98,7 @@ def ecwnpso(selfA, Xb, Y, HO, R, B): __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 diff --git a/src/daComposant/daAlgorithms/Atoms/ecwopso.py b/src/daComposant/daAlgorithms/Atoms/ecwopso.py index cc59223..eea37f9 100644 --- a/src/daComposant/daAlgorithms/Atoms/ecwopso.py +++ b/src/daComposant/daAlgorithms/Atoms/ecwopso.py @@ -27,6 +27,7 @@ __author__ = "Jean-Philippe ARGAUD" import numpy, logging, copy from daCore.NumericObjects import VariablesAndIncrementsBounds +from daCore.PlatformInfo import vfloat from numpy.random import uniform as rand # ============================================================================== @@ -72,9 +73,9 @@ def ecwopso(selfA, Xb, Y, HO, R, B): 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"]: @@ -97,6 +98,7 @@ def ecwopso(selfA, Xb, Y, HO, R, B): __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 diff --git a/src/daComposant/daAlgorithms/Atoms/ecwpspso.py b/src/daComposant/daAlgorithms/Atoms/ecwpspso.py new file mode 100644 index 0000000..f3ad15e --- /dev/null +++ b/src/daComposant/daAlgorithms/Atoms/ecwpspso.py @@ -0,0 +1,261 @@ +# -*- 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') diff --git a/src/daComposant/daAlgorithms/Atoms/ecwspso.py b/src/daComposant/daAlgorithms/Atoms/ecwspso.py index 9b3dc2b..0895941 100644 --- a/src/daComposant/daAlgorithms/Atoms/ecwspso.py +++ b/src/daComposant/daAlgorithms/Atoms/ecwspso.py @@ -21,7 +21,7 @@ # 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" @@ -29,6 +29,7 @@ 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 # ============================================================================== @@ -74,9 +75,9 @@ def ecwspso(selfA, Xb, Y, HO, R, B): 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"]: @@ -99,6 +100,7 @@ def ecwspso(selfA, Xb, Y, HO, R, B): __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 @@ -155,40 +157,41 @@ def ecwspso(selfA, Xb, Y, HO, R, B): 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,:] diff --git a/src/daComposant/daAlgorithms/Atoms/ecwstdkf.py b/src/daComposant/daAlgorithms/Atoms/ecwstdkf.py index d862628..aa9a584 100644 --- a/src/daComposant/daAlgorithms/Atoms/ecwstdkf.py +++ b/src/daComposant/daAlgorithms/Atoms/ecwstdkf.py @@ -26,7 +26,7 @@ __doc__ = """ __author__ = "Jean-Philippe ARGAUD" import numpy -from daCore.PlatformInfo import PlatformInfo +from daCore.PlatformInfo import PlatformInfo, vfloat mpr = PlatformInfo().MachinePrecision() # ============================================================================== @@ -115,8 +115,8 @@ def ecwstdkf(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False): 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 ) diff --git a/src/daComposant/daAlgorithms/Atoms/eosg.py b/src/daComposant/daAlgorithms/Atoms/eosg.py index 9e0a54b..e29ac5d 100644 --- a/src/daComposant/daAlgorithms/Atoms/eosg.py +++ b/src/daComposant/daAlgorithms/Atoms/eosg.py @@ -25,7 +25,7 @@ __doc__ = """ """ __author__ = "Jean-Philippe ARGAUD" -import numpy, logging +import numpy, logging, copy import daCore.NumericObjects # ============================================================================== @@ -34,7 +34,6 @@ def eosg(selfA, Xb, HO, outputEOX = False, assumeNoFailure = True): Ensemble Of Simulations Generation """ # - __seed = numpy.random.get_state() sampleList = daCore.NumericObjects.BuildComplexSampleList( selfA._parameters["SampleAsnUplet"], selfA._parameters["SampleAsExplicitHyperCube"], @@ -42,6 +41,8 @@ def eosg(selfA, Xb, HO, outputEOX = False, assumeNoFailure = True): selfA._parameters["SampleAsIndependantRandomVariables"], Xb, ) + if outputEOX or selfA._toStore("EnsembleOfStates"): + EOX = numpy.stack(tuple(copy.copy(sampleList)), axis=1) # # ---------- if selfA._parameters["SetDebug"]: @@ -86,25 +87,14 @@ def eosg(selfA, Xb, HO, outputEOX = False, assumeNoFailure = True): 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 diff --git a/src/daComposant/daAlgorithms/Atoms/etkf.py b/src/daComposant/daAlgorithms/Atoms/etkf.py index 0063e14..b152016 100644 --- a/src/daComposant/daAlgorithms/Atoms/etkf.py +++ b/src/daComposant/daAlgorithms/Atoms/etkf.py @@ -33,6 +33,7 @@ from daCore.NumericObjects import EnsembleMean 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, @@ -165,7 +166,7 @@ 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) @@ -196,7 +197,7 @@ def etkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, _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) @@ -229,7 +230,7 @@ def etkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, _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) @@ -262,7 +263,7 @@ def etkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, _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) @@ -346,8 +347,8 @@ def etkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, 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 ) diff --git a/src/daComposant/daAlgorithms/Atoms/exkf.py b/src/daComposant/daAlgorithms/Atoms/exkf.py index 4c8b036..8683d92 100644 --- a/src/daComposant/daAlgorithms/Atoms/exkf.py +++ b/src/daComposant/daAlgorithms/Atoms/exkf.py @@ -26,7 +26,7 @@ __doc__ = """ __author__ = "Jean-Philippe ARGAUD" import numpy -from daCore.PlatformInfo import PlatformInfo +from daCore.PlatformInfo import PlatformInfo, vfloat mpr = PlatformInfo().MachinePrecision() mfp = PlatformInfo().MaximumPrecision() @@ -186,8 +186,8 @@ def exkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q): 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 ) diff --git a/src/daComposant/daAlgorithms/Atoms/exks.py b/src/daComposant/daAlgorithms/Atoms/exks.py index f7c5c76..1f8ad32 100644 --- a/src/daComposant/daAlgorithms/Atoms/exks.py +++ b/src/daComposant/daAlgorithms/Atoms/exks.py @@ -26,7 +26,7 @@ __doc__ = """ __author__ = "Jean-Philippe ARGAUD" import numpy -from daCore.PlatformInfo import PlatformInfo +from daCore.PlatformInfo import PlatformInfo, vfloat mpr = PlatformInfo().MachinePrecision() mfp = PlatformInfo().MaximumPrecision() @@ -209,8 +209,8 @@ def exks(selfA, Xb, Y, U, HO, EM, CM, R, B, Q): 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 ) diff --git a/src/daComposant/daAlgorithms/Atoms/ienkf.py b/src/daComposant/daAlgorithms/Atoms/ienkf.py index 7212d42..ee29bc9 100644 --- a/src/daComposant/daAlgorithms/Atoms/ienkf.py +++ b/src/daComposant/daAlgorithms/Atoms/ienkf.py @@ -31,7 +31,7 @@ from daCore.NumericObjects import EnsembleOfAnomalies 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() @@ -226,8 +226,8 @@ def ienkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, VariantM="IEnKF12", 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 ) diff --git a/src/daComposant/daAlgorithms/Atoms/incr3dvar.py b/src/daComposant/daAlgorithms/Atoms/incr3dvar.py index 9540603..6e6fd88 100644 --- a/src/daComposant/daAlgorithms/Atoms/incr3dvar.py +++ b/src/daComposant/daAlgorithms/Atoms/incr3dvar.py @@ -28,7 +28,7 @@ __author__ = "Jean-Philippe ARGAUD" 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() # ============================================================================== @@ -90,8 +90,8 @@ def incr3dvar(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False): 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"]) ) @@ -142,6 +142,8 @@ def incr3dvar(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False): 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( @@ -278,7 +280,7 @@ def incr3dvar(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False): 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"): diff --git a/src/daComposant/daAlgorithms/Atoms/lbfgsb111hlt.py b/src/daComposant/daAlgorithms/Atoms/lbfgsb111hlt.py new file mode 100644 index 0000000..eb99c19 --- /dev/null +++ b/src/daComposant/daAlgorithms/Atoms/lbfgsb111hlt.py @@ -0,0 +1,506 @@ +# 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 + +## 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 . 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 diff --git a/src/daComposant/daAlgorithms/Atoms/mlef.py b/src/daComposant/daAlgorithms/Atoms/mlef.py index f2228f9..1c61c76 100644 --- a/src/daComposant/daAlgorithms/Atoms/mlef.py +++ b/src/daComposant/daAlgorithms/Atoms/mlef.py @@ -33,7 +33,7 @@ from daCore.NumericObjects import EnsembleMean 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() @@ -231,8 +231,8 @@ def mlef(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, 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 ) diff --git a/src/daComposant/daAlgorithms/Atoms/mmqr.py b/src/daComposant/daAlgorithms/Atoms/mmqr.py index a3e64ed..03106ae 100644 --- a/src/daComposant/daAlgorithms/Atoms/mmqr.py +++ b/src/daComposant/daAlgorithms/Atoms/mmqr.py @@ -97,7 +97,7 @@ def mmqr( 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) diff --git a/src/daComposant/daAlgorithms/Atoms/psas3dvar.py b/src/daComposant/daAlgorithms/Atoms/psas3dvar.py index a98a604..5702392 100644 --- a/src/daComposant/daAlgorithms/Atoms/psas3dvar.py +++ b/src/daComposant/daAlgorithms/Atoms/psas3dvar.py @@ -27,7 +27,7 @@ __author__ = "Jean-Philippe ARGAUD" 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): @@ -74,8 +74,8 @@ 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"]) ) @@ -123,6 +123,8 @@ def psas3dvar(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False): 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( @@ -257,7 +259,7 @@ def psas3dvar(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False): 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"): diff --git a/src/daComposant/daAlgorithms/Atoms/senkf.py b/src/daComposant/daAlgorithms/Atoms/senkf.py index c707883..9b26c3c 100644 --- a/src/daComposant/daAlgorithms/Atoms/senkf.py +++ b/src/daComposant/daAlgorithms/Atoms/senkf.py @@ -34,7 +34,7 @@ from daCore.NumericObjects import EnsembleOfAnomalies 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() @@ -229,8 +229,8 @@ def senkf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q, 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 ) diff --git a/src/daComposant/daAlgorithms/Atoms/std3dvar.py b/src/daComposant/daAlgorithms/Atoms/std3dvar.py index b67735e..3335bb4 100644 --- a/src/daComposant/daAlgorithms/Atoms/std3dvar.py +++ b/src/daComposant/daAlgorithms/Atoms/std3dvar.py @@ -27,7 +27,7 @@ __author__ = "Jean-Philippe ARGAUD" 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): @@ -76,8 +76,8 @@ 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"]) ) @@ -126,6 +126,8 @@ def std3dvar(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False): 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( @@ -258,7 +260,7 @@ def std3dvar(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False): 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"): diff --git a/src/daComposant/daAlgorithms/Atoms/std4dvar.py b/src/daComposant/daAlgorithms/Atoms/std4dvar.py index 39ca157..8965e4a 100644 --- a/src/daComposant/daAlgorithms/Atoms/std4dvar.py +++ b/src/daComposant/daAlgorithms/Atoms/std4dvar.py @@ -27,7 +27,7 @@ __author__ = "Jean-Philippe ARGAUD" 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() @@ -96,7 +96,7 @@ def std4dvar(selfA, Xb, Y, U, HO, EM, CM, R, B, Q): 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. @@ -128,7 +128,7 @@ def std4dvar(selfA, Xb, Y, U, HO, EM, CM, R, B, Q): 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"]) ) @@ -186,6 +186,8 @@ def std4dvar(selfA, Xb, Y, U, HO, EM, CM, R, B, Q): 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( diff --git a/src/daComposant/daAlgorithms/Atoms/uskf.py b/src/daComposant/daAlgorithms/Atoms/uskf.py index 02e3d55..d8fc792 100644 --- a/src/daComposant/daAlgorithms/Atoms/uskf.py +++ b/src/daComposant/daAlgorithms/Atoms/uskf.py @@ -26,7 +26,7 @@ __doc__ = """ __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() @@ -212,8 +212,8 @@ def uskf(selfA, Xb, Y, U, HO, EM, CM, R, B, Q): 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 ) diff --git a/src/daComposant/daAlgorithms/Atoms/van3dvar.py b/src/daComposant/daAlgorithms/Atoms/van3dvar.py index 541a5c1..c1495b0 100644 --- a/src/daComposant/daAlgorithms/Atoms/van3dvar.py +++ b/src/daComposant/daAlgorithms/Atoms/van3dvar.py @@ -28,7 +28,7 @@ __author__ = "Jean-Philippe ARGAUD" 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() # ============================================================================== @@ -83,8 +83,8 @@ def van3dvar(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False): 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"]) ) @@ -134,6 +134,8 @@ def van3dvar(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False): 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( @@ -269,7 +271,7 @@ def van3dvar(selfA, Xb, Y, U, HO, CM, R, B, __storeState = False): 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"): diff --git a/src/daComposant/daAlgorithms/DerivativeFreeOptimization.py b/src/daComposant/daAlgorithms/DerivativeFreeOptimization.py index e3ee107..2f04da2 100644 --- a/src/daComposant/daAlgorithms/DerivativeFreeOptimization.py +++ b/src/daComposant/daAlgorithms/DerivativeFreeOptimization.py @@ -22,6 +22,7 @@ import numpy, logging, scipy.optimize from daCore import BasicObjects, PlatformInfo +from daCore.PlatformInfo import vfloat # ============================================================================== class ElementaryAlgorithm(BasicObjects.Algorithm): @@ -154,24 +155,24 @@ 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 ) diff --git a/src/daComposant/daAlgorithms/DifferentialEvolution.py b/src/daComposant/daAlgorithms/DifferentialEvolution.py index 9cd2f80..814c526 100644 --- a/src/daComposant/daAlgorithms/DifferentialEvolution.py +++ b/src/daComposant/daAlgorithms/DifferentialEvolution.py @@ -22,6 +22,7 @@ import numpy, logging, scipy.optimize from daCore import BasicObjects +from daCore.PlatformInfo import vfloat # ============================================================================== class ElementaryAlgorithm(BasicObjects.Algorithm): @@ -180,24 +181,24 @@ 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 ) diff --git a/src/daComposant/daAlgorithms/InterpolationByReducedModelTask.py b/src/daComposant/daAlgorithms/InterpolationByReducedModelTask.py new file mode 100644 index 0000000..b055ccb --- /dev/null +++ b/src/daComposant/daAlgorithms/InterpolationByReducedModelTask.py @@ -0,0 +1,112 @@ +# -*- 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') diff --git a/src/daComposant/daAlgorithms/InterpolationByReducedModelTest.py b/src/daComposant/daAlgorithms/InterpolationByReducedModelTest.py new file mode 100644 index 0000000..ddf1acb --- /dev/null +++ b/src/daComposant/daAlgorithms/InterpolationByReducedModelTest.py @@ -0,0 +1,165 @@ +# -*- 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') diff --git a/src/daComposant/daAlgorithms/MeasurementsOptimalPositioningTask.py b/src/daComposant/daAlgorithms/MeasurementsOptimalPositioningTask.py index df67567..d015b64 100644 --- a/src/daComposant/daAlgorithms/MeasurementsOptimalPositioningTask.py +++ b/src/daComposant/daAlgorithms/MeasurementsOptimalPositioningTask.py @@ -34,15 +34,15 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): 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", @@ -139,7 +139,7 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): 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"] ) @@ -149,7 +149,7 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): 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"] ) diff --git a/src/daComposant/daAlgorithms/NonLinearLeastSquares.py b/src/daComposant/daAlgorithms/NonLinearLeastSquares.py index 40067f4..8292632 100644 --- a/src/daComposant/daAlgorithms/NonLinearLeastSquares.py +++ b/src/daComposant/daAlgorithms/NonLinearLeastSquares.py @@ -49,10 +49,12 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): "LBFGSB", "TNC", "CG", - "NCG", "BFGS", "LM", ], + listadv = [ + "NCG", + ], ) self.defineRequiredParameter( name = "EstimationOf", diff --git a/src/daComposant/daAlgorithms/ObservationSimulationComparisonTest.py b/src/daComposant/daAlgorithms/ObservationSimulationComparisonTest.py index bf234d4..bff5def 100644 --- a/src/daComposant/daAlgorithms/ObservationSimulationComparisonTest.py +++ b/src/daComposant/daAlgorithms/ObservationSimulationComparisonTest.py @@ -21,9 +21,10 @@ # 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): @@ -101,8 +102,8 @@ 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 ) diff --git a/src/daComposant/daAlgorithms/ParticleSwarmOptimization.py b/src/daComposant/daAlgorithms/ParticleSwarmOptimization.py index 7519e92..bfb5a38 100644 --- a/src/daComposant/daAlgorithms/ParticleSwarmOptimization.py +++ b/src/daComposant/daAlgorithms/ParticleSwarmOptimization.py @@ -22,7 +22,7 @@ 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): @@ -39,6 +39,9 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): "SPSO-2011", ], listadv = [ + "SPSO-2011-AIS", + "SPSO-2011-SIS", + "SPSO-2011-PSIS", "PSO", ], ) @@ -194,9 +197,15 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): 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"]) diff --git a/src/daComposant/daAlgorithms/QuantileRegression.py b/src/daComposant/daAlgorithms/QuantileRegression.py index 4264c55..6cee1b6 100644 --- a/src/daComposant/daAlgorithms/QuantileRegression.py +++ b/src/daComposant/daAlgorithms/QuantileRegression.py @@ -32,7 +32,7 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): 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., ) diff --git a/src/daComposant/daAlgorithms/SamplingTest.py b/src/daComposant/daAlgorithms/SamplingTest.py index 702765e..1b96a78 100644 --- a/src/daComposant/daAlgorithms/SamplingTest.py +++ b/src/daComposant/daAlgorithms/SamplingTest.py @@ -20,15 +20,22 @@ # # 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 = [], @@ -100,7 +107,8 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): 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", @@ -129,22 +137,22 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): 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"): @@ -161,7 +169,23 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): 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"]) diff --git a/src/daComposant/daAlgorithms/TabuSearch.py b/src/daComposant/daAlgorithms/TabuSearch.py index c4ada65..7eab87e 100644 --- a/src/daComposant/daAlgorithms/TabuSearch.py +++ b/src/daComposant/daAlgorithms/TabuSearch.py @@ -22,6 +22,7 @@ import numpy from daCore import BasicObjects +from daCore.PlatformInfo import vfloat # ============================================================================== class ElementaryAlgorithm(BasicObjects.Algorithm): @@ -185,24 +186,24 @@ 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 # diff --git a/src/daComposant/daCore/ExtendedLogging.py b/src/daComposant/daCore/ExtendedLogging.py index afa9e1f..02bfaf4 100644 --- a/src/daComposant/daCore/ExtendedLogging.py +++ b/src/daComposant/daCore/ExtendedLogging.py @@ -93,11 +93,26 @@ class ExtendedLogging(object): """ 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 @@ -130,7 +145,7 @@ class ExtendedLogging(object): 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) diff --git a/src/daComposant/daCore/NumericObjects.py b/src/daComposant/daCore/NumericObjects.py index 428f42d..d14db9d 100644 --- a/src/daComposant/daCore/NumericObjects.py +++ b/src/daComposant/daCore/NumericObjects.py @@ -27,7 +27,7 @@ __author__ = "Jean-Philippe ARGAUD" 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) @@ -205,7 +205,7 @@ class FDApproximation(object): 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 @@ -772,6 +772,7 @@ def HessienneEstimation( __selfA, __nb, __HaM, __HtM, __BI, __RI ): 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,)+\ @@ -900,13 +901,13 @@ def VariablesAndIncrementsBounds( __Bounds, __BoxBounds, __Xini, __Name, __Multi __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 # ============================================================================== diff --git a/src/daComposant/daCore/PlatformInfo.py b/src/daComposant/daCore/PlatformInfo.py index 2c0e4bf..6bfcbbe 100644 --- a/src/daComposant/daCore/PlatformInfo.py +++ b/src/daComposant/daCore/PlatformInfo.py @@ -148,6 +148,7 @@ class PlatformInfo(object): __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"): @@ -220,6 +221,14 @@ class PlatformInfo(object): __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 @@ -291,6 +300,12 @@ try: 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 ) @@ -349,6 +364,17 @@ def date2int( __date, __lang="FR" ): 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 diff --git a/src/daComposant/daCore/version.py b/src/daComposant/daCore/version.py index d45f319..92508e9 100644 --- a/src/daComposant/daCore/version.py +++ b/src/daComposant/daCore/version.py @@ -27,9 +27,9 @@ __author__ = "Jean-Philippe ARGAUD" __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(".","_") diff --git a/src/daEficas/CMakeLists.txt b/src/daEficas/CMakeLists.txt index ffe4a71..89ac1db 100644 --- a/src/daEficas/CMakeLists.txt +++ b/src/daEficas/CMakeLists.txt @@ -29,28 +29,29 @@ set(DAEFICAS_FILES __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") diff --git a/src/daEficas/Makefile.am b/src/daEficas/Makefile.am index 60afe87..d412263 100644 --- a/src/daEficas/Makefile.am +++ b/src/daEficas/Makefile.am @@ -34,27 +34,28 @@ mypkgpython_PYTHON = \ __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 diff --git a/src/daEficas/traduitADAOV7_4_0ToV9_11_0.py b/src/daEficas/traduitADAOV7_4_0ToV9_11_0.py deleted file mode 100644 index 5701b4a..0000000 --- a/src/daEficas/traduitADAOV7_4_0ToV9_11_0.py +++ /dev/null @@ -1,118 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV7_4_0ToV9_12_0.py b/src/daEficas/traduitADAOV7_4_0ToV9_12_0.py new file mode 100644 index 0000000..6e3d41d --- /dev/null +++ b/src/daEficas/traduitADAOV7_4_0ToV9_12_0.py @@ -0,0 +1,118 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV7_5_0ToV9_11_0.py b/src/daEficas/traduitADAOV7_5_0ToV9_11_0.py deleted file mode 100644 index 5701b4a..0000000 --- a/src/daEficas/traduitADAOV7_5_0ToV9_11_0.py +++ /dev/null @@ -1,118 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV7_5_0ToV9_12_0.py b/src/daEficas/traduitADAOV7_5_0ToV9_12_0.py new file mode 100644 index 0000000..6e3d41d --- /dev/null +++ b/src/daEficas/traduitADAOV7_5_0ToV9_12_0.py @@ -0,0 +1,118 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV7_5_1ToV9_11_0.py b/src/daEficas/traduitADAOV7_5_1ToV9_11_0.py deleted file mode 100644 index 5701b4a..0000000 --- a/src/daEficas/traduitADAOV7_5_1ToV9_11_0.py +++ /dev/null @@ -1,118 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV7_5_1ToV9_12_0.py b/src/daEficas/traduitADAOV7_5_1ToV9_12_0.py new file mode 100644 index 0000000..6e3d41d --- /dev/null +++ b/src/daEficas/traduitADAOV7_5_1ToV9_12_0.py @@ -0,0 +1,118 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV7_6_0ToV9_11_0.py b/src/daEficas/traduitADAOV7_6_0ToV9_11_0.py deleted file mode 100644 index df4e517..0000000 --- a/src/daEficas/traduitADAOV7_6_0ToV9_11_0.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV7_6_0ToV9_12_0.py b/src/daEficas/traduitADAOV7_6_0ToV9_12_0.py new file mode 100644 index 0000000..3162d43 --- /dev/null +++ b/src/daEficas/traduitADAOV7_6_0ToV9_12_0.py @@ -0,0 +1,98 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV7_7_0ToV9_11_0.py b/src/daEficas/traduitADAOV7_7_0ToV9_11_0.py deleted file mode 100644 index df4e517..0000000 --- a/src/daEficas/traduitADAOV7_7_0ToV9_11_0.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV7_7_0ToV9_12_0.py b/src/daEficas/traduitADAOV7_7_0ToV9_12_0.py new file mode 100644 index 0000000..3162d43 --- /dev/null +++ b/src/daEficas/traduitADAOV7_7_0ToV9_12_0.py @@ -0,0 +1,98 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV7_8_0ToV9_11_0.py b/src/daEficas/traduitADAOV7_8_0ToV9_11_0.py deleted file mode 100644 index df4e517..0000000 --- a/src/daEficas/traduitADAOV7_8_0ToV9_11_0.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV7_8_0ToV9_12_0.py b/src/daEficas/traduitADAOV7_8_0ToV9_12_0.py new file mode 100644 index 0000000..3162d43 --- /dev/null +++ b/src/daEficas/traduitADAOV7_8_0ToV9_12_0.py @@ -0,0 +1,98 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV8_1_0ToV9_11_0.py b/src/daEficas/traduitADAOV8_1_0ToV9_11_0.py deleted file mode 100644 index df4e517..0000000 --- a/src/daEficas/traduitADAOV8_1_0ToV9_11_0.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV8_1_0ToV9_12_0.py b/src/daEficas/traduitADAOV8_1_0ToV9_12_0.py new file mode 100644 index 0000000..3162d43 --- /dev/null +++ b/src/daEficas/traduitADAOV8_1_0ToV9_12_0.py @@ -0,0 +1,98 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV8_2_0ToV9_11_0.py b/src/daEficas/traduitADAOV8_2_0ToV9_11_0.py deleted file mode 100644 index df4e517..0000000 --- a/src/daEficas/traduitADAOV8_2_0ToV9_11_0.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV8_2_0ToV9_12_0.py b/src/daEficas/traduitADAOV8_2_0ToV9_12_0.py new file mode 100644 index 0000000..3162d43 --- /dev/null +++ b/src/daEficas/traduitADAOV8_2_0ToV9_12_0.py @@ -0,0 +1,98 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV8_3_0ToV9_11_0.py b/src/daEficas/traduitADAOV8_3_0ToV9_11_0.py deleted file mode 100644 index df4e517..0000000 --- a/src/daEficas/traduitADAOV8_3_0ToV9_11_0.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV8_3_0ToV9_12_0.py b/src/daEficas/traduitADAOV8_3_0ToV9_12_0.py new file mode 100644 index 0000000..3162d43 --- /dev/null +++ b/src/daEficas/traduitADAOV8_3_0ToV9_12_0.py @@ -0,0 +1,98 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV8_4_0ToV9_11_0.py b/src/daEficas/traduitADAOV8_4_0ToV9_11_0.py deleted file mode 100644 index df4e517..0000000 --- a/src/daEficas/traduitADAOV8_4_0ToV9_11_0.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV8_4_0ToV9_12_0.py b/src/daEficas/traduitADAOV8_4_0ToV9_12_0.py new file mode 100644 index 0000000..3162d43 --- /dev/null +++ b/src/daEficas/traduitADAOV8_4_0ToV9_12_0.py @@ -0,0 +1,98 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV8_5_0ToV9_11_0.py b/src/daEficas/traduitADAOV8_5_0ToV9_11_0.py deleted file mode 100644 index df4e517..0000000 --- a/src/daEficas/traduitADAOV8_5_0ToV9_11_0.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV8_5_0ToV9_12_0.py b/src/daEficas/traduitADAOV8_5_0ToV9_12_0.py new file mode 100644 index 0000000..3162d43 --- /dev/null +++ b/src/daEficas/traduitADAOV8_5_0ToV9_12_0.py @@ -0,0 +1,98 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV8_6_0ToV9_11_0.py b/src/daEficas/traduitADAOV8_6_0ToV9_11_0.py deleted file mode 100644 index df4e517..0000000 --- a/src/daEficas/traduitADAOV8_6_0ToV9_11_0.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV8_6_0ToV9_12_0.py b/src/daEficas/traduitADAOV8_6_0ToV9_12_0.py new file mode 100644 index 0000000..3162d43 --- /dev/null +++ b/src/daEficas/traduitADAOV8_6_0ToV9_12_0.py @@ -0,0 +1,98 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV9_10_0ToV9_11_0.py b/src/daEficas/traduitADAOV9_10_0ToV9_11_0.py deleted file mode 100644 index df4e517..0000000 --- a/src/daEficas/traduitADAOV9_10_0ToV9_11_0.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV9_10_0ToV9_12_0.py b/src/daEficas/traduitADAOV9_10_0ToV9_12_0.py new file mode 100644 index 0000000..3162d43 --- /dev/null +++ b/src/daEficas/traduitADAOV9_10_0ToV9_12_0.py @@ -0,0 +1,98 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV9_11_0ToV9_12_0.py b/src/daEficas/traduitADAOV9_11_0ToV9_12_0.py new file mode 100644 index 0000000..3162d43 --- /dev/null +++ b/src/daEficas/traduitADAOV9_11_0ToV9_12_0.py @@ -0,0 +1,98 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV9_2_0ToV9_11_0.py b/src/daEficas/traduitADAOV9_2_0ToV9_11_0.py deleted file mode 100644 index df4e517..0000000 --- a/src/daEficas/traduitADAOV9_2_0ToV9_11_0.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV9_2_0ToV9_12_0.py b/src/daEficas/traduitADAOV9_2_0ToV9_12_0.py new file mode 100644 index 0000000..3162d43 --- /dev/null +++ b/src/daEficas/traduitADAOV9_2_0ToV9_12_0.py @@ -0,0 +1,98 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV9_3_0ToV9_11_0.py b/src/daEficas/traduitADAOV9_3_0ToV9_11_0.py deleted file mode 100644 index df4e517..0000000 --- a/src/daEficas/traduitADAOV9_3_0ToV9_11_0.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV9_3_0ToV9_12_0.py b/src/daEficas/traduitADAOV9_3_0ToV9_12_0.py new file mode 100644 index 0000000..3162d43 --- /dev/null +++ b/src/daEficas/traduitADAOV9_3_0ToV9_12_0.py @@ -0,0 +1,98 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV9_4_0ToV9_11_0.py b/src/daEficas/traduitADAOV9_4_0ToV9_11_0.py deleted file mode 100644 index df4e517..0000000 --- a/src/daEficas/traduitADAOV9_4_0ToV9_11_0.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV9_4_0ToV9_12_0.py b/src/daEficas/traduitADAOV9_4_0ToV9_12_0.py new file mode 100644 index 0000000..3162d43 --- /dev/null +++ b/src/daEficas/traduitADAOV9_4_0ToV9_12_0.py @@ -0,0 +1,98 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV9_5_0ToV9_11_0.py b/src/daEficas/traduitADAOV9_5_0ToV9_11_0.py deleted file mode 100644 index df4e517..0000000 --- a/src/daEficas/traduitADAOV9_5_0ToV9_11_0.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV9_5_0ToV9_12_0.py b/src/daEficas/traduitADAOV9_5_0ToV9_12_0.py new file mode 100644 index 0000000..3162d43 --- /dev/null +++ b/src/daEficas/traduitADAOV9_5_0ToV9_12_0.py @@ -0,0 +1,98 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV9_6_0ToV9_11_0.py b/src/daEficas/traduitADAOV9_6_0ToV9_11_0.py deleted file mode 100644 index df4e517..0000000 --- a/src/daEficas/traduitADAOV9_6_0ToV9_11_0.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV9_6_0ToV9_12_0.py b/src/daEficas/traduitADAOV9_6_0ToV9_12_0.py new file mode 100644 index 0000000..3162d43 --- /dev/null +++ b/src/daEficas/traduitADAOV9_6_0ToV9_12_0.py @@ -0,0 +1,98 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV9_7_0ToV9_11_0.py b/src/daEficas/traduitADAOV9_7_0ToV9_11_0.py deleted file mode 100644 index df4e517..0000000 --- a/src/daEficas/traduitADAOV9_7_0ToV9_11_0.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV9_7_0ToV9_12_0.py b/src/daEficas/traduitADAOV9_7_0ToV9_12_0.py new file mode 100644 index 0000000..3162d43 --- /dev/null +++ b/src/daEficas/traduitADAOV9_7_0ToV9_12_0.py @@ -0,0 +1,98 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV9_8_0ToV9_11_0.py b/src/daEficas/traduitADAOV9_8_0ToV9_11_0.py deleted file mode 100644 index df4e517..0000000 --- a/src/daEficas/traduitADAOV9_8_0ToV9_11_0.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV9_8_0ToV9_12_0.py b/src/daEficas/traduitADAOV9_8_0ToV9_12_0.py new file mode 100644 index 0000000..3162d43 --- /dev/null +++ b/src/daEficas/traduitADAOV9_8_0ToV9_12_0.py @@ -0,0 +1,98 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOV9_9_0ToV9_11_0.py b/src/daEficas/traduitADAOV9_9_0ToV9_11_0.py deleted file mode 100644 index df4e517..0000000 --- a/src/daEficas/traduitADAOV9_9_0ToV9_11_0.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOV9_9_0ToV9_12_0.py b/src/daEficas/traduitADAOV9_9_0ToV9_12_0.py new file mode 100644 index 0000000..3162d43 --- /dev/null +++ b/src/daEficas/traduitADAOV9_9_0ToV9_12_0.py @@ -0,0 +1,98 @@ +# -*- 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() diff --git a/src/daEficas/traduitADAOsansToV9_11_0.py b/src/daEficas/traduitADAOsansToV9_11_0.py deleted file mode 100644 index 5701b4a..0000000 --- a/src/daEficas/traduitADAOsansToV9_11_0.py +++ /dev/null @@ -1,118 +0,0 @@ -# -*- 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() diff --git a/src/daEficas/traduitADAOsansToV9_12_0.py b/src/daEficas/traduitADAOsansToV9_12_0.py new file mode 100644 index 0000000..6e3d41d --- /dev/null +++ b/src/daEficas/traduitADAOsansToV9_12_0.py @@ -0,0 +1,118 @@ +# -*- 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() diff --git a/src/daSalome/__init__.py b/src/daSalome/__init__.py index 75c34a2..0dd8479 100644 --- a/src/daSalome/__init__.py +++ b/src/daSalome/__init__.py @@ -126,9 +126,10 @@ __author__ = "Jean-Philippe ARGAUD" __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 *