Advertisement
Stan_

direct_multiple_shooting

Dec 14th, 2018
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 5.94 KB | None | 0 0
  1. % Метод: Direct Multiple Shooting
  2.  
  3. function Example5
  4. % очистить command window, workspace, закрыть графику
  5. clc, clear all, close all
  6. import casadi.*
  7.  
  8. % Горизонт управления
  9. T = 1.5;
  10. mu = 0.5;
  11.  
  12. % Количество интервалов и период дискретизации
  13. delta = 0.1;
  14. N = T / delta;
  15.  
  16. % Переменные модели
  17. x = MX.sym('x', 2);
  18. u = MX.sym('u', 1);
  19.  
  20. % Стоимость этапа: L(x,u)
  21. L = (x(1)^2 + x(2)^2) / 2 + u^2;
  22.  
  23. % Динамика системы: правая часть ДУ
  24. xdot = [x(2) + u * (mu + (1 - mu) * x(1));
  25.         x(1) + u * (mu - 4 * (1 - mu) * x(2))];
  26. % Начальное состояние
  27. x0 = [-0.7; -0.8];    
  28.  
  29. % Создаем интегратор с помощью CVODES из SUNDIALS Suite
  30. % использование: x(delta | 0, x0, u) = F('x0', x0, 'p', u)
  31. ode = struct('x', x, 'p', u, 'ode', xdot, 'quad', L);
  32. F = integrator('F', 'cvodes', ode, struct('tf', delta));
  33.  
  34. % Собираем переменные и ограничения задачи
  35. u = MX.sym('u',N,1);
  36. x = MX.sym('x',N,2);
  37. % Формирование вектора cons, который в структуре NLP будет входить в
  38. % условия g. Этот вектор должен равняться нулю, так как траектория x
  39. % непрерывна
  40. cons = vec(x(1,:))-x0;
  41. J   = 0;
  42. for k = 1:(N-1)
  43.     res = F('x0', x(k,:), 'p', u(k));    % x(delta | 0, s, u(k))
  44.     cons = [cons; vec(x(k+1,:)) - res.xf];
  45.     J   = J + res.qf;
  46. end
  47. res = F('x0', x(N,:), 'p', u(N));
  48. % Терминальное слагаемое
  49. E = 16.5926*(res.xf(1)^2+res.xf(2)^2)+2*11.5926*res.xf(1)*res.xf(2);
  50. % Создаем NLP-solver
  51. % Теперь переменные оптимизации - u и x. Также добавляются новые условия
  52. % непрерывности cons
  53. nlp = struct('x', [u; x(:)], 'f', J + E, 'g', [cons; E]);
  54. solver = nlpsol('solver', 'ipopt', nlp);
  55. % Решаем задачу нелинейного программирования
  56. tic
  57. sol = solver('x0', zeros(3*N,1),...
  58.     'lbx', [repmat(-2,N,1); repmat(-Inf,2*N,1)],...
  59.     'ubx', [repmat(2,N,1); repmat(+Inf,2*N,1)],...
  60.     'lbg', [zeros(2*N,1); -Inf],...
  61.     'ubg', [zeros(2*N,1); 0.7]);
  62. t_Elapsed = toc;
  63. opt = full(sol.x);
  64. u_opt = opt(1:N);
  65.  
  66. % Восстанавливаем траекторию. Хотя она уже и так найдена в результате
  67. % выполнения метода direct multiple shooting, но я хочу сравнить
  68. % траектории, чтобы они совпадали
  69. J_opt = full(sol.f);
  70. x_opt = x0;
  71. for k = 1:N
  72.     res = F('x0', x_opt(:,k), 'p', u_opt(k));
  73.     x_opt = [x_opt full(res.xf)];
  74. end
  75.  
  76. % Оптимальная траектория, полученная по методу direct multiple shooting
  77. x_opt2 = transpose(reshape(opt(N+1:3*N),[N,2]));
  78. res = F('x0', x_opt2(:,N), 'p', u_opt(N));
  79. x_opt2 = [x_opt2 full(res.xf)];
  80. % Выводим результаты и графики
  81. results(delta*(0:N),x_opt2,u_opt)
  82.  
  83. % Вывод, проверяющий условие непрерывности траектории
  84. x_opt2 - x_opt
  85. % -----------------------------------------------------------------
  86. % Вывод результатов
  87. % -----------------------------------------------------------------
  88. function results(T,X,U)
  89.     fprintf('   k  |      u(k)        x(1)        x(2)     \n');
  90.     fprintf('----------------------------------------------\n');
  91.     for k = 1:length(T)-1
  92.         fprintf(' %3.1f  | %+11.6f %+11.6f %+11.6f \n', T(k), u_opt(k),...
  93.             X(1,k), X(2,k));
  94.     end
  95.     fprintf('Термин.состояние  = %+11.6f %+11.6f \n\n', X(1,end),...
  96.         X(2,end));
  97.     fprintf('Оптим. значение   = %6.4f \n\n', J_opt);
  98.     fprintf('Время решения     = %6.4f \n\n', t_Elapsed);
  99.  
  100.     fig = figure(1);
  101.     set(fig,'Position', [50    100   1000   400]);
  102.  
  103.     subplot(1,2,1); hold on; grid on;    
  104.     ineqplot('16.5926*(x.^2+y.^2)+2*11.5926*x.*y<0.7',[-0.8 -0.2 -0.8...
  105.         0.2]);
  106.     plot(X(1,:),X(2,:),'-k', 'Linewidth', 1);
  107.     xlabel('x1')
  108.     ylabel('x2')
  109.     title('фазовый портрет')
  110.    
  111.     subplot(1,2,2); hold on; grid on;
  112.     stairs(T,[U;nan],'-k', 'Linewidth', 1);
  113.     plot(T, X(1,:), '-', 'Linewidth', 1)
  114.     plot(T, X(2,:), '--', 'Linewidth', 1)
  115.     xlabel('t')
  116.     legend('Location', 'west')
  117.     legend('u','x1','x2')
  118.     title('оптимальное управление, траектория')
  119. end
  120. function ineqplot(I,R,c)
  121. % Plotting inequalities, simple and easy.
  122. %
  123. % Input arguments
  124. % I - Inequality as string, i.e.  'x+y>10'
  125. % R - Vector of four components defined by: [xmin, xmax, ymin, ymax],
  126. %       if two components are passed: [min, max], the defined region
  127. %       will be a square and xmin=ymin=min, xmax=ymax=max.
  128. % c - A three-element RGB vector, or one of the MATLAB
  129. %       predefined names, specifying the plot color.
  130. %
  131. % Output arguments
  132. % h - returns the handle of the scattergroup
  133. %       object created.
  134. %
  135. % Examples:
  136. % >> ineqplot('x.^2+y.^2<10',[-5 5], 'r');
  137. % >> h = ineqplot('y<x+3',[0 10 -5 5]);
  138. % >> set(h,'MarkerFaceColor','r'); % Change color
  139. %
  140. %
  141. % $ Author:   Jorge De Los Santos $
  142. % $ Version:  0.1.0 (initial version) $
  143. %
  144. % Default color
  145. if nargin<3, c='b'; end % blue default
  146. % Length of R vector
  147. if length(R)==4
  148.     xmin = R(1); xmax = R(2);
  149.     ymin = R(3); ymax = R(4);
  150. elseif length(R)==2
  151.     xmin = R(1); xmax = R(2);
  152.     ymin = R(1); ymax = R(2);
  153. end
  154. % hold
  155. set(gca,'NextPlot','add');
  156. % Limits
  157. axis([xmin xmax ymin ymax]);
  158. % Number of points (Change N value for more resolution)
  159. N = 150;
  160. dx=(xmax-xmin)/N; %
  161. dy=(ymax-ymin)/N;
  162. [x,y]=meshgrid(xmin:dx:xmax, ymin:dy:ymax);
  163. % Eval condition
  164. idx = find(~eval(I));
  165. x(idx) = NaN; %#ok
  166. plot(x(:),y(:),c,...
  167.     'LineStyle','-',...
  168.     'MarkerSize',1);
  169. end
  170. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement