#+TITLE: Control Optimization
:DRAWER:
#+LANGUAGE: en
#+EMAIL: dehaeze.thomas@gmail.com
#+AUTHOR: Dehaeze Thomas

#+HTML_LINK_HOME: ../index.html
#+HTML_LINK_UP:   ../index.html

#+HTML_HEAD: <link rel="stylesheet" type="text/css" href="https://research.tdehaeze.xyz/css/style.css"/>
#+HTML_HEAD: <script type="text/javascript" src="https://research.tdehaeze.xyz/js/script.js"></script>

#+BIND: org-latex-image-default-option "scale=1"
#+BIND: org-latex-image-default-width ""

#+LaTeX_CLASS: scrreprt
#+LaTeX_CLASS_OPTIONS: [a4paper, 10pt, DIV=12, parskip=full, bibliography=totoc]
#+LATEX_HEADER: \input{preamble.tex}
#+LATEX_HEADER_EXTRA: \input{preamble_extra.tex}
#+LATEX_HEADER_EXTRA: \bibliography{nass-control.bib}

#+BIND: org-latex-bib-compiler "biber"

#+PROPERTY: header-args:matlab  :session *MATLAB*
#+PROPERTY: header-args:matlab+ :comments no
#+PROPERTY: header-args:matlab+ :exports none
#+PROPERTY: header-args:matlab+ :results none
#+PROPERTY: header-args:matlab+ :eval no-export
#+PROPERTY: header-args:matlab+ :noweb yes
#+PROPERTY: header-args:matlab+ :mkdirp yes
#+PROPERTY: header-args:matlab+ :output-dir figs
#+PROPERTY: header-args:matlab+ :tangle no

#+PROPERTY: header-args:latex  :headers '("\\usepackage{tikz}" "\\usepackage{import}" "\\import{$HOME/Cloud/tikz/org/}{config.tex}")
#+PROPERTY: header-args:latex+ :imagemagick t :fit yes
#+PROPERTY: header-args:latex+ :iminoptions -scale 100% -density 150
#+PROPERTY: header-args:latex+ :imoutoptions -quality 100
#+PROPERTY: header-args:latex+ :results file raw replace
#+PROPERTY: header-args:latex+ :buffer no
#+PROPERTY: header-args:latex+ :tangle no
#+PROPERTY: header-args:latex+ :eval no-export
#+PROPERTY: header-args:latex+ :exports results
#+PROPERTY: header-args:latex+ :mkdirp yes
#+PROPERTY: header-args:latex+ :output-dir figs
#+PROPERTY: header-args:latex+ :post pdf2svg(file=*this*, ext="png")
:END:

#+latex: \clearpage

* Build                                                             :noexport:
#+NAME: startblock
#+BEGIN_SRC emacs-lisp :results none :tangle no
(add-to-list 'org-latex-classes
             '("scrreprt"
               "\\documentclass{scrreprt}"
               ("\\chapter{%s}" . "\\chapter*{%s}")
               ("\\section{%s}" . "\\section*{%s}")
               ("\\subsection{%s}" . "\\subsection*{%s}")
               ("\\paragraph{%s}" . "\\paragraph*{%s}")
               ))

