source: trunk/yao/templates/Y$pname.cpp @ 547

Last change on this file since 547 was 547, checked in by grlod, 13 years ago

Bug on the old structure generation
Debugging "cout" deleted

  • Property svn:eol-style set to native
File size: 149.5 KB
Line 
1/*/////////////////////////////////////////////////////////////////////////////
2/////////////////////// 1e HEADER de DYNAMO (dynide.h) //////////////////////*/
3/******************************************************************************
4                        dynide.h  :  Include, DEfine, (Etc...)
5Ysys error #next=2
6******************************************************************************/
7#ifndef Y$PNAME_CPP
8#define Y$PNAME_CPP
9
10$CPP_IsNewStructure
11
12/*///////////////////////////////////////////////////////////////////////////*/
13/*              LES INCLUDES DE DYNAMO ET POUR TOUT LE MONDE                 */
14//#include <iomanip.h>
15#include <iostream>
16
17#include <iomanip>
18#include <stdio.h>     
19#include <string.h>
20//#include <fstream.h>
21#include <fstream>
22#include <stdlib.h>
23#include <time.h>       
24#include <math.h>
25#include <signal.h>
26#include <stdarg.h>
27//#include <ccomplex>
28#include <complex>
29//#include <complex.h>  //pour octopus (Mandrake et ces pb de deprecated ...!?)
30
31/*///////////////////////////////////////////////////////////////////////////*/
32/*                  DES DEFINES PROPRES A YAO                                */
33#define BUFSIZE                                         1024
34#define STRSIZE20                                       20
35#define STRSIZE80                                       80
36#define NB_MAX_ARG_CDE          30              /* nombre maxi d'arguments pour une commande */
37#define ON                                                               1
38#define OFF                                                              0
39#define OK                                                               1
40#define KO                                                               0
41#define OUI                                                              1
42#define NON                                                              0
43#define PI                 3.14159265358979323846
44#define LG_MAX_NAME                             24                              /* longueur max d'un nom ou mot a usage divers */
45
46using namespace std;
47/*///////////////////////////////////////////////////////////////////////////*/
48
49#ifdef LINUXPC
50                                                // ici les fonctions sont underscorees
51extern void *scpctl_;
52extern void *ctlcan_;
53extern void *canctl_;
54//extern "C" void m1qn3_ (void f(long *, long *, float [], float *, float [], long [], float [], double []),
55extern "C" void m1qn3_ (void f(int *, long *, float [], float *, float [], long [], float [], double []),
56                        void **, void **, void **,
57                        long *, float [], float *, float [], float *, float *,
58                        float *, long *, long *, long *, long *, long *, long [], float [], long *,
59                        long [], float [], double []
60                        );
61//#ifdef YO_M2QN1 ici, on ne sait pas encore si YO_M2QN1 va etre defini ...
62//extern "C" void m2qn1_ (void f(long *, long *, float [], float *, float [], long [], float [], double []),
63extern "C" void m2qn1_ (void f(int *, long *, float [], float *, float [], long [], float [], double []),
64                        long *, float [], float *, float [], float [], float *, float *,
65                        long *, long *, long *, long *, long *, float [], float [],
66                        long [], float [], long [], float [], double []
67                        );
68//#endif
69#else
70                                                // la elles ne le sont pas
71extern void *scpctl;
72extern void *ctlcan;
73extern void *canctl;
74//extern "C" void m1qn3 (void f(long *, long *, float [], float *, float [], long [], float [], double []),
75extern "C" void m1qn3 (void f(int *, long *, float [], float *, float [], long [], float [], double []),
76                        void **, void **, void **,
77                        long *, float [], float *, float [], float *, float *,
78                        float *, long *, long *, long *, long *, long *, long [], float [], long *,
79                        long [], float [], double []
80                        );
81//#ifdef YO_M2QN1 ... idem ici, (ce ne devrait pas etre genant (?)  ;
82//extern "C" void m2qn1 (void f(long *, long *, float [], float *, float [], long [], float [], double []),
83extern "C" void m2qn1 (void f(int *, long *, float [], float *, float [], long [], float [], double []),
84                        long *, float [], float *, float [], float [], float *, float *,
85                        long *, long *, long *, long *, long *, float [], float [],
86                        long [], float [], long [], float [], double []
87                        );
88//#endif
89#endif
90
91/*///////////////////////////////////////////////////////////////////////////*/
92
93//Include$prj"03.h"
94$CPP_NamespaceBegin
95
96/*/////////////////////////////////////////////////////////////////////////////
97/////////////////////// 2e HEADER de DYNAMO (dynamo.h) //////////////////////*/
98/******************************************************************************
99                    dynamo.h  :  ici commence l'encapsulage ...
100******************************************************************************/
101
102/*///////////////////////////////////////////////////////////////////////////*/
103/*              DES ELEMENTS POUR M1QN3 */
104/*#define       Y3_M                                             8      ou en variable globale Y3m ? anywhere now this is done by the generator ! */
105int             Y3run(char vers);                       /* add first for "chloro" (Frederic) */
106void    Y3valstate_all();                       /* add first for "atmos"  (Cedric)   */
107int                     Y3windice;                                              /* indice de travail pour l'affectation des tableaux Y3x et Y3g */
108int             Yc3_run(char vers);
109long    Y3modo;               /*  mode de sortie de m1qn3 (a toute fin utile) */
110
111/*///////////////////////////////////////////////////////////////////////////*/
112/*              DES PROTOTYPAGES POUR TOUS LE MONDE                                  */
113/*Des fonctions de services de Yao ------------------------------------------*/
114template<class TypVal>int       Yinv_tri_vect (int mat_dim, TypVal vect[], TypVal prod[], TypVal inf[], TypVal diag[], TypVal sup[]);
115template<class TypVal>int Yinv_tri_mat (int mat_dim, TypVal inf[], TypVal diag[], TypVal sup[], TypVal mat_inv[]);
116template<class TypReel>void Yvsmatt(int lig, int col, int max_col, TypReel vin[], TypReel Mat[], TypReel vout[]);
117//template<class TypReel>void YvsmattLuigi(int lig, int col, int max_col, TypReel vin[], TypReel Mat[], TypReel vout[]);
118template<class TypReel>void Yvsmat (int lig, int col, int max_col, TypReel vout[], TypReel Mat[], TypReel vin[]);
119template<class TypValA, class TypValB, class TypValX>void Ymxmat (int la, int cl, int cb, TypValA MatA[], TypValB MatB[], TypValX MatX[]);
120template<class TypReal> void Ycx_jac(complex<TypReal> derivee, int j, int i);
121template<class TypReal> void Ycxr_jac(complex<TypReal> derivee, int l, int c);
122
123/*Des fonctions standards de Yao (a completer au fur et a mesure selon les
124  besoins ...?) -------------------------------------------------------------*/
125template<class TypReal>void Yiorwf (char *nmmod, int w4, int w1, int w2, int w3, int wt, TypReal *valout, TypReal valin);
126int     Yio_savestate (char *nmmod, char *oaxis, int pdt, char *filename);
127void    Yrun(long Yit);
128void            Ybasic_it();
129void            Yforwardrun(int itraj, int nbpas);      //Yforwardrun(long Yit, int Ypas);
130int             Yforward(int itraj, int topstop);   //Yforward(int Ypas);
131int             Yforward_order();       
132void            Ycobs(); //Ycost();
133void            Ycostlms_all ();
134void            Ybackwardrun(int itraj, int nbpas); //Ybackwardrun(long Yit, int Ypas);
135void            Ybackward(int itraj, int topstop);  //Ybackward(int Ypas);
136int             Ybackward_order();
137void    Ylinward(int Ypas);
138void            Yadjust();
139void            Yadjust_all ();
140int             Yimod(char *nmmod);
141void    Ysetting(char *codop);
142void    Ydbg_ting(char *str, int nbi, char *nmmod);
143void    Ydbg_beta(char *str, int nbi, char *nmmod);
144void    Ydbg_nanf(char *str, int nbi, char *nmmod);
145int     Ytesterrad_mod(char *nmmod, double YLTRes, double YAdRes);
146int     Yset_modeltime (int time);  //PLM, je ne traite que le repositionnement au debut du modele !!! (ARAR)
147int     Yispace(char *spacename);
148int     Yitraj(char *trajname);
149int     Ytttt_pdt (int wxtraj, int topy, int wytraj);
150int     Yactraj(int cdesc, char *cdes[]);
151int     Yfarg(int(*fct)(int argc, char *argv[]), char *args);
152int       Yrecup_cde (int *cdesc, char *cdeline, char *cdes[]);
153void    Ylopera();
154void      Ylistobs(int itraj);
155int     Yentry0 (int argc, char *argv[]);
156
157/*Des fonctions reseaux de neurones de Yao: celles-ci sont dans Dynnet.h ----*/
158
159
160/* ///////////////////////////////////////////////////////////////////////// */
161/*                      DES TYPES ET STRUCTURES DE DONNEES                                   */
162enum YCostKind          /* les fonctions de cout : */
163{               COST_APPLI,                      /* fonction de cout propre à l'application */
164                COST_LMS                                 /* fonction de cout lms standard de Yao */
165};
166enum YCostL2Kind                /* les fonctions de cout : */
167{               //COSTL2_GRAD,           /*  */
168                //COSTL2_ONLY                    /*  */
169    //,COSTL3_PROJECT    /*  */
170    //,COSTL3_NANACT     /*  */
171    //,
172                WISHL2_NANACT              /*  */
173    ,WISHL2_DIFF             /*  */
174    ,WISHL2_QTEA             /*  */
175    ,COSTL2_WISHDIFF   /*  */
176    ,COSTL2_WISHQTEA     /*  */
177    ,COSTL2_GRAD                 /*  */
178};
179enum YAdjustKind        /* le type d'ajustement : */
180{               ADJUST_APPLI,            /* fonction d'ajustement propre à l'application */
181                ADJUST_STD,                      /* fonction d'ajustement standard (et classique) de Yao */
182                ADJUST_M1QN3             /* M1QN3 (PLM: pas vraiment utile puisque c'est d'office forced avec m1qn3, but ...) */
183};
184enum YRunL1Kind         /* type de run (run algo mode) au 1er niveau :*/
185{               RUNL1_STD,                       /* soit methode de base simple, standard */
186          RUNL1_M1QN3            /* soit 'a la maniere de'  m1qn3 */
187};
188enum YRunL2Kind         /* le mode de fonctionnement de run (run algo mode), 2Úme niveau : */
189{               RUNL2_STD,                              /* soit algo de base simple, standard */
190                RUNL2_INCR                      /* soit algo incremental */
191};
192enum YioKind              /* le cas d'io concerne : */
193{               YIO_LOADSTATE,   /* chargement des etats (not yet) */
194                YIO_SAVESTATE,   /* sauvegarde des etats */
195                YIO_LOADOBS,             /* chargement des observations */
196                YIO_SAVEOBS,             /* sauvegarde des observations (not yet & why?) */
197                YIO_OUTOOBS,             /* copie state->obs */
198                YIO_OUTOEBX,             /* copie state->ebauche (in the same arbobs) */
199                YIO_OBSTOUT,             /* copie obs->state (not yet & why?) */
200                YIO_LISTOBS                      /* liste des observations */
201};
202/* type du run courant de trajectoire (pour hidjack)*/
203enum YWardKind
204{               FORWARD,
205                BACKWARD,
206                LINWARD
207};
208/* structure d'un noeud de l'arborescence des observations */
209struct   Yst_nodo  {
210        int              iind; /* indice pour l'indicateur t, m, s, i, j */
211        struct Yst_nodo *frere;
212        struct Yst_nodo *fils;
213};
214
215/* structure d'une trajectoire */
216struct Yst_traj {
217        char            name[STRSIZE80+1];
218        char    type;
219        int               nbuptime;
220        float   offtime;
221        float   dtime;                     // delta t
222        float           curtime;
223        int                     toptime;       // temps unitaire
224        int               nbsteptime;
225        float           stoptime;      //=Ybegintime + offtime + (dt*nbsteptime)   (nb: initialement, Ybegintime=0)
226        int     (*fward)(int nbt);
227        int     (*bward)(int nbt);
228        int     (*lward)(int nbt);
229        int     (*dfward)(int modop, char *nmmod, int All, int KeKo, int koleft, float pdx, float ptol, int yi, int yj, int yk);
230        short   isactiv;
231        struct  Yst_nodo *YRobs;      //=NULL; // Racine de l'Arborescence des observations
232  struct  Yst_nodo *TRobs;      // un pointeur sur le Time   s/Root courant trouve
233};
234/* structure d'un espace */
235struct Yst_space {
236        char            name[STRSIZE80+1];
237        char    type;
238        int                     axi;
239        int                     axj;
240        int                     axk;
241        char            traj_name[STRSIZE80+1];
242};
243/* structure d'un operateur */
244struct Yst_opera {
245        char            name[STRSIZE80+1];
246        char    type;
247        int                     axi;
248        int                     axj;
249        int                     axk;
250        char            traj_name[STRSIZE80+1];
251        short   isactiv;
252};
253/* structure d'un module */
254struct Yst_modul {
255        char            Name[STRSIZE80+1];
256        void            *Tadr;
257        int                     dim;
258        int                     axi;
259        int                     axj;
260        int                     axk;
261        int                     nb_input;
262        int                     nb_stout;
263        int                     nb_time;
264        int                     is_cout;
265        int                     is_target;
266        int                     deb_target;
267        int                     end_target;
268        double  scoef;
269        double  bcoef;
270        double  pcoef;
271        int     ctrord;
272        char            space_name[STRSIZE80+1];
273        //short   sys_flagobs;
274};
275/* structure d'un reseau de neurone */
276typedef enum {SigLin, SigSig} Activation;
277struct Yst_netward {
278        char            Name[STRSIZE80+1];
279        int             nbweight;
280        int                     nbinput;
281        int                     nboutput;
282        int             maxcell;
283        double  *tweight;
284        Activation activ;
285};
286/* structure des definitions de valeurs */
287struct Yst_defval {
288        char            Name[STRSIZE80+1];
289        char            macro[STRSIZE80+1];
290};
291
292short            Ysysdbg;       /* reserved for system supervisor */
293
294/* ///////////////////////////////////////////////////////////////////////// */
295/*                       LES GLOBALES DE YAO ET POUR TOUT LE MONDE                           */
296//!!! added Yqs_nbparts (temporally of course) for the quasi static
297int Yqs_nbParts = 1;
298long             Ytop0;                                                                 /* un top global pour decompter le temps */
299int                      YTemps;                                                                /* horloge des pas de temps a patir d'NBUPTIME */
300//float  YTotalCost;                                            /* cout total */
301double   YTotalCost;                                            /* cout total */
302double   YCoefGrad = 1.0;                               /* coeff de calcul du gradient (defaut=1) */
303enum             YCostKind       YTypeCost=COST_LMS;    /* le type de la fonction de cout (default=lms) */
304enum             YCostL2Kind YCaseCost=COSTL2_GRAD; //COSTL2_GRAD;      /*  */
305enum             YAdjustKind YTypeAdjust=ADJUST_STD;    /* le type d'ajustement (default=standard) */
306enum             YRunL1Kind     YAL1Run=RUNL1_STD; /* mode (algo) du run au 1er niveau (default=standard : definie par la commande run utilisee) */
307enum             YRunL2Kind     YAL2Run=RUNL2_STD; /* mode (algo) du run au 2em niveau (default=standard : definie par la commande run utilisee) */
308long             YNbItRun;                                                      /* nombre d'itérations demande ((IO)niter p/m1qn3) */
309long             YItRun;                                                                /* l'iteration courante du run */
310long             YNbExtL;                                                         /* nombre de boucles externes pour les algo incrementaux */
311int                      YDispTime;                                                     /* boolean pour l'affichage du temps */
312int                      YDispCost;                                                     /* boolean pour l'affichage du cout */
313char             YPrompt[STRSIZE20+1];  /* le prompt pour la saisie des commandes */
314int                      YEcho = ON;                                            /* echo de la commande */
315
316int                      Yi, Yj, Yk;                                               /* indice de parcourt de l'espace gabarit */
317int YY;                                         /* The variable YY is used only as artifact (in the parallelization) for the bug of openMP
318                                                 * that does not allow to global variables passed to a function to conserve the value
319                                                 * of the calling function.
320                                                 * The value passed to the function is uncorrect (probably is the initialization value) */
321
322int                      YY_RUNBRK=ON;                                  /* gestion signal d'interruption pour breaker le run */
323short            YM_EXE;                                                        /* Mode d'execution: 'B': Batch; 'I': intercatif */
324//int            YM_GRADTEST = OFF;             /* Mode test du gradient: pour tester les derivees (ne pas affecter */
325                                                                                                                                /*      les inputs des modules) */
326int              Yszint, Yszreal;                       /* tailles d'un int et d'un reel (initialises au debut de Dynamo.cpp */
327FILE             *Yiofp;                                                                /* file pointeur pour les fonctions d'entree/sortie */
328short      YioWrite, YioRead;                   /* flag (booleen) pour le mode de fonctionnement des fct d'entree/sortie */
329short      YioBin, YioAscii;                    /* flag pour le type de stockage des donnees: binaire ou ascii */
330short            YioState, YioTime, YioAxes; /* flag pour la convention, le format de stockage des donnees */
331int                      YioszReal;             /* taille d'un reel pour des valeurs (binaire?) a loader (en provenance de l'exterieur */
332short            YioModulot;                                            /* modulo t pour les sauvegardes de donnees */
333int                YioInsertObsCtr=-1;          /* compteur d'obs inserees (-1 pour savoir si y'a au moins 1 obs. Utile pour testad */ 
334int                YioOvrObsCtr;                                        /* compteur d'obs overidees */ 
335int                YioSelectedCtr;                              /* compteur de selection */     
336int                      YioDi, YioDj, YioDk;           /* dimension d'un espace exterieur a charger */
337int                      Yiodi, Yiodj, Yiodk;           /* decalage a appliquer sur les coordonnes d'un espace exterieur a charger */           
338char     YioSep[STRSIZE20]="\n";/* chaine de caratÚres pour la separation de token dans les fct d'io (modifiable pas set_sep) */
339int                      Ydmod;                                                                 /* dimension du module en cours*/
340short            Ytestad_module;                                /* flag de test de l'adjoint par module */
341double   YLTRes, YAdRes;                                /* resultat des tests de l'adjoint par module */
342double   Yerrelmax;                                             /* une erreur relative max */
343int                      Ynbko, Ymaxko;                                 /* nombre de ko et le max autorise */
344double   Ypzedi;                                                          /* un parametre de zero informatique */
345enum     YWardKind Ycurward;    /* type du run courant de trajectoire (pour hidjack) */
346int      YNbBasicIntL = 1;      /* nombre de boucle interne a basic_it, modifiable avec set_nb_basic_intern_loop (default=1) */
347int      YItBasicIntL;          /* iteration de la boucle interne a basic_it */
348
349/* multi-spatio-tempo : ---------*/
350
351/* variables globales a gerer par changement de contexte ! */
352float    Ybegintime = 0.0;      /* temps initial du modele global */
353float    Yendtime   = 0.0;      /* temps final du modele global   */
354#define  MYMAXREEL       3.40282347e+38
355int      YidTraj;                                                         /* indice de la trajectoire courante*/
356int      YNBUPTIME, YNBALLTIME;
357int      YA1, YA2, YA3;                                 /* taille des axes de l'espace courant */
358#define  Yt     YTemps                                  /* temps courant de la trajectoire courante (toptime) */
359int      Ytps;                                                                  /* variable pour la gestion du temps entre trajectoire */
360
361// For the parallelization: all these global variables should be privates.
362// Yi, Yj, Yk is for the correct run of the computation loops.
363// YY is for the OpenMP bug that doesn't allow to call a function in a parallel region and mantain the thread value
364// of a global private variable. The value in the called function is not what should be.
365// Ytps is for the special case of multi_t so when two modules connected have different trajectory and
366// the should be translated with Ytttt_pdt() function.
367//#ifdef YO_PARALLEL
368#ifdef _OPENMP
369  #pragma omp threadprivate(Yi, Yj, Yk, YY, Ytps)       
370#endif                                                 
371
372
373
374/* certaines variables generees */
375extern struct Yst_modul YTabMod[];
376
377//=============================================================================
378//                             OU DOIS-JE METTRE Ygetval ???
379//=============================================================================
380double Ygetval(char *codop) //creed pour dx random des fonctions de test
381{   double val;             //utilised par ...
382                if (codop[0]=='R')  /* rand in [-1, 1]  * coef */
383                {  //return(((double)rand()/RAND_MAX)*2-1);
384                   val = ((double)rand()/RAND_MAX)*2-1;
385                         if (strlen(codop)>1)
386                         {  //si R est suivi d'autres caracteres, ce doit etre un coef a appliquer
387                            //sur le random (ex: si codop = "R0.15" alors val = val * 0.15
388                            val = val * atof(codop+1);
389                         }
390                         return(val);
391                }
392                else
393                         return (0.0);
394}
395//=============================================================================
396void Ycreate_errnew()
397{    printf("error on space allocation with new when crteating module; see your YAO administrator\n");
398     exit(-9);
399}
400//=============================================================================
401
402
403
404//=============================================================================
405//                             TOOL BOX 1
406//=============================================================================
407
408//=============================================================================
409//                  deux fonctions inline MIN et MAX
410// Ymin : renvoie le MIN de 2 valeurs (dans le type de la 1Úre)
411template<class TypVala, class TypValb>inline TypVala Ymin (TypVala a, TypValb b)
412{       return (a<b)? a:b;
413}
414//-----------------------------------------------------------------------------
415// Ymax : renvoie le MAX de 2 valeurs (dans le type de la 1Úre)
416template<class TypVala, class TypValb> TypVala Ymax (TypVala a, TypValb b)
417{       return (a>b)? a:b;
418}
419
420//=============================================================================
421/* Ypr_tabr: affiche les elements d'un tableau de reels */
422template<class TypReal>void Ypr_tabr (char *str, TypReal TabReal[], int nbelt, char *sep)
423{       printf("%s", str);
424  for(int i=0; i<nbelt;++i) printf("[%i] = % -23.15e%s", i, TabReal[i], sep);
425}
426//=============================================================================
427
428//=============================================================================
429//                    some singles lineare algebra functions
430/* Yprosca: produit scalaire (de 2 vecteurs)                                 */
431template<class TypReel>double Yprosca (TypReel a[], TypReel b[], int sz)
432{       int i;
433        double res=0.0, cal;
434  //for (i=0; i<sz; ++i) res += a[i]*b[i];
435        for (i=0; i<sz; ++i)
436        {               cal = a[i]*b[i]; res += cal;
437                        //if (Ysysdbg) printf("Yprosca: % -23.15e <+= % -23.15e * % -23.15e \n", res, a[i], b[i]);
438        }
439        return(res);
440}
441
442//=============================================================================
443//                    some singles statiticals functions
444/* Ystat_moy:   moyenne d'un tableau de valeurs                              */
445template<class TypVal, class TypRes>void Ystat_moy (TypVal TabVal[], int nbelt, TypRes *moy)
446{       *moy=0.0;
447        for(int i=0; i<nbelt;++i) *moy += TabVal[i];
448        *moy = *moy/nbelt;
449}
450/* --------------------------------------------------------------------------*/
451/* Ystat_mv:   moyenne et variance d'un tableau de valeurs                   */
452template<class TypVal, class TypRes>void Ystat_mv (TypVal TabVal[], int nbelt, TypRes *moy, TypRes *var)
453{
454        /* moyenne */
455        Ystat_moy(TabVal, nbelt, moy);
456
457        /* variance */
458        *var=0.0;
459        for(int i=0; i<nbelt;++i) *var += pow((TabVal[i]-*moy),2);
460        *var = *var/nbelt;
461}
462/* --------------------------------------------------------------------------*/
463/* Ystat_norm1: normalisation d'un tableau de valeurs */
464template<class TypVal, class TypRes>void Ystat_norm1 (TypVal TabVal[], int nbelt, TypRes moy, TypRes sig)
465{
466        for(int i=0; i<nbelt;++i) TabVal[i] = (TabVal[i]-moy)/sig;
467}
468/* --------------------------------------------------------------------------*/
469/* Ystat_denorm1: de-normalisation d'un tableau de valeurs */
470template<class TypVal, class TypRes>void Ystat_denorm1 (TypVal TabVal[], int nbelt, TypRes moy, TypRes sig)
471{
472        for(int i=0; i<nbelt;++i) TabVal[i] = TabVal[i]*sig + moy;
473}
474
475/*===========================================================================*/
476/*===========================================================================*/
477
478//FOR DEBUG
479//void Ytrobs (int indic, char *nmmod, int nout, int iaxe, int jaxe, int kaxe, int pdt, YREAL *vobs, YREAL *qtea)
480void Ytrobs (int indic, char *nmmod, int nout, int iaxe, int jaxe, int kaxe, int pdt, double *vobs, double *qtea)
481{        printf("%i %s %i %i %i %i t=%i %e %e \n",indic, nmmod, nout, iaxe, jaxe, kaxe, pdt, *vobs, *qtea);
482}
483//void Ywlobs(void(*fct)(int i1, char *str, int i2, int i3, int i4, int i5, int i6, YREAL *r1, YREAL *r2), int indic);
484void Ywlobs(void(*fct)(int i1, char *str, int i2, int i3, int i4, int i5, int i6, double *r1, double *r2), int indic);
485
486
487//=============================================================================
488//                       GENERIC MODUL OBJECT FUNCTION
489//=============================================================================
490template <class TypVal, class TypClass> int Ysetstate_generic (char *nmmod, TypVal val, TypClass *pc[])
491{               int imod, nbs, axi, axj, axk;
492                imod = Yimod(nmmod);
493                        nbs = YTabMod[imod].nb_stout;
494                        axi = YTabMod[imod].axi;
495                        axj = YTabMod[imod].axj;
496                        axk = YTabMod[imod].axk;
497
498                 //cas non tempo
499            if (axk>0)
500                        {  //cas 3D
501                           for (int Yw1=0; Yw1<axi; ++Yw1){
502                           for (int Yw2=0; Yw2<axj; ++Yw2){
503                           for (int Yw3=0; Yw3<axk; ++Yw3){
504                           for (int Yws=0; Yws<nbs; ++Yws){
505                                 pc[Yw1*axj*axk+Yw2*axk+Yw3]->Ystate[Yws] = val;}}}}
506                        }
507                        else if (axj>0)
508                        {  //cas 2D
509                           for (int Yw1=0; Yw1<axi; ++Yw1){
510                           for (int Yw2=0; Yw2<axj; ++Yw2){
511                           for (int Yws=0; Yws<nbs; ++Yws){
512                                 pc[Yw1*axj+Yw2]->Ystate[Yws] = val;}}}
513                        }
514                        else
515                        {  //cas 1D
516                           for (int Yw1=0; Yw1<axi; ++Yw1){
517                           for (int Yws=0; Yws<nbs; ++Yws){
518                                 pc[Yw1]->Ystate[Yws] = val;}}
519                        }
520     return(1); //?
521}
522//=============================================================================
523template <class TypVal, class TypClass> int Ysetstatet_generic (char *nmmod, TypVal val, TypClass *pc[])
524{               int imod, nbs, axi, axj, axk, axt;
525                imod = Yimod(nmmod);
526                        nbs = YTabMod[imod].nb_stout;
527                        axi = YTabMod[imod].axi;
528                        axj = YTabMod[imod].axj;
529                        axk = YTabMod[imod].axk;
530                        axt = YTabMod[imod].nb_time;
531
532                //cas tempo
533            if (axk>0)
534                        {  //cas 3D
535                           for (int Yw1=0; Yw1<axi; ++Yw1){
536                           for (int Yw2=0; Yw2<axj; ++Yw2){
537                           for (int Yw3=0; Yw3<axk; ++Yw3){
538                     for (int Ywt=0; Ywt<axt; ++Ywt){
539                           for (int Yws=0; Yws<nbs; ++Yws){
540                                 //pc[Yw1][Yw2][3]->Ystate[Ywt][Yws] = val;}}}}}
541                                 pc[Yw1*axj*axk+Yw2*axk+Yw3]->Ystate[Ywt][Yws] = val;}}}}}
542                        }
543                        else if (axj>0)
544                        {  //cas 2D
545                           for (int Yw1=0; Yw1<axi; ++Yw1){
546                           for (int Yw2=0; Yw2<axj; ++Yw2){
547                     for (int Ywt=0; Ywt<axt; ++Ywt){
548                           for (int Yws=0; Yws<nbs; ++Yws){
549                                 //pc[Yw1][Yw2]->Ystate[Ywt][Yws] = val;}}}}
550                                 pc[Yw1*axj+Yw2]->Ystate[Ywt][Yws] = val;}}}}
551                        }
552                        else
553                        {  //cas 1D
554                           for (int Yw1=0; Yw1<axi; ++Yw1){
555                     for (int Ywt=0; Ywt<axt; ++Ywt){
556                           for (int Yws=0; Yws<nbs; ++Yws){
557                                 pc[Yw1]->Ystate[Ywt][Yws] = val;}}}
558                        }
559      return(1); //?
560}
561//=============================================================================
562//=============================================================================
563
564
565
566/*///////////////////////////////////////////////////////////////////////////*/
567/*                      L'INCLUDE DE L'APPLI GENERATRICE et de son nom                       */
568
569
570
571$CPP_Y1PRJ
572//IncludeY3prj
573$CPP_Y2PRJ
574$CPP_PRJNAME
575$CPP_VERREF
576
577
578//=============================================================================
579/* ////////////////////////////////////////////////////////////////////////////
580//               DES FONCTIONS DE SERVICES (boite a outils)                                                                      //
581//////////////////////////////////////////////////////////////////////////// */
582
583/*===========================================================================*/
584/* Yvsmat:    multiplication d'une Sous-MATrice par un Vecteur               */
585/* --------------------------------------------------------------------------*/
586/*template<class TypReel>void oldYvsmat (int lig, int col, int max_col, TypReel vout[], TypReel Mat[], TypReel vin[])
587{       int l, c, lmc;
588  TypReel cal;
589        for (l=0; l<lig; ++l)
590        {               vout[l] = 0.0;
591                        lmc=l*max_col;
592                        for (c=0; c<col; ++c)
593                        {               //vout[l] += vin[c]* Mat[lmc+c];
594                                        cal = vin[c] * Mat[lmc+c]; vout[l] += cal;
595                        }
596        }
597}*/
598template<class TypReel> void Yvsmat (int lig, int col, int max_col, TypReel vout[], TypReel Mat[], TypReel vin[])
599{       int l, c;
600  TypReel cal, *M;
601  for (l=0; l<lig; ++l)
602        {   vout[l] = 0.0;
603            M=&Mat[l*max_col];
604            for (c=0; c<col; ++c)
605                        {               cal = vin[c] * M[c];
606                                        vout[l] += cal;
607                        }
608        }
609}
610/*===========================================================================*/
611/* Yvsmatt:   multiplication d'une Sous-MATrice Transposee par un Vecteur    */
612/* --------------------------------------------------------------------------*/
613/*template<class TypReel>void oldYvsmatt (int lig, int col, int max_col, TypReel vin[], TypReel Mat[], TypReel vout[])
614{       int l, c;
615  TypReel cal;
616        for (c=0; c<col; ++c)
617        {               vout[c] = 0.0;
618                        for (l=0; l<lig; ++l)
619                        {         //vout[c] += vin[l]* Mat[(l*max_col)+c];
620                                  cal = vin[l]* Mat[(l*max_col)+c]; vout[c] += cal;
621//printf("xxxxxxxx>  %e * %e +=> %e  \n", vin[l], Mat[(l*max_col)+c], vout[c]);
622                        }
623        }
624  //if (Yi==0 && Yj==0 && Yk==0 && YTemps==2)
625        //   printf ("Yvmat: vin[%i]=%f Mat(%i,%i)=%f\n", l, vin[l], l, c, Mat[(l*max_col)+c]);
626}*/
627template<class TypReel> void Yvsmatt (int lig, int col, int max_col, TypReel vin[], TypReel Mat[], TypReel vout[])
628{       int l, c;
629  TypReel cal, *M;
630        memset(vout,0,col*sizeof(TypReel));
631        for (l=0; l<lig; ++l)
632        {   M=&Mat[l*max_col];
633            for (c=0; c<col; ++c)
634            {   cal = vin[l] * M[c];
635                vout[c] += cal;
636            }
637        }
638}
639
640// Juste pour le parallelisme: on est en train ici d'essayer de paralleliser la moltiplication Yvsmatt.
641// Cette solution n'est pas optimelle mais ça nous permet déjà de voir que le nested parallelism ne marche pas dans ce cas.
642// On fait pas assez de calcule dans cette fonction pour justifier l'overhead du au parallelisme.
643// On laisse cette fonction pour futures études.
644// Les amolioration à faire c'est des gérer mieu toutes les variables et trouver un moyen pour ne pas faire le dernier for: lastprivate ou du genre.
645/*template<class TypReel> void YvsmattLuigi (int lig, int col, int max_col, TypReel vin[], TypReel Mat[], TypReel vout[])
646{
647  TypReel v[col];
648  memset(vout,0,col*sizeof(TypReel));
649  memset(v,0,col*sizeof(TypReel));
650#pragma omp parallel for
651  //shared(v,col,lig,max_col, Mat, vin) private(vout) default(none) num_threads(1)
652  for(int c=0; c<col; ++c){   
653    TypReel *M;
654    TypReel cal=0;
655    M=&Mat[c];
656    for(int l=0; l<lig; ++l)
657      cal += vin[l] * M[l*max_col];
658      //vout[c] += vin[l] * M[l*max_col];
659    v[c] = cal;
660  }
661  for(int c=0; c<col; ++c)
662    vout[c] = v[c];
663}
664*/
665
666/*===========================================================================*/
667/* Ymxmat:   multiplication de Matrices : X = A * B                          */
668/* --------------------------------------------------------------------------*/
669template<class TypValA, class TypValB, class TypValX>void Ymxmat (int la, int cl, int cb, TypValA MatA[], TypValB MatB[], TypValX MatX[])
670{ //la = nbre de lignes de A
671  //cl = nombre de colonnes de A = nombre de lignes de B
672  //cb = nombre de colonnes de B
673  int l, n, c;
674  int lxcl;
675  TypValX cal;
676        for (c=0; c<cb; ++c)
677        {               for (l=0; l<la; ++l)
678                        {   cal = (TypValX)0.0;
679                            lxcl = l*cl;
680                                        for (n=0; n<cl; ++n)
681                                        {       cal += MatA[lxcl+n] * MatB[c+n*cb];                                     
682                                        }
683                                        MatX[l*cb+c] = cal; 
684                        }
685        }
686}
687/*===========================================================================*/
688/*                      Calcul de derivees complexes                         */
689/*---------------------------------------------------------------------------*/
690template<class TypReal> void Ycx_jac(complex<TypReal> derivee, int j, int i)
691{ /* Peut etre utilised si le module n'a que des complexes
692     en entrees-sorties. Les indices j, i a passer doivent
693           correspondre a un indicage sur les complexes          */
694        int l, c;
695        l=j*2-2; c=i*2-2;
696        Yjac[][]   = real(derivee);
697        Yjac[l+1][]   = imag(derivee);
698        Yjac[][c+1]   = -Yjac[l+1][];
699        Yjac[l+1][c+1]   = Yjac[][];
700}
701//-----------------------------------------------------------------------------
702template<class TypReal> void Ycxr_jac(complex<TypReal> derivee, int l, int c)
703{       /* Peut etre utilised lorsque le module melange reels et
704           complexes en entrees-sorties. Les indices l, c a passer doivent
705           correspondre a un indicage sur les reels                         */
706        Yjac[l-1][c-1]   = real(derivee);
707        Yjac[][c-1]   = imag(derivee);
708        Yjac[l-1][]   = -Yjac[][c-1];
709        Yjac[][]   = Yjac[l-1][c-1];
710}
711
712/*===========================================================================*/
713/*                Inversion d'une matrice (carree) tri-diagonale             
714  input:        mat_dim : dimension des vecteur et de la matrice
715                                inf                     :       vecteur inferieur
716                                diag            :       vecteur diagonal
717                                sup                     :       vecteur superieur
718  output:       mat_inv :       la matrice inverse
719  code retour                   : 0=Ok, 1=Ko                                                                                                                                                                                     */
720/* ------------------------------------------------------------------------- */
721template<class TypVal>int Yinv_tri_mat (int mat_dim, TypVal inf[], TypVal diag[], TypVal sup[], TypVal mat_inv[])
722{               /* Construction de la matrice inverse */
723    int                         i, j; 
724    TypVal      *vect, *prod; //TypVal   vect[mat_dim], prod[mat_dim];
725    vect   =    (TypVal*) calloc(mat_dim, sizeof(TypVal));
726    prod   =    (TypVal*) calloc(mat_dim, sizeof(TypVal));
727
728    for (i = 0; i < mat_dim; i++)
729    {
730                for (j = 0; j < mat_dim; j++)
731                        vect[j] = (TypVal)0;
732        vect[i] = (TypVal)1;
733
734        if (!Yinv_tri_vect (mat_dim, vect, prod, inf, diag, sup))
735        {               cout << "~~~~~>Yinv_tri_vect:  erreur 1:  ????????????????????????\n";
736                        return 0;       /* csr: avant y'avait que if DEBUG_... */
737                        }
738       
739        for (j = 0; j < mat_dim; j++)
740                        mat_inv[(j*mat_dim)+i] = prod[j];
741    }
742    free(vect); free(prod);
743    return 1;
744}
745/* -------------------- Inversion matrice (suite) !? ----------------------- */
746template<class TypVal>int       Yinv_tri_vect (int mat_dim, TypVal vect[], TypVal prod[], TypVal inf[], TypVal diag[], TypVal sup[])
747{               int       i;
748    TypVal    bet;
749    TypVal    *R; //(TypVal)   R[mat_dim];
750    R              =    (TypVal*) calloc(mat_dim, sizeof(TypVal));
751
752    if (diag[0] == (TypVal)0)
753    {           cout << "~~~~~>Yinv_tri_vect:  erreur 1:  ???????????????????????????\n";
754        return 0;
755        }
756    prod[0] = vect[0] / (bet = diag[0]);
757
758    for (i = 1; i < mat_dim; i++)
759    {
760        R[i] = sup[i - 1] / bet;
761        bet  = diag[i] - inf[i] * R[i];
762
763        if (bet == (TypVal)0.0)
764        {               cout << "~~~~~>Yinv_tri_vect:  erreur 2:  ???????????????????????????\n";
765                        return 0;
766        }
767        prod[i] = (vect[i] - inf[i] * prod[i - 1]) / bet;
768    }
769
770    for (i = (mat_dim - 2); i >= 0; i--)
771    {           prod[i] -= R[i + 1] * prod[i + 1];
772    }
773    free(R);
774    return 1;
775}
776
777
778/* ////////////////////////////////////////////////////////////////////////////
779//                      LES FONCTIONS STANDARS DE YAO                                                                                            //
780//////////////////////////////////////////////////////////////////////////// */
781/* ----------------------------------------------------------------------------
782//================== Help me if you can I'm feeling bad ==================== */
783void Yhelp(char lang)
784{ printf("\n Not include: user_fct,  Not yet include : Yauto_fct\n");
785
786        if (lang=='f') /* ..................... FRANCAIS ..........................*/
787        {       printf (" Abreviations: file: fichier;  str: chaine de caractÚre;  modname: nom de module\n");
788          printf ("   nbpdt: nombre de pas de temps  val: valeur entiere   real: un reel\n");
789          printf ("   nout: n° de sortie\n");
790                printf ("   (I) (resp (B)): valable seulement en mode Interactif (resp Batch)\n");
791                printf ("   [0 ou 1 au choix] {1 seul choix obligatoire}\n");
792                printf ("   la saisie soit en minuscule soit en majuscule exclusivement est acceptee\n");
793                printf ("-----------------------------------------------------------------------------\n");
794                //divers
795                printf (" help | aide|? : [e | f]: l'aide que vous venez d'afficher\n");
796                printf (" exit |quit|bye: pour en finir avec Yao \n");
797                printf (" !             : str: permet de passer la commande systeme contenue dans str\n");
798                printf (" echo          : {on | off}: active ou pas l'affichage de la commande (B)\n");
799                printf (" set_prompt    : str:  pour avoir un prompt à son goût\n");
800                printf (" pause         : marque une pause: se met en attente d'un RC pour continuer\n");
801                printf (" ltraj         : liste des trajectoires avec certaines informations\n");
802                printf (" straj         : schema des trajectoires (valide si offtime et dtime sont des entiers)\n");
803                printf (" pdt2pdt       : fromtrajname steptime totrajname : (sous reserve) donne l'equivalence du\n");
804                printf ("               : steptime de fromtrajname pour la trajectoire totrajname\n");
805                printf (" activ|unactiv : {trajname ,typetraj} [{trajname ,typetraj}[...]] [{only, less}]: activation\n");
806                printf ("               : ou neutralisation de trajectoire (cf doc)\n");
807                printf (" lspace        : liste des espaces avec certaines informations\n");
808                printf (" nmod          : modname: donne le numero du module modname\n");
809                printf (" lmod          : liste des modules avec certaines informations\n");
810                printf (" lval          : liste des valeurs prédéfinies \n");
811                printf (" load_inst     : file: execute les instructions contenues dans file\n");
812                printf (" goto          : label: pour sauter les instructions suivantes jusqu'a la chaine 'label'\n");
813                //pour preparer un run
814    printf (" set_begintime : val: affecte la valeur val au temps initial du modele global\n");
815    printf (" set_modeltime : 0: positionne toutes les trajectoires sur leur temps initial\n");
816    printf (" set_toptime   : trajname val: affecte le temps unitaire courant de la trajectoire a val\n");
817    printf (" set_dtime     : trajname val: affecte la valeur val au dt de la trajectoire\n");
818    printf (" set_offtime   : trajname val: affecte val au decalage temporel de la trajectoire\n");
819                printf (" print_cost    : [on | off |]: soit affiche le cout (YTotalCost) soit met a ON, OFF ou LAST\n");
820                printf ("                 le flag qui permet de l'afficher au cours (ou a la fin avec LAST) des iterations \n");
821                printf (" print_time    : [on | off]: soit affiche le top de toutes les trajectoires, soit switch\n");
822                printf ("               : le flag qui permet l'affichage du temps au cours d'itérations\n");
823                printf (" cost          : {lms real | appli}: choix de la fonction de cout, et définition d'un\n");
824                printf ("                 coef pour la calculer qui s'applique à tous les modules, mais ... \n");
825                printf (" set_scoef     : modname coef: positionne un coef pour modname en lieu et place de\n");
826                printf ("                 celui défini par cost\n");
827                printf (" set_bcoef     : modname coef: positionne un coef pour modname pour le calcul du cout\n");
828                printf ("                 sur les termes d'ébauche\n");
829                printf (" set_pcoef     : modname coef: positionne un coef ou %cage pour modname: utilisation :\n",'%');
830                printf ("                 1: delta pour l'incremental; 2: ...\n");
831                printf (" adjust        : {std | appli}: choix de la formule d'ajustement de ou des variables\n");
832                printf ("                 Ã  minimiser\n");
833                printf (" testad        : pdx [{-1, tol}] maxcase [zinfo]]: test de l'adjoint global [ou local]:\n");
834                printf ("                               < M'(Xo).dx, dy > = < dx, M*(Xo).dy >\n");
835                printf (" testdf        : i j k codop [%c]pdx ptol [modname-ko]: fonction de vérification de la\n", '%');
836                printf ("                 programmation des dérivées au point ijk, au temps t=1,\n");
837                printf ("                 codop (reel, 0, N, R, r : cf doc) determine les valeurs des entrées des modules,\n");
838                printf ("                 pdx=une perturbation (en %ctage si %c) de x, et ptol une tolérance en %c.\n", '%', '%', '%');
839                printf (" testlt        : pdx alpha fdec nbloop [modop]: test du lineaire tangent, et \n");
840                printf (" testof          test de la fonction objective (cf doc...) avec dx = Xo*pdx, alpha : \n");
841                printf ("                 parametre de tendance,  fdec : facteur de decroissance de alpha, nbloop :\n");
842                printf ("                 nombre de boucles de decroissance, et modop : un mode operatoire 0 ou 1\n");
843                printf (" set_iosep     : chaine de caracteres: a utiliser comme separateur de token dans les fonction d'i/o\n");
844                printf (" outoobs       : modname nout liste_pdt: Utilisation des états commes observations\n");
845                printf (" loadobs       : cf paramÚtres dans la doc: Chargement d'observations à partir d'un fichier\n");
846                printf (" loadstate     : cf paramÚtres dans la doc: Chargement d'états à partir d'un fichier\n");
847                printf (" savestate     : objname nout oaxis t[%c] {A,B} {0,1,2,3} [filename]: sauvegarde de modules selon\n",'%');
848                printf ("                 objname (cf doc) pour la (ou toutes les (si 0)) sortie selon l'ordre oaxis des\n");
849                printf ("                 axes au (ou pour tous les si 0) pas de temps t (ou modulo(t)), en Ascii\n");
850                printf ("                 ou Binaire. puis vient:  0=>que la valeur, 1=>+les axes, 2=>+le temps, 3=1+2.\n");
851                printf ("                 les sorties se font dans filename ou à défaut, sur la sortie standard (écran)\n");
852                printf (" outoebx       : modname nout liste_pdtI: Utilisation des états initiaux comme d'ebauche\n");
853                printf (" lobs          : [trajname]: liste des observations limitee a trajname si precise\n");
854                printf (" sampleof/i    : modulx infx supx dx moduly infy supy dy outfile: echantillonage de la fonction\n");
855                printf ("                 de cout pour une ou deux variables\n");
856                printf (" nnet          : netname: donne le numero du réseau de neurones netname\n");
857                printf (" lnet          : liste des réseaux de neurones avec certaines informations\n");
858                printf (" netload       : netname filename : chargement du réseau netname avec le fichier filename\n");
859                printf (" setn_activ    : netname activation : choix de la fonction d'activation pour le réseau\n");
860                printf ("                 netname. activaltion=SIGSIG => que sigmoide; avec SIGLIN les sorties\n");
861                printf ("                 sont linéaires\n");
862                printf (" setn_plin     : dmin dmax th: positionne les parametres de la fonction\n");
863                printf ("                 lineair(O_NETWARD)\n");
864                printf (" setn_psig     : mx dmin scale offset: positionne les paramÚtres de la\n");
865                printf ("                 fonction sigmoïde(O_NETWARD)\n");
866                printf (" forward       : nbpdt: effectue une passe avant sur nbpdt pas de temps\n");
867                printf (" backward      : nbpdt: effectue une passe arriÚre sur nbpdt pas de temps\n");
868                printf (" set_nbiter    : val: positionne le nombre d'itérations (YNbIter) à effectuer\n");
869                printf ("                 par les fonctions run\n");
870                printf (" set_nbextl    : val: positionne le nombre de boucles externes (YNbExtL) à effectuer\n");
871                printf ("                 par les algorithmes incrementaux\n");
872                printf (" run           : Lance YNbIter fois l'itération 'de base': passe avant, calcul\n");
873                printf ("                 du cout, passe arriÚre, ajustement des variables\n");
874                printf (" runi          : version incremental de run m avec YNbExtL boucles externes\n");
875                #ifdef YO_M1QN3
876                //pour m1qn3 (a aussi besoin de set_nbiter; le 1er mot se termine par un m)
877                printf ("\n setm_io       : val:                   Ces instructions \n");
878                printf (" setm_impres   : val:                   concernent M1QN3.\n");
879                printf (" setm_mode     : val:                   Il est préférable\n");
880                printf (" setm_nsim     : val:                    de se repporter\n");
881                printf (" setm_dxmin    : [real]:              directement au chapitre\n");
882                printf (" setm_epsg     : real:                  qui le concerne\n");
883                printf (" setm_ddf1     : real:                      dans la\n");
884                printf (" runm et runim :                         documen-\n\n");
885                printf (" runm2 & runim2:                                tation\n\n");
886                #endif
887                //instructions des Modules
888                printf (" setstate      : modname real: affecte la valeur real à tous les états de toutes les\n");
889                printf ("                 occurences (ijkt) du modul modname\n");
890                printf (" setstate_all  : real: affecte la valeur real à tous les états de tous les modules\n");
891                printf (" setepsi       : modname real: affecte la valeur real à tous les epsilons de toutes les\n");
892                printf ("                 occurences (ijk) du modul modname\n");
893                printf (" setepsi_all   : real: affecte la valeur real à tous les epsilons de tous les modules target\n");
894                printf ("-----------------------------------------------------------------------------\n");
895        }
896        else if (lang=='e') /* ................... ANGLAIS ........................*/
897        { printf ("Abreviations:  str: string;  modname: modul name  nstept: number of time step\n");
898          printf ("  (I) (resp (B)): only for Interactive (resp Batch) mode\n");
899          printf ("  nout: n° de out\n");
900          printf ("  val: integer   real: real\n");
901          printf ("  [0 or 1 to choose] {must only one choice}\n");
902                printf ("  both upper or lower case input is availuable but not mixed\n");
903                printf ("---------------------------------------------------------------------------\n");
904                //divers
905                printf ("help | aide|? : [e | f]: ###\n");
906                printf ("exit |quit|bye: to get aways from Yao\n");
907                printf ("!             : str: ### \n");
908                printf ("echo          : {on | off}: ### n");
909                printf ("set_prompt    : str: ### \n");         
910                printf ("pause         : ###\n");
911                printf ("ltraj         : ###\n");
912                printf ("straj         : ###\n");
913                printf ("pdt2pdt       : fromtrajname steptime totrajname: ###\n");
914                printf ("activ|unactiv : {trajname ,typetraj} [{trajname ,typetraj}[...]] [{only, less}]: ###\n");
915                printf ("lspace        : ###\n");
916                printf ("nmod          : modname: ###\n");
917                printf ("lmod          : ###\n");
918                printf ("lval          : ###\n");
919                printf ("load_inst     : file: ###\n");
920                printf ("goto          : label: ###\n");               
921                //pour preparer un run
922    printf ("set_begintime : val: ###\n");
923    printf ("set_modeltime : 0: ###\n");
924    printf ("set_toptime   : trajname val: ###\n");
925    printf ("set_dtime     : trajname val: ###\n");
926    printf ("set_offtime   : trajname val: ###\n");
927                printf ("print_cost    : [on | off | last]: ###\n");
928                printf ("print_time    : [on | off]: ###\n");
929                printf ("cost          : {lms val | appli}: ###\n");
930                printf ("set_scoef     : modname coef: ###\n");
931                printf ("set_bcoef     : modname coef: ###\n");
932                printf ("set_pcoef     : modname coef: ###\n");
933                printf ("adjust        : {std | appli}: ###\n");
934                printf ("testad        : pdx [{-1, tol}] maxcase [zinfo]]: ###\n");
935                printf ("testdf        : i j k codop [%c]pdx ptol: ###\n", '%');
936                printf ("testlt        : pdx alpha fdec nbloop [modop]: ###\n");
937                printf ("testof        : pdx alpha fdec nbloop [modop]: ###\n");                                       
938                printf ("set_iosep       : chaine de caracteres: ###\n");
939                printf ("outoobs       : modname nout liste_pdt: ###\n");
940                printf ("loadobs       : cf paramÚtres dans la doc: ###\n");
941                printf ("loadstate     : cf paramÚtres dans la doc: ###\n");           
942                printf ("savestate     : objname nout oaxis t[%c] {A,B} {0,1,2,3} [filename]: ###\n",'%');
943                printf ("outoebx       : modname nout liste_pdtI: ###\n");             
944                printf ("lobs          : [trajname]:###\n");
945                printf ("sampleof/i    : modulx infx supx dx moduly infy supy dy outfile: ###\n");
946                printf ("nnet          : netname: ###\n");             
947                printf ("lnet          : ###\n");               
948                printf ("netload       : netname filename : ###\n");
949                printf ("setn_activ    : netname activation : ###\n");
950                printf ("setn_plin     : dmin dmax th: ###\n");
951                printf ("setn_psig     : mx dmin scale offset: ###\n");         
952                printf ("forward       : nstept: ###\n");
953                printf ("backward      : nstept: ###\n");
954                printf ("set_nbiter    : val: ###\n");
955                printf ("set_nbextl    : val: ###\n");
956                printf ("run           : ###\n");
957                printf ("runi          : ###\n");
958                #ifdef YO_M1QN3         
959                //pour m1qn3 (also need set_nbiter; first word end letter is m)
960                printf ("setm_io       : val: ###\n");
961                printf ("setm_impres   : val: ###\n");
962                printf ("setm_mode     : val: ###\n");
963                printf ("setm_nsim     : val: ###\n");
964                printf ("setm_dxmin    : [real]: ###\n");
965                printf ("setm_epsg     : real: ###\n");
966                printf ("setm_ddf1     : real: ###\n");
967                printf ("runm et runim : ###\n");
968                printf ("runm2 & runim2: ###\n");
969                #endif                                                 
970                //modul instruction
971                printf ("setstate      : modname real: ###\n");
972                printf ("setstate_all  : real: ###\n");
973                printf ("setepsi       : modname real: ###\n");
974                printf ("setepsi_all   : real: ###\n");
975                printf ("-----------------------------------------------------------------------------\n");
976        }
977        printf("\n");
978}
979
980/* ----------------------------------------------------------------------------
981//=========== appelle d'une fonction sous la forme argc argv =============== */
982//                   avec constitution des arguments
983int Yfarg(int(*fct)(int argc, char *argv[]), char *args)
984{  int  cdesc;
985   char *cdes[NB_MAX_ARG_CDE];
986   char cdeline[BUFSIZE+1];
987
988         strcpy(cdeline, args);
989         if (!Yrecup_cde (&cdesc, cdeline, cdes))
990                                return(0);
991         return(fct(cdesc, cdes));
992}
993/* ----------------------------------------------------------------------------
994//================ Indice d'une definition dans YTabDefval ================= */
995int Yisdefval(char *name)
996{       int     wi;
997        for (wi=0; wi<YNBDEFVAL; ++wi)
998        {       if (strcmp(name, YTabDefval[wi].Name) == 0)
999                         return (wi);
1000        }
1001        return(-1);
1002}
1003/*----------------------- liste des valeurs définies ------------------------*/
1004void Ylval()
1005{
1006        printf (" |  N° |     nom      |  valeur  | \n");     
1007        for (int w1=0; w1<YNBDEFVAL; ++w1)
1008                  printf (" | %3i | %-12s | %8s |\n", w1+1,
1009                                                  YTabDefval[w1].Name, YTabDefval[w1].macro);
1010  printf("\n");
1011}
1012/* ----------------------------------------------------------------------------
1013//=============== Valorisation du tableau Yting pour testdf ================ */
1014void Ysetting(char *codop)
1015{
1016        double val;
1017        if      (codop[0]=='N') /* input value = input indice */
1018        {        for(int wi=0; wi<YMAX_NBI; ++wi) Yting[wi]=wi+1;
1019        }       
1020        else if (codop[0]=='r') /* rand in [0, 1] */
1021        {        for(int wi=0; wi<YMAX_NBI; ++wi) Yting[wi]=(double)rand()/RAND_MAX;
1022        }       
1023        else if (codop[0]=='R') /* rand in [-1, 1] */
1024        {        for(int wi=0; wi<YMAX_NBI; ++wi) Yting[wi]=((double)rand()/RAND_MAX)*2 -1;
1025        }
1026        else if ( codop[0]=='F' || codop[0]=='f')
1027        {/*nb codop=='F' used for dfward: see testdf in Yao8.c (so don't use it here)*/
1028        }
1029        else if (codop[0]=='U')
1030        {/* the User must it-self feel Yting before calling testdf */
1031        }       
1032        else /* otherwise we considere it is a real */
1033        {   val = atof(codop);
1034                        for(int wi=0; wi<YMAX_NBI; ++wi) Yting[wi]=val;
1035        }
1036}
1037
1038/* ----------------------------------------------------------------------------
1039//=============== test de l'erreur sur l'adjoint par module ================ */
1040int Ytesterrad_mod(char *nmmod, double YLTRes, double YAdRes)
1041{       double errel;
1042
1043        /* max case demanded deja atteind */
1044        if (Ynbko>=Ymaxko) return(0);
1045       
1046        /* cas de valeurs proches d'un zero informatique ... ->ok !? */
1047        if (Yerrelmax!=-1)
1048         if (fabs(YLTRes)<=Ypzedi  && fabs(YAdRes)<=Ypzedi)
1049            return(1);
1050
1051        /* autres cas, on calcul et on test l'erreur relative */
1052        errel = (YLTRes-YAdRes)/YLTRes;
1053        if (fabs(errel)>=Yerrelmax || Yerrelmax<0.0)   
1054        {  printf (" %8s(%i %i %i; %i)  % 23.15e - % 23.15e = % -23.15e  relerr=% 21.15e\n",
1055                            nmmod, Yi+1, Yj+1, Yk+1, Yt+1, YLTRes, YAdRes, YLTRes-YAdRes, errel);
1056           ++Ynbko;
1057           //if (Ynbko>=Ymaxko) return(0);
1058        }
1059        return(1);
1060}
1061
1062/* ----------------------------------------------------------------------------
1063//======================== Fonction pour le deboggage ====================== */
1064void Ydbg_nanf(char *str, int nbi, char *nmmod)
1065{
1066        for (int wi=0; wi<nbi; ++wi)
1067        {
1068                if (finite((double)Yting[wi]) == 0)
1069                { printf("dbg: %s %s[%i]: (%i %i %i : %i) : NaN or Inf found for Yting !!!=> exit process\n",
1070                               str, nmmod, wi+1,  Yi+1, Yj+1, Yk+1, Yt+1);
1071          exit(0);
1072                }
1073                if (finite((double)Ytbeta[wi]) == 0)
1074                { printf("dbg: %s %s[%i]: (%i %i %i : %i) : NaN or Inf found for Ytbeta !!!=> exit process\n",
1075                                                             str, nmmod, wi+1,  Yi+1, Yj+1, Yk+1, Yt+1);
1076          exit(0);
1077                }
1078        }
1079}
1080/* ------------------------------------------------------------------------- */
1081void Ydbg_ting(char *str, int nbi, char *nmmod)
1082{
1083   printf ("dbg: %s module %s : (%i %i %i ; %i) \n", str, nmmod, Yi+1, Yj+1, Yk+1, Yt+1);
1084         for (int wi=0; wi<nbi; ++wi)
1085         {   printf("dbg:  input [%i]: => %e \n", wi+1,  Yting[wi]);
1086         }
1087}
1088void Ydbg_ting_wrk(char *str, int nbi, char *nmmod)
1089{       if(!strcmp(str, "F: ")) return;
1090        if (Yt!=1) return;
1091             printf ("dbg: %s module %s : (%i %i %i ; %i) \n", str, nmmod, Yi+1, Yj+1, Yk+1, Yt+1);
1092         for (int wi=0; wi<nbi; ++wi)
1093         {   printf("dbg:  input [%i]: => %22.16e \n", wi+1,  Yting[wi]);
1094         }
1095}
1096/* --------------------------------------------------------------------------*/
1097void Ydbg_beta(char *str, int nbi, char *nmmod)
1098{                        printf ("dbg: %s module %s : (%i %i %i ; %i) \n", str, nmmod, Yi+1, Yj+1, Yk+1, Yt+1);
1099         for (int wi=0; wi<nbi; ++wi)
1100         {   printf("dbg:   grad [%i]: => %e \n", wi+1, Ytbeta[wi]);
1101         }
1102}
1103
1104//============================= trajectoire : ...  ==========================*/
1105void Ydispcurstep(int itraj)  /* not realy used because not practical */
1106{ /* pour voir la progression des trajectoires.
1107     echelle de tps non respectee si dt n'est pas entier ! */
1108  int   i, j;
1109  float wtime;
1110        float startime;
1111        printf ("   |");
1112  wtime = Ybegintime;
1113        startime = Ybegintime + YTabTraj[itraj].offtime;
1114        while (wtime < startime)
1115        { printf(" "); ++wtime;
1116        }
1117        while (wtime < YTabTraj[itraj].curtime)
1118        {       for (i=0; i<YTabTraj[itraj].dtime; ++i) printf(" ");
1119    wtime += YTabTraj[itraj].dtime;
1120        }
1121        if (wtime < YTabTraj[itraj].stoptime)
1122        {       for (j=1; j<YTabTraj[itraj].dtime; ++j) printf("_");
1123          printf(".");
1124        }
1125        printf("\n");
1126}
1127/*-------------------------*/
1128void Ystraj()
1129{ int   i, j;
1130  float wtime;
1131  float startime;
1132        printf("\n\n            representation graphique des trajectoires\n");
1133        printf("attention, echelle de temps non respectée si dt et offt ne sont pas entiers !\n\n");
1134
1135        for (i=0; i<YNBTRAJ;++i)
1136        {   printf(" %8s:  |", YTabTraj[i].name);
1137            wtime = Ybegintime;
1138                        startime = Ybegintime + YTabTraj[i].offtime;
1139            while (wtime < startime)
1140            { printf(" "); ++wtime;
1141                        }
1142            while (wtime < YTabTraj[i].stoptime)
1143                        { for (j=1; j<YTabTraj[i].dtime; ++j) printf("_");
1144                          printf(".");
1145                                wtime += YTabTraj[i].dtime;
1146                        }
1147                        printf("|\n\n");
1148        }
1149}
1150
1151//============== trajectoire : repositionnement sur le modele ===============*/
1152int Yset_modeltime (int time)  //PLM, je ne traite que le repositionnement au debut du modele !!! (ARAR)
1153{  int wi;
1154         for (wi=0; wi<YNBTRAJ; ++wi)
1155         {       YTabTraj[wi].toptime = YTabTraj[wi].nbuptime;
1156                         YTabTraj[wi].curtime = Ybegintime + YTabTraj[wi].offtime;
1157   }
1158   return(0);
1159}
1160//=================== trajectoire : recalcule de curtime ====================*/
1161int Yupdcurtime(int itraj)
1162{
1163        if (itraj<0 || itraj >= YNBTRAJ) return(-1);
1164        YTabTraj[itraj].curtime = Ybegintime + YTabTraj[itraj].offtime
1165                                + (YTabTraj[itraj].toptime - YTabTraj[itraj].nbuptime)
1166                                  * YTabTraj[itraj].dtime;
1167        return(0);
1168}
1169/*=================== trajectoire : recalcule de stoptime ===================*/
1170int Yupdstoptime(int itraj)
1171{
1172        if (itraj<0 || itraj >= YNBTRAJ) return(-1);
1173        YTabTraj[itraj].stoptime = Ybegintime + YTabTraj[itraj].offtime
1174                                + YTabTraj[itraj].dtime * YTabTraj[itraj].nbsteptime;
1175        return(0);
1176}
1177/*============ Indice Trajectoire dans tableau des trajectoires =============*/
1178int Yitraj(char *nmtraj)
1179{
1180  for (int w1=0; w1<YNBTRAJ; ++w1)
1181                if (strcmp(YTabTraj[w1].name, nmtraj) == 0)
1182                                return (w1);
1183        return(-1);     
1184}
1185/*---------------------------------------------
1186int Yitrajimod(int imod)
1187{return(Yitraj(YTabSpace[Yispace(YTabMod[imod].space_name)].traj_name));
1188} cf v */
1189/*---------------------------------------------*/
1190int Ypdt2pdt (int wxtraj, int topy, int wytraj)
1191{   /* ATTENTION: cette fonction doit etre en phase
1192       avec celle, de meme nom, qui est dans Yao8.c */
1193    float offy, offx, dty, dtx;
1194    int   topx, upty, uptx;
1195
1196    offy = YTabTraj[wytraj].offtime;
1197    offx = YTabTraj[wxtraj].offtime;
1198    dty  = YTabTraj[wytraj].dtime;
1199    dtx  = YTabTraj[wxtraj].dtime;
1200    upty = YTabTraj[wytraj].nbuptime;
1201    uptx = YTabTraj[wxtraj].nbuptime;
1202
1203    topx = (int)( (offy + (topy-upty)*dty - dty - offx) / dtx ) + uptx + 1;
1204    return(topx);
1205}
1206/*---------------------------------------------*/
1207int Ytttt_pdt (int wxtraj, int topy, int wytraj)
1208{ /* traduction du temps d'une trajectoire a l'autre mais en considerant
1209     cette fois qu'on travaille avec des indices C et qu'on borne
1210     le resultat au temps de la trajectoire */
1211   int  topx;
1212   topx = Ypdt2pdt(wxtraj, topy+1, wytraj) - 1;
1213   if (topx < 0) topx = 0;
1214   else if (topx >= YTabTraj[wxtraj].nbuptime + YTabTraj[wxtraj].nbsteptime)
1215      topx = YTabTraj[wxtraj].nbuptime + YTabTraj[wxtraj].nbsteptime - 1;
1216     
1217   return(topx);
1218}
1219/*==================== liste du tableau des trajectoires ====================*/
1220void Yltraj()
1221{
1222        printf (" |  id | traj name type| upt.  offt.    dt    curt.  topt. nbstept.  stopt. act| \n"); 
1223        for (int w1=0; w1<YNBTRAJ; ++w1)
1224                  printf (" | %3i | %-10s  %c | %2i   %6.3f %6.3f  %6.3f  %2i      %2i     %6.3f   %1i |\n",
1225                          w1+1,
1226                                                  YTabTraj[w1].name,
1227                                                  YTabTraj[w1].type,
1228                                                  YTabTraj[w1].nbuptime,
1229                                                  YTabTraj[w1].offtime,
1230                                                  YTabTraj[w1].dtime,
1231                                                  YTabTraj[w1].curtime,
1232                                                  YTabTraj[w1].toptime,
1233                                                  YTabTraj[w1].nbsteptime,
1234                                                  YTabTraj[w1].stoptime,
1235                                                  YTabTraj[w1].isactiv
1236                                                 );
1237  printf("\n");
1238}
1239
1240/*================ activation ou desactivation de trajectoire ===============*/
1241//syntax : {activ, unactiv} {trajname ,typetraj} [{trajname ,typetraj}[...]] [only]
1242//exemple: active Traj1 M Q Traj7 R only
1243int Yisa_typetraj(char typetraj)
1244{   int w1;
1245    for (w1=0; w1<YNBTRAJ; ++w1)
1246                  if (YTabTraj[w1].type == typetraj)
1247                                 return (1);
1248          return(0);
1249}
1250/*---------------------------------------------*/
1251int Yactraj(int cdesc, char *cdes[])
1252{
1253    int w1, w2; int only=0; int less=0; int activ=0;
1254    if (strcmp(cdes[0], "activ")==0 || strcmp(cdes[0], "ACTIV")== 0)
1255       activ=1;
1256
1257          /* verif trajname et/ou typetraj existe */
1258          for (w1=1; w1<cdesc; ++w1)
1259          { if (strlen(cdes[w1])==1) //un caractere => doit etre un type de trajectoire
1260            {  if (!Yisa_typetraj(cdes[w1][0]))
1261               {  printf("(un)activ: trajectory type (%c) does not exist\n", cdes[w1][0]);
1262                              return(0);
1263               }
1264            }
1265            else if (strcmp(cdes[w1], "ONLY") == 0 || strcmp(cdes[w1], "only") == 0)
1266            {  //only ou less doit etre le dernier token
1267               if (w1 != cdesc-1)
1268               {  printf("(un)activ: \"only\" must be the last token\n");
1269                              return(0);
1270               }
1271               only=1;
1272            }
1273            else if (strcmp(cdes[w1], "LESS") == 0 || strcmp(cdes[w1], "less") == 0)
1274            {  //only ou less doit etre le dernier token
1275               if (w1 != cdesc-1)
1276               {  printf("(un)activ: \"less\" must be the last token\n");
1277                              return(0);
1278               }
1279               less=1;
1280            }
1281           
1282            else
1283            {  //ce doit etre le nom d'une trajectoire
1284                                 if (Yitraj(cdes[w1])<0)
1285                     {   printf("(un)activ: unknwon trajectory name (%s) \n", cdes[w1]);
1286                               return(0);
1287                     }
1288            }
1289          }
1290
1291          //----------------------------------
1292          if (only) /* si only est utilised */
1293          {  for (w1=0; w1<YNBTRAJ; ++w1)
1294             {   if (activ) YTabTraj[w1].isactiv = 0; //pour activ on commence par tout desactiver
1295                 else if (YTabTraj[w1].fward != NULL) //pour unactiv, on commence par tout activer
1296                         YTabTraj[w1].isactiv = 1;    //sauf les traj non operationnelle
1297             }
1298          }
1299          else if (less) /* si less est utilised */
1300          {  for (w1=0; w1<YNBTRAJ; ++w1)
1301             {   if (!activ) YTabTraj[w1].isactiv = 0; //pour unactiv on commence par tout desactive
1302                                         else if (YTabTraj[w1].fward != NULL)  //pour active on commence par tout activer sauf les traj non operationnelle
1303                         YTabTraj[w1].isactiv = 1;
1304             }
1305          }
1306
1307          //----------------------------------
1308          /* puis on va activer ou desactiver selon chaque token */
1309          for (w1=1; w1<cdesc; ++w1)
1310          {   if (strcmp(cdes[w1], "ONLY") == 0 || strcmp(cdes[w1], "only") == 0
1311              ||  strcmp(cdes[w1], "LESS") == 0 || strcmp(cdes[w1], "less") == 0)
1312                 break;
1313              for (w2=0; w2<YNBTRAJ; ++w2)
1314              {   if (  strcmp(cdes[w1], YTabTraj[w2].name)==0
1315                  ||   (strlen(cdes[w1])==1 && cdes[w1][0]==YTabTraj[w2].type)
1316                     )
1317                  {  /* on ne touche pas aux trajectoires non oprationnelles */
1318                     if (YTabTraj[w2].fward == NULL)
1319                        continue;
1320                     if (activ) //pour activ on active sauf si less
1321                     {  if (less) YTabTraj[w2].isactiv = 0;
1322                                else YTabTraj[w2].isactiv = 1;
1323                     }
1324                     else //pour unactiv, on desactive sauf si less
1325                                                         {  if (less) YTabTraj[w2].isactiv = 1;
1326                                else YTabTraj[w2].isactiv = 0;
1327                     }               
1328                                                }             
1329              }
1330          }
1331
1332          return(1);
1333}
1334
1335/*======================= liste du tableau des espaces ======================*/
1336void Ylspace()
1337{
1338        printf (" |  id | space name type | axi axj axk | traj name | \n");     
1339        for (int w1=0; w1<YNBSPACE; ++w1)
1340                  printf (" | %3i |  %-10s  %c  | %3i %3i %3i | %-10s|\n", w1+1,
1341                                                  YTabSpace[w1].name, YTabSpace[w1].type,
1342                                                  YTabSpace[w1].axi, YTabSpace[w1].axj, YTabSpace[w1].axk,
1343                                                  YTabSpace[w1].traj_name);
1344  printf("\n");
1345}
1346/*============== Indice espace dans tableau des espaces =====================*/
1347int Yispace(char *nmspace)
1348{
1349  for (int w1=0; w1<YNBSPACE; ++w1)
1350                if (strcmp(YTabSpace[w1].name, nmspace) == 0)
1351                                return (w1);
1352        return(-1);
1353}
1354/*---------------------------------------------*/
1355int Yispaceimod(int imod) //!?
1356{return(Yispace(YTabMod[imod].space_name));
1357} //!?
1358
1359
1360/*======================= liste du tableau des operateurs ===================*/
1361void Ylopera()
1362{ printf (" |  id | opera name type | axi axj axk | traj name | act | \n");
1363        for (int w1=0; w1<YNBOPERA; ++w1)
1364                  printf (" | %3i |  %-10s  %c  | %3i %3i %3i | %-10s|  %1i  |\n", w1+1,
1365                                                  YTabOpera[w1].name, YTabOpera[w1].type,
1366                                                  YTabOpera[w1].axi, YTabOpera[w1].axj, YTabOpera[w1].axk,
1367                                                  YTabOpera[w1].traj_name, YTabOpera[w1].isactiv);
1368  printf("\n");
1369}
1370/* ---------------- indice operateur dans tableau des operateurs ------------*/
1371int Yiopera(char *nmopera)
1372{ for (int w1=0; w1<YNBOPERA; ++w1)
1373                if (strcmp(YTabOpera[w1].name, nmopera) == 0)
1374                                return (w1);
1375        return(-1);
1376}
1377/*----------------- activation/desactivation d'operateurs -------------------*/
1378void Yact_operator(char type, short etat)
1379{ int w1;
1380  for (w1=0; w1<YNBOPERA; ++w1)
1381    if (YTabOpera[w1].type==type || type=='*') YTabOpera[w1].isactiv=etat;
1382}
1383/*---------------------------------------------*/
1384int Yioperaimod(int imod) //!?
1385{return(Yiopera(YTabMod[imod].space_name));
1386} //!?
1387
1388/*======================= Indice du tableau des operateurs ===================*/
1389int Yitrajimod(int imod)
1390{   //renvoie l'indice de la trajectoire a laquelle le
1391    //module est rattached via un espace ou un operateur
1392    int w1;
1393    if      ( (w1=Yioperaimod(imod)) >=0)
1394       return(Yitraj(YTabOpera[w1].traj_name));
1395    else if ( (w1=Yispaceimod(imod)) >=0)
1396       return(Yitraj(YTabSpace[w1].traj_name));   
1397    else
1398    {  //unpossible case
1399       printf ("Ysys error #1\n"); return(-9);
1400    }
1401}
1402/* ----------------------------------------------------------------------------
1403//================= Indice Module dans tableau des modules ================= */
1404int Yimod(char *nmmod)
1405{ for (int w1=0; w1<YNBMODUL; ++w1)
1406                if (strcmp(YTabMod[w1].Name, nmmod) == 0)
1407                                return (w1);
1408        return(-1);     
1409}
1410/*================ print la liste du tableau des modules =================== */
1411void Ylmod(int argc, char *argv[])
1412{  int all = 1; int target = 0; int cout = 0;
1413   /* entete */
1414   //printf (" | id | nbi nbs | dim | axi axj axk | nbt | C T O |    scoef      bcoef      pcoef   | name / space\n");
1415         printf (" | id | nbi nbs | dim | axi axj axk | nbt | C  T deb end |    scoef      bcoef      pcoef   | name / space\n");
1416
1417         /* positionnement de flag pour savoir ce qu'on doit printer */
1418         for(int wi=1; wi<argc; ++wi)
1419         {  if (!strcmp(argv[wi], "target") || !strcmp(argv[wi], "TARGET") ) {all=0; target=1;}
1420            if (!strcmp(argv[wi], "cout")   || !strcmp(argv[wi], "COUT") )   {all=0; cout=1;}
1421         }
1422
1423         /* boucle sur les modules pour l'affichage */
1424         for (int w1=0; w1<YNBMODUL; ++w1)
1425         {
1426       if( all || (target==1 && YTabMod[w1].is_target) || (cout==1 && YTabMod[w1].is_cout) )
1427                         {  //printf (" |%3i | %3i %3i | %3i | %3i %3i %3i |%4i | %1i %1i %1i | %5.4e %5.4e %5.4e | %s / %s\n", w1+1,
1428                printf (" |%3i | %3i %3i | %3i | %3i %3i %3i |%4i | %1i  %1i%3i %3i  | %5.4e %5.4e %5.4e | %s / %s\n", w1+1,
1429                                                   YTabMod[w1].nb_input, YTabMod[w1].nb_stout, YTabMod[w1].dim,
1430                                                   YTabMod[w1].axi, YTabMod[w1].axj, YTabMod[w1].axk, YTabMod[w1].nb_time,
1431                                                   YTabMod[w1].is_cout, YTabMod[w1].is_target, YTabMod[w1].deb_target, YTabMod[w1].end_target,
1432                                                   YTabMod[w1].scoef, YTabMod[w1].bcoef, YTabMod[w1].pcoef, YTabMod[w1].Name, YTabMod[w1].space_name);
1433                                                         //YTabMod[w1].ctrord,
1434                         }
1435         }
1436   printf("\n");
1437}
1438/*=================== liste association module/operateur =================== */
1439void Ylmocop()
1440{  int w1, w2;
1441   printf (" ----- association list moduls/operators -----\n");
1442         for (w1=0; w1<YNBMODUL; ++w1)
1443         {   if (YTabMocop[w1][0] != -1) //y'a au moins un operateur associed
1444                   {  printf ("%s: ", YTabMod[w1].Name);
1445                      w2=0;
1446                      while (w2<YNBOPERA && YTabMocop[w1][w2]!=-1)
1447                      {   printf("%8s ", YTabOpera[YTabMocop[w1][w2]].name);
1448                          ++w2;
1449                      }
1450                      printf("\n");
1451                   }
1452         }
1453         printf("\n");
1454}
1455/* ----------------------------------------------------------------------------
1456//================ Indice Reseaux dans tableau des Resaux ================== */
1457#ifdef YO_NETWARD
1458int Yinet(char *nmnet)
1459{
1460        for (int w1=0; w1<YNBNET; ++w1)
1461                if (strcmp(YTabNet[w1].Name, nmnet) == 0)
1462                                return (w1);
1463        return(-1);
1464}
1465//================ print la liste du tableau des reseaux =================== */
1466void Ylnet ()
1467{
1468        char activ[10];
1469        printf (" | ind |    nom   | nbw  | nbin | nbout | maxcell |  tweight  | factiv |\n"); 
1470        for (int w1=0; w1<YNBNET; ++w1)
1471        {      if (YTabNet[w1].activ==SigLin) sprintf(activ,"siglin");
1472                else if (YTabNet[w1].activ==SigSig) sprintf(activ,"sigsig");
1473                else sprintf(activ,"unknown!?");
1474                printf (" | %3i | %8s | %3i  | %3i  |  %3i  |   %3i   | %9p | %s |\n", w1+1,
1475                                                YTabNet[w1].Name, YTabNet[w1].nbweight,
1476                                                YTabNet[w1].nbinput, YTabNet[w1].nboutput, YTabNet[w1].maxcell,
1477                                                YTabNet[w1].tweight, activ);
1478        }
1479}
1480#endif
1481/* ----------------------------------------------------------------------------
1482//======== positionnement des indices de parcourt des axes de l'espace ===== */
1483int YsetPaxe(int dim, char *oaxis, int  axe1, int  axe2, int axe3,
1484                                                                                                                                         int *axo1, int *axo2, int *axo3)
1485{
1486        if (dim==3)
1487        {
1488                        if      (strcmp(oaxis, "ijk") == 0 || strcmp(oaxis, "IJK") == 0)
1489                        {        *axo1=axe1; *axo2=axe2; *axo3=axe3;}
1490                        else if (strcmp(oaxis, "ikj") == 0 || strcmp(oaxis, "IKJ") == 0)
1491                        {        *axo1=axe1; *axo2=axe3; *axo3=axe2;}                   
1492                        else if (strcmp(oaxis, "jik") == 0 || strcmp(oaxis, "JIK") == 0)
1493                        {        *axo1=axe2; *axo2=axe1; *axo3=axe3;}                   
1494                        else if (strcmp(oaxis, "jki") == 0 || strcmp(oaxis, "JKI") == 0)
1495                        {        *axo1=axe2; *axo2=axe3; *axo3=axe1;}                   
1496                        else if (strcmp(oaxis, "kij") == 0 || strcmp(oaxis, "KIJ") == 0)
1497                        {        *axo1=axe3; *axo2=axe1; *axo3=axe2;}                   
1498                        else if (strcmp(oaxis, "kji") == 0 || strcmp(oaxis, "KJI") == 0)
1499                        {        *axo1=axe3; *axo2=axe2; *axo3=axe1;}
1500                        else
1501                                 return(0);
1502                        /* default when error : {*axo1=axe1; *axo2=axe2; *axo3=axe3;}   */
1503        }
1504        else if (dim==2)
1505        {
1506                        if      (strcmp(oaxis, "ij") == 0 || strcmp(oaxis, "IJ") == 0)
1507                        {        *axo1=axe1; *axo2=axe2;}
1508                        else if (strcmp(oaxis, "ji") == 0 || strcmp(oaxis, "JI") == 0)
1509                        {        *axo1=axe2; *axo2=axe1;}
1510                        else if (strcmp(oaxis, "ik") == 0 || strcmp(oaxis, "IK") == 0)
1511                        {        *axo1=axe1; *axo2=axe3;}
1512                        else if (strcmp(oaxis, "ki") == 0 || strcmp(oaxis, "KI") == 0)
1513                        {        *axo1=axe3; *axo2=axe1;}
1514                        else if (strcmp(oaxis, "jk") == 0 || strcmp(oaxis, "JK") == 0)
1515                        {        *axo1=axe2; *axo2=axe3;}
1516                        else if (strcmp(oaxis, "kj") == 0 || strcmp(oaxis, "KJ") == 0)
1517                        {        *axo1=axe3; *axo2=axe2;}                       
1518                        else
1519                                 return(0);
1520        }
1521        else    /* ...(dim==1) */
1522        {
1523                                if    (strcmp(oaxis, "i") == 0 || strcmp(oaxis, "I") == 0)
1524                        {        *axo1=axe1;}
1525                        else if (strcmp(oaxis, "j") == 0 || strcmp(oaxis, "J") == 0)
1526                        {        *axo1=axe2;}
1527                        else if (strcmp(oaxis, "k") == 0 || strcmp(oaxis, "K") == 0)
1528                        {        *axo1=axe3;}
1529                        else
1530                                 return(0);
1531        }
1532        return(1);
1533}
1534
1535
1536/*---------------------------------------------------------------------------*/
1537/* gestion des entrees - sorties et des observations pour Yao  :                                                 */
1538#include "Dyniob.h"
1539/*---------------------------------------------------------------------------*/
1540
1541
1542/* ----------------------------------------------------------------------------
1543//============================ FONCTIONS DE COUT =========================== */
1544void Ycost()  //TRobs, YNBUPTIME, YidTraj, YTemps doivent etre posisionned
1545{   long        curtop;
1546
1547                if (TRobs==NULL) return;
1548
1549                Ytrupdt = TRobs->iind;                                                                                  /* true pdt : temps initiaux et trajectoire*/
1550                if (Ytrupdt<0) Ytrupdt = -TRobs->iind-1;    /* true pdt : cas ebauches  */
1551
1552                Yact_operator('*', OFF);      /* on desactive tous les operateurs */
1553
1554    /* traitement OPERATEURS HHHHH */
1555                YCaseCost = WISHL2_NANACT;    /* pour WISH: ca mettra NAN (niveau module) */
1556                Ycobs_TR(TRobs->fils);                    /* puis ca active les operateurs associed au module (H, R, ...) */
1557
1558    Yforward_operator('H');               /* forward de tous les operateurs 'H' qui auront ete actived :M(x)->YS */
1559
1560    if (YAL2Run==RUNL2_STD)       /* cas d'un run standard */
1561    {  /* DIFFERENCE [H(M(x)) - Yo] : Ywish=Ystate-Obs */
1562                   YCaseCost = WISHL2_DIFF;      /* puis, avec ce flag, on va faire la difference sur la        */
1563                   Ycobs_TR(TRobs->fils);                          /* zone WISH (Ywish=Ystate-Obs) (uniquement la ou y'a des obs) */
1564    }
1565#ifdef YO_VARINCR
1566                else if(YAL2Run==RUNL2_INCR)  /* cas d'un run incremental */
1567    {  //Ylinward_operator('H');       /* pour pousser le calculer du lineaire tangent sur H: H'M'(x)dx ->YG  */
1568                   //YCaseCost = WISHL2_QTEA;      /* puis, avec ce flag, on va calculer l'ex qtea directement dans Ywish */
1569                   //Ycobs_TR(TRobs->fils);                        /* (qtea)=Ywish  =  YG - (Y° - YS)  =  H'M'(Xk).dx - (y° - H(M(Xk))     */
1570       //qtea a deja ete valorised par Ylinward_flopobs
1571       //on projete simplement YS->YW
1572                   YCaseCost = WISHL2_QTEA;     /* puis, avec ce flag, on va  projeter la  zone qtea dans la     */
1573                   Ycobs_TR(TRobs->fils);                          /* zone WISH (Ywish=qtea = YG - (Y° -YS)  =  H'M'(Xk).dx - (y° - H(M(Xk)) (uniquement la ou y'a des obs) */
1574    }
1575#endif
1576       
1577    /* traitement OPERATEURS de covariance ('B' ou/et 'R', ou/et 'K') */
1578   if (TRobs->iind < 0) /* sur la partie ebauche */
1579                  Yforward_operator('B');  /* lance tous les operateurs 'B' qui auront ete actived */
1580         else                                                                   /* sur la trajectoire */
1581                        Yforward_operator('R');  /* lance tous les operateurs 'R' qui auront ete actived */
1582         Yforward_operator('K');     /* ebauche et traj : lance tous les operateurs 'K' qui auront ete actived */
1583
1584          /* Calcul cout et gradient avec les zones Ywish en se rappelant que maintenant Ywish=Ystate-Obs
1585             (ou dans le cas de l'incremental Ywish=Ystate+Ygrad-Obs):
1586             mais eventuellement aussi avec les zones Ystate lorsqu'il y a un operateur 'R' */
1587    if (YAL2Run==RUNL2_STD)       /* cas d'un run standard */
1588    {  YCaseCost = COSTL2_WISHDIFF;  /* puis avec ce flag */
1589                   Ycobs_TR(TRobs->fils);                    /* on calcule : grad = costdiff(YW, YW||YS=COV(YW))   */
1590    }                                /* grad = coef*Ywish, et cout = coef*Ywish*COV(Ywish) */
1591#ifdef YO_VARINCR
1592                else if(YAL2Run==RUNL2_INCR)  /* cas d'un run incremental */
1593    {  YCaseCost = COSTL2_WISHQTEA;  /* puis avec ce flag */
1594                   Ycobs_TR(TRobs->fils);                    /* on calcule : grad = costdiff(qtea, YW||YS=COV(YW)  */
1595    }                                                                                                                            /* grad = coef*qtea, et cout = coef*Yqtea*COV(Ywish) */
1596#endif
1597
1598                /* Retropropagation operateurs H actived */
1599                Ybackward_operator('H');
1600               
1601    /* affichage du cout if required */
1602          if (YDispCost==ON)
1603                {        curtop = time((time_t *)NULL);
1604                         if (TRobs->iind < 0)  /* partie ebauche*/
1605                         {  printf(" >>> Yiter %-3ld traj %-8s pdE=%i after %lds: Total cost = % -23.15e\n",
1606                                                     YItRun, YTabTraj[YidTraj].name, -TRobs->iind, curtop-Ytop0, YTotalCost);
1607                         }
1608                         else if(TRobs->iind < YNBUPTIME)       /* partie temps initiaux */
1609                         {  printf(" >>> Yiter %-3ld traj %-8s pdI=%i after %lds: Total cost = % -23.15e\n",
1610                                                     YItRun, YTabTraj[YidTraj].name, TRobs->iind+1, curtop-Ytop0, YTotalCost);
1611                         }
1612                         else
1613                   {  printf(" >>> Yiter %-3ld traj %-8s pdt=%i after %lds: Total cost = % -23.15e\n",
1614                                                           YItRun, YTabTraj[YidTraj].name, YTemps+1, curtop-Ytop0, YTotalCost);
1615                   }
1616                }
1617               
1618                /* pour avancer sur cette liste des temps */
1619                TRobs = TRobs->frere;
1620}
1621/*---------------------------------------------------------------------------*/
1622/* ---------- cout sur terme d'ebauche et observations initiales  -----------*/
1623void Ycostebx()
1624{
1625        for (YidTraj=0; YidTraj<YNBTRAJ; ++YidTraj)
1626        {   TRobs = YTabTraj[YidTraj].TRobs;
1627            YNBUPTIME = YTabTraj[YidTraj].nbuptime;
1628      //while (TRobs!=NULL)
1629      while (TRobs != NULL  && TRobs->iind < YNBUPTIME)
1630            {   //printf("costebx: traj=%i Yt=%i \n", YidTraj, YTemps);
1631                if (TRobs->iind >= 0)         // partie temps initiaux
1632                                                 YTemps = TRobs->iind;
1633                                        else                                                                                            // partie ebauche
1634                                                 YTemps = -TRobs->iind-1;
1635
1636                Ycost();
1637            }
1638                        YTabTraj[YidTraj].TRobs = TRobs; //est-ce bien utile ?
1639        }
1640}
1641/* ----------------------------------------------------------------------------
1642//======================== FONCTIONS D'AJUSTEMENT ========================== */
1643void Yadjust()
1644{
1645          if (YTypeAdjust == ADJUST_APPLI)
1646                         adjust_target ();
1647          else if (YTypeAdjust == ADJUST_STD) /* default */
1648             Yadjust_all ();
1649}
1650/*memo: for a kind of temperature
1651float                   epsi_fact;
1652epsi_fact = 0.0; //1.0; //0.02;
1653YS1_Ke(0)               -= ( Epsi_Ke    * pow(1-epsi_fact, YItRun) ) * YG1_Ke(0);
1654*/
1655/* ----------------------------------------------------------------------------*/
1656#ifdef YO_VARINCR
1657void Yc_adjustd()               /* cas de l'incremental: ajustement dx dans la boucle interne */
1658{          if (YTypeAdjust == ADJUST_APPLI)
1659                          adjust_target ();     /* nb: le user peut tester les flags pour savoir dans quel cas il est */
1660           else if (YTypeAdjust == ADJUST_STD) /* default */
1661              Yc_adjustd_all ();
1662}
1663#endif
1664
1665
1666/* ----------------------------------------------------------------------------
1667//============================= FONCTION FORWARD =========================== */
1668int Yforward_elect()
1669{   int wi;
1670    int candidat = -1;
1671    float wtime = MYMAXREEL; //DBL_MAX; //999999;
1672
1673    for (wi=0; wi<YNBTRAJ; ++wi)                                                                //dans l'ordre des declaration
1674    {   if (YTabTraj[wi].curtime < wtime                                //qui est la + en retard
1675        &&  YTabTraj[wi].toptime < YTabTraj[wi].nbuptime + YTabTraj[wi].nbsteptime      //qui n'est pas en bout de course
1676        &&  YTabTraj[wi].isactiv                                                                // qui est active
1677      //&&  YTabTraj[wi].curtime < Ystoptime  ...!?   ARAR
1678      //&&  YTabTraj[wi].curtime < Yendtime   ...!?   ARAR
1679           )
1680        {  candidat = wi;
1681           wtime = YTabTraj[wi].curtime;
1682        }
1683    }
1684    return(candidat);
1685}
1686/*---------------------------------------------------------------------------*/
1687int Yforward(int itraj, int topstop)
1688{  int itrajelue; int nbcall=0;
1689         /* passe avant sur l'ensemble du modele global (i.e. sur ttes les trajectoires )
1690            de la ou on est positionned ! jusqu'a : 2 cas :
1691              si itraj = -1: on ira jusqu'a la fin du modele (et topstop ne sert pas)
1692              sinon, on s'arrete des que le toptime de la trajectoire passed en parametre
1693                     (qui sert donc de reference) a atteint le topstop (non inclus: i.e. on s'arrete avant) */
1694
1695                while ((itrajelue=Yforward_elect()) >= 0)  // le while controle la progression
1696                {   //ici, on n'avance QUE d'UN PDT sur la trajectoire selectionnee !
1697                                YTemps = YTabTraj[itrajelue].toptime;  //(ctx pour les modules par exemple)
1698                                if (itrajelue==itraj && YTemps >= topstop) return(nbcall); //cf^ (eventuel arret sur une traj de ref)
1699                                YidTraj = itrajelue;                   //(ctx pour les modules par exemple)
1700
1701        if (YDispTime)
1702        {   printf (" >>> Traj %s, Current forward time = %i \n", YTabTraj[itrajelue].name, YTemps+1);
1703                                                //Ydispcurstep(itrajelue);
1704                                }
1705        forward_before(0); //arar
1706                                YTabTraj[itrajelue].fward(0); //<-: forward_order (pour LA trajectoire selectionnee)
1707                                ++nbcall;
1708                                forward_after(0); //arar
1709        {++YTabTraj[itrajelue].toptime; //<-: ++YTemps
1710         YTabTraj[itrajelue].curtime += YTabTraj[itrajelue].dtime; //<-: multi
1711        }
1712    }
1713    return(nbcall);
1714}
1715
1716/*...........................................................................*/
1717void Yforwardrun(int itraj, int nbpdt)
1718{   long topend;
1719                Ytop0 = time((time_t *)NULL);
1720
1721                if (YTabTraj[itraj].fward==NULL)
1722                {  printf("no forward function defined for that trajectory\n");
1723                   return;
1724                }               
1725                if (YTabTraj[itraj].toptime + nbpdt > YTabTraj[itraj].nbuptime + YTabTraj[itraj].nbsteptime )
1726                {        printf ("required forward step out of upper limit: \n");
1727                   printf ("         current top (%i) + required step (%i) > top max (%i) \n",
1728                                        YTabTraj[itraj].toptime, nbpdt, YTabTraj[itraj].nbuptime + YTabTraj[itraj].nbsteptime);
1729                         return;
1730                }
1731
1732    YidTraj  = itraj; //(ctx pour les modules par exemple)
1733                //YTemps = YTabTraj[itraj].toptime; //(ctx pour les modules par exemple)                  //-
1734
1735    before_it(1);
1736                for (int Ywt=1; Ywt<= nbpdt; ++Ywt)
1737                {               YTemps = YTabTraj[itraj].toptime; //(ctx pour les modules par exemple)          //+             
1738        if (YDispTime) printf (" >>> Traj %s, Current forward time = %i \n", YTabTraj[itraj].name, YTemps+1);
1739
1740        forward_before(Ywt);
1741                                YTabTraj[itraj].fward(0); //<-: forward_order
1742                                forward_after(Ywt);
1743                                //++YTemps;                //ctx                                                                                                                                                                        //-
1744        {++YTabTraj[itraj].toptime; //<-: ++YTemps
1745         YTabTraj[itraj].curtime += YTabTraj[itraj].dtime; //<-: multi
1746        }
1747                }
1748                topend = time((time_t *)NULL); /* time(&topend); topend = time((long *)NULL);*/
1749                printf("forward duration ....: %lds\n", topend-Ytop0);
1750                return;
1751}
1752
1753/* ----------------------------------------------------------------------------
1754//============== fonction de calcul du cout en passe avant ...  ============= */
1755void Yforwardcost()
1756{
1757                long    curtop;
1758                int   witraj;
1759                int   itrajelue;
1760               
1761                /* init ... */
1762//      YCaseCost = COSTL2_ONLY;  ne devrait plus etre utile ici puisque reposisionned apres par Ycost !!!
1763                YTotalCost = 0.0;                               //cout a 0
1764                               
1765          //TRobs = YRobs->fils;
1766          for (witraj=0; witraj<YNBTRAJ; ++witraj)    /* init des pointeurs des arbo d'obs supposed */
1767          {   YTabTraj[witraj].TRobs = YTabTraj[witraj].YRobs->fils; /* inversed (i.e: ascending)   */
1768          }
1769
1770                /* Calcul du cout sur les termes d'ebauche et aux temps initiaux*/
1771                if (YTypeCost==COST_APPLI)                      /* l'utilisateur devra prendre totalement */
1772                {        cost_function(-1);                                     //(YUPTIME-1)   /* en charge le calcul du cout ! */
1773                }
1774                else
1775                {  /* a faire trajectoire par trajectoire (si obs il y a) */
1776                   Ycostebx();
1777                }
1778
1779                /*Puis on va calculer le cout en passe avant */
1780                Yset_modeltime(0);
1781                before_it(1);      //(YItRun);
1782
1783    while ((itrajelue=Yforward_elect()) >= 0)  // le while controle la progression
1784                {     //ici, on n'avance QUE d'UN PDT sur la trajectoire selectionnee !
1785
1786                                YTemps = YTabTraj[itrajelue].toptime;  //(ctx pour les modules par exemple)
1787                                YidTraj = itrajelue;                   //(ctx pour les modules par exemple)
1788                                YNBUPTIME = YTabTraj[itrajelue].nbuptime;
1789
1790        if (YDispTime)
1791        {  printf (" >>> Traj %s, Current forwardcost time = %i \n", YTabTraj[itrajelue].name, YTemps+1);
1792                                         //Ydispcurstep(itrajelue);
1793        }
1794        forward_before(0); //arar
1795                                if (YAL2Run==RUNL2_STD)
1796                                         YTabTraj[itrajelue].fward(0); //<-: Yforward_order ();
1797#ifdef YO_VARINCR
1798                                else if (YAL2Run==RUNL2_INCR)
1799                                         YTabTraj[itrajelue].lward(0); //<-: Ylinward_order ();
1800#endif
1801                                forward_after  (0); //arar
1802                               
1803                                if (YTypeCost == COST_APPLI)            /* l'utilisateur devra prendre totalement */
1804                                         cost_function (YTemps);                        /* en charge le calcul du cout !          */
1805                                else
1806                                {  TRobs = YTabTraj[itrajelue].TRobs;  /* on se positionne sur le top d'obs courant de la trajectoire elue*/
1807                                   //Ycobs();                   /* calcul du cout au pas de temps (YTemps) courant (s'il y a lieu) */
1808                                   //YTabTraj[itrajelue].TRobs = TRobs;  /* pour avancer sur cette liste des temps */
1809                                         if (TRobs!=NULL && TRobs->iind==YTemps) //si cette traj a des obs au temps courant
1810                                         {  Ycost(); //calcul du cout
1811                                      YTabTraj[itrajelue].TRobs = TRobs;  /* pour avancer sur cette liste des temps */
1812                                   }
1813                                }
1814                                                                                               
1815        {++YTabTraj[itrajelue].toptime; //<-: ++YTemps
1816         YTabTraj[itrajelue].curtime += YTabTraj[itrajelue].dtime; //<-: multi
1817        }
1818                }
1819
1820                if (YDispCost==2)       //LAST
1821                {        curtop = time((time_t *)NULL);
1822                         printf(" >>> at iter %3ld after %lds: Total cost = % -23.15e\n", YItRun, curtop-Ytop0, YTotalCost);
1823                }
1824}
1825
1826/* ----------------------------------------------------------------------------
1827//============================ FONCTIONS BACKWARD ========================== */
1828int Ybackward_elect()
1829{   int wi;
1830    int candidat = -1;
1831    float wtime = -MYMAXREEL; //DBL_MAX; //999999;
1832                float wprectime;
1833
1834    for (wi=YNBTRAJ-1; wi>=0; --wi)
1835    {   wprectime = YTabTraj[wi].curtime - YTabTraj[wi].dtime;
1836        if (wprectime > wtime
1837        &&  YTabTraj[wi].toptime > YTabTraj[wi].nbuptime
1838        &&  YTabTraj[wi].isactiv
1839      //&&  YTabTraj[wi].curtime > Ybegintime   ...!?   ARAR
1840           )
1841        {  candidat = wi;
1842           wtime = wprectime;
1843        }
1844    }
1845    return(candidat);
1846}
1847/*---------------------------------------------------------------------------*/
1848void Ybackward(int itraj, int topstop) //meme principe que forward
1849{  int itrajelue, wi;
1850       
1851         /* passe arriere sur l'ensemble du modele global (i.e. sur ttes les trajectoires )
1852            de la ou on est positionned ! */
1853               
1854         //YCaseCost = COSTL2_GRAD;     //opera
1855                                                       
1856         for (wi=0; wi<YNBTRAJ; ++wi)           /* init des pointeurs des arbo d'observations  */
1857         {   YTabTraj[wi].TRobs = YTabTraj[wi].YRobs->fils;    //TRobs = YRobs->fils;
1858         }
1859
1860   /* passe arriere sur tout le modele global (i.e. sur ttes les trajectoires ) */
1861    while ((itrajelue=Ybackward_elect()) >= 0)  // le while controle la progression
1862                {   //ici, on ne recule QUE d'UN PDT sur la trajectoire selectionnee !
1863                                YidTraj = itrajelue;                    //(ctx pour les modules par exemple)
1864              YTemps = YTabTraj[itrajelue].toptime;   //(ctx pour les modules par exemple)
1865                                if (itrajelue==itraj && YTemps <= topstop) return; //eventuel arret sur une traj de ref
1866
1867        {--YTemps; --YTabTraj[itrajelue].toptime;                       //<-: --YTemps
1868         YTabTraj[itrajelue].curtime -= YTabTraj[itrajelue].dtime; //<-: multi
1869         YNBUPTIME = YTabTraj[itrajelue].nbuptime;
1870        }
1871        if (YDispTime)
1872        {  printf (" >>> Traj %s, Current backward time = %i \n", YTabTraj[itrajelue].name, YTemps+1);
1873                                         //Ydispcurstep(itrajelue);
1874        }
1875
1876                                backward_before (0); /* arar *//* doit obligatoirement exister ds le user's global ? */
1877                                /*---------------------*/
1878                                if (YTypeCost == COST_APPLI)            /* l'utilisateur devra prendre totalement */
1879                                         cost_function (YTemps);                        /* en charge le calcul du cout !          */
1880                                else
1881                                {  TRobs = YTabTraj[itrajelue].TRobs;  /* on se positionne sur le top d'obs courant de la trajectoire elue */
1882                                         //YCaseCost = COSTL2_GRAD;
1883                                   //Ycobs();                   /* calcul du cout au pas de temps (YTemps) courant (s'il y a lieu) */
1884                                   //YTabTraj[itrajelue].TRobs = TRobs;    /* pour avancer sur cette liste des temps */
1885                                         if (TRobs!=NULL && TRobs->iind==YTemps) /* si cette traj a des obs au temps courant */
1886                                         {  Ycost();                             /* calcul du cout */
1887                                      YTabTraj[itrajelue].TRobs = TRobs;   /* pour avancer sur cette liste des temps */
1888                                   }
1889                                }
1890                                /*---------------------*/
1891                                YTabTraj[itrajelue].bward(0); //<-: backward_order du modele sur la trajectoire
1892                                Yrazgrad_only(itrajelue);                /* apres backprop, mise a 0 du gradient pour tous les modules qui n'ont pas de temps de la trajectoire ! */
1893                                backward_after (0);   /* arar */ /* doit obligatoirement exister ds le user's global ? */
1894    }
1895}
1896/*................................................................................*/
1897void Ybackwardrun(int itraj, int nbpdt)
1898{   long topend;
1899                Ytop0 = time((time_t *)NULL);
1900               
1901                if (YTabTraj[itraj].bward==NULL)
1902                {  printf("no backward function defined for that trajectory\n");
1903                   return;
1904                }               
1905                if (YTabTraj[itraj].toptime - nbpdt < YTabTraj[itraj].nbuptime)
1906                {        printf ("required backward step out of lower limit: \n");
1907                   printf ("         current top (%i) - required step (%i) < nbuptime (%i) \n",
1908                                        YTabTraj[itraj].toptime, nbpdt, YTabTraj[itraj].nbuptime);
1909                         return;
1910                }
1911    //YCaseCost = COSTL2_GRAD; ne devrait plus etre utile ici puisque reposisionned apres par Ycost !!!
1912                TRobs = YTabTraj[itraj].YRobs->fils; //TRobs = YRobs->fils; init du pointeur sur l'arbo des observations
1913
1914    YidTraj = itraj; //(ctx pour les modules par exemple)
1915                YTemps = YTabTraj[itraj].toptime; //(ctx pour les modules par exemple)
1916                YNBUPTIME = YTabTraj[itraj].nbuptime;
1917
1918                for (int Ywt=1; Ywt<= nbpdt; ++Ywt)
1919                {   {--YTemps; --YTabTraj[itraj].toptime; //ctx //<-: --YTemps
1920         YTabTraj[itraj].curtime -= YTabTraj[itraj].dtime; //<-: multi
1921        }
1922        if (YDispTime) printf (" >>> Traj %s, Current backward time = %i \n", YTabTraj[itraj].name, YTemps+1);
1923        backward_before(Ywt);
1924                                if (YTypeCost == COST_APPLI)
1925                                   cost_function (YTemps);
1926                                //else Ycobs();
1927                                else //si cette traj a des obs au temps courant alors calcul du cout (?)
1928                                {  if (TRobs!=NULL && TRobs->iind==YTemps)
1929                                      Ycost(); //nb c'est Ycost qui avance TRobs (TRobs=TRobs->frere)
1930                                                        YTabTraj[itraj].TRobs = TRobs; //pour avancer sur cette liste des temps: est-ce bien utile
1931        }                                    //puisque, ici, il n'y a qu'une trajectoire.
1932                                YTabTraj[itraj].bward(0); //<-: backward_order
1933        Yrazgrad_only(itraj); //razgrad_only que sur la trajectoire concernee !
1934        backward_after(Ywt);
1935                }
1936                after_it(1);
1937
1938                topend = time((time_t *)NULL);
1939                printf("backward duration ....: %lds\n", topend-Ytop0);
1940                return;
1941}
1942
1943
1944/* ----------------------------------------------------------------------------
1945//============================= FONCTIONS LINWARD ========================== */
1946#ifdef YO_GRADTEST
1947#define YO_LINWARD
1948#endif
1949#ifdef YO_VARINCR
1950#define YO_LINWARD
1951#endif
1952#ifdef YO_LINWARD
1953void Ylinward(int bidon) //int bidon : pour rester compatible en attendant que tout soit termine !!!
1954{   int itrajelue;     
1955          // passe avant lineaire sur l'ensemble du modele global (i.e. sur ttes les trajectoires )
1956          // de la ou on est positionned !
1957    while ((itrajelue=Yforward_elect()) >= 0)   // le while controle la progression
1958                {   //ici, on n'avance QUE d'UN PDT sur la trajectoire selectionnee !
1959                               
1960                                YTemps = YTabTraj[itrajelue].toptime; //(ctx pour les modules par exemple)
1961                                YidTraj = itrajelue;                  //(ctx pour les modules par exemple)
1962
1963        if (YDispTime) printf (" >>> Traj %s, Current linward time = %i \n", YTabTraj[itrajelue].name, YTemps+1);
1964        forward_before(0); //arar
1965                                YTabTraj[itrajelue].lward(0); //<-: linward_order
1966                                forward_after(0); //arar
1967        {++YTabTraj[itrajelue].toptime; //<-: ++YTemps
1968         YTabTraj[itrajelue].curtime += YTabTraj[itrajelue].dtime; //<-: multi
1969        }
1970    }
1971}
1972                /* faut-il ou pas mettre les forward_before et forward_after ? */
1973                /*? plutot NON a priori car les etats sont deja calcules !  ...*/
1974                /* et finalement plutot OUI car qui sait si l'on aurait pas,   */
1975                /* par exemple, besoin de forcage dans le calcul des derivees !*/
1976                /* et puis qui peut le + peut le - */
1977#endif
1978/*---------------------------------------------------------------------------*/
1979#ifdef YO_VARINCR
1980void Yset_qteaebx() //calcul de qtea sur la partie ebauche seulement
1981{   int wi;
1982    for (wi=0; wi<YNBTRAJ; ++wi)
1983    {   TRobs = YTabTraj[wi].YRobs->fils;
1984        while (TRobs != NULL)
1985        {   if (TRobs->iind < 0)
1986            {  Yrovobs_TR(TRobs, Yc_dstar_all, 9);
1987            }
1988            TRobs = TRobs->frere;
1989        }         
1990          }
1991}
1992/*---------------------------------------------------------------------------*/
1993void Ylinward_flopobs(int bidon) //int bidon : pour rester compatible en attendant que tout soit termine !!!
1994{   //YLINWARD sur le modele +, et en passant, si y'a des obs pour un modules :
1995    //                          Forward+Linward des OPerateurs associed aux modules qui ont des OBS
1996    int itrajelue, wi;
1997
1998          for (wi=0; wi<YNBTRAJ; ++wi)          /* init des pointeurs des arbo d'observations  */
1999    {   YTabTraj[wi].TRobs = YTabTraj[wi].YRobs->fils;    //TRobs = YRobs->fils;
2000          }
2001
2002          /* passe avant lineaire sur l'ensemble du modele global (i.e. sur ttes les trajectoires )
2003            de la ou on est positionned ! */
2004    while ((itrajelue=Yforward_elect()) >= 0)   // le while controle la progression
2005                {   //ici, on n'avance QUE d'UN PDT sur la trajectoire selectionnee !
2006
2007                                YTemps = YTabTraj[itrajelue].toptime; //(ctx pour les modules par exemple)
2008                                YidTraj = itrajelue;                  //(ctx pour les modules par exemple)
2009
2010        if (YDispTime) printf (" >>> Traj %s, Current linward time = %i \n", YTabTraj[itrajelue].name, YTemps+1);
2011        forward_before(0); //arar
2012                                YTabTraj[itrajelue].lward(0); //<-: linward_order
2013
2014        /* because opera ... */
2015                          TRobs = YTabTraj[itrajelue].TRobs;      /* on se positionne sur le top d'obs courant de la trajectoire elue */
2016                                if (TRobs!=NULL && TRobs->iind==YTemps) /* si cette traj a des obs au temps courant */
2017                                {
2018                                   Yact_operator('*', OFF);
2019                       YCaseCost = WISHL2_NANACT; /* pour WISH: ca mettra NAN (niveau module) */
2020                       Ycobs_TR(TRobs->fils);                   /* puis ca active les operateurs associed au module (H, R, ...) */
2021                                       
2022           Yforward_operator('H');        /* il faut faire forward avant pour avoir les etats H(M(x)) ensuite on peut faire linward */
2023           Ylinward_operator('H');        /* je ne lance pas les autres operateurs (B,R,K) car ce sont des operateurs de covariance
2024                                         dont les modules ne devraient pas etre cout (bien que plm, ce n'est pas verified) */                           
2025                                   Yrovobs_TR(TRobs, Yc_dstar_all, 0);  /* pour calculer qtea=H'M'(Xk).dx - (y° - H(M(Xk)) */                         
2026                                   YTabTraj[itrajelue].TRobs = TRobs->frere;  /* pour avancer sur cette liste des temps */
2027                                }
2028                                                               
2029                                forward_after(0); //arar
2030        {++YTabTraj[itrajelue].toptime; //<-: ++YTemps
2031         YTabTraj[itrajelue].curtime += YTabTraj[itrajelue].dtime; //<-: multi
2032        }
2033    }
2034}
2035                /* faut-il ou pas mettre les forward_before et forward_after ? */
2036                /*? plutot NON a priori car les etats sont deja calcules !  ...*/
2037                /* et finalement plutot OUI car qui sait si l'on aurait pas,   */
2038                /* par exemple, besoin de forcage dans le calcul des derivees !*/
2039                /* et puis qui peut le + peut le - */
2040#endif
2041/* ----------------------------------------------------------------------------
2042//================================= Iteration de base ====================== */
2043/*
2044void old_Ybasic_it()
2045{
2046                long    curtop;
2047                                       
2048                Yset_modeltime(0);
2049                before_it(YItRun);      // doit obligatoirement exister ds le user's global ?
2050
2051                if(YAL2Run==RUNL2_STD)
2052                        Yforward (-1, 0); //Yforward (YNBSTEPTIME);
2053#ifdef YO_VARINCR
2054                else if(YAL2Run==RUNL2_INCR)
2055                {
2056      Yset_qteaebx();      //pour calculer qtea sur la partie ebauche
2057      Ylinward_flopobs(0); //Lineaire tangent pour calculer qtea=H'M'(Xk).dx - (y° - H(M(Xk)) sur la trajectoire
2058                }
2059#endif
2060
2061                Yrazgrad_all();  // avant fct de cout et backprop : sur tous les pas de temps, raz de tous les gradients de tous les modules
2062                //YTotalCost = YTotGrCost = 0.0;        // Raz aussi du Cout et de son Gradient total avant les calculs de cout
2063                YTotalCost = 0.0;       // Raz aussi du Cout avant les calculs de cout
2064                Ybackward(-1, 0); // Ybackward (YNBSTEPTIME);// AD (adjoint):-> d*x =M*(X).dX : Yjac * YG -> Ytbeta
2065
2066                // calcul du cout et gradient sur les termes d'ebauches et obs initiales
2067                if (YTypeCost==COST_APPLI)               // l'utilisateur devra prendre totalement
2068                                        cost_function (-1); //(YUPTIME-1); // en charge le calcul du cout !  (partie<uptime)
2069                else
2070                {                       //Ycobx();      calcul du cout et gradient sur les termes d'ebauches et obs initiales
2071                                        Ycostebx();  // calcul du cout et gradient sur les termes d'ebauches et obs initiales
2072                }
2073               
2074                if (YDispCost==2)       //LAST
2075                {        curtop = time((time_t *)NULL);
2076                         printf(" >>> at iter %3ld after %lds: Total cost = % -23.15e\n", YItRun, curtop-Ytop0, YTotalCost);
2077                }                       
2078
2079                if(YAL1Run==RUNL1_STD)
2080                { if(YAL2Run==RUNL2_STD)
2081                                Yadjust();
2082#ifdef YO_VARINCR
2083                        else if(YAL2Run==RUNL2_INCR)
2084                                Yc_adjustd();
2085#endif
2086                        after_it(YItRun);                               // doit obligatoirement exister ds le user's global ?
2087                }       
2088} ----------------------------------------------------------------------------*/
2089void Ybasic_it()
2090{
2091                long    curtop;
2092
2093                double sumJ = 0.0;                              /* cumul (summation) de la fonction de cout J (i.e. YTotalCost) */
2094    YREAL *TGSumTarget=NULL;    /* Tableau de cumul (SUMmation) des Gradients des Target */
2095
2096                before_it(YItRun);      /* doit obligatoirement exister ds le user's global ? */
2097
2098    if (YNbBasicIntL>1)
2099          {             //YREAL *TGSumTarget=new YREAL[YSIZEPB];        // nb: ne pas declarer TGSumTarget ici, sinon ce reste local au if {!!!}
2100                                TGSumTarget = new (std::nothrow) YREAL[YSIZEPB];                // tableau de cumul des gradient des variables a controler
2101                                if (TGSumTarget==NULL){printf("Yao=>ABORT: pb on new TabYG in Ybasic_it (see Yao system administrator)\n"); exit(-9);}
2102                                memset(TGSumTarget, 0, YSIZEPB*sizeof(YREAL));
2103    }
2104
2105                //for (int YItBasicIntL=1; YItBasicIntL<=YNbBasicIntL; ++YItBasicIntL) //BASIC INTERN LOOP ......................
2106                //      |_> was local !!!
2107                for (YItBasicIntL=1; YItBasicIntL<=YNbBasicIntL; ++YItBasicIntL) //BASIC INTERN LOOP ......................
2108    {
2109                                Yset_modeltime(0);
2110                                //before_it(YItRun);    /* doit obligatoirement exister ds le user's global ? */
2111
2112                                if(YAL2Run==RUNL2_STD)
2113                                        Yforward (-1, 0); //Yforward (YNBSTEPTIME);
2114                #ifdef YO_VARINCR
2115                                else if(YAL2Run==RUNL2_INCR)
2116                                {  //nb:dans le cas incremental, le forward est supposed avoir deja ete fait par Yforwardcost dans la boucle externe
2117                                         Yset_qteaebx();      //pour calculer qtea sur la partie ebauche (qtea = dx-(Xb-Xk) = YGo-(Xb-YSo))
2118                                         Ylinward_flopobs(0); //Lineaire tangent pour calculer qtea=H'M'(Xk).dx - (y° - H(M(Xk)) sur la trajectoire
2119                                }
2120                #endif
2121
2122                                Yrazgrad_all();  /* avant fct de cout et backprop : sur tous les pas de temps, raz de tous les gradients de tous les modules */
2123                                YTotalCost = 0.0;       /* Raz aussi du Cout avant les calculs de cout */
2124                                Ybackward(-1, 0); // Ybackward (YNBSTEPTIME);/* AD (adjoint):-> d*x =M*(X).dX : Yjac * YG -> Ytbeta */
2125
2126                                /* calcul du cout et gradient sur les termes d'ebauches et obs initiales */
2127                                if (YTypeCost==COST_APPLI)               /* l'utilisateur devra prendre totalement */
2128                                                        cost_function (-1); //(YUPTIME-1); /* en charge le calcul du cout !  (partie<uptime)   */
2129                                else
2130                                {                       //Ycobx();      calcul du cout et gradient sur les termes d'ebauches et obs initiales
2131                                                        Ycostebx();  /* calcul du cout et gradient sur les termes d'ebauches et obs initiales */
2132                                }
2133
2134                                if (YNbBasicIntL>1)
2135                                {  sumJ += YTotalCost;                  //cumul de la fonction de cout
2136                                         //cumul des gradients
2137                                         Y3windice=0;
2138           YgradCTOtab_target(TGSumTarget);                     /* Cumul de YGo dans [TGSumTarget]  */
2139                                }
2140                } //FIN INTERN LOOP ..................................................................
2141
2142                if (YNbBasicIntL>1)
2143          {  //on transfert les cumuls de la fonction de cout dans la fonction de cout
2144                   YTotalCost = sumJ;
2145       //on transfert les cumuls des gradients dans les zones YG
2146                         Y3windice=0;
2147       YtabTOgrad_target(TGSumTarget);
2148                   if (YDispCost==ON)   //=1
2149                   {    //curtop = time((time_t *)NULL); on affiche le cout cumule
2150                            printf(" >>> Cumul Total cost after basic internal loop = % -23.15e\n", YTotalCost);
2151                   }
2152                }
2153
2154                if (YDispCost==2)       //LAST
2155                {        curtop = time((time_t *)NULL);
2156                         printf(" >>> at iter %3ld after %lds: Total cost = % -23.15e\n", YItRun, curtop-Ytop0, YTotalCost);
2157                }
2158
2159                if(YAL1Run==RUNL1_STD)
2160                { if(YAL2Run==RUNL2_STD)
2161                                Yadjust();
2162#ifdef YO_VARINCR
2163                        else if(YAL2Run==RUNL2_INCR)
2164                                Yc_adjustd();
2165#endif
2166                        after_it(YItRun);                               /* doit obligatoirement exister ds le user's global ? */
2167                }
2168
2169                if (YNbBasicIntL>1) delete[] TGSumTarget;  /* on libere TGSumTarget */
2170}
2171
2172/* ----------------------------------------------------------------------------
2173//================================= FONCTION RUN =========================== */
2174void Yrun(long Yit)
2175{
2176                long topend;
2177                Ytop0 = time((time_t *)NULL);
2178        printf("\nstart run time: %s\n", ctime(&Ytop0));
2179
2180                YY_RUNBRK=OFF;  /* pour gere le break d'un run en interactif */
2181
2182                /* YTypeMode=MODE_STD; gestion standard de l'adjust et de l'after_it */
2183                YAL1Run=RUNL1_STD;      // Run niveau 1 standard
2184                YAL2Run=RUNL2_STD;      // Run niveau 2 standard
2185
2186                for (YItRun=1; YItRun<=Yit; ++YItRun)
2187                {               Ybasic_it();
2188                                if (YY_RUNBRK) break;
2189                }
2190        printf("\nstart run time ....: %s", ctime(&Ytop0));
2191        topend = time((time_t *)NULL);
2192          printf("  end run time ....: %s", ctime(&topend));
2193                printf("  run duration ....: %lds\n\n", topend-Ytop0);
2194                YY_RUNBRK=ON;
2195}
2196
2197/* ============================================================================
2198// POUR RUNNER AVEC M1QN3 ... a voir a faire (commentaires: ../omean/)                   */
2199#ifdef YO_M1QN3
2200#include "Dynmqn.h"
2201#endif
2202
2203/* ============================================================================
2204// FONCTIONS DE TEST POUR VALIDATION                                         */
2205#ifdef YO_GRADTEST
2206#include "Dyntst.h"
2207#endif
2208
2209
2210#ifdef NEW_STRUCTURE
2211#include "Project$PName.hpp"
2212#include "RunModelStd.hpp"
2213#include "RunModelM1QN3.hpp"
2214
2215using namespace $pname;
2216#endif
2217
2218
2219/* ============================================================================
2220//                      IMPLEMENTATION POUR L'ALGO L'INCREMENTAL             */
2221#ifdef YO_VARINCR
2222/* --------------------------------------------------------------------------*/
2223void Yc_run(long Yit)                                   //runi
2224{
2225                //int  witraj;
2226                int  extl, intl;
2227                long topend;
2228                Ytop0 = time((time_t *)NULL);
2229        printf("\nstart run time: %s\n", ctime(&Ytop0));
2230
2231                YY_RUNBRK=OFF;      /* pour gere le break d'un run en interactif */
2232                YAL1Run=RUNL1_STD;  /* run de niveau 1 standard */
2233                YItRun = 1;         /* init increment des iteration */
2234
2235                //INITIALISATION:--------------------------------------
2236                //1) On suppose X(k=0) initialised par l'utilisateur (setstate ou xuserfct)
2237    //2) On suppose que les obs (y°) et les ebauches ebx (Xb) ont ete charges (comme Nal et d'hab)
2238    //   avec loadobs, outoobs, (loadstate) outoebx
2239    //3) On suppose que l'utilisateur a positionned avec set_pcoef et pour chaque target module,
2240    //   les %ages qui serviront a initialiser les dx (avec la fct Ysetpdelta) dans la boucle externe
2241
2242    //BOUCLE EXTERNE ET INTERNE:---------------------------
2243                //boucle EXTERNE: .....................................
2244                for (extl=1; extl<=YNbExtL; ++extl)
2245                {       printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ extern loop ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
2246                                printf(" BE:%3i", extl);
2247
2248                                /* A) MD (Modele Direct):-> M(Xk) : states : [X] */
2249                                YAL2Run=RUNL2_STD; /* run de niveau 2 standard pour forwardcost*/
2250                                Yobs_reverse_time_lists();      // inversion de l'ordre du temps (descending->ascending)
2251                                Yforwardcost();                                           // passe avant (=>les YS sont calculed) avec calcul du cout sur la vraie fonction
2252                                Yobs_reverse_time_lists();      // re-inversion de l'ordre du temps (ascending->descending)
2253                                YAL2Run=RUNL2_INCR; /* mais run de niveau 2 incremental pour l'incremental */
2254
2255                                //B) SET de dx : ca depend de X et pcoef                                 
2256        //for (witraj=0; witraj<YNBTRAJ; ++witraj)
2257        //  YdeltaEQPCstate_traj(witraj, "Y#T", 0, YTabTraj[witraj].nbuptime);
2258        YdeltaEQPCstate_target(); //V7: YdeltaEQPCstate_all ("Y#T", 0, YUPTIME);        //%1
2259                               
2260                                //C) boucle INTERNE: .................................
2261                                for (intl=1; intl<=Yit; ++intl)
2262                                {
2263                                                printf(" BI:%3i", intl);
2264                                                ++YItRun;
2265
2266                                                //0) RAZ des zones Ygrad car ils vont etre propaged par le LT. en particulier
2267                                                //   et initialement les modules non target doivent avoir un dx=0 (isn-it).
2268                                                Yrazgrad_all();
2269
2270                                                //1) Transfert dans la zone Ygrad des Ydelta initialement affectes par YdeltaEQPCstate, puis ...?
2271                                                //   car c'est cette zone la (Ygrad) qui est propagee par le LT.
2272            YgradEQPdelta_target(1.0);
2273
2274//----------------------
2275                                                Ybasic_it();
2276//----------------------
2277                                                if (YY_RUNBRK) break;
2278
2279                                }//fin boucle INTERNE ..............................
2280
2281                                //suite boucle EXTERNE .............................
2282                                //D) Xk+1 = Xk + dx
2283                                Yc_adjustk_all ();
2284
2285                                if (YY_RUNBRK) break;
2286
2287                }//fin boucle EXTERNE .................................
2288                printf("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ end extern loop ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n");
2289
2290                /* cout sur la vraie fonction */
2291                printf(" BE:%3i", extl-1);
2292                YAL2Run=RUNL2_STD; /* run de niveau 2 standard pour forwardcost*/
2293                Yobs_reverse_time_lists();      // inversion de l'ordre du temps (descending->ascending)
2294                Yforwardcost();                                         // passe avant avec calcul du cout
2295                Yobs_reverse_time_lists();      // re-inversion de l'ordre du temps (ascending->descending)     
2296
2297        printf("\nstart run time ....: %s", ctime(&Ytop0));
2298        topend = time((time_t *)NULL);
2299          printf("  end run time ....: %s", ctime(&topend));
2300                printf("  run duration ....: %lds\n\n", topend-Ytop0);
2301                YY_RUNBRK=ON;
2302}
2303
2304// fin du code specifique pour l'INCREMENTAL (si YO_VARINCR)
2305#endif
2306/*-------------------------------------------------------------------------- */
2307
2308
2309/* ----------------------------------------------------------------------------
2310//============== echantillonnage fonction de cout pour plotting ============= */
2311int Ysampleof(char *modP, double Pinf, double Psup, double dP,
2312              char *modQ, double Qinf, double Qsup, double dQ, char *nmfile)
2313{
2314    FILE  *fpout;
2315    int   iPmod, iQmod;
2316    YREAL Pval, Qval, SUPP, SUPQ;
2317    long  topend;
2318    int         iP=0, iQ=0;
2319    int   iPtraj, iQtraj; /* indices des trajectoires des modules */
2320
2321    /* INIT et VERIF */
2322    iPmod = Yimod(modP);
2323    iQmod = Yimod(modQ);
2324
2325    if (iPmod<0 || iQmod<0)
2326    {  printf("sampleof(i): unknown module (%s or %s)\n", modP, modQ);
2327       return(0);
2328    }
2329
2330          if (iPmod==iQmod)
2331    {  printf("sampleof(i): Oh Oh! a modul with it-self !!! \n");
2332    }
2333
2334          /*if (YioInsertObsCtr == -1)  // il faut des obs pour pouvoir calculer un cout !
2335          {  printf("sampleof(i): you may had load obs\n");
2336             return(0);
2337          } cf ci-dessous */
2338
2339    if (Pinf>Psup || Qinf>Qsup)
2340    {  printf("sampleof(i): sup values must be greater (or equal) than inf values\n");
2341       return(0);
2342    }
2343
2344    if (dP<=0. || dQ<=0.) //pour pas boucler
2345    {  printf("sampleof(i): step values must be greater than 0\n");
2346       return(0);
2347    }
2348
2349    if ((fpout = fopen(nmfile, "w")) <= 0)
2350    {  printf ("sampleof(i): open file %s failed \n", nmfile);
2351       return (0);
2352    }
2353
2354                Ytop0 = time((time_t *)NULL);
2355        printf("\nstart sampleof(i) time: %s\n", ctime(&Ytop0));
2356
2357        iPtraj = Yitrajimod(iPmod);  /* indice des traj */
2358        iQtraj = Yitrajimod(iQmod);  /*   des modules   */
2359
2360                //Yobs_reverse_time_lists();              //inversion de l'ordre du temps -> ascending
2361                if (Yobs_reverse_time_lists()==0) //inversion de l'ordre du temps -> ascending
2362    {  // il faut des obs pour pouvoir calculer un cout !
2363       printf("sampleof(i): you may had load obs\n");
2364             return(0);
2365    }
2366                YItRun =1;
2367
2368                if (YAL2Run==RUNL2_INCR)
2369                {        Yset_modeltime(0);
2370                         before_it(YItRun);
2371                         Yforward(-1,0);    //hyp:Xo initialised et on calcule YS pour avoir YSn = M(Xo)
2372                }
2373
2374          /* boucle de calcul du cout pour chaque couple de valeur sur la plage donnee */
2375    Qval = Qinf;
2376    iQ = 0;
2377                SUPQ = Qsup + (Qsup * 1.0e-16); //pb of machine precision !!??
2378                while (Qval <= SUPQ)
2379    {           if (YAL2Run==RUNL2_STD)
2380                         Ysetstate_mod (modQ, Qval);
2381#ifdef YO_VARINCR
2382                else if (YAL2Run==RUNL2_INCR)
2383                                         YgradEQval_traj(iQtraj, modQ, YTabMod[iQmod].deb_target, YTabMod[iQmod].end_target, Qval);
2384#endif
2385                Pval = Pinf;
2386                iP = 0;
2387                                SUPP = Psup + (Psup * 1.0e-16); //pb of machine precision !!??
2388                                while (Pval <= SUPP)
2389        {               
2390                                                if (YAL2Run==RUNL2_STD)
2391                             Ysetstate_mod (modP, Pval);
2392#ifdef YO_VARINCR
2393                    else if (YAL2Run==RUNL2_INCR)                               
2394                                             YgradEQval_traj(iPtraj, modP, YTabMod[iPmod].deb_target, YTabMod[iPmod].end_target, Pval);
2395#endif
2396            Yforwardcost();     //calcul du cout en passe avant
2397                                                ++YItRun;
2398            //fprintf(fpout, "%e \t", YTotalCost);fflush(fpout);
2399            fprintf(fpout, "% 23.15e \t", YTotalCost);fflush(fpout);
2400            printf("o"); fflush(stdout);
2401            ++iP;
2402                                                Pval = Pinf + (dP * iP);
2403        }
2404        fprintf(fpout, "\n"); printf("\n");
2405        ++iQ;
2406                                Qval = Qinf + (dQ * iQ);
2407    }
2408                printf("sampleof(i): dim deduced: %i lines, %i columns\n", iQ, iP);
2409
2410                /* On laisse les choses comme on les a trouved */
2411                Yobs_reverse_time_lists();      // re-inversion de l'ordre du temps -> descending
2412
2413    fclose (fpout);
2414
2415                //printf("\nsampleof(i): completed,\n");
2416    printf("sampleof(i) start time ....: %s", ctime(&Ytop0));
2417        topend = time((time_t *)NULL);
2418          printf("  sampleof(i) end time ....: %s", ctime(&topend));
2419                printf("  sampleof(i) duration ....: %lds\n\n", topend-Ytop0);
2420
2421    return (1);
2422}
2423/*-------------------------------------------------------------------------- */
2424/* ///////////////////////////////////////////////////////////////////////// */
2425
2426
2427
2428
2429/* ////////////////////////////////////////////////////////////////////////////
2430//============================== INTERPRETEUR =================================
2431// PROCEDURE RUN : c'est un interpréteur de fichier d'instructions !!!
2432//                 ou de commandes intercatives !!!
2433//=============================================================================
2434//////////////////////////////////////////////////////////////////////////// */
2435/* SOME PROTOTYPAGE */
2436//int   Yrecup_cde (int *cdesc, char *cdeline, char *cdes[]); -> Dynamo.h
2437int     Yinterprete_cde(int cdesc, char *cdes[]);
2438/* SOME OTHER GLOABLE */
2439int   Yrecurlev=0;                                        /* niveau d'appel recursif de load_inst */
2440int   Yerr1tpret=0;                                     /* flag d'erreur */
2441char    cdeline[BUFSIZE + 1];           /* ligne de commande lue */
2442char  *pcdeline;                                                        /* pointeur sur la ligne de commande lue */
2443char  *cdes[NB_MAX_ARG_CDE];    /* tableau des arguments de la commande */
2444int   cdesc;                                                                    /* nombre d'argument de la commande */
2445
2446/* __________________________________________________________________________*/
2447void Ysignal(int isig)
2448{       /* interception de ctrl C pour breaker un run en cours */
2449        if (YY_RUNBRK) exit(0);
2450        printf("Break required; will act at next iteration\n");
2451        YY_RUNBRK=ON;
2452}
2453
2454/* __________________________________________________________________________*/
2455int Yload_inst (FILE *fpinst, char *nmfile, int *nbenrlus)
2456{       /* lecture et execution des instructions qui sont dans le fichier nmfile */
2457        int                     goinglabel=0;
2458        char    label[LG_MAX_NAME+1];
2459        int                     wi;             
2460
2461        while (fgets (cdeline, BUFSIZE, fpinst) != NULL)
2462        {
2463                        ++*nbenrlus;
2464                       
2465                        if (cdeline[strlen(cdeline)-1] == '\n')                 
2466                                 cdeline[strlen(cdeline)-1] = '\0';
2467                        /* ?strupr(cdeline); */
2468                        pcdeline = cdeline;
2469                       
2470                        /* positionnement en debut de ligne. i.e.: 1er caractere significatif */
2471                        while (pcdeline[0] == ' ' || pcdeline[0] == '\t') ++pcdeline;
2472                       
2473                        if (pcdeline[0] == '#') /* commentaire en debut de ligne (#) */
2474                                        continue;
2475                                       
2476                        wi=0;                                                                                                   /* commentaire en fin de ligne (|)*/
2477                        while (pcdeline[wi]!='\0')
2478                        { if (pcdeline[wi]=='|') {pcdeline[wi]='\0'; break;}
2479                        ++wi;
2480                        }
2481
2482                        if (pcdeline[0] == '!' && !goinglabel) /* commande systeme */
2483                        {               system (&pcdeline[1]);
2484                                        continue;
2485                        }
2486                        if (YEcho && !goinglabel) printf ("Yao#>%s\n", cdeline);
2487                        if (!Yrecup_cde (&cdesc, pcdeline, cdes))
2488                        {        printf ("inst: file %s, commande %s, ligne %i : error found=>stop \n", nmfile, cdes[0], *nbenrlus);
2489                                 return(0);
2490                        }
2491                        if (cdesc == 0)
2492                                continue;
2493                               
2494                        /* traitement d'un goto label */
2495                        if (goinglabel)
2496                        {  if (!strcmp(cdes[0], label)) goinglabel=0;
2497                           continue;
2498                        }
2499                        if (!strcmp(cdes[0], "GOTO") || !strcmp(cdes[0], "goto"))
2500                        { if (cdesc != 2)
2501                          { printf("inst: file %s, line %i, goto must be folling by one label \n", nmfile, *nbenrlus);
2502                            return (0);
2503                          }
2504                          strcpy(label, cdes[1]);
2505                          goinglabel = 1;
2506                          continue;
2507                        }
2508               
2509                        /* inserer ici (si besoin) un upercase de l'instruction (cdes[0]) */
2510                        if (!Yinterprete_cde(cdesc, cdes))
2511                        {        if(!Yerr1tpret)
2512                             printf ("inst: file %s, commande %s, ligne %i : error found=>stop \n", nmfile, cdes[0], *nbenrlus);
2513                                 Yerr1tpret=1;
2514                                 return(0);
2515                        }
2516        }
2517
2518  fclose(fpinst);
2519        return(1);
2520}
2521
2522/* ============================================================================
2523// LE PROGRAMME MAIN IT-SELF """"""""""""""""""""""""""""""""""""""""""""""" */
2524int Yboot_appli (int argc, char *argv[])
2525{
2526  int   wi;                    /* variable de travail local (indice de boucle, ...) */
2527
2528        /* SOME INIT ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
2529        Yszint  = sizeof(int);                  /* taille d'un int */
2530        Yszreal = sizeof(YREAL);                /* taille d'un reel pour les states (...) {float ou double} */
2531        srand( (unsigned)time( NULL ) );
2532        YDispTime = OFF;
2533        YDispCost = OFF;
2534        sprintf(YPrompt, "Yao:%s> ", PRJNAME);
2535
2536        for (wi=0; wi<YNBTRAJ; ++wi)
2537        { YTabTraj[wi].YRobs = (struct Yst_nodo*) malloc(sizeof(struct Yst_nodo)); /* init du Root des arborescences */
2538          YTabTraj[wi].YRobs->frere = YTabTraj[wi].YRobs->fils = NULL;  /* d'observations pour chaque trajectoire */
2539        }
2540
2541        memset(Yting, 0, YMAX_NBI*sizeof(YREAL));                                                           // y'avait double au lieu
2542        //memset(Yjac, 0, YMAX_NBS*YMAX_NBI*sizeof(YREAL));                       // de YREAL et ca provoquait
2543        memset(Yjac, 0, YMAX_JAC_NBS*YMAX_JAC_NBI*sizeof(YREAL));       // de YREAL et ca provoquait
2544        memset(Ytbeta, 0, YMAX_NBI*sizeof(YREAL));                                                  // un plantage quand on etait en float !!!
2545
2546        /* pour intercepter ctrl C lors d'un run et l'arreter */
2547        signal(SIGINT, Ysignal);
2548
2549        /* message de demarrage */
2550        printf ("\nStarting Yao : %s ", VERREF);
2551        printf ("\nProject %s. \n(You are in ", PRJNAME);
2552        if (sizeof(YREAL)==sizeof(double)) printf("double mode)\n"); else printf("float mode)\n");
2553
2554#ifdef PARALLEL
2555        cout << "This is a parallel version of the application, the max number of threads that the system supports are: " 
2556          << omp_get_max_threads() << "." << endl;
2557#endif
2558
2559        #ifdef NEW_STRUCTURE
2560        activeProject = new Project$PName();
2561        activeProject->initialize();
2562        #endif
2563
2564        /* CREATION DU MODELE: (le fait on systématiquement ou est-ce au user de   */
2565        Ycreate_all ();                  /* le mettre dans les instructions? Quid Initialiser? */
2566
2567        /* Une fonction de demarrage pour l'appli specifique du user; */
2568        appli_start     (argc, argv);
2569
2570  return (0);
2571}
2572/*----------------------------------*/
2573int Yentry1 (int argc, char *argv[]); //prototypage de Yentry1 qui prolonge Yentry0 !
2574int Yentry0 (int argc, char *argv[])
2575{
2576        /* l'ancienne syntaxe etait     :
2577        //                              prjname                                 :=> execution en batch avec le fichier prjname.i
2578        //   ou   prjname nmfile        :=> execution en batch avec le fichier nmfile
2579        //   ou   prjname [] [-i]       :=> execution en mode interactif                                                                 */
2580        /* NOUVELLE SYNTAXE :
2581                  prjname [...] [-b -e -i [fichier_d'instruction]]
2582                 OPTION :
2583                        -b              : boot de l'appli ((some init, Creat, appli_start)
2584                                sans execution d'instruction aucune.
2585                        -e    : execution d'instructions (cf ci-apres) ce qui suppose que
2586                                le boot de l'appli (option -b) est deja fait.
2587                        Par defaut :  -b  et  -e
2588
2589                        -i [nmfile]
2590                                        si nmfile n'est pas fourni
2591                                           alors : on execute en mode Interactif
2592                                        si nmfile est fourni et qu'il ne correspond pas a un fichier existant
2593                                           alors : on execute en mode Interactif
2594                                        si nmfile est fourni et qu'il correspond a un fichier qui existe
2595                                           alors : l'appli est lancee en Batch avec nmfile pour fichier d'instructions
2596                        Par defaut : on essaie de lancer en Batch avec prjname.i si il existe, sinon -> erreur
2597        */
2598        /* gestion des options */
2599        int optb=0, opte=0, opti=0;
2600        int wi=0;
2601        while (wi<argc)         //boucle de positionnement des options
2602        {               if (!strcmp(argv[wi], "-b"))
2603                        {        optb=1;
2604                        }
2605            else if (!strcmp(argv[wi], "-e"))
2606                        {        opte=1;
2607                        }
2608            else if (!strcmp(argv[wi], "-i"))
2609                        {        opti=wi; //ici, on memorise l'indice de l'argument
2610                        }
2611                        ++wi;
2612        }
2613        /* gestion des options */
2614        if (optb==0 && opte==0)
2615        {  //par defaut :-> b et e
2616           optb=opte=1;
2617        }
2618        if (opti>0 && !opte)
2619        {  //l'option -i n'a de sens que pour une execution
2620           printf(" -i option has no sens without execution\n");
2621                 return(0);
2622        }
2623  if (optb)
2624        {  Yboot_appli(argc, argv);     //boot, ammorcage, init, creat de l'appli
2625        }
2626        //if (opti>0) //fichier d'instruction ...{} : c'est dans Yentry1 que ca se passe
2627  if (opte)
2628        {  Yentry1(argc, argv);                 //execution de l'appli
2629        }
2630
2631        /* decoupage supplementaire pour pouvoir eviter d'allouer a chaque fois
2632           un nouvel espace par Ycreate_all lorsque une appli est appeled plusieurs
2633                 fois par une autre, ... de plus, ainsi on evite que les modules soit remis
2634                 a 0 entre 2+ appels ...
2635           Tout cela amene a definir un nouveau mode de lancement qu'on pourrait par
2636           exemple appeler un mode de boot uniquement de l'appli : option "-b"
2637                 Donc l'option -b ne doit etre utilise qu'une et une seul fois pour toutes
2638                 puis ensuite, on devrait pouvoir utilise l'option -e autant de fois que necesaire !? */
2639        return(0);
2640}
2641/*----------------------------------*/
2642int Yentry1 (int argc, char *argv[])
2643{
2644  char  fileinst[STRSIZE80+1]; /* fichier d'instructions initial */
2645  FILE  *fpinst=NULL;                            /* file pointeur du fichier d'instruction */
2646  int   nbenrlus;                                                        /* nbr d'enr du fichier d'instruction lus */
2647        int   wi=0;
2648
2649        /* determination du mode d'execution (Interactif ou batch) et fichier d'instructions */
2650        YM_EXE=0;
2651        while (wi<argc)
2652        {  //on recherche l'indication du fichier d'instruction qui desormais peut se trouver n'importe ou parmi les options
2653           if (!strcmp(argv[wi], "-i"))
2654                 {  ++wi;
2655                    if (wi<argc)
2656                                {               strcpy (fileinst, argv[wi]); //le parametre qui suit -i pourrait etre un fichier d'instruction
2657                                                if ((fpinst = fopen(fileinst, "r")) <= 0)       //ce qui suit n'est pas un fichier qui
2658                                        {        YM_EXE = 'I';                                                                                                          //existe => mode d'execution Interactif !
2659                                        }
2660                                                else //mode d'execution Batch
2661                                                {  YM_EXE = 'B';
2662                                                }
2663                                }
2664                                else //par d'argument apres -i => mode d'execution interactif !
2665                                {        YM_EXE = 'I';
2666                                }
2667                                break;
2668                 }
2669                 ++wi;
2670        }
2671        if (YM_EXE==0) //=> -i n'a pas ete rencontre; si un fichier prjname.i existe,
2672        {                                                        //   on l'executera en mode Batch sinon erreur
2673                        sprintf (fileinst, "%s.i", PRJNAME);
2674                        if ((fpinst = fopen(fileinst, "r")) <= 0)
2675                {        printf ("instruction file %s not found \n", fileinst);
2676                         return(0);
2677                }
2678                        YM_EXE = 'B';
2679        }
2680
2681        /* Execution des instructions :~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
2682        if (YM_EXE=='B')
2683        {       nbenrlus=0;
2684          ++Yrecurlev;
2685                if (!Yload_inst(fpinst, fileinst, &nbenrlus)) // on s'arrete a la 1ere erreur,
2686                {        printf("-error found while file %s, line %i. sequence aborted \n", fileinst, nbenrlus);
2687                         exit(9);                                                                                                               
2688                }  /* de toute facon, on s'arrete a la fin */                   
2689        }
2690        else if (YM_EXE=='I')
2691        {       /* En mode INTERACTIF, on entre dans une boucle "sans fin..." */
2692                printf("\n\n");
2693                printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
2694                printf("         Yao welcome you friendly      \n");
2695                printf("       and wish you a happy new year    \n");
2696                printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n");
2697                while (1)
2698                {       printf("%s", YPrompt);  /*le prompt */
2699                        /* printf("yao> "); //le prompt */
2700
2701                        /* récupération de la commande gets (cdeline); */
2702                        fgets(cdeline, BUFSIZE, stdin);
2703
2704                        /* strupr (cdeline); */
2705                        pcdeline = cdeline;
2706                        while (pcdeline[0] == ' ') ++pcdeline;
2707               
2708                        /* commande systeme */         
2709                        if (pcdeline[0] == '!')
2710                        {               system (&pcdeline[1]);
2711                                        continue;
2712                        }
2713                       
2714                        /* commande yao */
2715                        if (!Yrecup_cde(&cdesc, pcdeline, cdes))                       
2716                                 continue;
2717
2718                        if (cdesc == 0)
2719                                 continue;
2720                        if (strcmp(cdes[0], "EXIT") == 0 || strcmp(cdes[0], "exit") == 0 ||
2721                            strcmp(cdes[0], "QUIT") == 0 || strcmp(cdes[0], "quit") == 0 ||
2722                            strcmp(cdes[0], "BYE") == 0  || strcmp(cdes[0], "bye")  == 0  )
2723                        {         if (rand()%2==0) printf("\n             I'LL BE  BACK !\n\n");
2724                                        else                                     printf("\n        Yao c'est un truc de OUF !\n\n");
2725                                        return(0); //exit(0);
2726                        }
2727                        else
2728                        {       Yerr1tpret=0;
2729                          if (!Yinterprete_cde(cdesc, cdes))
2730                          {      if (rand()%2==0) printf ("        Yao, c'est plus fort que toi. \n");
2731                                         else                                     printf ("          Are you talking to me !? \n");
2732                          }
2733                        }
2734                }
2735        }
2736        else
2737                printf ("unpossible case #@§?§???§§§\n");
2738
2739        return(0);
2740}
2741/*
2742int main(int argc, char *argv[])
2743{   PRJMAIN (argc, argv);
2744    return(0);
2745}
2746*/
2747/* ========================================================================= */
2748/* fonction de découpage de la commande par chaine de caractÚre dans un tableau */
2749int Yrecup_cde (int *cdesc, char *cdeline, char *cdes[])
2750{
2751        int     i;
2752  i=strlen(cdeline) - 1; //printf("\n %i line=|%s|", i+1, cdeline);
2753
2754        /* while (cdeline[i] == ' ' || cdeline[i] == '\t') --i; //je me positionne à la fin de la chaine pour y mettre '\0' */
2755        /* while (cdeline[i] == ' ' || cdeline[i] == '\t' || cdeline[i] == '\n') --i; //je me positionne à la fin de la chaine pour y mettre '\0' */
2756  /*while (cdeline[i] == '\n') --i; // je me positionne à la fin de la chaine pour y mettre '\0' */
2757  while (cdeline[i] == '\n' || cdeline[i] == ' ' || cdeline[i] == '\t') --i; /* je me positionne à la fin de la chaine pour y mettre '\0' */
2758    cdeline[i+1] = '\0';
2759
2760        i=0;                                                                                                                                            /* je me repositionne au début de la chaine */
2761        *cdesc = 0;     
2762        while (cdeline[i] != '\0')                                                      /* tant qu'on a pas fini de balayer toute la chaine */
2763        {
2764                if (*cdesc>=NB_MAX_ARG_CDE)                                                                     /* verif qu'on ne depasse pas le nombre */
2765                {  printf("too much arg in that order\n");      /* d'arguments defini                   */
2766                         return(0);
2767                }
2768       
2769                while (cdeline[i] == ' ' || cdeline[i] == '\t') ++i;    /* je suis avant le prochain mot et je vais à sa rencontre */
2770                cdes[*cdesc]=&cdeline[i];                                                                                                                       /* je suis dessus, je stock son adresse */
2771                ++*cdesc;                                                                                                                                                                                       /* j'incremente le nombre de mot trouves */
2772
2773                /* cas particulier pour le changement du prompt: on s'interrompt avant */
2774                if ((strcmp(cdes[0], "set_prompt")==0   || strcmp(cdes[0], "SET_PROMPT")==0) && (*cdesc==2)) return(1);                 
2775                /* de meme, cas particulier pour le changement du separateur d'io: on s'interrompt avant */
2776                if ((strcmp(cdes[0], "set_iosep")==0    || strcmp(cdes[0], "SET_IOSEP")==0) && (*cdesc==2)) return(1);                 
2777               
2778                while (cdeline[i] != ' ' && cdeline[i] != '\0')
2779                {       ++i;                                                                                                                            /* j'avance sur le mot jusqu'à sa fin */
2780                        if (cdeline[i] == '\t') break;                  /* (pour pouvoir passer ensuite au mot suivant) */
2781                }
2782                if (cdeline[i] != '\0')
2783                {       cdeline[i] = '\0';
2784                        ++i;
2785                }
2786                       
2787        }
2788        return (1);
2789}       
2790
2791/* ========================================================================= */
2792/* fonction d'interpretation et de traduction de la commande */
2793int Yinterprete_cde(int cdesc, char *cdes[])
2794{
2795        int      w1, w2;
2796        double ww1;
2797        int              codret = 1;                                            /* init a pas d'erreur */
2798
2799  char  fileinst[STRSIZE80+1];  /* un fichier d'instructions */
2800  FILE  *fpinst;                                                          /* file pointeur du fichier d'instruction */
2801  int   nbenrlus;                                                               /* nbr d'enr du fichier d'instruction lus */
2802
2803  int   witraj;                                                                 /* multi: indice de trajectoire */
2804       
2805        //printf (">>>%s\n", cdes[0]);
2806       
2807        /* pre-traitement pour la substitution des mots definis */
2808        for (w1=0; w1<cdesc; ++w1)
2809        {               w2=Yisdefval(cdes[w1]);
2810                        if (w2 >=0 )
2811                        {        strcpy(cdes[w1], YTabDefval[w2].macro);
2812                        }
2813        }
2814       
2815        /*---------------------------------------------------------*/           
2816        if (strcmp(cdes[0], "LVAL") == 0        || strcmp(cdes[0], "lval") == 0)
2817        {  Ylval();
2818        }       
2819        else if (strcmp(cdes[0], "STRAJ") == 0 || strcmp(cdes[0], "straj") == 0)
2820        {        Ystraj();
2821        }
2822        else if (strcmp(cdes[0], "PDT2PDT") == 0 || strcmp(cdes[0], "pdt2pdt") == 0)
2823        { //syntax: pdt2pdt fromtraj steptime  totraj
2824                if (cdesc != 4)
2825                {  printf("pdt2pdt: syntax is: pdt2pdt fromtraj steptime  totraj\n");
2826                   return(1);
2827                }
2828                w1 = Yitraj(cdes[1]);
2829                w2 = Yitraj(cdes[3]);
2830                if (w1<0 || w2<0)
2831                {        printf("pdt2pdt: unknwon trajectory name (%s) or (%s) \n", cdes[1], cdes[3]);
2832                         return(0);
2833                }
2834                /*if (atoi(cdes[2])<=YTabTraj[w1].nbuptime)
2835                {        printf("pdt2pdt: steptime must be > nbuptime of trajectory %s\n", cdes[1]);
2836                         return(0);
2837                } il ne s'agit ici que de verifier le comportement de la fonction de traduction Ypdt2pdt */
2838                printf("pdt %i [%i] of %s  --is--> pdt %i [%i] for %s \n", atoi(cdes[2]), atoi(cdes[2])-1,      cdes[1],
2839                  Ypdt2pdt(w2, atoi(cdes[2]), w1), Ypdt2pdt(w2, atoi(cdes[2]), w1)-1,
2840                  cdes[3]);
2841        }
2842        else if (strcmp(cdes[0], "SET_TOPTIME") == 0 || strcmp(cdes[0], "set_toptime") == 0)
2843        { //syntax: set_toptime trajname integer
2844                if (cdesc != 3) return(0);
2845
2846                witraj = Yitraj(cdes[1]);
2847                if (witraj<0)
2848                {        printf("set_toptime: unknwon trajectory name (%s) \n", cdes[1]);
2849                         return(0);
2850                }
2851                w1 = atoi(cdes[2]);
2852                if (w1<YTabTraj[witraj].nbuptime || w1 >= YTabTraj[witraj].nbuptime + YTabTraj[witraj].nbsteptime)
2853                {        printf("set_toptime: value must be >=%d and <=%d\n", YTabTraj[witraj].nbuptime,
2854               YTabTraj[witraj].nbuptime + YTabTraj[witraj].nbsteptime -1);
2855                         return(0);
2856                }
2857                YTabTraj[witraj].toptime = w1;
2858                Yupdcurtime(witraj);
2859        }
2860        else if (strcmp(cdes[0], "SET_MODELTIME") == 0 || strcmp(cdes[0], "set_modeltime") == 0)
2861        {
2862                if (cdesc != 2) return(0);
2863                w1 = atoi(cdes[1]);
2864                if (w1!=0)
2865                {        printf("set_modeltime: work only with 0, found %s \n", cdes[1]);
2866                         return(0);
2867                }
2868                Yset_modeltime(w1);
2869        }
2870        else if (strcmp(cdes[0], "SET_NBITER") == 0     || strcmp(cdes[0], "set_nbiter") == 0)
2871        {
2872                if (cdesc != 2) return(0);
2873                YNbItRun = atol(cdes[1]);
2874        }
2875        else if (strcmp(cdes[0], "SET_NBEXTL") == 0     || strcmp(cdes[0], "set_nbextl") == 0)
2876        {
2877                if (cdesc != 2) return(0);              /* pas de test sur YO_VARINCR :    */
2878                YNbExtL = atoi(cdes[1]);                        /* cela ne porte pa a concequence */
2879        }
2880        else if (strcmp(cdes[0], "SET_NB_BASIC_INTERN_LOOP") == 0       || strcmp(cdes[0], "set_nb_basic_intern_loop") == 0)
2881        {
2882                if (cdesc != 2) return(0);
2883                w1 = atoi(cdes[1]);
2884                if (w1<=0)
2885                {        printf("the basic intern loop number must be positive \n");
2886                         return(0);
2887                }
2888                YNbBasicIntL = w1;
2889        }
2890        else if (strcmp(cdes[0], "RUN") == 0    || strcmp(cdes[0], "run") == 0)
2891        {
2892                /* if (cdesc != 2)      return(0); */
2893                if (YNbItRun<=0)
2894                {        printf("run: number of run iteration not seted; use set_nbiter please\n");
2895                         return(0);
2896                }
2897                if (YioInsertObsCtr<0)
2898                   printf("run: warning : oh oh, run with no obs !!! \n");
2899                #ifdef NEW_STRUCTURE
2900                RunModelStd *run = new RunModelStd();
2901                run->nbQuasiStaticParts = Yqs_nbParts;
2902                run->nbItMax = YNbItRun;
2903                run->model = activeProject->activeModel;
2904                activeProject->mappingStructure();
2905                run->run();             
2906                #else
2907                Yrun(YNbItRun);
2908                #endif
2909        }
2910        else if (strcmp(cdes[0], "RUNI") == 0   || strcmp(cdes[0], "runi") == 0)
2911        {
2912                #ifdef YO_VARINCR
2913                if (YNbItRun<=0)
2914                {        printf("runi: number of run iteration seted; use set_nbiter please\n");
2915                         return(0);
2916                }
2917                if (YNbExtL<=0)
2918                {        printf("runi: number of extern loop not seted; use set_nbextl please\n");
2919                         return(0);
2920                }
2921                if (YioInsertObsCtr<0)
2922                   printf("runi: warning : oh oh, run with no obs !!! \n");
2923                Yc_run(YNbItRun);
2924                #else
2925                printf("runi: incremental option (O_VARINCR) is not active \n");
2926                return(0);
2927                #endif
2928        }
2929        else if (strcmp(cdes[0], "SET_DXALEA") == 0     || strcmp(cdes[0], "set_dxalea") == 0)
2930        { //valorisation d'une grandeur aleatoire pour la determination de dx dans certaines fonctions de test
2931                #ifdef YO_GRADTEST
2932                if (cdesc == 1)        //sans passage de parametre :
2933                {        Ydxalea[0] = '\0';  //-> neutralise l'alea
2934                }
2935                else //on prend tel quel le parametre passed ; pour bien faire, ce ne doit pas etre
2936                {    // n'importe quoi mais plm je ne controle pas !
2937                   //je verifie seulement la longueur
2938                         if (strlen(cdes[1]) > STRSIZE20)
2939                   {  printf("set_dxalea: too long parameter, max is %i \n", STRSIZE20);
2940                      return(0);
2941                         }
2942                   strcpy(Ydxalea, cdes[1]);
2943                }
2944                #else
2945                printf("set_dxalea: GRADTEST option is not active \n");
2946                return(0);
2947                #endif
2948        }
2949        else if (strcmp(cdes[0], "TESTDF") == 0 || strcmp(cdes[0], "testdf") == 0)
2950        { //test des derivees des modules,
2951                #ifdef YO_GRADTEST
2952                if (sizeof(YREAL)!=sizeof(double))
2953                {               printf("testdf: real format must be double (use option O_REAL double in .d)\n");
2954                         return(0);
2955                }
2956                if (cdesc <8)
2957                {        printf("testdf error: syntaxe is : testdf i j k t codop [%c]pdx ptol [nmmod-ko-max][max]\n", '%');
2958                         return(0);
2959                }
2960                Ytestdf(cdesc, cdes);
2961                #else
2962                printf("testdf: GRADTEST option is not active \n");
2963                return(0);
2964                #endif
2965        }
2966        else if (strcmp(cdes[0], "TESTAD") == 0 || strcmp(cdes[0], "testad") == 0)
2967        { //test de l'ADjoint
2968                #ifdef YO_GRADTEST
2969                if (sizeof(YREAL)!=sizeof(double))
2970                {               printf("testad: real format must be double (use option O_REAL double in .d)\n");
2971                         return(0);
2972                }
2973                if (cdesc == 2)
2974                {  if (YioInsertObsCtr != -1)
2975                   {     printf("testad error: obs must not be used before global Adjoint test\n");
2976                           //because: ca modifie le dy au cours de la redescente qui ne sera plus le meme
2977                           //         que celui utilised lors du calcul de LTRes.
2978                           //         Cette contrainte n'est pas utile pour testad_mod car le test est local.
2979                             return(0);
2980                   }                                                   
2981                         Ytestad     (atof(cdes[1])); //Ytestad(atof(cdes[1]), 0.0, 0);
2982                }
2983                else if (cdesc == 4)
2984                         Ytestad_mod (atof(cdes[1]), atof(cdes[2]), atoi(cdes[3]), 0.0);
2985                else if (cdesc == 5)
2986                         Ytestad_mod (atof(cdes[1]), atof(cdes[2]), atoi(cdes[3]), atof(cdes[4]));
2987                else
2988                {        printf("testad error: syntaxe is : testad pdx [errelmax maxko][pzedi]\n");
2989                         return(0);
2990                }                                       
2991                #else
2992                printf("testad: GRADTEST option is not active \n");
2993                return(0);
2994                #endif                         
2995        }               
2996        else if (strcmp(cdes[0], "TESTLT") == 0 || strcmp(cdes[0], "testlt") == 0)
2997        { //test du Lineaire Tangent
2998                #ifdef YO_GRADTEST
2999                if (sizeof(YREAL)!=sizeof(double))
3000                {               printf("testlt: real format must be double (use option O_REAL double in .d)\n");
3001                         return(0);
3002                }
3003                if      (cdesc==5)             
3004                         Ytestlt(atof(cdes[1]), atof(cdes[2]), atof(cdes[3]), atoi(cdes[4]), 1, 0); //0, 0); //default
3005                else if (cdesc==6)                     
3006                         Ytestlt(atof(cdes[1]), atof(cdes[2]), atof(cdes[3]), atoi(cdes[4]), atoi(cdes[5]), 0);
3007                else if (cdesc==7)                     
3008                         Ytestlt(atof(cdes[1]), atof(cdes[2]), atof(cdes[3]), atoi(cdes[4]), atoi(cdes[5]), atoi(cdes[6]));
3009                else
3010                {        printf("testlt error: syntaxe is : testlt pdx alpha fdec nbloop [modop]\n");                   
3011                         return(0);
3012                }                       
3013                #else
3014                printf("testlt: GRADTEST option is not active \n");
3015                return(0);
3016                #endif                         
3017        }               
3018        else if (strcmp(cdes[0], "TESTOF") == 0 || strcmp(cdes[0], "testof") == 0)
3019        { //test de l'Objective Fonction
3020                #ifdef YO_GRADTEST
3021                if (sizeof(YREAL)!=sizeof(double))
3022                {               printf("testof: real format must be double (use option O_REAL double in .d)\n");
3023                         return(0);
3024                }
3025                if      (cdesc==5)
3026                         Ytestof(atof(cdes[1]), atof(cdes[2]), atof(cdes[3]), atoi(cdes[4]), 1, 0);  //0, 0);
3027                else if (cdesc==6)
3028                         Ytestof(atof(cdes[1]), atof(cdes[2]), atof(cdes[3]), atoi(cdes[4]), atoi(cdes[5]), 0);
3029                else if (cdesc==7)
3030                         Ytestof(atof(cdes[1]), atof(cdes[2]), atof(cdes[3]), atoi(cdes[4]), atoi(cdes[5]), atoi(cdes[6]));
3031                else
3032                {        printf("testof error: syntaxe is : testof pdx alpha fdec nbloop [modop] \n");                 
3033                         return(0);
3034                }
3035                #else
3036                printf("testof: GRADTEST option is not active \n");
3037                return(0);
3038                #endif                         
3039        }                       
3040        else if (strcmp(cdes[0], "FORWARD") == 0 || strcmp(cdes[0], "forward") == 0)
3041        {  //syntax: forward [trajname nbpdt]
3042          if (cdesc!=1 && cdesc!=3)     return(0);     
3043          if (cdesc==1) //forward sur le modele global: i.e du debut jusqu'a la 'fin' de
3044          {             //toutes les trajectoires sur tous les modeles (pour creer des obs par exemple)
3045             //Yset_modeltime(0); en attendant de mettre cette instruction a disposition du user (fait pour 0)
3046       before_it(1);
3047             Yforward(-1, 0);
3048          }
3049          else //(cdesc==3) //forward trajname nbpdt: forward nbpdt sur une trajectoire particuliere
3050          {  witraj = Yitraj(cdes[1]);
3051                   if (witraj>=0) //cas de la syntaxe: forward trajname nbp :=> forward sur une traj particuliere
3052                   {    w1 = atoi(cdes[2]);
3053                      if (w1<=0)
3054                      {  printf("forward: bad step_time given, must be >=1\n");
3055                               return(0);
3056                      }
3057                      Yforwardrun(witraj, w1);
3058                   }
3059                   else //cas de syntaxe: forward nbp trajname :=> trajname est la trajectoire de reference
3060                   {    //pour avancer tout le modele de nbp pas de temps par rapport a cette trajectoire.
3061                                        witraj = Yitraj(cdes[2]);
3062                      if (witraj<0)
3063                      {  printf("forward: unknwon trajectory name (%s) \n", cdes[2]);
3064                               return(0);
3065                      }
3066                w1 = atoi(cdes[1]);
3067                      if (w1<=0)
3068                      {  printf("forward: bad step_time given, must be >=1\n");
3069                               return(0);
3070                      }
3071                      before_it(1);
3072                      Yforward(witraj, YTabTraj[witraj].toptime + w1);
3073                   }
3074                }
3075        }                       
3076        else if (strcmp(cdes[0], "BACKWARD") == 0 || strcmp(cdes[0], "backward") == 0)
3077        {  //syntax: backward [trajname nbpdt]
3078          if (cdesc!=1 && cdesc!=3)     return(0);     
3079          if (cdesc==1) //backward sur le modele global: i.e d'ou il est jusqu'au debut de
3080          {             //toutes les trajectoires sur tous les modeles
3081             Ybackward(-1, 0);
3082             after_it(1);
3083          }
3084          else //(cdesc==3) //2 cas possibles :
3085          {  witraj = Yitraj(cdes[1]);
3086                   if (witraj>=0) //cas de la syntaxe: backward trajname nbp :=> backward sur une traj particuliere
3087                   {    w1 = atoi(cdes[2]);
3088                      if (w1<=0)
3089                      {  printf("backward: bad step_time given, must be >=1\n");
3090                               return(0);
3091                      }
3092                      Ybackwardrun(witraj, w1);
3093                   }
3094                   else //cas de syntaxe: backward nbp trajname :=> trajname est la trajectoire de reference
3095                   {    //pour reculer tout le modele de nbp pas de temps par rapport a cette trajectoire.
3096                                        witraj = Yitraj(cdes[2]);
3097                      if (witraj<0)
3098                      {  printf("backward: unknwon trajectory name (%s) \n", cdes[2]);
3099                               return(0);
3100                      }
3101                w1 = atoi(cdes[1]);
3102                      if (w1<=0)
3103                      {  printf("backward: bad step_time given, must be >=1\n");
3104                               return(0);
3105                      }
3106                      Ybackward(witraj, YTabTraj[witraj].toptime - w1);
3107                      after_it(1);
3108                   }
3109                }
3110        }
3111        else if ( strcmp(cdes[0], "ACTIV") == 0 || strcmp(cdes[0], "activ") == 0
3112             ||   strcmp(cdes[0], "UNACTIV") == 0 || strcmp(cdes[0], "unactiv") == 0 )
3113        {       //syntax: {activ, unactiv} {trajname ,typetraj} [{trajname ,typetraj}[...]] [only]
3114          //exemple: active Traj1 M Q Traj7 R only
3115          if (cdesc <2) return(0);       
3116                codret = Yactraj(cdesc, cdes);
3117                return(codret);
3118        }
3119        else if (strcmp(cdes[0], "SET_BEGINTIME") == 0 || strcmp(cdes[0], "set_begintime") == 0)
3120        {       //syntax: set_begintime valeur
3121          if (cdesc != 2)       return(0);
3122                ww1 = atof(cdes[1]);
3123                if (ww1<0.0)
3124                {        printf("set_begintime: bad value given for set_begintime, must not be negativ \n");
3125                         return(0);
3126                }
3127                Ybegintime = ww1;
3128    for (w1=0; w1<YNBTRAJ; ++w1) {Yupdcurtime(w1);Yupdstoptime(w1);}
3129        }
3130        else if (strcmp(cdes[0], "SET_OFFTIME") == 0 || strcmp(cdes[0], "set_offtime") == 0)
3131        {       //syntax: set_offtime trajname valeur
3132          if (cdesc != 3)       return(0);
3133                ww1 = atof(cdes[2]);
3134                if (ww1<0.0)
3135                {        printf("set_offtime: bad value given for set_offtime, must not be negativ \n");
3136                         return(0);
3137                }
3138                witraj = Yitraj(cdes[1]);
3139                if (witraj<0)
3140                {        printf("set_offtime: unknwon trajectory name (%s) \n", cdes[1]);
3141                         return(0);
3142                }
3143                YTabTraj[witraj].offtime = ww1;
3144                Yupdcurtime(witraj); Yupdstoptime(witraj);
3145        }
3146        else if (strcmp(cdes[0], "SET_DTIME") == 0 || strcmp(cdes[0], "set_dtime") == 0)
3147        {       //syntax: set_dtime trajname valeur
3148          if (cdesc != 3)       return(0);
3149                ww1 = atof(cdes[2]);
3150                if (ww1<=0.0)
3151                {        printf("set_dtime: bad value given for set_dtime, must be greater 0 \n");
3152                         return(0);
3153                }
3154                witraj = Yitraj(cdes[1]);
3155                if (witraj<0)
3156                {        printf("set_dtime: unknwon trajectory name (%s) \n", cdes[1]);
3157                         return(0);
3158                }
3159                YTabTraj[witraj].dtime = ww1;
3160                Yupdcurtime(witraj);Yupdstoptime(witraj);
3161        }
3162        else if (strcmp(cdes[0], "PRINT_TIME") == 0 || strcmp(cdes[0], "print_time") == 0)
3163        {
3164                        if (cdesc==1)
3165                        {  printf ("^^^^^^^ CURRENT TRAJ TIME: ");
3166                           for (w1=0; w1<YNBTRAJ; ++w1) printf ("%s:->%d, ", YTabTraj[w1].name, YTabTraj[w1].toptime);
3167                           printf("\n");
3168                        }
3169                        else if (strcmp(cdes[1], "ON") == 0 || strcmp(cdes[1], "on") == 0)
3170                                                        YDispTime = ON;
3171                                         else
3172                                                        YDispTime = OFF;
3173        }
3174        else if (strcmp(cdes[0], "PRINT_COST") == 0 || strcmp(cdes[0], "print_cost") == 0)
3175        {
3176                        if (cdesc==1)
3177                                         printf ("^^^^^^^ TOTAL COST = % -23.15e \n", YTotalCost);
3178                        else if (strcmp(cdes[1], "ON") == 0 || strcmp(cdes[1], "on") == 0)
3179                                                  YDispCost = ON;               //=1
3180                        else if (strcmp(cdes[1], "LAST") == 0 || strcmp(cdes[1], "last") == 0)
3181                                                  YDispCost = 2;                //=2
3182                                         else
3183                                                        YDispCost = OFF;        //=0
3184        }
3185        else if (strcmp(cdes[0], "COST") == 0 || strcmp(cdes[0], "cost") == 0)
3186        {
3187                        if (cdesc<=1) return(0);
3188                        if (strcmp(cdes[1], "LMS") == 0 || strcmp(cdes[1], "lms") == 0)
3189                        { /*syntaxe: cost lms [val] */
3190                                        if (cdesc<2 || cdesc>3) return(0);                                     
3191                                        if (cdesc==3)
3192                                        {  if (!strtod(cdes[2], NULL)) return(0);
3193                                                 for(w1=0; w1<YNBMODUL;++w1)
3194                                                                 YTabMod[w1].scoef = strtod(cdes[2], NULL);
3195                                        }                                                                                                               
3196                                        YTypeCost = COST_LMS;
3197                                        return(1);
3198                        }
3199                        else if (strcmp(cdes[1], "APPLI") == 0 || strcmp(cdes[1], "appli") == 0)
3200                        {
3201                                        if (cdesc != 2) return(0);
3202                                                        YTypeCost = COST_APPLI;
3203                                        return(1);
3204                        }                       
3205                        return(0);
3206        }
3207        else if (strcmp(cdes[0], "set_scoef") == 0      || strcmp(cdes[0], "SET_SCOEF") == 0)
3208        {       /* syntaxe: set_scoef nmmod scoef */
3209                if (cdesc != 3) return(0);
3210                YTabMod[Yimod(cdes[1])].scoef = atof(cdes[2]);
3211        }
3212        else if (strcmp(cdes[0], "set_bcoef") == 0      || strcmp(cdes[0], "SET_BCOEF") == 0)
3213        {       /* syntaxe: set_bcoef nmmod bcoef */
3214                if (cdesc != 3) return(0);
3215                YTabMod[Yimod(cdes[1])].bcoef = atof(cdes[2]);
3216        }
3217        else if (strcmp(cdes[0], "set_pcoef") == 0      || strcmp(cdes[0], "SET_PCOEF") == 0)
3218        {       /* syntaxe: set_pcoef nmmod pcoef */
3219                if (cdesc != 3) return(0);
3220          YTabMod[Yimod(cdes[1])].pcoef = atof(cdes[2]);
3221        }       
3222        else if (strcmp(cdes[0], "ADJUST") == 0 || strcmp(cdes[0], "adjust") == 0)
3223        {
3224                        if (cdesc!=2) return(0);
3225                        if (strcmp(cdes[1], "STD") == 0 || strcmp(cdes[1], "std") == 0)
3226                                                YTypeAdjust = ADJUST_STD;
3227                        else if (strcmp(cdes[1], "APPLI") == 0 || strcmp(cdes[1], "appli") == 0)
3228                                                YTypeAdjust = ADJUST_APPLI;
3229                        else
3230                                        return(0);
3231                        return(1);
3232        }
3233        else if (strcmp(cdes[0], "ECHO") == 0 || strcmp(cdes[0], "echo") == 0)
3234        {
3235                        if (cdesc != 2) return(0);
3236                        if (strcmp(cdes[1], "ON") == 0 || strcmp(cdes[1], "on") == 0)
3237                                        YEcho = ON;
3238                        if (strcmp(cdes[1], "OFF") == 0 || strcmp(cdes[1], "off") == 0)
3239                                        YEcho = OFF;   
3240        }
3241        else if (strcmp(cdes[0], "SETM_DXMIN") == 0     || strcmp(cdes[0], "setm_dxmin") == 0)
3242        {
3243                #ifdef YO_M1QN3         
3244                if (cdesc==2)                                                                           /* si 1 parametre est passed on considere qu'il */
3245                   Y3dxmin[0] = atof(cdes[1]);  /* s'agit du scalaire dxmin pour m1qn3          */
3246                else if (cdesc == 1)
3247                {
3248                   #ifdef YO_M2QN1                                                      /* si aucun parametre, on considere, a condition*/
3249                   Y3valdxmin_all();                                            /* d'avoir M1QN2, que c'est un vecteur qu'il faut utiliser */
3250                         #else
3251                         printf("setm_dxmin: m2qn1 (via o_m1qn3) option is not active \n");
3252                   return(0);
3253                   #endif
3254                }
3255                #else
3256                {       printf("setm_dxmin: m1qn3 option is not active \n");
3257                        return(0);
3258                }
3259                #endif                 
3260        }
3261        else if (strcmp(cdes[0], "SETM_DDF1") == 0      || strcmp(cdes[0], "setm_ddf1") == 0)
3262        {
3263                #ifdef YO_M1QN3
3264                if (cdesc != 2) return(0);
3265                Y3ddf1 = atof(cdes[1]);
3266                #else
3267                printf("setm_ddf1: m1qn3 option is not active \n");
3268                return(0);
3269                #endif         
3270        }                                       
3271        else if (strcmp(cdes[0], "SETM_EPSG") == 0      || strcmp(cdes[0], "setm_epsg") == 0)
3272        {
3273                #ifdef YO_M1QN3
3274                if (cdesc != 2) return(0);
3275                Y3epsg = atof(cdes[1]);
3276                #else
3277                printf("setm_epsg: m1qn3 option is not active \n");
3278                return(0);
3279                #endif         
3280        }
3281        else if (strcmp(cdes[0], "SETM_IMPRES") == 0    || strcmp(cdes[0], "setm_impres") == 0)
3282        {
3283                #ifdef YO_M1QN3
3284                if (cdesc != 2) return(0);
3285                Y3impres = atol(cdes[1]);
3286                #else
3287                printf("setm_impres: m1qn3 option is not active \n");
3288                return(0);
3289                #endif         
3290        }
3291        else if (strcmp(cdes[0], "SETM_IO") == 0        || strcmp(cdes[0], "setm_io") == 0)
3292        {
3293                #ifdef YO_M1QN3
3294                if (cdesc != 2) return(0);
3295                Y3io = atol(cdes[1]);
3296                #else
3297                printf("setm_io: m1qn3 option is not active \n");
3298                return(0);
3299                #endif         
3300        }
3301        else if (strcmp(cdes[0], "SETM_MODE") == 0      || strcmp(cdes[0], "setm_mode") == 0)
3302        {
3303                #ifdef YO_M1QN3
3304                if (cdesc != 2) return(0);
3305                Y3mode = atol(cdes[1]);
3306                #else
3307                printf("setm_mode: m1qn3 option is not active \n");
3308                return(0);
3309                #endif         
3310        }
3311        else if (strcmp(cdes[0], "SETM_NSIM") == 0      || strcmp(cdes[0], "setm_nsim") == 0)
3312        {
3313                #ifdef YO_M1QN3
3314                if (cdesc != 2) return(0);
3315                Y3nsim = atol(cdes[1]);
3316                #else
3317                printf("setm_nsim: m1qn3 option is not active \n");
3318                return(0);
3319                #endif         
3320        }       
3321        else if (strcmp(cdes[0], "SETM_XINF") == 0      || strcmp(cdes[0], "setm_xinf") == 0)
3322        {
3323                #ifdef YO_M2QN1
3324                Y3valxinf_all();
3325                #else
3326                printf("setm_xinf: m2qn1 (via o_m1qn3) option is not active  \n");
3327                return(0);
3328                #endif         
3329        }
3330        else if (strcmp(cdes[0], "SETM_XSUP") == 0      || strcmp(cdes[0], "setm_xsup") == 0)
3331        {
3332                #ifdef YO_M2QN1
3333                Y3valxsup_all();
3334                #else
3335                printf("setm_xsup: m2qn1 (via o_m1qn3) option is not active  \n");
3336                return(0);
3337                #endif         
3338        }       
3339        else if (strcmp(cdes[0], "RUNM") == 0   || strcmp(cdes[0], "runm") == 0
3340             ||  strcmp(cdes[0], "RUNM2")== 0   || strcmp(cdes[0], "runm2")== 0)
3341        {       
3342                #ifndef YO_M1QN3
3343                printf("runm(2): m1qn3 option is not active \n");
3344                return(0);
3345                #endif
3346                #ifndef YO_M2QN1
3347                if (strcmp(cdes[0], "RUNM2") == 0       || strcmp(cdes[0], "runm2") == 0)
3348                {  printf("runm2: m2qn1 (via o_m1qn3) option is not active \n");
3349                   return(0);
3350                }
3351                #endif                                 
3352               
3353                #ifdef YO_M1QN3
3354                if (YNbItRun<=0)
3355                {        printf("runm(2): number of run iteration not seted; use set_nbiter please\n");
3356                         return(0);
3357                }
3358                if (Y3ddf1<=0)
3359                {       printf("runm(2): expected positive fcost decrease missed; use setm_ddf1\n");
3360                         return(0);
3361                }
3362                if (YioInsertObsCtr<0)
3363                   printf("runm(2): warning : oh oh, run with no obs !!! \n");
3364                YTypeAdjust = ADJUST_M1QN3; //d'office avec M1QN3
3365                #ifdef NEW_STRUCTURE           
3366                RunModelM1QN3 *run = new RunModelM1QN3();
3367                run->nbQuasiStaticParts = Yqs_nbParts;
3368                run->nbItMax = YNbItRun;
3369                run->model = activeProject->activeModel;
3370           if (strcmp(cdes[0], "RUNM") == 0     || strcmp(cdes[0], "runm") == 0)
3371           run->minimizerType = M1QN3;
3372        else
3373        run->minimizerType = M2QN1;
3374
3375                activeProject->mappingStructure();
3376                run->run();             
3377                #else
3378                if (strcmp(cdes[0], "RUNM") == 0        || strcmp(cdes[0], "runm") == 0)
3379                   return(Y3run ('0'));
3380                else
3381                   return(Y3run ('2'));
3382                #endif
3383                #endif
3384        }       
3385        else if (strcmp(cdes[0], "RUNIM") == 0  || strcmp(cdes[0], "runim") == 0
3386             ||  strcmp(cdes[0], "RUNIM2")== 0  || strcmp(cdes[0], "runim2")== 0)
3387        {
3388                #ifndef YO_M1QN3
3389                printf("runim(2): m1qn3 option is not active \n");
3390                return(0);
3391                #endif         
3392                #ifndef YO_VARINCR
3393                printf("runim(2): incremental option (O_VARINCR) is not active \n");
3394                return(0);
3395                #endif
3396                #ifndef YO_M2QN1
3397                if (strcmp(cdes[0], "RUNIM2") == 0      || strcmp(cdes[0], "runim2") == 0)
3398                {  printf("runim2: m2qn1 (via o_m1qn3) option is not active \n");
3399                   return(0);
3400                }
3401                #endif                         
3402                                                                                                       /* - - - - - - - - - - - - - - */                       
3403                #ifdef YO_M1QN3
3404                #ifdef YO_VARINCR
3405                if (YNbItRun<=0)
3406                {        printf("runim(2): number of run iteration not seted; use set_nbiter please\n");
3407                         return(0);
3408                }
3409                if (Y3ddf1<=0)
3410                {       printf("runim(2): expected positive fcost decrease missed; use setm_ddf1\n");
3411                         return(0);
3412                }
3413                if (YNbExtL<=0)
3414                {        printf("runim(2): number of extern loop not seted; use set_nbextl please\n");
3415                         return(0);
3416                }
3417                if (YioInsertObsCtr<0)
3418                   printf("runim(2): warning : oh oh, run with no obs !!! \n");
3419
3420                YTypeAdjust = ADJUST_M1QN3; //d'office avec M1QN3
3421                if (strcmp(cdes[0], "RUNIM") == 0       || strcmp(cdes[0], "runim") == 0)
3422                   return(Yc3_run ('0'));
3423                else
3424                   return(Yc3_run ('2'));
3425                #endif
3426                #endif
3427        }
3428        else if (strcmp(cdes[0], "LTRAJ") == 0  || strcmp(cdes[0], "ltraj") == 0)
3429        {  Yltraj();
3430        }
3431        else if (strcmp(cdes[0], "LSPACE") == 0 || strcmp(cdes[0], "lspace") == 0)
3432        {  Ylspace();
3433        }
3434        else if (strcmp(cdes[0], "LOPERA") == 0 || strcmp(cdes[0], "lopera") == 0)
3435        {  Ylopera();
3436        }
3437        else if (strcmp(cdes[0], "NMOD") == 0   || strcmp(cdes[0], "nmod") == 0)
3438        {  if (cdesc != 2)      return(0);
3439                 printf("^^^^^^^ %i est le numero du module %s \n", Yimod(cdes[1])+1, cdes[1]);
3440        }                       
3441        else if (strcmp(cdes[0], "LMOD") == 0   || strcmp(cdes[0], "lmod") == 0)
3442        {  Ylmod(cdesc, cdes);
3443        }
3444        else if (strcmp(cdes[0], "LMOCOP") == 0 || strcmp(cdes[0], "lmocop") == 0)
3445        {  Ylmocop();
3446        }
3447        else if (strcmp(cdes[0], "NNET") == 0   || strcmp(cdes[0], "nnet") == 0)
3448        {
3449                #ifdef YO_NETWARD
3450                if (cdesc != 2) {printf("nnet: syntax is nnet name\n"); return(0);}
3451                printf("^^^^^^^ %i est le numero du reseau %s \n", Yinet(cdes[1])+1, cdes[1]);
3452                #else
3453                printf("nnet: netward option is not active \n");
3454                return(0);
3455                #endif         
3456        }                       
3457        else if (strcmp(cdes[0], "LNET") == 0   || strcmp(cdes[0], "lnet") == 0)
3458        {
3459                #ifdef YO_NETWARD
3460                Ylnet();
3461                #else
3462                printf("nnet: netward option is not active \n");
3463                return(0);
3464                #endif         
3465        }
3466        else if (strcmp(cdes[0], "SAVESTATE") == 0      || strcmp(cdes[0], "savestate") == 0)
3467        {       /* syntaxe:             [0]                        [1]    [2]      [3]   [4]          [5]                    [6]              [7]
3468                                                                savestate objname s(ortie) oaxis pdt {a(scii), b(inaire)} {0, 1, 2, 3} [filename] */
3469                if (cdesc < 7)
3470                {        printf("savestate: syntax error: savestate objname numout oaxis pdt {A, B} {0, 1, 2, 3} [filename]\n");
3471                         return(0);
3472                }
3473                                       
3474                YioModulot = OFF;               
3475                if (cdes[4][strlen(cdes[4])-1] == '%')
3476                {        YioModulot = ON;
3477                }
3478
3479                //if (atoi(cdes[4])<0 || atoi(cdes[4])>YNBALLTIME)
3480                if (atoi(cdes[4])<0) //pdt
3481                {        // les pas de temps vont de 1 a YNBALLTIME,
3482                   //   et 0:=> tous les pas de temps (pour les modules temporise)
3483                         //printf("savestate: out of time, must be 0 (for all) or in [1, %i]\n", YNBALLTIME);
3484                         printf("savestate: out of time, must be 0 (for all) or greater\n");
3485                         return(0);
3486                } //test refait dans Yio_savestate, car il faut apprecier nballtime selon la trajectoire
3487
3488                YioWrite = ON; /*=>*/ YioRead = OFF;            /* on s'apprete a ecrire */
3489               
3490                YioState = atoi(cdes[2]); /* si 0 alors tous les states sinon, que celle demandee */
3491               
3492                YioAscii=YioBin=OFF;
3493                if      (cdes[5][0]=='a' || cdes[5][0]=='A') YioAscii=ON;
3494                else if (cdes[5][0]=='b' || cdes[5][0]=='B') YioBin  =ON;
3495                               
3496                YioAxes=YioTime=OFF;
3497                if      (cdes[6][0]=='1')  YioAxes=ON;
3498                else if (cdes[6][0]=='2')  YioTime=ON;
3499                else if (cdes[6][0]=='3') {YioAxes=ON; YioTime=ON;}
3500
3501                if (cdesc==7)
3502                {       if (YioBin)
3503                        {        printf("savestate: only ascii coding allowed if no file provided\n");
3504                           return(0);
3505                        }
3506                        codret = Yio_savestate(cdes[1], cdes[3], atoi(cdes[4]), "stdout");
3507                }
3508                else if (cdesc==8)
3509                        codret = Yio_savestate(cdes[1], cdes[3], atoi(cdes[4]), cdes[7]);
3510                else
3511                {       printf("savestate: syntax error\n");
3512                        return(0);
3513                }
3514                return(codret);
3515        }
3516        else if (  strcmp(cdes[0], "LOADSTATE") == 0    || strcmp(cdes[0], "loadstate") == 0
3517                                        || strcmp(cdes[0], "LOADOBS")   == 0    || strcmp(cdes[0], "loadobs")   == 0)
3518        {       /* syntaxe:             [0]                      [1]    [2]        [3]   [4]          [5]                   [6]   [7]           [8]
3519                                                                load...  nmmod s(ortie) oaxis  pdt {a(scii), b(inaire)} {0, 1} nmfile {f(loat), d(ouble)
3520                                                                 cas YioAxes                                     ----- cas non YioAxes -----
3521                                                                 di  dj   dk                                            Di  di   Dj   dj   Dk   dk
3522                                                                [9] [10] [11]                                    [9] [10] [11] [12] [13] [14]
3523                */
3524                if (cdesc < 9)
3525                {        printf("%s: syntax error #1\n", cdes[0]);
3526                         return(0);
3527                }               
3528                //if (atoi(cdes[4])<0 || atoi(cdes[4])>YNBALLTIME)
3529                if (atoi(cdes[4])<0)
3530                {        /* les pas de temps vont de 1 a YNBALLTIME,
3531                      et 0:=> tous les pas de temps (pour les modules temporise) */
3532                         //printf("%s: out of time, must be 0 (for all) or in [1, %i]\n", cdes[0], YNBALLTIME);
3533                         printf("%s: out of time, must be 0 (for all) or greater\n", cdes[0]);
3534                         return(0);
3535                }
3536
3537                YioWrite = OFF; /*=>*/ YioRead = ON;            /* on s'apprete a lire */
3538               
3539                YioState = atoi(cdes[2]); /* si 0 alors tous les states sinon, que celle demandee */
3540               
3541                YioAscii=YioBin=OFF;
3542                if      (cdes[5][0]=='a' || cdes[5][0]=='A') YioAscii=ON;
3543                else if (cdes[5][0]=='b' || cdes[5][0]=='B') YioBin  =ON;
3544                else
3545                {        printf("%s: error on coding type, must be A for ascii or B fo Binary\n", cdes[0]);
3546                         return(0);
3547                }               
3548                               
3549                YioAxes=OFF;           
3550                if                      (cdes[6][0]=='1')  YioAxes=ON;
3551
3552                YioTime=OFF;
3553                if      (cdes[4][0]=='0')  YioTime=ON;
3554               
3555                if      (cdes[8][0]=='f' || cdes[8][0]=='F') YioszReal=sizeof(float);
3556                else if (cdes[8][0]=='d' || cdes[8][0]=='D') YioszReal=sizeof(double);
3557                else
3558                {        printf("%s: error on real type, must be F for float or D for double\n", cdes[0]);
3559                         return(0);
3560                }       
3561               
3562                /* prise en compte eventuelle d'un décalage */
3563                //was:     YioDi=YA1;    #ifdef YA2 YioDj=YA2; #endif     #ifdef YA3 YioDk=YA3; #endif
3564                /* multi :
3565                if (cdes[1][0] != '*')
3566                {  wimod = Yimod(cdes[1]);
3567                   if (wimod<0)
3568                   {    printf("%s: unknwon modul name (%s) \n", cdes[0], cdes[1]);
3569                            return(0);
3570                   }
3571                   YioDi=YTabMod[wimod].axi; YioDj=YTabMod[wimod].axj;YioDk=YTabMod[wimod].axk;
3572                }*/
3573                YioDi=YioDj=YioDk=0;    /* multi: lors du load on positonnera ces valeurs selon le module
3574                                                dans la mesure ou le user ne les aura pas valoriseed    */
3575                Yiodi=Yiodj=Yiodk=0;
3576                if (!YioAxes)           /*  Di  di   Dj   dj   Dk   dk  */
3577                {                                                               /* [9] [10] [11] [12] [13] [14] */
3578                  if (cdesc==10 || cdesc==12 || cdesc==14 || cdesc>15)
3579                        {        printf("%s: syntax error #2\n", cdes[0]);
3580                                 return(0);
3581                        }               
3582                        if (cdesc>10)
3583                        {  YioDi=atoi(cdes[9]); Yiodi=atoi(cdes[10]);} 
3584                        if (cdesc>12)
3585                        {  YioDj=atoi(cdes[11]); Yiodj=atoi(cdes[12]);} 
3586                        if (cdesc>14)
3587                        {  YioDk=atoi(cdes[13]); Yiodk=atoi(cdes[14]);}
3588                }
3589                else /*(YioAxes :   di  dj   dk                         */
3590                {                                                               /* [9] [10] [11]      */
3591                        if (cdesc>12)
3592                        {        printf("%s: syntax error #3\n", cdes[0]);
3593                                 return(0);
3594                        }                       
3595                        if (cdesc>9)   
3596                        {        Yiodi=atoi(cdes[9]);}
3597                        if (cdesc>10)   
3598                        {        Yiodj=atoi(cdes[10]);}
3599                        if (cdesc>11)   
3600                        {        Yiodk=atoi(cdes[11]);}
3601                }
3602                                                                                               
3603                if (strcmp(cdes[0], "LOADSTATE") == 0   || strcmp(cdes[0], "loadstate") == 0)
3604                {        codret = Yio_load(YIO_LOADSTATE, cdes[1], cdes[3], atoi(cdes[4]), cdes[7]);
3605                }
3606                else if (strcmp(cdes[0], "LOADOBS")   == 0      || strcmp(cdes[0], "loadobs")   == 0)
3607                {        codret = Yio_load(YIO_LOADOBS, cdes[1], cdes[3], atoi(cdes[4]), cdes[7]);
3608                }
3609                return(codret);
3610        }
3611        else if ( !strcmp(cdes[0], "OUTOOBS") || !strcmp(cdes[0], "outoobs")
3612               || !strcmp(cdes[0], "OUTOEBX") || !strcmp(cdes[0], "outoebx") )
3613        {       /* syntaxe:             [0]                     [1]    [2]        [3]     [4]  ...
3614                                                                outoobs  nmmod s(ortie) pdt1  pdt2 ...
3615                                                                outoebx  nmmod s(ortie) pdt1  pdt2 ... */
3616                if (cdesc < 4)
3617                {        printf("%s: syntax error, argument missing\n", cdes[0]);
3618                         return(0);
3619                }
3620               
3621                if (strcmp(cdes[0], "OUTOOBS") == 0     || strcmp(cdes[0], "outoobs") == 0)
3622                {       codret = Youtoobs(YIO_OUTOOBS, cdesc, cdes);
3623                }
3624                else if (strcmp(cdes[0], "OUTOEBX")   == 0      || strcmp(cdes[0], "outoebx")   == 0)
3625                {       codret = Youtoobs(YIO_OUTOEBX, cdesc, cdes);
3626                }
3627                return(codret);         
3628        }
3629        else if (strcmp(cdes[0], "lobs") == 0   || strcmp(cdes[0], "LOBS") == 0)
3630        { /* syntaxe:  lobs [trajname] */
3631    if (cdesc >2)       return(0);
3632          if (cdesc==1) Ylistobs(YNBTRAJ);
3633          else
3634          { w1 = Yitraj(cdes[1]);
3635            if (w1<0)
3636            {  printf ("lobs %s: unknwon trajectorie name \n", cdes[1]);
3637               return(0);
3638            }
3639            Ylistobs(w1);
3640          }     
3641        }
3642        else if (strcmp(cdes[0], "setn_psig") == 0      || strcmp(cdes[0], "SETN_PSIG") == 0)
3643        {
3644                #ifdef YO_NETWARD               
3645                /* syntaxe: setn_psig mx dmin scale offset */
3646                if (cdesc != 5) return(0);
3647                Ynet_setpsig(atof(cdes[1]), atof(cdes[2]), atof(cdes[3]), atof(cdes[4]));
3648                #else
3649                printf("netward option is not active \n");
3650                return(0);
3651                #endif                                         
3652        }
3653        else if (strcmp(cdes[0], "setn_plin") == 0      || strcmp(cdes[0], "SETN_PLIN") == 0)
3654        {       
3655                #ifdef YO_NETWARD               
3656                /* syntaxe: setn_plin dmin dmax th */
3657                if (cdesc != 4) return(0);
3658                Ynet_setplin(atof(cdes[1]), atof(cdes[2]), atof(cdes[3]));             
3659                #else
3660                printf("netward option is not active \n");
3661                return(0);
3662                #endif         
3663        }
3664        else if (strcmp(cdes[0], "setn_activ") == 0     || strcmp(cdes[0], "SETN_ACTIV") == 0)
3665        {       
3666                #ifdef YO_NETWARD               
3667                /* syntaxe: setn_activ nmnet {siglin sigsig} */
3668                if (cdesc != 3) return(0);
3669                if (Yinet(cdes[1])<0)
3670                {  printf("setn_activ: bad netward name\n"); return(0);
3671                }
3672                if       (strcmp(cdes[2],"siglin")==0 || strcmp(cdes[2],"SIGLIN")==0)
3673                                                YTabNet[Yinet(cdes[1])].activ = SigLin;         
3674                else if (strcmp(cdes[2],"sigsig")==0 || strcmp(cdes[2],"SIGSIG")==0)
3675                                                YTabNet[Yinet(cdes[1])].activ = SigSig;
3676                else
3677                {  printf("setn_activ: bad function name\n"); return(0);
3678                }
3679                #else
3680                printf("netward option is not active \n");
3681                return(0);
3682                #endif         
3683        }
3684        else if (strcmp(cdes[0], "dispn_plin") == 0     || strcmp(cdes[0], "DISPN_PLIN") == 0)
3685        {       
3686                #ifdef YO_NETWARD               
3687                Ynet_displin();                 
3688                #else
3689                printf("netward option is not active \n");
3690                return(0);
3691                #endif         
3692        }
3693        else if (strcmp(cdes[0], "dispn_psig") == 0     || strcmp(cdes[0], "DISPN_PSIG") == 0)
3694        {       
3695                #ifdef YO_NETWARD               
3696                Ynet_dispsig();                 
3697                #else
3698                printf("netward option is not active \n");
3699                return(0);
3700                #endif         
3701        }
3702        //!! adding quasi static command
3703        else if (strcmp(cdes[0], "set_qs_parts") == 0)
3704        {
3705                #ifdef NEW_STRUCTURE
3706        if (cdesc==2)
3707           {
3708        Yqs_nbParts = atoi (cdes[1]);
3709           }
3710                #else
3711                printf("New structure not activated. \n");
3712                #endif
3713        }
3714
3715        else if (strcmp(cdes[0], "set_prompt") == 0     || strcmp(cdes[0], "SET_PROMPT") == 0)
3716        {       
3717                if (cdesc==2)
3718                                strncpy(YPrompt, cdes[1], STRSIZE20);
3719                else
3720                                YPrompt[0]='\0';
3721        }
3722        else if (strcmp(cdes[0], "SET_IOSEP") == 0      || strcmp(cdes[0], "set_iosep") == 0)
3723        {
3724    /*if (cdesc==1)
3725    {  YioSep[0]='\0';
3726       return(1);
3727    }
3728    if (cdesc!=2)
3729                {        printf("set_iosep: need no more than a single string parameter\n"); icicicici
3730                         return(0);
3731                }
3732    if (cdes[1][0]!='"' || cdes[1][strlen(cdes[1])-1]!='"')
3733                {        printf("set_iosep: string parameter must be delimited by \"\n");
3734                         return(0);
3735                }
3736    strcpy(YioSep, cdes[1]);*/
3737                if (cdesc==2)
3738                {        //strncpy(YioSep, cdes[1], STRSIZE20);
3739       //on va copier caractere par caractere jusqu'à STRSIZE20 maximum
3740       //en substituant certains caracteres speciaux (\n, \t, ..?) par leur equivalent
3741       w1=w2=0;
3742       while (cdes[1][w1]!='\0' && w1<STRSIZE20)
3743       {        if (cdes[1][w1]=='\\')
3744                {  if      (cdes[1][w1+1]=='n') {YioSep[w2]='\n'; w1+=2; ++w2; continue;} //new line
3745                   else if (cdes[1][w1+1]=='t') {YioSep[w2]='\t'; w1+=2; ++w2; continue;} //horizontal tab
3746             //...??? cf .../UDEV/specar.c
3747          }
3748          YioSep[w2]=cdes[1][w1]; ++w1; ++w2;
3749       }
3750    }
3751                else
3752                                YioSep[0]='\0';
3753        }
3754        else if (strcmp(cdes[0], "LOAD_INST") == 0 || strcmp(cdes[0], "load_inst") == 0)
3755        {       
3756          strcpy(fileinst, cdes[1]);                   
3757          if ((fpinst = fopen(fileinst, "r")) <= 0)
3758          {      printf ("file %s not found \n", fileinst);
3759                   return(0);
3760          }
3761          nbenrlus = 0;
3762          ++Yrecurlev;
3763                if (!Yload_inst(fpinst, fileinst, &nbenrlus)) // on s'arrete a la 1ere erreur,
3764                {        for (w1=0; w1<Yrecurlev; ++w1) printf("-");
3765                   printf("error found while file %s, line %i. sequence aborted \n", fileinst, nbenrlus);
3766                   --Yrecurlev;                 
3767                   return(0);                                                                                                           
3768                }
3769    --Yrecurlev;
3770        return(1);                     
3771        }
3772        else if (strcmp(cdes[0], "SAMPLEOF") == 0 || strcmp(cdes[0], "sampleof") == 0)
3773        {       //syntaxe: sampleof modP Pinf Psup dP modQ Qinf Qsup dQ nmfile
3774                if (cdesc != 10)
3775                {        printf("sampleof: syntax error: sampleof modP Pinf Psup dP modQ Qinf Qsup dQ nmfile\n");
3776                         return(0);
3777                }
3778                YAL2Run=RUNL2_STD;
3779                return(Ysampleof(cdes[1], atof(cdes[2]), atof(cdes[3]), atof(cdes[4]),
3780                                 cdes[5], atof(cdes[6]), atof(cdes[7]), atof(cdes[8]), cdes[9]));       
3781        }       
3782        else if (strcmp(cdes[0], "SAMPLEOFI") == 0 || strcmp(cdes[0], "sampleofi") == 0)
3783        {       //syntaxe: sampleofi modP Pinf Psup dP modQ Qinf Qsup dQ nmfile
3784                #ifdef YO_VARINCR               
3785                if (cdesc != 10)
3786                {        printf("sampleofi: syntax error: sampleofi modP Pinf Psup dP modQ Qinf Qsup dQ nmfile\n");
3787                         return(0);
3788                }
3789                YAL2Run=RUNL2_INCR;
3790                return(Ysampleof(cdes[1], atof(cdes[2]), atof(cdes[3]), atof(cdes[4]),
3791                                 cdes[5], atof(cdes[6]), atof(cdes[7]), atof(cdes[8]), cdes[9]));       
3792                #else
3793                printf("incremental option (VARINCR) is not active \n");
3794                return(0);
3795                #endif         
3796        }       
3797        else if (  strcmp(cdes[0], "HELP") == 0 || strcmp(cdes[0], "help") == 0
3798                || strcmp(cdes[0], "AIDE") == 0 || strcmp(cdes[0], "aide") == 0 || cdes[0][0]=='?'
3799                )
3800        {       
3801                 if (cdesc>1)
3802                 {      if (cdes[1][0]=='e' || cdes[1][0]=='E' )
3803                                         Yhelp('e');
3804                          else
3805                                         Yhelp('f');
3806                 }
3807                 else
3808                    Yhelp('f');
3809        }
3810        else if (!strcmp(cdes[0], "setstate")    || !strcmp(cdes[0], "SETSTATE"))
3811        {        if (cdesc!=3) return(0);
3812                 if (Yimod(cdes[1])<0)
3813                 {      printf("setstate: unknown modul %s \n", cdes[1]);
3814                                return (0);
3815                 }                                             
3816                 return(Ysetstate_mod(cdes[1], atof(cdes[2])));
3817        }
3818        else if (!strcmp(cdes[0], "setstate_all") || !strcmp(cdes[0], "SETSTATE_ALL"))
3819        {        if (cdesc!=3) return(0);
3820                 return(Ysetstate_mod("Y#A", atof(cdes[1])));
3821        }
3822        else if (strcmp(cdes[0], "PAUSE") == 0 || strcmp(cdes[0], "pause") == 0)
3823        {        getchar();
3824        }
3825        else if (strcmp(cdes[0], "YBID") == 0 || strcmp(cdes[0], "ybid") == 0)
3826        {
3827                        //      Ytryrov();
3828        }
3829        else /* sinon il peut s'agit d'une auto ou d'une user fonction */
3830                 if (!Yauto_call(cdesc, cdes))
3831                                if (!Yuser_call(cdesc, cdes))
3832                                         codret = 0;
3833
3834        return(codret);
3835}
3836
3837/* ////////////////////////////////////////////////////////////////////////////////
3838///////////////////////////// fin fichier Yao.cpp /////////////////////////////////
3839//////////////////////////////////////////////////////////////////////////////// */
3840
3841
3842$CPP_NamespaceEnd
3843$CPP_NamespaceLaunch
3844
3845#endif
Note: See TracBrowser for help on using the repository browser.