如何修复 DimensionError?

问题描述

我遇到了一个奇怪的错误,仍然无法弄清楚。

#include <iostream>
#include "fusion.h"

using namespace mosek::fusion;
using namespace monty;

int main(int argc,char ** argv)
{

  int number_of_steps = 7;
  int lambda1 = 1000;
  int lambda2 = 1000;
  int dim_space = 3;
  auto A = new_array_ptr<double,2>({ {-0.1504,0.5675,-0.7252},{-0.4518,0.0456,0.0530},{0.2635,-0.1113,-0.2546},{-0.0495,-0.2224,0.1030},{ 0.1216,-0.2716,0.0503},{ 0.2000,-0.2788,0.1627},{0.3534,-0.2255,0.1733},{ 0.2737,-0.2614,0.1941},{0.3001,0.1014,0.3227},{ 0.2473,0.0765,0.3377}});
  
  auto b = new_array_ptr<double,2>({{0.3597},{0.8894},{0.9238},{0.9682},{0.9534},{0.9251},{0.8912},{0.9050},{0.8919},{0.9050}});

  auto b_rep = new_array_ptr<double,2>({{0.3597,0.3597,0.3597},{0.8894,0.8894,0.8894},{0.9238,0.9238,0.9238},{0.9682,0.9682,0.9682},{0.9534,0.9534,0.9534},{0.9251,0.9251,0.9251},{0.8912,0.8912,0.8912},{0.9050,0.9050,0.9050},{0.8919,0.8919,0.8919},0.9050}});

  Model::t M = new Model();
  auto x = M->variable(new_array_ptr<int,1>({dim_space,number_of_steps}),Domain::unbounded()) ;
  Matrix::t recipe = Matrix::dense(A);

  // This way does not work,// for (int i = 0; i < number_of_steps; i++)
  // {
  //   auto x_i = Var::vstack(x->index(0,i),x->index(1,x->index(2,i));
  //   M->constraint(Expr::mul(recipe,x_i),Domain::lessthan(b));
  // }
  
  // This is working fine
  M->constraint(Expr::mul(A,x),Domain::lessthan(b_rep));
}

这里当我使用 M->constraint(Expr::mul(A,Domain::lessthan(b_rep)); 表达式时它工作正常。但同样的事情可以通过以下方式完成,但不起作用,

for (int i = 0; i < number_of_steps; i++)
{
     auto x_i = Var::vstack(x->index(0,i));
     M->constraint(Expr::mul(recipe,Domain::lessthan(b));
}

我收到以下错误

terminate called after throwing an instance of 'mosek::fusion::DimensionError'
  what():  Mismatching expression and domain
Aborted (core dumped)

解决方法

b 的形状是 (1,10),表达式的形状是 (10)。如果你这样做,它会起作用

  auto b = new_array_ptr<double,1>({0.3597,0.8894,0.9238,0.9682,0.9534,0.9251,0.8912,0.9050,0.8919,0.9050});

或者,您也可以使用与以前相同的 b,但作为域使用

Domain::lessThan(b)->withShape(new_array_ptr<int,1>({10}))

然而,最推荐使用运行良好的矢量化变体。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...