;; Remove automatic org heading labels
(defun my-latex-filter-removeOrgAutoLabels (text backend info)
  "Org-mode automatically generates labels for headings despite explicit use of `#+LABEL`. This filter forcibly removes all automatically generated org-labels in headings."
  (when (org-export-derived-backend-p backend 'latex)
    (replace-regexp-in-string "\\\\label{sec:flexible_org[a-f0-9]+}\n" "" text)))
(add-to-list 'org-export-filter-headline-functions
             'my-latex-filter-removeOrgAutoLabels)

;; Remove all org comments in the output LaTeX file
(defun delete-org-comments (backend)
  (loop for comment in (reverse (org-element-map (org-element-parse-buffer)
                                    'comment 'identity))
        do
        (setf (buffer-substring (org-element-property :begin comment)
                                (org-element-property :end comment))
              "")))
(add-hook 'org-export-before-processing-hook 'delete-org-comments)

;; Use no package by default
(setq org-latex-packages-alist nil)
(setq org-latex-default-packages-alist nil)

;; Do not include the subtitle inside the title
(setq org-latex-subtitle-separate t)
(setq org-latex-subtitle-format "\\subtitle{%s}")

(setq org-export-before-parsing-hook '(org-ref-glossary-before-parsing
                                       org-ref-acronyms-before-parsing))
#+END_SRC

* Notes                                                             :noexport:
** Notes

Prefix is =detail_control=

Up to now, basic control strategy ("decentralized" control in the frame of the struts), HAC-LAC

Discussion about:
- *Use multiple sensors*: Discussion about two sensor control VS HAC-LAC VS Sensor Fusion ?
- *Decoupling strategies*
  - [ ] file:~/Cloud/research/matlab/decoupling-strategies/svd-control.org
- *Control optimization*

** DONE [#A] Fix the outline
CLOSED: [2025-04-03 Thu 12:01]

Lot is already discussed in:
- A5 [[file:~/Cloud/work-projects/ID31-NASS/phd-thesis-chapters/A5-simscape-nano-hexapod/simscape-nano-hexapod.org::*Control of Stewart Platforms][Control of Stewart Platforms]]
- Some will be discussed in the geometry optimization (cubic configuration / decoupling / ...)

- [ ] Maybe do not write this section at all?

** DONE [#B] Papers to be included here
CLOSED: [2025-04-03 Thu 12:01]

- [X] H-infinity synthesis of complementary filters:
  [[file:~/Cloud/research/papers/published/dehaeze19_compl_filter_shapin_using_synth/index.org][file:~/Cloud/research/papers/published/dehaeze19_compl_filter_shapin_using_synth/index.org]]
  Or newer version: [[file:~/Cloud/research/papers/dehaeze21_desig_compl_filte/journal/dehaeze21_desig_compl_filte.org][file:~/Cloud/research/papers/dehaeze21_desig_compl_filte/journal/dehaeze21_desig_compl_filte.org]]
- [X] Virtual sensor fusion
  [[file:~/Cloud/research/papers/published/verma19_virtu_senso_fusio_high_preci_contr/elsarticle-template-harv.tex][file:~/Cloud/research/papers/published/verma19_virtu_senso_fusio_high_preci_contr/elsarticle-template-harv.tex]]
  Maybe not this one.
- [X] Feedback control based on complementary filters:
  [[file:~/Cloud/research/papers/dehaeze20_virtu_senso_fusio/index.org][file:~/Cloud/research/papers/dehaeze20_virtu_senso_fusio/index.org]]

** TODO [#A] Copy Paper about Complementary Filter Design
SCHEDULED: <2025-04-03 Thu>

[[file:~/Cloud/research/papers/dehaeze21_desig_compl_filte/journal/dehaeze21_desig_compl_filte.org][file:~/Cloud/research/papers/dehaeze21_desig_compl_filte/journal/dehaeze21_desig_compl_filte.org]]

- [ ] Copy Matlab Code: [[file:~/Cloud/research/papers/dehaeze21_desig_compl_filte/matlab/dehaeze21_desig_compl_filte_matlab.org]]
- [X] Copy Tikz Code: [[file:~/Cloud/research/papers/dehaeze21_desig_compl_filte/tikz/dehaeze21_desig_compl_filte_tikz.org]]
- [ ] Rework all labels:
  - [ ] sections
  - [ ] equations
  - [ ] tables

** TODO [#A] Review of control for Stewart platforms?

[[file:~/Cloud/work-projects/ID31-NASS/matlab/stewart-simscape/org/bibliography.org::*Control][Control]]

Or html version: https://research.tdehaeze.xyz/stewart-simscape/docs/bibliography.html

** TODO [#C] Discuss different strategies?

- Robust control
- Adaptive control
- etc...

* Introduction                                                        :ignore:

When controlling a MIMO system (specifically parallel manipulator such as the Stewart platform?)

Several considerations:
- Section ref:sec:detail_control_multiple_sensor: How to most effectively use/combine multiple sensors
- Section ref:sec:detail_control_decoupling: How to decouple a system
- Section ref:sec:detail_control_optimization: How to design the controller

* Multiple Sensor Control
:PROPERTIES:
:HEADER-ARGS:matlab+: :tangle matlab/detail_control_1_complementary_filtering.m
:END:
<<sec:detail_control_multiple_sensor>>

** Introduction                                                      :ignore:

# *This section is based on*:
# - file:~/Cloud/research/papers/published/dehaeze19_compl_filter_shapin_using_synth/index.org
#   *Or newer version:* [[file:~/Cloud/research/papers/dehaeze21_desig_compl_filte/journal/dehaeze21_desig_compl_filte.org][file:~/Cloud/research/papers/dehaeze21_desig_compl_filte/journal/dehaeze21_desig_compl_filte.org]]
*Look at what was done in the introduction [[file:~/Cloud/work-projects/ID31-NASS/phd-thesis-chapters/A0-nass-introduction/nass-introduction.org::*Stewart platforms: Control architecture][Stewart platforms: Control architecture]]*

Explain why multiple sensors are sometimes beneficial:
- collocated sensor that guarantee stability, but is still useful to damp modes outside the bandwidth of the controller using sensor measuring the performance objective

- Review for Stewart platform => Table
  [[file:~/Cloud/work-projects/ID31-NASS/matlab/stewart-simscape/org/bibliography.org::*Multi Sensor Control][Multi Sensor Control]]
  Several sensors:
  - force sensor, inertial, strain ...
  Several architectures:
  - Sensor fusion
  - Cascaded control
  - Two sensor control
  [[cite:&beijen14_two_sensor_contr_activ_vibrat]]
  [[cite:&yong16_high_speed_vertic_posit_stage]]

#+begin_src latex :file detail_control_architecture_hac_lac.pdf
\begin{tikzpicture}
  % Blocs
  \node[block={2.0cm}{2.0cm}] (P) {Plant};
  \coordinate[] (input)   at ($(P.south west)!0.5!(P.north west)$);
  \coordinate[] (outputH) at ($(P.south east)!0.2!(P.north east)$);
  \coordinate[] (outputL) at ($(P.south east)!0.8!(P.north east)$);

  \node[block, above=0.2 of P] (Klac) {$K_\text{LAC}$};
  \node[addb, left=0.5 of input] (addF) {};
  \node[block, left=0.6 of addF] (Khac) {$K_\text{HAC}$};
  % \node[addb={+}{}{}{}{-}, left=0.5 of Khac] (subr) {};

  % Connections and labels
  \draw[->] (outputL) -- ++(0.5, 0) coordinate(eastlac) |- (Klac.east);
  \node[above right] at (outputL){$x^\prime$};
  \draw[->] (Klac.west) -| (addF.north);
  \draw[->] (addF.east) -- (input) node[above left]{$u$};

  % \draw[<-] (subr.west)node[above left]{$r$} -- ++(-0.5, 0);
  % \draw[->] (outputH) -- ++(0.5, 0)  -- ++(0, -1.0) -| (subr.south);
  \draw[->] (outputH) -- ++(0.5, 0)  -- ++(0, -0.7) -| ($(Khac.west)+(-0.5, 0)$) -- (Khac.west);
  \node[above right] at (outputH){$x$};
  % \draw[->] (subr.east) -- (Khac.west) node[above left]{$\epsilon$};
  \draw[->] (Khac.east) node[above right]{$u^\prime$} -- (addF.west);

  \begin{scope}[on background layer]
    \node[fit={(Klac.north-|eastlac) (addF.west|-P.south)}, fill=black!20!white, draw, dashed, inner sep=4pt] (Pi) {};
    % \node[anchor={north west}, align=left] at (Pi.north west){\scriptsize{Damped}\\\scriptsize{Plant}};
    \node[above=0 of Pi]{\scriptsize{Damped Plant}};
  \end{scope}
\end{tikzpicture}
#+end_src

#+begin_src latex :file detail_control_architecture_sensor_fusion.pdf
\begin{tikzpicture}
  % Blocs
  \node[block={2.0cm}{2.0cm}] (P) {Plant};
  \coordinate[] (input)    at ($(P.south west)!0.5!(P.north west)$);
  \coordinate[] (outputH)  at ($(P.south east)!0.2!(P.north east)$);
  \coordinate[] (outputL)  at ($(P.south east)!0.8!(P.north east)$);
  \coordinate[] (outputSS) at ($(P.south east)!0.5!(P.north east)$);

  \node[block, right=0.8 of outputH] (KH) {$H_\text{HPF}$};
  \node[block, right=0.8 of outputL] (KL) {$H_\text{LPF}$};
  \node[addb={+}{}{}{}{}, right=2.2 of outputSS] (addss) {};
  \node[block, left=0.6 of input] (K) {$K_{ss}$};

  % Connections and labels
  \draw[->] (outputL) -- (KL.west);
  \draw[->] (outputH) -- (KH.west);
  \node[above right] at (outputL){$x_L$};
  \node[above right] at (outputH){$x_H$};
  \draw[->] (KL.east) -| (addss.north);
  \draw[->] (KH.east) -| (addss.south);
  \draw[->] (addss.east) -- ++(0.9, 0);
  \draw[->] ($(addss.east) + (0.5, 0)$)node[branch]{}node[above]{$x_{ss}$} -- ++(0, -1.6) -| ($(K.west)+(-0.5, 0)$) -- (K.west);
  \draw[->] (K.east) -- (input) node[above left]{$u$};

  \begin{scope}[on background layer]
    \node[fit={(KL.north west) (KH.south-|addss.east)}, fill=black!20!white, draw, dashed, inner sep=4pt] (Pss) {};
    \node[above=0 of Pss]{\scriptsize{Sensor Fusion}};
  \end{scope}
\end{tikzpicture}
#+end_src

#+begin_src latex :file detail_control_architecture_two_sensor_control.pdf
\begin{tikzpicture}
  % Blocs
  \node[block={2.0cm}{2.0cm}] (P) {Plant};
  \coordinate[] (input)    at ($(P.south west)!0.5!(P.north west)$);
  \coordinate[] (output1)  at ($(P.south east)!0.8!(P.north east)$);
  \coordinate[] (output2)  at ($(P.south east)!0.2!(P.north east)$);

  \node[addb={+}{}{}{}{}, left=0.8 of input] (addF) {};
  \coordinate[left= 1.0 of addF] (Ks);
  \node[block] (K1) at (Ks|-output1) {$K_\text{1}$};
  \node[block] (K2) at (Ks|-output2) {$K_\text{2}$};

  \draw[->] (output1) -| ++(0.6, 1.2) -| ($(K1.west)+(-0.5, 0)$) -- (K1.west);
  \draw[->] (output2) -| ++(0.6,-1.0) -| ($(K2.west)+(-0.5, 0)$) -- (K2.west);

  \draw[->] (K1.east)node[above right]{$u_1$} -| (addF.north);
  \draw[->] (K2.east)node[above right]{$u_2$} -| (addF.south);
  \draw[->] (addF.east) -- (input) node[above left=0 and 0.2]{$u$};

  \node[above right] at (output1){$x_1$};
  \node[above right] at (output2){$x_2$};

  \begin{scope}[on background layer]
    \node[fit={(K1.north west) (K2.south-|addF.east)}, fill=black!20!white, draw, dashed, inner sep=4pt] (Pss) {};
    \node[above=0 of Pss]{\scriptsize{Two-Sensor Control}};
  \end{scope}
\end{tikzpicture}
#+end_src

#+name: fig:detail_control_control_multiple_sensors
#+caption: Different control strategies when using multiple sensors. High Authority Control / Low Authority Control (\subref{fig:detail_control_architecture_hac_lac}). Sensor Fusion (\subref{fig:detail_control_architecture_sensor_fusion}). Two-Sensor Control (\subref{fig:detail_control_architecture_two_sensor_control})
#+attr_latex: :options [htbp]
#+begin_figure
#+attr_latex: :caption \subcaption{\label{fig:detail_control_architecture_hac_lac} HAC-LAC}
#+attr_latex: :options {0.48\textwidth}
#+begin_subfigure
#+attr_latex: :scale 1
[[file:figs/detail_control_architecture_hac_lac.png]]
#+end_subfigure
#+attr_latex: :caption \subcaption{\label{fig:detail_control_architecture_two_sensor_control} Two Sensor Control}
#+attr_latex: :options {0.48\textwidth}
#+begin_subfigure
#+attr_latex: :scale 1
[[file:figs/detail_control_architecture_two_sensor_control.png]]
#+end_subfigure

\bigskip
#+attr_latex: :caption \subcaption{\label{fig:detail_control_architecture_sensor_fusion} Sensor Fusion}
#+attr_latex: :options {0.95\textwidth}
#+begin_subfigure
#+attr_latex: :scale 1
[[file:figs/detail_control_architecture_sensor_fusion.png]]
#+end_subfigure
#+end_figure


Cascaded control / HAC-LAC Architecture was already discussed during the conceptual phase.
This is a very comprehensive approach that proved to give good performances.

On the other hand of the spectrum, the two sensor approach yields to more control design freedom.
But it is also more complex.

In this section, we wish to study if sensor fusion can be an option for multi-sensor control:
- may be used to optimize the noise characteristics
- optimize the dynamical uncertainty

While there are different ways to fuse sensors:
- complementary filters
- kalman filtering

The focus is made here on complementary filters, as they give a simple frequency analysis.



Measuring a physical quantity using sensors is always subject to several limitations.
First, the accuracy of the measurement is affected by several noise sources, such as electrical noise of the conditioning electronics being used.
Second, the frequency range in which the measurement is relevant is bounded by the bandwidth of the sensor.
One way to overcome these limitations is to combine several sensors using a technique called "sensor fusion" [[cite:&bendat57_optim_filter_indep_measur_two]].
Fortunately, a wide variety of sensors exists, each with different characteristics.
By carefully choosing the fused sensors, a so called "super sensor" is obtained that can combines benefits of the individual sensors.

In some situations, sensor fusion is used to increase the bandwidth of the measurement [[cite:&shaw90_bandw_enhan_posit_measur_using_measur_accel;&zimmermann92_high_bandw_orien_measur_contr;&min15_compl_filter_desig_angle_estim]].
For instance, in [[cite:&shaw90_bandw_enhan_posit_measur_using_measur_accel]] the bandwidth of a position sensor is increased by fusing it with an accelerometer providing the high frequency motion information.
For other applications, sensor fusion is used to obtain an estimate of the measured quantity with lower noise [[cite:&hua05_low_ligo;&hua04_polyp_fir_compl_filter_contr_system;&plummer06_optim_compl_filter_their_applic_motion_measur;&robert12_introd_random_signal_applied_kalman]].
More recently, the fusion of sensors measuring different physical quantities has been proposed to obtain interesting properties for control [[cite:&collette15_sensor_fusion_method_high_perfor;&yong16_high_speed_vertic_posit_stage]].
In [[cite:&collette15_sensor_fusion_method_high_perfor]], an inertial sensor used for active vibration isolation is fused with a sensor collocated with the actuator for improving the stability margins of the feedback controller.

Practical applications of sensor fusion are numerous.
It is widely used for the attitude estimation of several autonomous vehicles such as unmanned aerial vehicle [[cite:&baerveldt97_low_cost_low_weigh_attit;&corke04_inert_visual_sensin_system_small_auton_helic;&jensen13_basic_uas]] and underwater vehicles [[cite:&pascoal99_navig_system_desig_using_time;&batista10_optim_posit_veloc_navig_filter_auton_vehic]].
Naturally, it is of great benefits for high performance positioning control as shown in [[cite:&shaw90_bandw_enhan_posit_measur_using_measur_accel;&zimmermann92_high_bandw_orien_measur_contr;&min15_compl_filter_desig_angle_estim;&yong16_high_speed_vertic_posit_stage]].
Sensor fusion was also shown to be a key technology to improve the performance of active vibration isolation systems [[cite:&tjepkema12_sensor_fusion_activ_vibrat_isolat_precis_equip]].
Emblematic examples are the isolation stages of gravitational wave detectors [[cite:&collette15_sensor_fusion_method_high_perfor;&heijningen18_low]] such as the ones used at the LIGO [[cite:&hua05_low_ligo;&hua04_polyp_fir_compl_filter_contr_system]] and at the Virgo [[cite:&lucia18_low_frequen_optim_perfor_advan]].

There are mainly two ways to perform sensor fusion: either using a set of complementary filters [[cite:&anderson53_instr_approac_system_steer_comput]] or using Kalman filtering [[cite:&brown72_integ_navig_system_kalman_filter]].
For sensor fusion applications, both methods are sharing many relationships [[cite:&brown72_integ_navig_system_kalman_filter;&higgins75_compar_compl_kalman_filter;&robert12_introd_random_signal_applied_kalman;&fonseca15_compl]].
However, for Kalman filtering, assumptions must be made about the probabilistic character of the sensor noises [[cite:&robert12_introd_random_signal_applied_kalman]] whereas it is not the case with complementary filters.
Furthermore, the advantages of complementary filters over Kalman filtering for sensor fusion are their general applicability, their low computational cost [[cite:&higgins75_compar_compl_kalman_filter]], and the fact that they are intuitive as their effects can be easily interpreted in the frequency domain.

A set of filters is said to be complementary if the sum of their transfer functions is equal to one at all frequencies.
In the early days of complementary filtering, analog circuits were employed to physically realize the filters [[cite:&anderson53_instr_approac_system_steer_comput]].
Analog complementary filters are still used today [[cite:&yong16_high_speed_vertic_posit_stage;&moore19_capac_instr_sensor_fusion_high_bandw_nanop]], but most of the time they are now implemented digitally as it allows for much more flexibility.

Several design methods have been developed over the years to optimize complementary filters.
The easiest way to design complementary filters is to use analytical formulas.
Depending on the application, the formulas used are of first order [[cite:&corke04_inert_visual_sensin_system_small_auton_helic;&yeh05_model_contr_hydraul_actuat_two;&yong16_high_speed_vertic_posit_stage]], second order [[cite:&baerveldt97_low_cost_low_weigh_attit;&stoten01_fusion_kinet_data_using_compos_filter;&jensen13_basic_uas]] or even higher orders [[cite:&shaw90_bandw_enhan_posit_measur_using_measur_accel;&zimmermann92_high_bandw_orien_measur_contr;&stoten01_fusion_kinet_data_using_compos_filter;&collette15_sensor_fusion_method_high_perfor;&matichard15_seism_isolat_advan_ligo]].

As the characteristics of the super sensor depends on the proper design of the complementary filters [[cite:&dehaeze19_compl_filter_shapin_using_synth]], several optimization techniques have been developed.
Some are based on the finding of optimal parameters of analytical formulas [[cite:&jensen13_basic_uas;&min15_compl_filter_desig_angle_estim;&fonseca15_compl]], while other are using convex optimization tools [[cite:&hua04_polyp_fir_compl_filter_contr_system;&hua05_low_ligo]] such as linear matrix inequalities [[cite:&pascoal99_navig_system_desig_using_time]].
As shown in [[cite:&plummer06_optim_compl_filter_their_applic_motion_measur]], the design of complementary filters can also be linked to the standard mixed-sensitivity control problem.
Therefore, all the powerful tools developed for the classical control theory can also be used for the design of complementary filters.
For instance, in [[cite:&jensen13_basic_uas]] the two gains of a Proportional Integral (PI) controller are optimized to minimize the noise of the super sensor.

The common objective of all these complementary filters design methods is to obtain a super sensor that has desired characteristics, usually in terms of noise and dynamics.
Moreover, as reported in [[cite:&zimmermann92_high_bandw_orien_measur_contr;&plummer06_optim_compl_filter_their_applic_motion_measur]], phase shifts and magnitude bumps of the super sensors dynamics can be observed if either the complementary filters are poorly designed or if the sensors are not well calibrated.
Hence, the robustness of the fusion is also of concern when designing the complementary filters.
Although many design methods of complementary filters have been proposed in the literature, no simple method that allows to specify the desired super sensor characteristic while ensuring good fusion robustness has been proposed.

Fortunately, both the robustness of the fusion and the super sensor characteristics can be linked to the magnitude of the complementary filters [[cite:&dehaeze19_compl_filter_shapin_using_synth]].
Based on that, this paper introduces a new way to design complementary filters using the $\mathcal{H}_\infty$ synthesis which allows to shape the complementary filters' magnitude in an easy and intuitive way.


** Matlab Init                                              :noexport:ignore:
#+begin_src matlab :tangle no :exports none :results silent :noweb yes :var current_dir=(file-name-directory buffer-file-name)
<<matlab-dir>>
#+end_src

#+begin_src matlab :exports none :results silent :noweb yes
<<matlab-init>>
#+end_src

#+begin_src matlab :tangle no :noweb yes
<<m-init-path>>
#+end_src

#+begin_src matlab :eval no :noweb yes
<<m-init-path-tangle>>
#+end_src

#+begin_src matlab :noweb yes
<<m-init-other>>
#+end_src

** Sensor Fusion and Complementary Filters Requirements
<<sec:detail_control_sensor_fusion_requirements>>
*** Introduction                                                      :ignore:

Complementary filtering provides a framework for fusing signals from different sensors.
As the effectiveness of the fusion depends on the proper design of the complementary filters, they are expected to fulfill certain requirements.
These requirements are discussed in this section.

*** Sensor Fusion Architecture
<<sec:detail_control_sensor_fusion>>

A general sensor fusion architecture using complementary filters is shown in Fig. ref:fig:detail_control_sensor_fusion_overview where several sensors (here two) are measuring the same physical quantity $x$.
The two sensors output signals $\hat{x}_1$ and $\hat{x}_2$ are estimates of $x$.
These estimates are then filtered out by complementary filters and combined to form a new estimate $\hat{x}$.

The resulting sensor, termed as super sensor, can have larger bandwidth and better noise characteristics in comparison to the individual sensors.
This means that the super sensor provides an estimate $\hat{x}$ of $x$ which can be more accurate over a larger frequency band than the outputs of the individual sensors.

#+begin_src latex :file detail_control_sensor_fusion_overview.pdf
\tikzset{block/.default={0.8cm}{0.8cm}}
\tikzset{addb/.append style={scale=0.7}}
\tikzset{node distance=0.6}
\begin{tikzpicture}
  \node[branch] (x) at (0, 0);
  \node[block, above right=0.3 and 0.5 of x](sensor1){Sensor 1};
  \node[block, below right=0.3 and 0.5 of x](sensor2){Sensor 2};

  \node[block, right=1.1 of sensor1](H1){$H_1(s)$};
  \node[block, right=1.1 of sensor2](H2){$H_2(s)$};

  \node[addb, right=5.0 of x](add){};

  \draw[] ($(x)+(-0.7, 0)$) node[above right]{$x$} -- (x.center);
  \draw[->] (x.center) |- (sensor1.west);
  \draw[->] (x.center) |- (sensor2.west);
  \draw[->] (sensor1.east) -- node[midway, above]{$\hat{x}_1$} (H1.west);
  \draw[->] (sensor2.east) -- node[midway, above]{$\hat{x}_2$} (H2.west);
  \draw[->] (H1) -| (add.north);
  \draw[->] (H2) -| (add.south);
  \draw[->] (add.east) -- ++(0.9, 0) node[above left]{$\hat{x}$};

  \begin{scope}[on background layer]
    \node[fit={($(H2.south-|x) + (0, -0.2)$) ($(H1.north-|add.east) + (0.2, 0.6)$)}, fill=black!10!white, draw, inner sep=6pt] (supersensor) {};
    \node[below] at (supersensor.north) {Super Sensor};

    \node[fit={(sensor2.south west) (sensor1.north east)}, fill=black!20!white, draw, inner sep=6pt] (sensors) {};
    \node[align=center] at (sensors.center) {{\tiny Normalized}\\[-0.5em]{\tiny Sensors}};

    \node[fit={(H2.south west) (H1.north-|add.east)}, fill=black!20!white, draw, inner sep=6pt] (filters) {};
    \node[align=center] at ($(filters.center) + (-0.3, 0)$) {{\tiny Complementary}\\[-0.5em]{\tiny Filters}};
  \end{scope}
\end{tikzpicture}
#+end_src

#+name: fig:detail_control_sensor_fusion_overview
#+caption: Schematic of a sensor fusion architecture using complementary filters.
#+RESULTS:
[[file:figs/detail_control_sensor_fusion_overview.png]]

The complementary property of filters $H_1(s)$ and $H_2(s)$ implies that the sum of their transfer functions is equal to one.
That is, unity magnitude and zero phase at all frequencies.
Therefore, a pair of complementary filter needs to satisfy the following condition:

\begin{equation}\label{eq:detail_control_comp_filter}
  H_1(s) + H_2(s) = 1
\end{equation}

It will soon become clear why the complementary property is important for the sensor fusion architecture.

*** Sensor Models and Sensor Normalization
<<sec:detail_control_sensor_models>>

In order to study such sensor fusion architecture, a model for the sensors is required.
Such model is shown in Fig. ref:fig:detail_control_sensor_model and consists of a linear time invariant (LTI) system $G_i(s)$ representing the sensor dynamics and an input $n_i$ representing the sensor noise.
The model input $x$ is the measured physical quantity and its output $\tilde{x}_i$ is the "raw" output of the sensor.

Before filtering the sensor outputs $\tilde{x}_i$ by the complementary filters, the sensors are usually normalized to simplify the fusion.
This normalization consists of using an estimate $\hat{G}_i(s)$ of the sensor dynamics $G_i(s)$, and filtering the sensor output by the inverse of this estimate $\hat{G}_i^{-1}(s)$ as shown in Fig. ref:fig:detail_control_sensor_model_calibrated.
It is here supposed that the sensor inverse $\hat{G}_i^{-1}(s)$ is proper and stable.
This way, the units of the estimates $\hat{x}_i$ are equal to the units of the physical quantity $x$.
The sensor dynamics estimate $\hat{G}_i(s)$ can be a simple gain or a more complex transfer function.

#+begin_src latex :file detail_control_sensor_model.pdf
\tikzset{block/.default={0.8cm}{0.8cm}}
\tikzset{addb/.append style={scale=0.7}}
\tikzset{node distance=0.6}
\begin{tikzpicture}
  \node[addb](add1){};
  \node[block, right=0.8 of add1](G1){$G_i(s)$};

  \draw[->] ($(add1.west)+(-0.7, 0)$) node[above right]{$x$} -- (add1.west);
  \draw[<-] (add1.north) -- ++(0, 0.7)node[below right](n1){$n_i$};
  \draw[->] (add1.east) -- (G1.west);
  \draw[->] (G1.east) -- ++(0.7, 0) node[above left]{$\tilde{x}_i$};

  \begin{scope}[on background layer]
    \node[fit={(add1.west |- G1.south) (n1.north -| G1.east)}, fill=black!20!white, draw, inner sep=3pt] (sensor1) {};
    \node[below left] at (sensor1.north east) {Sensor};
  \end{scope}
\end{tikzpicture}
#+end_src

#+begin_src latex :file detail_control_sensor_model_calibrated.pdf
\tikzset{block/.default={0.8cm}{0.8cm}}
\tikzset{addb/.append style={scale=0.7}}
\tikzset{node distance=0.6}
\begin{tikzpicture}
  \node[addb](add1){};
  \node[block, right=0.8 of add1](G1){$G_i(s)$};
  \node[block, right=0.8 of G1](G1inv){$\hat{G}_i^{-1}(s)$};

  \draw[->] ($(add1.west)+(-0.7, 0)$) node[above right]{$x$} -- (add1.west);
  \draw[<-] (add1.north) -- ++(0, 0.7)node[below right](n1){$n_i$};
  \draw[->] (add1.east) -- (G1.west);
  \draw[->] (G1.east) -- (G1inv.west) node[above left]{$\tilde{x}_i$};
  \draw[->] (G1inv.east) -- ++(0.8, 0) node[above left]{$\hat{x}_i$};

  \begin{scope}[on background layer]
    \node[fit={(add1.west |- G1inv.south) (n1.north -| G1inv.east)}, fill=black!10!white, draw, inner sep=6pt] (sensor1cal) {};
    \node[below left, align=right] at (sensor1cal.north east) {{\tiny Normalized}\\[-0.5em]{\tiny sensor}};

    \node[fit={(add1.west |- G1.south) (n1.north -| G1.east)}, fill=black!20!white, draw, inner sep=3pt] (sensor1) {};
    \node[below left] at (sensor1.north east) {Sensor};
  \end{scope}
\end{tikzpicture}
#+end_src

#+name: fig:detail_control_sensor_models
#+caption: Sensor models with and without normalization.
#+attr_latex: :options [htbp]
#+begin_figure
#+attr_latex: :caption \subcaption{\label{fig:detail_control_sensor_model}Basic sensor model consisting of a noise input $n_i$ and a linear time invariant transfer function $G_i(s)$}
#+attr_latex: :options {0.48\textwidth}
#+begin_subfigure
#+attr_latex: :scale 1
[[file:figs/detail_control_sensor_model.png]]
#+end_subfigure
#+attr_latex: :caption \subcaption{\label{fig:detail_control_sensor_model_calibrated}Normalized sensors using the inverse of an estimate $\hat{G}}
#+attr_latex: :options {0.48\textwidth}
#+begin_subfigure
#+attr_latex: :scale 1
[[file:figs/detail_control_sensor_model_calibrated.png]]
#+end_subfigure
#+end_figure

Two normalized sensors are then combined to form a super sensor as shown in Fig. ref:fig:detail_control_fusion_super_sensor.
The two sensors are measuring the same physical quantity $x$ with dynamics $G_1(s)$ and $G_2(s)$, and with /uncorrelated/ noises $n_1$ and $n_2$.
The signals from both normalized sensors are fed into two complementary filters $H_1(s)$ and $H_2(s)$ and then combined to yield an estimate $\hat{x}$ of $x$.

The super sensor output is therefore equal to:

\begin{equation}\label{eq:detail_control_comp_filter_estimate}
  \hat{x} = \Big( H_1(s) \hat{G}_1^{-1}(s) G_1(s) + H_2(s) \hat{G}_2^{-1}(s) G_2(s) \Big) x + H_1(s) \hat{G}_1^{-1}(s) G_1(s) n_1 + H_2(s) \hat{G}_2^{-1}(s) G_2(s) n_2
\end{equation}

#+begin_src latex :file detail_control_fusion_super_sensor.pdf
\tikzset{block/.default={0.8cm}{0.8cm}}
\tikzset{addb/.append style={scale=0.7}}
\tikzset{node distance=0.6}
\begin{tikzpicture}
  \node[branch] (x) at (0, 0);
  \node[addb, above right=0.8 and 0.5 of x](add1){};
  \node[addb, below right=0.8 and 0.5 of x](add2){};
  \node[block, right=0.8 of add1](G1){$G_1(s)$};
  \node[block, right=0.8 of add2](G2){$G_2(s)$};
  \node[block, right=0.8 of G1](G1inv){$\hat{G}_1^{-1}(s)$};
  \node[block, right=0.8 of G2](G2inv){$\hat{G}_2^{-2}(s)$};
  \node[block, right=0.8 of G1inv](H1){$H_1(s)$};
  \node[block, right=0.8 of G2inv](H2){$H_2(s)$};
  \node[addb, right=7 of x](add){};

  \draw[] ($(x)+(-0.7, 0)$) node[above right]{$x$} -- (x.center);
  \draw[->] (x.center) |- (add1.west);
  \draw[->] (x.center) |- (add2.west);
  \draw[<-] (add1.north) -- ++(0, 0.7)node[below right](n1){$n_1$};
  \draw[->] (add1.east) -- (G1.west);
  \draw[->] (G1.east) -- (G1inv.west) node[above left]{$\tilde{x}_1$};
  \draw[->] (G1inv.east) -- (H1.west) node[above left]{$\hat{x}_1$};
  \draw[<-] (add2.north) -- ++(0, 0.7)node[below right](n2){$n_2$};
  \draw[->] (add2.east) -- (G2.west);
  \draw[->] (G2.east) -- (G2inv.west) node[above left]{$\tilde{x}_2$};
  \draw[->] (G2inv.east) -- (H2.west) node[above left]{$\hat{x}_2$};
  \draw[->] (H1) -| (add.north);
  \draw[->] (H2) -| (add.south);
  \draw[->] (add.east) -- ++(0.7, 0) node[above left]{$\hat{x}$};

  \begin{scope}[on background layer]
    \node[fit={(G2.south-|x) (n1.north-|add.east)}, fill=black!10!white, draw, inner sep=9pt] (supersensor) {};
    \node[below left] at (supersensor.north east) {Super Sensor};

    \node[fit={(add1.west |- G1inv.south) (n1.north -| G1inv.east)}, fill=colorblue!20!white, draw, inner sep=6pt] (sensor1cal) {};
    \node[below left, align=right] at (sensor1cal.north east) {{\tiny Normalized}\\[-0.5em]{\tiny sensor}};
    \node[fit={(add1.west |- G1.south) (n1.north -| G1.east)}, fill=colorblue!30!white, draw, inner sep=3pt] (sensor1) {};
    \node[below left] at (sensor1.north east) {Sensor 1};

    \node[fit={(add2.west |- G2inv.south) (n2.north -| G2inv.east)}, fill=colorred!20!white, draw, inner sep=6pt] (sensor2cal) {};
    \node[below left, align=right] at (sensor2cal.north east) {{\tiny Normalized}\\[-0.5em]{\tiny sensor}};
    \node[fit={(add2.west |- G2.south) (n2.north -| G2.east)}, fill=colorred!30!white, draw, inner sep=3pt] (sensor2) {};
    \node[below left] at (sensor2.north east) {Sensor 2};
  \end{scope}
\end{tikzpicture}
#+end_src

#+name: fig:detail_control_fusion_super_sensor
#+caption: Sensor fusion architecture with two normalized sensors.
#+RESULTS:
[[file:figs/detail_control_fusion_super_sensor.png]]

*** Noise Sensor Filtering
<<sec:detail_control_noise_filtering>>

In this section, it is supposed that all the sensors are perfectly normalized, such that:

\begin{equation}\label{eq:detail_control_perfect_dynamics}
  \frac{\hat{x}_i}{x} = \hat{G}_i(s) G_i(s) = 1
\end{equation}

The effect of a non-perfect normalization will be discussed in the next section.

Provided eqref:eq:detail_control_perfect_dynamics is verified, the super sensor output $\hat{x}$ is then equal to:

\begin{equation}\label{eq:detail_control_estimate_perfect_dyn}
  \hat{x} = x + H_1(s) n_1 + H_2(s) n_2
\end{equation}

From eqref:eq:detail_control_estimate_perfect_dyn, the complementary filters $H_1(s)$ and $H_2(s)$ are shown to only operate on the noise of the sensors.
Thus, this sensor fusion architecture permits to filter the noise of both sensors without introducing any distortion in the physical quantity to be measured.
This is why the two filters must be complementary.

The estimation error $\delta x$, defined as the difference between the sensor output $\hat{x}$ and the measured quantity $x$, is computed for the super sensor eqref:eq:detail_control_estimate_error.

\begin{equation}\label{eq:detail_control_estimate_error}
  \delta x \triangleq \hat{x} - x = H_1(s) n_1 + H_2(s) n_2
\end{equation}

As shown in eqref:eq:detail_control_noise_filtering_psd, the Power Spectral Density (PSD) of the estimation error $\Phi_{\delta x}$ depends both on the norm of the two complementary filters and on the PSD of the noise sources $\Phi_{n_1}$ and $\Phi_{n_2}$.

\begin{equation}\label{eq:detail_control_noise_filtering_psd}
  \Phi_{\delta x}(\omega) = \left|H_1(j\omega)\right|^2 \Phi_{n_1}(\omega) + \left|H_2(j\omega)\right|^2 \Phi_{n_2}(\omega)
\end{equation}

If the two sensors have identical noise characteristics, $\Phi_{n_1}(\omega) = \Phi_{n_2}(\omega)$, a simple averaging ($H_1(s) = H_2(s) = 0.5$) is what would minimize the super sensor noise.
This is the simplest form of sensor fusion with complementary filters.

However, the two sensors have usually high noise levels over distinct frequency regions.
In such case, to lower the noise of the super sensor, the norm $|H_1(j\omega)|$ has to be small when $\Phi_{n_1}(\omega)$ is larger than $\Phi_{n_2}(\omega)$ and the norm $|H_2(j\omega)|$ has to be small when $\Phi_{n_2}(\omega)$ is larger than $\Phi_{n_1}(\omega)$.
Hence, by properly shaping the norm of the complementary filters, it is possible to reduce the noise of the super sensor.

*** Sensor Fusion Robustness
<<sec:detail_control_fusion_robustness>>

In practical systems the sensor normalization is not perfect and condition eqref:eq:detail_control_perfect_dynamics is not verified.

In order to study such imperfection, a multiplicative input uncertainty is added to the sensor dynamics (Fig. ref:fig:detail_control_sensor_model_uncertainty).
The nominal model is the estimated model used for the normalization $\hat{G}_i(s)$, $\Delta_i(s)$ is any stable transfer function satisfying $|\Delta_i(j\omega)| \le 1,\ \forall\omega$, and $w_i(s)$ is a weighting transfer function representing the magnitude of the uncertainty.

The weight $w_i(s)$ is chosen such that the real sensor dynamics $G_i(j\omega)$ is contained in the uncertain region represented by a circle in the complex plane, centered on $1$ and with a radius equal to $|w_i(j\omega)|$.

As the nominal sensor dynamics is taken as the normalized filter, the normalized sensor can be further simplified as shown in Fig. ref:fig:detail_control_sensor_model_uncertainty_simplified.

#+begin_src latex :file detail_control_sensor_model_uncertainty.pdf
\tikzset{block/.default={0.8cm}{0.8cm}}
\tikzset{addb/.append style={scale=0.7}}
\tikzset{node distance=0.6}
\begin{tikzpicture}
  \node[branch] (input) at (0,0) {};
  \node[block, above right= 0.4 and 0.4 of input](W1){$w_1(s)$};
  \node[block, right=0.4 of W1](delta1){$\Delta_1(s)$};
  \node[addb] (addu) at ($(delta1.east|-input) + (0.4, 0)$) {};
  \node[addb, right=0.4 of addu] (addn) {};
  \node[block, right=0.4 of addn] (G1) {$\hat{G}_1(s)$};
  \node[block, right=0.8 of G1](G1inv){$\hat{G}_1^{-1}(s)$};

  \draw[->] ($(input)+(-0.7, 0)$) node[above right]{$x$} -- (addu);
  \draw[->] (input.center) |- (W1.west);
  \draw[->] (W1.east) -- (delta1.west);
  \draw[->] (delta1.east) -| (addu.north);
  \draw[->] (addu.east) -- (addn.west);
  \draw[->] (addn.east) -- (G1.west);
  \draw[<-] (addn.north) -- ++(0, 0.7)node[below right](n1){$n_1$};
  \draw[->] (G1.east) -- (G1inv.west) node[above left]{$\tilde{x}_1$};
  \draw[->] (G1inv.east) -- ++(0.8, 0) node[above left]{$\hat{x}_1$};

  \begin{scope}[on background layer]
    \node[fit={(input.west |- G1inv.south) (delta1.north -| G1inv.east)}, fill=black!10!white, draw, inner sep=6pt] (sensor1cal) {};
    \node[below left, align=right] at (sensor1cal.north east) {{\tiny Normalized}\\[-0.5em]{\tiny sensor}};

    \node[fit={(input.west |- G1.south) (delta1.north -| G1.east)}, fill=black!20!white, draw, inner sep=3pt] (sensor1) {};
    \node[below left] at (sensor1.north east) {Sensor};
  \end{scope}
\end{tikzpicture}
#+end_src

#+begin_src latex :file detail_control_sensor_model_uncertainty_simplified.pdf
\tikzset{block/.default={0.8cm}{0.8cm}}
\tikzset{addb/.append style={scale=0.7}}
\tikzset{node distance=0.6}
\begin{tikzpicture}
  \node[branch] (input) at (0,0) {};
  \node[block, above right= 0.4 and 0.4 of input](W1){$w_1(s)$};
  \node[block, right=0.4 of W1](delta1){$\Delta_1(s)$};
  \node[addb] (addu) at ($(delta1.east|-input) + (0.4, 0)$) {};
  \node[addb, right=0.4 of addu] (addn) {};

  \draw[->] ($(input)+(-0.8, 0)$) node[above right]{$x$} -- (addu);
  \draw[->] (input.center) |- (W1.west);
  \draw[->] (W1.east) -- (delta1.west);
  \draw[->] (delta1.east) -| (addu.north);
  \draw[->] (addu.east) -- (addn.west);
  \draw[<-] (addn.north) -- ++(0, 0.6)node[below right](n1){$n_1$};
  \draw[->] (addn.east) -- ++(0.9, 0) node[above left]{$\hat{x}_1$};

  \begin{scope}[on background layer]
    \node[fit={(input.west |- addu.south) ($(delta1.north -| addn.east) + (0.1, 0)$)}, fill=black!10!white, draw, inner sep=6pt] (sensor1cal) {};
    \node[below left, align=right] at (sensor1cal.north east) {{\tiny Normalized}\\[-0.5em]{\tiny sensor}};
  \end{scope}
\end{tikzpicture}
#+end_src

#+name: fig:detail_control_sensor_models_uncertainty
#+caption: Sensor models with dynamical uncertainty
#+attr_latex: :options [htbp]
#+begin_figure
#+attr_latex: :caption \subcaption{\label{fig:detail_control_sensor_model_uncertainty}Sensor with multiplicative input uncertainty}
#+attr_latex: :options {0.58\textwidth}
#+begin_subfigure
#+attr_latex: :width 0.95\linewidth
[[file:figs/detail_control_sensor_model_uncertainty.png]]
#+end_subfigure
#+attr_latex: :caption \subcaption{\label{fig:detail_control_sensor_model_uncertainty_simplified}Simplified sensor model}
#+attr_latex: :options {0.38\textwidth}
#+begin_subfigure
#+attr_latex: :width 0.95\linewidth
[[file:figs/detail_control_sensor_model_uncertainty_simplified.png]]
#+end_subfigure
#+end_figure

The sensor fusion architecture with the sensor models including dynamical uncertainty is shown in Fig. ref:fig:detail_control_sensor_fusion_dynamic_uncertainty.

#+begin_src latex :file detail_control_sensor_fusion_dynamic_uncertainty.pdf
\tikzset{block/.default={0.8cm}{0.8cm}}
\tikzset{addb/.append style={scale=0.7}}
\tikzset{node distance=0.6}
\begin{tikzpicture}
  \node[branch] (x) at (0, 0);

  \node[branch, above right=1.0 and 0.3 of x] (input1) {};
  \node[branch, below right=1.0 and 0.3 of x] (input2) {};
  \node[block, above right= 0.4 and 0.3 of input1](W1){$w_1(s)$};
  \node[block, above right= 0.4 and 0.3 of input2](W2){$w_2(s)$};
  \node[block, right=0.4 of W1](delta1){$\Delta_1(s)$};
  \node[block, right=0.4 of W2](delta2){$\Delta_2(s)$};
  \node[addb] (addu1) at ($(delta1.east|-input1) + (0.4, 0)$) {};
  \node[addb] (addu2) at ($(delta2.east|-input2) + (0.4, 0)$) {};
  \node[addb, right=0.4 of addu1] (addn1) {};
  \node[addb, right=0.4 of addu2] (addn2) {};
  \node[block, right=0.9 of addn1](H1){$H_1(s)$};
  \node[block, right=0.9 of addn2](H2){$H_2(s)$};

  \node[addb, right=7 of x](add){};


  \draw[] ($(x)+(-0.7, 0)$) node[above right]{$x$} -- (x.center);
  \draw[->] (x.center) |- (addu1.west);
  \draw[->] (x.center) |- (addu2.west);
  \draw[->] (input1.center) |- (W1.west);
  \draw[->] (W1.east) -- (delta1.west);
  \draw[->] (delta1.east) -| (addu1.north);
  \draw[->] (addu1.east) -- (addn1.west);
  \draw[<-] (addn1.north) -- ++(0, 0.6)node[below right](n1){$n_1$};
  \draw[->] (input2.center) |- (W2.west);
  \draw[->] (W2.east) -- (delta2.west);
  \draw[->] (delta2.east) -| (addu2.north);
  \draw[->] (addu2.east) -- (addn2.west);
  \draw[<-] (addn2.north) -- ++(0, 0.6)node[below right](n2){$n_2$};

  \draw[->] (addn1.east) -- (H1.west) node[above left]{$\hat{x}_1$};
  \draw[->] (addn2.east) -- (H2.west) node[above left]{$\hat{x}_2$};
  \draw[->] (H1) -| (add.north);
  \draw[->] (H2) -| (add.south);
  \draw[->] (add.east) -- ++(0.7, 0) node[above left]{$\hat{x}$};

  \begin{scope}[on background layer]
    \node[fit={(addn2.south-|x) (delta1.north-|add.east)}, fill=black!10!white, draw, inner sep=9pt] (supersensor) {};
    \node[below left] at (supersensor.north east) {Super Sensor};

    \node[fit={(input1.west |- addu1.south) ($(delta1.north -| addn1.east) + (0.1, 0.0)$)}, fill=colorblue!20!white, draw, inner sep=6pt] (sensor1cal) {};
    \node[below left, align=right] at (sensor1cal.north east) {{\tiny Normalized}\\[-0.5em]{\tiny sensor 1}};

    \node[fit={(input2.west |- addu2.south) ($(delta2.north -| addn1.east) + (0.1, 0.0)$)}, fill=colorred!20!white, draw, inner sep=6pt] (sensor2cal) {};
    \node[below left, align=right] at (sensor2cal.north east) {{\tiny Normalized}\\[-0.5em]{\tiny sensor 2}};
  \end{scope}
\end{tikzpicture}
#+end_src

#+name: fig:detail_control_sensor_fusion_dynamic_uncertainty
#+caption: Sensor fusion architecture with sensor dynamics uncertainty
#+RESULTS:
[[file:figs/detail_control_sensor_fusion_dynamic_uncertainty.png]]


The super sensor dynamics eqref:eq:detail_control_super_sensor_dyn_uncertainty is no longer equal to $1$ and now depends on the sensor dynamical uncertainty weights $w_i(s)$ as well as on the complementary filters $H_i(s)$.

\begin{equation}\label{eq:detail_control_super_sensor_dyn_uncertainty}
  \frac{\hat{x}}{x} = 1 + w_1(s) H_1(s) \Delta_1(s) + w_2(s) H_2(s) \Delta_2(s)
\end{equation}

The dynamical uncertainty of the super sensor can be graphically represented in the complex plane by a circle centered on $1$ with a radius equal to $|w_1(j\omega) H_1(j\omega)| + |w_2(j\omega) H_2(j\omega)|$ (Fig. ref:fig:detail_control_uncertainty_set_super_sensor).

#+begin_src latex :file detail_control_uncertainty_set_super_sensor.pdf
\tikzset{block/.default={0.8cm}{0.8cm}}
\tikzset{addb/.append style={scale=0.7}}
\tikzset{node distance=0.6}
\begin{tikzpicture}
  \begin{scope}[shift={(4, 0)}]

    % Uncertainty Circle
    \node[draw, circle, fill=black!20!white, minimum size=3.6cm] (c) at (0, 0) {};
    \path[draw, fill=colorblue!20!white] (0, 0) circle [radius=1.0];
    \path[draw, fill=colorred!20!white] (135:1.0) circle [radius=0.8];
    \path[draw, dashed] (0, 0) circle [radius=1.0];

    % Center of Circle
    \node[below] at (0, 0){$1$};

    \draw[<->] (0, 0)   node[branch]{} -- coordinate[midway](r1) ++(45:1.0);
    \draw[<->] (135:1.0)node[branch]{} -- coordinate[midway](r2) ++(135:0.8);

    \node[] (l1) at (2, 1.5) {$|w_1 H_1|$};
    \draw[->, out=-90, in=0] (l1.south) to (r1);

    \node[] (l2) at (-3.2, 1.2) {$|w_2 H_2|$};
    \draw[->, out=0, in=-180] (l2.east) to (r2);

    \draw[<->] (0, 0) -- coordinate[near end](r3) ++(200:1.8);
    \node[] (l3) at (-2.5, -1.5) {$|w_1 H_1| + |w_2 H_2|$};
    \draw[->, out=90, in=-90] (l3.north) to (r3);
  \end{scope}

  % Real and Imaginary Axis
  \draw[->] (-0.5, 0) -- (7.0, 0) node[below left]{Re};
  \draw[->] (0, -1.7) -- (0, 1.7) node[below left]{Im};

  \draw[dashed] (0, 0) -- (tangent cs:node=c,point={(0, 0)},solution=2);
  \draw[dashed] (1, 0) arc (0:28:1) node[midway, right]{$\Delta \phi_\text{max}$};
\end{tikzpicture}
#+end_src

#+name: fig:detail_control_uncertainty_set_super_sensor
#+caption: Uncertainty region of the super sensor dynamics in the complex plane (grey circle). The contribution of both sensors 1 and 2 to the total uncertainty are represented respectively by a blue circle and a red circle. The frequency dependency $\omega$ is here omitted.
#+RESULTS:
[[file:figs/detail_control_uncertainty_set_super_sensor.png]]

The super sensor dynamical uncertainty, and hence the robustness of the fusion, clearly depends on the complementary filters' norm.
For instance, the phase $\Delta\phi(\omega)$ added by the super sensor dynamics at frequency $\omega$ is bounded by $\Delta\phi_{\text{max}}(\omega)$ which can be found by drawing a tangent from the origin to the uncertainty circle of the super sensor (Fig. ref:fig:detail_control_uncertainty_set_super_sensor) and that is mathematically described by eqref:eq:detail_control_max_phase_uncertainty.

\begin{equation}\label{eq:detail_control_max_phase_uncertainty}
    \Delta\phi_\text{max}(\omega) = \arcsin\big( |w_1(j\omega) H_1(j\omega)| + |w_2(j\omega) H_2(j\omega)| \big)
\end{equation}

As it is generally desired to limit the maximum phase added by the super sensor, $H_1(s)$ and $H_2(s)$ should be designed such that $\Delta \phi$ is bounded to acceptable values.
Typically, the norm of the complementary filter $|H_i(j\omega)|$ should be made small when $|w_i(j\omega)|$ is large, i.e., at frequencies where the sensor dynamics is uncertain.

** Complementary Filters Shaping
<<sec:detail_control_hinf_method>>
*** Introduction                                                     :ignore:

As shown in Section ref:sec:detail_control_sensor_fusion_requirements, the noise and robustness of the super sensor are a function of the complementary filters' norm.
Therefore, a synthesis method of complementary filters that allows to shape their norm would be of great use.
In this section, such synthesis is proposed by writing the synthesis objective as a standard $\mathcal{H}_\infty$ optimization problem.
As weighting functions are used to represent the wanted complementary filters' shape during the synthesis, their proper design is discussed.
Finally, the synthesis method is validated on an simple example.

*** Synthesis Objective
<<sec:detail_control_synthesis_objective>>

The synthesis objective is to shape the norm of two filters $H_1(s)$ and $H_2(s)$ while ensuring their complementary property eqref:eq:detail_control_comp_filter.
This is equivalent as to finding proper and stable transfer functions $H_1(s)$ and $H_2(s)$ such that conditions eqref:eq:detail_control_hinf_cond_complementarity, eqref:eq:detail_control_hinf_cond_h1 and eqref:eq:detail_control_hinf_cond_h2 are satisfied.

\begin{subequations}\label{eq:detail_control_comp_filter_problem_form}
  \begin{align}
  & H_1(s) + H_2(s) = 1 \label{eq:detail_control_hinf_cond_complementarity} \\
  & |H_1(j\omega)| \le \frac{1}{|W_1(j\omega)|} \quad \forall\omega \label{eq:detail_control_hinf_cond_h1} \\
  & |H_2(j\omega)| \le \frac{1}{|W_2(j\omega)|} \quad \forall\omega \label{eq:detail_control_hinf_cond_h2}
  \end{align}
\end{subequations}

$W_1(s)$ and $W_2(s)$ are two weighting transfer functions that are carefully chosen to specify the maximum wanted norm of the complementary filters during the synthesis.

*** Shaping of Complementary Filters using $\mathcal{H}_\infty$ synthesis
<<sec:detail_control_hinf_synthesis>>

In this section, it is shown that the synthesis objective can be easily expressed as a standard $\mathcal{H}_\infty$ optimization problem and therefore solved using convenient tools readily available.

Consider the generalized plant $P(s)$ shown in Fig. ref:fig:detail_control_h_infinity_robust_fusion_plant and mathematically described by eqref:eq:detail_control_generalized_plant.

\begin{equation}\label{eq:detail_control_generalized_plant}
  \begin{bmatrix} z_1 \\ z_2 \\ v \end{bmatrix} = P(s) \begin{bmatrix} w\\u \end{bmatrix}; \quad P(s) = \begin{bmatrix}W_1(s) & -W_1(s) \\ 0 & \phantom{+}W_2(s) \\  1 & 0 \end{bmatrix}
\end{equation}

#+begin_src latex :file detail_control_h_infinity_robust_fusion_plant.pdf
\tikzset{block/.default={0.8cm}{0.8cm}}
\tikzset{addb/.append style={scale=0.7}}
\tikzset{node distance=0.6}
\begin{tikzpicture}
  \node[block={4.0cm}{3.0cm}, fill=black!10!white] (P) {};
  \node[above] at (P.north) {$P(s)$};

  \node[block, below=0.2 of P, opacity=0] (H2) {$H_2(s)$};

  \coordinate[] (inputw)  at ($(P.south west)!0.75!(P.north west) + (-0.7, 0)$);
  \coordinate[] (inputu)  at ($(P.south west)!0.35!(P.north west) + (-0.7, 0)$);

  \coordinate[] (output1) at ($(P.south east)!0.75!(P.north east) + ( 0.7, 0)$);
  \coordinate[] (output2) at ($(P.south east)!0.35!(P.north east) + ( 0.7, 0)$);
  \coordinate[] (outputv) at ($(P.south east)!0.1!(P.north east) + ( 0.7, 0)$);

  \node[block, left=1.4 of output1] (W1){$W_1(s)$};
  \node[block, left=1.4 of output2] (W2){$W_2(s)$};
  \node[addb={+}{}{}{}{-}, left=of W1] (sub) {};

  \draw[->] (inputw) node[above right]{$w$} -- (sub.west);
  \draw[->] (inputu) node[above right]{$u$} -- (W2.west);
  \draw[->] (inputu-|sub) node[branch]{} -- (sub.south);
  \draw[->] (sub.east) -- (W1.west);
  \draw[->] ($(sub.west)+(-0.6, 0)$) node[branch]{} |- (outputv) node[above left]{$v$};
  \draw[->] (W1.east) -- (output1)node[above left]{$z_1$};
  \draw[->] (W2.east) -- (output2)node[above left]{$z_2$};
\end{tikzpicture}
#+end_src

#+begin_src latex :file detail_control_h_infinity_robust_fusion_fb.pdf
\tikzset{block/.default={0.8cm}{0.8cm}}
\tikzset{addb/.append style={scale=0.7}}
\tikzset{node distance=0.6}
\begin{tikzpicture}
  \node[block={4.0cm}{3.0cm}, fill=black!10!white] (P) {};
  \node[above] at (P.north) {$P(s)$};

  \node[block, below=0.2 of P] (H2) {$H_2(s)$};

  \coordinate[] (inputw)  at ($(P.south west)!0.75!(P.north west) + (-0.7, 0)$);
  \coordinate[] (inputu)  at ($(P.south west)!0.35!(P.north west) + (-0.4, 0)$);

  \coordinate[] (output1) at ($(P.south east)!0.75!(P.north east) + ( 0.7, 0)$);
  \coordinate[] (output2) at ($(P.south east)!0.35!(P.north east) + ( 0.7, 0)$);
  \coordinate[] (outputv) at ($(P.south east)!0.1!(P.north east) + ( 0.4, 0)$);

  \node[block, left=1.4 of output1] (W1){$W_1(s)$};
  \node[block, left=1.4 of output2] (W2){$W_2(s)$};
  \node[addb={+}{}{}{}{-}, left=of W1] (sub) {};

  \draw[->] (inputw) node[above right]{$w$} -- (sub.west);
  \draw[->] (inputu-|sub) node[branch]{} -- (sub.south);
  \draw[->] (sub.east) -- (W1.west);
  \draw[->] ($(sub.west)+(-0.6, 0)$) node[branch]{} |- (outputv) |- (H2.east);
  \draw[->] (H2.west) -| (inputu) -- (W2.west);
  \draw[->] (W1.east) -- (output1)node[above left]{$z_1$};
  \draw[->] (W2.east) -- (output2)node[above left]{$z_2$};
\end{tikzpicture}
#+end_src

#+name: fig:detail_control_h_infinity_robust_fusion
#+caption: Architecture for the $\mathcal{H}_\infty$ synthesis of complementary filters
#+attr_latex: :options [htbp]
#+begin_figure
#+attr_latex: :caption \subcaption{\label{fig:detail_control_h_infinity_robust_fusion_plant}Generalized plant}
#+attr_latex: :options {0.49\textwidth}
#+begin_subfigure
#+attr_latex: :scale 1
[[file:figs/detail_control_h_infinity_robust_fusion_plant.png]]
#+end_subfigure
#+attr_latex: :caption \subcaption{\label{fig:detail_control_h_infinity_robust_fusion_fb}Generalized plant with the synthesized filter}
#+attr_latex: :options {0.49\textwidth}
#+begin_subfigure
#+attr_latex: :scale 1
[[file:figs/detail_control_h_infinity_robust_fusion_fb.png]]
#+end_subfigure
#+end_figure

Applying the standard $\mathcal{H}_\infty$ synthesis to the generalized plant $P(s)$ is then equivalent as finding a stable filter $H_2(s)$ which based on $v$, generates a signal $u$ such that the $\mathcal{H}_\infty$ norm of the system in Fig. ref:fig:detail_control_h_infinity_robust_fusion_fb from $w$ to $[z_1, \ z_2]$ is less than one eqref:eq:detail_control_hinf_syn_obj.

\begin{equation}\label{eq:detail_control_hinf_syn_obj}
  \left\|\begin{matrix} \left(1 - H_2(s)\right) W_1(s) \\ H_2(s) W_2(s) \end{matrix}\right\|_\infty \le 1
\end{equation}

By then defining $H_1(s)$ to be the complementary of $H_2(s)$ eqref:eq:detail_control_definition_H1, the $\mathcal{H}_\infty$ synthesis objective becomes equivalent to eqref:eq:detail_control_hinf_problem which ensures that eqref:eq:detail_control_hinf_cond_h1 and eqref:eq:detail_control_hinf_cond_h2 are satisfied.

\begin{equation}\label{eq:detail_control_definition_H1}
  H_1(s) \triangleq 1 - H_2(s)
\end{equation}

\begin{equation}\label{eq:detail_control_hinf_problem}
  \left\|\begin{matrix} H_1(s) W_1(s) \\ H_2(s) W_2(s) \end{matrix}\right\|_\infty \le 1
\end{equation}

Therefore, applying the $\mathcal{H}_\infty$ synthesis to the standard plant $P(s)$ eqref:eq:detail_control_generalized_plant will generate two filters $H_2(s)$ and $H_1(s) \triangleq 1 - H_2(s)$ that are complementary eqref:eq:detail_control_comp_filter_problem_form and such that there norms are bellow specified bounds [[eqref:eq:detail_control_hinf_cond_h1]], eqref:eq:detail_control_hinf_cond_h2.

Note that there is only an implication between the $\mathcal{H}_\infty$ norm condition eqref:eq:detail_control_hinf_problem and the initial synthesis objectives eqref:eq:detail_control_hinf_cond_h1 and eqref:eq:detail_control_hinf_cond_h2 and not an equivalence.
Hence, the optimization may be a little bit conservative with respect to the set of filters on which it is performed, see [[cite:skogestad07_multiv_feedb_contr][Chap. 2.8.3]].
In practice, this is however not an found to be an issue.

*** Weighting Functions Design
<<sec:detail_control_hinf_weighting_func>>

Weighting functions are used during the synthesis to specify the maximum allowed complementary filters' norm.
The proper design of these weighting functions is of primary importance for the success of the presented $\mathcal{H}_\infty$ synthesis of complementary filters.

First, only proper and stable transfer functions should be used.
Second, the order of the weighting functions should stay reasonably small in order to reduce the computational costs associated with the solving of the optimization problem and for the physical implementation of the filters (the synthesized filters' order being equal to the sum of the weighting functions' order).
Third, one should not forget the fundamental limitations imposed by the complementary property eqref:eq:detail_control_comp_filter.
This implies for instance that $|H_1(j\omega)|$ and $|H_2(j\omega)|$ cannot be made small at the same frequency.

When designing complementary filters, it is usually desired to specify their slopes, their "blending" frequency and their maximum gains at low and high frequency.
To easily express these specifications, formula eqref:eq:detail_control_weight_formula is proposed to help with the design of weighting functions.

\begin{equation}\label{eq:detail_control_weight_formula}
  W(s) = \left( \frac{
           \hfill{} \frac{1}{\omega_c} \sqrt{\frac{1 - \left(\frac{G_0}{G_c}\right)^{\frac{2}{n}}}{1 - \left(\frac{G_c}{G_\infty}\right)^{\frac{2}{n}}}} s + \left(\frac{G_0}{G_c}\right)^{\frac{1}{n}}
         }{
           \left(\frac{1}{G_\infty}\right)^{\frac{1}{n}} \frac{1}{\omega_c} \sqrt{\frac{1 - \left(\frac{G_0}{G_c}\right)^{\frac{2}{n}}}{1 - \left(\frac{G_c}{G_\infty}\right)^{\frac{2}{n}}}} s + \left(\frac{1}{G_c}\right)^{\frac{1}{n}}
         }\right)^n
\end{equation}

The parameters in formula eqref:eq:detail_control_weight_formula are:
- $G_0 = \lim_{\omega \to 0} |W(j\omega)|$: the low frequency gain
- $G_\infty = \lim_{\omega \to \infty} |W(j\omega)|$: the high frequency gain
- $G_c = |W(j\omega_c)|$: the gain at a specific frequency $\omega_c$ in $\si{rad/s}$.
- $n$: the slope between high and low frequency. It also corresponds to the order of the weighting function.

The parameters $G_0$, $G_c$ and $G_\infty$ should either satisfy eqref:eq:detail_control_cond_formula_1 or eqref:eq:detail_control_cond_formula_2.

\begin{subequations}\label{eq:detail_control_condition_params_formula}
  \begin{align}
    G_0 < 1 < G_\infty \text{ and } G_0 < G_c < G_\infty \label{eq:detail_control_cond_formula_1}\\
    G_\infty < 1 < G_0 \text{ and } G_\infty < G_c < G_0 \label{eq:detail_control_cond_formula_2}
  \end{align}
\end{subequations}

The typical magnitude of a weighting function generated using eqref:eq:detail_control_weight_formula is shown in Fig. ref:fig:detail_control_weight_formula.

#+begin_src matlab :exports none
%% Weighting Function Design
% Parameters
n = 3; w0 = 2*pi*10; G0 = 1e-3; G1 = 1e1; Gc = 2;

% Formulas
W = (((1/w0)*sqrt((1-(G0/Gc)^(2/n))/(1-(Gc/G1)^(2/n)))*s + (G0/Gc)^(1/n))/((1/G1)^(1/n)*(1/w0)*sqrt((1-(G0/Gc)^(2/n))/(1-(Gc/G1)^(2/n)))*s + (1/Gc)^(1/n)))^n;

% Function generateWF can be used to easily design the weighting filters
% W = generateWF('n', 3, 'w0', 2*pi*10, 'G0', 1e-3, 'Ginf', 10, 'Gc', 2);
#+end_src

#+begin_src matlab :exports none :results none
%% Magnitude of the weighting function with parameters
figure;
hold on;
plot(freqs, abs(squeeze(freqresp(W, freqs, 'Hz'))), 'k-');

plot([1e-3 1e0], [G0 G0], 'k--', 'LineWidth', 1)
text(1e0, G0, '$\quad G_0$')

plot([1e1 1e3], [G1 G1], 'k--', 'LineWidth', 1)
text(1e1,G1,'$G_{\infty}\quad$','HorizontalAlignment', 'right')

plot([w0/2/pi w0/2/pi], [1 2*Gc], 'k--', 'LineWidth', 1)
text(w0/2/pi,1,'$\omega_c$','VerticalAlignment', 'top', 'HorizontalAlignment', 'center')

plot([w0/2/pi/2  2*w0/2/pi], [Gc Gc], 'k--', 'LineWidth', 1)
text(w0/2/pi/2, Gc, '$G_c \quad$','HorizontalAlignment', 'right')

text(w0/5/pi/2, abs(evalfr(W, j*w0/5)), 'Slope: $n \quad$', 'HorizontalAlignment', 'right')

text(w0/2/pi, abs(evalfr(W, j*w0)), '$\bullet$', 'HorizontalAlignment', 'center')
set(gca, 'XScale', 'log'); set(gca, 'YScale', 'log');
xlabel('Frequency [Hz]'); ylabel('Magnitude');
hold off;
xlim([freqs(1), freqs(end)]);
ylim([5e-4, 20]);
yticks([1e-4, 1e-3, 1e-2, 1e-1, 1, 1e1]);
#+end_src

#+begin_src matlab :tangle no :exports results :results file replace
exportFig('figs/detail_control_weight_formula.pdf', 'width', 'wide', 'height', 'normal');
#+end_src

#+name: fig:detail_control_weight_formula
#+caption: Magnitude of a weighting function generated using formula eqref:eq:detail_control_weight_formula, $G_0 = 1e^{-3}$, $G_\infty = 10$, $\omega_c = \SI{10}{Hz}$, $G_c = 2$, $n = 3$.
#+RESULTS:
[[file:figs/detail_control_weight_formula.png]]

*** Validation of the proposed synthesis method
<<sec:detail_control_hinf_example>>

The proposed methodology for the design of complementary filters is now applied on a simple example.
Let's suppose two complementary filters $H_1(s)$ and $H_2(s)$ have to be designed such that:
- the blending frequency is around $\SI{10}{Hz}$.
- the slope of $|H_1(j\omega)|$ is $+2$ below $\SI{10}{Hz}$.
  Its low frequency gain is $10^{-3}$.
- the slope of $|H_2(j\omega)|$ is $-3$ above $\SI{10}{Hz}$.
  Its high frequency gain is $10^{-3}$.

The first step is to translate the above requirements by properly designing the weighting functions.
The proposed formula eqref:eq:detail_control_weight_formula is here used for such purpose.
Parameters used are summarized in Table ref:tab:detail_control_weights_params.
The inverse magnitudes of the designed weighting functions, which are representing the maximum allowed norms of the complementary filters, are shown by the dashed lines in Fig. ref:fig:detail_control_weights_W1_W2.

#+begin_src matlab
%% Synthesis of Complementary Filters using H-infinity synthesis
% Design of the Weighting Functions
W1 = generateWF('n', 3, 'w0', 2*pi*10, 'G0', 1000, 'Ginf', 1/10, 'Gc', 0.45);
W2 = generateWF('n', 2, 'w0', 2*pi*10, 'G0', 1/10, 'Ginf', 1000, 'Gc', 0.45);
#+end_src

#+begin_src matlab :exports none :results none
%% description
figure;
tiledlayout(1, 1, 'TileSpacing', 'None', 'Padding', 'None');
ax1 = nexttile();
hold on;
set(gca,'ColorOrderIndex',1)
plot(freqs, 1./abs(squeeze(freqresp(W1, freqs, 'Hz'))), '--', 'DisplayName', '$|W_1|^{-1}$');
set(gca,'ColorOrderIndex',2)
plot(freqs, 1./abs(squeeze(freqresp(W2, freqs, 'Hz'))), '--', 'DisplayName', '$|W_2|^{-1}$');
set(gca, 'XScale', 'log'); set(gca, 'YScale', 'log');
xlabel('Frequency [Hz]', 'FontSize', 10); ylabel('Magnitude', 'FontSize', 10);
hold off;
xlim([freqs(1), freqs(end)]);
xticks([0.1, 1, 10, 100, 1000]);
ylim([8e-4, 20]);
yticks([1e-3, 1e-2, 1e-1, 1, 1e1]);
yticklabels({'', '$10^{-2}$', '', '$10^0$', ''});
ax1.FontSize = 9;
leg = legend('location', 'south', 'FontSize', 8);
leg.ItemTokenSize(1) = 18;
#+end_src

#+begin_src matlab :tangle no :exports results :results file replace
exportFig('figs/detail_control_weights_W1_W2.pdf', 'width', 'half', 'height', 350);
#+end_src

#+attr_latex: :options [b]{0.44\linewidth}
#+begin_minipage
#+attr_latex: :environment tabularx :width 0.7\linewidth :placement [b] :align ccc
#+attr_latex: :booktabs t :float nil
| Parameter   |         $W_1(s)$ |         $W_2(s)$ |
|-------------+------------------+------------------|
| $G_0$       |              $0.1$ |             $1000$ |
| $G_{\infty}$ |             $1000$ |              $0.1$ |
| $\omega_c$  | $2 \pi \cdot 10$ | $2 \pi \cdot 10$ |
| $G_c$       |             $0.45$ |             $0.45$ |
| $n$         |                $2$ |                $3$ |
#+latex: \captionof{table}{\label{tab:detail_control_weights_params}Parameters for \(W_1(s)\) and \(W_2(s)\)}
#+end_minipage
\hfill
#+attr_latex: :options [b]{0.52\linewidth}
#+begin_minipage
#+name: fig:detail_control_weights_W1_W2
#+attr_latex: :scale 1 :float nil
#+caption: Inverse magnitude of the weights
[[file:figs/detail_control_weights_W1_W2.png]]
#+end_minipage

The standard $\mathcal{H}_\infty$ synthesis is then applied to the generalized plant of Fig. ref:fig:detail_control_h_infinity_robust_fusion_plant.
The filter $H_2(s)$ that minimizes the $\mathcal{H}_\infty$ norm between $w$ and $[z_1,\ z_2]^T$ is obtained.
The $\mathcal{H}_\infty$ norm is here found to be close to one eqref:eq:detail_control_hinf_synthesis_result which indicates that the synthesis is successful: the complementary filters norms are below the maximum specified upper bounds.
This is confirmed by the bode plots of the obtained complementary filters in Fig. ref:fig:detail_control_hinf_filters_results.

\begin{equation}\label{eq:detail_control_hinf_synthesis_result}
  \left\|\begin{matrix} \left(1 - H_2(s)\right) W_1(s) \\ H_2(s) W_2(s) \end{matrix}\right\|_\infty \approx 1
\end{equation}

The transfer functions in the Laplace domain of the complementary filters are given in eqref:eq:detail_control_hinf_synthesis_result_tf.
As expected, the obtained filters are of order $5$, that is the sum of the weighting functions' order.

\begin{subequations}\label{eq:detail_control_hinf_synthesis_result_tf}
  \begin{align}
    H_2(s) &= \frac{(s+6.6e^4) (s+160) (s+4)^3}{(s+6.6e^4) (s^2 + 106 s + 3e^3) (s^2 + 72s + 3580)} \\
    H_1(s) &\triangleq H_2(s) - 1 = \frac{10^{-8} (s+6.6e^9) (s+3450)^2 (s^2 + 49s + 895)}{(s+6.6e^4) (s^2 + 106 s + 3e^3) (s^2 + 72s + 3580)}
  \end{align}
\end{subequations}

#+begin_src matlab
% Generalized Plant
P = [W1 -W1;
     0   W2;
     1   0];

% H-Infinity Synthesis
[H2, ~, gamma, ~] = hinfsyn(P, 1, 1,'TOLGAM', 0.001, 'METHOD', 'ric', 'DISPLAY', 'on');

% Define H1 to be the complementary of H2
H1 = 1 - H2;

% The function generateCF can also be used to synthesize the complementary filters.
% [H1, H2] = generateCF(W1, W2);
#+end_src

#+begin_src matlab :exports none :results none
%% Bode plot of the obtained complementary filters
figure;
tiledlayout(3, 1, 'TileSpacing', 'Compact', 'Padding', 'None');

% Magnitude
ax1 = nexttile([2, 1]);
hold on;
set(gca,'ColorOrderIndex',1)
plot(freqs, 1./abs(squeeze(freqresp(W1, freqs, 'Hz'))), '--', 'DisplayName', '$|W_1|^{-1}$');
set(gca,'ColorOrderIndex',2)
plot(freqs, 1./abs(squeeze(freqresp(W2, freqs, 'Hz'))), '--', 'DisplayName', '$|W_2|^{-1}$');

set(gca,'ColorOrderIndex',1)
plot(freqs, abs(squeeze(freqresp(H1, freqs, 'Hz'))), '-', 'DisplayName', '$H_1$');
set(gca,'ColorOrderIndex',2)
plot(freqs, abs(squeeze(freqresp(H2, freqs, 'Hz'))), '-', 'DisplayName', '$H_2$');
hold off;
set(gca, 'XScale', 'log'); set(gca, 'YScale', 'log');
set(gca, 'XTickLabel',[]); ylabel('Magnitude');
ylim([8e-4, 20]);
yticks([1e-3, 1e-2, 1e-1, 1, 1e1]);
yticklabels({'', '$10^{-2}$', '', '$10^0$', ''})
leg = legend('location', 'south', 'FontSize', 8, 'NumColumns', 2);
leg.ItemTokenSize(1) = 18;

% Phase
ax2 = nexttile;
hold on;
set(gca,'ColorOrderIndex',1)
plot(freqs, 180/pi*phase(squeeze(freqresp(H1, freqs, 'Hz'))), '-');
set(gca,'ColorOrderIndex',2)
plot(freqs, 180/pi*phase(squeeze(freqresp(H2, freqs, 'Hz'))), '-');
hold off;
set(gca, 'XScale', 'log');
xlabel('Frequency [Hz]'); ylabel('Phase [deg]');
yticks([-180:90:180]);
ylim([-180, 200])
yticklabels({'-180', '', '0', '', '180'})

linkaxes([ax1,ax2],'x');
xlim([freqs(1), freqs(end)]);
#+end_src

#+begin_src matlab :tangle no :exports results :results file replace
exportFig('figs/detail_control_hinf_filters_results.pdf', 'width', 'wide', 'height', 600);
#+end_src

#+name: fig:detail_control_hinf_filters_results
#+caption: Bode plot of the obtained complementary filters
#+RESULTS:
[[file:figs/detail_control_hinf_filters_results.png]]

This simple example illustrates the fact that the proposed methodology for complementary filters shaping is easy to use and effective.
A more complex real life example is taken up in the next section.

** "Closed-Loop" complementary filters
<<sec:detail_control_closed_loop_complementary_filters>>

An alternative way to implement complementary filters is by using a fundamental property of the classical feedback architecture shown in Fig. ref:fig:detail_control_feedback_sensor_fusion.
This idea is discussed in [[cite:&mahony05_compl_filter_desig_special_orthog;&plummer06_optim_compl_filter_their_applic_motion_measur;&jensen13_basic_uas]].

#+begin_src latex :file detail_control_feedback_sensor_fusion.pdf
\tikzset{block/.default={0.8cm}{0.8cm}}
\tikzset{addb/.append style={scale=0.7}}
\tikzset{node distance=0.6}
\begin{tikzpicture}
  \node[addb={+}{}{}{}{-}] (addfb) at (0, 0){};
  \node[block, right=1 of addfb] (L){$L(s)$};
  \node[addb={+}{}{}{}{}, right=1 of L] (adddy){};

  \draw[<-] (addfb.west) -- ++(-1, 0) node[above right]{$\hat{x}_2$};
  \draw[->] (addfb.east) -- (L.west);
  \draw[->] (L.east) -- (adddy.west);
  \draw[->] (adddy.east) -- ++(1.4, 0) node[above left]{$\hat{x}$};
  \draw[->] ($(adddy.east) + (0.5, 0)$) node[branch]{} -- ++(0, -0.8) coordinate(botc) -| (addfb.south);
  \draw[<-] (adddy.north) -- ++(0, 1) node[below right]{$\hat{x}_1$};

  \begin{scope}[on background layer]
    \node[fit={(L.north-|addfb.west) (botc)}, fill=black!10!white, draw, inner sep=6pt] (supersensor) {};
  \end{scope}
\end{tikzpicture}
#+end_src

#+name: fig:detail_control_feedback_sensor_fusion
#+caption: "Closed-Loop" complementary filters.
#+RESULTS:
[[file:figs/detail_control_feedback_sensor_fusion.png]]

Consider the feedback architecture of Fig. ref:fig:detail_control_feedback_sensor_fusion, with two inputs $\hat{x}_1$ and $\hat{x}_2$, and one output $\hat{x}$.
The output $\hat{x}$ is linked to the inputs by eqref:eq:detail_control_closed_loop_complementary_filters.

\begin{equation}\label{eq:detail_control_closed_loop_complementary_filters}
\hat{x} = \underbrace{\frac{1}{1 + L(s)}}_{S(s)} \hat{x}_1 + \underbrace{\frac{L(s)}{1 + L(s)}}_{T(s)} \hat{x}_2
\end{equation}

As for any classical feedback architecture, we have that the sum of the sensitivity transfer function $S(s)$ and complementary sensitivity transfer function $T_(s)$ is equal to one eqref:eq:detail_control_sensitivity_sum.

\begin{equation}\label{eq:detail_control_sensitivity_sum}
S(s) + T(s) = 1
\end{equation}

Therefore, provided that the the closed-loop system in Fig. ref:fig:detail_control_feedback_sensor_fusion is stable, it can be used as a set of two complementary filters.
Two sensors can then be merged as shown in Fig. ref:fig:detail_control_feedback_sensor_fusion_arch.

#+begin_src latex :file detail_control_feedback_sensor_fusion_arch.pdf
\tikzset{block/.default={0.8cm}{0.8cm}}
\tikzset{addb/.append style={scale=0.7}}
\tikzset{node distance=0.6}
\begin{tikzpicture}
  \node[addb={+}{}{}{}{-}] (addfb) at (0, 0){};
  \node[block, right=1 of addfb] (L){$L(s)$};
  \node[addb={+}{}{}{}{}, right=1 of L] (adddy){};

  \node[block, left=1.2 of addfb]    (sensor2){Sensor 2};
  \node[block, above=0.4 of sensor2] (sensor1){Sensor 1};
  \node[branch, left=0.6 of sensor2] (x){};

  \draw[->] (addfb.east) -- (L.west);
  \draw[->] (L.east) -- (adddy.west);
  \draw[->] (adddy.east) -- ++(1.4, 0) node[above left]{$\hat{x}$};
  \draw[->] ($(adddy.east) + (0.5, 0)$) node[branch]{} -- ++(0, -0.8) coordinate(botc) -| (addfb.south);
  \draw[->] (x.center) |- (sensor1.west);
  \draw[->] ($(x)-(0.8,0)$) node[above right]{$x$} -- (sensor2.west);
  \draw[->] (sensor2.east)node[above right=0 and 0.25]{$\hat{x}_2$} -- (addfb.west);
  \draw[->] (sensor1.east)node[above right=0 and 0.25]{$\hat{x}_1$} -| (adddy.north);

  \begin{scope}[on background layer]
    \node[fit={(x|-sensor1.north) (botc)}, fill=black!10!white, draw, inner sep=9pt] (supersensor) {};
    \node[fit={(sensor1.north-|addfb.west) (botc)}, fill=black!20!white, draw, inner sep=6pt] (feedbackfilter) {};
    \node[fit={(sensor2.west|-botc) (sensor1.north east)}, fill=black!20!white, draw, inner sep=6pt] (sensors) {};
    \node[above, align=center] at (sensors.south) {{\tiny Normalized}\\[-0.5em]{\tiny sensors}};
    \node[below, align=center] at (feedbackfilter.north) {{\tiny "Closed-Loop"}\\[-0.5em]{\tiny complementary filters}};
  \end{scope}
\end{tikzpicture}
#+end_src

#+name: fig:detail_control_feedback_sensor_fusion_arch
#+caption: Classical feedback architecture used for sensor fusion.
#+RESULTS:
[[file:figs/detail_control_feedback_sensor_fusion_arch.png]]

One of the main advantage of implementing and designing complementary filters using the feedback architecture of Fig. ref:fig:detail_control_feedback_sensor_fusion is that all the tools of the linear control theory can be applied for the design of the filters.
If one want to shape both $\frac{\hat{x}}{\hat{x}_1}(s) = S(s)$ and $\frac{\hat{x}}{\hat{x}_2}(s) = T(s)$, the $\mathcal{H}_\infty$ mixed-sensitivity synthesis can be easily applied.

To do so, weighting functions $W_1(s)$ and $W_2(s)$ are added to respectively shape $S(s)$ and $T(s)$ (Fig. ref:fig:detail_control_feedback_synthesis_architecture).
Then the system is rearranged to form the generalized plant $P_L(s)$ shown in Fig. ref:fig:detail_control_feedback_synthesis_architecture_generalized_plant.
The $\mathcal{H}_\infty$ mixed-sensitivity synthesis can finally be performed by applying the standard $\mathcal{H}_\infty$ synthesis to the generalized plant $P_L(s)$ which is described by eqref:eq:detail_control_generalized_plant_mixed_sensitivity.

\begin{equation}\label{eq:detail_control_generalized_plant_mixed_sensitivity}
  \begin{bmatrix} z \\ v \end{bmatrix} = P_L(s) \begin{bmatrix} w_1 \\ w_2 \\ u \end{bmatrix}; \quad P_L(s) = \begin{bmatrix}
    \phantom{+}W_1(s) & 0      & \phantom{+}1 \\
              -W_1(s) & W_2(s) &           -1
  \end{bmatrix}
\end{equation}

The output of the synthesis is a filter $L(s)$ such that the "closed-loop" $\mathcal{H}_\infty$ norm from $[w_1,\ w_2]$ to $z$ of the system in Fig. ref:fig:detail_control_feedback_sensor_fusion is less than one eqref:eq:detail_control_comp_filters_feedback_obj.

\begin{equation}\label{eq:detail_control_comp_filters_feedback_obj}
  \left\| \begin{matrix} \frac{z}{w_1} \\ \frac{z}{w_2} \end{matrix} \right\|_\infty = \left\| \begin{matrix} \frac{1}{1 + L(s)} W_1(s) \\ \frac{L(s)}{1 + L(s)} W_2(s) \end{matrix} \right\|_\infty \le 1
\end{equation}

If the synthesis is successful, the transfer functions from $\hat{x}_1$ to $\hat{x}$ and from $\hat{x}_2$ to $\hat{x}$ have their magnitude bounded by the inverse magnitude of the corresponding weighting functions.
The sensor fusion can then be implemented using the feedback architecture in Fig. ref:fig:detail_control_feedback_sensor_fusion_arch or more classically as shown in Fig. ref:fig:detail_control_sensor_fusion_overview by defining the two complementary filters using eqref:eq:detail_control_comp_filters_feedback.
The two architectures are equivalent regarding their inputs/outputs relationships.

\begin{equation}\label{eq:detail_control_comp_filters_feedback}
  H_1(s) = \frac{1}{1 + L(s)}; \quad H_2(s) = \frac{L(s)}{1 + L(s)}
\end{equation}

#+begin_src latex :file detail_control_feedback_synthesis_architecture.pdf
\tikzset{block/.default={0.8cm}{0.8cm}}
\tikzset{addb/.append style={scale=0.7}}
\tikzset{node distance=0.6}
\begin{tikzpicture}
  \node[block] (W2) at (0,0) {$W_2(s)$};
  \node[addb={+}{}{}{}{-}, right=0.8 of W2] (addfb){};
  \node[addb={+}{}{}{}{}, right=4.5 of W2] (adddy){};
  \node[block, above=0.8 of adddy] (W1){$W_1(s)$};

  \draw[<-] (W2.west) -- ++(-0.8, 0) node[above right]{$w_2$};
  \draw[->] (W2.east) -- (addfb.west) node[above left]{$\tilde{w}_2$};
  \draw[->] (addfb.east) -- ++(1, 0) node[above left]{$v$};
  \draw[<-] (adddy.west) -- ++(-1, 0) node[above right]{$u$};
  \draw[->] (adddy.east) -- ++(1.4, 0) node[above left]{$z$};
  \draw[->] (W1.south) -- (adddy.north) node[above right]{$\tilde{w}_1$};
  \draw[<-] (W1.north) -- ++(0, 0.8) node[below right]{$w_1$};
  \draw[->] ($(adddy.east) + (0.5, 0)$) node[branch]{} -- ++(0, -0.8) -| (addfb.south);
\end{tikzpicture}
#+end_src

#+begin_src latex :file detail_control_feedback_synthesis_architecture_generalized_plant.pdf
\tikzset{block/.default={0.8cm}{0.8cm}}
\tikzset{addb/.append style={scale=0.7}}
\tikzset{node distance=0.6}
\begin{tikzpicture}
  \node[block={4.5cm}{3.0cm}, fill=black!10!white] (P) {};
  \node[above] at (P.north) {$P_L(s)$};

  \coordinate[] (inputw1) at ($(P.south west)!0.75!(P.north west) + (-0.7, 0)$);
  \coordinate[] (inputw2) at ($(P.south west)!0.40!(P.north west) + (-0.7, 0)$);
  \coordinate[] (inputu)  at ($(P.south west)!0.15!(P.north west) + (-0.7, 0)$);

  \coordinate[] (outputz) at ($(P.south east)!0.75!(P.north east) + ( 0.7, 0)$);
  \coordinate[] (outputv) at ($(P.south east)!0.40!(P.north east) + ( 0.7, 0)$);

  \node[block, right=1.2 of inputw2] (W2){$W_2(s)$};
  \node[block, right=1.2 of inputw1] (W1){$W_1(s)$};
  \node[addb={+}{}{}{}{}, right=0.8 of W1] (add) {};
  \node[addb={+}{}{-}{}{},  right=1.8 of W2] (sub) {};

  \draw[->] (inputw2) node[above right]{$w_2$} -- (W2.west);
  \draw[->] (inputw1) node[above right]{$w_1$} -- (W1.west);
  \draw[->] (inputu)  node[above right]{$u$}   -| (add.south);
  \draw[->] (W2.east) -- (sub.west);
  \draw[->] (W1.east) -- (add.west);
  \draw[->] (add.east) -- (outputz)node[above left]{$z$};
  \draw[->] (sub.east) -- (outputv)node[above left]{$v$};
  \draw[->] (add-|sub) node[branch]{} -- (sub.north);
\end{tikzpicture}
#+end_src

#+name: fig:detail_control_h_inf_mixed_sensitivity_synthesis
#+caption: $\mathcal{H}_\infty$ mixed-sensitivity synthesis
#+attr_latex: :options [htbp]
#+begin_figure
#+attr_latex: :caption \subcaption{\label{fig:detail_control_feedback_synthesis_architecture}Feedback architecture with included weights}
#+attr_latex: :options {0.58\textwidth}
#+begin_subfigure
#+attr_latex: :scale 1
[[file:figs/detail_control_feedback_synthesis_architecture.png]]
#+end_subfigure
#+attr_latex: :caption \subcaption{\label{fig:detail_control_feedback_synthesis_architecture_generalized_plant}Generalized plant}
#+attr_latex: :options {0.38\textwidth}
#+begin_subfigure
#+attr_latex: :scale 1
[[file:figs/detail_control_feedback_synthesis_architecture_generalized_plant.png]]
#+end_subfigure
#+end_figure

As an example, two "closed-loop" complementary filters are designed using the $\mathcal{H}_\infty$ mixed-sensitivity synthesis.
The weighting functions are designed using formula eqref:eq:detail_control_weight_formula with parameters shown in Table ref:tab:detail_control_weights_params.
After synthesis, a filter $L(s)$ is obtained whose magnitude is shown in Fig. ref:fig:detail_control_hinf_filters_results_mixed_sensitivity by the black dashed line.
The "closed-loop" complementary filters are compared with the inverse magnitude of the weighting functions in Fig. ref:fig:detail_control_hinf_filters_results_mixed_sensitivity confirming that the synthesis is successful.
The obtained "closed-loop" complementary filters are indeed equal to the ones obtained in Section ref:sec:detail_control_hinf_example.

#+begin_src matlab
%% Design of "Closed-loop" complementary filters
% Design of the Weighting Functions
W1 = generateWF('n', 3, 'w0', 2*pi*10, 'G0', 1000, 'Ginf', 1/10, 'Gc', 0.45);
W2 = generateWF('n', 2, 'w0', 2*pi*10, 'G0', 1/10, 'Ginf', 1000, 'Gc', 0.45);

% Generalized plant for "closed-loop" complementary filter synthesis
P = [ W1 0   1;
     -W1 W2 -1];

% Standard H-Infinity Synthesis
[L, ~, gamma, ~] = hinfsyn(P, 1, 1,'TOLGAM', 0.001, 'METHOD', 'ric', 'DISPLAY', 'on');

% Complementary filters
H1 = inv(1 + L);
H2 = 1 - H1;
#+end_src

#+begin_src matlab :exports none :results none
%% Bode plot of the obtained complementary filters after H-infinity mixed-sensitivity synthesis
figure;
tiledlayout(3, 1, 'TileSpacing', 'Compact', 'Padding', 'None');

% Magnitude
ax1 = nexttile([2, 1]);
hold on;
set(gca,'ColorOrderIndex',1)
plot(freqs, 1./abs(squeeze(freqresp(W1, freqs, 'Hz'))), '--', 'DisplayName', '$|W_1|^{-1}$');
set(gca,'ColorOrderIndex',2)
plot(freqs, 1./abs(squeeze(freqresp(W2, freqs, 'Hz'))), '--', 'DisplayName', '$|W_2|^{-1}$');

set(gca,'ColorOrderIndex',1)
plot(freqs, abs(squeeze(freqresp(H1, freqs, 'Hz'))), '-', 'DisplayName', '$H_1$');
set(gca,'ColorOrderIndex',2)
plot(freqs, abs(squeeze(freqresp(H2, freqs, 'Hz'))), '-', 'DisplayName', '$H_2$');

plot(freqs, abs(squeeze(freqresp(L, freqs, 'Hz'))), 'k--', 'DisplayName', '$|L|$');
hold off;
set(gca, 'XScale', 'log'); set(gca, 'YScale', 'log');
set(gca, 'XTickLabel',[]); ylabel('Magnitude');
ylim([1e-3, 1e3]);
yticks([1e-3, 1e-2, 1e-1, 1, 1e1, 1e2, 1e3]);
yticklabels({'', '$10^{-2}$', '', '$10^0$', '', '$10^2$', ''});
leg = legend('location', 'northeast', 'FontSize', 8, 'NumColumns', 3);
leg.ItemTokenSize(1) = 18;

% Phase
ax2 = nexttile;
hold on;
set(gca,'ColorOrderIndex',1)
plot(freqs, 180/pi*phase(squeeze(freqresp(H1, freqs, 'Hz'))), '-');
set(gca,'ColorOrderIndex',2)
plot(freqs, 180/pi*phase(squeeze(freqresp(H2, freqs, 'Hz'))), '-');
hold off;
set(gca, 'XScale', 'log');
xlabel('Frequency [Hz]'); ylabel('Phase [deg]');
yticks([-180:90:180]);
ylim([-180, 200])
yticklabels({'-180', '', '0', '', '180'})

linkaxes([ax1,ax2],'x');
xlim([freqs(1), freqs(end)]);
#+end_src

#+begin_src matlab :tangle no :exports results :results file replace
exportFig('figs/detail_control_hinf_filters_results_mixed_sensitivity.pdf', 'width', 'wide', 'height', 600);
#+end_src

#+name: fig:detail_control_hinf_filters_results_mixed_sensitivity
#+caption: Bode plot of the obtained complementary filters after $\mathcal{H}_\infty$ mixed-sensitivity synthesis
#+RESULTS:
[[file:figs/detail_control_hinf_filters_results_mixed_sensitivity.png]]

** Synthesis of a set of three complementary filters
<<sec:detail_control_hinf_three_comp_filters>>

Some applications may require to merge more than two sensors [[cite:&stoten01_fusion_kinet_data_using_compos_filter;&fonseca15_compl]].
For instance at the LIGO, three sensors (an LVDT, a seismometer and a geophone) are merged to form a super sensor [[cite:&matichard15_seism_isolat_advan_ligo]].

When merging $n>2$ sensors using complementary filters, two architectures can be used as shown in Fig. ref:fig:detail_control_sensor_fusion_three.
The fusion can either be done in a "sequential" way where $n-1$ sets of two complementary filters are used (Fig. ref:fig:detail_control_sensor_fusion_three_sequential), or in a "parallel" way where one set of $n$ complementary filters is used (Fig. ref:fig:detail_control_sensor_fusion_three_parallel).

In the first case, typical sensor fusion synthesis techniques can be used.
However, when a parallel architecture is used, a new synthesis method for a set of more than two complementary filters is required as only simple analytical formulas have been proposed in the literature [[cite:&stoten01_fusion_kinet_data_using_compos_filter;&fonseca15_compl]].
A generalization of the proposed synthesis method of complementary filters is presented in this section.

#+begin_src latex :file detail_control_sensor_fusion_three_sequential.pdf
\tikzset{block/.default={0.8cm}{0.8cm}}
\tikzset{addb/.append style={scale=0.7}}
\tikzset{node distance=0.6}
\begin{tikzpicture}
  \node[branch] (x) at (0, 0);

  \node[block, right=0.4 of x] (sensor2) {Sensor 2};
  \node[block, above=0.4 of sensor2] (sensor1) {Sensor 1};
  \node[block, below=0.4 of sensor2] (sensor3) {Sensor 3};

  \node[block, right=1.1 of sensor1](H1){$H_1(s)$};
  \node[block, right=1.1 of sensor2](H2){$H_2(s)$};
  \node[addb] (add) at ($0.5*(H1.east)+0.5*(H2.east)+(0.6, 0)$){};

  \node[block, right=0.8 of add](H1p)  {$H_1^\prime(s)$};
  \node[block] (H2p) at (H1p|-sensor3) {$H_2^\prime(s)$};

  \node[addb] (addp) at ($0.5*(H1p.east)+0.5*(H2p.east)+(0.6, 0)$){};

  \draw[->] ($(x)+(-0.8, 0)$) node[above right]{$x$} -- (sensor2.west);
  \draw[->] (x.center)     |- (sensor1.west);
  \draw[->] (x.center)     |- (sensor3.west);
  \draw[->] (sensor1.east) -- (H1.west)  node[above left]{$\hat{x}_1$};
  \draw[->] (sensor2.east) -- (H2.west)  node[above left]{$\hat{x}_2$};
  \draw[->] (sensor3.east) -- (H2p.west) node[above left]{$\hat{x}_3$};
  \draw[->] (H1)           -| (add.north);
  \draw[->] (H2)           -| (add.south);
  \draw[->] (add.east)     -- (H1p.west) node[above left]{$\hat{x}_{12}$};
  \draw[->] (H1p)          -| (addp.north);
  \draw[->] (H2p)          -| (addp.south);
  \draw[->] (addp.east)    -- ++(0.8, 0) node[above left]{$\hat{x}$};

  \begin{scope}[on background layer]
    \node[fit={(x.west|-sensor3.south) (sensor1.north-|addp.east)}, fill=black!10!white, draw, inner sep=6pt] (supersensor) {};

    \node[fit={(x.west|-sensor1.north) (add.east|-sensor2.south)}, fill=black!20!white, draw, inner sep=3pt] (superinertialsensor) {};
  \end{scope}
\end{tikzpicture}
#+end_src

#+begin_src latex :file detail_control_sensor_fusion_three_parallel.pdf
\tikzset{block/.default={0.8cm}{0.8cm}}
\tikzset{addb/.append style={scale=0.7}}
\tikzset{node distance=0.6}
\begin{tikzpicture}
  \node[branch] (x) at (0, 0);
  \node[block, right=0.4 of x] (sensor2) {Sensor 2};
  \node[block, above=0.3 of sensor2] (sensor1) {Sensor 1};
  \node[block, below=0.3 of sensor2] (sensor3) {Sensor 3};

  \node[block, right=1.1 of sensor1](H1){$H_1(s)$};
  \node[block, right=1.1 of sensor2](H2){$H_2(s)$};
  \node[block, right=1.1 of sensor3](H3){$H_3(s)$};

  \node[addb, right=0.6 of H2](add){};

  \draw[->] (x.center)                             |- (sensor1.west);
  \draw[] ($(x)+(-0.8, 0)$) node[above right]{$x$} -- (sensor2.west);
  \draw[->] (x.center)                             |- (sensor3.west);

  \draw[->] (sensor1.east) -- (H1.west) node[above left]{$\hat{x}_1$};
  \draw[->] (sensor2.east) -- (H2.west) node[above left]{$\hat{x}_2$};
  \draw[->] (sensor3.east) -- (H3.west) node[above left]{$\hat{x}_3$};

  \draw[->] (H1) -| (add.north);
  \draw[->] (H2) -- (add.west);
  \draw[->] (H3) -| (add.south);

  \draw[->] (add.east) -- ++(0.8, 0) node[above left]{$\hat{x}$};

  \begin{scope}[on background layer]
    \node[fit={(H3.south-|x) (H1.north-|add.east)}, fill=black!10!white, draw, inner sep=6pt] (supersensor) {};
  \end{scope}
\end{tikzpicture}
#+end_src

#+name: fig:detail_control_sensor_fusion_three
#+caption: Possible sensor fusion architecture when more than two sensors are to be merged
#+attr_latex: :options [htbp]
#+begin_figure
#+attr_latex: :caption \subcaption{\label{fig:detail_control_sensor_fusion_three_sequential}Sequential fusion}
#+attr_latex: :options {0.58\textwidth}
#+begin_subfigure
#+attr_latex: :scale 0.9
[[file:figs/detail_control_sensor_fusion_three_sequential.png]]
#+end_subfigure
#+attr_latex: :caption \subcaption{\label{fig:detail_control_sensor_fusion_three_parallel}Parallel fusion}
#+attr_latex: :options {0.38\textwidth}
#+begin_subfigure
#+attr_latex: :scale 0.9
[[file:figs/detail_control_sensor_fusion_three_parallel.png]]
#+end_subfigure
#+end_figure

The synthesis objective is to compute a set of $n$ stable transfer functions $[H_1(s),\ H_2(s),\ \dots,\ H_n(s)]$ such that conditions eqref:eq:detail_control_hinf_cond_compl_gen and eqref:eq:detail_control_hinf_cond_perf_gen are satisfied.

\begin{subequations}\label{eq:detail_control_hinf_problem_gen}
  \begin{align}
    & \sum_{i=1}^n H_i(s) = 1 \label{eq:detail_control_hinf_cond_compl_gen} \\
    & \left| H_i(j\omega) \right| < \frac{1}{\left| W_i(j\omega) \right|}, \quad \forall \omega,\ i = 1 \dots n \label{eq:detail_control_hinf_cond_perf_gen}
  \end{align}
\end{subequations}

$[W_1(s),\ W_2(s),\ \dots,\ W_n(s)]$ are weighting transfer functions that are chosen to specify the maximum complementary filters' norm during the synthesis.

Such synthesis objective is closely related to the one described in Section ref:sec:detail_control_synthesis_objective, and indeed the proposed synthesis method is a generalization of the one presented in Section ref:sec:detail_control_hinf_synthesis.

A set of $n$ complementary filters can be shaped by applying the standard $\mathcal{H}_\infty$ synthesis to the generalized plant $P_n(s)$ described by eqref:eq:detail_control_generalized_plant_n_filters.

\begin{equation}\label{eq:detail_control_generalized_plant_n_filters}
  \begin{bmatrix} z_1 \\ \vdots \\ z_n \\ v \end{bmatrix} = P_n(s) \begin{bmatrix} w \\ u_1 \\ \vdots \\ u_{n-1} \end{bmatrix}; \quad
  P_n(s) = \begin{bmatrix}
    W_1    & -W_1   & \dots  & \dots  & -W_1 \\
    0      &  W_2   & 0      & \dots  & 0 \\
    \vdots & \ddots & \ddots & \ddots & \vdots \\
    \vdots &        & \ddots & \ddots & 0 \\
    0      & \dots  & \dots  & 0      & W_n \\
    1      & 0      & \dots  & \dots  & 0
    \end{bmatrix}
\end{equation}

If the synthesis if successful, a set of $n-1$ filters $[H_2(s),\ H_3(s),\ \dots,\ H_n(s)]$ are obtained such that eqref:eq:detail_control_hinf_syn_obj_gen is verified.

\begin{equation}\label{eq:detail_control_hinf_syn_obj_gen}
  \left\|\begin{matrix} \left(1 - \left[ H_2(s) + H_3(s) + \dots + H_n(s) \right]\right) W_1(s) \\ H_2(s) W_2(s) \\ \vdots \\ H_n(s) W_n(s) \end{matrix}\right\|_\infty \le 1
\end{equation}

$H_1(s)$ is then defined using eqref:eq:detail_control_h1_comp_h2_hn which is ensuring the complementary property for the set of $n$ filters eqref:eq:detail_control_hinf_cond_compl_gen.
Condition eqref:eq:detail_control_hinf_cond_perf_gen is satisfied thanks to eqref:eq:detail_control_hinf_syn_obj_gen.

\begin{equation}\label{eq:detail_control_h1_comp_h2_hn}
  H_1(s) \triangleq 1 - \big[ H_2(s) + H_3(s) + \dots + H_n(s) \big]
\end{equation}

An example is given to validate the proposed method for the synthesis of a set of three complementary filters.
The sensors to be merged are a displacement sensor from DC up to $\SI{1}{Hz}$, a geophone from $1$ to $\SI{10}{Hz}$ and an accelerometer above $\SI{10}{Hz}$.
Three weighting functions are designed using formula eqref:eq:detail_control_weight_formula and their inverse magnitude are shown in Fig. ref:fig:detail_control_three_complementary_filters_results (dashed curves).

Consider the generalized plant $P_3(s)$ shown in Fig. ref:fig:detail_control_comp_filter_three_hinf_gen_plant which is also described by eqref:eq:detail_control_generalized_plant_three_filters.

\begin{equation}\label{eq:detail_control_generalized_plant_three_filters}
  \begin{bmatrix} z_1 \\ z_2 \\ z_3 \\ v \end{bmatrix} = P_3(s) \begin{bmatrix} w \\ u_1 \\ u_2 \end{bmatrix}; \quad P_3(s) = \begin{bmatrix}W_1(s) & -W_1(s) & -W_1(s) \\ 0 & \phantom{+}W_2(s) & 0 \\ 0 & 0 & \phantom{+}W_3(s) \\ 1 & 0 & 0 \end{bmatrix}
\end{equation}


#+begin_src latex :file detail_control_comp_filter_three_hinf_gen_plant.pdf
\tikzset{block/.default={0.8cm}{0.8cm}}
\tikzset{addb/.append style={scale=0.7}}
\tikzset{node distance=0.6}
\begin{tikzpicture}
  \node[block={5.0cm}{4.5cm}, fill=black!10!white] (P) {};
  \node[above] at (P.north) {$P_3(s)$};

  \coordinate[] (inputw)  at ($(P.south west)!0.8!(P.north west) + (-0.7, 0)$);
  \coordinate[] (inputu)  at ($(P.south west)!0.4!(P.north west) + (-0.7, 0)$);

  \coordinate[] (output1) at ($(P.south east)!0.8!(P.north east)  + (0.7, 0)$);
  \coordinate[] (output2) at ($(P.south east)!0.55!(P.north east) + (0.7, 0)$);
  \coordinate[] (output3) at ($(P.south east)!0.3!(P.north east)  + (0.7, 0)$);
  \coordinate[] (outputv) at ($(P.south east)!0.1!(P.north east)  + (0.7, 0)$);

  \node[block, left=1.4 of output1] (W1){$W_1(s)$};
  \node[block, left=1.4 of output2] (W2){$W_2(s)$};
  \node[block, left=1.4 of output3] (W3){$W_3(s)$};
  \node[addb={+}{}{}{}{-}, left=of W1] (sub1) {};
  \node[addb={+}{}{}{}{-}, left=of sub1] (sub2) {};

  \node[block, below=0.3 of P, opacity=0] (H) {$\begin{bmatrix}H_2(s) \\ H_3(s)\end{bmatrix}$};

  \draw[->] (inputw) node[above right](w){$w$} -- (sub2.west);
  \draw[->] (W3-|sub1)node[branch]{} -- (sub1.south);
  \draw[->] (W2-|sub2)node[branch]{} -- (sub2.south);
  \draw[->] ($(sub2.west)+(-0.5, 0)$) node[branch]{} |- (outputv);
  \draw[->] (inputu|-W2) -- (W2.west);
  \draw[->] (inputu|-W3) -- (W3.west);

  \draw[->] (sub2.east) -- (sub1.west);
  \draw[->] (sub1.east) -- (W1.west);
  \draw[->] (W1.east) -- (output1)node[above left](z){$z_1$};
  \draw[->] (W2.east) -- (output2)node[above left]{$z_2$};
  \draw[->] (W3.east) -- (output3)node[above left]{$z_3$};
  \node[above] at (W2-|w){$u_1$};
  \node[above] at (W3-|w){$u_2$};
  \node[above] at (outputv-|z){$v$};
\end{tikzpicture}
#+end_src

#+begin_src latex :file detail_control_comp_filter_three_hinf_fb.pdf
\tikzset{block/.default={0.8cm}{0.8cm}}
\tikzset{addb/.append style={scale=0.7}}
\tikzset{node distance=0.6}
\begin{tikzpicture}
  \node[block={5.0cm}{4.5cm}, fill=black!10!white] (P) {};
  \node[above] at (P.north) {$P_3(s)$};

  \coordinate[] (inputw)  at ($(P.south west)!0.8!(P.north west) + (-0.7, 0)$);
  \coordinate[] (inputu)  at ($(P.south west)!0.4!(P.north west) + (-0.7, 0)$);

  \coordinate[] (output1) at ($(P.south east)!0.8!(P.north east)  + (0.7, 0)$);
  \coordinate[] (output2) at ($(P.south east)!0.55!(P.north east) + (0.7, 0)$);
  \coordinate[] (output3) at ($(P.south east)!0.3!(P.north east)  + (0.7, 0)$);
  \coordinate[] (outputv) at ($(P.south east)!0.1!(P.north east)  + (0.7, 0)$);

  \node[block, left=1.4 of output1] (W1){$W_1(s)$};
  \node[block, left=1.4 of output2] (W2){$W_2(s)$};
  \node[block, left=1.4 of output3] (W3){$W_3(s)$};
  \node[addb={+}{}{}{}{-}, left=of W1] (sub1) {};
  \node[addb={+}{}{}{}{-}, left=of sub1] (sub2) {};

  \node[block, below=0.3 of P] (H) {$\begin{bmatrix}H_2(s) \\ H_3(s)\end{bmatrix}$};

  \draw[->] (inputw) node[above right](w){$w$} -- (sub2.west);
  \draw[->] (W3-|sub1)node[branch]{} -- (sub1.south);
  \draw[->] (W2-|sub2)node[branch]{} -- (sub2.south);
  \draw[->] ($(sub2.west)+(-0.5, 0)$) node[branch]{} |- (outputv) |- (H.east);
  \draw[->] ($(H.south west)!0.7!(H.north west)$) -| (inputu|-W2) -- (W2.west);
  \draw[->] ($(H.south west)!0.3!(H.north west)$) -| ($(inputu|-W3)+(0.4, 0)$) -- (W3.west);

  \draw[->] (sub2.east) -- (sub1.west);
  \draw[->] (sub1.east) -- (W1.west);
  \draw[->] (W1.east) -- (output1)node[above left](z){$z_1$};
  \draw[->] (W2.east) -- (output2)node[above left]{$z_2$};
  \draw[->] (W3.east) -- (output3)node[above left]{$z_3$};
  \node[above] at (W2-|w){$u_1$};
  \node[above] at (W3-|w){$u_2$};
  \node[above] at (outputv-|z){$v$};
\end{tikzpicture}
#+end_src

#+name: fig:detail_control_comp_filter_three_hinf
#+caption: Architecture for the $\mathcal{H}_\infty$ synthesis of three complementary filters
#+attr_latex: :options [htbp]
#+begin_figure
#+attr_latex: :caption \subcaption{\label{fig:detail_control_comp_filter_three_hinf_gen_plant}Generalized plant}
#+attr_latex: :options {0.48\textwidth}
#+begin_subfigure
#+attr_latex: :scale 1
[[file:figs/detail_control_comp_filter_three_hinf_gen_plant.png]]
#+end_subfigure
#+attr_latex: :caption \subcaption{\label{fig:detail_control_comp_filter_three_hinf_fb}Generalized plant with the synthesized filter}
#+attr_latex: :options {0.48\textwidth}
#+begin_subfigure
#+attr_latex: :scale 1
[[file:figs/detail_control_comp_filter_three_hinf_fb.png]]
#+end_subfigure
#+end_figure

The standard $\mathcal{H}_\infty$ synthesis is performed on the generalized plant $P_3(s)$.
Two filters $H_2(s)$ and $H_3(s)$ are obtained such that the $\mathcal{H}_\infty$ norm of the closed-loop transfer from $w$ to $[z_1,\ z_2,\ z_3]$ of the system in Fig. ref:fig:detail_control_comp_filter_three_hinf_fb is less than one.
Filter $H_1(s)$ is defined using eqref:eq:detail_control_h1_compl_h2_h3 thus ensuring the complementary property of the obtained set of filters.

\begin{equation}\label{eq:detail_control_h1_compl_h2_h3}
  H_1(s) \triangleq 1 - \big[ H_2(s) + H_3(s) \big]
\end{equation}

Figure ref:fig:detail_control_three_complementary_filters_results displays the three synthesized complementary filters (solid lines) which confirms that the synthesis is successful.

#+begin_src matlab
%% Synthesis of a set of three complementary filters
% Design of the Weighting Functions
W1 = generateWF('n', 2, 'w0', 2*pi*1, 'G0', 1/10, 'Ginf', 1000, 'Gc', 0.5);
W2 = 0.22*(1 + s/2/pi/1)^2/(sqrt(1e-4) + s/2/pi/1)^2*(1 + s/2/pi/10)^2/(1 + s/2/pi/1000)^2;
W3 = generateWF('n', 3, 'w0', 2*pi*10, 'G0', 1000, 'Ginf', 1/10, 'Gc', 0.5);

% Generalized plant for the synthesis of 3 complementary filters
P = [W1 -W1 -W1;
     0   W2  0 ;
     0   0   W3;
     1   0   0];

% Standard H-Infinity Synthesis
[H, ~, gamma, ~] = hinfsyn(P, 1, 2,'TOLGAM', 0.001, 'METHOD', 'ric', 'DISPLAY', 'on');

% Synthesized H2 and H3 filters
H2 = tf(H(1));
H3 = tf(H(2));

% H1 is defined as the complementary filter of H2 and H3
H1 = 1 - H2 - H3;
#+end_src

#+begin_src matlab :exports none :results none
%% Bode plot of the inverse weighting functions and of the three complementary filters obtained using the H-infinity synthesis
figure;
tiledlayout(3, 1, 'TileSpacing', 'Compact', 'Padding', 'None');

% Magnitude
ax1 = nexttile([2, 1]);
hold on;
set(gca,'ColorOrderIndex',1)
plot(freqs, 1./abs(squeeze(freqresp(W1, freqs, 'Hz'))), '--', 'DisplayName', '$|W_1|^{-1}$');
set(gca,'ColorOrderIndex',2)
plot(freqs, 1./abs(squeeze(freqresp(W2, freqs, 'Hz'))), '--', 'DisplayName', '$|W_2|^{-1}$');
set(gca,'ColorOrderIndex',3)
plot(freqs, 1./abs(squeeze(freqresp(W3, freqs, 'Hz'))), '--', 'DisplayName', '$|W_3|^{-1}$');
set(gca,'ColorOrderIndex',1)
plot(freqs, abs(squeeze(freqresp(H1, freqs, 'Hz'))), '-', 'DisplayName', '$H_1$');
set(gca,'ColorOrderIndex',2)
plot(freqs, abs(squeeze(freqresp(H2, freqs, 'Hz'))), '-', 'DisplayName', '$H_2$');
set(gca,'ColorOrderIndex',3)
plot(freqs, abs(squeeze(freqresp(H3, freqs, 'Hz'))), '-', 'DisplayName', '$H_3$');
set(gca, 'XScale', 'log'); set(gca, 'YScale', 'log');
hold off;
set(gca, 'XScale', 'log'); set(gca, 'YScale', 'log');
ylabel('Magnitude');
set(gca, 'XTickLabel',[]);
ylim([1e-4, 20]);
leg = legend('location', 'northeast', 'FontSize', 8);
leg.ItemTokenSize(1) = 18;

% Phase
ax2 = nexttile;
hold on;
set(gca,'ColorOrderIndex',1)
plot(freqs, 180/pi*phase(squeeze(freqresp(H1, freqs, 'Hz'))));
set(gca,'ColorOrderIndex',2)
plot(freqs, 180/pi*phase(squeeze(freqresp(H2, freqs, 'Hz'))));
set(gca,'ColorOrderIndex',3)
plot(freqs, 180/pi*phase(squeeze(freqresp(H3, freqs, 'Hz'))));
hold off;
xlabel('Frequency [Hz]'); ylabel('Phase [deg]');
set(gca, 'XScale', 'log');
yticks([-180:90:180]); ylim([-220, 220]);

linkaxes([ax1,ax2],'x');
xlim([freqs(1), freqs(end)]);
#+end_src

#+begin_src matlab :tangle no :exports results :results file replace
exportFig('figs/detail_control_three_complementary_filters_results.pdf', 'width', 'wide', 'height', 600);
#+end_src

#+name: fig:detail_control_three_complementary_filters_results
#+caption: Bode plot of the inverse weighting functions and of the three complementary filters obtained using the $\mathcal{H}_\infty$ synthesis
#+RESULTS:
[[file:figs/detail_control_three_complementary_filters_results.png]]

** Conclusion
:PROPERTIES:
:UNNUMBERED: t
:END:

A new method for designing complementary filters using the $\mathcal{H}_\infty$ synthesis has been proposed.
It allows to shape the magnitude of the filters by the use of weighting functions during the synthesis.
This is very valuable in practice as the characteristics of the super sensor are linked to the complementary filters' magnitude.
Therefore typical sensor fusion objectives can be translated into requirements on the magnitudes of the filters.
Several examples were used to emphasize the simplicity and the effectiveness of the proposed method.

However, the shaping of the complementary filters' magnitude does not allow to directly optimize the super sensor noise and dynamical characteristics.
Future work will aim at developing a complementary filter synthesis method that minimizes the super sensor noise while ensuring the robustness of the fusion.

* Decoupling Strategies
:PROPERTIES:
:HEADER-ARGS:matlab+: :tangle matlab/detail_control_2_decoupling.m
:END:
<<sec:detail_control_decoupling>>

** Introduction                                                      :ignore:

# *This report is based on*:
# - file:~/Cloud/research/matlab/decoupling-strategies/svd-control.org
# - [X] Maybe not relevant, as it is experimental results based on the Stewart platform file:/home/thomas/Cloud/meetings/group-meetings-me/2021-08-16-Nano-Hexapod-Control/2021-08-16-Nano-Hexapod-Control.org

When dealing with MIMO systems, a typical strategy is to:
- first decouple the plant dynamics
- apply SISO control for the decoupled plant

Assumptions:
- parallel manipulators

Review of decoupling strategies for Stewart platforms:
- [[file:~/Cloud/work-projects/ID31-NASS/matlab/stewart-simscape/org/bibliography.org::*Decoupling Strategies][Decoupling Strategies]]


- [ ] What example should be taken?
  *3dof system*? stewart platform?
  Maybe simpler.

** Matlab Init                                              :noexport:ignore:
#+begin_src matlab :tangle no :exports none :results silent :noweb yes :var current_dir=(file-name-directory buffer-file-name)
<<matlab-dir>>
#+end_src

#+begin_src matlab :exports none :results silent :noweb yes
<<matlab-init>>
#+end_src

#+begin_src matlab :tangle no :noweb yes
<<m-init-path>>
#+end_src

#+begin_src matlab :eval no :noweb yes
<<m-init-path-tangle>>
#+end_src

#+begin_src matlab :noweb yes
<<m-init-other>>
#+end_src

** Interaction Analysis

** Decentralized Control (actuator frame)

** Center of Stiffness and center of Mass

- Example
- Show

** Modal Decoupling

** Data Based Decoupling

- Static decoupling
- SVD

** Conclusion
:PROPERTIES:
:UNNUMBERED: t
:END:

Table that compares all the strategies.

* Closed-Loop Shaping using Complementary Filters
:PROPERTIES:
:HEADER-ARGS:matlab+: :tangle matlab/detail_control_3_close_loop_shaping.m
:END:
<<sec:detail_control_optimization>>

** Introduction                                                      :ignore:

# - file:~/Cloud/research/papers/published/verma19_virtu_senso_fusio_high_preci_contr/elsarticle-template-harv.pdf
# - file:~/Cloud/research/papers/dehaeze20_virtu_senso_fusio/index.org

Performance of a feedback control is dictated by closed-loop transfer functions.
For instance sensitivity, transmissibility, etc... Gang of Four.

There are several ways to design a controller to obtain a given performance.

Decoupled Open-Loop Shaping:
- As shown in previous section, once the plant is decoupled: open loop shaping
- Explain procedure when applying open-loop shaping
- Lead, Lag, Notches, Check Stability, c2d, etc...
- But this is open-loop shaping, and it does not directly work on the closed loop transfer functions

Other strategy: Model Based Design:
- [[file:~/Cloud/work-projects/ID31-NASS/matlab/stewart-simscape/org/bibliography.org::*Multivariable Control][Multivariable Control]]
- Talk about Caio's thesis?
- Review of model based design (LQG, H-Infinity) applied to Stewart platform
- Difficulty to specify robustness to change of payload mass

In this section, an alternative is proposed in which complementary filters are used for closed-loop shaping.
It is presented for a SISO system, but can be generalized to MIMO if decoupling is sufficient.
It will be experimentally demonstrated with the NASS.

** Matlab Init                                              :noexport:ignore:
#+begin_src matlab :tangle no :exports none :results silent :noweb yes :var current_dir=(file-name-directory buffer-file-name)
<<matlab-dir>>
#+end_src

#+begin_src matlab :exports none :results silent :noweb yes
<<matlab-init>>
#+end_src

#+begin_src matlab :tangle no :noweb yes
<<m-init-path>>
#+end_src

#+begin_src matlab :eval no :noweb yes
<<m-init-path-tangle>>
#+end_src

#+begin_src matlab :noweb yes
<<m-init-other>>
#+end_src

** Conclusion
:PROPERTIES:
:UNNUMBERED: t
:END:

* Conclusion
:PROPERTIES:
:UNNUMBERED: t
:END:
<<sec:detail_control_conclusion>>

* Bibliography                                                        :ignore:
#+latex: \printbibliography[heading=bibintoc,title={Bibliography}]

* Matlab Functions                                                  :noexport:
** =generateWF=: Generate Weighting Functions

#+begin_src matlab :tangle matlab/src/generateWF.m :comments none :mkdirp yes :eval no
function [W] = generateWF(args)
% generateWF -
%
% Syntax: [W] = generateWeight(args)
%
% Inputs:
%    - n  - Weight Order (integer)
%    - G0 - Low frequency Gain
%    - G1 - High frequency Gain
%    - Gc - Gain of the weight at frequency w0
%    - w0 - Frequency at which |W(j w0)| = Gc [rad/s]
%
% Outputs:
%    - W - Generated Weighting Function

%% Argument validation
arguments
    args.n    (1,1) double {mustBeInteger, mustBePositive} = 1
    args.G0   (1,1) double {mustBeNumeric, mustBePositive} = 0.1
    args.Ginf (1,1) double {mustBeNumeric, mustBePositive} = 10
    args.Gc   (1,1) double {mustBeNumeric, mustBePositive} = 1
    args.w0   (1,1) double {mustBeNumeric, mustBePositive} = 1
end

% Verification of correct relation between G0, Gc and Ginf
mustBeBetween(args.G0, args.Gc, args.Ginf);

%% Initialize the Laplace variable
s = zpk('s');

%% Create the weighting function according to formula
W = (((1/args.w0)*sqrt((1-(args.G0/args.Gc)^(2/args.n))/(1-(args.Gc/args.Ginf)^(2/args.n)))*s + ...
      (args.G0/args.Gc)^(1/args.n))/...
     ((1/args.Ginf)^(1/args.n)*(1/args.w0)*sqrt((1-(args.G0/args.Gc)^(2/args.n))/(1-(args.Gc/args.Ginf)^(2/args.n)))*s + ...
      (1/args.Gc)^(1/args.n)))^args.n;

%% Custom validation function
function mustBeBetween(a,b,c)
    if ~((a > b && b > c) || (c > b && b > a))
        eid = 'createWeight:inputError';
        msg = 'Gc should be between G0 and Ginf.';
        throwAsCaller(MException(eid,msg))
    end
#+end_src

** =generateCF=: Generate Complementary Filters

#+begin_src matlab :tangle matlab/src/generateCF.m :comments none :mkdirp yes :eval no
function [H1, H2] = generateCF(W1, W2, args)
% generateCF -
%
% Syntax: [H1, H2] = generateCF(W1, W2, args)
%
% Inputs:
%    - W1 - Weighting Function for H1
%    - W2 - Weighting Function for H2
%    - args:
%      - method  - H-Infinity solver ('lmi' or 'ric')
%      - display - Display synthesis results ('on' or 'off')
%
% Outputs:
%    - H1 - Generated H1 Filter
%    - H2 - Generated H2 Filter

%% Argument validation
arguments
    W1
    W2
    args.method  char {mustBeMember(args.method,{'lmi', 'ric'})} = 'ric'
    args.display char {mustBeMember(args.display,{'on', 'off'})} = 'on'
end

%% The generalized plant is defined
P = [W1 -W1;
     0   W2;
     1   0];

%% The standard H-infinity synthesis is performed
[H2, ~, gamma, ~] = hinfsyn(P, 1, 1,'TOLGAM', 0.001, 'METHOD', args.method, 'DISPLAY', args.display);

%% H1 is defined as the complementary of H2
H1 = 1 - H2;
#+end_src

* Helping Functions                                                 :noexport:
** Initialize Path
#+NAME: m-init-path
#+BEGIN_SRC matlab
%% Path for functions, data and scripts
addpath('./matlab/src/'); % Path for functions
addpath('./matlab/');     % Path for scripts
#+END_SRC

#+NAME: m-init-path-tangle
#+BEGIN_SRC matlab
%% Path for functions, data and scripts
addpath('./src/'); % Path for functions
#+END_SRC

** Initialize other elements
#+NAME: m-init-other
#+BEGIN_SRC matlab
%% Colors for the figures
colors = colororder;

%% Initialize Frequency Vector
freqs = logspace(-1, 3, 1000);
#+END_SRC
