Valérie Pascual
email: valerie.pascual@inria.fr

Laurent Hascoët

Mixed-language Automatic Differentiation

Keywords: automatic differentiation, program transformation, mixed-language, interoperability, program analysis AMS Subject Classification: 68N20; 68N99 1. Automatic Differentiation and Language Interoperability

As Automatic Differentiation (AD) usage is spreading to larger and more sophisticated applications, problems arise for codes that use several programming languages. This work describes the issues involved in interoperability between languages and focuses on the main issue which is parameter passing. It describes the architecture of a source transformation AD tool and the algorithms used to differentiate mixed-language codes. A language-independent internal representation enables application of global analysis and strategies on the entire source code. Our goal is that the Tapenade AD tool differentiates codes that mix C and Fortran and generates efficient differentiated code using these strategies.

• Different AD tools may implement very different AD concepts such as overloadingbased versus source-transformation based transformations, or association-by-address versus association-by-name for storage of derivatives values. These concepts are generally not directly compatible. • When selecting the source-transformation concept (for efficiency of the differentiated code), performance of the differentiated code strongly depends on the quality of dataflow analysis, which is improved if it is global on the code. A global analysis with separate AD tools would require inter-tool communication at the level of data-flow analysis, which does not exist at present.

It is possible to produce efficient derivative code for mixed-language applications using single-language AD tools by writing by hand dummy definitions of black-box procedures with the same data flow behavior. However, this method is prone to error and is tedious to apply for large mixed-language applications. It is also possible to automatically interface differentiated codes from different languages with a suitable high-level specification, for instance for MATLAB, and C or Fortran source code. [START_REF] Bücker | A system for interfacing MATLAB with external software geared toward automatic differentiation[END_REF].

Moreover, efficient AD using different tools would require interoperable data-flow analysis between these tools, implying that the tools share their analysis strategy, which is almost never the case. Consequently, we think a better approach is to use a single tool, with a single internal representation and data-flow analysis strategy, therefore converting each source file to this unique representation regardless of its original language. It turns out that Tapenade [START_REF] Hascoët | The Tapenade automatic differentiation tool: Principles, model, and specification[END_REF] provides such an internal representation, accessible at present from C [START_REF] Pascual | TAPENADE for C[END_REF] or Fortran [START_REF] Pascual | Extension of TAPENADE toward Fortran 95[END_REF] sources.

Other AD tools provide a language-independent internal representation. OpenAD provides such a representation based on the XAIF formalism. However, this gives birth to two separate tools, OpenAD/F [START_REF] Utke | OpenAD/F: A modular, open-source tool for automatic differentiation of Fortran codes[END_REF] for Fortran, and ADIC2 [START_REF] Hari | ADIC2: Development of a component source transformation system for differentiating C and C++[END_REF] for C. Still, it seems that there is no deep reason to prevent OpenAD application to mixed-language codes. We are lacking information about a common architecture between TAF and TAC++ [START_REF] Voßbeck | Development and first applications of TAC++[END_REF] that would allow such mixed-language AD.

Rapsodia [8] [9] was the first AD tool to support algorithmic differentiation in tangent mode of mixed-language components, specifically C++ and Fortran. As Rapsodia uses operator overloading, it performs no global analysis of the code. To our knowledge the extension of mixed-language differentiation with Rapsodia to adjoint mode is not yet provided.

Language standards and interoperability

Language standards often say little about interoperability with other languages, leaving much freedom to compilers. As interoperability conventions differ across compilers, mixed-language applications may use an include file such as cfortran.h [START_REF] Burow | Mixed Language Programming[END_REF] to provide a compiler independent interface between C and Fortran procedures and global data.

Still, usage, de facto standards, has progressively evolved, in particular between C and Fortran. The Fortran 2003 standard has specified its interaction with C in more detail. As far as AD is concerned, AD tools should not commit to any specific interoperability strategy, and in particular to parameter-passing behaviors. Those might change with new languages and versions of languages. Instead, an AD tool must be able to handle a small set of behaviors from which one can describe all reasonable ways of parameter-passing.

The main issue raised by analysis and transformation of mixed-language codes is parameter-passing. Other issues are related to matching elements across languages, mainly types and procedures. These matching issues seem less complex than parameterpassing, but are relevant for the further discussion and considered first.

Interoperability of types

Interoperability between types (and between variables of these types) across languages relies on identical memory representations built by compilers. Obviously interoperable types must match in the sense that they have the same structure, number of fields, and these fields must recursively be of interoperable types. Compilers often grant a natural interoperability between structured types. However Fortran 2003 provides the bind attribute to tell at compile time that a Fortran type has a C equivalent. It is essential to identify interoperable types in both languages, in particular because it may help to distinguish candidate interoperable procedures according to the types of their arguments.

Interoperability of procedures

Similarly, interoperability between procedures relies on the compiler identifying the called procedure from another language, usually comparing procedure names, arguments number, and interoperable arguments types. Interoperable procedures in Fortran 2003 are declared with an explicit interface. The bind attribute defines a binding label. It is the name by which the Fortran procedure is known to the C processor. By default, the binding label is the lower-case version of the Fortran name. With Fortran 77 and Fortran 90, different conventions exist to associate both names: by adding an underscore character at the end of the Fortran name, either with the same name, or with the name in uppercase, depending on the compilers.

Parameter-passing strategies

The parameter-passing strategy is already a property of each given, single language. Mixed-language calls may be at the interface between two different parameter-passing strategies, which adds extra complexity.

Inside a given language, parameter-passing may use one of a few classical strategies: call by value, call by reference, call by value-result, call by sharing, call by name, etc. Call by value is the most common strategy. In call by value, the argument expression is evaluated, and the resulting value is copied to the corresponding variable in the function. If the called function overwrites one of its formal arguments, this affects only a local copy of the actual argument, so that the argument passed into the function call is unchanged when the function returns. In call by reference, a procedure receives a reference to a variable and can therefore modify the variable passed as actual argument. Call by valueresult, also named call by copy-restore, is a special case of call by reference. It differs from call by reference when two arguments alias one another. Under call by reference, writing to one will affect the other. Call by value-result gives the function distinct copies, but the result in the callers environment depends on which of the aliased arguments is copied back first. Call by sharing is a terminology used by languages such as Python, Java and other object oriented languages. It is analogous to call by value where the passed value is either the argument when it is of a primitive type or its address when it is an object. Call by name is a strategy where each occurrence of the formal argument is replaced with the actual argument in the style of macro-expansion. This paper only focuses on the parameter-passing strategies used by Fortran and C.

Fortran and C parameter-passing strategies

Consider now the classical mix of Fortran and C. Parameter-passing mechanisms differ in the two languages. In Fortran, call by value-result and call by reference are used. Fortran 2003 introduces the VALUE attribute to specify call by value. In C, call by value is the only parameter-passing mechanism: all parameters are passed by value. In particular when an array is passed to a procedure, a pointer is passed: it is the address of the first element. In C, one simulates call by reference by passing a pointer to this parameter.

In mixed-language calls, the caller and the called procedures must agree on how parameters are passed, with explicit interfaces of the C procedures called from Fortran. The default parameter-passing mechanism between Fortran and C is call by reference. Inside a C procedure, all arguments of a Fortran call are represented by pointers, except the arguments corresponding to parameters with the VALUE attribute.

We believe that every mixed-language parameter-passing strategy used with Fortran and C can boil down to a few simple behaviors at the time of entry into and return from the called procedure. At call time, we define what we call the passed argument, which may be the actual argument, or the memory pointed to by the actual argument, or conversely the address of the actual argument, depending on the mixed-language strategy that must be captured. Then the internal memory corresponding to this passed argument is copied into the internal memory corresponding to the called procedure's formal argument. At return time, the internal memory corresponding to the formal argument may be either copied back to the actual parameter, or not copied in which case it will vanish when the called procedure is popped from the call stack. When there is a back copy, it follows the link from the passed argument back to the actual argument: if they are the same, the copy is written into the actual argument, and if the passed argument is the destination of the actual, then the copy is written at the address designated by the actual argument. Fig. 1 illustrates these behaviors for a few representative multi-language calls, and also for pure Fortran calls, distinguishing the scalar case from the array case, and for a C call using pointers simulating a call by reference. For each situation, we explicit the choice of the passed argument and the choice about back copy that implement the desired behavior. In anticipation on the next section, Fig. 1 also shows, for each situation, the Translator object used by Tapenade to specify these choices to the data-flow analyses.

Data-flow analysis of mixed-language applications

