{"id":5833,"date":"2023-09-09T03:40:49","date_gmt":"2023-09-09T02:40:49","guid":{"rendered":"http:\/\/mosaic-modeling.de\/?page_id=5833"},"modified":"2023-09-09T20:37:42","modified_gmt":"2023-09-09T19:37:42","slug":"use-of-user-defined-language-specifications-ii-parameter-estimation-with-single-shooting","status":"publish","type":"page","link":"https:\/\/mosaic-modeling.de\/?page_id=5833","title":{"rendered":"Use of User-defined Language Specifications II \u2013 Dynamic Optimization via Single Shooting"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">On this page<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/mosaic-modeling.de\/?page_id=5833\/#Goal\" >Goal<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/mosaic-modeling.de\/?page_id=5833\/#Workflow-for-setting-up-a-UDLS\" >Workflow for setting up a UDLS<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/mosaic-modeling.de\/?page_id=5833\/#Global-language-settings\" >Global language settings<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/mosaic-modeling.de\/?page_id=5833\/#Operations\" >Operations<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/mosaic-modeling.de\/?page_id=5833\/#Variable-namings\" >Variable namings<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/mosaic-modeling.de\/?page_id=5833\/#Code-generation-properties\" >Code generation properties<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/mosaic-modeling.de\/?page_id=5833\/#Code-elements\" >Code elements<\/a><ul class='ez-toc-list-level-5' ><li class='ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/mosaic-modeling.de\/?page_id=5833\/#Help-header\" >Help header<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/mosaic-modeling.de\/?page_id=5833\/#Optimization-layer\" >Optimization layer<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/mosaic-modeling.de\/?page_id=5833\/#Simulation-layer\" >Simulation layer<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/mosaic-modeling.de\/?page_id=5833\/#Model-equations\" >Model equations<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/mosaic-modeling.de\/?page_id=5833\/#Display-results\" >Display results<\/a><\/li><\/ul><\/li><\/ul><\/li><\/ul><\/nav><\/div>\n<h3><span class=\"ez-toc-section\" id=\"Goal\"><\/span>Goal<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>In this example, we will set up a UDLS for sequential optimization in Matlab. The UDLS is available in MOSAICmodeling with ID 185804.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Workflow-for-setting-up-a-UDLS\"><\/span>Workflow for setting up a UDLS<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>A UDLS is set up in the &#8220;Miscellaneous&#8221; section of MOSAICmodeling in the tab Language Specification. Should this tab be invisible to you and you would like to use it, please <a href=\"http:\/\/mosaic-modeling.de\/?page_id=4090\">request this feature<\/a> for your account.<\/p>\n<h4><span class=\"ez-toc-section\" id=\"Global-language-settings\"><\/span>Global language settings<span class=\"ez-toc-section-end\"><\/span><\/h4>\n<p>We begin in the tab Global Language Settings by adding an informative description. As programming languages can change their syntax over time, you should also mention for which version this UDLS is tested. Then, perform the following steps:<\/p>\n<ol>\n<li>Deactivate Direct Functions Supported and Case Sensitive in the Language Settings. The former will prohibit the inclusion of direct function calls, the latter ensures a difference between capital and small letters. Note that we exclude functions only for the sake of simplicity and their addition to the UDLS would be fairly simple.<\/li>\n<li>Activate Force Floating Point in the Number settings<\/li>\n<li>Select &#8220;DAE&#8221; as Equation System Type<\/li>\n<li>Select &#8220;Optimization&#8221; and &#8220;Sequential&#8221; in the box Opt or Nopt<\/li>\n<\/ol>\n<p>The button in the bottom right corner next to Minimum Specifications Complete should be green now.<\/p>\n<h4><span class=\"ez-toc-section\" id=\"Operations\"><\/span>Operations<span class=\"ez-toc-section-end\"><\/span><\/h4>\n<p>Move to the Operations tab. We need to specify in which way basic operations are expressed in the programming language, i.e., Matlab. Therefore,<\/p>\n<ol>\n<li>Click on Add and add a &#8220;+&#8221; as Infix, click on the green arrow to see the output<\/li>\n<li>Click on Subtract and add a &#8220;-&#8221; as Infix, click on the green arrow to see the output<\/li>\n<li>Click on Multiply and add &#8220;(&#8221; as Prefix, &#8220;)*(&#8221; as Infix, and &#8220;)&#8221; as Suffix, click on the green arrow to see the output. The additional brackets ensure that any addition or subtraction terms in LEFT or RIGHT are correctly enclosed<\/li>\n<li>Click on Divide and add &#8220;(&#8221; as Prefix, &#8220;)\/(&#8221; as Infix, and &#8220;)&#8221; as Suffix, click on the green arrow to see the output<\/li>\n<li>Click on Power and add &#8220;(&#8221; as Prefix, &#8220;)^(&#8221; as Infix, and &#8220;)&#8221; as Suffix, click on the green arrow to see the output<\/li>\n<li>Click on R-root and add &#8220;(&#8221; as Prefix, &#8220;)^(1.0\/(&#8221; as Infix, and &#8220;))&#8221; as Suffix, click on the green arrow to see the output. Alternatively, you could implement the Matlab function nthroot(X,N). Attention: Make sure that you selected Swap LR because MOSAICmodeling uses the function \\sqrt[N]{X} internally, i.e., the first argument (LEFT) is the root&#8217;s exponent.<\/li>\n<li>Click on Exp and add &#8220;exp(&#8221; as Prefix and &#8220;)&#8221; as Suffix, click on the green arrow to see the output<\/li>\n<li>Click on Log and add &#8220;log(&#8221; as Prefix and &#8220;)&#8221; as Suffix, click on the green arrow to see the output<\/li>\n<li>Click on Sinus and add &#8220;sin(&#8221; as Prefix and &#8220;)&#8221; as Suffix, click on the green arrow to see the output<\/li>\n<li>Click on Cosinus and add &#8220;cos(&#8221; as Prefix and &#8220;)&#8221; as Suffix, click on the green arrow to see the output<\/li>\n<li>Click on Parentheses and add &#8220;(&#8221; as Prefix and &#8220;)&#8221; as Suffix, click on the green arrow to see the output<\/li>\n<\/ol>\n<p>The remaining operations are not of interest for this example and can therefore be neglected.<\/p>\n<h4><span class=\"ez-toc-section\" id=\"Variable-namings\"><\/span>Variable namings<span class=\"ez-toc-section-end\"><\/span><\/h4>\n<p>Go to the tab Variable Namings and do the following:<\/p>\n<ol>\n<li>Select Use Variable Naming as Strategy<\/li>\n<li>Click on Namespace to base name and add a &#8220;_&#8221; as Infix, click on the green arrow to see the output. You see that there is now a &#8220;_&#8221; between std and P<\/li>\n<li>Add the same &#8220;_&#8221; for Leading superscript, Leading subscript, and Leading indexname. After every change, click on the green arrow to see what has changed<\/li>\n<li>In this example, we leave the Infix for Index name to index value empty<\/li>\n<\/ol>\n<h4><span class=\"ez-toc-section\" id=\"Code-generation-properties\"><\/span>Code generation properties<span class=\"ez-toc-section-end\"><\/span><\/h4>\n<p>Next, we skip the tab External Functions as we do not supply additional interfaces, and go directly to the tab Code Generation Properties to add options for the user export. Which options exactly you would like to define, is up to the user. In the UDLS, there is an extensive list of options for fmincon (the optimizer), DAE solvers (for integrating the dynamic model), and for fsolve (to solve the algebraic sub-system). If you want to see the complete list, take a look at the UDLS with the ID given above. Here, we just want to highlight a couple of options as they are particularly relevant for the example <a href=\"http:\/\/mosaic-modeling.de\/?page_id=5838\">Use of Optimizations II \u2013 Dynamic Optimization via Single Shooting<\/a>, in which this UDLS is applied.<\/p>\n<ol>\n<li>Add the the Property OdeSolver with Handle _ODESOLVER_, Type STRING, and Default ode15<\/li>\n<li>Add the the Property Algorithm with Handle _ALGORITHM_, Type STRING, and Default &#8216;sqp&#8217;<\/li>\n<li>Add the the Property DisplayIter with Handle _DISPLAY_, Type STRING, and Default &#8216;iter&#8217;<\/li>\n<li>Add the the Property MaxFunEvals with Handle _MAXFUNEVALS_, Type INTEGER, and Default 100000<\/li>\n<li>Add the the Property MaxIterations with Handle _MAXITERATIONS_, Type INTEGER, and Default 100000<\/li>\n<li>Click on the row containing the name DisplayIter and click on &#8220;+ Option&#8221; on the right-hand side. Enter &#8216;iter&#8217; and confirm. Repeat this for &#8216;notify&#8217;, &#8216;off&#8217;, &#8216;final&#8217;, &#8216;notify-detailed&#8217;, &#8216;iter-detailed&#8217;, and &#8216;final-detailed&#8217;. This allows the user to select a preferred choice within MOSAICmodeling when a simulation shall be exported<\/li>\n<\/ol>\n<h4><span class=\"ez-toc-section\" id=\"Code-elements\"><\/span>Code elements<span class=\"ez-toc-section-end\"><\/span><\/h4>\n<p>This tab is fairly complicated as it contains the structure for the generated code. We will try to be as concise as possible in our description. However, you can of course also directly open the UDLS with the ID given above. We begin in the in the block _FULL_PROBLEM_SOLVING_CODE_. This block shall basically contain the overall structure of the generated code. Here, we now add the following lines:<\/p>\n\n\n<pre class=\"wp-block-code\"><code>_Help_Header_\n\n_Optimization_layer_\n\n_Simulation_layer_\n\n_Model_Equations_\n\n_DIR_FUN_IMPL_LOOP_\n\n_Display_Results_<\/code><\/pre>\n\n\n<p>These blocks will execute the following tasks:<\/p>\n<ul>\n<li>_Help_Header_: generation of documentation code at the beginning<\/li>\n<li>_Optimization_layer_: variable initialization and call of fmincon<\/li>\n<li>_Simulation_layer_: integration of DAE system and calculation of objective function<\/li>\n<li>_Model_Equations_: model equations of DAE system, algebraic sub-system, and nonlinear constraints for optimization<\/li>\n<li>_Display_Results_: will show the results for the calculated variables<\/li>\n<\/ul>\n<p>We will now go through these blocks in sequential order. Note that when you really develop a UDLS, this process might be much more iterative than in this example here.<\/p>\n<h5><span class=\"ez-toc-section\" id=\"Help-header\"><\/span>Help header<span class=\"ez-toc-section-end\"><\/span><\/h5>\n<p>The block _Help_Header_ does not exist so far.\u00a0 Hence, we create it by highlighting the _FULL_PROBLEM_SOLVING_CODE_ block and clicking on &#8220;+ Node&#8221; at the bottom left corner. Define the handle _Help_Header_ in the popup window and click on Submit&#8221;. You can now move the created block upwards or downwards using the two arrows.<\/p>\n<p>Highlight the new block and enter the following code:<\/p>\n\n\n<pre class=\"wp-block-code\"><code>% Matlab code to optimize the differential-algebraic equation system below\n% Code generated with MOSAICmodeling<\/code><\/pre>\n\n\n<p>Hence, this block will only add a couple of comments at the beginning. You can make this much more complicated and add the whole notation of your system, but we will keep it simple here.<\/p>\n<h5><span class=\"ez-toc-section\" id=\"Optimization-layer\"><\/span>Optimization layer<span class=\"ez-toc-section-end\"><\/span><\/h5>\n<p>In the optimization layer, the variables are initialized, the decisions and their bounds are set, the solver options are specified, and the optimizer is called according to the code below:<\/p>\n\n\n<pre class=\"wp-block-code\"><code>function SolveDynamicOptimizationProblem()\n\tclear\n\tclose all\n\tclc\n\n\t% declare interval of independent variable\n_Set_DIFF_VAR_\n\t% initial conditions for explicit state variables\n_Set_Init_STATE_VARS_EXPL_LOOP_\n\t% initial conditions for implicit state variables\n_Set_STATE_VARS_IMPL_LOOP_\n\t% objective function\n_Set_OBJECTIVE_LOOP_\n\t% set parameters\n_Set_PARAMS_LOOP_\n\t% define decision variables and their bounds\n_Set_DECISIONS_\n\tM = &#91;eye(_DIM_DIFFEQUAS_,_DIM_DIFFEQUAS_),zeros(_DIM_DIFFEQUAS_,_DIM_ALGEQUAS_); zeros(_DIM_ALGEQUAS_, _DIM_ALGEQUAS_+_DIM_DIFFEQUAS_)];\n\n\t% specify options\t\n\tOPToptions = optimoptions('fmincon',...\n\t\t'Algorithm',_ALGORITHM_,...\n\t\t'CheckGradients',_CHECKGRADIENTS_,...\n\t\t'ConstraintTolerance',_CONSTRAINTTOLERANCE_,...\n\t\t'Diagnostics',_DIAGNOSTICS_,...\n\t\t'DiffMaxChange',_DIFFMAXCHANGE_,...\n\t\t'DiffMinChange',_DIFFMINCHANGE_,...\n\t\t'Display',_DISPLAY_,...\n\t\t'FiniteDifferenceStepSize',_FINITEDIFFERENCESTEPSIZE_,...\n\t\t'FiniteDifferenceType',_FINITEDIFFERENCETYPE_,...\n\t\t'FunValCheck',_FUNVALCHECK_,...\n\t\t'MaxFunctionEvaluations',_MAXFUNCTIONEVALUATIONS_,...\n\t\t'MaxIterations',_MAXITERATIONS_,...\n\t\t'OptimalityTolerance',_OPTIMALITYTOLERANCE_,...\n\t\t'OutputFcn',_OUTPUTFCN_,...\n\t\t'PlotFcn',_PLOTFCN_,...\n\t\t'SpecifyConstraintGradient',_SPECIFYCONSTRAINTGRADIENT_,...\n\t\t'SpecifyObjectiveGradient',_SPECIFYOBJECTIVEGRADIENT_,...\n\t\t'StepTolerance',_STEPTOLERANCE_,...\n\t\t'TypicalX',_TYPICALX_,...\n\t\t'UseParallel',_USEPARALLEL_);\n\n\tDAEoptions = odeset('AbsTol',_DAEABSTOL_,...\n\t\t'BDF',_DAEBDF_,...\n\t\t'Events',_DAEEVENTS_,...\n\t\t'InitialStep',_DAEINITIALSTEP_,...\n\t\t'Jacobian',_DAEJACOBIAN_,...\n\t\t'JConstant',_DAEJCONSTANT_,...\n\t\t'JPattern',_DAEJPATTERN_,...\n\t\t'Mass',M,...\n\t\t'MassSingular',_DAEMASSSINGULAR_,...\n\t\t'MaxOrder',_DAEMAXORDER_,...\n\t\t'MaxStep',_DAEMAXSTEP_,...\n\t\t'MStateDependence',_DAEMSTATEDEPENDENCE_,...\n\t\t'MvPattern',_DAEMVPATTERN_,...\n\t\t'NonNegative',_DAENONNEGATIVE_,...\n\t\t'NormControl',_DAENORMCONTROL_,...\n\t\t'OutputFcn',_DAEOUTPUTFCN_,...\n\t\t'OutputSel',_DAEOUTPUTSEL_,...\n\t\t'Refine',_DAEREFINE_,...\n\t\t'RelTol',_DAERELTOL_,...\n\t\t'Stats',_DAESTATS_,...\n\t\t'Vectorized',_DAEVECTORIZED_);\n\n\tNLEoptions = optimoptions('fsolve',...\n\t\t'Display',_NLEDISPLAY_,...\n\t\t'FunctionTolerance',_NLEFUNCTIONTOLERANCE_,...\n\t\t'MaxFunctionEvaluations',_NLEMAXFUNCTIONEVALUATIONS_,...\n\t\t'MaxIterations',_NLEMAXITERATIONS_,...\n\t\t'OptimalityTolerance',_NLEOPTIMALITYTOLERANCE_);\n\n\t% solve sequential optimization problem\n\t&#91;DEC,FVAL,EXITFLAG,OUTPUT,LAMBDA,GRAD,HESSIAN] = fmincon(@(DEC) objectiveFunction(DEC,X_INTERVAL,Y_INIT,PARAMS,NLEoptions,DAEoptions),DEC_INIT,&#91;],&#91;],&#91;],&#91;],LB,UB,@(DEC) NONLCON(DEC,X_INTERVAL,Y_INIT,PARAMS,NLEoptions,DAEoptions),OPToptions);\n\n\t% plot optimized profiles\n\t&#91;X,Y] = ode15s(@(X,Y)DAESystem(X,Y,PARAMS,DEC),X_INTERVAL,Y_INIT',DAEoptions);\n\tdisplayResults(X,Y);\n\nend<\/code><\/pre>\n\n\n<p>This code creates a function in Matlab that begins with a looping setting the time horizon of the integration (which is in this case equal to the optimization horizon), set the initial guesses for both explicit and implicit variables. Finally, the objective is &#8211; in this specific case &#8211; added to the variable vector of the DAE system. Then, the parameter values are set within a loop. Finally, the decisions and their bounds are set.<\/p>\n<p>We then proceed with the specification of the mass matrix for the DAE solver and the various options for optimizer, DAE solver, and NLE solver. Then, we call fmincon to solve the optimization problem. Finally, the DAE system is solved again with the decisions obtained via optimization and the profiles of the variables are plotted. <\/p>\n<p>As you can see, the block requires the loops _Set_DIFF_VAR_ (DifferentialVariable), _Set_STATE_VARS_EXPL_LOOP_ (StateVariablesExplicit), _Set_STATE_VARS_IMPL_LOOP_ (StateVariablesImplicit), _Set_OBJECTIVE_LOOP_ (ObjectiveFunction), _Set_DECISIONS_ (GenericVariables), and _Set_PARAMS_LOOP_ (Parameters). These loops are now added as subnodes of the node _Optimization_layer_. For most of these nodes, the code to be entered is straightforward, e.g., for the parameter block:<\/p>\n\n\n<pre class=\"wp-block-code\"><code>\tY_INIT(_CTRVALUE_) = _INIT_VALUE_;  \t% _VAR_NAME_  \n<\/code><\/pre>\n\n\n<p>For the GenericVariables block, a configuration is required. Therefore, right-click on the node _Set_Decisions_ and set OPTIMIZATION_VAR to True. Then add the code below to the block:<\/p>\n\n\n<pre class=\"wp-block-code\"><code>\tDEC_INIT(_CTRVALUE_) = _VAR_VALUE_;\t% _VAR_NAME_\n\tLB(_CTRVALUE_) = _LOWER_BOUND_;\n\tUB(_CTRVALUE_) = _UPPER_BOUND_;\n<\/code><\/pre>\n\n\n<p>This ensures that only the degrees of freedom of the optimization problem are initialized with value and bounds.<\/p>\n<h5><span class=\"ez-toc-section\" id=\"Simulation-layer\"><\/span>Simulation layer<span class=\"ez-toc-section-end\"><\/span><\/h5>\n<p>After you have added code to all blocks described above, create a new sub-node of the Full Code and name it _Simulation_layer. Enter the code below into this block:<\/p>\n\n\n<pre class=\"wp-block-code\"><code>function OBJ = objectiveFunction(DEC,X_INTERVAL,Y_INIT,PARAMS,NLEoptions,DAEoptions)\n\n\t% if true, the algebraic sub-system of the DAE is solved\n\tif _SOLVEALGEBRAICSUBSYSTEM_\n\t\tY_DIFF_INIT = Y_INIT(1:_DIM_DIFFEQUAS_);\n\t\tY_ALG_INIT = Y_INIT(1+_DIM_DIFFEQUAS_:end);\n\t\tY_ALG_INIT = fsolve (@( Y_ALG ) AESubSystem(Y_ALG,Y_DIFF_INIT,PARAMS,DEC),Y_ALG_INIT,NLEoptions);\n\t\tY_INIT = &#91;Y_DIFF_INIT, Y_ALG_INIT];\n\tend\n\n\t&#91;X,Y] = _ODESOLVER_(@(X,Y)DAESystem(X,Y,PARAMS,DEC),X_INTERVAL,Y_INIT',DAEoptions);\n\n_OBJECTIVE_LOOP_\n\nend<\/code><\/pre>\n\n\n<p>This code optionally solves the algebraic sub-system to initialize the DAE and then calls the DAE solver specified by the user to integrate the system. Within the code, the _OBJECTIVE_LOOP_ is a sub-node of type ObjectiveFunction with the following code:<\/p>\n\n\n<pre class=\"wp-block-code\"><code>\tOBJ = Y(end,end);\n<\/code><\/pre>\n\n\n<p>This code applies if we are interested in the value of the objective at the end. In our application example, the objective is equal to the negative integral of the molar concentration of a specific component. As the integral is formulated as differential equation, we simply need its value at the end of the time horizon.<\/p>\n<h5><span class=\"ez-toc-section\" id=\"Model-equations\"><\/span>Model equations<span class=\"ez-toc-section-end\"><\/span><\/h5>\n<p>The next block writes the DAE system, the algebraic sub-system, and the nonlinear (in)equality constraints:<\/p>\n\n\n<pre class=\"wp-block-code\"><code> function DYDX = DAESystem(X,Y,PARAMS,DEC)\n\n\t% read out differential variable\n_Read_DIFF_VAR_\n\t% read out parameters \n_Read_PARAMS_LOOP_\n\t% read out explicit state variables  \n_Read_STATE_VARS_EXPL_LOOP_\n\t% read out implicit state variables\n_Read_STATE_VARS_IMPL_LOOP_\n_Read_OBJECTIVE_LOOP_\n_Read_DECISIONS_\n_DIR_FUN_CALL_LOOP_\n\t% evaluate the explicit differential equations \n_Calc_EQUAS_ODE_LOOP_\n\t% evaluate the implicit algebraic equations\n_Calc_EQUAS_AE_LOOP_\n\tDYDX=DYDX';\n\nend\n\nfunction DYDX = AESubSystem(Y_ALG,Y_DIFF,PARAMS,DEC)\n\n\tY = &#91;Y_DIFF, Y_ALG];\n\n\t% read out parameters \n_Read_PARAMS_LOOP_\n\t% read out explicit state variables  \n_Read_STATE_VARS_EXPL_LOOP_\n\t% read out implicit state variables\n_Read_STATE_VARS_IMPL_LOOP_\n_Read_OBJECTIVE_LOOP_\n_Read_DECISIONS_\n_DIR_FUN_CALL_LOOP_\n\t% evaluate the explicit differential equations \n_Calc_EQUAS_ODE_LOOP_\n\t% evaluate the implicit algebraic equations\n_Calc_EQUAS_AE_LOOP_\n\tDYDX=DYDX(_DIM_DIFFEQUAS_+1:end)';\n\nend\n\nfunction &#91;c, ceq] = NONLCON(DEC,X_INTERVAL,Y_INIT,PARAMS,NLEoptions,DAEoptions)\n\n\t% if true, the algebraic sub-system of the DAE is solved\n\tif _SOLVEALGEBRAICSUBSYSTEM_\n\t\tY_DIFF_INIT = Y_INIT(1:_DIM_DIFFEQUAS_);\n\t\tY_ALG_INIT = Y_INIT(1+_DIM_DIFFEQUAS_:end);\n\t\tY_ALG_INIT = fsolve (@( Y_ALG ) AESubSystem(Y_ALG,Y_DIFF_INIT,PARAMS,DEC),Y_ALG_INIT,NLEoptions);\n\t\tY_INIT = &#91;Y_DIFF_INIT, Y_ALG_INIT];\n\tend\n\n\t&#91;X,Y] = _ODESOLVER_(@(X,Y)DAESystem(X,Y,PARAMS,DEC),X_INTERVAL,Y_INIT',DAEoptions);\n\n\t% inequality constraints for lower bound\n_Calc_Bounds_STATE_VARS_EXPL_LOOP_\n_Calc_Bounds_STATE_VARS_IMPL_LOOP_\n\tc = &#91;c_lb, c_ub];\n\tceq = &#91;];\n\nend<\/code><\/pre>\n\n\n<p>Again, there are a couple of sub-nodes to read the specific variable and parameter names from the generic variable and parameter vectors <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/mosaic-modeling.de\/wp-content\/ql-cache\/quicklatex.com-42ae22abcaa05c2d6c2fdc3746446019_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#89;\" title=\"Rendered by QuickLaTeX.com\" height=\"12\" width=\"14\" style=\"vertical-align: 0px;\"\/> and <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/mosaic-modeling.de\/wp-content\/ql-cache\/quicklatex.com-3e9d88fb2e0551cb4fa0915d2ae9a816_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#80;&#65;&#82;&#65;&#77;&#83;\" title=\"Rendered by QuickLaTeX.com\" height=\"13\" width=\"85\" style=\"vertical-align: 0px;\"\/>, to read the decision variables <img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/mosaic-modeling.de\/wp-content\/ql-cache\/quicklatex.com-57f95c220fda0a308fa4ae094265a10a_l3.png\" class=\"ql-img-inline-formula quicklatex-auto-format\" alt=\"&#68;&#69;&#67;\" title=\"Rendered by QuickLaTeX.com\" height=\"12\" width=\"43\" style=\"vertical-align: 0px;\"\/>, etc. Details can be found in the UDLS with the ID given at the top of this page.<\/p>\n<h5><span class=\"ez-toc-section\" id=\"Display-results\"><\/span>Display results<span class=\"ez-toc-section-end\"><\/span><\/h5>\n<p>Finally, we want to be able to plot the dynamic profiles of the variables. For this purpose, we define the relatively simple plot function below. More advanced would be to also plot the decision variables over time, etc.<\/p>\n\n\n<pre class=\"wp-block-code\"><code>function displayResults(X,Y)\n\t% decide for a plot type: \n\t%   0 \t-&gt; Plot the variables into individual figures \n\t%   1 \t-&gt; Plot into sub figures \n\t%   2 \t-&gt; Plot all selected into one figure \n\t%   other -&gt; Do not plot \n\tplotType = _PLOTTYPE_; \n\n\t% set a line width: \n\tlinewidth = 1.5; \n\n\t% define which dependent variables should be plotted\n\t%   1 \t-&gt; Plot.\n\t%   other \t-&gt; Do not plot.\n_Plot_Control_State_Vars_\n\n\t% decide wether to normalize the y axis\n\t%   1 \t-&gt; Normalized\n\t%   other \t-&gt; Individual maximum scale\n\taxisControl = 1;\n\n\t%====================================================\n\n\t% labels of the dependent variables\n_Label_State_Vars_\n_Label_Diff_Var_\n\n\t% plot the variables \n\tfigureIndex=1; \n\txMinVal = min(X); \n\txMaxVal = max(X); \n\tyMinVal = min(min(Y)); \n\tyMaxVal = max(max(Y)); \n\tif (plotType==0) \n\t\t% create a plot for each state variable individually \n\t\tfor i=1:_DIM_VARS_\n\t\t\tif (plotControl(i)==1)\n\t\t\t\tfig=figure(i);\n\t\t\t\tset(fig,'defaultTextInterpreter','none')\n\t\t\t\tplot(X,Y(:,i),'LineWidth',linewidth)\n\t\t\t\ttitle('Solution of the DAE equation system');\n\t\t\t\txlabel(xAxisLabel);\n\t\t\t\tylabel(yAxisLabels{i});\n\t\t\t\tif (axisControl==1)\n\t\t\t\t\taxis(&#91;xMinVal xMaxVal min(Y(:,i)) max(Y(:,i))]);\n\t\t\t\tend\n\t\t\t\tlegend(yAxisLabels(i,:));\n\t\t\t\tfigureIndex=figureIndex+1;\n\t\t\tend\n\t\tend\n\telseif (plotType==1)\n\t\t% use a subplot environment\n\t\tfirstTime = 1;\n\t\tnumberOfPlots = sum(plotControl);\n\t\tfig=figure(1);\n\t\tset(fig,'defaultTextInterpreter','none')\n\t\tfor i=1:_DIM_VARS_\n\t\t\tif (plotControl(i)==1)\n\t\t\t\tsubplot(numberOfPlots,1,figureIndex);\n\t\t\t\tplot(X,Y(:,i),'LineWidth',linewidth)\n\t\t\t\tylabel(yAxisLabels{i});\n\t\t\t\tlegend(yAxisLabels{i});\n\t\t\t\tif (axisControl==1)\n\t\t\t\t\taxis(&#91;xMinVal xMaxVal min(Y(:,i)) max(Y(:,i))]);\n\t\t\t\tend\n\t\t\t\tfigureIndex=figureIndex+1;\n\t\t\t\tif (firstTime) \n\t\t\t\t\ttitle('Solution of the DAE equation system');\n\t\t\t\t\tfirstTime = 0;\n\t\t\t\tend \n\t\t\tend \n\t\tend\n\t\txlabel(xAxisLabel);\n\telseif (plotType==2)\n\t\t% plot in one figure\n\t\tcolors = &#91;\n\t\t\t'r'\t% -&gt; Red\n\t\t\t'g' % -&gt; Green\n\t\t\t'b' % -&gt; Blue\n\t\t\t'c' % -&gt; Cyan\n\t\t\t'm' % -&gt; Magenta\n\t\t\t'y' % -&gt; Yellow\n\t\t\t'k' % -&gt; Black\n\t\t\t];\n\t\tcolorCtr=1;\n\t\tmaxColors=7;\n\t\tfig=figure(1);\n\t\tset(fig,'defaultTextInterpreter','none')\n\t\thold on;\n\t\tfor i=1:_DIM_VARS_\n\t\t\tif (plotControl(i)==1)\n\t\t\t\tlinespec = colors(colorCtr);\n\t\t\t\tif (colorCtr&lt;=maxColors)\n\t\t\t\t\tcolorCtr = colorCtr+1;\n\t\t\t\tend\n\t\t\t\tplot(X,Y(:,i),linespec,'LineWidth',linewidth);\n\t\t\tend\n\t\tend\n\t\ttitle('Solution of the DAE equation system');\n\t\txlabel(xAxisLabel);\n\t\tylabel(yAxisLabels{i});\n\t\tlegend(yAxisLabels{:});\n\t\thold off;\n\tend\n\n\nend\n<\/code><\/pre>\n\n\n<p>Once you have tested the UDLS, save it so that is available in the future.<\/p>","protected":false},"excerpt":{"rendered":"<p>Goal In this example, we will set up a UDLS for sequential optimization in Matlab. The UDLS is available in MOSAICmodeling with ID 185804. Workflow for setting up a UDLS A UDLS is set up in the &#8220;Miscellaneous&#8221; section of MOSAICmodeling in the tab Language Specification. Should this tab be invisible to you and you [&hellip;]<\/p>\n","protected":false},"author":252,"featured_media":0,"parent":5484,"menu_order":1,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-5833","page","type-page","status-publish","czr-hentry"],"_links":{"self":[{"href":"https:\/\/mosaic-modeling.de\/index.php?rest_route=\/wp\/v2\/pages\/5833","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/mosaic-modeling.de\/index.php?rest_route=\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/mosaic-modeling.de\/index.php?rest_route=\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/mosaic-modeling.de\/index.php?rest_route=\/wp\/v2\/users\/252"}],"replies":[{"embeddable":true,"href":"https:\/\/mosaic-modeling.de\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=5833"}],"version-history":[{"count":17,"href":"https:\/\/mosaic-modeling.de\/index.php?rest_route=\/wp\/v2\/pages\/5833\/revisions"}],"predecessor-version":[{"id":5915,"href":"https:\/\/mosaic-modeling.de\/index.php?rest_route=\/wp\/v2\/pages\/5833\/revisions\/5915"}],"up":[{"embeddable":true,"href":"https:\/\/mosaic-modeling.de\/index.php?rest_route=\/wp\/v2\/pages\/5484"}],"wp:attachment":[{"href":"https:\/\/mosaic-modeling.de\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=5833"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}