# title: Piecewise linear costs
#
# description: |
#     Add a piecewise cost function that steadily increases investment costs with increasing technology rated capacity.
#     This requires the user to switch on the binary purchase decision variable for any relevant technology.
#     Without the purchase decision variable, the technology will have non-zero costs irrespective even if the technology capacity is zero.
#
#     New indexed parameters:
#
#     - `cost_flow_cap_piecewise_slopes` (defining the new set `pieces`)
#     - `cost_flow_cap_piecewise_intercept` (defining the new set `pieces`)
#
# ---

dimensions:
  pieces:
    dtype: integer
    iterator: piece

parameters:
  cost_flow_cap_piecewise_slopes:
    description: The gradient of each of the piecewise limiting line defining the convex, non-linear cost curve
    unit: unitless

  cost_flow_cap_piecewise_intercept:
    description: The y-axis intercept of each of the piecewise limiting line defining the convex, non-linear cost curve
    unit: unitless

variables:
  piecewise_cost_investment:
    description: Investment cost that increases monotonically
    foreach: [nodes, techs, costs]
    default: 0
    unit: cost
    where: >
        cost_flow_cap_piecewise_slopes AND cost_flow_cap_piecewise_intercept
        AND purchased_units
    bounds:
      min: 0
      max: .inf

constraints:
  piecewise_costs:
    description: >
      Limit the lower bound of piecewise investment costs to monotonically
      increasing values. Since the model is cost minimising, this is equivalent
      to forcing the investment cost to a specific point along the curve that
      is traced by the superposition of all pieces.
    foreach: [nodes, techs, costs, pieces]
    where: piecewise_cost_investment
    equations:
      - expression: >
          piecewise_cost_investment >=
          sum(cost_flow_cap_piecewise_slopes * flow_cap, over=carriers)
          + cost_flow_cap_piecewise_intercept * purchased_units

# We inject this new source of into the `cost` global expression
global_expressions:
  cost_investment:
    where: >
      (cost_investment_flow_cap OR cost_investment_storage_cap
      OR cost_investment_source_cap OR cost_investment_area_use
      OR cost_investment_purchase OR piecewise_cost_investment)
    equations:
      - expression: >
          sum(cost_investment_flow_cap, over=carriers) +
          cost_investment_storage_cap +
          cost_investment_source_cap +
          cost_investment_area_use +
          cost_investment_purchase +
          piecewise_cost_investment