Static data-flow analysis [START_REF] Muchnick | Advanced Compiler Design and Implementation[END_REF] is an essential step to achieve efficient differentiation with a source-to-source AD tool. The goal of static data-flow analysis is to provide information on the data computed and returned by a program without knowing the values of the program's run-time inputs. In other words, static data-flow analysis extracts useful information on the program at compile-time, this information being thus valid for any run-time execution on any inputs. Obviously, such an information can only be partial and must often resort to the undecidable "I don't know" reply in addition to "yes" or "no". Abstract Interpretation [START_REF] Cousot | Abstract interpretation based formal methods and future challenges[END_REF] is a framework for static data-flow analysis in which the values computed in the original code are replaced with abstract values containing the propagated abstract information. One classical example of the abstract information that one may want to propagate is the interval in which the run-time value will range, or the set of possible destinations of each pointer variable. Starting from some abstract information on the inputs or outputs (which may be empty), abstract interpretation propagates it through the program, possibly guided by its control-flow structure. Instead of a true execution of the program, possible only at run-time, this propagation must stand for every possible execution path. Some data-flow analyses follow these paths forwards, others need to follow them backwards. As call graphs may be cyclic in general (recursivity), and flow graphs may be cyclic (loops), completion of the analysis requires the reaching of a fixed point both on the call graph and on each flow graph. The abstract domain in which the propagated information range is designed in such a way that this fixed point is reached in a finite number of iterations. Most of the classical data-flow analyses prove useful for AD as well as specific analyses such as activity and TBR analyses [START_REF] Hascoët | To be recorded" analysis in reverse-mode automatic differentiation[END_REF][START_REF] Pascual | Native handling of message-passing communication in dataflow analysis[END_REF]. In most AD-specific data-flow analysis the abstract information is, for each variable v a boolean value (e.g. does v influence the output in a differentiable way?) or a set of other variables (e.g. which input variables have a differentiable influence on v?).

To be accurate, data-flow analysis should be flow-sensitive and context-sensitive. In a context-sensitive analysis, each procedure uses a context that is built from the information available at its call sites. Even when choosing a generalization, i.e., using only one context to summarize all call sites, this context allows the analysis to find more accurate results inside the called procedure. Flow-sensitive analysis operates at the flow graph level of a procedure. In a flow-sensitive analysis, the propagation of data-flow information follows an order compatible with the flow graph, thus respecting possible execution order. The present study does not interfere with flow-sensitivity of analysis, as flow-sensitivity operates at the level of an individual procedure, which is written in a single language. On the other hand, it is tightly related to context-sensitivity, as the frontier between two distinct implementation languages is precisely located at procedure calls.

In a context-sensitive analysis, each procedure is analyzed with one (or many) context that is built from the information available at its call sites. One can build one context that summarizes all call sites, through generalization, or one can build several contexts for each call site, making the choice of specialization. The AD tool Tapenade, for example, lets the user choose by adding directives in the source that activate specialization for a procedure [START_REF] Hueckelheim | Algorithmic differentiation of code with multiple context-specific activities[END_REF], thus allowing the analysis to find more accurate results inside the called procedure.

Context-sensitive analysis has an essential role to play with mixed-language applications, as the context may belong to a different programming language with a different parameter-passing strategy. In the following sections, we will investigate how to extend our AD tool to analyze mixed-language codes, and how differentiation must be adapted.

Extension of Tapenade algorithms for interoperability

Tapenade was originally designed to support different imperative languages. The motivation was to share the concept of the tool and its implementation between these languages (at present, Fortran and C). We believe that this architecture also lets us deal with mixed-language source with a minimal implementation effort, affecting only a few components of the tool.

Tapenade represents a code as a call graph whose nodes represent procedures, and arrows represent calls. Each call graph node contains a flow graph, in which nodes are blocks of elementary instructions (in particular calls), and arrows represent control jumps. At present, Tapenade used on C or on Fortran source builds an internal representation of the same nature, using the same components for procedures, instructions, variables, types, etc. We exploit this common representation to deal with mixed-language codes, in particular mixing Fortran and C.

We first take a look at matching of types and procedures. Two interoperable entities are represented with the same internal representation in the AD tool. This representation distinguishes each component of structured types, and distinguishes pointer variables from their pointee destination variables. The representation of arrays, on the other hand, does not distinguish array elements, and therefore we need not worry about their possibly different memory layout in Fortran and C. Sometimes it is not possible to preserve this nice structural matching, for instance for the complex Fortran type which should match a 2-fields structure in C. Then the correspondence must be enforced by implementation, and possibly incurs some degradation of information.

The question of procedure matching amounts to finding, for a given procedure call, the node of the call graph that will be effectively called. This depends on the mixed-language conventions on procedure names and on type matching. Procedure name conventions may vary, and Tapenade offers parameterization to define one convention, using commandline arguments or directives at the call site. It also interprets attributes of Fortran 2003.

For instance, these parameters let us specify that inside a Fortran code all calls to a procedure named FOO will connect to a C procedure named foo . Type matching may also play an important role here, when the number and types of argument may help disambiguate between several candidate procedure matches.

C calls

