unary_mx.cpp
1 /*
2  * This file is part of CasADi.
3  *
4  * CasADi -- A symbolic framework for dynamic optimization.
5  * Copyright (C) 2010-2023 Joel Andersson, Joris Gillis, Moritz Diehl,
6  * KU Leuven. All rights reserved.
7  * Copyright (C) 2011-2014 Greg Horn
8  *
9  * CasADi is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 3 of the License, or (at your option) any later version.
13  *
14  * CasADi is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with CasADi; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  *
23  */
24 
25 
26 #include "unary_mx.hpp"
27 #include "casadi_misc.hpp"
28 #include "global_options.hpp"
29 #include "serializing_stream.hpp"
30 #include <sstream>
31 #include <vector>
32 
33 namespace casadi {
34 
35  UnaryMX::UnaryMX(Operation op, MX x) : op_(op) {
36  // Put a densifying node in between if necessary
37  if (!operation_checker<F00Checker>(op_)) {
38  x = densify(x);
39  }
40 
41  set_dep(x);
42  set_sparsity(x->sparsity());
43  }
44 
45  std::string UnaryMX::disp(const std::vector<std::string>& arg) const {
46  return casadi_math<double>::print(op_, arg.at(0));
47  }
48 
49  int UnaryMX::eval(const double** arg, double** res, casadi_int* iw, double* w) const {
50  double dummy = std::numeric_limits<double>::quiet_NaN();
51  casadi_math<double>::fun(op_, arg[0], dummy, res[0], nnz());
52  return 0;
53  }
54 
55  int UnaryMX::eval_sx(const SXElem** arg, SXElem** res, casadi_int* iw, SXElem* w) const {
56  SXElem dummy = 0;
57  casadi_math<SXElem>::fun(op_, arg[0], dummy, res[0], nnz());
58  return 0;
59  }
60 
61  void UnaryMX::eval_mx(const std::vector<MX>& arg, std::vector<MX>& res,
62  const std::vector<bool>& unique) const {
63  bool unique_arg0 = !unique.empty() && unique[0];
64  res[0] = MX::unary(op_, arg[0], unique_arg0);
65  }
66 
67  void UnaryMX::eval_linear(const std::vector<std::array<MX, 3> >& arg,
68  std::vector<std::array<MX, 3> >& res) const {
69  MX dummy[3];
70  casadi_math<MX>::fun_linear(op_, arg[0].data(), dummy, res[0].data());
71  }
72 
73  void UnaryMX::ad_forward(const std::vector<std::vector<MX> >& fseed,
74  std::vector<std::vector<MX> >& fsens) const {
75  // Get partial derivatives
76  MX pd[2];
77  MX dummy; // Function value, dummy second argument
78  casadi_math<MX>::der(op_, dep(), dummy, shared_from_this<MX>(), pd);
79 
80  // Propagate forward seeds
81  for (casadi_int d=0; d<fsens.size(); ++d) {
82  fsens[d][0] = pd[0]*fseed[d][0];
83  }
84  }
85 
86  void UnaryMX::ad_reverse(const std::vector<std::vector<MX> >& aseed,
87  std::vector<std::vector<MX> >& asens) const {
88  // Get partial derivatives
89  MX pd[2];
90  MX dummy; // Function value, dummy second argument
91  casadi_math<MX>::der(op_, dep(), dummy, shared_from_this<MX>(), pd);
92 
93  // Propagate adjoint seeds
94  for (casadi_int d=0; d<aseed.size(); ++d) {
95  asens[d][0] += pd[0]*aseed[d][0];
96  }
97  }
98 
99  int UnaryMX::sp_forward(const bvec_t** arg, bvec_t** res, casadi_int* iw, bvec_t* w) const {
100  copy_fwd(arg[0], res[0], nnz());
101  return 0;
102  }
103 
104  int UnaryMX::eval_activity(const bvec_t** arg, bvec_t** res, casadi_int* iw, bvec_t* w) const {
105  const bvec_t zero_out = operation_checker<F0XChecker>(op_) ? 0 : ~static_cast<bvec_t>(0);
106  const bvec_t* a = arg[0];
107  bvec_t* r = res[0];
108  for (casadi_int i=0; i<nnz(); ++i) r[i] = a[i] ? ~static_cast<bvec_t>(0) : zero_out;
109  return 0;
110  }
111 
112  int UnaryMX::sp_reverse(bvec_t** arg, bvec_t** res, casadi_int* iw, bvec_t* w) const {
113  copy_rev(arg[0], res[0], nnz());
114  return 0;
115  }
116 
118  const std::vector<casadi_int>& arg,
119  const std::vector<casadi_int>& res,
120  const std::vector<bool>& arg_is_ref,
121  std::vector<bool>& res_is_ref) const {
122  std::string r, x;
123  if (nnz()==1) {
124  // Scalar assignment
125  r = g.workel(res[0]);
126  x = g.workel(arg[0]);
127  } else {
128  // Vector assignment
129  g.local("cs", "const casadi_real", "*");
130  g.local("rr", "casadi_real", "*");
131  g.local("i", "casadi_int");
132  g << "for (i=0, rr=" << g.work(res[0], nnz(), false) << ", cs="
133  << g.work(arg[0], nnz(), arg_is_ref[0])
134  << "; i<" << sparsity().nnz() << "; ++i) ";
135  r = "*rr++";
136  x = "*cs++";
137  }
138 
139  // Output the operation
140  g << r << " = " << g.print_op(op_, " " + x + " ") << ";\n";
141  }
142 
143  bool UnaryMX::is_nonnegative() const {
144  return operation_checker<NonnegativeChecker>(op_);
145  }
146 
147  MX UnaryMX::_get_binary(casadi_int op, const MX& y, bool scX, bool scY,
148  bool unique_x, bool unique_y) const {
149  switch (op_) {
150  case OP_NEG:
151  if (op==OP_ADD) return y->_get_binary(OP_SUB, dep(), scY, scX, unique_y, false);
152  else if (op==OP_MUL) return -dep()->_get_binary(OP_MUL, y, scX, scY, false, unique_y);
153  else if (op==OP_DIV) return -dep()->_get_binary(OP_DIV, y, scX, scY, false, unique_y);
154  break;
155  case OP_INV:
156  if (op==OP_MUL) return y->_get_binary(OP_DIV, dep(), scY, scX, unique_y, false);
157  break;
158  case OP_TWICE:
159  if (op==OP_SUB && MX::is_equal(y, dep(), maxDepth())) return dep();
160  break;
161  case OP_SQ:
162  if (op==OP_ADD && y.op()==OP_SQ) /*sum of squares:*/
163  if ((dep().op()==OP_SIN && y->dep().op()==OP_COS) ||
164  (dep().op()==OP_COS && y->dep()->op()==OP_SIN)) /* sin^2(x)+sin^2(y) */
165  if (MX::is_equal(dep()->dep(), y->dep()->dep(), maxDepth())) /*sin^2(x) + cos^2(x) */
166  return MX::ones(y.sparsity());
167  break;
168  default: break; // no rule
169  }
170 
171  // Fallback to default implementation
172  return MXNode::_get_binary(op, y, scX, scY, unique_x, unique_y);
173  }
174 
177  s.pack("UnaryMX::op", static_cast<int>(op_));
178  }
179 
181  int op;
182  s.unpack("UnaryMX::op", op);
183  op_ = Operation(op);
184  }
185 
186 } // namespace casadi
Helper class for C code generation.
std::string work(casadi_int n, casadi_int sz, bool is_ref) const
std::string print_op(casadi_int op, const std::string &a0)
Print an operation to a c file.
void local(const std::string &name, const std::string &type, const std::string &ref="")
Declare a local variable.
std::string workel(casadi_int n) const
Helper class for Serialization.
void unpack(Sparsity &e)
Reconstruct an object from the input stream.
static MX ones(casadi_int nrow=1, casadi_int ncol=1)
Create a dense matrix or a matrix with specified sparsity with all entries one.
Node class for MX objects.
Definition: mx_node.hpp:51
static void copy_fwd(const bvec_t *arg, bvec_t *res, casadi_int len)
Propagate sparsities forward through a copy operation.
Definition: mx_node.cpp:1302
static bool maxDepth()
Get equality checking depth.
Definition: mx_node.hpp:380
static void copy_rev(bvec_t *arg, bvec_t *res, casadi_int len)
Propagate sparsities backwards through a copy operation.
Definition: mx_node.cpp:1308
virtual MX _get_binary(casadi_int op, const MX &y, bool scX, bool scY, bool unique_x=false, bool unique_y=false) const
Get a binary operation operation (matrix-matrix)
Definition: mx_node.cpp:852
const Sparsity & sparsity() const
Get the sparsity.
Definition: mx_node.hpp:410
casadi_int nnz(casadi_int i=0) const
Definition: mx_node.hpp:427
const MX & dep(casadi_int ind=0) const
dependencies - functions that have to be evaluated before this one
Definition: mx_node.hpp:392
virtual void serialize_body(SerializingStream &s) const
Serialize an object without type information.
Definition: mx_node.cpp:530
void set_sparsity(const Sparsity &sparsity)
Set the sparsity.
Definition: mx_node.cpp:224
virtual casadi_int op() const =0
Get the operation.
void set_dep(const MX &dep)
Set unary dependency.
Definition: mx_node.cpp:228
MX - Matrix expression.
Definition: mx.hpp:92
static MX unary(casadi_int op, const MX &x, bool unique=false)
Create nodes by their ID.
Definition: mx.cpp:560
const Sparsity & sparsity() const
Get the sparsity pattern.
Definition: mx.cpp:612
static bool is_equal(const MX &x, const MX &y, casadi_int depth=0)
Definition: mx.cpp:867
casadi_int op() const
Get operation type.
Definition: mx.cpp:851
The basic scalar symbolic class of CasADi.
Definition: sx_elem.hpp:75
Helper class for Serialization.
void pack(const Sparsity &e)
Serializes an object to the output stream.
casadi_int nnz() const
Get the number of (structural) non-zeros.
Definition: sparsity.cpp:148
Operation op_
operation
Definition: unary_mx.hpp:151
bool is_nonnegative() const override
Check if not negative.
Definition: unary_mx.cpp:143
void ad_reverse(const std::vector< std::vector< MX > > &aseed, std::vector< std::vector< MX > > &asens) const override
Calculate reverse mode directional derivatives.
Definition: unary_mx.cpp:86
void eval_linear(const std::vector< std::array< MX, 3 > > &arg, std::vector< std::array< MX, 3 > > &res) const override
Evaluate the MX node on a const/linear/nonlinear partition.
Definition: unary_mx.cpp:67
casadi_int op() const override
Get the operation.
Definition: unary_mx.hpp:115
void eval_mx(const std::vector< MX > &arg, std::vector< MX > &res, const std::vector< bool > &unique=std::vector< bool >()) const override
Evaluate symbolically (MX)
Definition: unary_mx.cpp:61
int eval_activity(const bvec_t **arg, bvec_t **res, casadi_int *iw, bvec_t *w) const override
Propagate signal activity forward.
Definition: unary_mx.cpp:104
int sp_forward(const bvec_t **arg, bvec_t **res, casadi_int *iw, bvec_t *w) const override
Propagate sparsity forward.
Definition: unary_mx.cpp:99
int eval(const double **arg, double **res, casadi_int *iw, double *w) const override
Evaluate the function numerically.
Definition: unary_mx.cpp:49
int eval_sx(const SXElem **arg, SXElem **res, casadi_int *iw, SXElem *w) const override
Evaluate the function symbolically (SX)
Definition: unary_mx.cpp:55
void serialize_body(SerializingStream &s) const override
Serialize an object without type information.
Definition: unary_mx.cpp:175
MX _get_binary(casadi_int op, const MX &y, bool scX, bool scY, bool unique_x=false, bool unique_y=false) const override
Get a binary operation operation.
Definition: unary_mx.cpp:147
void generate(CodeGenerator &g, const std::vector< casadi_int > &arg, const std::vector< casadi_int > &res, const std::vector< bool > &arg_is_ref, std::vector< bool > &res_is_ref) const override
Generate code for the operation.
Definition: unary_mx.cpp:117
int sp_reverse(bvec_t **arg, bvec_t **res, casadi_int *iw, bvec_t *w) const override
Propagate sparsity backwards.
Definition: unary_mx.cpp:112
std::string disp(const std::vector< std::string > &arg) const override
Print expression.
Definition: unary_mx.cpp:45
UnaryMX(Operation op, MX x)
Constructor is private, use "create" below.
Definition: unary_mx.cpp:35
void ad_forward(const std::vector< std::vector< MX > > &fseed, std::vector< std::vector< MX > > &fsens) const override
Calculate forward mode directional derivatives.
Definition: unary_mx.cpp:73
The casadi namespace.
Definition: archiver.cpp:28
unsigned long long bvec_t
Operation
Enum for quick access to any node.
Definition: calculus.hpp:60
@ OP_COS
Definition: calculus.hpp:68
@ OP_INV
Definition: calculus.hpp:73
@ OP_SIN
Definition: calculus.hpp:68
@ OP_TWICE
Definition: calculus.hpp:67
@ OP_SUB
Definition: calculus.hpp:65
@ OP_ADD
Definition: calculus.hpp:65
@ OP_DIV
Definition: calculus.hpp:65
@ OP_NEG
Definition: calculus.hpp:66
@ OP_MUL
Definition: calculus.hpp:65
@ OP_SQ
Definition: calculus.hpp:67
static void der(unsigned char op, const T &x, const T &y, const T &f, T *d)
Evaluate a built in derivative function.
Definition: calculus.hpp:1385
static void fun_linear(unsigned char op, const T *x, const T *y, T *f)
Evaluate function on a const/linear/nonlinear partition.
Definition: calculus.hpp:1562
static std::string print(unsigned char op, const std::string &x, const std::string &y)
Print.
Definition: calculus.hpp:1651
static void fun(unsigned char op, const T &x, const T &y, T &f)
Evaluate a built in function (scalar-scalar)
Definition: calculus.hpp:1299