Antares Simulator
Power System Simulator
LinearExpression.h
1 /*
2  * Copyright 2007-2024, RTE (https://www.rte-france.com)
3  * See AUTHORS.txt
4  * SPDX-License-Identifier: MPL-2.0
5  * This file is part of Antares-Simulator,
6  * Adequacy and Performance assessment for interconnected energy networks.
7  *
8  * Antares_Simulator is free software: you can redistribute it and/or modify
9  * it under the terms of the Mozilla Public Licence 2.0 as published by
10  * the Mozilla Foundation, either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * Antares_Simulator is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * Mozilla Public Licence 2.0 for more details.
17  *
18  * You should have received a copy of the Mozilla Public Licence 2.0
19  * along with Antares_Simulator. If not, see <https://opensource.org/license/mpl-2-0/>.
20  */
21 #pragma once
22 
23 #include <stdexcept>
24 #include <utility>
25 #include <vector>
26 
27 namespace Antares::Optimization
28 {
29 class LinearExpression final
30 {
31 public:
33  explicit LinearExpression(double constant);
34  explicit LinearExpression(const std::vector<std::pair<int, double>>& coefs, double constant);
35  LinearExpression(const LinearExpression& other) = default;
36  void mergeDuplicateCoefficients();
37 
38  LinearExpression& operator*=(double factor);
39  LinearExpression& operator+=(const LinearExpression& other);
40  LinearExpression& operator-=(const LinearExpression& other);
41  LinearExpression operator-() const;
42  LinearExpression operator/(const LinearExpression& other) const;
43  LinearExpression& operator*=(const LinearExpression& other);
44  LinearExpression& operator^=(const LinearExpression& other);
45 
46  void addVariable(int index, double value);
47  double constant() const;
48 
49  using const_iterator = std::vector<std::pair<int, double>>::const_iterator;
50  const_iterator begin() const;
51  const_iterator end() const;
52  const std::pair<int, double>& operator[](std::size_t) const;
53  std::size_t size() const;
54 
55  bool hasCoefs() const;
56 
57 private:
58  std::vector<std::pair<int, double>> coefs_;
59  double constant_ = 0.;
60 };
61 
62 template<class Op>
63 double applyOperation(const std::vector<const LinearExpression*>& expressions, Op op)
64 {
65  std::vector<double> constants(expressions.size(), 0);
66  for (int i = 0; i < expressions.size(); ++i)
67  {
68  const auto& expression = expressions[i];
69  if (expression->hasCoefs())
70  {
71  throw std::invalid_argument(std::string("Operator '") + typeid(op).name()
72  + "' cannot be applied to expressions with "
73  "coefficients (non-constant expressions).");
74  }
75  constants[i] = expression->constant();
76  }
77 
78  return op(constants);
79 }
80 
81 } // namespace Antares::Optimization
Definition: LinearExpression.h:30