|
| 1 | +#include "affine.h" |
| 2 | +#include <assert.h> |
| 3 | +#include <stdio.h> |
| 4 | +#include <string.h> |
| 5 | + |
| 6 | +/* Reshape changes the shape of an expression without permuting data. |
| 7 | + * Only Fortran (column-major) order is supported, where reshape is a no-op |
| 8 | + * for the underlying data layout. */ |
| 9 | + |
| 10 | +static void forward(expr *node, const double *u) |
| 11 | +{ |
| 12 | + node->left->forward(node->left, u); |
| 13 | + memcpy(node->value, node->left->value, node->size * sizeof(double)); |
| 14 | +} |
| 15 | + |
| 16 | +static void jacobian_init(expr *node) |
| 17 | +{ |
| 18 | + expr *x = node->left; |
| 19 | + x->jacobian_init(x); |
| 20 | + node->jacobian = new_csr_matrix(node->size, node->n_vars, x->jacobian->nnz); |
| 21 | + CSR_Matrix *jac = node->jacobian; |
| 22 | + memcpy(jac->p, x->jacobian->p, (x->size + 1) * sizeof(int)); |
| 23 | + memcpy(jac->i, x->jacobian->i, x->jacobian->nnz * sizeof(int)); |
| 24 | +} |
| 25 | + |
| 26 | +static void eval_jacobian(expr *node) |
| 27 | +{ |
| 28 | + expr *x = node->left; |
| 29 | + x->eval_jacobian(x); |
| 30 | + memcpy(node->jacobian->x, x->jacobian->x, x->jacobian->nnz * sizeof(double)); |
| 31 | +} |
| 32 | + |
| 33 | +static void wsum_hess_init(expr *node) |
| 34 | +{ |
| 35 | + node->left->wsum_hess_init(node->left); |
| 36 | + CSR_Matrix *child_hess = node->left->wsum_hess; |
| 37 | + node->wsum_hess = new_csr_matrix(child_hess->m, child_hess->n, child_hess->nnz); |
| 38 | + memcpy(node->wsum_hess->p, child_hess->p, (child_hess->m + 1) * sizeof(int)); |
| 39 | + memcpy(node->wsum_hess->i, child_hess->i, child_hess->nnz * sizeof(int)); |
| 40 | + node->wsum_hess->nnz = child_hess->nnz; |
| 41 | +} |
| 42 | + |
| 43 | +static void eval_wsum_hess(expr *node, const double *w) |
| 44 | +{ |
| 45 | + node->left->eval_wsum_hess(node->left, w); |
| 46 | + CSR_Matrix *child_hess = node->left->wsum_hess; |
| 47 | + CSR_Matrix *hess = node->wsum_hess; |
| 48 | + memcpy(hess->x, child_hess->x, child_hess->nnz * sizeof(double)); |
| 49 | +} |
| 50 | + |
| 51 | +static bool is_affine(const expr *node) |
| 52 | +{ |
| 53 | + return node->left->is_affine(node->left); |
| 54 | +} |
| 55 | + |
| 56 | +expr *new_reshape(expr *child, int d1, int d2) |
| 57 | +{ |
| 58 | + assert(d1 * d2 == child->size); |
| 59 | + expr *node = new_expr(d1, d2, child->n_vars); |
| 60 | + node->left = child; |
| 61 | + expr_retain(child); |
| 62 | + node->forward = forward; |
| 63 | + node->is_affine = is_affine; |
| 64 | + node->jacobian_init = jacobian_init; |
| 65 | + node->eval_jacobian = eval_jacobian; |
| 66 | + node->wsum_hess_init = wsum_hess_init; |
| 67 | + node->eval_wsum_hess = eval_wsum_hess; |
| 68 | + |
| 69 | + return node; |
| 70 | +} |
0 commit comments