REAL X SUBROUTINE GEE(V) . . . REAL V CALL GEE(X) -Passed argument is X -Upon return, abstract information on V is copied back into X Translator: V -> X (Back copy) REAL Y( 1 0 0 ) SUBROUTINE GEE(B) . . . REAL B( 2

Mixed-language data-flow analysis

Parameter passing comes into play during data-flow analysis. In our tool's implementation, all data-flow analyses (e.g. in-out, activity, liveness) inherit from a base analysis class that provides primitives to transfer data-flow information between a caller procedure and a callee. Specific analyses only differ in the nature of the propagated information and in the way these propagated values behave for a handful of classical combination operations. For instance, in-out analysis finds in-out sets, which contain for each procedure the smallest possible sets of variables that may or must be read or overwritten by this procedure. Activity analysis propagates forward the set of the variables that depend on some independent input. It propagates backwards the set of the variables that influence some dependent output in a differentiable way. Most adaptions to mixed-language code must be done in the base analysis class. This information transfer is driven by an object we call a Translator, which describes how actual arguments are matched with formal arguments.

We consider scalars and arrays as elementary components. If we were to distinguish data-flow information of different cells of arrays, we would have to evaluate and compare all array indices in the code. This is, in general, out of reach of a static analysis. If an access to an element A(i) or to an array slice A(lower:upper:stride) of an array A modifies the data-flow information, our choice is to conservatively impact the complete array A. However, in Fortran EQUIVALENCE or COMMON, we consider each fragment as an elementary component.

Variables, and in particular those in arguments, may have a finer structure. Languages have introduced variables of structured type and pointers. Since the data-flow properties that we analyze may be different for each component of these structured objects, we distinguish all of their elementary components. Recursively, a structured type has one component per field, and a pointer type has two components corresponding to the pointer itself and to the pointer destination.

For example, a formal argument of type mystruct *arg where mystruct is a record: struct mystruct { int numElems; float *elems; } is represented by four elementary formal arguments : the top-level arg which is a pointer to a structured type with two elementary components, arg->numElems, arg->elems. In addition, the fourth elementary argument represents the destination *(arg->elems). While compilers do not require such a fine structure, abstract interpretation requires it. The data-flow information may then be more accurate on each component.

To each elementary formal argument of the called procedure, the Translator associates the corresponding elementary actual argument at the call site, which is either an expression or an elementary variable known to the calling procedure. In addition, the Translator associates to each elementary formal argument a Back copy boolean that specifies whether the corresponding data-flow information must be copied upon return. This boolean is set to "true" if the argument is passed by reference, or if the passed argument is the memory pointed to by the argument, or the address of the argument. For each example situation in Fig. 1, the Translator that implements the desired behavior is shown below the textual description of the behavior, as a set of arrows from formal elementary argument to actual elementary argument and back copy boolean. The rule of thumb is that the Translator associates the formal argument with the passed argument.

The "Fortran calls C" situation deserves further comment: since the C formal argument is a pointer to a float, there are in fact two elementary formal arguments, one for a and one for *a. The same happens for "C calls C". As a is associated with the passed argument &X, *a is naturally associated with *(&X) in other words with X. The actual value of (or information regarding) X is propagated to the callee through this second elementary argument. Consequently, even if no back copy is done upon return into &X itself, every write into *a in foo is automatically reflected into X.

The way each data-flow analysis, which computes a given data-flow value, uses the specification from the Translator can be sketched as follows: immediately before the call, and for each elementary formal argument (left column of Translator), we retrieve the corresponding elementary actual argument (right column), and we retrieve the current data-flow value for it. The initial data-flow value of the elementary formal argument is set to this retrieved value. Analysis can then run on the called procedure. Upon return from the call, the top-level elementary arguments that bear the "No back copy" retain the data-flow value they had before the call. For all other elementary arguments the data-flow value of the elementary formal argument upon return is copied back into the data-flow value of the elementary actual argument. This description applies to forward data-flow analyses. Adaption to backward analyses requires minor technical changes.

Mixed-language differentiation

The impact of mixed-language differentiation on the tangent mode of differentiation is quite limited. In tangent mode, the data-flow of derivatives follows closely the dataflow of primal variables. Therefore the strategy implemented in the primal code to pass primal variables can be simply reused for the tangent derivatives. There is a minor issue when differentiating a call to a function F which returns a value that has a derivative. Our convention is to pass this derivative as the return value of the differentiated F D. Therefore F D must be called with an extra argument to pass the primal result of F. This extra argument and its corresponding passed parameter must be declared and used according to the parameter-passing mechanism, e.g. by passing the address of the argument when F is a Fortran function and the call site is in C, as shown in Fig. 2. The issue is already present in mono-language C code.

REAL FUNCTION F( t ) REAL t . . . END REAL FUNCTION F D ( t , td , f )

REAL t , td , f . . . END e x t e r n f l o a t f ( f l o a t * t ) ;

v o i d f o o ( f l o a t * x ) { * x = f ( x ) ; } e x t e r n f l o a t f d ( f l o a t * t , f l o a t * td , f l o a t * f ) ; v o i d f o o d ( f l o a t * x , f l o a t * xd ) {
f l o a t t m p r e s u l t ; * xd = f d ( x , xd , &t m p r e s u l t ) ; * x = t m p r e s u l t ; } Problems arise for adjoint differentiation. Since a use of a variable in the primal code may become an overwrite of its adjoint variable, parameter passing method must be adapted. Consequently, the adjoint of an argument passed by value must sometimes be passed by reference. This is a general problem with pass-by-value parameters. It must be dealt with for mixed-language code as well as with mono-language code that uses pass-by-value.

In general, adjoint differentiation of a formal parameter that is passed by value requires two adjoint variables. A simple way to justify that is to view the formal parameter inside the called procedure as a new copy of the passed parameter. Consider for illustration the parameter u of procedure BAR in Fig. 3: overwrites of u in BAR do not affect the actual argument *x in foo. In the body of BAR, we will consider that u is now a local variable, whereas the first formal argument is renamed as u0. We conceptually add an initial instruction : u = u0 ; at the beginning of BAR. Applying the standard adjoint method, we introduce ub, the adjoint variable of u, initialized to zero and then used and updated in the body of the adjoint BAR B. At the end of BAR B, ub is added to ub0 (the adjoint of the first formal argument), as the contribution to the adjoint of ub0 (i.e. equivalently *xb) of the adjoint of its copy u. This is nothing but the standard adjoint of the initialization instruction of u. In order to propagate the resulting value of u0b to the calling subroutine, the passed actual argument xb must be a reference, and the argument ub0 of BAR B must not inherit the VALUE attribute from u. Because of the order of assignments, increments and updates of ub and ub0, there is in general no way of implementing this mechanism with a single adjoint variable ub. In the particular case where the passed-by-value argument is not modified in BAR, a single adjoint variable is enough, which must be passed by reference.

We focused on the main issue with mixed-language codes, which is parameter passing. We did not discuss interoperability of global variables. A Fortran variable that interoperates with a C variable is represented internally in the same way as a Fortran variable that is equivalenced with another Fortran variable with an equivalence declaration. Interoperable global variables, for instance using a common declaration or the bind attribute of Fortran, and an extern C declaration, share the same memory location. Inside the Tapenade internal representation these variables occupy the same memory location.

Application of Automatic Differentiation to CalculiX

To validate our extension of Tapenade for interoperability, we differentiate a real size mixed-language application, the CalculiX finite element library [START_REF] Dhondt | The Finite Element Method for Three-Dimensional Thermomechanical Applications[END_REF], written in C and Fortran77/Fortran90, which does not use the Fortran 2003 interoperability standard. A C include file contains the prototypes of the Fortran subroutines that are called from C. The main procedure is in C. The analysis of the source code with Tapenade detects 719 mixed-language calls of 178 different Fortran subroutines from C. No C procedure is called by a Fortran procedure. All data transfer is through arguments of procedure calls. No global variable or common is used to transfer data between C and Fortran. In our test case, the head procedure for differentiation is linstatic, which is called by the main procedure.

In order to measure the improvements that mixed-language differentiation brings, we will consider three differentiation approaches.

• Separate AD (Sec. 5.1) is the only approach available at a reasonable cost using only single-language AD tools. It will serve as a reference.

• True mixed-language AD can be achieved with single-language AD tools at a significant development cost. We describe this in Sec. 5.2. • We automate mixed-language AD to achieve the same performance with a much lower development cost. We describe this in Sec. 5.3 With all methods, we use the option -context to generate automatically the context code to call the differentiated procedure linstatic d. This option extends the data-flow analysis to the complete code passed to the differentiation command. It also declares, allocates, and initializes the input and output derivatives values [START_REF] Hascoët | Source-to-source adjoint algorithmic differentiation of an ice sheet model written in C[END_REF]. Using this option requires that all source code is given to the AD tool, including not-to-differentiate code from the main procedure to the call to linstatic. Therefore 79 C source files (42 000 lines of code) and 627 Fortran source files (160 000 lines of code) are passed to the differentiation commands. We choose the default behavior of Tapenade, which is generalization, to analyze the procedures with different contexts at different call sites.

Separate AD

Separate AD is done in two steps. First we differentiate only the C source files, then we differentiate the Fortran source files. As the top procedure to differentiate is in C, we differentiate the C files with the command line: tapenade -head "linstatic(co maxvm pnorm)>(co maxvm pnorm)" -context *.c and consider all the Fortran subroutines as external subroutines.

When differentiating only the C code, the analyses of external procedure calls make conservative assumptions and so are less accurate. The external procedure is supposed to communicate with the calling code only through the calling arguments. All actual arguments are supposed to be read inside the external procedure, and all actual arguments that are variables are supposed to be overwritten. Any variable argument of a differentiable type is assumed to return a value that depends on the input value of every argument of a differentiable type. Therefore a differentiated argument is created for any argument of a differentiable type. The differentiated C code that we obtain calls 28 differentiated external subroutines.

We then differentiate the Fortran files, given the list of these 28 Fortran subroutines called from C, with the command line: tapenade -fixinterface -head "..." -head "..." ... *.f

To be consistent with differentiation of the C code, each of these Fortran subroutines is differentiated in the most general way, i.e. all outputs with respect to all inputs. We use Tapenade option -fixinterface to prevent it from applying any reduction to these output and input sets.

An extra step is needed to create the executable differentiated code. With separate AD, the Fortran procedure "foo" is differentiated as "foo d" in a file "foo d.f". The called name of "foo" from C is "foo " and the name of the differentiated procedure is "foo d" in the differentiated call. It must be changed to "foo d ". The C calls of the 28 differentiated Fortran procedures must be changed. Finally we compile and link the differentiated object files and the necessary non differentiated object files to obtain the executable differentiated code.

In the performance comparisons of Sec. 5.4, this differentiated code is referred to as "Separate AD". It sets the reference to appreciate the improvements brought by mixedlanguage AD. The next two sections describe how to achieve better performance through mixed-language AD, either manually (a tedious and error-prone approach) or automatically through our new developments.

Tedious manual mixed-language AD

To achieve true efficient mixed-language AD with an AD tool that supports only one language, we must provide some knowledge of the external procedures that are called from the C source code. For each of the Fortran subroutines called from C, we must provide a stub which is a dummy definition written in C. This stub must embody the differentiable data dependences of the actual Fortran procedure, i.e. which outputs depend on which inputs. The first step then differentiates the complete C code, together with all these stubs. In a second step, we must differentiate the Fortran code, according to the activity context discovered by the first step for the Fortran subroutines represented by their stubs. This is made somewhat easier by Tapenade, that emits during differentiation messages of the kind:

(AD09) Please provide a differential of function foo for arguments Arg1=(in;out) Result=(out) Following these messages we build a differentiation command on the Fortran code with as many differentiation heads as needed with the correct dependent and independent parameters. This two-steps method is only applicable when the call tree is easily split in two layers. More steps are required if for instance the Fortran code calls C back. Things may get even worse in the case of recursion. In our application, 28 Fortran subroutines are differentiated and called from C. These 28 Fortran subroutines need a particular attention to define a correct stub for each of them: each parameter must be carefully checked, in particular for subroutines with many parameters. Notice that the stubs must be rewritten if these 28 Fortran procedures are modified, for instance if we want to differentiate a new version of Calculix.

The goal of the present section is to show how tedious this manual approach to mixedlanguage AD can be. As our purpose is to improve the AD tool Tapenade to automate mixed-language AD, we did not invest too much time applying it. We only checked that it eventually provides a differentiated code that is very similar and has the same performance as our new automated mixed-language AD, described in the next section.

Automated mixed-language AD

The different steps above are now replaced with just one step with mixed-language AD. All the C and Fortran source files are analyzed and differentiated at the same time, with the command line: tapenade -head "linstatic(co maxvm pnorm)>(co maxvm pnorm)" -context *.c *.f As we differentiated all the C and Fortran files at the same time, we add the option -java "-mx51200m -Xss2280k" to the Tapenade command to increase the Java process size. This single Tapenade command generates a differentiated code composed of the C linstatic d differentiated procedure and its C calling context, and of all the C and Fortran differentiated procedures. All the generated files are compiled and linked together with the necessary non-differentiated files to build an executable, without any further manual modification. This approach produces a differentiated code which is efficient, i.e. as efficient as the one produced by the approach of Sec. 5.2, at a development cost which is much less than in Sec. 5.2.

Experimental result

Considering run-time and memory use of the differentiated program, there is no reason to expect a significant improvement from approach described in Sec. 5.2 to approach described in Section 5.3. The stub-based approach (5.2) is in principle able to express finely the dependence information, so that performance of the differentiated codes are similar. Approach 5.2 may even perform slightly better, like any approach that involves a great deal of hand modifications. The difference between approaches 5.2 and 5.3 is mainly about comparing a partly manual differentiation process that may take a few work days, with an automated process that takes minutes. In contrast, we provide execution comparisons between separate AD (5.1) and our new proposed mixed-language AD (5.3).

We execute the differentiated codes in tangent mode and measure the run-time and memory on examples provided with CalculiX. We have validated tangent mixed-language AD by comparison with divided differences. Table 1 shows a significant improvement both in run-time and memory usage. In average, the total run-time and the time spent in the linstatic d differentiated procedure is divided by two with mixed-language AD compared with separate AD. This brings the slowdown factor of the differentiated code obtained by mixed-language AD down to 1.5 compared to the primal code.

Table 2 shows some time measurements for AD analyses and differentiation with both methods. Time spent during analyses is 3 to 6 times longer with mixed-language AD because we analyze the complete call graph. This gives more accurate results, as the conservative assumptions for the external procedures with separate AD are replaced with the results of the analyses on the complete Fortran source code of these procedures. The activity analysis through the complete call graph finds the variables that do not need to be differentiated. It detects the variables that do not depend on the independent input variables, and the variables that do not influence the dependent output variables. This is done for each mixed-language call of a procedure, whatever the language of the caller and the callee, and it takes into account the parameter passing strategy for each parameter. This leads to fewer differentiated variables and simplifies the differentiated code, through slicing and partial evaluation. Fewer instructions need to be differentiated as a result. If no formal parameter of a procedure is differentiated, the procedure is not differentiated, so fewer procedures need to be differentiated. Therefore the differentiation itself takes less time. The first benefit that we notice in Table 3 is the reduction of the number of differentiated files and procedures. Let us detail the contents of these generated files. In C, a given source file may define several static variables. The scope of these variables is shared by all the procedures of this file and not by others outside. Consequently, it is not possible to split these files into many, nor to merge them into a single file. The consequence for AD is that we cannot use the Tapenade option that puts all differentiated code into one file, nor can we create one file per differentiated procedure. Differentiated code must follow the file structure of the source code. If a static variable is used in both a source procedure and in a differentiated procedure, it must be defined only once, which means the differentiated file must also contain the source procedure and the definition of this static variable. In CalculiX source code, only one differentiated file contains a copy of a source procedure to respect the file scope of global variables.

With mixed-language AD, the total number of lines is divided by more than half. The accurate analyses reduce the number of differentiated procedures. Only 5 C procedures are differentiated, instead of 21 on a total of 90 in the source code. Among the 12 generated files, 5 files contain differentiated procedures, 6 files contain procedures used in the context call of the linstatic d procedure. The last generated file contains the prototypes of differentiated procedures and is included in other generated files in order to compile them correctly.

The second benefit is observed inside each differentiated procedure. Several C differentiated procedures have fewer differentiated parameters. The last line in Table 3 summarizes the benefit of mixed-language AD: the number of Fortran differentiated subroutines called from C is reduced by a factor of more than 5. Instead of the 28 Fortran subroutines that separate AD has differentiated, or the 28 that manual mixed-language AD have required a stub for, we observe that only 5 are effectively differentiated by our automated approach.

To summarize, mixed-language AD and its accurate analyses on the complete call graph produce a more efficient code, with fewer differentiated procedures, parameters, fewer calls to external Fortran procedures, and fewer differentiated instructions. All these improvements result from the accurate interprocedural analyses of the complete source code. Furthermore no additional hand-written stubs or code is required. Time spent to obtain and validate a mixed-language differentiated code is drastically reduced. Mixedlanguage AD of CalculiX with Tapenade generates a code that compiles without modification, the interoperability convention is automatically used in the differentiated code.

However we still need to improve the generated code if the source code uses an include file such as cfortran.h or the one in CalculiX, and function-like macros to call Fortran subroutines from C, as shown here:

FORTRAN(foo,(co, ...)); With the GNU compiler, this call is expanded in: foo (co, ...); As Tapenade differentiates the C source files after using the C preprocessor, all the macro definitions are lost in the differentiated code, as shown in this piece of differentiated code of CalculiX: foo (co, ...); ... foo d (co, cod, ...); Tapenade offers parameterization to describe the association of Fortran and C procedure names that respects the compiler convention. If the C source files contain macrodefinitions for calling Fortran subroutines, we would like to regenerate a code after postprocessing with the same convention with macro-definitions such as:

FORTRAN(foo,(co, ...)); ... FORTRAN(foo d,(co, cod, ...)); In the current implementation, the differentiated code only respects the interoperability convention of the current compiler.

Conclusion and further work

We extended Tapenade to differentiate codes that mix C and Fortran, with calls in either direction and validated this extension on the CalculiX finite element library. The architecture of Tapenade, with a language-independent internal representation, allowed us to implement this functionality quite easily, with modifications in only a few component of the tool. Most adaptions to mixed-language code concern the data-flow analyses used by Tapenade and the data-flow information transferred between a caller procedure and a callee. This information transfer is driven by a translator which describes the parameter-passing strategy.

Measurements on the generated code of CalculiX show significant improvements with mixed-language AD. As the analyses are more efficient, the differentiated code contains fewer differentiated procedures, variables, and instructions and is only half as long. From a user point-of-view, mixed-language AD avoids a lot of time consuming manual handling to obtain correct differentiated code, and allows a more "automatic" differentiation.

Concerning the mixed-language AD of CalculiX, only the tangent code has been validated. The next step will be the validation of the adjoint code that now uses the adjoinable dynamic memory management library ADMM.

Future improvements may concern the differentiation of very large mixed-language codes that take too much space and time, in particular during pointer destination analysis and activity analysis. It turns out that mixed-language applications are often larger than single-language. The natural answer to size problems used in compilers is separate compilation. The question then arises whether we can provide a sort of separate AD. This is a difficult issue as AD heavily relies on global data-flow analysis. This would require a convenient way to provide data-flow information on procedures that are either external or written in a different language. This question would in turn ask for a standardization effort among AD tools and perhaps with compilers.

Figure 1 .

 1 Figure 1. Mixed-language calls and the Translator that implements their behaviors

Figure 2 .

 2 Figure 2. Tangent mixed-language differentiation with Tapenade

Figure 3 .

 3 Figure 3. Mixed-language differentiation with Tapenade, C calling Fortran case

Table 1 .

 1 Run-time and memory performance of the tangent differentiated code using on one hand separate AD and on the other hand mixed-language AD

	Calculix differentiated code execution	Separate AD	Mixed-language AD
	linstatic d run-time	0.104 s	0.057 s
	total run-time	0.122 s	0.067 s
	peak stack size	66.10 KB	48.66 KB
	Calculix C + Fortran code	Separate AD	Mixed-language AD
		(C + Fortran)
	Pointer destinations analysis	25 + 0.02 s	144 s
	In-out analysis	9 + 0.18 s	37 s
	Activity analysis	102 + 0.9 s	440 s
	Differentiation	8.5 + 1.5 s	5.5 s
	Total time	242 + 11 s	750 s

Table 2 .

 2 Time measurements of analyses and differentiations of Calculix C and Fortran code

Table 3

 3 shows some measurements on the differentiated code we obtain with both methods.

	Calculix C code differentiation	Separate AD	Mixed-language AD
	# differentiated files	28	12
	# non differentiated procedures	50	79
	# context procedures	19	6
	# differentiated procedures	21	5
	# lines of differentiated code	42000	19400
	# calls to differentiated Fortran subroutines	28	5

Table 3 .

 3 Comparison of the C part of the differentiated code, using on one hand separate AD and on the other hand mixed-language AD. The original C code consists of 79 files, 90 procedures, and 40000 lines of code. The call graph under the differentiation root contains 80 C procedures.


J Rouquette

J Haines

V Bornand

M Pintard

Ph Papet

J L Sauvajol

Use of Resonance Raman Spectroscopy to study the phase diagram of PbZr 0.52 Ti 0.48 O 3

Keywords: 77, 80, Bh, 71, 35, Aa

Evidence is presented for the first time that the sharp and continuous spectral changes observed in PbZr 0.52 Ti 0.48 O 3 (PZT) between 350 and 10 K with the 647.1 nm wavelength are due to a resonance Raman effect. Such a phenomenon can be explained by means of a self trapped exciton emission oxygen deficient complex (Ti Ti '-V O .. ) of PZT powder whose energy is close to the radiation line of the laser. This kind of approach should also be very useful to distinguish the phase transition sequence for other related ferro/piezoelectric systems.

I. INTRODUCTION

Perovskite PbZr 1-x Ti x O 3 ceramics are the most widely used ferroelectric materials because of their excellent properties. The highest piezoelectric and electromechanical coupling coefficients have been obtained for compositions near the morphotropic phase boundary (MPB) 1 between rhombohedral (R3m) and tetragonal (P4mm) phases (x ≈ 0.48).

The MPB has generated much interest, especially since the discovery of a monoclinic phase 2 (Cm) in the MPB region for temperatures below 300 K. In this monoclinic form, the polarization can be modulated for example as a function of an external applied electric field between the rhombohedral and tetragonal directions based on a polarization rotation mechanism thus providing a possible explanation for this high piezoelectric response 3 .

Additionally, a second monoclinic phase 4 with a doubled unit cell (Cc) has been observed at low temperature (T ≤ 210 K) for PbZr 0.52 Ti 0.48 O 3 . This complex phase diagram around the MPB does not take into account the static disorder of the zirconium and titanium ion displacements 5,6 which introduces the well-known ferroelectric domain structure.

Furthermore, recent experiments based on electron diffraction 5 and neutron diffraction 7 studies, Raman scattering 8 results, as well as theoretical calculations 9 have indicated the existence of an intrinsic short range dynamic disorder over nearly the entire PZT solid solution predominantly due to off-center lead displacements 7,10 . Therefore, the boundaries between the different phases, in particularly close to MPB compositions are still subject to debate. Based on Raman measurements 8,[11][12][13][14] for compositions near the MPB, only minor spectral changes occurring in the temperature-composition range near the MPB were observed. This was associated with a two-phase coexistence 8 as has been the case for more than 30 years.

In this contribution, we investigate the different phase transitions of PbZr 0.52 Ti 0.48 O 3 (PZT) between 10 and 350 K by resonance Raman spectroscopy. Based on the temperature dependence in the frequencies of the vibrational modes, we clearly identified the transformations previously characterized by dielectric measurements [15][16] , X-ray 17 and neutron diffraction 4 . The resonance phenomenon can be explained by the existence of a self-trapped exciton emission of an oxygen deficient complex of PZT powder (Ti Ti '-V O ..

).

Thus, resonance Raman scattering spectroscopy is one of the most useful methods to identify the phonon modes which couple to an electronic system [18][19] . As many perovskite oxides display very similar visible photoluminescence between 2 and 3 eV [20][21] , Raman Resonance Spectroscopy of self-trapped exciton could be used in a similar way to clarify complex phase diagrams of MPB-ferroelectric or -relaxor systems.

II. EXPERIMENTAL

PbZr 0.52 Ti 0.48 O 3 solid solutions was prepared by the conventional solid state reaction from high-purity (>99.9%) oxides via a two-stage calcination process [22][23][24][25][26][27][28] . A first set of ambient-temperature experiments was performed using a Jobin Yvon Labram spectrometer with a 632.8 nm He-Ne excitation line and laser output powers of 8 mW. The laser beam was focused with a 50× lens leading to a spot of approximately 2-3 µm of diameter.

Additional variable-temperature Raman experiments (10-350K) were performed using an Oxford Instrument Microstat closed-cycle helium cryostat. The Raman spectra were obtained with an Argon-Krypton laser (488, 514.5 and 647.1 nm) and a Jobin-Yvon T64000 triple monochromator equipped with an Olympus microscope and a CCD cooled to 140 K. A 50× objective was used to investigate sample regions with a diameter of about 3 µm. The laser output powers were 8 mW. The temperature was measured near the sample using a silicon diode.

III. RESULTS AND DISCUSSION

In a previous study 28 , Raman Spectroscopy with the 647.1 nm excitation line was used as a function of temperature to identify the boundaries between tetragonal and monoclinic (with simple and double-unit cell) ferroelectric phases previously observed in PbZr 0.52 Ti 0.48 O 3 (PZT) by dielectric measurements, X-ray and neutron diffraction. The obtained data were clearly different from the 514.5 nm Raman measurements generally reported in the literature 8,[11][12][13][14] , in which the temperature dependence of the broad vibrational modes was minor. The 647.1 nm Kr + line was used in the previous study 28 as PZT samples are known to absorb rather strongly in the high-energy visible range 30 . A carefully analysis of room temperature Raman spectra of PbZr 0.52 Ti 0.48 O 3 using several sets of excitation lines (488, 514.5, 632.8 and 647.1 nm), Fig. 1, reveals a more interesting phenomenon. On one hand, between 488 nm and 514.5 nm, Raman spectra are almost the same and the broad vibrational modes are at the same position. With respect to these previous results, significant changes are observed for the 632.8 nm and 647.1 nm spectra.

For these latter spectra, the main features are an increase in intensity at low-frequency (150 -300 cm -1 ), and a change in the profile of the band located around 200 cm -1 . However, in the range above 170 cm -1 , the spectra obtained at 647.1 nm (1.92 eV) and 632.8 nm (1.96 eV) are also different. The main differences occur in the region of the broad features located between 170-350 cm -1 and 400-650 cm -1 . Especially, in the spectrum measured at 647.1 nm, one can note the appearance of a new and intense component at 510 cm -1 , of a weak line around 413 cm -1 and the shifts of the two main components located in the 170-350 cm -1 region. In order to explain this difference between the behavior using the high-(488 and 514.5 nm) and low-(632.8 nm and 647.1 nm) energy excitation lines on one hand, and between the 632.8 nm and 647.1 nm spectra on the other hand, one can link the 647.1 nm and 632.8 nm energies (1.92 and 1.96 eV) with the 2.0 eV luminescence observed by Liu et al. at ambient temperature for PbZr 0.52 Ti 0.48 O 3 films and ceramics 29 . Thus, the wavelength of the probe light may be more or less tuned to a resonance excitation of PZT sample. The maximum phonon-intensity in the resonance phenomenon is well-known to occur for energies slightly different from that of the photoluminescence line, which may explain the difference in behaviour for the 632.8 nm and 647.1 nm spectra (j'ai enlever smooth?). The photoluminescence at 2.0 eV was previously assigned by Trepakov et al. to a self trapped exciton emission of an oxygen deficient complex (Ti Ti '-V O ..

) for PLZT ceramics 30 and these authors have also proposed that this emission could be observed in other self-activated ATiO 3 perovskite-structure materials. Note that in our sample, oxygen vacancies can easily be explained at high temperature by the loss of PbO weight during sintering [22][23][24][25][26][27][28] , therefore we have:

V O ↔ V O .. +

2e' and Ti Ti

x + e' ↔ Ti Ti ' where Kröger-Vink notation 31 is used.

Exciton transition interacting with the lattice could then occur between the localized hole V O .. and the localized electron Ti Ti '.

Very recently, Mochizuki et al. provide evidence for the crystal defect origin (oxygen defects and chemical heterogeneity in the surface region) of the photoluminescence of a SrTiO 3 single crystal 32 centered at 2.4 eV which could clearly be modified depending on the oxidizing-reducing atmosphere.

Two sets of Raman spectra obtained between 10 and 300 K with 514.5 and 647.1 nm excitation lines are shown on Fig. 2a and Fig. 2b respectively. The 514.5 nm spectra, Fig. 2a, are in clear accordance with those previously reported in the literature 8,[11][12][13][14] where the temperature effect is clearly minor, which could be associated to the well-known staticdynamic disorder of PZT systems [5][6][7][8][9] . In contrast, the 647.1 nm Raman signal previously reported 28 , Fig. 2b, exhibits major and continuous spectral changes as a function of the temperature; additionally, the changes are in close agreement with the transformation temperature previously reported by dielectric measurements [15][16] , X-ray 17 and neutron diffraction 4 . This indicates that the same sample, which has only one phase transition sequence, was studied as a function of the temperature by two different laser energies but only the 647.1 nm probe light enabled these transformations to be detected. Based on this observation, we can conclude that the changes in temperature are clearly excitation line dependent. These changes are related therefore to the evolution of the resonance conditions and thus to the electronic levels involved as a function of the phase transition sequence in PZT materials. Interestingly, it transpires that the resonance behaviour using the 647. in which the S -AS ratio is not scaled as it is the case for example in the resonance process of carbon nanotubes 34 . This anomalous strong signal in the S -scattering can find its origin from a particular resonance behavior on emission, for which the phonon intensity would increase to a much greater extent under specific conditions on the S -rather than on the AS -side. This can explain the existence of a background scattering centered around 380 cm -1 on the S -Raman spectra obtained as a function of the temperature, Fig.

T)+1)). Thus to fit these spectra between 10 and 350 K, a quadratic baseline was first subtracted to take into account this peculiar background.

