<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (C) 2014-2023 Ryan Specialty, LLC.

  This file is part of tame-core.

  tame-core is free software: you can redistribute it and/or modify it
  under the terms of the GNU General Public License as
  published by the Free Software Foundation, either version 3 of the
  License, or (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
-->
<package xmlns="http://www.lovullo.com/rater"
         xmlns:c="http://www.lovullo.com/calc"
         xmlns:t="http://www.lovullo.com/rater/apply-template"
         core="true"
         desc="Percentage arithmetic">

  <import package="../base" />


  Converting between real and~percent is trivial:

  $$
    \begin{align}
      r &amp;= p\over100;
      p &amp;= 100r.
    \end{align}
  $$

  ^[Percent difference] (also called ^[relative change]) describes
  the~change in value as a~percentage (for example: $10$~is $50%$
  of~$20$, and is~$100%$ of~$5$).  ^[Percent change] recognizes the
  direction of the change (that is---$10$ is~$20$ reduced by~$50%$, so
  $p=-50$).

  Since ``change'' sounds like a~verb eclarative contexts, we use
  the~term ^[percent difference] to mean ^[relative change]; it is
  defined as:

  $$\delta \over x = {{x_\beta - x_\alpha}\over{x_\alpha}} \times 100 = p.$$

  Notice that this preserves the direction of the change.  So, in the
  context of the previous example, we can say that $10$
  \emph{reduces}~$20$ by~$50%$, giving~$p=-50%$.


  <template name="_rtop_"
            desc="Rational number to percentage">
    <param name="@name@"  desc="Percentage to convert" />

    <param name="@index@" desc="Index">
      <text></text>
    </param>

    <param name="@desc@" desc="Optional description">
      <text>Real number to convert into percentage</text>
    </param>

    <param name="@difference@"
           desc="Whether to interpret as a percent difference (default
                 false)">
      <text>false</text>
    </param>

    <param name="@negate@" desc="Whether to negate percentage before
                                 conversion">
      <text>false</text>
    </param>


    <c:product>
      <if name="@negate@" eq="true">
        <c:const value="-1" desc="Negate result" />
      </if>

      <c:sum>
        <c:value-of name="@name@" index="@index@" />

        <if name="@difference@" eq="true">
          <c:const value="-1"
                   desc="Percent difference is relative (1 = 100%)" />
        </if>
      </c:sum>

      <c:const value="100"
               desc="Real to percentage" />
    </c:product>
  </template>



  <template name="_ptor_" desc="Percent to rational number">
    <param name="@name@" desc="Percentage to convert" />
    <param name="@index@" desc="Index" />

    <param name="@value@" desc="Constant (instead of named value)" />
    <param name="@desc@" desc="Optional description for constant value">
      <text>Percent to convert</text>
    </param>

    <param name="@difference@" desc="Whether to perform a percent
                                     difference (default false)">
      <text>false</text>
    </param>

    <param name="@negate@" desc="Whether to negate percentage before
                                 conversion">
      <text>false</text>
    </param>

    <c:sum>
      <if name="@difference@" eq="true">
        <c:const value="1"
                 desc="Perform percent difference" />
      </if>

      <c:quotient>
        <c:product>
          <if name="@negate@" eq="true">
            <c:value-of name="NEGATE" />
          </if>

          <if name="@name@">
            <c:value-of name="@name@" index="@index@" />
          </if>
          <unless name="@name@">
            <c:const value="@value@" desc="@desc@" />
          </unless>
        </c:product>

        <c:const value="100" desc="Convert to rational number" />
      </c:quotient>
    </c:sum>
  </template>



  <template name="_ptor-each_"
            desc="Each percent to real number">
    <param name="@name@"      desc="Percentage to convert" />
    <param name="@generates@" desc="Value to generate into" />

    <param name="@difference@"
           desc="Whether to perform a percent difference">
      <text>false</text>
    </param>

    <param name="@negate@" desc="Whether to negate percentage before
                                 conversion">
      <text>false</text>
    </param>


    <rate yields="_{@generates@}">
      <c:sum of="@name@"
             generates="@generates@" index="k"
             desc="Real representation of {@name@}">
        <t:ptor difference="@difference@" negate="@negate@"
                name="@name@" index="k" />
      </c:sum>
    </rate>
  </template>



  <!--
    Yields a total percent as an integer and rational number. The
    integer is useful for displaying a total percent (e.g. for
    credits/surcharges) and the rational number is useful for using
    for multiplication in an equation.

    Example:

      <t:total-percent class="foo"
                       to_int="fooPercentTotal" to_rat="fooTotal"
                       index="k">
        <with-param name="@values@">
          <c:value-of name="fooA" index="k" />
          <c:value-of name="fooB" index="k" />
        </with-param>
      </t:total-percent>

    Let fooA = 5, fooB = -7

    will yield:
      - fooPercentTotal = -2
      - fooTotal        = 0.98
  -->
  <template name="_total-percent_"
            desc="Generates a total percentage as an integer and a
                  rational number">
    <!-- for use by @values@ -->
    <param name="@index@" desc="Index variable" />

    <param name="@class@" desc="Classification match" />
    <param name="@to_int@" desc="Integer total to yield" />
    <param name="@to_rat@" desc="Rational number to yield" />

    <param name="@values@" desc="Value nodes" />

    <param name="@yields_int@" desc="Yields for integer total">
      <text>_</text>
      <param-value name="@to_int@" />
    </param>
    <param name="@yields_rat@" desc="Yields for rational total">
      <text>_</text>
      <param-value name="@to_rat@" />
    </param>


    <!-- percent total (e.g. 7 for 7%) -->
    <rate-each class="@class@" yields="@yields_int@"
               generates="@to_int@" index="@index@">
      <c:sum>
        <param-copy name="@values@" />
      </c:sum>
    </rate-each>


    <!-- as a rational number (to multiply by; e.g. 1.07 for 7%, 0.93 for -7%) -->
    <rate-each class="@class@" yields="@yields_rat@"
               generates="@to_rat@" index="k">
      <c:sum>
        <c:const value="1" desc="Relative percent" />
        <t:ptor name="@to_int@" index="k" />
      </c:sum>
    </rate-each>
  </template>



  <!--
    This template is useful for, say, when a coverage is partially
    included, but additional coverage may be purchased. For example,
    if 10% of coverage X is included, but you can purchase more Y if
    10% is insufficient, then we can simply reduce coverage Y by 10%
    of coverage X.

    If the initial value is insufficient, then the value 0 will be
    produced.
  -->
  <template name="_percent-reduction_"
            desc="Reduces a set of values by a percentage of another set of values">
    <param name="@index@" desc="Value index" />

    <param name="@reduce@"    desc="Vector to reduce values of" />
    <param name="@percentof@" desc="Vector to reduce values by a percentage of" />
    <param name="@percent@"   desc="Percent reduction (as a float)" />
    <param name="@minval@"    desc="Minimum value to reduce by (optional)" />
    <param name="@condition@" desc="Boolean conditions (vector for
                                    each index) under which reduction should be applied" />

    <param name="@desc@" desc="Optional description">
      <text>Percent to reduce by</text>
    </param>

    <param name="@label@" desc="Label for max() application">
      <text>Reduced </text>
      <param-value name="@reduce@" />
      <text> by </text>
      <param-value name="@percent@" />
      <text>*</text>
      <param-value name="@percentof@" />
      <text> (cannot fall below 0)</text>
    </param>


    <c:apply name="max" label="@label@">
      <!-- if the reduction produces a value less than 0, then simply return 0 -->
      <c:arg name="max1">
        <c:const value="0"
                 desc="0 will be returned if the reduction is too great" />
      </c:arg>

      <c:arg name="max2">
        <c:sum>
          <c:value-of name="@reduce@" index="@index@"
                      label="Initial value" />

          <c:let>
            <c:values>
              <c:value name="reduce" type="float"
                       desc="Value to reduce by, should condition be met">
                <c:product>
                  <c:const value="@percent@" desc="@desc@" />
                  <c:value-of name="@percentof@" index="@index@" />
                </c:product>
              </c:value>
            </c:values>

            <t:negate>
              <c:product label="Conditional reduction">
                <if name="@condition@">
                  <c:when name="@condition@" index="@index@">
                    <c:eq>
                      <c:value-of name="TRUE" />
                    </c:eq>
                  </c:when>
                </if>

                <if name="@minval@">
                  <c:apply name="max" max1="reduce">
                    <c:arg name="max2">
                      <c:const value="@minval@"
                               desc="Minimum value to reduce by" />
                    </c:arg>
                  </c:apply>
                </if>
                <unless name="@minval@">
                  <c:value-of name="reduce" label="Value to reduce by" />
                </unless>
              </c:product>
            </t:negate>
          </c:let>
        </c:sum>
      </c:arg>
    </c:apply>
  </template>



  <template name="_percent-of-set_"
            desc="Returns the percent of a set of given values">
    <param name="@class@"     desc="Class match" />
    <param name="@of@"        desc="Vector of values to take the percent of" />
    <param name="@percent@"   desc="Percent reduction (as a float)" />
    <param name="@generates@" desc="Value to generate" />

    <param name="@yields@" desc="Yield">
      <param-value name="@generates@" />
      <text>Total</text>
    </param>


    <rate-each class="@class@" yields="@yields@"
               generates="@generates@" index="k">
      <c:apply name="round">
        <c:arg name="roundval">
          <c:apply name="max">
            <!-- if the reduction produces a value less than 0, then simply return 0 -->
            <c:arg name="max1">
              <c:const value="0"
                       desc="0 will be returned if the reduction is too great" />
            </c:arg>

            <c:arg name="max2">
              <c:product label="Percent value">
                <c:const value="@percent@" desc="Percent to reduce by" />

                <c:value-of name="@of@" index="k"
                            label="Value to take percentage of" />
              </c:product>
            </c:arg>
          </c:apply>
        </c:arg>
      </c:apply>
    </rate-each>
  </template>
</package>