Beginning from 350 K, Fig. 4a, the Raman spectrum of PbZr 0.52 Ti 0.48 O 3 consists of several broad lines. Below 300 K, Fig. 5a, the Raman lines become more asymmetric, noticeably for the mode 1 and the region 2 and 3, indicating the transformation to the monoclinic phase 28 . Upon decreasing temperature, a decrease of the line width occurs and at 200 K the modes 4 and 5 appear, Figs 4b-6a. These changes, which are represented on the spectrum obtained at 154 K, Fig. 5b, are clearly associated to the phase transition between the two monoclinic phases (Cm-Cc) 28 . The increase in the number of modes (Fig. 5d) at the phase transition is consistent with the greater number of modes predicted by group theory due to the doubling of the unit cell. Below 35 K, Fig. 5c, a brutal change in intensity of the entire spectrum occurs accompanied with the disappearance of mode 8 and the inversion in intensity ratio of mode 6-7, Fig. 4b-5c-6b. These changes indicate an important modification to the local and/or lange range structure. Until now, no phase transition has been detected at such a temperature for this composition based on X-ray diffraction and neutron diffraction experiments [35][36][37] . Such behavior may instead result from a maximum in the phonon-intensity due to the resonance effect for a 1.92 eV laser energy, which may be reached in a discontinuous manner due to a change in the local structure around the titanium atoms in this disordered system. The temperature dependence of the Raman modes is summarized on the Fig. 5d. As described above, the transformation temperatures obtained from our data are in good agreement with those published previously.

IV. CONCLUSIONS

In this study, we investigated the phase transition sequence of PbZr 0.52 Ti 0.48 O 3 as a function of the temperature by resonance Raman Spectroscopy. Using an excitation line of 647.1 nm with an energy close to a self-trapped level exciton energy deficient complex (Ti Ti ' -V O ..) of PZT powder, we induced a resonance effect. As resonance Raman scattering spectroscopy is known to be a powerful method to detect the phonon modes which couple to an electronic system, this technique has clearly permitted us to distinguish the structural change of PZT in spite of its well-known static-dynamical disorder [5][6][7][8][9]

  1 nm excitation line is structure-dependent what is an original phenomenon. Corrected Stokes (n(ω,T)+1)/n(ω,T) -anti-Stokes (S -AS) Raman spectra of PbZr 0.52 Ti 0.48 O 3 obtained at 150 K with the 514.5 nm excitation line and represented on the same abscissa, Fig. 3a, give clearly evidence of Bose statistics. Consequently, we did not observe any anomalously high local heating over the entire temperature range for spectra obtained with this radiation line. Corrected S -AS Raman spectra of PbZr 0.52 Ti 0.48 O 3 obtained at 200 K with the 647.1 nm excitation line, Fig. 3b, show a distinct phenomenon

FIG. 4 .

 4 FIG.1. Room temperature Raman spectra of PbZr 0.52 Ti 0.48 O 3 using as-followed excitation


T Huraux

F Sempé

Y Haradji
email: yvon.haradji@edf.fr

SMACH : Simuler l'activité humaine pour limiter les pics de consommation électrique

Keywords: modèle à base d'agents, comportements humains, consommation électrique Agent-based model, human behaviour, electrical consumption

Dans cet article, nous proposons un modèle de simulation du comportement humain pour une gestion efficace de la consommation énergétique dans le contexte résidentiel. Nous présentons la plateforme de simulation associée : SMACH. Elle permet aux experts de représenter les activités des habitants au sein de leur foyer et en particulier leur capacité d'adaptation dynamique. Nous décrivons la dynamique du système et nous illustrons sur un exemple complet l'émergence d'habitudes et l'adaptation à des événements extérieurs.

Introduction

La gestion efficace de l'énergie, défi majeur dans le contexte de l'écologie et du marché énergétique, passe aujourd'hui par deux approches. D'une part, le transport et la réparti-tion de la charge qui ont été largement étudiés ces dernières années et auquel le concept de smart grid semble une réponse prometteuse [START_REF] Molderink | Management and control of domestic smart grid technology[END_REF]. D'autre part, la réduction des pics de consommation face auquel les fournisseurs d'électricité n'ont en général comme réponse que le sur-dimensionnement de leurs capacités de productions. Cependant, deux observations peuvent être faites. Premièrement, le secteur résidentiel représente 27% de l'énergie consommée en Europe [START_REF]Energy and environment report[END_REF]. Il semble donc intéressant d'essayer d'agir à ce niveau pour mieux gérer l'énergie et en particulier les pics de consommation. Deuxièmement, des études ont montré qu'il est possible d'agir au niveau des foyers en les incitant à mieux maîtriser leur consommation [START_REF]Benefits of demand response in electricity markets and recommendations for achieving them[END_REF], par exemple à travers des campagnes de sensibilisation ou l'utilisation de compteurs intelligents avec affichage de consommation en temps réel [START_REF] Rogers | Adaptive home heating control through gaussian process prediction and mathematical programming[END_REF]. Toutefois, ces études demandent du temps, beaucoup de moyens et ne permettent pas de comparer différentes approches. Au contraire les simulations multi-agents, intégrant une représentation explicite des comportements individuels, permettent de mener des études semblables avec bien moins de moyens Bien que certains modèles à base d'agents aient été proposés pour étudier le marché de l'électricité [START_REF] Zhou | Agent-based simulation of electricity markets : a survey of tools[END_REF] (en se concentrant sur les interactions entre fournisseurs et consommateurs), peu de travaux ont été menés sur la représentation de l'activité humaine dans les foyers. Dans [START_REF] Kashif | Simulating the dynamics of occupant behaviour for power management in residential buildings. Energy and Buildings[END_REF], les auteurs proposent de représenter explicitement le comportement des habitants à travers un processus de décision réactif et délibératif, fondé sur l'architecture d'agents délibératifs Brahms [START_REF] Sierhuis | Brahms : a multi-agent modelling environment for simulating work processes and practices[END_REF]. Celle-ci est très proche de l'architecture BDI et nécessite des définitions précises de cadre de pensée et de travail. Néanmoins, nous pensons qu'une représentation complexe du processus de décision n'est pas nécessaire [START_REF] Haradji | Human Activity and Social Simulation[END_REF] pour obtenir un modèle capable de répondre à notre objectif : étudier l'adaptation des activités des foyers face à diverses mesures d'incitation et des événements. C'est dans cet objectif que la plateforme de modélisation et de simulation SMACH a été proposée [START_REF] Amouroux | Simulating Human Activities to Investigate Household Energy Consumption[END_REF]. L'idée est la suivante : permettre aux experts du domaine d'expérimenter sur les activités quotidiennes des foyers en relation avec leur consommation électrique et en particulier comment l'organisation (des activités) du foyer est adaptée à de nouvelles contraintes (prix de l'électricité, événements imprévus, etc.).

Dans cet article, nous présentons tout d'abord le méta-modèle proposé par SMACH avant de décrire la dynamique du simulateur. Nous examinons ensuite deux mécanismes d'adaptation présents dans SMACH qui permettent au foyer représenté de s'adapter aux contraintes de tarif électrique variable, aux événements ponctuels et aux changements d'organisation du foyer. Nous illustrons ce mécanisme sur un exemple complet de simulation.

2 Méta-modèle de l'activité humaine SMACH repose sur deux propriétés fondamentales : (1) décrire simplement le comportement humain dans le contexte de la consommation électrique des foyers et [START_REF]Energy and environment report[END_REF] proposer des mécanismes réalistes d'auto-adaptation (lors de la simulation) de l'activité du foyer. Afin de satisfaire ces deux propriétés tout en maintenant une accessibilité aux experts du domaine, nous avons choisi de centrer la description de l'activité humaine autour de la notion de tâche.

Ces tâches peuvent nécessiter des appareils ménagers, qui sont définis dans un environnement.

Environnement

Le logement est composé d'un ensemble de pièces dans lesquelles sont localisés des appareils. Soit R l'ensemble des pièces et E celui des appareils. Pour chaque pièce r (r ∈ R), on note E r ⊂ E l'ensemble des appareils de cette pièce.

Chaque appareil électrique e ∈ E est caractérisé par une consommation électrique θ i . On note power : E → R + la fonction de calcul de Les habitudes peuvent être perturbées lors de situations exceptionnelles (e.g. vacances, maladie, etc.) que nous nommons événements. Un événement q ∈ Q est défini par un couple ([d sq , d eq ], W q ) avec W q un ensemble de couples (a, w). Concrètement, un événement associe de nouveaux rythmes aux actions de l'individu pendant une période donnée. Par exemple, lors des vacances, le rythme associé à l'action "travail" est inactif.

Simulation des activités humaines

A partir de ce méta-modèle, nous simulons l'activité humaine grâce au simulateur SMACH. Dans celui-ci, chaque individu du modèle est représenté par un agent dont les mécanismes de décision sont présentés dans les deux soussections suivantes. L'adaptation du comportement de l'agent au court du temps, du fait de l'activité humaine, est présentée dans la section 4.

Croyance et communication

Dans SMACH, les agents sont synchrones et sélectionnent, à chaque pas de temps, l'action à exécuter en se basant sur leurs croyances (et leur état interne). Dans cette sous-section, nous présentons le modèle de croyance et celui de communication des agents pour ensuite présenter la dynamique des agents dans la sous-section suivante. contenu d'un message, si besoin, est toujours une tâche unique t ∈ T . Les agents ont donc besoin de connaître a priori la liste des tâches et des agents qui peuvent les effectuer. Tous les agents peuvent communiquer avec l'ensemble des agents du logement (sans autre considération de localisation).

Dynamique des agents

Cette section présente comment les agents maintiennent leurs bases de croyances. Ensuite, nous présentons comment un agent individu sélectionne l'action à effectuer en fonction de ses croyances mais aussi de ses préférences et de ses communications.

Mise à jour des croyances. L'ajout (ou le retrait) d'une croyance à la base B i de l'agent est fonction de ses perceptions directes, ses communications mais aussi du fait d'un système de maintien de la cohérence sur l'état des actions et de la localisation des autres individus. Tout d'abord nous définissons les éléments suivants : d 0 la date courante et notons

+ i b et -i b l'ajout et le retrait d'une croyance b dans B i et visi(a)
la zone de visibilité de l'action a. La base de croyances B i de l'agent i est mise à jour lorsqu'il entre dans la zone de visibilité d'une action :

∀a | room(i) ∈ visi(a), d , a, status(a) ∈ B i ⇒ + i d 0 , a, status(a)
De la même façon, quand un individu reçoit un message avec le performatif je fais ou une réponse à un message As tu fait ? lors d'une conversation, une nouvelle croyance est ajoutée : + i d 0 , a, status(a) , avec a l'action correspondant à l'émetteur et la tâche du message. De plus, un système de maintien de la cohérence enlève toute croyance pré-existante invalidée du fait des contraintes suivantes : -Une action ne peut être que dans un état : La priorité (pr raw ) d'une action prend en compte l'état interne d'un individu : l'engagement (ou lassitude) sur l'action courante, l'influence du rythme associé (l'influence du rythme de l'action est présentée dans la section 4.1) et, dans une moindre mesure, la préférence de l'agent pour cette action. L'engagement concerne uniquement l'action en cours et sa valeur décroit linéairement au cours du temps. Inversement, la lassitude croît dès que la durée minimale est atteinte.

+ i d 0 , a, status(a) ⇒ ∀d < d 0 , -i d ,
La priorité est également influencée par des facteurs extérieurs : le prix de l'électricité (les tâches consommatrices sont fortement pénalisées lorsque le tarif est élevé et très légèrement favorisée quand il est faible), l'invitation pour faire une action en commun (par le biais de message) et les événements.

La hiérarchie des différentes influences a été déterminée par les experts applicatifs et les valeurs déterminées empiriquement par exploration de l'espace des paramètres par les modélisateurs (i.e. seules les valeurs relatives sont significatives). Par exemple, l'engagement à l'action courante est moins important que l'invitation à faire une action collective.

Afin de pouvoir représenter les séquences d'activité (comme aller au travail nécessite de s'habiller qui lui même se fait après prendre sa douche), la priorité d'une action est également influencée par l'action la plus urgente dépendant d'elle-même, i.e. la priorité maximale de toutes les actions qui ont a en pré-condition : pr dep = max a.t∈a .Tpre {a .pr} Ainsi, la priorité (effective) de l'action a.pr est définit par : a.pr = max{a.pr raw , pr dep }

Implémentation

Pour simuler nos modèles, les plate-formes de simulation existantes ne sont pas satisfaisantes. En effe,t nous avons besoin d'une interface de modélisation et d'analyse spécifique et qui soit adaptée aux experts du domaine de l'énergie. Pour ce faire, nous avons donc choisi de développer un simulateur ad hoc en collaboration avec les ergonomes partenaires. L'IHM d'analyse de simulation de SMACH (Fig. 1) permet devoir simultanément les éléments suivants. (1) La consommation électrique globale avec une couleur par appareil. Le panneau (2) détaille les activités des individus au cours d'une semaine (S25 sélectionnée en (1)) alors que les panneaux (3 et 3') permettent d'avoir le détail de l'activité par minute. Enfin, le panneau (4) permet d'observer les rythmes effectifs des actions (l'axe horizontal représente l'écoulement des jours alors que l'axe vertical celui des heures de la journée). Ici, nous présentons 3 situations à résoudre : (1) le processus d'organisation initiale, (2) la réorganisation induite par un changement de tarif électrique et (3) la ré-organisation suite à un changement majeur des activités du foyer. Avant toute chose, nous présentons le scénario de simulation.

Paramètres de Simulation

Le scénario représente une famille avec 2 parents (John et Marie) et un adolescent (Gustave).

Chaque agent individu à trois types de tâche : planifiée (travail, école, ...), mobile (avec une fréquence fixe mais réalisables à tout moment : repassage, aspirateur, ...) et sans contrainte (regarder la TV, lire, ...). Ce scénario débute en Janvier et se finit au bout de 3 mois.

Sans permettre d'adaptation, nous obtenons un taux d'occupation moyen ≈ 88% par semaine et par habitant. Ce taux est suffisamment élevé pour évaluer les capacités d'adaptation de notre modèle.

Notons que les contraintes de fréquence et d'horaires peuvent être outrepasser. En pratique, une hiérarchie de tâche est automatiquement créée : une tâche avec une contrainte de fréquence faible recevra une influence plus faible, et donc une probabilité de réalisation moindre, qu'une tâche ayant une contrainte élevée.

Création et stabilité de l'organisation

Lorsqu'on active les capacités d'adaptation, on obtient une évolution du taux de réalisation telle qu'attendue : il augmente régulièrement pendant 3 à 4 semaines puis se stabilise. La phase ascendante est révélatrice du processus d'organisation : les tâches non-planifiées trouvent des créneaux disponibles et celles contraintes adaptent également leurs influences si nécessaire. Nous obtenons un taux de ≈ 94% à l'équilibre (le complément correspondant aux abandons d'activités).

Que penser de ce taux de réalisation de 94% ? Le taux d'occupation est de 88% et le temps passé à effectuer des activités non contraintes est de 6% -temps qui aurait pu être utilisé pour les actions contraintes -nous pouvons donc estimer qu'une meilleure organisation est possible. Cependant, l'optimisation n'est pas notre objectif car, bien que les foyers organisent leur emploi du temps, ils ne l'optimisent pas complètement. L'augmentation du taux de complétion ayant lieux durant les premières semaines démontre les capacités d'adaptation, cela est suffisant pour estimer que le foyer est capable de s'adapter à ces contraintes initiales.

Pour une observation plus précise du processus d'adaptation nous allons observer le diagramme d'activité sur le long-terme (Fig.

Conclusion

Dans ce papier nous avons présenté un simulateur multi-agent de l'activité humaine, SMACH, et le méta-modèle associé. Celui-ci permet aux experts du domaine de représenter à la fois les activités de "routine" du foyer ainsi que des événements plus aléatoire (i.e. maladie, changement de travail, etc.) qui font partie de la vie quotidienne. Les perspectives de ce projet sont de trois ordres : (1) améliorer la calibration du framework, (2) l'utilisation d'un modèle thermodynamique évolué et (3) le passage à l'échelle. Premièrement, notre partenaire applicatif (EDF) conduit à l'heure actuelle des études de terrains avec des mesures d'activité (et de consommation) précises qui pourront être utilisées. Ces mesures en conjonction avec des simulations participatives nous permettrons de valider certaines hypothèses faites par les experts énergéticiens. Deuxièmement, le modèle de chauffage actuellement utilisé est simpliste au vue de nos objectifs. Nous sommes donc en train de coupler un modèle thermodynamique externe [START_REF] Plessis | Using design of experiments methods to develop low energy building model under modelica[END_REF] et de développer un modèle de confort inspiré de celui proposé par Fanger [START_REF] Van Hoof | Forty years of Fanger's model of thermal comfort : comfort for all ?[END_REF] (afin de contrôler de manière réaliste l'environnement thermique). Enfin, nous voulons pouvoir nous intéresser aux dynamiques de groupes sociaux et nous allons donc augmenter l'échelle de représentation afin de pouvoir représenter des populations de foyer de l'ordre du quartier.

FIGURE 2 -FIGURE 3 -

 23 FIGURE 2 -Diagramme d'activité avec 3 tâches : Aller à l'école (violet), Jouer à l'ordinateur (rouge) et randonnée (jaune)

FIGURE 4 -FIGURE 5 -

 45 FIGURE 4 -Taux de complétion par semaine

  consommation électrique d'un appareil. Nous considérons deux types d'appareils électriques.Les appareils à état sont définis par le tuple θ o , θ s , st avec θ o et θ s les consommations électriques quand e est en fonctionnement ou en veille, et st ∈ {off, standby, on} l'état de l'appareil, (contrôler par un individu au cours de ces activités). Les éclairages, TVs, ordinateurs, ... sont représentés par ce type d'appareil.Les appareils à programme sont définis par le tuple P e , st avec P e un ensemble de programmes. Chaque programme p est un couple (τ p , φ p ) avec τ p la durée du programme et φ p : [0, τ p ] → R + la fonction définissant la consommation à chaque instant du programme. L'état st de l'appareil est défini par le couple (p c , t c ) avec p c le programme courant et t c la durée écoulée depuis le début de ce programme (avec power(e) = φ pc (t c )). Les fours, machines à laver, etc., sont représentés par ce type d'appareil. Tous les profils de consommation du simulateur proviennent du projet REMODECE 1 qui a caractérisé la consommation des appareils en situation réelle.

	-coll ∈ {none, allowed, mandatory} la tâche
	doit/peut être réalisée à plusieurs ou seul ;
	-E t = { e, p } | e ∈ E & p ∈ {e.P e} éven-
	tuels appareils utilisés lors de la réalisation de
	la tâche et programmes associés ;
	-T pre ⊂ T tâches en pré-condition. Un indi-
	vidu ne peut réaliser une tâche que si toutes
	les tâches en pré-condition ont été réalisées
	(par lui-même ou un autre suivant la valeur
	de bene) ;
	Une action a ∈ A représente l'instanciation
	d'une tâche pour un individu donné. Elle est dé-
	finie par le tuple a = t, w, R a , st avec t la
	tâche associée, w son rythme, R a l'ensemble
	des pièces où l'action peut être réalisée et st ∈
	{undone, done} son état de réalisation.
	Afin de pouvoir exprimer les habitudes, le
	concept de rythme a été introduit dans le
	méta-modèle. Un rythme w (w ∈ W ) per-
	met de définir, pour chaque action, une fré-
	quence et un ensemble de périodes préféren-
	tielles. Une période préférentielle (PP) est com-
	posée d'une plage horaire et d'une périodicité
	(mensuelle, hebdomadaire, etc.) durant laquelle
	l'individu sera plus enclin à réaliser l'action
	associée. Un rythme est définie par le tuple
	per w , f req w , var w , P p w avec :
	-per ∈ {day, week, month, year} la périodi-
	cité ; -f req ∈ N + la fréquence ;
	-var ∈ {weak, medium, strong} le niveau de
	variabilité de la fréquence ;
	-P P les périodes préférentielles qui sont dé-
	finies par un tuple [d 1 , d 2 ], strength avec
	d 1 et d 2 date de début et de fin, strength ∈
	{weak, medium, imperative} la force de
	cette période ;
	Pour mieux comprendre, prenons l'exemple
	de la tâche "manger". Nous pourrions vou-loir définir un rythme tel que l'action associée d'un individu soit réalisée jus-qu'à trois fois par jour, ce qui donnerait le tuple : w m = {day; 3; weak; pp 1,2,3 } avec pp 1 = {[7h; 9h], imperative},	Lors de la simulation, la pièce dans laquelle l'in-dividu est localisé (room(i) ∈ R), son action courante (action(i) ∈ A i ), ses croyances (B i ), et ses communications (C i ) sont valuées pour définir complètement un individu.
	pp 2	=	{[12h; 14h], weak} et pp 3	=	Une tâche t ∈ T représente une activité géné-
	{[19h, 22h], strong}. Dans le cas présent	rique du foyer, à partir de laquelle les actions des
	l'individu mangera toujours le matin, rarement	individus sont dérivées. Une tâche est un tuple
	le midi et presque tous les soirs.		τ min , τ max , bene, visi, coll, E t , T pre avec :
					-τ min , τ max durées minimale et maximale
					d'exécution ;
					-bene ∈ {alone, collective} définit si la tâche
					va profiter à l'individu ou à tout le foyer ;
					-visi ∈ {none, individual, room, house} vi-
					sibilité (par les autres individus) de la tâche ;

2.2 Les membres du foyer et leurs comportements

Nous considérons le foyer comme un ensemble d'individus fixé pour le scénario. Chaque membre du foyer est représenté par un agent individu, i ∈ I. Celui-ci est caractérisé par l'ensemble des actions A i qu'il peut effectuer et son niveau de responsabilité res i . Ce dernier permet de distinguer les enfants, des adolescents et des adultes.

  i d , a 2 , running and + i d 0 , a 2 , done Dynamique des actions. L'état d'une action st ne se réduit pas à son statut de réalisation (undone ou done), il y a, en réalité, quatre attributs : -real number ∈ N + est le nombre de réalisations déjà effectuées pour le jour courant. La valeur de a.st ∈ {done, undone} est directement calculée à partir de a.real number ≥ 1 ; -real max ∈ N + est le nombre maximal de réalisation prévu pour le jour courant (qui dépend du rythme w) ; -τ ≤ a.t.τ max est le temps écoulé lorsque a est en cours d'exécution ; -pr ∈ [-1; 1] niveau de priorité. La priorité a.pr est réévaluée à chaque pas de temps (voir ci-après) et l'agent exécute l'action ayant la priorité maximale parmi les actions réalisables. Une action est réalisable aux conditions suivantes :-Toutes les tâches en pré-conditions ont été Bien que l'état des actions évolue en permanence suivant le comportement de l'individu et de son environnement. Celui-ci est ré-initialisé tous les jours à minuit . En pratique, a.st est remis à undone, a.real number , a.τ et a.pr à 0, et le nombre de réalisation maximal est recalculé en fonction du rythme : si le jour courant contient une période préférentielle, ppi, et s'il reste des réalisations à faire (w.real < w.real max ).

						évalué directement
						par l'agent. Au contraire, il utilise ses croyances
						pour déterminer si l'action est réalisée ou pas et
						s'il peut l'exécuter. Cependant, lors du démar-
						rage de l'action, le simulateur va vérifier que les
						conditions sont effectivement remplies ainsi un
						agent ne pourra démarrer une action qui n'est
						pas effectivement réalisable. Dans ce cas, toutes
						les croyances inconsistantes de l'agent sont éli-
						minées.
						Une action, a, en cours de réalisation, peut être
						interrompue pour 2 raisons : (1) une autre action
						(réalisable), a , a une priorité supérieure ou (2) a
						est devenue impossible. Suite à une interruption,
						l'état de l'action a est modifiée en fonction de sa
						durée d'exécution :
						-Si a a été exécutée pour une durée τ ≥ τ min ,
		a, s = status(a)		son nombre de réalisation a.real number est in-
	-Un	agent	ne	peut	effectuer	crémenté et a.τ est remis à 0. Le statut de l'ac-
	qu'une seule action à la fois :	tion a.st est passé à done.
	+ i d 0 , a, status(a) ⇒ ∀a |actor(a) =	-Si a.τ < τ min L'action est mise "en attente" :
	actor(a ), -i d , a , s and + i d 0 , a , done ;	a.τ est maintenue à sa valeur courante (et son
	-Une action ne peut durer plus longtemps	nombre de réalisation demeure inchangé). Par

que sa durée maximale : si ∃b ∈ B i tel que b.d + b.a.t.τ max > d 0 , alorsi b et + i d 0 , b.

a, done ; -Deux actions associées avec une tâche "exclusive" (a 1 .t = a 2 .t = t and t.coll = none) ne peuvent être conduite simultanément : réalisées : ∀t ∈ a.t.T pre , ∃a ∈ A|a .t = t ∧ a .st = done ∧ (actor(a ) = actor(a) ∨ t .bene = i.e.collective) -Tous les appareils nécessaires sont disponibles : ∀e ∈ a.t.E t , a /a .running ∧ e ∈ a .t .E t Notons que a.st ne peut être exemple, si un enfant est interrompue lors de l'action faire ses devoirs, il ne perdra pas le bénéfice de les avoir commencés.

  Ce méta-modèle se base sur une définition quantitative de tâches planifiées (i.e. fréquence, périodes préférentielles et degré d'obligation). Nous avons également démontrer les capacités du modèle à représenter des habitudes contraintes et émergentes. Pour ce faire, nous avons présenté un exemple de simulation avec l'introduction d'un tarif électrique variable et une autre au cours de laquelle les contraintes professionnelles d'un individu sont drastiquement changées et, par voie de conséquence, l'organisation de l'activité globale du foyer qui est affectée.

http ://remodece.isr.uc.pt

Une croyance b d'un individu i est un tuple b = d, a, s avec d sa date de création, a ∈ A une action et s ∈ {undone, running, done} l'état perçu de celle-ci. d, a, s ∈ B i veut donc dire qu'au temps d, l'individu i à l'information que l'action a est dans l'état s. Cette croyance est conservée dans la base de croyances de i tant qu'aucune autre perception ou déduction ne la contredit. Dans l'état initial, s = undone pour toutes les actions. D'autre part, nous considérons que les individus connaissent l'ensemble des actions que chaque agent peut réaliser, pour pouvoir envoyer les messages d'invitation ou de de mande d'aide.En plus de la réalisation de ses actions individuelles, les habitants d'un foyer peuvent communiquer pour échanger des informations ou demander de l'aide. Pour ce faire, nous utilisons un protocole de communication multi-agent inspiré de FIPA-ACL[START_REF]FIPA Communicative Act Library Specification and FIPA ACL Message Structure Specification. Technical report[END_REF]. Une conversation c ∈ C i est un ensemble ordonné de n messages, msg 1 , ..., msg n , avec msg i = d, to, f rom, perf, c et d la date du message, to et f rom émetteur et destinataire, perf le performatif et c le contenu. Les performatifs principaux sont : es-tu prêt à ... ?, que fais-tu ?, as tu fait ... ?, peux-tu faire ... ? et leur réponse je fais ..., non, oui, plus tard. Le