feat(minco_ws): MID360 + Point-LIO + SCAN/MINCO 导航工作区(19 个包)

- scan/: SCAN 无图局部规划(6 包)+ step_blocker(台阶封堵)+ body_odom(雷达→车体中心)
- navigation/: MINCO + Nav2 有图方案;perception/: Livox 驱动 + Point-LIO + rog_map
- chassis/: R2 底盘串口桥
- docs/: QUICKSTART(上机流程)/ SCAN_VEHICLE(方案与限制)/ DEPLOY_ROBOT(双机部署)
- scripts/: setup_deps.sh(依赖体检/安装)+ deploy_to_robot.sh(rsync 同步/远程编译)

排除 build/ install/ log/、PCD 地图(155 MB,单独 rsync)。
This commit is contained in:
2026-10-20 10:51:18 +08:00
parent eba4570f4e
commit a2947065b3
829 changed files with 272495 additions and 1 deletions
@@ -0,0 +1,63 @@
# =============================================================================
# chassis_serial_node — 运行参数(R2 底盘串口桥)
#
# 本文件是本节点所有可调项的**唯一真源**。launch/chassis_serial.launch.py 里 port 的
# launch 参数默认值就是从这里反读的,因此 launch 文件不可能再与它冲突。ROS 2 中
# parameters 列表按顺序应用、后者胜,所以 launch 文件只可能覆盖 port,且只在你显式
# 传 port:=... 时才发生。
#
# install 出来的是**拷贝**(setup.py 用拷贝方式安装 config/*.yaml),所以改 src/ 下的
# 本文件必须重新编译才生效。想改完即用、免重建,就把它直接指给节点:
# ros2 launch techx_r2_chassis_control chassis_serial.launch.py \
# params_file:=$HOME/sru_ws/src/techx_r2_chassis_control/config/chassis_serial.yaml
# =============================================================================
chassis_serial_node:
ros__parameters:
# 串口设备。两种命名风格**只能选一种**,并与你的 udev 规则保持一致
# —— 本包不自带 .rules 文件:
# /dev/ttyUSB0 内核原始名;与枚举顺序有关,重启或插入其他 USB 串口设备后
# 可能改名
# /dev/r2_chassis 绑定到适配器序列号的 udev 稳定别名(需你自建规则)
# 请在真机上核实:这两个路径在裸开发机上都不存在,且节点打不开设备时会直接抛错。
port: /dev/ttyUSB0
baudrate: 115200
# 这个值会传给 serial.Serial(),但节点**从不回读**任何帧
# (见 protocol.py:只做 上位机 -> STM32 单向),所以它对行为完全无影响。
serial_timeout_sec: 0.02
# 下行发帧率。**固定定时器**:每隔 1/velocity_rate_hz 秒就写一帧,与 /cmd_vel 到达
# 快慢无关,因此数值没变时也在重发同样的字节。带宽不是瓶颈 —— 每帧 10 B,按此速率
# 只占 115200 8N1 的约 2.6%。
velocity_rate_hz: 30.0
# /cmd_vel 静默超过这么久,就进入 stale 分支(见下方 send_zero_on_timeout)。
# 注意:上游策略发 /cmd_vel 的实际速率只有约 1.4-1.7 Hz(周期约 0.66 s,受 Odin
# 深度流限制),**比本超时更长**。配合 send_zero_on_timeout: true,就意味着每
# 0.66 s 里约有 0.46 s 在发零速帧 —— 轮子会走走停停。请在真机上核实;若确实如此,
# 应把它放宽到 >= 1.0。
cmd_vel_timeout_sec: 0.2
# true = stale 期间持续发零速帧把链路撑住(启动瞬间也算 stale,因为
# _last_cmd_time 初值为 0.0)。
# false = stale 期间完全不发,启动阶段同样不发。
# 两种取值下,下位机都**必须**实现自己的超时:本节点写失败的那一帧,与 STM32
# 从未收到的那一帧,是无法区分的。
send_zero_on_timeout: true
# 输出限幅,作用在 /cmd_vel 各分量**乘 1000 转线上格式之前**。
# 现值已低于上游策略能给出的值,因而几乎每一步都在生效:
# 纯策略、摇杆回中 : |vx| <= 0.6, |wz| <= 0.6
# 策略 + 摇杆推到底 : |vx| <= 2.7, |wz| <= 2.2
# 截断是**静默**的 —— 策略节点收不到任何反馈,无从察觉。
# 这是策略选择而非协议限制:线上格式本身能表达 ±32.767(int16 × 1000)。
max_vx_m_s: 0.5
max_vy_m_s: 0.5
max_wz_rad_s: 0.5
# true = 30 Hz 每帧打一行 INFO,含完整十六进制负载。
# 按默认速率会非常吵;只在调试协议时打开。
log_velocity_frames: true
@@ -0,0 +1,559 @@
# -*- coding: utf-8 -*-
"""生成本包的串口协议 PDF 说明(下位机接收模块对接用)。
用法:
source $WS/venv/bin/activate
python src/techx_r2_chassis_control/docs/build_protocol_pdf.py
依赖:reportlab(已在 $WS/venv 内)+ 系统中文字体 arphic/uming.ttc。
示例帧与 CRC 全部由 ../techx_r2_chassis_control/protocol.py 现算,保证与代码一致。
注意(踩过的坑):
1. 正文里的减号不要用 U+2212(−),UMing 没有该字形,会渲染成空白框;用 ASCII 连字符。
2. 代码块必须做 HTML 转义,否则代码里的 "<h" 会被 reportlab 当成标签吃掉。
3. 代码块字体是 Courier,不含中文字形,注释一律用英文,中文会变成黑块。
"""
from __future__ import annotations
import os
import sys
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import mm
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import (
BaseDocTemplate,
Frame,
HRFlowable,
KeepTogether,
PageBreak,
PageTemplate,
Paragraph,
Spacer,
Table,
TableStyle,
)
HERE = os.path.dirname(os.path.abspath(__file__))
PKG = os.path.join(os.path.dirname(HERE), "techx_r2_chassis_control")
sys.path.insert(0, PKG)
import protocol as P # noqa: E402
OUT_PDF = os.path.join(HERE, "R2底盘串口协议_v2.pdf")
CJK_FONT_PATH = "/usr/share/fonts/truetype/arphic/uming.ttc"
CJK_SUBFONT_INDEX = 0 # 0 = AR PL UMing CN
CJK = "CJK"
MONO = "Courier"
INK = colors.HexColor("#1A1A1A")
MUTED = colors.HexColor("#5F5E5A")
ACCENT = colors.HexColor("#0F4C81")
RULE = colors.HexColor("#C9D3DC")
CODE_BG = colors.HexColor("#F3F4F3")
WARN_BG = colors.HexColor("#FBEFE6")
WARN_LINE = colors.HexColor("#C0733A")
OK_BG = colors.HexColor("#EDF4E9")
OK_LINE = colors.HexColor("#5A8A3C")
CELL_HDR = colors.HexColor("#0F4C81")
CELL_ALT = colors.HexColor("#F7F9FB")
def register_fonts() -> None:
pdfmetrics.registerFont(TTFont(CJK, CJK_FONT_PATH, subfontIndex=CJK_SUBFONT_INDEX))
pdfmetrics.registerFontFamily(CJK, normal=CJK, bold=CJK, italic=CJK, boldItalic=CJK)
# ---------------------------------------------------------------- styles
def build_styles() -> dict:
s = {}
s["title"] = ParagraphStyle(
"title", fontName=CJK, fontSize=20, leading=27, textColor=ACCENT, spaceAfter=4, alignment=TA_LEFT
)
s["subtitle"] = ParagraphStyle(
"subtitle", fontName=CJK, fontSize=10.5, leading=16, textColor=MUTED, spaceAfter=2
)
s["h1"] = ParagraphStyle(
"h1", fontName=CJK, fontSize=13.5, leading=19, textColor=ACCENT, spaceBefore=13, spaceAfter=5
)
s["h2"] = ParagraphStyle(
"h2", fontName=CJK, fontSize=11.5, leading=17, textColor=INK, spaceBefore=9, spaceAfter=3
)
s["body"] = ParagraphStyle(
"body", fontName=CJK, fontSize=9.8, leading=15.6, textColor=INK, spaceAfter=4
)
s["bullet"] = ParagraphStyle(
"bullet", parent=s["body"], leftIndent=11, bulletIndent=2, spaceAfter=1.5
)
s["code"] = ParagraphStyle(
"code", fontName=MONO, fontSize=8.1, leading=11.6, textColor=INK
)
s["cell"] = ParagraphStyle(
"cell", fontName=CJK, fontSize=8.8, leading=12.6, textColor=INK
)
s["cellh"] = ParagraphStyle(
"cellh", fontName=CJK, fontSize=8.8, leading=12.6, textColor=colors.white
)
s["cellc"] = ParagraphStyle(
"cellc", fontName=MONO, fontSize=8.6, leading=12.6, textColor=INK
)
s["byteidx"] = ParagraphStyle(
"byteidx", fontName=CJK, fontSize=7.6, leading=10, textColor=MUTED, alignment=TA_CENTER
)
s["bytename"] = ParagraphStyle(
"bytename", fontName=CJK, fontSize=9, leading=12, textColor=colors.white, alignment=TA_CENTER
)
s["footnote"] = ParagraphStyle(
"footnote", fontName=CJK, fontSize=8.4, leading=13, textColor=MUTED, spaceAfter=3
)
return s
STYLES = build_styles()
def esc_code(text: str) -> str:
"""代码块转义:先转义 HTML 实体,再保留空格与换行。"""
text = text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
return text.replace("\n", "<br/>").replace(" ", "&nbsp;")
def code_block(text: str, width: float):
inner = Paragraph(esc_code(text), STYLES["code"])
return Table([[inner]], colWidths=[width],
style=TableStyle([
("BACKGROUND", (0, 0), (-1, -1), CODE_BG),
("BOX", (0, 0), (-1, -1), 0.5, RULE),
("LEFTPADDING", (0, 0), (-1, -1), 4.5 * mm),
("RIGHTPADDING", (0, 0), (-1, -1), 4.5 * mm),
("TOPPADDING", (0, 0), (-1, -1), 3.2 * mm),
("BOTTOMPADDING", (0, 0), (-1, -1), 3.2 * mm),
]))
def note(text: str, width: float, kind: str = "warn"):
bg, line = (WARN_BG, WARN_LINE) if kind == "warn" else (OK_BG, OK_LINE)
return Table([[Paragraph(text, STYLES["cell"])]], colWidths=[width],
style=TableStyle([
("BACKGROUND", (0, 0), (-1, -1), bg),
("LINEBEFORE", (0, 0), (0, -1), 2.2, line),
("LEFTPADDING", (0, 0), (-1, -1), 4 * mm),
("RIGHTPADDING", (0, 0), (-1, -1), 4 * mm),
("TOPPADDING", (0, 0), (-1, -1), 3 * mm),
("BOTTOMPADDING", (0, 0), (-1, -1), 3 * mm),
]))
def data_table(rows, col_widths, code_cols=(), align_center=()):
body = []
for r_i, row in enumerate(rows):
out = []
for c_i, cell in enumerate(row):
if isinstance(cell, str):
st = STYLES["cellh"] if r_i == 0 else (STYLES["cellc"] if c_i in code_cols else STYLES["cell"])
out.append(Paragraph(cell, st))
else:
out.append(cell)
body.append(out)
t = Table(body, colWidths=col_widths, repeatRows=1)
t.setStyle(TableStyle([
("BACKGROUND", (0, 0), (-1, 0), CELL_HDR),
("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, CELL_ALT]),
("GRID", (0, 0), (-1, -1), 0.4, RULE),
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
("LEFTPADDING", (0, 0), (-1, -1), 2.6 * mm),
("RIGHTPADDING", (0, 0), (-1, -1), 2.6 * mm),
("TOPPADDING", (0, 0), (-1, -1), 2.0 * mm),
("BOTTOMPADDING", (0, 0), (-1, -1), 2.0 * mm),
*[("ALIGN", (c, 1), (c, -1), "CENTER") for c in align_center],
]))
return t
# ---------------------------------------------------------------- examples
def frames():
ex = [
("静止(停车)", 0.0, 0.0, 0.0),
("前进", 0.25, 0.0, 0.0),
("后退", -0.20, 0.0, 0.0),
("左横移", 0.0, 0.15, 0.0),
("原地右转", 0.0, 0.0, -0.30),
("斜向 + 转向", 0.10, 0.05, 0.20),
("极限值(前进满速)", 2.5, 0.0, 0.0),
("极限值(旋转满速)", 0.0, 0.0, 1.5),
]
out = []
for name, vx, vy, wz in ex:
raw = P.pack_velocity_frame(vx * P.VX_SCALE, vy * P.VY_SCALE, wz * P.OMEGA_SCALE)
out.append((name, vx, vy, wz, raw))
return out
def main() -> None:
register_fonts()
doc = BaseDocTemplate(
OUT_PDF,
pagesize=A4,
leftMargin=17 * mm,
rightMargin=17 * mm,
topMargin=16 * mm,
bottomMargin=16 * mm,
title="R2 底盘串口通信协议 v2",
author="techx_r2_chassis_control",
subject="下位机(STM32)接收模块实现说明",
)
W = doc.width
def on_page(canv, d):
canv.saveState()
canv.setStrokeColor(RULE)
canv.setLineWidth(0.5)
y = A4[1] - 12 * mm
canv.line(doc.leftMargin, y, A4[0] - doc.rightMargin, y)
canv.setFont(CJK, 7.8)
canv.setFillColor(MUTED)
canv.drawString(doc.leftMargin, y + 2.6 * mm, "R2 底盘串口通信协议 v2 · 下位机接收模块实现说明")
canv.drawRightString(A4[0] - doc.rightMargin, y + 2.6 * mm, "第 %d 页" % d.page)
canv.line(doc.leftMargin, 12 * mm, A4[0] - doc.rightMargin, 12 * mm)
canv.restoreState()
doc.addPageTemplates([PageTemplate(
id="main",
frames=[Frame(doc.leftMargin, doc.bottomMargin, W, doc.height, id="f")],
onPage=on_page)])
F = []
add = F.append
def h1(t):
add(Paragraph(t, STYLES["h1"]))
def h2(t):
add(Paragraph(t, STYLES["h2"]))
def para(t):
add(Paragraph(t, STYLES["body"]))
def bullets(items, numbered=False):
for i, t in enumerate(items):
add(Paragraph(t, STYLES["bullet"], bulletText=("%d." % (i + 1)) if numbered else "·"))
# ------------------------------------------------------------ 封面
add(Paragraph("R2 底盘串口通信协议 v2", STYLES["title"]))
add(Paragraph("下位机(STM32)接收模块实现说明 —— 上位机到 下位机 单向速度指令", STYLES["subtitle"]))
add(HRFlowable(width="100%", thickness=1.4, color=ACCENT, spaceBefore=5, spaceAfter=7))
add(data_table([
["项目", "内容"],
["协议版本", "v2(定长 10 字节,只发速度指令)"],
["上位机实现", "ROS 2 包 techx_r2_chassis_control,节点 chassis_serial_node"],
["通信方向", "上位机 → 下位机,单向。下位机无需回包,协议不含任何上行帧"],
["文档用途", "供下位机开发者实现接收 / 校验 / 解析模块;帧示例与 CRC 由上位机代码现算,可直接作测试向量"],
], [24 * mm, W - 24 * mm]))
add(Spacer(1, 6))
add(note(
"一句话总结:上位机每 33 ms 发一帧 10 字节数据,帧内就是 vx、vy、omega 三个 int16 小端数值加一个 CRC16。"
"下位机要做的事只有三件——<b>按 10 字节切帧</b>、<b>校验 CRC</b>、<b>把三个数取出来驱动电机</b>;"
"另外建议加一条「超时未收到合法帧就停车」的兜底逻辑。", W, kind="ok"))
add(Spacer(1, 3))
# ------------------------------------------------------------ 1
h1("1. 概述")
para("上位机运行 ROS 2 导航 / 遥控栈,把最终速度指令发布在 <font face='%s'>/cmd_vel</font>"
"(geometry_msgs/Twist)话题上。本节点订阅该话题,取出线速度 x、线速度 y、角速度 z 三个分量,"
"换算成整数后按本协议打包,经串口写入下位机。整条链路是单向的:上位机只发,从不读串口,"
"因此协议里没有应答、没有序号、没有回读状态。" % MONO)
para("下位机侧要实现的收帧逻辑,本质是一个「固定长度 + 帧头 + CRC」的字节流解析器。需要注意的是:"
"帧头 <font face='%s'>AA 55</font> 会<b>偶然</b>出现在数据区里(速度值恰好为 0x55AA 或 0xAA55 时),"
"所以不能靠搜索帧头来切帧——必须以「10 字节固定帧 + CRC 校验通过」作为唯一的帧确认条件。"
"这一点在第 6 节展开。" % MONO)
# ------------------------------------------------------------ 2
h1("2. 物理层参数")
add(data_table([
["参数", "取值", "说明"],
["波特率", "115200 bps", "可通过上位机参数 baudrate 修改,下位机需保持一致"],
["数据位 / 校验 / 停止位", "8 / None / 1", "即 8N1,无奇偶校验"],
["流控", "无", "软件与硬件流控都不使用"],
["电平", "按硬件设计", "上位机侧通过 USB-TTL 适配器转为串口设备节点(默认 /dev/r2_chassis)"],
["帧率", "默认 30 Hz", "即约 33 ms 一帧;上位机参数 velocity_rate_hz 可调"],
["链路方向", "上位机 → 下位机", "下位机发回的任何字节上位机都不会读取,请勿依赖上行通道"],
], [38 * mm, 32 * mm, W - 70 * mm]))
# ------------------------------------------------------------ 3
h1("3. 帧结构(定长 10 字节)")
para("所有多字节数值均为<b>小端</b>(little-endian,低字节在前)。")
add(data_table([
["偏移", "长度", "字段", "类型", "单位", "说明"],
["0", "2", "header", "uint8[2]", "—", "固定 0xAA 0x55"],
["2", "2", "vx", "int16 LE", "mm/s", "机体坐标系前后方向,前进为正"],
["4", "2", "vy", "int16 LE", "mm/s", "机体坐标系左右方向,左移为正"],
["6", "2", "omega", "int16 LE", "mrad/s", "绕 Z 轴角速度,逆时针(左转)为正"],
["8", "2", "crc16", "uint16 LE", "—", "CRC16-MODBUS,覆盖 byte0 ~ byte7"],
], [14 * mm, 14 * mm, 20 * mm, 21 * mm, 17 * mm, W - 86 * mm], code_cols=(2,), align_center=(0, 1, 4)))
add(Spacer(1, 4))
cells = [("byte 0-1", "AA 55"), ("byte 2-3", "vx"), ("byte 4-5", "vy"),
("byte 6-7", "omega"), ("byte 8-9", "crc16")]
widths = [22 * mm, 25 * mm, 25 * mm, 30 * mm, 30 * mm]
scale = (W - 8 * mm) / sum(widths)
widths = [w * scale for w in widths]
bd = Table([[Paragraph(c[0], STYLES["byteidx"]) for c in cells],
[Paragraph(c[1], STYLES["bytename"]) for c in cells]], colWidths=widths)
bd.setStyle(TableStyle([
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
("TOPPADDING", (0, 0), (-1, 0), 1.2 * mm),
("BOTTOMPADDING", (0, 0), (-1, 0), 0.8 * mm),
("TOPPADDING", (0, 1), (-1, 1), 0.8 * mm),
("BOTTOMPADDING", (0, 1), (-1, 1), 1.6 * mm),
("LEFTPADDING", (0, 0), (-1, -1), 1.6 * mm),
("RIGHTPADDING", (0, 0), (-1, -1), 1.6 * mm),
("BACKGROUND", (0, 1), (0, 1), colors.HexColor("#5F5E5A")),
("BACKGROUND", (1, 1), (3, 1), colors.HexColor("#185FA5")),
("BACKGROUND", (4, 1), (4, 1), colors.HexColor("#993C1D")),
("BOX", (0, 1), (0, 1), 0.6, colors.white),
("BOX", (1, 1), (3, 1), 0.6, colors.white),
("BOX", (4, 1), (4, 1), 0.6, colors.white),
]))
add(KeepTogether([bd, Spacer(1, 3),
Paragraph("图 1 帧字节布局(灰色 = 帧头,蓝色 = 速度数据区,橙色 = 校验)",
STYLES["footnote"])]))
# ------------------------------------------------------------ 4
h1("4. 字段语义与数值换算")
para("三个字段都是 int16(-32768 ~ 32767),单位分别为 mm/s、mm/s、mrad/s,即「米每秒 × 1000」"
"和「弧度每秒 × 1000」,全部靠 1000 这一个比例常数换算,下位机侧反算则是除以 1000。"
"符号约定与 geometry_msgs/Twist 一致。")
add(data_table([
["字段", "上位机换算(→ 下发值)", "下位机反算", "实际上限", "int16 满量程"],
["vx", "mm/s = round(vx_m_s × 1000)", "vx_m_s = vx / 1000.0", "±2500", "±32767"],
["vy", "mm/s = round(vy_m_s × 1000)", "vy_m_s = vy / 1000.0", "±2500", "±32767"],
["omega", "mrad/s = round(wz_rad_s × 1000)", "wz_rad_s = omega / 1000.0", "±1500", "±32767"],
], [13 * mm, 66 * mm, 52 * mm, 18 * mm, 27 * mm], code_cols=(1, 2), align_center=(3, 4)))
add(Spacer(1, 3))
add(Paragraph("实际上限指上位机下发前的限幅:vx/vy 为 ±2500(±2.5 m/s),omega 为 ±1500(±1.5 rad/s),"
"下位机收到的数值不会超出该范围;仍建议下位机做一次范围钳制作为防御性处理。",
STYLES["footnote"]))
# ------------------------------------------------------------ 5
h1("5. CRC16-MODBUS 校验")
para("校验算法为标准 CRC16-MODBUS:多项式 0x8005(反射形式 0xA001),初值 0xFFFF,"
"输入输出都不做取反,也没有最终异或。计算范围是 <b>byte0 ~ byte7</b>(帧头 + 数据),"
"算出的 16 位结果以小端写入 byte8、byte9(低字节在前)。")
h2("5.1 接收端校验要点")
bullets([
"先按小端把 byte8、byte9 拼成期望值:<font face='%s'>expect = byte8 | (byte9 &lt;&lt; 8)</font>" % MONO,
"再对前 8 字节算 CRC,与 expect 比较,不相等即丢帧",
"多项式、初值、位序三者任一不同都会和上位机对不上,请直接使用下面的参考实现",
])
add(KeepTogether([
Paragraph("5.2 C 参考实现(可直接抄进 STM32)", STYLES["h2"]),
code_block(
"/* CRC16-MODBUS: poly=0xA001, init=0xFFFF, no reflect in/out, no final xor */\n"
"uint16_t crc16_modbus(const uint8_t *buf, uint16_t len)\n"
"{\n"
" uint16_t crc = 0xFFFF;\n"
" for (uint16_t i = 0; i < len; i++) {\n"
" crc ^= (uint16_t)buf[i];\n"
" for (int b = 0; b < 8; b++) {\n"
" if (crc & 0x0001) crc = (crc >> 1) ^ 0xA001;\n"
" else crc = (crc >> 1);\n"
" crc &= 0xFFFF;\n"
" }\n"
" }\n"
" return crc;\n"
"}\n"
"\n"
"/* usage: after a full 10-byte frame f[] has arrived */\n"
"uint16_t expect = (uint16_t)f[8] | ((uint16_t)f[9] << 8);\n"
"if (crc16_modbus(f, 8) != expect) { /* drop this frame */ }",
W)]))
# ------------------------------------------------------------ 6
h1("6. 接收端实现建议")
add(note(
"<b>关键坑:帧头不可作为切帧依据。</b>数据区里的 vx / vy / omega 是任意 int16,"
"完全可能等于 0x55AA 或 0xAA55,从而在字节流里造出一个假的 <font face='%s'>AA 55</font>。"
"正确做法是固定 10 字节切帧 + CRC 判定:只有 10 字节对齐且 CRC 通过的帧才采信。"
"若 CRC 失败,不要整帧丢弃后从下一帧开始,而应逐个字节滑动重同步(丢 1 字节再试),"
"这样偶发干扰后最多丢一帧就能重新对齐。" % MONO, W))
h2("6.1 推荐收帧流程")
bullets([
"串口用 DMA + 空闲中断(IDLE)收数据,或中断驱动填环形缓冲,按 10 字节一帧取出;",
"检查字节 0、1 是否为 0xAA 0x55。不是则丢弃 1 字节,回到上一步;",
"对前 8 字节算 CRC16,与 byte8 / byte9(小端拼接)比对。失败则丢弃 1 字节并重新对齐;",
"校验通过:按小端解析 vx、vy、omega,并刷新「最后一次有效帧到达时间」;",
"把三个值写入电机控制环节(可按需再做死区与斜率限制);",
"另设一个定时器:若距上次有效帧超过 300 ~ 500 ms,则强制 vx = vy = omega = 0 并置故障标志。",
], numbered=True)
add(Spacer(1, 4))
add(KeepTogether([code_block(
"/* 10-byte fixed frame + CRC resync */\n"
"static uint8_t buf[10];\n"
"static uint16_t len = 0;\n"
"static uint32_t last_ok_ms = 0;\n"
"\n"
"void on_rx_byte(uint8_t b)\n"
"{\n"
" buf[len++] = b;\n"
" if (len < 10) return;\n"
"\n"
" if (buf[0] == 0xAA && buf[1] == 0x55\n"
" && crc16_modbus(buf, 8) == ((uint16_t)buf[8] | ((uint16_t)buf[9] << 8))) {\n"
" int16_t vx = (int16_t)((uint16_t)buf[2] | ((uint16_t)buf[3] << 8));\n"
" int16_t vy = (int16_t)((uint16_t)buf[4] | ((uint16_t)buf[5] << 8));\n"
" int16_t omega = (int16_t)((uint16_t)buf[6] | ((uint16_t)buf[7] << 8));\n"
" apply_velocity(vx, vy, omega); /* units: mm/s, mm/s, mrad/s */\n"
" last_ok_ms = now_ms();\n"
" len = 0; /* whole frame consumed */\n"
" } else {\n"
" memmove(buf, buf + 1, 9); /* shift by 1 byte and retry */\n"
" len = 9;\n"
" }\n"
"}\n"
"\n"
"/* watchdog: call from a 100 Hz ~ 1 kHz task */\n"
"void safety_tick(void)\n"
"{\n"
" if (now_ms() - last_ok_ms > 400) apply_velocity(0, 0, 0);\n"
"}",
W)]))
h2("6.2 超时停车约定")
para("上位机的行为:只要 200 ms 内没有收到新的 /cmd_vel,它就持续发送全零帧(vx = vy = omega = 0),"
"而不是停发。也就是说链路正常运行时下位机一定会持续收到帧——<b>「收不到帧」本身就意味着异常</b>"
"(上位机崩溃、串口断开、线缆松动)。所以下位机必须自带超时停车,不能只依赖上位机发零帧。")
para("上位机零速帧的固定字节为 <font face='%s'>%s</font>,可用它作为「停车帧」的识别基准。"
% (MONO, P.frame_to_hex(P.pack_velocity_frame(0, 0, 0))))
# ------------------------------------------------------------ 7
add(PageBreak())
h1("7. 示例帧(可直接作单元测试向量)")
para("下表全部由上位机代码 <font face='%s'>protocol.py</font> 现算生成,与实际下发的字节完全一致。"
"建议下位机把这些帧灌进解析函数做回归测试。" % MONO)
rows = [["场景", "vx (m/s)", "vy (m/s)", "omega (rad/s)", "payload byte2~byte7", "完整 10 字节帧"]]
for name, vx, vy, wz, raw in frames():
rows.append([name, "%+.2f" % vx, "%+.2f" % vy, "%+.3f" % wz,
P.frame_to_hex(raw[2:8]), P.frame_to_hex(raw)])
add(data_table(rows, [31 * mm, 15 * mm, 15 * mm, 20 * mm, 40 * mm, W - 121 * mm],
code_cols=(1, 2, 3, 4, 5), align_center=(1, 2, 3)))
add(Spacer(1, 7))
h2("7.1 逐字节解释示例:前进 0.25 m/s")
raw = P.pack_velocity_frame(0.25 * P.VX_SCALE, 0, 0)
bytes_hex = ["%02X" % b for b in raw]
meaning = [
"帧头高字节,固定 0xAA",
"帧头低字节,固定 0x55",
"vx 低字节:250 mm/s = 0x00FA",
"vx 高字节",
"vy 低字节:0 mm/s",
"vy 高字节",
"omega 低字节:0 mrad/s",
"omega 高字节",
"CRC16 低字节",
"CRC16 高字节",
]
rows = [["字节位置", "值", "含义"]] + [["byte %d" % i, bytes_hex[i], meaning[i]] for i in range(10)]
add(data_table(rows, [24 * mm, 16 * mm, W - 40 * mm], code_cols=(1,), align_center=(1,)))
add(Spacer(1, 3))
add(Paragraph("整帧:<font face='%s'>%s</font>;CRC16-MODBUS 计算结果为 "
"<font face='%s'>0x%04X</font>(小端写入即 %s %s)。"
% (MONO, P.frame_to_hex(raw), MONO,
P.crc16_modbus(bytes(b"\xAA\x55" + raw[2:8])), bytes_hex[8], bytes_hex[9]),
STYLES["footnote"]))
# ------------------------------------------------------------ 8
h1("8. 上位机侧行为(对接需知)")
add(data_table([
["参数(ROS 2 参数名)", "默认值", "对下位机的影响"],
["velocity_rate_hz", "30.0", "发包频率,决定下位机收到帧的节奏"],
["cmd_vel_timeout_sec", "0.2", "超过该时长无新指令即发零速帧"],
["send_zero_on_timeout", "true", "置 false 则超时后直接停发(此时下位机的超时兜底更关键)"],
["max_vx_m_s / max_vy_m_s", "2.5 / 2.5", "下发前的限幅,vx / vy 不会超过 ±2500"],
["max_wz_rad_s", "1.5", "下发前的角速度限幅,omega 不会超过 ±1500"],
["baudrate", "115200", "必须与下位机一致"],
["port", "/dev/...", "上位机侧串口设备名(默认 /dev/r2_chassis),与下位机无关"],
], [46 * mm, 26 * mm, W - 72 * mm], code_cols=(0,), align_center=(1,)))
h2("8.1 上电与重启行为")
bullets([
"上位机节点启动后立刻按帧率发帧,在收到第一条 /cmd_vel 之前发的都是零速帧;",
"没有任何握手、心跳或使能流程。下位机随时上电都能从下一帧开始正常接收;",
"下位机重启不需要通知上位机,只要按 10 字节切帧即可重新同步;",
"上位机不会因为下位机不回包而报错——它根本不读串口。",
])
# ------------------------------------------------------------ 9
h1("9. 下位机自检清单")
add(data_table([
["#", "检查项", "通过标准"],
["1", "串口参数", "115200 8N1,无流控"],
["2", "收帧切分", "以 10 字节为单位处理,不用搜帧头切帧"],
["3", "CRC 实现", "对 byte0~7 算 0xA001 / 0xFFFF,结果与 byte8、byte9(小端)一致"],
["4", "字节序", "vx / vy / omega 按小端拼 int16,负数能正确解析(如 0xFF9C = -100)"],
["5", "重同步", "灌入含假帧头或坏 CRC 的脏字节流后,能在 1 ~ 2 帧内恢复对齐"],
["6", "超时停车", "停发数据 300 ~ 500 ms 后电机速度归零并置标志"],
["7", "示例帧回归", "第 7 节所有示例帧的解析结果与表中数值一致"],
["8", "零速帧", "收到全零帧后电机确实停止(而不是仅写入变量)"],
], [9 * mm, 30 * mm, W - 39 * mm], align_center=(0,)))
add(Spacer(1, 6))
add(note("负数字节序自检用例:int16 -100 = 0xFF9C,小端下发为 <font face='%s'>9C FF</font>"
"(低字节 9C 在前,高字节 FF 在后)。若解析出 +155 之类的怪值,"
"说明字节序或符号扩展写错了。" % MONO, W, kind="ok"))
# ------------------------------------------------------------ 附录
add(PageBreak())
h1("附录 A 上位机发送侧实现(Python,节选自 protocol.py)")
add(code_block(
"FRAME_LEN = 10\n"
"HEADER = b\"\\xAA\\x55\"\n"
"VX_SCALE = VY_SCALE = OMEGA_SCALE = 1000.0 # m/s->mm/s, rad/s->mrad/s\n"
"\n"
"def pack_velocity_frame(vx_mm_s, vy_mm_s, omega_mrad_s):\n"
" payload = bytearray(HEADER)\n"
" payload.extend(struct.pack(\"<h\", clamp_i16(vx_mm_s)))\n"
" payload.extend(struct.pack(\"<h\", clamp_i16(vy_mm_s)))\n"
" payload.extend(struct.pack(\"<h\", clamp_i16(omega_mrad_s)))\n"
" payload.extend(struct.pack(\"<H\", crc16_modbus(bytes(payload))))\n"
" return bytes(payload) # always exactly 10 bytes\n"
"\n"
"# node side, inside a 30 Hz timer:\n"
"# frame = pack_velocity_frame(vx*1000, vy*1000, wz*1000)\n"
"# serial.write(frame); serial.flush() # write only, never read",
W))
add(Spacer(1, 4))
h1("附录 B Python 侧解析参考(可当对照实现)")
add(code_block(
"def parse_velocity_frame(raw: bytes):\n"
" assert len(raw) == 10 and raw[0:2] == b\"\\xAA\\x55\"\n"
" expect = raw[8] | (raw[9] << 8)\n"
" assert crc16_modbus(raw[:8]) == expect, \"crc mismatch\"\n"
" vx, vy, omega = struct.unpack_from(\"<hhh\", raw, 2)\n"
" return vx / 1000.0, vy / 1000.0, omega / 1000.0 # m/s, m/s, rad/s",
W))
add(Spacer(1, 6))
add(HRFlowable(width="100%", thickness=0.6, color=RULE, spaceAfter=6))
add(Paragraph("文档由 <font face='%s'>docs/build_protocol_pdf.py</font> 自动生成;协议若有改动,"
"重新运行该脚本即可得到与新版固件一致的新版 PDF。协议权威定义见 "
"<font face='%s'>techx_r2_chassis_control/protocol.py</font> 文件头注释。"
% (MONO, MONO), STYLES["footnote"]))
doc.build(F)
print("written:", OUT_PDF, os.path.getsize(OUT_PDF), "bytes")
if __name__ == "__main__":
main()
@@ -0,0 +1,242 @@
# R2 底盘协议 · 上位机侧核查与自检手册
- 日期:2026-10-03
- 范围:**仅 `src/techx_r2_chassis_control`(ROS 2 上位机包)**,不涉及下位机固件
- 权威实现:`techx_r2_chassis_control/protocol.py`
- 接口契约文档:`docs/R2底盘串口协议_v2.pdf`
---
## 0. 一句话
上位机这一侧**实现是正确的**:帧格式、CRC、字节序、量纲都已用交叉验证跑通(§7 验证记录)。
真正需要你「掌握」的不是写它,而是**能回答下面 6 个问题**——它们全都指向「协议契约」和「失效路径」,而这两样代码里没有。
---
## Q1 · 为什么是小端 `<h` 而不是大端?
**答案**:小端是协议规定,上位机用 `struct.pack("<h", ...)` 直接实现(`protocol.py:77`)。
```python
def i16_to_le(value: int) -> bytes:
return struct.pack("<h", clamp_i16(value))
```
**看懂它的方法**:用一个**负数**做验证,正数看不出字节序。
```python
import struct
struct.pack("<h", -100) # b'\x9c\xff' ← 小端:低字节在前
struct.unpack("<h", b"\x9c\xff")[0] # -100
struct.pack(">h", -100) # b'\xff\x9c' ← 大端:高字节在前
```
`-0.1 m/s` × 1000 = `-100 mm/s` = `0xFF9C`,小端上线就是 `9C FF`。
上位机产出 `AA 55 9C FF 00 ...`(见 §7)。**记住这个 `9C FF`——它是判断字节序写错的最快特征。**
**为什么这件事必须你来定**:字节序是两边各自手工拼装的约定,不是代码内部的自洽性。编译器不会帮你检查,测试也不会自动发现——只有协议文档能定它。
---
## Q2 · CRC 覆盖哪几个字节?校验失败时谁负责?
### CRC 参数(`protocol.py:58-69`)
| 参数 | 值 |
|---|---|
| 多项式 | `0xA001`(MODBUS 反射形式) |
| 初值 | `0xFFFF` |
| 输入/输出位反转 | 无 |
| 最终异或 | 无 |
| **覆盖范围** | **`byte0..byte7`(帧头 + 三个 int16),不含 CRC 自身** |
| CRC 字段摆放 | `byte8` 低字节、`byte9` 高字节 |
代码里的实现与文档一致:
```python
payload.extend(struct.pack("<H", crc16_modbus(bytes(payload)))) # 此时 payload 恰好 8 字节
```
**判据**:`crc16_modbus()` 的入参长度决定了覆盖范围。**看这类实现时,永远先数一下「喂进去几个字节」。** 覆盖范围差一个字节,CRC 全错但代码照样能跑。
### 「校验失败怎么办」——上位机答不了,必须写进文档
这是本题真正的重点:
- 上位机**是单向发送的,从不读回**(`protocol.py:11-12` 写得很明确),所以它**永远不知道** CRC 有没有通过。
- 因此「CRC 失败时下位机的行为」**不是代码问题,是契约问题**:必须在 `R2底盘串口协议_v2.pdf` 里写成强制条款(例如「丢弃该帧」还是「归零停车」),由下位机实现,并在验收时逐条核对。
- 上位机侧唯一相关的动作是**保证 CRC 正确**——这一点已通过 §7 的交叉验证确认。
**顺带一个上位机侧的死参数**:`chassis_serial_node.py:32` 声明了 `serial_timeout_sec: 0.02` 并传给 `serial.Serial(...)`,但节点**从不调用 `read()`**。这个参数对节点行为零影响。
它无害,但暴露了一个模式:**参数名被配齐了,却没有逐个确认「有没有用」**。审这类包时,把每个 `declare_parameter` 都追一遍消费者,是最快的体检手段。
---
## Q3 · 30 Hz 发帧率、`cmd_vel_timeout_sec 0.2`、下位机超时 —— 谁兜底?
三层的时间量级设计得是对的(`200 ms = 6 帧 @ 30 Hz`,留了 6 帧余量):
| 层 | 触发条件 | 动作 | 上位机侧能否验证 |
|---|---|---|---|
| 上位机 | `/cmd_vel` 200 ms 未更新 | 发送**零速帧**(`chassis_serial_node.py:83-94`) | ✅ 可直接看日志验证 |
| 协议契约 | 下位机 200 ms 无**合法帧** | 三轴强制清零 | ❌ 上位机收不到任何反馈,只能靠下位机自检 |
| 硬件 | 固件失控 | 看门狗复位 | ❌ 与上位机无关 |
**关键结论(上位机视角)**:
- 上位机的超时兜底**只在「链路还活着、但没人在发 `/cmd_vel`」时有效**。
- **如果串口本身断了**(拔线、USB 掉设备、下位机复位),上位机的 `write()` 可能仍然成功返回(写进内核缓冲区而已),但**下位机永远收不到那个零速帧**。上位机**没有任何手段感知这一点**。
- 所以「失联后必须自己停下来」这条责任**只能在协议文档里强制下位机承担**。这是当前架构下唯一可行的安全边界,也是你写协议文档时最该加粗的一句话。
**看懂它的方法**:把超时分层列出来,逐层问两个问题——
1. 这一层的判据是什么时钟、什么阈值?
2. **这一层失效时,谁接住?**
第 2 问通常会发现链条上有洞。
---
## Q4 · 粘包 / 半包时 `AA 55` 怎么重新对齐?
**上位机侧的答案很干净:这件事不在上位机的责任范围内。**
理由:上位机是**唯一写者**,且每次 `write()` 都恰好写完整 10 字节(`chassis_serial_node.py:96-99`):
```python
frame = pack_velocity_frame(vx * VX_SCALE, vy * VY_SCALE, wz * OMEGA_SCALE)
with self._write_lock:
self._serial.write(frame)
self._serial.flush()
```
`FRAME_LEN = 10` 定长、单次 write、有 `_write_lock` 串行化 ⇒ **上位机不可能产生粘包或半包**。
**但有两个前提,它们才是上位机该守的**:
1. **这条串口不能有第二个写者。**
只要有人往同一个 `/dev/r2_chassis` 混写别的内容(调试输出、另一个节点、`ros2 topic pub` 之外的临时脚本),线上就会出现非 10 字节片段,此后所有帧永久错位。
→ 建议:把「同一串口禁止其他写者」写进包文档,并在部署时确认没有第二个进程持有该设备。
2. **`write()` 返回成功 ≠ 数据发出去了。**
`pyserial` 的 `write()` 成功只代表写进了内核 TTY 缓冲区。真正的失败(下位机没上电、线松了)**上位机看不到**。
→ 可选的加固:检查 `write()` 返回值是否等于 10(当前代码**没有检查**)。
**「滑 1 字节重同步」是谁的活**:是**下位机**的。因为它收到的字节流可能因为 DMA/中断丢字节而错位。上位机无法也不需要处理对齐——它只保证「自己发出去的永远是完整帧」。
**看懂它的方法**:判断「切帧责任」归属,看**谁是接收方**。接收方负责重同步;发送方只负责帧完整性。这条分工写进协议文档,能省掉后面大量扯皮。
---
## Q5 · `int16 mm/s` 的量化会不会造成抖动?
**上位机侧可以给出确定的答案:量化台阶是 1 mm/s,而且不存在溢出风险。**
1. **台阶**:`VX_SCALE = 1000`、`int16` ⇒ 1 LSB = **1 mm/s = 0.001 m/s**(`protocol.py:28-30`)。
2. **不会溢出**(这是上位机侧可以证明的):`int16` 满量程 ±32767 mm/s = ±32.767 m/s,而上下位机双重限幅在 ±2.5 m/s ⇒ **只用了满量程的 7.6%**。即使去掉所有限幅,`int16` 溢出需要 >32 m/s 的输入,物理上不可能。
3. **限幅后不回写**(`chassis_serial_node.py:72-81`):
```python
def _on_cmd_vel(self, msg: Twist) -> None:
self._latest_vx_m_s = self._clamp(msg.linear.x, ...) # 只存内部变量
```
`msg` 本身没被修改,也没有任何反馈话题。**下游节点不知道指令被截断了**——`/cmd_vel` 上写着 3.0 m/s,实际发出去的是 2.5 m/s,`ros2 topic echo /cmd_vel` 看不出来。
→ 排查「车走不到预期速度」时,这是一个会骗人的地方。诊断方法:把 `log_velocity_frames` 打开,对比日志里的 `TX vx=...` 与 `/cmd_vel` 的原值。
**结论**:`int16` 的 1 mm/s 台阶**不是抖动的可能原因**。真正需要你判断的是:
- **下游(下位机舵轮解算)的死区有多大?** 如果它的死区折算成线速度比 1 mm/s 粗(这类代码的死区常设 0.1 rad/s 量级),那么**主导精度的是那个死区,不是协议量化**。
- **节拍是否对齐?** 上位机 30 Hz 定频发送,下位机以什么频率消费?两个不同频率之间如果没有缓冲,会造成速度指令被随机取样,**这才是低速顿挫的典型成因**,而且它属于**契约层**——需要在协议文档里规定下位机的消费节拍(或规定「每当收到合法帧立即更新目标值」)。
量化、死区、采样节拍,这三者的关系是排查慢速抖动的固定顺序:**先比粗细,再比频率。**
---
## Q6 · 架空状态下怎么证明「下位机收到的是同一条帧」?
上位机侧现有条件:**串口单向,无 ACK,没有回读**。`test_cmd_vel_pub.py` 只发 `/cmd_vel`,不验证任何东西。
分三步补,从便宜到贵:
### 第 1 步(现在就能做,不需要硬件)——固化自检向量
把 §7 的 5 条帧交给下位机做单元测试。**这是唯一能跨过「上位机怎么打包」与「下位机怎么解包」边界、且不需要任何硬件的验证手段。**
| 输入 (m/s, m/s, rad/s) | 线上 10 字节 | 期望解出 |
|---|---|---|
| `(+0.000, +0.000, +0.000)` | `AA 55 00 00 00 00 00 00 CF 09` | `(0, 0, 0)` |
| `(+0.100, +0.000, +0.000)` | `AA 55 64 00 00 00 00 00 C7 2D` | `(+0.1, 0, 0)` |
| `(-0.100, +0.000, +0.000)` | `AA 55 9C FF 00 00 00 00 C6 81` | `(-0.1, 0, 0)` |
| `(+0.000, +0.100, +0.000)` | `AA 55 00 00 64 00 00 00 D0 39` | `(0, +0.1, 0)` |
| `(+0.000, +0.000, +0.100)` | `AA 55 00 00 00 00 64 00 E5 C9` | `(0, 0, +0.1)` |
> 价值:**任一侧改代码,跑这张表就知道有没有破协议。** 它把「口头约定」变成了「可执行断言」。建议直接放进协议文档附录。
### 第 2 步(架空抬轮)——上位机侧发送留痕
给 `chassis_serial_node` 加一个**只读**诊断:把每帧的 `frame_to_hex()` 和时间戳记进环形缓冲,发布到 `~/tx_trace`(`std_msgs/String`),默认关闭。
- 纯观测,不改发送逻辑、不改安全默认值。
- 用 `ros2 topic echo` 就能逐帧核对「打算发什么」和「实际写了什么字节」。
- 注意这只能证明**上位机发出了什么**,证明不了下位机收到了。
### 第 3 步(唯一能证明「下位机真的执行了」的办法)——要求下位机回读
请下位机增加一条**上行帧**(建议用 `55 AA` 起头,与下行 `AA 55` 对称,避免误判),内容为「当前执行的 vx/vy/ω + 本地时间戳」,10 Hz 即可。上位机订阅后与已发送命令做时间对齐比对。
- 这一步会把「单向无回读」的架构改掉,属于**架构决策,需要你拍板**,不是改个参数。
- 收益:直接得到「指令延迟」「CRC 失败率」「失联次数」三个可量化验收指标,也是 §Q3 那条安全边界唯一的验证方式。
---
## 附 A · 上位机包体检清单(本包实测)
| # | 位置 | 现象 | 性质 |
|---|---|---|---|
| 1 | `chassis_serial_node.py:32` | `serial_timeout_sec: 0.02` 声明并传给了 `serial.Serial`,但节点从不 `read()` ⇒ **零影响的死参数** | 无害,但说明参数未逐个确认 |
| 2 | `config/chassis_serial.yaml:12` | `log_velocity_frames: true` ⇒ 30 Hz 每帧打一行 hex 日志。**默认值是否合适要人工判断** | 需决策 |
| 3 | `chassis_serial_node.py:62` | `1.0 / max(1.0, rate_hz)` ⇒ `velocity_rate_hz` 传 0 时**静默降级成 1 Hz**,不报错也不告警 | 静默降级 |
| 4 | `chassis_serial_node.py:57,85` | `_last_cmd_time = 0.0` 初值 ⇒ 启动瞬间即判 stale。配 `send_zero_on_timeout: true` 时会先发零速帧(正确);若设为 `false`,节点启动后**完全不发帧**,下位机必须自己有兜底 | 跨设备安全边界 |
| 5 | `chassis_serial_node.py:72-81` | 限幅结果不回写 `msg`、无反馈话题 ⇒ 下游无法感知截断 | 可观测性缺口 |
| 6 | `yaml:3` vs `launch/chassis_serial.launch.py:14,24` | yaml 写 `port: /dev/ttyUSB0`,launch 的 `port_arg` 默认 `/dev/r2_chassis` 且作为**后置参数覆盖** ⇒ **yaml 里的 port 永远不生效**。两处必须统一 | **真实缺陷** |
| 7 | `chassis_serial_node.py:98` | `self._serial.write(frame)` 未检查返回值是否 == `FRAME_LEN` | 建议加固 |
| 8 | `chassis_serial_node.py:76` | 用 `time.monotonic()` 计时(正确做法);注意不要改成 `time.time()`——墙钟会因 NTP 跳变导致误判 | 已正确 |
**第 6 条是这里唯一需要改代码的**:`launch` 里的 `port` 覆盖会让 yaml 配置失效。两种修法(需你确认):
- 删掉 `launch` 的 `port_arg` 默认覆盖,只保留 `DeclareLaunchArgument('port', default_value='')` 并在为空时不传该参数;
- 或把 yaml 与 launch 的默认值统一为同一个设备路径(并配 udev 规则固定设备名)。
---
## 附 B · 自己验证协议一致性的方法(不需要硬件)
不要「读一遍觉得对」就结束。用**独立实现 + 随机交叉验证**:
1. 按 `docs/R2底盘串口协议_v2.pdf` 的文字描述,**不看 `protocol.py`**,另外写一份最小实现;
2. 用 5000 组随机 8 字节 payload 对比两份实现的 `crc16_modbus()`;
3. 用 3000 组随机 `(vx, vy, ω)`(含超限值)跑「打包 → 解包」闭环,比对是否等于「限幅+四舍五入」后的期望值。
本次核查按此方法执行,结果见 §7。
---
## 7. 验证记录(2026-10-03 实测)
| 项目 | 方法 | 结果 |
|---|---|---|
| CRC16-MODBUS 一致性 | 5000 组随机 8 字节 payload,对照独立实现 | **不一致 0 组** |
| 端到端 pack → parse 闭环 | 3000 组随机 `(vx, vy, ω)`(含 ±3.5 / ±2.0 超限) | **失败 0 组** |
| 负值字节序 | `-0.1 m/s` → 是否产出 `9C FF` | **通过** |
| 双重限幅一致性 | 上位机 ±2.5 / ±2.5 / ±1.5 与协议文档一致 | **通过** |
| 溢出风险 | `int16` 满量程 ±32.767 m/s vs 限幅 ±2.5 m/s | **不可能溢出** |
**可直接粘贴的断言**:
```python
from techx_r2_chassis_control.protocol import pack_velocity_frame, frame_to_hex
assert frame_to_hex(pack_velocity_frame(0, 0, 0)) == "AA 55 00 00 00 00 00 00 CF 09"
assert frame_to_hex(pack_velocity_frame(100, 0, 0)) == "AA 55 64 00 00 00 00 00 C7 2D"
assert frame_to_hex(pack_velocity_frame(-100, 0, 0)) == "AA 55 9C FF 00 00 00 00 C6 81"
assert frame_to_hex(pack_velocity_frame(0, 100, 0)) == "AA 55 00 00 64 00 00 00 D0 39"
assert frame_to_hex(pack_velocity_frame(0, 0, 100)) == "AA 55 00 00 00 00 64 00 E5 C9"
```
@@ -0,0 +1,93 @@
"""启动 R2 底盘串口桥(/cmd_vel -> STM32 速度帧)。
本节点所有可调项的唯一真源是 config/chassis_serial.yaml。这里额外把 port 暴露成 launch
参数,因为台架调试时常需要临时换个设备;它的默认值**从 yaml 反读**,两者因此不可能不一致。
重要 —— 为什么过去改 yaml 对 port 完全无效:
ROS 2 里 parameters 是一个**列表**,按顺序应用、**后者胜**。本文件旧版写的是::
parameters=[LaunchConfiguration('config'), {'port': LaunchConfiguration('port')}]
而 port 的 launch 默认值被硬编码成 /dev/r2_chassis。于是第二段字典永远压过参数文件,
config/chassis_serial.yaml 里写的 port 变成死信 —— 无论怎么改 yaml 都改不动它。
这与 sru_nav_ros2/launch/sru_nav.launch.py 中记录的失败模式同源(当年
odom_twist_in_base_frame 一直是 false,而 yaml 写的是 true),修法也相同:默认值从文件读。
关于 install 拷贝:setup.py 是用**拷贝**方式安装 config/*.yaml 的,所以
install/.../share/techx_r2_chassis_control/config/ 下是另一个文件;改 src/ 里的 yaml
必须重新编译才生效。用 params_file:= 直接指向源码树可以免重建(该参数就是为此存在),
长期方案是 colcon build --symlink-install。
典型用法::
ros2 launch techx_r2_chassis_control chassis_serial.launch.py
# 台架测试临时换设备
ros2 launch techx_r2_chassis_control chassis_serial.launch.py port:=/dev/ttyUSB0
# 改完即用,不必重新编译
ros2 launch techx_r2_chassis_control chassis_serial.launch.py \\
params_file:=$HOME/sru_ws/src/techx_r2_chassis_control/config/chassis_serial.yaml
警告 —— 节点在构造函数里就打开串口,且下位机没有独立的失联兜底:
任何能触达 /cmd_vel 的测试都必须先让轮子离地。
"""
import os
import yaml
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
def _yaml_default(params_file, name, fallback):
"""读取参数文件里 name 的写法值。
有意**不做** .lower()。sru_nav_ros2/launch/sru_nav.launch.py 里的同名助手末尾带
.lower(),那是为读布尔值写的;照抄到这里会把设备路径 /dev/ttyUSB0 变成 /dev/ttyusb0。
文件读不出来时回落到 fallback,这样 yaml 坏了也仍能启动,让节点自己报更清楚的错,
而不是死在 launch 系统里。
"""
try:
with open(params_file, 'r') as f:
params = yaml.safe_load(f)['chassis_serial_node']['ros__parameters']
return str(params[name])
except Exception:
return fallback
def generate_launch_description():
pkg_share = get_package_share_directory('techx_r2_chassis_control')
default_params_file = os.path.join(pkg_share, 'config', 'chassis_serial.yaml')
declared_arguments = [
DeclareLaunchArgument(
'params_file', default_value=default_params_file,
description='节点参数文件(默认取包 share 目录下的 config/chassis_serial.yaml)。'
'安装出来的是拷贝而非符号链接 —— 把它指向 src/ 下那份即可改完即用、'
'无需重新编译。'),
DeclareLaunchArgument(
'port', default_value=_yaml_default(default_params_file, 'port', '/dev/ttyUSB0'),
description='串口设备。默认值从 config/chassis_serial.yaml 反读,该文件即唯一真源;'
'临时覆盖一次用 port:=...。'),
]
chassis_node = Node(
package='techx_r2_chassis_control',
executable='chassis_serial_node',
name='chassis_serial_node',
output='screen',
# 顺序有意义:第 0 项是参数文件,第 1 项是命令行覆盖。后者胜 —— 这是故意的
# (port:=... 就靠它生效),而它之所以安全,只因为上面 port 的默认值正是从
# 同一个文件读出来的。
parameters=[
LaunchConfiguration('params_file'),
{'port': LaunchConfiguration('port')},
],
)
return LaunchDescription(declared_arguments + [chassis_node])
@@ -0,0 +1,19 @@
<?xml version="1.0"?>
<package format="3">
<name>techx_r2_chassis_control</name>
<version>0.2.0</version>
<description>Python serial bridge: /cmd_vel -> R2 chassis STM32 velocity frames.</description>
<maintainer email="[email protected]">techx</maintainer>
<license>MIT</license>
<buildtool_depend>ament_python</buildtool_depend>
<exec_depend>rclpy</exec_depend>
<exec_depend>geometry_msgs</exec_depend>
<test_depend>ament_lint_auto</test_depend>
<test_depend>ament_lint_common</test_depend>
<export>
<build_type>ament_python</build_type>
</export>
</package>
@@ -0,0 +1,4 @@
[develop]
script_dir=$base/lib/techx_r2_chassis_control
[install]
install_scripts=$base/lib/techx_r2_chassis_control
@@ -0,0 +1,30 @@
from setuptools import setup
from glob import glob
import os
package_name = 'techx_r2_chassis_control'
setup(
name=package_name,
version='0.2.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages', ['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
(os.path.join('share', package_name, 'launch'), glob('launch/*.launch.py')),
(os.path.join('share', package_name, 'config'), glob('config/*.yaml')),
],
install_requires=['setuptools', 'pyserial'],
zip_safe=True,
maintainer='techx',
maintainer_email='[email protected]',
description='Python serial bridge: /cmd_vel -> R2 chassis STM32 velocity frames.',
license='MIT',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'chassis_serial_node = techx_r2_chassis_control.chassis_serial_node:main',
'test_cmd_vel_pub = techx_r2_chassis_control.test_cmd_vel_pub:main',
],
},
)
@@ -0,0 +1,121 @@
from __future__ import annotations
import threading
import time
import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist
try:
import serial
except ImportError as exc: # pragma: no cover - runtime dependency on robot
serial = None
from .protocol import (
OMEGA_SCALE,
VX_SCALE,
VY_SCALE,
frame_to_hex,
pack_velocity_frame,
)
class ChassisSerialNode(Node):
"""Bridge /cmd_vel -> STM32 serial velocity frames."""
def __init__(self) -> None:
super().__init__("chassis_serial_node")
self.declare_parameter("port", "/dev/ttyUSB0")
self.declare_parameter("baudrate", 115200)
self.declare_parameter("serial_timeout_sec", 0.02)
self.declare_parameter("velocity_rate_hz", 30.0)
self.declare_parameter("cmd_vel_timeout_sec", 0.2)
self.declare_parameter("send_zero_on_timeout", True)
self.declare_parameter("max_vx_m_s", 2.5)
self.declare_parameter("max_vy_m_s", 2.5)
self.declare_parameter("max_wz_rad_s", 1.5)
self.declare_parameter("log_velocity_frames", False)
if serial is None:
raise RuntimeError("pyserial is not installed. Install with: sudo apt install python3-serial")
self._port = self.get_parameter("port").value
self._baudrate = int(self.get_parameter("baudrate").value)
self._serial = serial.Serial(
self._port,
self._baudrate,
timeout=float(self.get_parameter("serial_timeout_sec").value),
)
self.get_logger().info(f"Opened chassis serial port {self._port} @ {self._baudrate}")
self._write_lock = threading.Lock()
self._latest_vx_m_s = 0.0
self._latest_vy_m_s = 0.0
self._latest_wz_rad_s = 0.0
self._last_cmd_time = 0.0
self.create_subscription(Twist, "/cmd_vel", self._on_cmd_vel, 10)
rate_hz = float(self.get_parameter("velocity_rate_hz").value)
self.create_timer(1.0 / max(1.0, rate_hz), self._velocity_timer_cb)
def destroy_node(self) -> bool:
try:
if self._serial is not None and self._serial.is_open:
self._serial.close()
except Exception:
pass
return super().destroy_node()
def _on_cmd_vel(self, msg: Twist) -> None:
self._latest_vx_m_s = self._clamp(msg.linear.x, float(self.get_parameter("max_vx_m_s").value))
self._latest_vy_m_s = self._clamp(msg.linear.y, float(self.get_parameter("max_vy_m_s").value))
self._latest_wz_rad_s = self._clamp(msg.angular.z, float(self.get_parameter("max_wz_rad_s").value))
self._last_cmd_time = time.monotonic()
@staticmethod
def _clamp(value: float, limit: float) -> float:
limit = abs(float(limit))
return max(-limit, min(limit, float(value)))
def _velocity_timer_cb(self) -> None:
timeout_sec = float(self.get_parameter("cmd_vel_timeout_sec").value)
stale = self._last_cmd_time <= 0.0 or (time.monotonic() - self._last_cmd_time) > timeout_sec
if stale:
if not bool(self.get_parameter("send_zero_on_timeout").value):
return
vx = vy = wz = 0.0
else:
vx = self._latest_vx_m_s
vy = self._latest_vy_m_s
wz = self._latest_wz_rad_s
frame = pack_velocity_frame(vx * VX_SCALE, vy * VY_SCALE, wz * OMEGA_SCALE)
with self._write_lock:
self._serial.write(frame)
self._serial.flush()
if bool(self.get_parameter("log_velocity_frames").value):
self.get_logger().info(
f"TX vx={vx * VX_SCALE:.0f}mm/s vy={vy * VY_SCALE:.0f}mm/s "
f"omega={wz * OMEGA_SCALE:.0f}mrad/s | {frame_to_hex(frame)}"
)
def main(args=None) -> None:
rclpy.init(args=args)
node = ChassisSerialNode()
try:
rclpy.spin(node)
except KeyboardInterrupt:
pass
finally:
node.destroy_node()
rclpy.shutdown()
if __name__ == "__main__":
main()
@@ -0,0 +1,117 @@
"""R2 chassis serial protocol, v2 (velocity only).
Frame layout, fixed 10 bytes, little endian:
Byte0-1 0xAA 0x55 header
Byte2-3 vx int16, mm/s
Byte4-5 vy int16, mm/s
Byte6-7 omega int16, mrad/s
Byte8-9 CRC16-MODBUS over byte0..byte7
Host -> STM32 only. The host never reads frames back, so there is no receive
command set.
Sign convention follows geometry_msgs/Twist:
vx = linear.x (m/s, forward positive)
vy = linear.y (m/s, left positive)
omega = angular.z (rad/s, counter-clockwise positive)
"""
from __future__ import annotations
from dataclasses import dataclass
import struct
FRAME_LEN = 10
HEADER = b"\xAA\x55"
VX_SCALE = 1000.0 # m/s -> mm/s
VY_SCALE = 1000.0 # m/s -> mm/s
OMEGA_SCALE = 1000.0 # rad/s -> mrad/s
class ProtocolError(ValueError):
"""Raised when a serial frame is malformed."""
@dataclass(frozen=True)
class VelocityCommand:
"""Parsed chassis velocity frame."""
vx_mm_s: int
vy_mm_s: int
omega_mrad_s: int
@property
def vx_m_s(self) -> float:
return self.vx_mm_s / VX_SCALE
@property
def vy_m_s(self) -> float:
return self.vy_mm_s / VY_SCALE
@property
def omega_rad_s(self) -> float:
return self.omega_mrad_s / OMEGA_SCALE
def crc16_modbus(data: bytes) -> int:
"""Compute CRC16-MODBUS, polynomial 0xA001, init 0xFFFF."""
crc = 0xFFFF
for byte in data:
crc ^= byte
for _ in range(8):
if crc & 0x0001:
crc = (crc >> 1) ^ 0xA001
else:
crc >>= 1
crc &= 0xFFFF
return crc
def clamp_i16(value: float | int) -> int:
return max(-32768, min(32767, int(round(value))))
def i16_to_le(value: int) -> bytes:
return struct.pack("<h", clamp_i16(value))
def le_to_i16(data: bytes, offset: int = 0) -> int:
return struct.unpack_from("<h", data, offset)[0]
def le_to_u16(data: bytes, offset: int = 0) -> int:
return struct.unpack_from("<H", data, offset)[0]
def pack_velocity_frame(vx_mm_s: float | int, vy_mm_s: float | int, omega_mrad_s: float | int) -> bytes:
"""Build a 10-byte velocity frame for the STM32."""
payload = bytearray(HEADER)
payload.extend(i16_to_le(vx_mm_s))
payload.extend(i16_to_le(vy_mm_s))
payload.extend(i16_to_le(omega_mrad_s))
payload.extend(struct.pack("<H", crc16_modbus(bytes(payload))))
return bytes(payload)
def parse_velocity_frame(raw: bytes | bytearray) -> VelocityCommand:
"""Parse a velocity frame. Used by tooling and lower-machine-side tests."""
raw = bytes(raw)
if len(raw) != FRAME_LEN:
raise ProtocolError(f"frame length must be {FRAME_LEN}, got {len(raw)}")
if raw[0:2] != HEADER:
raise ProtocolError("invalid frame header")
expected_crc = le_to_u16(raw, 8)
actual_crc = crc16_modbus(raw[:8])
if expected_crc != actual_crc:
raise ProtocolError(f"crc mismatch expected=0x{expected_crc:04X}, actual=0x{actual_crc:04X}")
return VelocityCommand(
vx_mm_s=le_to_i16(raw, 2),
vy_mm_s=le_to_i16(raw, 4),
omega_mrad_s=le_to_i16(raw, 6),
)
def frame_to_hex(frame: bytes | bytearray) -> str:
return " ".join(f"{b:02X}" for b in bytes(frame))
@@ -0,0 +1,55 @@
from __future__ import annotations
import argparse
import time
import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist
class CmdVelPublisher(Node):
def __init__(self, vx: float, vy: float, omega: float, rate_hz: float, duration_sec: float) -> None:
super().__init__("test_cmd_vel_pub")
self._publisher = self.create_publisher(Twist, "/cmd_vel", 10)
self._vx = vx
self._vy = vy
self._omega = omega
self._duration_sec = duration_sec
self._start_time = time.monotonic()
self._timer = self.create_timer(1.0 / max(1.0, rate_hz), self._timer_cb)
def _timer_cb(self) -> None:
elapsed = time.monotonic() - self._start_time
if elapsed > self._duration_sec:
self.get_logger().info("Finished publishing /cmd_vel")
rclpy.shutdown()
return
msg = Twist()
msg.linear.x = self._vx
msg.linear.y = self._vy
msg.angular.z = self._omega
self._publisher.publish(msg)
self.get_logger().info(f"Publish /cmd_vel vx={self._vx:.3f} vy={self._vy:.3f} omega={self._omega:.3f}")
def build_arg_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Publish test /cmd_vel")
parser.add_argument("--vx", type=float, default=0.1, help="linear.x in m/s")
parser.add_argument("--vy", type=float, default=0.0, help="linear.y in m/s")
parser.add_argument("--omega", type=float, default=0.0, help="angular.z in rad/s")
parser.add_argument("--rate-hz", type=float, default=10.0)
parser.add_argument("--duration-sec", type=float, default=3.0)
return parser
def main(args=None) -> None:
parser = build_arg_parser()
parsed_args, ros_args = parser.parse_known_args(args)
rclpy.init(args=ros_args)
node = CmdVelPublisher(parsed_args.vx, parsed_args.vy, parsed_args.omega, parsed_args.rate_hz, parsed_args.duration_sec)
rclpy.spin(node)
if __name__ == "__main__":
main()
@@ -0,0 +1,53 @@
cmake_minimum_required(VERSION 3.8)
project(ros_interfaces)
if(CMAKE_COMPILER_ID MATCHES "Clang|GNU")
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF) # 禁用编译器扩展
add_compile_options(-Wall -Wextra -Wpedantic)
set(CMAKE_BUILD_TYPE "Release")
add_compile_options(-Werror)
endif()
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# Find required packages
find_package(ament_cmake REQUIRED)
find_package(std_msgs REQUIRED)
find_package(nav_msgs REQUIRED)
find_package(geometry_msgs REQUIRED)
find_package(sensor_msgs REQUIRED)
find_package(rosidl_default_generators REQUIRED)
# Declare ROS2 message, service, and action files
set(msg_files
"msg/cluster/DynamicObstacle.msg"
"msg/cluster/DynamicObstacleArray.msg"
"msg/minco_traj/PositionCommand.msg"
"msg/minco_traj/MpcPositionCommand.msg"
"msg/Behavior.msg"
"msg/EnemyRobotStatus.msg"
"msg/RadarInfo.msg"
"msg/AllyRobotStatus.msg"
"msg/TeamInformation.msg"
"msg/GameInfo.msg"
"msg/SentryInfoOffline.msg"
"msg/SentryInfoOnline.msg"
)
# set(srv_files
# )
# Generate interfaces
rosidl_generate_interfaces(${PROJECT_NAME}
${msg_files}
${srv_files}
DEPENDENCIES std_msgs geometry_msgs nav_msgs sensor_msgs
)
# Export dependencies
ament_export_dependencies(rosidl_default_runtime)
ament_package()
@@ -0,0 +1,11 @@
# 机器人装甲板ID常量定义
uint8 HERO = 1 # 英雄机器人
uint8 ENGINEER = 2 # 工程机器人
uint8 INFANTRY_3 = 3 # 3号步兵机器人
uint8 INFANTRY_4 = 4 # 4号步兵机器人
uint8 robot_id # 机器人ID
# 机器人的基本状态信息
uint16 robot_hp # 剩余血量
# 机器人位置信息
geometry_msgs/Pose position # 位置坐标
@@ -0,0 +1,48 @@
uint8 desired_stance
uint8 STANCE_ATTACK=1
uint8 STANCE_DEFEND=2
uint8 STANCE_MOVE=3
uint8 STANCE_ENHANCED_ATTACK = 4
uint8 STANCE_ENHANCED_DEFEND = 5
uint8 STANCE_ENHANCED_MOVE = 6
uint8 control_mode
uint8 CONTROL_AUTO=0
uint8 CONTROL_MANUAL=1
bool use_gyro_mode
float32 gyro_vel
uint8 desire_lifter_pos
uint8 LIFTER_TOP=0
uint8 LIFTER_BOTTOM=1
uint8 LIFTER_MIDDLE=2
uint16 ammo_purchase_request
uint8 revive_request
uint8 remote_revive_request
uint8 remote_ammo_request
uint8 remote_health_request
bool use_limited_scan
float32 scan_yaw_min
float32 scan_yaw_max
uint8 pitch_mode
uint8 PITCH_TOP=0
uint8 PITCH_BOTTOM=1
bool not_aim_enemy
bool use_capacitor
bool tunnel_escape_active
float32 tunnel_escape_vx
float32 tunnel_escape_vy
float32 tunnel_escape_wz
bool tunnel_prepare_active
bool tunnel_ready
bool tunnel_align_active
float32 tunnel_align_angle_deg
@@ -0,0 +1,13 @@
# 机器人装甲板ID常量定义
uint8 HERO = 1 # 英雄机器人
uint8 ENGINEER = 2 # 工程机器人
uint8 INFANTRY_3 = 3 # 3号步兵机器人
uint8 INFANTRY_4 = 4 # 4号步兵机器人
# 机器人的基本状态信息
uint8 robot_id # 机器人ID,蓝方=红方+100
uint16 robot_hp # 机器人血量
uint16 allowed_projectile # 允许发射的弹丸数量,单位发
# 机器人位置信息
geometry_msgs/Pose position # 位置坐标
@@ -0,0 +1,11 @@
std_msgs/Header header
uint16 game_time_remaining # 比赛剩余时间,单位s
uint16 coin_remaining # 己方剩余金币数量
uint32 event_code # 场地事件代码,未解码,需接收后根据协议解码
uint8 game_status # 0:未开始比赛 1:准备阶段 2:15s裁判系统自检 3:5s倒计时 4:比赛中 5:比赛结算中
float32 manual_point_x # 手动指定的目标点x坐标,单位m,坐标系minimap
float32 manual_point_y # 手动指定的目标点y坐标,单位m,坐标系minimap
uint8 manual_key # 手动指定的目标点快捷
uint16 enemy_outpost_hp # 敌方前哨站血量
uint16 enemy_base_hp # 敌方基地血量
@@ -0,0 +1,6 @@
std_msgs/Header header
ros_interfaces/EnemyRobotStatus[6] enemies # 雷达检测到的机器人信息列表,最多6个机器人
uint16 enemy_coin_left # 敌方剩余金币数量
uint16 enemy_coin_accumulated # 敌方累计获得金币数量
bool is_enemy_outpost_sensed # 敌方前哨站是否被雷达识别到
@@ -0,0 +1,12 @@
std_msgs/Header header
bool is_get # 视觉是否瞄准到敌人
geometry_msgs/Point armor_pos # 瞄准到的装甲板位置,具体坐标系询问视觉
uint8 armor_num # 不做红蓝方区分
float32 yaw_camerainit_to_gimbal # camera_init到gimbal的yaw轴角度 逆时针为正
uint8 lifter_current_pos # 0 -- kTop 1 -- kBottom 2 -- kMiddle
bool is_transformable # 是否能够进行变形(不止变形中不能变形,升降卡住后也无法进行变形)
float32 transform_state # 变形状态,0-1,0%为未变形,100%为完全变形,过渡状态根据实际情况变化
uint8 capacitor_capacity # 电容容量百分比
bool tunnel_yaw_aligned # 底盘航向是否完成对齐
@@ -0,0 +1,13 @@
std_msgs/Header header
uint16 self_health # 机器人血量
uint16 bullets_remaining # 剩余发弹量
uint16 cooling_value # 机器人每秒冷却值
uint16 heat_limit # 机器人热量上限
uint16 current_heat # 机器人当前热量
geometry_msgs/Point sentry_pos # 哨兵位置
float32 speed_monitor_angle # 测速模块朝向,单位为度,正北为0度
uint32 sentry_info_1 # 哨兵信息1,未解码,需接收后根据协议解码
uint16 sentry_info_2 # 哨兵信息2,未解码,需接收后根据协议解码
uint64 sentry_info_3 # 哨兵信息3,未解码,需接收后根据协议解码
uint8 energy_ratio # 底盘能量比例
@@ -0,0 +1,5 @@
std_msgs/Header header # 时间戳和坐标系
AllyRobotStatus[4] allies # 四名队友机器人状态
uint16 outpost_hp # 前哨站血量
uint16 base_hp # 基地血量
@@ -0,0 +1,6 @@
int32 id
geometry_msgs/Point centroid
geometry_msgs/Vector3 size
geometry_msgs/Quaternion orientation
geometry_msgs/Vector3 velocity
float32 speed
@@ -0,0 +1,2 @@
std_msgs/Header header
DynamicObstacle[] obstacles
@@ -0,0 +1,6 @@
std_msgs/Header header
ros_interfaces/PositionCommand[] cmds
uint32 mpc_horizon
uint8 command_flag
uint8 NORMAL_COMMAND = 1
uint8 BLOCK_COMMAND = 137
@@ -0,0 +1,15 @@
std_msgs/Header header
geometry_msgs/Point position
geometry_msgs/Vector3 velocity
geometry_msgs/Vector3 acceleration
geometry_msgs/Vector3 jerk
geometry_msgs/Vector3 angular_velocity
float64 yaw
float64 yaw_dot
float64 vel_norm
float64 acc_norm
float64[3] kx
float64[3] kv
uint32 trajectory_id
@@ -0,0 +1,33 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>ros_interfaces</name>
<version>2.0.0</version>
<description>
The ros_interfaces package provides all the messages for RoboMaster AI Robot driver
</description>
<author>YuChen</author>
<maintainer email="[email protected]">RoboMaster</maintainer>
<license>GPL 3.0</license>
<url type="repository">https://github.com/RoboMaster/RoboRTS-Base</url>
<url type="bugtracker">https://github.com/RoboMaster/RoboRTS-Base/issues</url>
<buildtool_depend>ament_cmake</buildtool_depend>
<buildtool_depend>rosidl_default_generators</buildtool_depend>
<build_depend>std_msgs</build_depend>
<build_depend>geometry_msgs</build_depend>
<build_depend>rosidl_default_generators</build_depend>
<depend>nav_msgs</depend>
<depend>sensor_msgs</depend>
<exec_depend>rosidl_default_runtime</exec_depend>
<member_of_group>rosidl_interface_packages</member_of_group>
<export>
<build_type>ament_cmake</build_type>
</export>
</package>
+58
View File
@@ -0,0 +1,58 @@
cmake_minimum_required(VERSION 3.10)
project(minco_controller)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_BUILD_TYPE Release)
find_package(ament_cmake_auto REQUIRED)
ament_auto_find_build_dependencies()
find_package(Eigen3 REQUIRED)
option(MINCO_DEBUG "Enable Minco debug printing" OFF)
find_package(qpOASES QUIET)
if(NOT qpOASES_FOUND)
find_path(QPOASES_INCLUDE_DIR qpOASES.hpp PATH_SUFFIXES qpOASES qpoases)
find_library(QPOASES_LIBRARY qpOASES)
endif()
ament_auto_add_library(${PROJECT_NAME} SHARED
src/mpc_solver.cpp
src/minco_mpc_controller.cpp
src/performance/mpc_performance_monitor.cpp
)
target_include_directories(${PROJECT_NAME}
PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
target_link_libraries(${PROJECT_NAME}
Eigen3::Eigen
)
if(MINCO_DEBUG)
target_compile_definitions(${PROJECT_NAME} PRIVATE MINCO_DEBUG)
endif()
set(_QPOASES_LINKED FALSE)
set(_QPOASES_VENDOR_DIR ${CMAKE_CURRENT_SOURCE_DIR}/third_party/qpOASES)
if(EXISTS "${_QPOASES_VENDOR_DIR}/include/qpOASES.hpp" AND EXISTS "${_QPOASES_VENDOR_DIR}/src")
file(GLOB _QPOASES_VENDOR_SRC "${_QPOASES_VENDOR_DIR}/src/*.cpp")
add_library(qpOASES_vendor STATIC ${_QPOASES_VENDOR_SRC})
set_target_properties(qpOASES_vendor PROPERTIES POSITION_INDEPENDENT_CODE ON)
target_include_directories(qpOASES_vendor PUBLIC "${_QPOASES_VENDOR_DIR}/include")
target_compile_definitions(qpOASES_vendor PRIVATE __NO_COPYRIGHT__ LINUX)
target_link_libraries(${PROJECT_NAME} qpOASES_vendor)
set(_QPOASES_LINKED TRUE)
endif()
pluginlib_export_plugin_description_file(nav2_core minco_controller.xml)
ament_auto_package(USE_SCOPED_HEADER_INSTALL_DIR)
+168
View File
@@ -0,0 +1,168 @@
# 🎮 MincoMpcController
> 面向全向哨兵底盘的 Nav2 Controller 插件:以 MINCO 轨迹为参考,使用凝聚式 QP MPC 在 SE(2) 状态空间输出全局坐标系速度指令。
[返回项目主页](../../../README.md) · [MINCO Planner](../minco_planner/README.md)
## ✨ 模块定位
`minco_controller::MincoMpcController` 实现 `nav2_core::Controller`,订阅规划器生成的 `/opt_path` 与 Point-LIO 里程计,在 Nav2 Controller Server 的控制周期内求解 MPC。当前主配置控制频率为 **100 Hz**。
主要特性:
- 状态 `x = [px, py, yaw]`,控制 `u = [vx, vy, wz]`。
- qpOASES 求解凝聚后的有约束二次规划。
- 单调推进参考索引,减少高速运动时参考点回跳。
- 速度、角速度及相邻控制量差分约束。
- 控制时延、雷达到底盘参考点杆臂及车体 roll 补偿。
- 支持固定角速度小陀螺模式与 yaw 优化轨迹。
- 发布预测轨迹,提供求解耗时与频率统计。
## 🧠 模块流程图
```mermaid
flowchart LR
T["/opt_path"] --> R[参考序列构造]
O["/aft_mapped_to_init"] --> S[位姿与全局速度提取]
S --> L[杆臂 / roll / 时延补偿]
R --> Q[凝聚式 QP]
L --> Q
Q --> C[速度与加速度约束]
C --> U["/cmd_vel_mpc"]
Q --> V["/mpc_predict_path"]
```
### 流程概述
控制器以 `/opt_path` 中的 P/V/A/J 与 yaw 参考构造有限时域序列,同时从 latest-state odom 提取当前 SE(2) 状态。完成杆臂、固定 roll 和控制时延补偿后,将跟踪问题凝聚为只包含控制量的 QP;qpOASES 求解后应用速度死区、目标停车和 speed limit,最后通过 `/cmd_vel_mpc` 输出世界坐标系速度。
## 🧪 技术方向
- 状态为 `[x, y, yaw]`,控制为 `[vx, vy, wz]`,通过固定 `dt` 的离散模型预测有限时域状态。
- 代价由状态跟踪误差 `Q` 和控制参考误差 `R` 构成;速度、角速度和相邻控制量差分由 QP 上下界约束。
- 参考索引单调前进,并结合 `control_delay_compensation` 前移参考,减少高速运动时跟踪旧参考。
- Planner 输出的速度/加速度等前馈会进入 MPC 参考构造;上游热启动和轨迹边界状态会直接影响控制器收到的参考速度。
## ⚡ 性能方向
- 将状态消元后求解凝聚 QP,限制 100 Hz 控制周期内的决策变量规模。
- odom 订阅使用 `KeepLast(1) + best_effort + volatile`,只消费最新状态,避免高频定位消息排队。
- `/opt_path` 使用 `SystemDefaultsQoS`;控制与预测可视化 publisher 深度为 1,避免历史控制结果积压。
- `MpcPerformanceMonitor` 在开关启用时记录求解耗时、完整周期耗时、控制频率、命令/参考速度和 odom 回调延迟;关闭时不写 CSV。
## 🌐 坐标系与输出约定
控制器从 odom 四元数提取 yaw,将雷达参考点速度转换并补偿到底盘控制参考点。输出的 `vx/vy` 保持为**全局坐标系速度分量**,用于当前下位机通信约定;不要默认把它当作 `base_link` 局部速度。
杆臂速度关系可概括为:
```text
v_base = v_lidar + ω × r
```
其中 `r` 的符号取决于配置中“雷达参考点相对底盘参考点”的定义。修改安装位置后,Planner 与 Controller 必须同步校核。
## 📡 ROS 接口
| 方向 | Topic | 类型 | 说明 |
|---|---|---|---|
| 输入 | `/opt_path` | `ros_interfaces/msg/MpcPositionCommand` | MINCO 位置、速度、朝向参考 |
| 输入 | `/aft_mapped_to_init` | `nav_msgs/msg/Odometry` | 当前位姿、速度与角速度 |
| 输出 | `/cmd_vel_mpc` | `geometry_msgs/msg/Twist` | 提供给 communication / 底盘链路的控制量 |
| 输出 | `/mpc_predict_path` | `nav_msgs/msg/Path` | MPC 预测轨迹可视化 |
Nav2 标准接口 `setPlan()`、`computeVelocityCommands()` 和 `setSpeedLimit()` 仍由插件实现;项目主链路的高阶轨迹信息来自 `/opt_path`。
## ⚙️ 关键参数
配置位于 `src/navigation/navi2_bringup/params/sentry1.yaml` 的 `controller_server.ros__parameters.FollowPath`。
| 参数 | 当前典型值 | 说明 |
|---|---:|---|
| `controller_frequency` | `100.0` | Controller Server 调用频率 |
| `dt` | `0.05` | MPC 预测离散步长,不等同于控制周期 |
| `lookahead_time` | `0.5` | 参考轨迹前视时间 |
| `control_delay_compensation` | `0.05` | 控制链路时延预测 |
| `Q` | `[3, 3, 2]` | x、y、yaw 跟踪权重 |
| `R` | `[1.5, 1.5, 1]` | vx、vy、wz 输入权重 |
| `vx/vy_min/max` | `±3.0` | 全局平移速度约束 |
| `omega_min/max` | `±5.0` | 角速度约束 |
| `use_acc_constraints` | `true` | 启用相邻控制量差分约束 |
| `ax/ay_min/max` | `±2.0` | 平移加速度约束 |
| `alpha_min/max` | `±5.0` | 角加速度约束 |
| `use_small_gyro_mode` | `false` | 固定角速度小陀螺模式 |
| `fixed_wz` | `4.18` | 小陀螺目标角速度 |
### 📐 杆臂与姿态补偿
```yaml
lidar_offset_x: 0.0
lidar_offset_y: -0.20
lidar_roll_offset: 0.1745
```
- `lidar_offset_x/y`:里程计参考点与底盘控制参考点的平面偏移。
- `lidar_roll_offset`:安装姿态导致的固定横滚补偿。
- 三者均是实体标定量,不应仅凭轨迹观感随意调整。
- 修改后应低速验证原地旋转、纯 x/y 平移和组合运动,确认补偿方向正确。
## 🚀 启动与检查
控制器随 Nav2 完整启动:
```bash
ros2 launch navi2 navigation2.launch.py
```
运行时检查:
```bash
ros2 topic hz /opt_path
ros2 topic hz /aft_mapped_to_init
ros2 topic hz /cmd_vel_mpc
ros2 topic echo /cmd_vel_mpc --once
```
在 RViz 中叠加 `/opt_path_vis` 与 `/mpc_predict_path`,可快速判断误差来自参考轨迹还是控制器预测。
## 📈 性能观测
`performance.enable` 为总开关,`print_enable`、`detailed_csv_enable` 和 `odom_sub_debug_enable` 分别控制终端摘要、逐周期 CSV 和 odom 订阅窗口统计。当前比赛 YAML 中总开关与 `print_enable` 为开启,详细 CSV 与 odom 窗口统计关闭;由于周期样本只在 detailed CSV 开启时采集,默认不会记录逐周期求解 CSV。详细性能 CSV 默认路径:
```text
/tmp/mpc_perf_detailed.csv
```
字段包含 `success`、`solve_time_ms`、`cycle_time_ms`、`controller_hz`、`cmd_vx/vy/wz` 和 `ref_vx/vy/wz`,并可附带 `run_id/scenario/variant`。`csv_flush_every_n` 用于降低刷盘频率。
重点关注控制回调实际频率、QP 求解 P95/P99、失败次数,以及命令速度与参考速度的稳态差。100 Hz 控制要求 CSV、终端日志和可视化不能阻塞主回调。
## ⚠️ 已知问题与改进方向
- 当前电控速度跟随存在稳态误差,上游 Planner 因而强制保留热启动速度/加速度前馈。该补偿会提高参考速度,但不能替代底盘速度闭环标定;应联合对比 `ref_v*`、`cmd_v*` 与底盘反馈。
- 模型是速度层 SE(2) 运动学模型,未显式描述轮胎侧滑、电机/底盘执行延迟变化和速度闭环动态;高加速度、坡面或碰撞扰动下模型误差会增大。
- `/opt_path` 与 odom 使用不同 QoS 语义:轨迹为系统默认 QoS,odom 为 best-effort latest-state。诊断“无控制输出”时必须分别检查两条订阅是否匹配。
- 预测轨迹用于诊断,不代表底盘真实执行路径;实际闭环效果需结合 odom、communication CSV 和下位机反馈判断。
## 🛠️ 常见问题
| 现象 | 优先检查 |
|---|---|
| `/cmd_vel_mpc` 无输出 | Nav2 lifecycle、是否收到 `/opt_path` 与 odom |
| 速度方向与车体直觉不一致 | 输出为全局速度;核对下位机坐标约定 |
| 原地旋转伴随平移 | 杆臂偏移符号、雷达安装位置和角速度单位 |
| 高频振荡 | `Q/R` 比例、时延补偿、参考密度、加速度约束 |
| 跟踪明显滞后 | odom/轨迹时间戳、控制延迟、前视时间和下位机延迟 |
| QP 不可行 | 初始状态偏差、速度/加速度边界和参考突变 |
| 小陀螺退出异常 | 上层模式切换是否恢复参数与固定角速度配置 |
## 🗂️ 关键源码
- `src/minco_mpc_controller.cpp`:插件生命周期、参考构造、补偿、QP 与输出。
- `include/minco_controller/minco_mpc_controller.hpp`:状态、参数与接口定义。
- `minco_controller.xml`:pluginlib 注册信息。
- `src/navigation/navi2_bringup/params/sentry1.yaml`:比赛主参数。
## 📚 延伸阅读
轨迹如何生成见 [MincoPlanner 文档](../minco_planner/README.md),系统启动和通信链路见[项目主 README](../../../README.md)。
@@ -0,0 +1,31 @@
//
// Created by yunfan on 11/8/24.
//
#ifndef SUPER_COLOR_TEXT_HPP
#define SUPER_COLOR_TEXT_HPP
#include <string>
namespace color_text {
static const std::string RESET = "\033[0m";
static const std::string BLACK = "\033[30m"; /* Black */
static const std::string RED = "\033[31m"; /* Red */
static const std::string GREEN = "\033[32m"; /* Green */
static const std::string YELLOW = "\033[33m"; /* Yellow */
static const std::string BLUE = "\033[34m"; /* Blue */
static const std::string MAGENTA = "\033[35m"; /* Magenta */
static const std::string CYAN = "\033[36m"; /* Cyan */
static const std::string WHITE = "\033[37m"; /* White */
static const std::string REDPURPLE = "\033[95m"; /* Red Purple */
static const std::string BOLDBLACK = "\033[1m\033[30m"; /* Bold Black */
static const std::string BOLDRED = "\033[1m\033[31m"; /* Bold Red */
static const std::string BOLDGREEN = "\033[1m\033[32m"; /* Bold Green */
static const std::string BOLDYELLOW = "\033[1m\033[33m"; /* Bold Yellow */
static const std::string BOLDBLUE = "\033[1m\033[34m"; /* Bold Blue */
static const std::string BOLDMAGENTA = "\033[1m\033[35m"; /* Bold Magenta */
static const std::string BOLDCYAN = "\033[1m\033[36m"; /* Bold Cyan */
static const std::string BOLDWHITE = "\033[1m\033[37m"; /* Bold White */
static const std::string BOLDREDPURPLE = "\033[1m\033[95m"; /* Bold Red Purple */
} // namespace color_text
#endif // SUPER_COLOR_TEXT_HPP
@@ -0,0 +1,77 @@
#pragma once
#include "color_text.hpp"
#include <algorithm>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <string_view>
namespace custom_log {
inline std::string now_string()
{
using namespace std::chrono;
const auto now = system_clock::now();
const auto now_t = system_clock::to_time_t(now);
std::tm tm_buf{};
#if defined(_WIN32)
localtime_s(&tm_buf, &now_t);
#else
localtime_r(&now_t, &tm_buf);
#endif
const auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;
std::ostringstream ts;
ts << std::setfill('0') << std::setw(2) << tm_buf.tm_hour << ':' << std::setw(2) << tm_buf.tm_min << ':'
<< std::setw(2) << tm_buf.tm_sec << '.' << std::setw(3) << ms.count();
return ts.str();
}
template <typename T> struct named_value
{
std::string_view name;
const T * ptr;
};
template <typename T> constexpr named_value<T> nv(std::string_view name, const T & v)
{
return {name, &v};
}
void log_info_line(std::string_view text);
template <typename... NVs> inline void log_info(std::string prefix, const NVs &... nvs)
{
std::ostringstream oss;
oss << std::boolalpha;
((oss << prefix << nvs.name << " = " << *(nvs.ptr) << ::color_text::RESET << '\n'), ...);
log_info_line(oss.str());
}
// 带分割线与列对齐的块状调试输出
template <typename... NVs> inline void log_block(std::string prefix, const NVs &... nvs)
{
// 计算最大键名宽度
std::size_t maxw = 0;
(void)std::initializer_list<int>{(maxw = std::max<std::size_t>(maxw, nvs.name.size()), 0)...};
// 构造分割线(至少 50 列)
const std::size_t bar_len = std::max<std::size_t>(50, maxw + 10);
std::string bar(bar_len, '-');
std::ostringstream oss;
oss << std::boolalpha;
// 时间戳 + 顶部分割线
oss << prefix << '[' << now_string() << "] " << bar << ::color_text::RESET << '\n';
// 对齐的 name : value
((oss << prefix << std::left << std::setw(static_cast<int>(maxw)) << nvs.name << " : " << *(nvs.ptr)
<< ::color_text::RESET << '\n'),
...);
// 底部分割线
oss << prefix << bar << ::color_text::RESET << '\n';
log_info_line(oss.str());
}
} // namespace custom_log
#define NV(var) ::custom_log::nv(#var, (var))
@@ -0,0 +1,178 @@
#pragma once
#include <cstdint>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
#include "nav2_core/controller.hpp"
#include "geometry_msgs/msg/pose_stamped.hpp"
#include "geometry_msgs/msg/twist.hpp"
#include "geometry_msgs/msg/twist_stamped.hpp"
#include "nav_msgs/msg/odometry.hpp"
#include "nav_msgs/msg/path.hpp"
#include "rclcpp/rclcpp.hpp"
#include "rclcpp_lifecycle/lifecycle_node.hpp"
#include "tf2_ros/buffer.h"
#include "ros_interfaces/msg/mpc_position_command.hpp"
#include "log.hpp"
#include "minco_controller/mpc_solver.hpp"
#include "minco_controller/performance/mpc_performance_monitor.hpp"
namespace minco_controller {
class MincoMpcController : public nav2_core::Controller
{
public:
// === Constructor & Lifecycle ===
MincoMpcController() = default;
~MincoMpcController() override;
void configure(const rclcpp_lifecycle::LifecycleNode::WeakPtr & parent,
std::string name,
std::shared_ptr<tf2_ros::Buffer> tf,
std::shared_ptr<nav2_costmap_2d::Costmap2DROS> costmap_ros) override;
void cleanup() override;
void activate() override;
void deactivate() override;
// === Core Planning Interfaces ===
geometry_msgs::msg::TwistStamped computeVelocityCommands(const geometry_msgs::msg::PoseStamped & pose,
const geometry_msgs::msg::Twist & velocity,
nav2_core::GoalChecker * goal_checker) override;
void applyGravityCompensation(const nav_msgs::msg::Odometry::SharedPtr & odom, double & vx, double & vy);
void setPlan(const nav_msgs::msg::Path & path) override;
void setSpeedLimit(const double & speed_limit, const bool & percentage) override;
private:
// === Callbacks ===
void onOptPath(const ros_interfaces::msg::MpcPositionCommand::SharedPtr msg);
void onOdom(const nav_msgs::msg::Odometry::SharedPtr msg);
// === Utility & Helper Functions ===
void configureMpcPerfLogging(const rclcpp_lifecycle::LifecycleNode::SharedPtr & node);
// --- Reference and Path Processing ---
// Find the nearest point on cached trajectory and build horizon reference sequence.
bool buildReferenceFromOptPath(const State & curr, std::vector<ReferencePoint> & out_ref) const;
bool transformPathToOdom(const ros_interfaces::msg::MpcPositionCommand::SharedPtr & opt,
std::vector<ros_interfaces::msg::PositionCommand> & out_cmds) const;
// --- Motion and Frame Utilities ---
void compensateLeverArm(double v_lidar_x,
double v_lidar_y,
double omega_z,
double yaw,
double & vx_global,
double & vy_global,
double & omega_global) const;
void extractGlobalVelocityAndYaw(const nav_msgs::msg::Odometry::SharedPtr & odom,
double & vx_global,
double & vy_global,
double & omega_global,
double & yaw_global) const;
// --- Interpolation Utilities ---
static double normalizeYaw(double yaw);
inline static double interpolateYaw(double yaw1, double yaw2, double alpha)
{
double diff = std::atan2(std::sin(yaw2 - yaw1), std::cos(yaw2 - yaw1));
return yaw1 + diff * alpha;
}
inline static double interpolate(double v1, double v2, double alpha) { return v1 + (v2 - v1) * alpha; }
inline static Eigen::Vector2d interpolate(
const Eigen::Vector2d & v1, const Eigen::Vector2d & v2, double alpha)
{
return v1 + (v2 - v1) * alpha;
}
// --- Visualization ---
void publishVisualization(const std::vector<State> & pred_path, const State & curr_state);
// === ROS 2 Interfaces (Publishers, Subscribers, Timers) ===
rclcpp::Subscription<ros_interfaces::msg::MpcPositionCommand>::SharedPtr opt_path_sub_;
rclcpp::Subscription<nav_msgs::msg::Odometry>::SharedPtr odom_sub_;
rclcpp::Publisher<nav_msgs::msg::Path>::SharedPtr mpc_predict_path_pub_;
rclcpp::Publisher<nav_msgs::msg::Path>::SharedPtr mpc_real_path_pub_;
rclcpp::Publisher<geometry_msgs::msg::Twist>::SharedPtr cmd_vel_mpc_pub_;
// === TF & Costmap & Frames ===
rclcpp_lifecycle::LifecycleNode::WeakPtr node_;
rclcpp::Logger logger_{rclcpp::get_logger("MincoMpcController")};
std::string name_;
std::shared_ptr<tf2_ros::Buffer> tf_;
std::shared_ptr<nav2_costmap_2d::Costmap2DROS> costmap_ros_;
std::string global_frame_;
std::string base_frame_;
std::string odom_frame_;
std::string map_frame_;
// === State Variables & Caches ===
// --- Visualization Cache ---
std::vector<geometry_msgs::msg::PoseStamped> real_path_history_;
rclcpp::Time last_real_path_pub_time_;
// --- Runtime Data Cache ---
mutable std::mutex data_mtx_;
ros_interfaces::msg::MpcPositionCommand::SharedPtr latest_opt_path_;
nav_msgs::msg::Odometry::SharedPtr latest_odom_;
// --- Reference Tracking State ---
// Track reference index over time when trajectory is not updated to avoid jumping back to start.
mutable double tracked_ref_idx_{0.0};
mutable rclcpp::Time tracked_ref_time_;
mutable uint32_t tracked_opt_traj_id_{0};
mutable bool has_tracked_ref_{false};
// --- Nav2 Plan Cache ---
nav_msgs::msg::Path global_plan_;
mutable std::mutex plan_mtx_;
// === Core Modules (Pointers to FSM, Optimizers, etc.) ===
MPCConfig mpc_config_;
std::unique_ptr<MpcSolver> solver_;
// === Configurations & Parameters ===
// Dynamic speed limit from Nav2 setSpeedLimit().
double speed_limit_{0.0};
bool speed_limit_percentage_{false};
// Other controller parameters.
double fixed_wz_{0.0};
double deadzone_speed_threshold_{0.02};
double control_delay_compensation_{0.25};
double lidar_offset_x_{0.0};
double lidar_offset_y_{0.0};
double lidar_roll_offset_ = 0.0;
bool use_small_gyro_mode_{true};
MpcPerformanceMonitor mpc_perf_monitor_;
long long last_mpc_perf_stamp_ns_{0};
// Low-pass filter for MPC output to prevent stick-slip oscillation on slopes.
mutable Eigen::Vector3d prev_u_global_{0.0, 0.0, 0.0};
double vel_smooth_alpha_{0.3};
// P0: Integral action for unmodeled disturbances (gravity on slopes, slip).
// Leaky integrators of along-track and cross-track position errors.
mutable Eigen::Vector2d integral_err_{0.0, 0.0};
double k_i_along_{1.5}; // integral gain: along-track (boost on slopes)
double k_i_cross_{3.0}; // integral gain: cross-track (precision on curves)
double integral_decay_{0.98};
};
} // namespace minco_controller
@@ -0,0 +1,57 @@
#pragma once
#include <vector>
#include <Eigen/Core>
#include "minco_controller/mpc_types.hpp"
namespace minco_controller {
// 纯 C++ MPC 求解器:不依赖 ROS,仅依赖 Eigen 与 qpOASES。
class MpcSolver
{
public:
explicit MpcSolver(const MPCConfig & config);
void setConfig(const MPCConfig & config);
// @brief 求解一次 MPC。
// @param curr 当前状态 (map)
// @param ref_traj 参考轨迹 (horizon 个点,若不足由插件层补齐)
// @param out_u 输出控制 (map)
// @param out_pred (可选) 输出预测轨迹
// @return 是否求解成功
bool solve(const State & curr,
const std::vector<ReferencePoint> & ref_traj,
Control & out_u,
std::vector<State> * out_pred = nullptr);
Eigen::Vector3d getLastControl() const { return last_u_global_; }
private:
// 构建离散线性模型:x_{k+1} = A x_k + B_k u_k
// 状态为 [x,y,yaw],控制变量 u_k 为 map/global 系 [vx, vy, omega]
void buildStepModel(double yaw_ref, Eigen::Matrix3d & A, Eigen::Matrix<double, 3, 3> & B) const;
// 组装 MPC 的 condensed QP:0.5*U^T H U + g^T U
// 其中 U 堆叠了 horizon 个控制量 [vx, vy, omega] (map/global)
bool buildCondensedQP(const State & curr,
const std::vector<ReferencePoint> & ref_traj,
Eigen::MatrixXd & H,
Eigen::VectorXd & g,
Eigen::VectorXd & lb,
Eigen::VectorXd & ub,
Eigen::MatrixXd & A_con,
Eigen::VectorXd & lbA,
Eigen::VectorXd & ubA);
private:
MPCConfig config_;
// 用于加速度约束的上一时刻 global 控制量
Eigen::Vector3d last_u_global_{0.0, 0.0, 0.0};
bool has_last_u_{false};
};
} // namespace minco_controller
@@ -0,0 +1,79 @@
#pragma once
#include <vector>
#include <Eigen/Core>
namespace minco_controller {
// 状态:全局系 (map) 下的位姿
struct State
{
double x{0.0};
double y{0.0};
double yaw{0.0};
double vx{0.0};
double vy{0.0};
double omega{0.0};
};
// 控制量:速度命令 (vx, vy, omega)
// 约定:对外输出为全局系 (map) 下速度;插件层再转换到 base_link。
struct Control
{
double vx{0.0};
double vy{0.0};
double omega{0.0};
};
// 参考点:来自 Minco 轨迹的高精度前馈信息
struct ReferencePoint
{
Eigen::Vector2d pos{0.0, 0.0}; // map系位置
Eigen::Vector2d vel{0.0, 0.0}; // map系速度(前馈)
double yaw{0.0}; // 参考航向
double yaw_rate{0.0}; // 参考角速度(前馈)
};
// MPC 配置
struct MPCConfig
{
// 采样周期与预测步长
double dt{0.05};
double planner_freq{20.0};
double lookahead_time{0.5};
int horizon{10};
// 代价权重:Q(状态误差) / R(控制误差)
// 状态采用 [x, y, yaw],控制采用 [vx, vy, omega]
// Q_along/cross are rotated to align with the reference heading at each horizon step.
Eigen::Vector3d Q{5.0, 5.0, 2.0};
double q_along{3.0}; // weight along heading (lower → timing flexibility)
double q_cross{12.0}; // weight cross-track (higher → precision)
Eigen::Vector3d R{1.0, 1.0, 0.5};
// 速度约束(作用在 map/global 速度变量上)
double vx_min{-1.0};
double vx_max{1.0};
double vy_min{-1.0};
double vy_max{1.0};
double omega_min{-2.0};
double omega_max{2.0};
// 加速度约束(可选)
bool use_acc_constraints{false};
double ax_min{-2.0};
double ax_max{2.0};
double ay_min{-2.0};
double ay_max{2.0};
double alpha_min{-4.0};
double alpha_max{4.0};
// qpOASES 求解器参数
int max_working_set_recalculations{200};
int max_iterations{200};
double eps_regularization{1e-9};
};
} // namespace minco_controller
@@ -0,0 +1,98 @@
#pragma once
#include <chrono>
#include <fstream>
#include <limits>
#include <string>
#include "builtin_interfaces/msg/time.hpp"
#include "rclcpp/rclcpp.hpp"
namespace minco_controller {
struct MpcPerformanceConfig
{
bool enable{true};
bool print_enable{true};
bool detailed_csv_enable{false};
bool odom_sub_debug_enable{true};
std::string detailed_csv_path{"/tmp/mpc_perf_detailed.csv"};
std::string run_id;
std::string scenario;
std::string variant;
double print_period_sec{1.0};
int csv_flush_every_n{30};
};
struct MpcPerfSample
{
double stamp_ros{0.0};
long long stamp_steady_ns{0};
bool success{false};
double solve_time_ms{std::numeric_limits<double>::quiet_NaN()};
double cycle_time_ms{std::numeric_limits<double>::quiet_NaN()};
double controller_hz{std::numeric_limits<double>::quiet_NaN()};
double cmd_vx{0.0};
double cmd_vy{0.0};
double cmd_wz{0.0};
double ref_vx{std::numeric_limits<double>::quiet_NaN()};
double ref_vy{std::numeric_limits<double>::quiet_NaN()};
double ref_wz{std::numeric_limits<double>::quiet_NaN()};
};
struct OdomSubWindowStats
{
std::chrono::steady_clock::time_point window_start{};
uint64_t callback_count{0};
double delay_sum_ms{0.0};
double delay_min_ms{std::numeric_limits<double>::infinity()};
double delay_max_ms{0.0};
uint64_t delay_count{0};
};
class MpcPerformanceMonitor
{
public:
MpcPerformanceMonitor() = default;
~MpcPerformanceMonitor();
void configure(const MpcPerformanceConfig & config, rclcpp::Logger logger);
void close();
bool enabled() const;
bool detailedCsvEnabled() const;
bool printEnabled() const;
void recordMpcSample(const MpcPerfSample & sample);
void recordOdomCallback(
const rclcpp::Time & now,
const builtin_interfaces::msg::Time & stamp);
static long long steadyNowNs();
private:
void writeDetailedHeader();
void writeDetailedRow(const MpcPerfSample & sample);
void maybePrintOdomStats();
void resetOdomWindow(std::chrono::steady_clock::time_point now);
void flushIfNeeded();
static std::string num(double value);
static std::string boolean(bool value);
static std::string sanitize(std::string value);
MpcPerformanceConfig config_{};
rclcpp::Logger logger_{rclcpp::get_logger("MpcPerformanceMonitor")};
std::ofstream detailed_csv_;
int detailed_csv_rows_{0};
OdomSubWindowStats odom_stats_{};
};
} // namespace minco_controller
@@ -0,0 +1,9 @@
<class_libraries>
<library path="minco_controller">
<class type="minco_controller::MincoMpcController" base_class_type="nav2_core::Controller">
<description>
基于 qpOASES 的 Minco MPC 控制器
</description>
</class>
</library>
</class_libraries>
+32
View File
@@ -0,0 +1,32 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>minco_controller</name>
<version>0.0.1</version>
<description>Nav2 Controller plugin: Minco MPC controller based on qpOASES</description>
<maintainer email="[email protected]">TODO</maintainer>
<license>Apache-2.0</license>
<buildtool_depend>ament_cmake</buildtool_depend>
<depend>nav2_common</depend>
<depend>nav2_core</depend>
<depend>nav2_util</depend>
<depend>nav2_costmap_2d</depend>
<depend>rclcpp</depend>
<depend>rclcpp_lifecycle</depend>
<depend>geometry_msgs</depend>
<depend>nav_msgs</depend>
<depend>pluginlib</depend>
<depend>tf2</depend>
<depend>tf2_ros</depend>
<depend>tf2_geometry_msgs</depend>
<depend>ros_interfaces</depend>
<depend>eigen3_cmake_module</depend>
<export>
<build_type>ament_cmake</build_type>
<nav2_core plugin="${prefix}/minco_controller.xml" />
</export>
</package>
@@ -0,0 +1,996 @@
#include "minco_controller/minco_mpc_controller.hpp"
#include "color_text.hpp"
#include "log.hpp"
#include <iostream>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <limits>
#include <optional>
#include <Eigen/Geometry>
#ifdef MINCO_DEBUG
#include <chrono>
#include <iostream>
#endif
#include "nav2_util/node_utils.hpp"
#include "tf2/LinearMath/Matrix3x3.h"
#include "tf2/utils.h"
#include "tf2_geometry_msgs/tf2_geometry_msgs.hpp"
#include "pluginlib/class_list_macros.hpp"
namespace custom_log {
void log_info_line(std::string_view text)
{
std::cout << text;
}
} // namespace custom_log
namespace minco_controller {
MincoMpcController::~MincoMpcController()
{
mpc_perf_monitor_.close();
}
double MincoMpcController::normalizeYaw(double yaw)
{
return std::atan2(std::sin(yaw), std::cos(yaw));
}
void MincoMpcController::configureMpcPerfLogging(
const rclcpp_lifecycle::LifecycleNode::SharedPtr & node)
{
const std::string default_mpc_csv_path = "/tmp/mpc_perf_detailed.csv";
nav2_util::declare_parameter_if_not_declared(
node, name_ + ".performance.enable", rclcpp::ParameterValue(true));
nav2_util::declare_parameter_if_not_declared(
node, name_ + ".performance.print_enable", rclcpp::ParameterValue(true));
nav2_util::declare_parameter_if_not_declared(
node, name_ + ".performance.detailed_csv_enable", rclcpp::ParameterValue(false));
nav2_util::declare_parameter_if_not_declared(
node, name_ + ".performance.odom_sub_debug_enable", rclcpp::ParameterValue(true));
nav2_util::declare_parameter_if_not_declared(
node, name_ + ".performance.print_period_sec", rclcpp::ParameterValue(1.0));
nav2_util::declare_parameter_if_not_declared(
node, name_ + ".performance.csv_flush_every_n", rclcpp::ParameterValue(30));
nav2_util::declare_parameter_if_not_declared(
node, name_ + ".performance.mpc_csv_path", rclcpp::ParameterValue(default_mpc_csv_path));
nav2_util::declare_parameter_if_not_declared(
node, name_ + ".performance.run_id", rclcpp::ParameterValue(""));
nav2_util::declare_parameter_if_not_declared(
node, name_ + ".performance.scenario", rclcpp::ParameterValue(""));
nav2_util::declare_parameter_if_not_declared(
node, name_ + ".performance.variant", rclcpp::ParameterValue(""));
bool performance_enable = true;
bool print_enable = true;
bool detailed_csv_enable = false;
bool odom_sub_debug_enable = true;
double print_period_sec = 1.0;
int csv_flush_every_n = 30;
std::string mpc_csv_path = default_mpc_csv_path;
std::string run_id;
std::string scenario;
std::string variant;
node->get_parameter(name_ + ".performance.enable", performance_enable);
node->get_parameter(name_ + ".performance.print_enable", print_enable);
node->get_parameter(name_ + ".performance.detailed_csv_enable", detailed_csv_enable);
node->get_parameter(name_ + ".performance.odom_sub_debug_enable", odom_sub_debug_enable);
node->get_parameter(name_ + ".performance.print_period_sec", print_period_sec);
node->get_parameter(name_ + ".performance.csv_flush_every_n", csv_flush_every_n);
node->get_parameter(name_ + ".performance.mpc_csv_path", mpc_csv_path);
node->get_parameter(name_ + ".performance.run_id", run_id);
node->get_parameter(name_ + ".performance.scenario", scenario);
node->get_parameter(name_ + ".performance.variant", variant);
MpcPerformanceConfig perf_cfg;
perf_cfg.enable = performance_enable;
perf_cfg.print_enable = print_enable;
perf_cfg.detailed_csv_enable = detailed_csv_enable;
perf_cfg.odom_sub_debug_enable = odom_sub_debug_enable;
perf_cfg.detailed_csv_path = mpc_csv_path;
perf_cfg.run_id = run_id;
perf_cfg.scenario = scenario;
perf_cfg.variant = variant;
perf_cfg.print_period_sec = print_period_sec;
perf_cfg.csv_flush_every_n = csv_flush_every_n;
mpc_perf_monitor_.configure(perf_cfg, logger_);
}
void MincoMpcController::configure(const rclcpp_lifecycle::LifecycleNode::WeakPtr & parent,
std::string name,
std::shared_ptr<tf2_ros::Buffer> tf,
std::shared_ptr<nav2_costmap_2d::Costmap2DROS> costmap_ros)
{
node_ = parent;
name_ = name;
tf_ = tf;
costmap_ros_ = costmap_ros;
auto node = parent.lock();
logger_ = node->get_logger();
global_frame_ = costmap_ros_->getGlobalFrameID();
base_frame_ = costmap_ros_->getBaseFrameID();
configureMpcPerfLogging(node);
// 声明/读取参数
nav2_util::declare_parameter_if_not_declared(node, name + ".dt", rclcpp::ParameterValue(0.05));
nav2_util::declare_parameter_if_not_declared(node, name + ".horizon", rclcpp::ParameterValue(10));
nav2_util::declare_parameter_if_not_declared(
node, name + ".Q", rclcpp::ParameterValue(std::vector<double>{5.0, 5.0, 2.0}));
nav2_util::declare_parameter_if_not_declared(
node, name + ".R", rclcpp::ParameterValue(std::vector<double>{1.0, 1.0, 0.5}));
nav2_util::declare_parameter_if_not_declared(node, name + ".vx_min", rclcpp::ParameterValue(-1.0));
nav2_util::declare_parameter_if_not_declared(node, name + ".vx_max", rclcpp::ParameterValue(1.0));
nav2_util::declare_parameter_if_not_declared(node, name + ".vy_min", rclcpp::ParameterValue(-1.0));
nav2_util::declare_parameter_if_not_declared(node, name + ".vy_max", rclcpp::ParameterValue(1.0));
nav2_util::declare_parameter_if_not_declared(node, name + ".omega_min", rclcpp::ParameterValue(-2.0));
nav2_util::declare_parameter_if_not_declared(node, name + ".omega_max", rclcpp::ParameterValue(2.0));
nav2_util::declare_parameter_if_not_declared(node, name + ".fixed_wz", rclcpp::ParameterValue(0.0));
nav2_util::declare_parameter_if_not_declared(
node, name + ".deadzone_speed_threshold", rclcpp::ParameterValue(0.02));
nav2_util::declare_parameter_if_not_declared(
node, name + ".control_delay_compensation", rclcpp::ParameterValue(0.25));
nav2_util::declare_parameter_if_not_declared(
node, name + ".use_small_gyro_mode", rclcpp::ParameterValue(true));
nav2_util::declare_parameter_if_not_declared(
node, name + ".use_acc_constraints", rclcpp::ParameterValue(false));
nav2_util::declare_parameter_if_not_declared(node, name + ".ax_min", rclcpp::ParameterValue(-2.0));
nav2_util::declare_parameter_if_not_declared(node, name + ".ax_max", rclcpp::ParameterValue(2.0));
nav2_util::declare_parameter_if_not_declared(node, name + ".ay_min", rclcpp::ParameterValue(-2.0));
nav2_util::declare_parameter_if_not_declared(node, name + ".ay_max", rclcpp::ParameterValue(2.0));
nav2_util::declare_parameter_if_not_declared(node, name + ".alpha_min", rclcpp::ParameterValue(-4.0));
nav2_util::declare_parameter_if_not_declared(node, name + ".alpha_max", rclcpp::ParameterValue(4.0));
nav2_util::declare_parameter_if_not_declared(
node, name + ".odom_frame", rclcpp::ParameterValue("camera_init"));
nav2_util::declare_parameter_if_not_declared(node, name + ".map_frame", rclcpp::ParameterValue("map"));
nav2_util::declare_parameter_if_not_declared(node, name + ".lidar_offset_x", rclcpp::ParameterValue(0.0));
nav2_util::declare_parameter_if_not_declared(node, name + ".lidar_offset_y", rclcpp::ParameterValue(0.0));
nav2_util::declare_parameter_if_not_declared(
node, name + ".lidar_roll_offset", rclcpp::ParameterValue(0.0));
double dt = 0.05;
double lookahead_time = 0.5;
node->get_parameter(name + ".dt", dt);
node->get_parameter(name + ".lookahead_time", lookahead_time);
std::vector<double> Qv;
std::vector<double> Rv;
node->get_parameter(name + ".Q", Qv);
node->get_parameter(name + ".R", Rv);
mpc_config_.dt = dt;
mpc_config_.lookahead_time = lookahead_time;
mpc_config_.horizon = static_cast<int>(std::ceil(lookahead_time / dt));
if (Qv.size() == 3) {
mpc_config_.Q = Eigen::Vector3d(Qv[0], Qv[1], Qv[2]);
}
if (Rv.size() == 3) {
mpc_config_.R = Eigen::Vector3d(Rv[0], Rv[1], Rv[2]);
}
node->get_parameter(name + ".vx_min", mpc_config_.vx_min);
node->get_parameter(name + ".vx_max", mpc_config_.vx_max);
node->get_parameter(name + ".vy_min", mpc_config_.vy_min);
node->get_parameter(name + ".vy_max", mpc_config_.vy_max);
node->get_parameter(name + ".omega_min", mpc_config_.omega_min);
node->get_parameter(name + ".omega_max", mpc_config_.omega_max);
node->get_parameter(name + ".fixed_wz", fixed_wz_);
node->get_parameter(name + ".deadzone_speed_threshold", deadzone_speed_threshold_);
node->get_parameter(name + ".control_delay_compensation", control_delay_compensation_);
node->get_parameter(name + ".use_small_gyro_mode", use_small_gyro_mode_);
node->get_parameter(name + ".use_acc_constraints", mpc_config_.use_acc_constraints);
node->get_parameter(name + ".ax_min", mpc_config_.ax_min);
node->get_parameter(name + ".ax_max", mpc_config_.ax_max);
node->get_parameter(name + ".ay_min", mpc_config_.ay_min);
node->get_parameter(name + ".ay_max", mpc_config_.ay_max);
node->get_parameter(name + ".alpha_min", mpc_config_.alpha_min);
node->get_parameter(name + ".alpha_max", mpc_config_.alpha_max);
node->get_parameter(name + ".odom_frame", odom_frame_);
node->get_parameter(name + ".map_frame", map_frame_);
node->get_parameter(name + ".lidar_offset_x", lidar_offset_x_);
node->get_parameter(name + ".lidar_offset_y", lidar_offset_y_);
node->get_parameter(name + ".lidar_roll_offset", lidar_roll_offset_);
solver_ = std::make_unique<MpcSolver>(mpc_config_);
// 订阅优化轨迹:/opt_path
opt_path_sub_ = node->create_subscription<ros_interfaces::msg::MpcPositionCommand>("/opt_path",
rclcpp::SystemDefaultsQoS(),
std::bind(&MincoMpcController::onOptPath, this, std::placeholders::_1));
// 订阅里程计:用于延迟补偿和mpc输入状态
auto odom_qos = rclcpp::QoS(rclcpp::KeepLast(1)).best_effort().durability_volatile();
odom_sub_ = node->create_subscription<nav_msgs::msg::Odometry>("/aft_mapped_to_init",
odom_qos,
std::bind(&MincoMpcController::onOdom, this, std::placeholders::_1));
mpc_predict_path_pub_ = node->create_publisher<nav_msgs::msg::Path>("/mpc_predict_path", 1);
mpc_real_path_pub_ = node->create_publisher<nav_msgs::msg::Path>("/mpc_real_path", 1);
cmd_vel_mpc_pub_ = node->create_publisher<geometry_msgs::msg::Twist>("/cmd_vel_mpc", 1);
real_path_history_.clear();
last_real_path_pub_time_ = node->now();
RCLCPP_INFO(logger_,
"%s: MincoMpcController configured (dt=%.3f, lookahead_time=%.3f, deadzone=%.3f, delay_comp=%.3f, "
"small_gyro=%s, fixed_wz=%.3f, lidar_offset_x=%.3f, lidar_offset_y=%.3f, lidar_roll_offset=%.3f)",
name_.c_str(),
dt,
lookahead_time,
deadzone_speed_threshold_,
control_delay_compensation_,
use_small_gyro_mode_ ? "true" : "false",
fixed_wz_,
lidar_offset_x_,
lidar_offset_y_,
lidar_roll_offset_);
}
void MincoMpcController::compensateLeverArm(double v_lidar_x,
double v_lidar_y,
double omega_z,
double yaw,
double & vx_global,
double & vy_global,
double & omega_global) const
{
const double v_body_x = v_lidar_x + omega_z * lidar_offset_y_;
const double v_body_y = v_lidar_y - omega_z * lidar_offset_x_;
const double cos_yaw = std::cos(yaw);
const double sin_yaw = std::sin(yaw);
vx_global = v_body_x * cos_yaw - v_body_y * sin_yaw;
vy_global = v_body_x * sin_yaw + v_body_y * cos_yaw;
omega_global = omega_z;
// std::cout << "Raw velocities: vx_lidar=" << v_lidar_x << ", vy_lidar=" << v_lidar_y
// << ", omega_z=" << omega_z << ", yaw=" << yaw << std::endl;
// std::cout << "Compensated velocities: vx_global=" << vx_global << ", vy_global=" << vy_global
// << ", omega_global=" << omega_global << std::endl;
}
void MincoMpcController::extractGlobalVelocityAndYaw(const nav_msgs::msg::Odometry::SharedPtr & odom,
double & vx_global,
double & vy_global,
double & omega_global,
double & yaw_global) const
{
// 1. 提取 3D 体轴速度 (IMU 物理中心的局部速度)
Eigen::Vector3d v_body_imu(
odom->twist.twist.linear.x, odom->twist.twist.linear.y, odom->twist.twist.linear.z);
// 2. 提取全量 3D 姿态四元数
Eigen::Quaterniond q(odom->pose.pose.orientation.w,
odom->pose.pose.orientation.x,
odom->pose.pose.orientation.y,
odom->pose.pose.orientation.z);
// 3. 3D 旋转:将倾斜机体系下的速度无损映射回与地面平行的全局系
Eigen::Vector3d v_imu_global = q * v_body_imu;
// 4. 提取角速度与 Yaw 角
omega_global = odom->twist.twist.angular.z;
yaw_global = tf2::getYaw(odom->pose.pose.orientation);
// 5. 计算全局杆臂补偿 (将底盘水平安装偏置旋转到全局系)
double offset_global_x = std::cos(yaw_global) * lidar_offset_x_ - std::sin(yaw_global) * lidar_offset_y_;
double offset_global_y = std::sin(yaw_global) * lidar_offset_x_ + std::cos(yaw_global) * lidar_offset_y_;
// 6. 计算底盘旋转中心的全局速度
vx_global = v_imu_global.x() + omega_global * offset_global_y;
vy_global = v_imu_global.y() - omega_global * offset_global_x;
}
void MincoMpcController::cleanup()
{
mpc_perf_monitor_.close();
opt_path_sub_.reset();
odom_sub_.reset();
mpc_predict_path_pub_.reset();
mpc_real_path_pub_.reset();
cmd_vel_mpc_pub_.reset();
solver_.reset();
std::lock_guard<std::mutex> lk(data_mtx_);
latest_opt_path_.reset();
latest_odom_.reset();
}
void MincoMpcController::activate()
{
}
void MincoMpcController::deactivate()
{
}
void MincoMpcController::setPlan(const nav_msgs::msg::Path & path)
{
std::lock_guard<std::mutex> lk(plan_mtx_);
global_plan_ = path;
}
void MincoMpcController::setSpeedLimit(const double & speed_limit, const bool & percentage)
{
speed_limit_ = speed_limit;
speed_limit_percentage_ = percentage;
}
void MincoMpcController::onOptPath(const ros_interfaces::msg::MpcPositionCommand::SharedPtr msg)
{
std::lock_guard<std::mutex> lk(data_mtx_);
const uint32_t new_traj_id = (msg && !msg->cmds.empty()) ? msg->cmds.front().trajectory_id : 0u;
const uint32_t old_traj_id = (latest_opt_path_ && !latest_opt_path_->cmds.empty())
? latest_opt_path_->cmds.front().trajectory_id
: 0u;
// 仅在轨迹 ID 切换时重置跟踪状态;同一轨迹重复发布(更新时间戳)不重置
if (new_traj_id != old_traj_id) {
has_tracked_ref_ = false;
}
latest_opt_path_ = msg;
}
void MincoMpcController::onOdom(const nav_msgs::msg::Odometry::SharedPtr msg)
{
auto node = node_.lock();
if (node && msg) {
mpc_perf_monitor_.recordOdomCallback(node->now(), msg->header.stamp);
}
std::lock_guard<std::mutex> lk(data_mtx_);
latest_odom_ = msg;
}
bool MincoMpcController::transformPathToOdom(const ros_interfaces::msg::MpcPositionCommand::SharedPtr & opt,
std::vector<ros_interfaces::msg::PositionCommand> & out_cmds) const
{
std::string source_frame = opt->header.frame_id;
if (source_frame.empty()) {
source_frame = map_frame_;
auto node_ptr = node_.lock();
if (node_ptr) {
RCLCPP_WARN_THROTTLE(logger_,
*node_ptr->get_clock(),
10000,
"Received opt_path with empty frame_id, defaulting to '%s'",
source_frame.c_str());
}
}
// 从costmap获取全局坐标系,优先使用global_frame_,如果未设置则退回到odom_frame_
std::string target_frame = global_frame_;
if (target_frame.empty()) {
target_frame = odom_frame_;
}
if (source_frame == target_frame) {
out_cmds = opt->cmds;
return true;
}
// 如果坐标系不同,尝试进行转换
try {
geometry_msgs::msg::TransformStamped transform =
tf_->lookupTransform(target_frame, source_frame, tf2::TimePointZero);
out_cmds = opt->cmds;
for (auto & cmd : out_cmds) {
// Transform position
geometry_msgs::msg::PointStamped p_in, p_out;
p_in.header.frame_id = source_frame;
p_in.point = cmd.position;
tf2::doTransform(p_in, p_out, transform);
cmd.position = p_out.point;
// Transform velocity (vector)
geometry_msgs::msg::Vector3Stamped v_in, v_out;
v_in.header.frame_id = source_frame;
v_in.vector = cmd.velocity;
tf2::doTransform(v_in, v_out, transform);
cmd.velocity = v_out.vector;
// Transform acceleration (vector)
geometry_msgs::msg::Vector3Stamped a_in, a_out;
a_in.header.frame_id = source_frame;
a_in.vector = cmd.acceleration;
tf2::doTransform(a_in, a_out, transform);
cmd.acceleration = a_out.vector;
// Transform jerk (vector)
geometry_msgs::msg::Vector3Stamped j_in, j_out;
j_in.header.frame_id = source_frame;
j_in.vector = cmd.jerk;
tf2::doTransform(j_in, j_out, transform);
cmd.jerk = j_out.vector;
// Transform yaw
double yaw_diff = tf2::getYaw(transform.transform.rotation);
cmd.yaw = normalizeYaw(cmd.yaw + yaw_diff);
}
} catch (tf2::TransformException & ex) {
return false;
}
return true;
}
bool MincoMpcController::buildReferenceFromOptPath(
const State & curr, std::vector<ReferencePoint> & out_ref) const
{
auto node = node_.lock();
if (!node) {
return false;
}
const rclcpp::Time now = node->now();
// 获取最新的优化轨迹和里程计数据,以及当前跟踪状态(索引、时间戳、轨迹ID)
ros_interfaces::msg::MpcPositionCommand::SharedPtr opt;
double tracked_ref_idx = 0.0;
rclcpp::Time tracked_ref_time;
uint32_t tracked_opt_traj_id = 0u;
bool has_tracked_ref = false;
{
std::lock_guard<std::mutex> lk(data_mtx_);
opt = latest_opt_path_;
tracked_ref_idx = tracked_ref_idx_;
tracked_ref_time = tracked_ref_time_;
tracked_opt_traj_id = tracked_opt_traj_id_;
has_tracked_ref = has_tracked_ref_;
}
if (!opt || opt->cmds.empty()) {
return false;
}
// 坐标系转换处理
std::vector<ros_interfaces::msg::PositionCommand> cmds;
if (!transformPathToOdom(opt, cmds)) {
return false;
}
const size_t n_cmds = cmds.size();
const double planner_dt = 1.0 / mpc_config_.planner_freq;
if (planner_dt <= 1.0e-6) {
return false;
}
// 最近点搜索(基于最小欧式距离),并计算更精确的最近点投影索引
size_t best_idx = 0;
double best_d2 = std::numeric_limits<double>::infinity();
for (size_t i = 0; i < n_cmds; ++i) {
const double dx = cmds[i].position.x - curr.x;
const double dy = cmds[i].position.y - curr.y;
const double d2 = dx * dx + dy * dy;
if (d2 < best_d2) {
best_d2 = d2;
best_idx = i;
}
}
double nearest_idx_float = static_cast<double>(best_idx);
if (best_idx < n_cmds - 1) {
const auto & p_curr = cmds[best_idx];
const auto & p_next = cmds[best_idx + 1];
Eigen::Vector2d a_vec(p_next.position.x - p_curr.position.x, p_next.position.y - p_curr.position.y);
Eigen::Vector2d b_vec(curr.x - p_curr.position.x, curr.y - p_curr.position.y);
double len_sq = a_vec.squaredNorm();
if (len_sq > 1e-6) {
double projection = a_vec.dot(b_vec) / len_sq;
if (projection > -0.5 && projection < 1.0) {
nearest_idx_float += projection;
}
}
}
nearest_idx_float = std::max(0.0, nearest_idx_float);
const uint32_t current_traj_id = (!opt->cmds.empty()) ? opt->cmds.front().trajectory_id : 0u;
// 轨迹未更新时,按时间持续向前推进参考索引,且不允许回退
// const bool same_opt_traj = has_tracked_ref && tracked_opt_traj_id == current_traj_id;
// double progress_idx_float = nearest_idx_float;
// if (same_opt_traj) {
// double dt_pass = (now - tracked_ref_time).seconds();
// dt_pass = std::max(0.0, dt_pass);
// progress_idx_float = tracked_ref_idx + dt_pass / planner_dt;
// }
// double current_idx_float = std::max(nearest_idx_float, progress_idx_float);
// // 同一条轨迹若超过阈值仍未更新,判定规划器卡死
// const double traj_stamp_sec =
// static_cast<double>(opt->header.stamp.sec) + static_cast<double>(opt->header.stamp.nanosec) * 1.0e-9;
// const double absolute_age = now.seconds() - traj_stamp_sec;
// if (same_opt_traj && absolute_age > 0.5) {
// return false;
// }
double current_idx_float = nearest_idx_float;
current_idx_float = std::min(current_idx_float, static_cast<double>(n_cmds - 1));
{
std::lock_guard<std::mutex> lk(data_mtx_);
tracked_ref_idx_ = current_idx_float;
tracked_ref_time_ = now;
tracked_opt_traj_id_ = current_traj_id;
has_tracked_ref_ = true;
}
double current_traj_time = current_idx_float * planner_dt;
// 让 MPC 始终去追踪未来一段时间的参考点,用于控制延迟补偿
double control_delay = control_delay_compensation_;
current_traj_time += control_delay;
const int N = mpc_config_.horizon;
const double mpc_dt = mpc_config_.dt;
out_ref.clear();
out_ref.reserve(static_cast<size_t>(N));
for (int k = 0; k < N; ++k) {
double target_time = current_traj_time + k * mpc_dt;
double target_idx_float = target_time / planner_dt;
if (target_idx_float < 0.0)
target_idx_float = 0.0;
if (target_idx_float > static_cast<double>(n_cmds - 1)) {
target_idx_float = static_cast<double>(n_cmds - 1);
}
size_t target_idx = static_cast<size_t>(std::floor(target_idx_float));
size_t next_idx = target_idx + 1;
double alpha = target_idx_float - static_cast<double>(target_idx);
ReferencePoint rp;
if (next_idx < n_cmds) {
// 二次前馈插值(泰勒展开),使用 P/V/A/J 进行插值,补偿控制延迟带来的误差。
const double dt = std::max(0.0, std::min(planner_dt, alpha * planner_dt));
const double dt2 = dt * dt;
const double dt3 = dt2 * dt;
const Eigen::Vector2d p_i(cmds[target_idx].position.x, cmds[target_idx].position.y);
const Eigen::Vector2d v_i(cmds[target_idx].velocity.x, cmds[target_idx].velocity.y);
const Eigen::Vector2d a_i(cmds[target_idx].acceleration.x, cmds[target_idx].acceleration.y);
const Eigen::Vector2d j_i(cmds[target_idx].jerk.x, cmds[target_idx].jerk.y);
rp.pos = p_i + v_i * dt + 0.5 * a_i * dt2 + (1.0 / 6.0) * j_i * dt3;
rp.vel = v_i + a_i * dt + 0.5 * j_i * dt2;
// 线性角度插值
rp.yaw = interpolateYaw(cmds[target_idx].yaw, cmds[next_idx].yaw, alpha);
rp.yaw_rate = interpolate(cmds[target_idx].yaw_dot, cmds[next_idx].yaw_dot, alpha);
} else {
const auto & p_end = cmds.back();
rp.pos = Eigen::Vector2d(p_end.position.x, p_end.position.y);
rp.vel = Eigen::Vector2d(0.0, 0.0);
rp.yaw = p_end.yaw;
rp.yaw_rate = 0.0;
}
out_ref.push_back(rp);
}
// 对参考序列的 yaw 进行连续性处理
if (!out_ref.empty()) {
double diff = out_ref[0].yaw - curr.yaw;
// 将 diff 限制在 [-PI, PI]
diff = std::atan2(std::sin(diff), std::cos(diff));
out_ref[0].yaw = curr.yaw + diff;
for (size_t i = 1; i < out_ref.size(); ++i) {
double d_yaw = out_ref[i].yaw - out_ref[i - 1].yaw;
d_yaw = std::atan2(std::sin(d_yaw), std::cos(d_yaw));
out_ref[i].yaw = out_ref[i - 1].yaw + d_yaw;
}
}
return true;
}
void MincoMpcController::applyGravityCompensation(
const nav_msgs::msg::Odometry::SharedPtr & odom, double & vx, double & vy)
{
if (!odom) {
return;
}
tf2::Quaternion q;
tf2::fromMsg(odom->pose.pose.orientation, q);
double roll = 0.0;
double pitch = 0.0;
double yaw = 0.0;
tf2::Matrix3x3(q).getRPY(roll, pitch, yaw);
// std::cout << "Original roll: " << roll << ", pitch: " << pitch << ", yaw: " << yaw << std::endl;
const double true_roll = roll - lidar_roll_offset_;
constexpr double angle_threshold = 0.05;
constexpr double k_gravity_x = 1.0;
constexpr double k_gravity_y = 20.0;
double body_comp_x = 0.0;
double body_comp_y = 0.0;
if (std::abs(pitch) > angle_threshold) {
body_comp_x = k_gravity_x * std::sin(-pitch);
}
if (std::abs(true_roll) > angle_threshold) {
body_comp_y = k_gravity_y * std::sin(std::abs(true_roll));
}
if (body_comp_x == 0.0 && body_comp_y == 0.0) {
return;
}
const double global_comp_x = body_comp_x * std::cos(yaw) - body_comp_y * std::sin(yaw);
const double global_comp_y = body_comp_x * std::sin(yaw) + body_comp_y * std::cos(yaw);
vx += global_comp_x;
vy += global_comp_y;
vx = std::clamp(vx, mpc_config_.vx_min, mpc_config_.vx_max);
vy = std::clamp(vy, mpc_config_.vy_min, mpc_config_.vy_max);
}
geometry_msgs::msg::TwistStamped MincoMpcController::computeVelocityCommands(
const geometry_msgs::msg::PoseStamped & pose,
const geometry_msgs::msg::Twist & velocity,
nav2_core::GoalChecker * goal_checker)
{
const bool record_perf = mpc_perf_monitor_.detailedCsvEnabled();
const auto cycle_start = record_perf ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
auto node = node_.lock();
const rclcpp::Time now = node->now();
std::optional<MpcPerfSample> perf;
if (record_perf) {
perf.emplace();
perf->stamp_ros = now.seconds();
perf->stamp_steady_ns = MpcPerformanceMonitor::steadyNowNs();
}
auto finish = [&](geometry_msgs::msg::TwistStamped out_cmd, bool success, const std::string &) {
if (perf) {
perf->success = success;
perf->cycle_time_ms =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - cycle_start).count();
if (last_mpc_perf_stamp_ns_ > 0 && perf->stamp_steady_ns > last_mpc_perf_stamp_ns_) {
const double dt_sec = static_cast<double>(perf->stamp_steady_ns - last_mpc_perf_stamp_ns_) * 1.0e-9;
if (dt_sec > 1.0e-9) {
perf->controller_hz = 1.0 / dt_sec;
}
}
last_mpc_perf_stamp_ns_ = perf->stamp_steady_ns;
perf->cmd_vx = out_cmd.twist.linear.x;
perf->cmd_vy = out_cmd.twist.linear.y;
perf->cmd_wz = out_cmd.twist.angular.z;
mpc_perf_monitor_.recordMpcSample(*perf);
}
return out_cmd;
};
nav_msgs::msg::Odometry::SharedPtr latest_odom;
{
std::lock_guard<std::mutex> lk(data_mtx_);
latest_odom = latest_odom_;
}
// 1) 构造当前状态(基于 pose + 最新里程计速度,用于延迟补偿)
State curr;
curr.x = pose.pose.position.x;
curr.y = pose.pose.position.y;
curr.yaw = normalizeYaw(tf2::getYaw(pose.pose.orientation));
if (latest_odom) {
double vx = latest_odom->twist.twist.linear.x;
double vy = latest_odom->twist.twist.linear.y;
double omega = latest_odom->twist.twist.angular.z;
double yaw = normalizeYaw(tf2::getYaw(latest_odom->pose.pose.orientation));
// extractGlobalVelocityAndYaw(latest_odom, vx, vy, omega, yaw);
compensateLeverArm(vx, vy, omega, yaw, curr.vx, curr.vy, curr.omega);
// curr.yaw = normalizeYaw(yaw);
// curr.vx = vx;
// curr.vy = vy;
// curr.omega = omega;
const double noise_threshold = 0.03;
if (std::abs(curr.vx) < noise_threshold) {
curr.vx = 0.0;
}
if (std::abs(curr.vy) < noise_threshold) {
curr.vy = 0.0;
}
if (std::abs(curr.omega) < noise_threshold) {
curr.omega = 0.0;
}
} else {
curr.vx = 0.0;
curr.vy = 0.0;
curr.omega = 0.0;
}
geometry_msgs::msg::TwistStamped cmd;
cmd.header.stamp = now;
cmd.header.frame_id = global_frame_;
// Sync Nav2 success semantics: if GoalChecker says reached, output zero command immediately.
if (goal_checker != nullptr) {
geometry_msgs::msg::PoseStamped goal_pose;
bool has_goal_pose = false;
{
std::lock_guard<std::mutex> lk(plan_mtx_);
if (!global_plan_.poses.empty()) {
goal_pose = global_plan_.poses.back();
has_goal_pose = true;
}
}
if (has_goal_pose && goal_checker->isGoalReached(pose.pose, goal_pose.pose, velocity)) {
std::lock_guard<std::mutex> lk(data_mtx_);
has_tracked_ref_ = false;
latest_opt_path_.reset();
cmd.twist.linear.x = 0.0;
cmd.twist.linear.y = 0.0;
cmd.twist.angular.z = 0.0;
return finish(cmd, true, "NONE");
}
}
if (control_delay_compensation_ > 1e-3) {
curr.x += curr.vx * control_delay_compensation_;
curr.y += curr.vy * control_delay_compensation_;
curr.yaw += curr.omega * control_delay_compensation_;
curr.yaw = normalizeYaw(curr.yaw);
}
// 2) 构造参考序列:优先 /opt_path
std::vector<ReferencePoint> ref;
bool ok_ref = buildReferenceFromOptPath(curr, ref);
if (!ok_ref || !solver_) {
// 无参考则输出 0
cmd.twist.linear.x = 0.0;
cmd.twist.linear.y = 0.0;
cmd.twist.angular.z = 0.0;
return finish(cmd, false, ok_ref ? "SOLVER_UNAVAILABLE" : "NO_REFERENCE");
}
if (perf && !ref.empty()) {
perf->ref_vx = ref.front().vel.x();
perf->ref_vy = ref.front().vel.y();
perf->ref_wz = ref.front().yaw_rate;
}
// 3) 调用 MPC 求解(输出 global_frame_ 系速度,此处为 camera_init)
Control u_global;
std::vector<State> pred_states;
const auto solve_start = record_perf ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
#ifdef MINCO_DEBUG
auto t_start = std::chrono::high_resolution_clock::now();
#endif
bool success = solver_->solve(curr, ref, u_global, &pred_states);
if (perf) {
perf->solve_time_ms =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - solve_start).count();
}
publishVisualization(pred_states, curr);
#ifdef MINCO_DEBUG
auto t_end = std::chrono::high_resolution_clock::now();
if (success && !ref.empty()) {
double dt_ms = std::chrono::duration<double, std::milli>(t_end - t_start).count();
double plan_vx = u_global.vx;
double plan_vy = u_global.vy;
double ref_vx = ref[0].vel.x();
double ref_vy = ref[0].vel.y();
double v_err_x = plan_vx - ref_vx;
double v_err_y = plan_vy - ref_vy;
double curr_x = curr.x;
double curr_y = curr.y;
double ref_x = ref[0].pos.x();
double ref_y = ref[0].pos.y();
double p_err_x = curr_x - ref_x;
double p_err_y = curr_y - ref_y;
custom_log::log_block(std::string("\033[34m[MincoMpc] "),
NV(plan_vx),
NV(plan_vy),
NV(ref_vx),
NV(ref_vy),
NV(v_err_x),
NV(v_err_y),
NV(curr_x),
NV(curr_y),
NV(ref_x),
NV(ref_y),
NV(p_err_x),
NV(p_err_y),
NV(dt_ms));
}
#endif
if (!success) {
std::cout << color_text::RED << "[MincoMpc] Solver Failed!" << color_text::RESET << std::endl;
// Debug info for failure
if (!ref.empty()) {
std::cout << "[MincoMpc] Ref Size: " << ref.size() << std::endl;
std::cout << "[MincoMpc] Curr: " << curr.x << ", " << curr.y << ", " << curr.yaw << std::endl;
std::cout << "[MincoMpc] Ref[0]: " << ref[0].pos.x() << ", " << ref[0].pos.y() << ", " << ref[0].yaw
<< std::endl;
}
cmd.twist.linear.x = 0.0;
cmd.twist.linear.y = 0.0;
cmd.twist.angular.z = 0.0;
return finish(cmd, false, "QP_FAILED");
}
// 5) 直接下发全局坐标系速度
double vx_mpc = u_global.vx;
double vy_mpc = u_global.vy;
double wz = fixed_wz_;
// 小陀螺模式:当启用时,始终输出固定的旋转速度,而不使用 MPC 输出的角速度。
if (!use_small_gyro_mode_) {
wz = std::min(mpc_config_.omega_max, std::max(mpc_config_.omega_min, u_global.omega));
}
double output_delay = 0.025;
double phase_delay = curr.omega * output_delay;
double cos_phase = std::cos(phase_delay);
double sin_phase = std::sin(phase_delay);
double vx = cos_phase * vx_mpc + sin_phase * vy_mpc;
double vy = -sin_phase * vx_mpc + cos_phase * vy_mpc;
// 5) 处理 Nav2 setSpeedLimit
if (speed_limit_ > 1e-6) {
const double v_norm = std::hypot(vx, vy);
if (v_norm > 1e-6) {
double scale = 1.0;
if (speed_limit_percentage_) {
scale = std::clamp(speed_limit_ / 100.0, 0.0, 1.0);
} else {
scale = std::min(1.0, speed_limit_ / v_norm);
}
vx *= scale;
vy *= scale;
}
}
// 6) 死区截断
const double deadzone = deadzone_speed_threshold_;
if (std::hypot(vx, vy) < deadzone) {
vx = 0.0;
vy = 0.0;
}
constexpr double goal_pos_threshold = 0.3;
bool stop_mpc_cmd = false;
geometry_msgs::msg::PoseStamped goal_pose_stamped;
{
std::lock_guard<std::mutex> lk(plan_mtx_);
if (!global_plan_.poses.empty()) {
goal_pose_stamped = global_plan_.poses.back();
}
}
if (!goal_pose_stamped.header.frame_id.empty()) {
geometry_msgs::msg::PoseStamped goal_pose_in_odom = goal_pose_stamped;
if (goal_pose_in_odom.header.frame_id != odom_frame_) {
try {
goal_pose_in_odom = tf_->transform(goal_pose_in_odom, odom_frame_);
} catch (const tf2::TransformException &) {
goal_pose_in_odom.header.frame_id.clear();
}
}
if (!goal_pose_in_odom.header.frame_id.empty()) {
const double dx = pose.pose.position.x - goal_pose_in_odom.pose.position.x;
const double dy = pose.pose.position.y - goal_pose_in_odom.pose.position.y;
const double dist = std::hypot(dx, dy);
stop_mpc_cmd = (dist <= goal_pos_threshold);
}
}
if (cmd_vel_mpc_pub_) {
geometry_msgs::msg::Twist raw_cmd;
raw_cmd.linear.x = stop_mpc_cmd ? 0.0 : vx;
raw_cmd.linear.y = stop_mpc_cmd ? 0.0 : vy;
raw_cmd.angular.z = stop_mpc_cmd ? 0.0 : wz;
cmd_vel_mpc_pub_->publish(raw_cmd);
}
// applyGravityCompensation(latest_odom, vx, vy);
cmd.twist.linear.x = vx;
cmd.twist.linear.y = vy;
cmd.twist.angular.z = wz;
return finish(cmd, true, "NONE");
}
void MincoMpcController::publishVisualization(
const std::vector<State> & pred_path, const State & curr_state)
{
auto node = node_.lock();
if (!node)
return;
rclcpp::Time now = node->now();
// 1. 发布预测路径
if (mpc_predict_path_pub_ && mpc_predict_path_pub_->get_subscription_count() > 0 && !pred_path.empty()) {
nav_msgs::msg::Path path_msg;
path_msg.header.stamp = now;
path_msg.header.frame_id = global_frame_;
for (const auto & s : pred_path) {
geometry_msgs::msg::PoseStamped ps;
ps.header = path_msg.header;
ps.pose.position.x = s.x;
ps.pose.position.y = s.y;
ps.pose.position.z = 0.0;
tf2::Quaternion q;
q.setRPY(0, 0, s.yaw);
ps.pose.orientation = tf2::toMsg(q);
path_msg.poses.push_back(ps);
}
mpc_predict_path_pub_->publish(path_msg);
}
// 2. 发布实际路径
geometry_msgs::msg::PoseStamped ps;
ps.header.stamp = now;
ps.header.frame_id = global_frame_;
ps.pose.position.x = curr_state.x;
ps.pose.position.y = curr_state.y;
ps.pose.position.z = 0.0;
tf2::Quaternion q;
q.setRPY(0, 0, curr_state.yaw);
ps.pose.orientation = tf2::toMsg(q);
if (real_path_history_.empty()) {
real_path_history_.push_back(ps);
} else {
const auto & last = real_path_history_.back();
double dist =
std::hypot(last.pose.position.x - ps.pose.position.x, last.pose.position.y - ps.pose.position.y);
// 简单的距离过滤,避免原地不动时数据堆积
if (dist > 0.02) {
real_path_history_.push_back(ps);
}
}
// 保持历史长度
if (real_path_history_.size() > 5000) {
size_t remove_count = real_path_history_.size() - 5000;
real_path_history_.erase(real_path_history_.begin(), real_path_history_.begin() + remove_count);
}
if (mpc_real_path_pub_ && mpc_real_path_pub_->get_subscription_count() > 0) {
// 降频发布:1.0 Hz
if ((now - last_real_path_pub_time_).seconds() > 1.0) {
nav_msgs::msg::Path path_msg;
path_msg.header.stamp = now;
path_msg.header.frame_id = global_frame_;
// 如果历史太长,可以只发布最近的一部分,或者对历史进行下采样(本例直接发布全部,但频率低)
path_msg.poses = real_path_history_;
mpc_real_path_pub_->publish(path_msg);
last_real_path_pub_time_ = now;
}
}
}
} // namespace minco_controller
PLUGINLIB_EXPORT_CLASS(minco_controller::MincoMpcController, nav2_core::Controller)
@@ -0,0 +1,357 @@
#include "minco_controller/mpc_solver.hpp"
#include <algorithm>
#include <cmath>
#include <iostream>
#include <limits>
#include <vector>
#include "color_text.hpp"
#include <qpOASES.hpp>
namespace minco_controller {
MpcSolver::MpcSolver(const MPCConfig & config) : config_(config)
{
}
void MpcSolver::setConfig(const MPCConfig & config)
{
config_ = config;
}
void MpcSolver::buildStepModel(
double /*yaw_ref*/, Eigen::Matrix3d & A, Eigen::Matrix<double, 3, 3> & B) const
{
A.setIdentity();
B.setZero();
// 纯全局坐标系控制,解耦 X, Y, Yaw
B(0, 0) = config_.dt;
B(1, 1) = config_.dt;
B(2, 2) = config_.dt;
}
bool MpcSolver::buildCondensedQP(const State & curr,
const std::vector<ReferencePoint> & ref_traj,
Eigen::MatrixXd & H,
Eigen::VectorXd & g,
Eigen::VectorXd & lb,
Eigen::VectorXd & ub,
Eigen::MatrixXd & A_con,
Eigen::VectorXd & lbA,
Eigen::VectorXd & ubA)
{
const int N = config_.horizon;
if (N <= 0) {
return false;
}
if (static_cast<int>(ref_traj.size()) < N) {
return false;
}
// 构建堆叠模型 X = A_hat x0 + B_hat U
// 其中nx,nu 分别为单步状态与控制量维度,nX,nU 为堆叠后维度
const int nx = 3;
const int nu = 3;
const int nU = nu * N;
const int nX = nx * N;
// 堆叠状态:X = [x1..xN, y1..yN, yaw1..yawN]
// X = [x1,y1,yaw1, x2,y2,yaw2, ..., xN,yN,yawN]^T
// X = A_hat * x0 + B_hat * U
Eigen::MatrixXd A_hat = Eigen::MatrixXd::Zero(nX, nx);
Eigen::MatrixXd B_hat = Eigen::MatrixXd::Zero(nX, nU);
Eigen::Matrix3d A = Eigen::Matrix3d::Identity();
for (int i = 0; i < N; ++i) {
Eigen::Matrix<double, 3, 3> Bi;
buildStepModel(ref_traj[i].yaw, A, Bi);
// A_hat block: A^{i+1}
Eigen::Matrix3d A_power = Eigen::Matrix3d::Identity();
for (int p = 0; p < i + 1; ++p) {
A_power = A * A_power;
}
A_hat.block<3, 3>(i * nx, 0) = A_power;
// B_hat: 影响 x_{i+1} 的所有 u_0..u_i
for (int j = 0; j <= i; ++j) {
// 由于 A=I,这里仍按通用形式写:A^{i-j} * B_j
Eigen::Matrix3d A_ij = Eigen::Matrix3d::Identity();
for (int p = 0; p < i - j; ++p) {
A_ij = A * A_ij;
}
Eigen::Matrix<double, 3, 3> Bj;
buildStepModel(ref_traj[j].yaw, A, Bj);
B_hat.block<3, 3>(i * nx, j * nu) = A_ij * Bj;
}
}
// 参考状态堆叠 X_ref
Eigen::VectorXd X_ref = Eigen::VectorXd::Zero(nX);
for (int i = 0; i < N; ++i) {
X_ref(i * nx + 0) = ref_traj[i].pos.x();
X_ref(i * nx + 1) = ref_traj[i].pos.y();
X_ref(i * nx + 2) = ref_traj[i].yaw;
}
// 参考控制堆叠 U_ref (直接使用全局速度)
Eigen::VectorXd U_ref = Eigen::VectorXd::Zero(nU);
for (int i = 0; i < N; ++i) {
U_ref(i * nu + 0) = ref_traj[i].vel.x();
U_ref(i * nu + 1) = ref_traj[i].vel.y();
U_ref(i * nu + 2) = ref_traj[i].yaw_rate;
}
// Q_bar / R_bar (对角块)
// P1: Rotate Q at each horizon step to decompose tracking penalty
// into along-track (heading direction) and cross-track (perpendicular).
// Higher cross-track weight enforces precision on curves/narrow passages.
Eigen::MatrixXd Q_bar = Eigen::MatrixXd::Zero(nX, nX);
Eigen::MatrixXd R_bar = Eigen::MatrixXd::Zero(nU, nU);
for (int i = 0; i < N; ++i) {
const double yaw_ref = ref_traj[i].yaw;
const double c = std::cos(yaw_ref);
const double s = std::sin(yaw_ref);
// Q_xy = R^T * diag(q_along, q_cross) * R (R is 2D rotation by yaw_ref)
// R = [c, -s; s, c], so:
// Q_xy = [c*q_along*c + s*q_cross*s, c*q_along*(-s) + s*q_cross*c;
// (-s)*q_along*c + c*q_cross*s, (-s)*q_along*(-s) + c*q_cross*c]
const double qa = config_.q_along;
const double qc = config_.q_cross;
Q_bar(i * nx + 0, i * nx + 0) = qa * c * c + qc * s * s;
Q_bar(i * nx + 0, i * nx + 1) = (qc - qa) * c * s;
Q_bar(i * nx + 1, i * nx + 0) = (qc - qa) * c * s;
Q_bar(i * nx + 1, i * nx + 1) = qa * s * s + qc * c * c;
Q_bar(i * nx + 2, i * nx + 2) = config_.Q.z(); // yaw weight unchanged
R_bar.block<3, 3>(i * nu, i * nu) = config_.R.asDiagonal();
}
// d = A_hat * x0 - X_ref
Eigen::Vector3d x0(curr.x, curr.y, curr.yaw);
const Eigen::VectorXd d = A_hat * x0 - X_ref;
// H = 2*(B^T Q B + R)
H = 2.0 * (B_hat.transpose() * Q_bar * B_hat + R_bar);
// 数值正则(避免 Hessian 奇异)
H += config_.eps_regularization * Eigen::MatrixXd::Identity(nU, nU);
// g = 2*(B^T Q d - R U_ref)
g = 2.0 * (B_hat.transpose() * Q_bar * d - R_bar * U_ref);
// 变量边界(速度约束,map/global 系)
// Use -1e12 instead of -inf: qpOASES defines INFTY=1e20 internally.
// IEEE -inf causes NaN in active-set arithmetic.
lb = Eigen::VectorXd::Constant(nU, -1.0e12);
ub = Eigen::VectorXd::Constant(nU, 1.0e12);
for (int i = 0; i < N; ++i) {
lb(i * nu + 0) = config_.vx_min;
ub(i * nu + 0) = config_.vx_max;
lb(i * nu + 1) = config_.vy_min;
ub(i * nu + 1) = config_.vy_max;
lb(i * nu + 2) = config_.omega_min;
ub(i * nu + 2) = config_.omega_max;
}
// 加速度约束(可选):a_min <= (v_k - v_{k-1})/dt <= a_max
if (!config_.use_acc_constraints) {
A_con.resize(0, 0);
lbA.resize(0);
ubA.resize(0);
return true;
}
const int nC = 3 * N; // 对每个 k 对每个轴各一个差分约束:v_k - v_{k-1}
A_con = Eigen::MatrixXd::Zero(nC, nU);
lbA = Eigen::VectorXd::Zero(nC);
ubA = Eigen::VectorXd::Zero(nC);
const double last_vx = last_u_global_.x();
const double last_vy = last_u_global_.y();
const double last_w = last_u_global_.z();
// 约束形式:lbA <= A_con * U <= ubA
// 这里 A_con * U 直接表示 (v_k - v_{k-1}),再用 bounds 限制到 [a_min*dt, a_max*dt]
for (int k = 0; k < N; ++k) {
for (int axis = 0; axis < 3; ++axis) {
const int row = k * 3 + axis;
const int col_curr = k * 3 + axis;
A_con(row, col_curr) = 1.0;
if (k == 0) {
// v0 - v(-1)
// v(-1) 使用当前时刻真实全局速度作为已知常数,转移到 bounds:
// a_min*dt <= v0 - v_curr_global <= a_max*dt
const double last = (axis == 0 ? last_vx : (axis == 1 ? last_vy : last_w));
lbA(row) =
(axis == 0 ? config_.ax_min : (axis == 1 ? config_.ay_min : config_.alpha_min)) * config_.dt +
last;
ubA(row) =
(axis == 0 ? config_.ax_max : (axis == 1 ? config_.ay_max : config_.alpha_max)) * config_.dt +
last;
} else {
const int col_prev = (k - 1) * 3 + axis;
A_con(row, col_prev) = -1.0;
lbA(row) =
(axis == 0 ? config_.ax_min : (axis == 1 ? config_.ay_min : config_.alpha_min)) * config_.dt;
ubA(row) =
(axis == 0 ? config_.ax_max : (axis == 1 ? config_.ay_max : config_.alpha_max)) * config_.dt;
}
}
}
return true;
}
bool MpcSolver::solve(const State & curr,
const std::vector<ReferencePoint> & ref_traj,
Control & out_u,
std::vector<State> * out_pred)
{
const int N = config_.horizon;
if (N <= 0) {
return false;
}
if (static_cast<int>(ref_traj.size()) < N) {
return false;
}
Eigen::MatrixXd H;
Eigen::VectorXd g;
Eigen::VectorXd lb;
Eigen::VectorXd ub;
Eigen::MatrixXd A_con;
Eigen::VectorXd lbA;
Eigen::VectorXd ubA;
if (!buildCondensedQP(curr, ref_traj, H, g, lb, ub, A_con, lbA, ubA)) {
return false;
}
const int nV = static_cast<int>(g.size());
const int nC = static_cast<int>(lbA.size());
std::vector<qpOASES::real_t> H_qp(static_cast<size_t>(nV) * static_cast<size_t>(nV), 0.0);
for (int i = 0; i < nV; ++i) {
for (int j = 0; j < nV; ++j) {
H_qp[static_cast<size_t>(i) * static_cast<size_t>(nV) + static_cast<size_t>(j)] =
static_cast<qpOASES::real_t>(H(i, j));
}
}
std::vector<qpOASES::real_t> g_qp(static_cast<size_t>(nV), 0.0);
std::vector<qpOASES::real_t> lb_qp(static_cast<size_t>(nV), 0.0);
std::vector<qpOASES::real_t> ub_qp(static_cast<size_t>(nV), 0.0);
for (int i = 0; i < nV; ++i) {
g_qp[static_cast<size_t>(i)] = static_cast<qpOASES::real_t>(g(i));
lb_qp[static_cast<size_t>(i)] = static_cast<qpOASES::real_t>(lb(i));
ub_qp[static_cast<size_t>(i)] = static_cast<qpOASES::real_t>(ub(i));
}
std::vector<qpOASES::real_t> A_qp;
std::vector<qpOASES::real_t> lbA_qp;
std::vector<qpOASES::real_t> ubA_qp;
const qpOASES::real_t * A_ptr = nullptr;
const qpOASES::real_t * lbA_ptr = nullptr;
const qpOASES::real_t * ubA_ptr = nullptr;
if (nC > 0) {
A_qp.assign(static_cast<size_t>(nC) * static_cast<size_t>(nV), 0.0);
for (int i = 0; i < nC; ++i) {
for (int j = 0; j < nV; ++j) {
A_qp[static_cast<size_t>(i) * static_cast<size_t>(nV) + static_cast<size_t>(j)] =
static_cast<qpOASES::real_t>(A_con(i, j));
}
}
lbA_qp.assign(static_cast<size_t>(nC), 0.0);
ubA_qp.assign(static_cast<size_t>(nC), 0.0);
for (int i = 0; i < nC; ++i) {
lbA_qp[static_cast<size_t>(i)] = static_cast<qpOASES::real_t>(lbA(i));
ubA_qp[static_cast<size_t>(i)] = static_cast<qpOASES::real_t>(ubA(i));
}
A_ptr = A_qp.data();
lbA_ptr = lbA_qp.data();
ubA_ptr = ubA_qp.data();
}
qpOASES::QProblem qp(nV, nC);
qpOASES::Options options;
options.setToMPC();
options.printLevel = qpOASES::PL_NONE;
qp.setOptions(options);
qpOASES::int_t nWSR = static_cast<qpOASES::int_t>(config_.max_working_set_recalculations);
const qpOASES::returnValue ret =
qp.init(H_qp.data(), g_qp.data(), A_ptr, lb_qp.data(), ub_qp.data(), lbA_ptr, ubA_ptr, nWSR);
if (ret != qpOASES::SUCCESSFUL_RETURN) {
if (ret == qpOASES::RET_MAX_NWSR_REACHED) {
std::cout << color_text::RED << "[MpcSolver] qpOASES Max NWSR Reached!" << color_text::RESET
<< std::endl;
} else if (ret == qpOASES::RET_INIT_FAILED_INFEASIBILITY) {
std::cout << color_text::RED << "[MpcSolver] qpOASES Infeasible!" << color_text::RESET << std::endl;
} else {
std::cout << color_text::RED << "[MpcSolver] qpOASES Error Code: " << static_cast<int>(ret)
<< color_text::RESET << std::endl;
}
return false;
}
std::vector<qpOASES::real_t> xOpt(static_cast<size_t>(nV), 0.0);
qp.getPrimalSolution(xOpt.data());
// 如果需要输出预测轨迹
if (out_pred) {
out_pred->clear();
out_pred->reserve(N + 1);
out_pred->push_back(curr);
State s = curr;
Eigen::Matrix3d A; // Identity inside buildStepModel
Eigen::Matrix<double, 3, 3> B;
for (int i = 0; i < N; ++i) {
const double ux = static_cast<double>(xOpt[static_cast<size_t>(3 * i + 0)]);
const double uy = static_cast<double>(xOpt[static_cast<size_t>(3 * i + 1)]);
const double uw = static_cast<double>(xOpt[static_cast<size_t>(3 * i + 2)]);
// 使用 QP 构建时的线性化点 (reference yaw) 进行推演
buildStepModel(ref_traj[i].yaw, A, B);
double dx = B(0, 0) * ux + B(0, 1) * uy + B(0, 2) * uw;
double dy = B(1, 0) * ux + B(1, 1) * uy + B(1, 2) * uw;
double dyaw = B(2, 0) * ux + B(2, 1) * uy + B(2, 2) * uw;
s.x += dx;
s.y += dy;
s.yaw += dyaw;
out_pred->push_back(s);
}
}
// 取第一个控制量 u0 (global)
const Eigen::Vector3d u0_global(
static_cast<double>(xOpt[0]), static_cast<double>(xOpt[1]), static_cast<double>(xOpt[2]));
// 记录上一帧全局速度,用于平滑加速度
last_u_global_ = u0_global;
has_last_u_ = true;
// 直接输出全局速度
out_u.vx = u0_global.x();
out_u.vy = u0_global.y();
out_u.omega = u0_global.z();
return true;
}
} // namespace minco_controller
@@ -0,0 +1,203 @@
#include "minco_controller/performance/mpc_performance_monitor.hpp"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <iomanip>
#include <sstream>
namespace minco_controller {
MpcPerformanceMonitor::~MpcPerformanceMonitor()
{
close();
}
void MpcPerformanceMonitor::configure(const MpcPerformanceConfig & config, rclcpp::Logger logger)
{
close();
config_ = config;
logger_ = logger;
detailed_csv_rows_ = 0;
resetOdomWindow(std::chrono::steady_clock::now());
if (!enabled() || !detailedCsvEnabled()) {
return;
}
detailed_csv_.open(config_.detailed_csv_path, std::ios::out | std::ios::trunc);
if (!detailed_csv_.is_open()) {
RCLCPP_ERROR(logger_, "[MincoMpc] Failed to open MPC perf CSV: %s", config_.detailed_csv_path.c_str());
config_.detailed_csv_enable = false;
return;
}
writeDetailedHeader();
}
void MpcPerformanceMonitor::close()
{
if (detailed_csv_.is_open()) {
detailed_csv_.flush();
detailed_csv_.close();
}
}
bool MpcPerformanceMonitor::enabled() const
{
return config_.enable;
}
bool MpcPerformanceMonitor::detailedCsvEnabled() const
{
return config_.enable && config_.detailed_csv_enable;
}
bool MpcPerformanceMonitor::printEnabled() const
{
return config_.enable && config_.print_enable;
}
void MpcPerformanceMonitor::recordMpcSample(const MpcPerfSample & sample)
{
if (!detailedCsvEnabled() || !detailed_csv_.is_open()) {
return;
}
writeDetailedRow(sample);
flushIfNeeded();
}
void MpcPerformanceMonitor::recordOdomCallback(
const rclcpp::Time & now,
const builtin_interfaces::msg::Time & stamp)
{
if (!enabled() || !config_.odom_sub_debug_enable) {
return;
}
if (odom_stats_.window_start == std::chrono::steady_clock::time_point{}) {
resetOdomWindow(std::chrono::steady_clock::now());
}
++odom_stats_.callback_count;
const rclcpp::Time stamp_time(stamp);
const double delay_ms = (now - stamp_time).seconds() * 1000.0;
if (std::isfinite(delay_ms)) {
odom_stats_.delay_sum_ms += delay_ms;
odom_stats_.delay_min_ms = std::min(odom_stats_.delay_min_ms, delay_ms);
odom_stats_.delay_max_ms = std::max(odom_stats_.delay_max_ms, delay_ms);
++odom_stats_.delay_count;
}
maybePrintOdomStats();
}
long long MpcPerformanceMonitor::steadyNowNs()
{
return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
}
void MpcPerformanceMonitor::writeDetailedHeader()
{
if (!detailed_csv_.is_open()) {
return;
}
detailed_csv_
<< "run_id,scenario,variant,stamp_ros,stamp_steady_ns,success,solve_time_ms,cycle_time_ms,"
"controller_hz,cmd_vx,cmd_vy,cmd_wz,ref_vx,ref_vy,ref_wz\n";
}
void MpcPerformanceMonitor::writeDetailedRow(const MpcPerfSample & sample)
{
detailed_csv_ << sanitize(config_.run_id) << ',' << sanitize(config_.scenario) << ','
<< sanitize(config_.variant) << ',' << num(sample.stamp_ros) << ','
<< sample.stamp_steady_ns << ',' << boolean(sample.success) << ','
<< num(sample.solve_time_ms) << ',' << num(sample.cycle_time_ms) << ','
<< num(sample.controller_hz) << ',' << num(sample.cmd_vx) << ','
<< num(sample.cmd_vy) << ',' << num(sample.cmd_wz) << ',' << num(sample.ref_vx) << ','
<< num(sample.ref_vy) << ',' << num(sample.ref_wz) << '\n';
}
void MpcPerformanceMonitor::maybePrintOdomStats()
{
if (!printEnabled()) {
return;
}
const auto now = std::chrono::steady_clock::now();
const double window_sec = std::chrono::duration<double>(now - odom_stats_.window_start).count();
const double print_period_sec = std::max(config_.print_period_sec, 1.0e-6);
if (window_sec < print_period_sec) {
return;
}
const double callback_hz = window_sec > 1.0e-9
? static_cast<double>(odom_stats_.callback_count) / window_sec
: 0.0;
const double avg_delay_ms = odom_stats_.delay_count > 0
? odom_stats_.delay_sum_ms / static_cast<double>(odom_stats_.delay_count)
: std::numeric_limits<double>::quiet_NaN();
const double min_delay_ms = odom_stats_.delay_count > 0
? odom_stats_.delay_min_ms
: std::numeric_limits<double>::quiet_NaN();
const double max_delay_ms = odom_stats_.delay_count > 0
? odom_stats_.delay_max_ms
: std::numeric_limits<double>::quiet_NaN();
RCLCPP_INFO(
logger_,
"[MincoMpc][OdomSub] callback_hz=%.3f delay_ms avg=%.3f min=%.3f max=%.3f count=%lu",
callback_hz,
avg_delay_ms,
min_delay_ms,
max_delay_ms,
static_cast<unsigned long>(odom_stats_.callback_count));
resetOdomWindow(now);
}
void MpcPerformanceMonitor::resetOdomWindow(std::chrono::steady_clock::time_point now)
{
odom_stats_.window_start = now;
odom_stats_.callback_count = 0;
odom_stats_.delay_sum_ms = 0.0;
odom_stats_.delay_min_ms = std::numeric_limits<double>::infinity();
odom_stats_.delay_max_ms = 0.0;
odom_stats_.delay_count = 0;
}
void MpcPerformanceMonitor::flushIfNeeded()
{
const int flush_every_n = std::max(config_.csv_flush_every_n, 1);
if (++detailed_csv_rows_ % flush_every_n == 0) {
detailed_csv_.flush();
}
}
std::string MpcPerformanceMonitor::num(double value)
{
if (!std::isfinite(value)) {
return "NaN";
}
std::ostringstream ss;
ss << std::fixed << std::setprecision(6) << value;
return ss.str();
}
std::string MpcPerformanceMonitor::boolean(bool value)
{
return value ? "1" : "0";
}
std::string MpcPerformanceMonitor::sanitize(std::string value)
{
std::replace(value.begin(), value.end(), ',', '_');
return value;
}
} // namespace minco_controller
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type = "text/xsl" href = "http://www.coin-or.org/projects/autoGen.xsl"?>
<projectData xmlns="coin-or.org" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="coin-or.org http://www.coin-or.org/projects/autoGen.xsd">
<projectBasics>
<projectName>qpOASES</projectName>
<projectDescription>
qpOASES is an open-source C++ implementation of the recently
proposed online active set strategy for solving quadratic
programming (QP) problems. It has several theoretical features
that make it particularly suited for model predictive control
(MPC) applications. Further numerical modifications have made
qpOASES a reliable QP solver, even when tackling semi-definite,
ill-posed or degenerated QP problems. Moreover, several
interfaces to third-party software make qpOASES easy-to-use
even for users without knowledge of C/C++.
</projectDescription>
<projectShortDescription>An open-source C++ implementation of the recently proposed online active set strategy.</projectShortDescription>
<projectManager>Joachim Ferreau</projectManager>
<projectHomePage>https://github.com/coin-or/qpOASES</projectHomePage>
<projectLicense>​GNU Lesser General Public License (LGPL), v2.1</projectLicense>
<projectLicenseURL>http://www.gnu.org/licenses/lgpl-2.1.html</projectLicenseURL>
<coinLinkedProjects/>
<otherLinkedPackages>
<otherPackage>
<packageName>BLAS</packageName>
<packageURL>http://www.netlib.org/blas</packageURL>
<requiredOrOptional>Optional</requiredOrOptional>
</otherPackage>
<otherPackage>
<packageName>LAPACK</packageName>
<packageURL>http://www.netlib.org/lapack</packageURL>
<requiredOrOptional>Optional</requiredOrOptional>
</otherPackage>
</otherLinkedPackages>
<projectLanguage>C++</projectLanguage>
<developmentStatus>
<activityStatus>Active</activityStatus>
<maturityLevel>3</maturityLevel>
</developmentStatus>
<testedPlatforms>
<platform>
<operatingSystem>Linux</operatingSystem>
<compiler>g++</compiler>
</platform>
<platform>
<operatingSystem>Microsoft Windows</operatingSystem>
<compiler>CYGWIN/g++</compiler>
</platform>
</testedPlatforms>
<projectCategories>
<category>Optimization deterministic nonlinear</category>
</projectCategories>
</projectBasics>
<leftMenuLinks>
<documentation>http://www.qpOASES.org/go/manual</documentation>
<sourceCodeDownload>https://github.com/coin-or/qpOASES</sourceCodeDownload>
<binaryDownload/>
<mailingList>http://list.coin-or.org/mailman/listinfo/qpOASES</mailingList>
</leftMenuLinks>
</projectData>
+94
View File
@@ -0,0 +1,94 @@
##
## This file is part of qpOASES.
##
## qpOASES -- An Implementation of the Online Active Set Strategy.
## Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
## Christian Kirches et al. All rights reserved.
##
## qpOASES is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public
## License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your option) any later version.
##
## qpOASES is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
## See the GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public
## License along with qpOASES; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
##
MAIN AUTHORS
============
qpOASES's core functionality and software design have been developed by the
following main developers (in alphabetical order):
Hans Joachim Ferreau
Christian Kirches
Andreas Potschka
FURTHER AUTHORS
===============
Moreover, the following developers have contributed code to qpOASES's
third-party interfaces or provided additional functionality
(in alphabetical order):
Alexander Buchner
Holger Diedam
Dennis Janka
Manuel Kudruss
Andreas Waechter
Sebastian F. Walter
CONTRIBUTORS
============
Finally, the following people have not contributed to the source code,
but have helped making qpOASES even more useful by testing, reporting
bugs or proposing algorithmic improvements (in alphabetical order):
Eckhard Arnold
Joris Gillis
Boris Houska
D. Kwame Minde Kufoalor
Aude Perrin
Silvio Traversaro
Milan Vukov
Thomas Wiese
Leonard Wirsching
SCIENTIFIC MENTORS
==================
We also would like to thank two persons who had a major share in making
qpOASES a success. Not by writing even a single line of code, but by
establishing the idea of using a homotopy-based approach for high-speed
QP solutions and by excellent scientific guidance during the development
process:
Hans Georg Bock
Moritz Diehl
All users are invited to further improve qpOASES by providing comments,
code enhancements, bug reports, additional documentation or whatever you
feel is missing.
##
## end of file
##
@@ -0,0 +1,94 @@
##
## This file is part of qpOASES.
##
## qpOASES -- An Implementation of the Online Active Set Strategy.
## Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
## Christian Kirches et al. All rights reserved.
##
## qpOASES is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public
## License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your option) any later version.
##
## qpOASES is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
## See the GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public
## License along with qpOASES; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
##
MAIN AUTHORS
============
qpOASES's core functionality and software design have been developed by the
following main developers (in alphabetical order):
Hans Joachim Ferreau
Christian Kirches
Andreas Potschka
FURTHER AUTHORS
===============
Moreover, the following developers have contributed code to qpOASES's
third-party interfaces or provided additional functionality
(in alphabetical order):
Alexander Buchner
Holger Diedam
Dennis Janka
Manuel Kudruss
Andreas Waechter
Sebastian F. Walter
CONTRIBUTORS
============
Finally, the following people have not contributed to the source code,
but have helped making qpOASES even more useful by testing, reporting
bugs or proposing algorithmic improvements (in alphabetical order):
Eckhard Arnold
Joris Gillis
Boris Houska
D. Kwame Minde Kufoalor
Aude Perrin
Silvio Traversaro
Milan Vukov
Thomas Wiese
Leonard Wirsching
SCIENTIFIC MENTORS
==================
We also would like to thank two persons who had a major share in making
qpOASES a success. Not by writing even a single line of code, but by
establishing the idea of using a homotopy-based approach for high-speed
QP solutions and by excellent scientific guidance during the development
process:
Hans Georg Bock
Moritz Diehl
All users are invited to further improve qpOASES by providing comments,
code enhancements, bug reports, additional documentation or whatever you
feel is missing.
##
## end of file
##
@@ -0,0 +1,200 @@
##
## This file is part of qpOASES.
##
## qpOASES -- An Implementation of the Online Active Set Strategy.
## Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
## Christian Kirches et al. All rights reserved.
##
## qpOASES is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public
## License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your option) any later version.
##
## qpOASES is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
## See the GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public
## License along with qpOASES; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
##
##
## Filename: CMakeLists.txt
## Author: Hans Joachim Ferreau (thanks to Milan Vukov)
## Version: 3.2
## Date: 2007-2017
##
cmake_minimum_required(VERSION 3.18)
PROJECT(qpOASES CXX)
SET(PACKAGE_NAME "qpOASES")
SET(PACKAGE_VERSION "3.2.2")
SET(PACKAGE_SO_VERSION "3.2")
SET(PACKAGE_DESCRIPTION "An implementation of the online active set strategy")
SET(PACKAGE_AUTHOR "Hans Joachim Ferreau, Andreas Potschka, Christian Kirches et al.")
SET(PACKAGE_MAINTAINER "Hans Joachim Ferreau, Andreas Potschka, Christian Kirches et al.")
SET(PACKAGE_URL "https://projects.coin-or.org/qpOASES")
SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
SET(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/libs)
IF(NOT CMAKE_INSTALL_LIBDIR)
SET(CMAKE_INSTALL_LIBDIR lib)
ENDIF(NOT CMAKE_INSTALL_LIBDIR)
IF(NOT CMAKE_INSTALL_BINDIR)
SET(CMAKE_INSTALL_BINDIR ${CMAKE_INSTALL_LIBDIR})
ENDIF(NOT CMAKE_INSTALL_BINDIR)
IF(NOT CMAKE_INSTALL_INCLUDEDIR)
SET(CMAKE_INSTALL_INCLUDEDIR include)
ENDIF(NOT CMAKE_INSTALL_INCLUDEDIR)
IF( NOT CMAKE_VERBOSE_MAKEFILE )
SET( CMAKE_VERBOSE_MAKEFILE OFF )
ENDIF( NOT CMAKE_VERBOSE_MAKEFILE )
IF( NOT CMAKE_BUILD_TYPE )
SET(CMAKE_BUILD_TYPE Release CACHE STRING
"Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel."
FORCE
)
ENDIF( NOT CMAKE_BUILD_TYPE )
option(BUILD_SHARED_LIBS "If ON, build shared library instead of static" OFF)
option(QPOASES_BUILD_EXAMPLES "Build examples." ON)
option(QPOASES_AVOID_LA_NAMING_CONFLICTS "If ON, avoid to re-defined symbols that conflict with Blas/Lapack provided functions." OFF)
IF(BUILD_SHARED_LIBS AND WIN32)
MESSAGE(FATAL_ERROR "Compiling qpOASES as a shared library in Windows is not supported.")
ENDIF()
############################################################
#################### compiler flags ########################
############################################################
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__NO_COPYRIGHT__")
IF(QPOASES_AVOID_LA_NAMING_CONFLICTS)
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__AVOID_LA_NAMING_CONFLICTS__")
ENDIF()
IF ( UNIX )
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -Wfloat-equal -Wshadow -DLINUX")
SET(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_DEBUG} -O3 -finline-functions")
ELSEIF( WINDOWS )
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -nologo -EHsc -DWIN32")
ENDIF()
SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -D__DEBUG__")
############################################################
######################## rpath #############################
############################################################
# use, i.e. don't skip the full RPATH for the build tree
set(CMAKE_SKIP_BUILD_RPATH FALSE)
# when building, don't use the install RPATH already
# (but later on when installing)
set(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)
set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib:${CMAKE_INSTALL_PREFIX}/lib/casadi")
# add the automatically determined parts of the RPATH
# which point to directories outside the build tree to the install RPATH
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
# the RPATH to be used when installing, but only if it's not a system directory
list(FIND CMAKE_PLATFORM_IMPLICIT_LINK_DIRECTORIES "${CMAKE_INSTALL_PREFIX}/lib" isSystemDir)
if("${isSystemDir}" STREQUAL "-1")
set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib:${CMAKE_INSTALL_PREFIX}/lib/casadi")
endif("${isSystemDir}" STREQUAL "-1")
############################################################
#################### build and install #####################
############################################################
INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/include)
# compile qpOASES libraries
FILE(GLOB SRC src/*.cpp)
# library
ADD_LIBRARY(qpOASES ${SRC})
INSTALL(TARGETS qpOASES
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
SET_TARGET_PROPERTIES(
qpOASES
PROPERTIES
SOVERSION ${PACKAGE_SO_VERSION}
)
# headers
INSTALL(FILES include/qpOASES.hpp
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
INSTALL(DIRECTORY include/qpOASES
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
FILES_MATCHING PATTERN "*.hpp"
PATTERN "*.ipp"
PATTERN ".svn" EXCLUDE)
############################################################
######################### Package Config ###################
############################################################
include(CMakePackageConfigHelpers)
set(INCLUDE_INSTALL_DIR ${CMAKE_INSTALL_INCLUDEDIR})
set(LIB_INSTALL_DIR ${CMAKE_INSTALL_LIBDIR})
configure_package_config_file(qpOASESConfig.cmake.in
${CMAKE_CURRENT_BINARY_DIR}/qpOASESConfig.cmake
INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/qpOASES
PATH_VARS INCLUDE_INSTALL_DIR LIB_INSTALL_DIR
NO_CHECK_REQUIRED_COMPONENTS_MACRO)
write_basic_package_version_file(
${CMAKE_CURRENT_BINARY_DIR}/qpOASESConfigVersion.cmake
VERSION ${PACKAGE_VERSION}
COMPATIBILITY SameMajorVersion)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/qpOASESConfig.cmake
${CMAKE_CURRENT_BINARY_DIR}/qpOASESConfigVersion.cmake
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/qpOASES
COMPONENT qpOASES)
############################################################
######################### examples #########################
############################################################
if (QPOASES_BUILD_EXAMPLES)
# compile qpOASES examples
SET(EXAMPLE_NAMES
example1
example1a
example1b
example2
example3
example3b
example4
example5
exampleLP
qrecipe
qrecipeSchur
)
FOREACH(ELEMENT ${EXAMPLE_NAMES})
ADD_EXECUTABLE(${ELEMENT} examples/${ELEMENT}.cpp)
TARGET_LINK_LIBRARIES(${ELEMENT} qpOASES)
ENDFOREACH(ELEMENT ${EXAMPLE_NAMES})
endif(QPOASES_BUILD_EXAMPLES)
##
## end of file
##
+79
View File
@@ -0,0 +1,79 @@
##
## This file is part of qpOASES.
##
## qpOASES -- An Implementation of the Online Active Set Strategy.
## Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
## Christian Kirches et al. All rights reserved.
##
## qpOASES is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public
## License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your option) any later version.
##
## qpOASES is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
## See the GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public
## License along with qpOASES; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
##
INSTALLATION UNDER LINUX
========================
0. Obtain qpOASES from COIN-OR:
Download a zipped archive containg the latest stable release and unpack it
into <install-dir>. Alternatively, you check out the latest stable branch,
e.g. by running
svn co https://projects.coin-or.org/svn/qpOASES/stable/3.2 <install-dir>
from your shell.
1. Compilation of the qpOASES library libqpOASES.a (or .so) and test examples:
cd <install-dir>
make
The library libqpOASES.a (or .so) provides the complete functionality of the
qpOASES software package. It can be used by, e.g., linking it against a main
function from the examples folder. The make also compiles a couple of test
examples; executables are stored within the directory <install-dir>/bin.
2. Running a simple test example:
Among others, an executable called example1 should have been created; run
it in order to test your installation:
cd <install-dir>/bin
./example1
If it terminates after successfully solving two QP problems, qpOASES has been
successfully installed!
3. Optional, create source code documentation (using doxygen):
cd <install-dir>/doc
doxygen doxygen.config
Afterwards, you can open the file <install-dir>/doc/html/index.html with
your favorite browser in order to view qpOASES's source code documentation.
NOTE: More detailed installation instructions, including information on how
to run unit tests can be found in the qpOASES User's Manual located
at <install-dir>/doc/manual.pdf!
##
## end of file
##
@@ -0,0 +1,79 @@
##
## This file is part of qpOASES.
##
## qpOASES -- An Implementation of the Online Active Set Strategy.
## Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
## Christian Kirches et al. All rights reserved.
##
## qpOASES is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public
## License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your option) any later version.
##
## qpOASES is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
## See the GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public
## License along with qpOASES; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
##
INSTALLATION UNDER LINUX
========================
0. Obtain qpOASES from COIN-OR:
Download a zipped archive containg the latest stable release and unpack it
into <install-dir>. Alternatively, you check out the latest stable branch,
e.g. by running
svn co https://projects.coin-or.org/svn/qpOASES/stable/3.2 <install-dir>
from your shell.
1. Compilation of the qpOASES library libqpOASES.a (or .so) and test examples:
cd <install-dir>
make
The library libqpOASES.a (or .so) provides the complete functionality of the
qpOASES software package. It can be used by, e.g., linking it against a main
function from the examples folder. The make also compiles a couple of test
examples; executables are stored within the directory <install-dir>/bin.
2. Running a simple test example:
Among others, an executable called example1 should have been created; run
it in order to test your installation:
cd <install-dir>/bin
./example1
If it terminates after successfully solving two QP problems, qpOASES has been
successfully installed!
3. Optional, create source code documentation (using doxygen):
cd <install-dir>/doc
doxygen doxygen.config
Afterwards, you can open the file <install-dir>/doc/html/index.html with
your favorite browser in order to view qpOASES's source code documentation.
NOTE: More detailed installation instructions, including information on how
to run unit tests can be found in the qpOASES User's Manual located
at <install-dir>/doc/manual.pdf!
##
## end of file
##
+503
View File
@@ -0,0 +1,503 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
+503
View File
@@ -0,0 +1,503 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
+118
View File
@@ -0,0 +1,118 @@
##
## This file is part of qpOASES.
##
## qpOASES -- An Implementation of the Online Active Set Strategy.
## Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
## Christian Kirches et al. All rights reserved.
##
## qpOASES is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public
## License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your option) any later version.
##
## qpOASES is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
## See the GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public
## License along with qpOASES; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
##
##
## Filename: Makefile
## Author: Hans Joachim Ferreau
## Version: 3.2
## Date: 2007-2017
##
include make.mk
##
## targets
##
ifeq ($(DEF_SOLVER), SOLVER_MUMPS)
EXTERNAL = mumps
else
EXTERNAL =
endif
all: $(EXTERNAL) bin src examples
#src_aw testing
ifeq ($(DEF_SOLVER), SOLVER_MUMPS)
mumps:
@echo $(QPOASESROOT)
@cd external/ThirdParty-Mumps; \
if [ -d "MUMPS" ]; then \
echo "Found MUMPS source code."; \
else get.Mumps; ./configure --prefix=$(PWD)/external/mumps_installation; fi; \
make && make install
endif
src: $(EXTERNAL)
@cd $@; ${MAKE} -s
bin:
mkdir bin
#src_aw:
# @cd $@; ${MAKE} -s
examples: src
@cd $@; ${MAKE} -s
doc:
@cd $@; ${MAKE} -s
testing: src
@cd testing/cpp; ${MAKE} -s
test: testing
@cd testing/cpp; ${MAKE} -s runTests
debugging:
@cd $@; ${MAKE} -s
clean:
ifeq ($(DEF_SOLVER), SOLVER_MUMPS)
@echo Cleaning up \(mumps\)
@cd external/ThirdParty-Mumps && ${MAKE} -s clean
@cd external && ${RM} -rf mumps_installation
endif
@cd src && ${MAKE} -s clean
@cd examples && ${MAKE} -s clean
@cd bin && ${RM} -f *.* *{EXE}
@cd testing/cpp && ${MAKE} -s clean
# && cd src_aw && ${MAKE} -s clean && cd .. \
# && cd debugging && ${MAKE} -s clean && cd .. \
clobber: clean
scilab:
@echo Compiling Scilab interface...
@cd ./interfaces/scilab/; ${MAKE} -s
python: all
cd ./interfaces/python/ && python setup.py build_ext --inplace
pythoninstall: all
cd ./interfaces/python/ && python setup.py install
c_wrapper:
@echo Compiling C interface...
@cd ./interfaces/c/; ${MAKE} -s
.PHONY : all src examples doc testing debugging clean clobber scilab python phythoninstall c_wrapper
##
## end of file
##
+84
View File
@@ -0,0 +1,84 @@
##
## This file is part of qpOASES.
##
## qpOASES -- An Implementation of the Online Active Set Strategy.
## Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
## Christian Kirches et al. All rights reserved.
##
## qpOASES is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public
## License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your option) any later version.
##
## qpOASES is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
## See the GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public
## License along with qpOASES; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
##
INTRODUCTION
============
qpOASES is an open-source C++ implementation of the recently proposed
online active set strategy, which was inspired by important observations
from the field of parametric quadratic programming (QP). It has several
theoretical features that make it particularly suited for model predictive
control (MPC) applications. Further numerical modifications have made
qpOASES a reliable QP solver, even when tackling semi-definite, ill-posed or
degenerated QP problems. Moreover, several interfaces to third-party software
like ​Matlab or ​Simulink are provided that make qpOASES easy-to-use even for
users without knowledge of C/C++.
GETTING STARTED
===============
1. For installation, usage and additional information on this software package
see the qpOASES User's Manual located at doc/manual.pdf or check its
source code documentation!
2. The file LICENSE.txt contains a copy of the GNU Lesser General Public
License (v2.1). Please read it carefully before using qpOASES!
3. The whole software package can be obtained from
http://www.qpOASES.org/ or
https://github.com/coin-or/qpOASES/
On this webpage you will also find further support such as a list of
questions posed by other users.
CONTACT THE AUTHORS
===================
If you have got questions, remarks or comments on qpOASES, it is strongly
encouraged to report them by creating a new ticket at the qpOASES webpage.
In case you do not want to disclose your feedback to the public, you may
send an e-mail to
[email protected]
Finally, you may contact one of the main authors directly:
Hans Joachim Ferreau, [email protected]
Andreas Potschka, [email protected]
Christian Kirches, [email protected]
Also bug reports, source code enhancements or success stories are most welcome!
##
## end of file
##
@@ -0,0 +1,189 @@
<doxygenlayout version="1.0">
<!-- Navigation index tabs for HTML output -->
<navindex>
<tab type="mainpage" visible="yes" title=""/>
<tab type="pages" visible="yes" title="" intro=""/>
<tab type="modules" visible="yes" title="" intro=""/>
<tab type="namespaces" visible="yes" title="">
<tab type="namespacelist" visible="yes" title="" intro=""/>
<tab type="namespacemembers" visible="yes" title="" intro=""/>
</tab>
<tab type="classes" visible="yes" title="">
<tab type="classlist" visible="yes" title="" intro=""/>
<tab type="classindex" visible="$ALPHABETICAL_INDEX" title=""/>
<tab type="hierarchy" visible="yes" title="" intro=""/>
<tab type="classmembers" visible="yes" title="" intro=""/>
</tab>
<tab type="files" visible="yes" title="">
<tab type="filelist" visible="yes" title="" intro=""/>
<tab type="globals" visible="yes" title="" intro=""/>
</tab>
<tab type="dirs" visible="yes" title="" intro=""/>
<tab type="examples" visible="yes" title="" intro=""/>
<tab type="user" visible="yes" url="../manual.pdf" title="Manual" intro=""/>
</navindex>
<!-- Layout definition for a class page -->
<class>
<briefdescription visible="yes"/>
<includes visible="$SHOW_INCLUDE_FILES"/>
<inheritancegraph visible="$CLASS_GRAPH"/>
<collaborationgraph visible="$COLLABORATION_GRAPH"/>
<allmemberslink visible="yes"/>
<memberdecl>
<nestedclasses visible="yes" title=""/>
<publictypes title=""/>
<publicslots title=""/>
<signals title=""/>
<publicmethods title=""/>
<publicstaticmethods title=""/>
<publicattributes title=""/>
<publicstaticattributes title=""/>
<protectedtypes title=""/>
<protectedslots title=""/>
<protectedmethods title=""/>
<protectedstaticmethods title=""/>
<protectedattributes title=""/>
<protectedstaticattributes title=""/>
<packagetypes title=""/>
<packagemethods title=""/>
<packagestaticmethods title=""/>
<packageattributes title=""/>
<packagestaticattributes title=""/>
<properties title=""/>
<events title=""/>
<privatetypes title=""/>
<privateslots title=""/>
<privatemethods title=""/>
<privatestaticmethods title=""/>
<privateattributes title=""/>
<privatestaticattributes title=""/>
<friends title=""/>
<related title="" subtitle=""/>
<membergroups visible="yes"/>
</memberdecl>
<detaileddescription title=""/>
<memberdef>
<inlineclasses title=""/>
<typedefs title=""/>
<enums title=""/>
<constructors title=""/>
<functions title=""/>
<related title=""/>
<variables title=""/>
<properties title=""/>
<events title=""/>
</memberdef>
<usedfiles visible="$SHOW_USED_FILES"/>
<authorsection visible="yes"/>
</class>
<!-- Layout definition for a namespace page -->
<namespace>
<briefdescription visible="yes"/>
<memberdecl>
<nestednamespaces visible="yes" title=""/>
<classes visible="yes" title=""/>
<typedefs title=""/>
<enums title=""/>
<functions title=""/>
<variables title=""/>
<membergroups visible="yes"/>
</memberdecl>
<detaileddescription title=""/>
<memberdef>
<inlineclasses title=""/>
<typedefs title=""/>
<enums title=""/>
<functions title=""/>
<variables title=""/>
</memberdef>
<authorsection visible="yes"/>
</namespace>
<!-- Layout definition for a file page -->
<file>
<briefdescription visible="yes"/>
<includes visible="$SHOW_INCLUDE_FILES"/>
<includegraph visible="$INCLUDE_GRAPH"/>
<includedbygraph visible="$INCLUDED_BY_GRAPH"/>
<sourcelink visible="yes"/>
<memberdecl>
<classes visible="yes" title=""/>
<namespaces visible="yes" title=""/>
<defines title=""/>
<typedefs title=""/>
<enums title=""/>
<functions title=""/>
<variables title=""/>
<membergroups visible="yes"/>
</memberdecl>
<detaileddescription title=""/>
<memberdef>
<inlineclasses title=""/>
<defines title=""/>
<typedefs title=""/>
<enums title=""/>
<functions title=""/>
<variables title=""/>
</memberdef>
<authorsection/>
</file>
<!-- Layout definition for a group page -->
<group>
<briefdescription visible="yes"/>
<groupgraph visible="$GROUP_GRAPHS"/>
<memberdecl>
<classes visible="yes" title=""/>
<namespaces visible="yes" title=""/>
<dirs visible="yes" title=""/>
<nestedgroups visible="yes" title=""/>
<files visible="yes" title=""/>
<defines title=""/>
<typedefs title=""/>
<enums title=""/>
<enumvalues title=""/>
<functions title=""/>
<variables title=""/>
<signals title=""/>
<publicslots title=""/>
<protectedslots title=""/>
<privateslots title=""/>
<events title=""/>
<properties title=""/>
<friends title=""/>
<membergroups visible="yes"/>
</memberdecl>
<detaileddescription title=""/>
<memberdef>
<pagedocs/>
<inlineclasses title=""/>
<defines title=""/>
<typedefs title=""/>
<enums title=""/>
<enumvalues title=""/>
<functions title=""/>
<variables title=""/>
<signals title=""/>
<publicslots title=""/>
<protectedslots title=""/>
<privateslots title=""/>
<events title=""/>
<properties title=""/>
<friends title=""/>
</memberdef>
<authorsection visible="yes"/>
</group>
<!-- Layout definition for a directory page -->
<directory>
<briefdescription visible="yes"/>
<directorygraph visible="yes"/>
<memberdecl>
<dirs visible="yes"/>
<files visible="yes"/>
</memberdecl>
<detaileddescription title=""/>
</directory>
</doxygenlayout>
@@ -0,0 +1,66 @@
##
## This file is part of qpOASES.
##
## qpOASES -- An Implementation of the Online Active Set Strategy.
## Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
## Christian Kirches et al. All rights reserved.
##
## qpOASES is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public
## License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your option) any later version.
##
## qpOASES is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
## See the GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public
## License along with qpOASES; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
##
##
## Filename: Makefile
## Author: Hans Joachim Ferreau
## Version: 3.2
## Date: 2007-2017
##
##
## settings
##
MAKEPDF = pdflatex
LATEX = latex
##
## targets
##
all: doc
.PHONY: doc
doc:
@ echo "Creating doxygen documentation "
@ doxygen doxygen.config
.PHONY: clean
clean:
@ ${RM} -rf ./html
.PHONY: clobber
clobber: clean
##
## end of file
##
@@ -0,0 +1,310 @@
#---------------------------------------------------------------------------
# Project related configuration options
#---------------------------------------------------------------------------
DOXYFILE_ENCODING = UTF-8
PROJECT_NAME = qpOASES
PROJECT_NUMBER = 3.2.2
PROJECT_BRIEF = "An Implementation of the Online Active Set Strategy"
PROJECT_LOGO =
OUTPUT_DIRECTORY =
CREATE_SUBDIRS = NO
OUTPUT_LANGUAGE = English
BRIEF_MEMBER_DESC = YES
REPEAT_BRIEF = NO
ABBREVIATE_BRIEF =
ALWAYS_DETAILED_SEC = NO
INLINE_INHERITED_MEMB = YES
FULL_PATH_NAMES = YES
STRIP_FROM_PATH = ..
STRIP_FROM_INC_PATH =
SHORT_NAMES = NO
JAVADOC_AUTOBRIEF = NO
QT_AUTOBRIEF = NO
MULTILINE_CPP_IS_BRIEF = NO
INHERIT_DOCS = YES
SEPARATE_MEMBER_PAGES = NO
TAB_SIZE = 4
ALIASES =
TCL_SUBST =
OPTIMIZE_OUTPUT_FOR_C = NO
OPTIMIZE_OUTPUT_JAVA = NO
OPTIMIZE_FOR_FORTRAN = NO
OPTIMIZE_OUTPUT_VHDL = NO
EXTENSION_MAPPING =
MARKDOWN_SUPPORT = YES
AUTOLINK_SUPPORT = YES
BUILTIN_STL_SUPPORT = NO
CPP_CLI_SUPPORT = NO
SIP_SUPPORT = NO
IDL_PROPERTY_SUPPORT = YES
DISTRIBUTE_GROUP_DOC = NO
SUBGROUPING = YES
INLINE_GROUPED_CLASSES = NO
INLINE_SIMPLE_STRUCTS = NO
TYPEDEF_HIDES_STRUCT = NO
SYMBOL_CACHE_SIZE = 0
LOOKUP_CACHE_SIZE = 0
#---------------------------------------------------------------------------
# Build related configuration options
#---------------------------------------------------------------------------
EXTRACT_ALL = NO
EXTRACT_PRIVATE = YES
EXTRACT_PACKAGE = NO
EXTRACT_STATIC = NO
EXTRACT_LOCAL_CLASSES = YES
EXTRACT_LOCAL_METHODS = NO
EXTRACT_ANON_NSPACES = NO
HIDE_UNDOC_MEMBERS = NO
HIDE_UNDOC_CLASSES = NO
HIDE_FRIEND_COMPOUNDS = NO
HIDE_IN_BODY_DOCS = NO
INTERNAL_DOCS = NO
CASE_SENSE_NAMES = YES
HIDE_SCOPE_NAMES = NO
SHOW_INCLUDE_FILES = YES
FORCE_LOCAL_INCLUDES = NO
INLINE_INFO = YES
SORT_MEMBER_DOCS = YES
SORT_BRIEF_DOCS = NO
SORT_MEMBERS_CTORS_1ST = NO
SORT_GROUP_NAMES = NO
SORT_BY_SCOPE_NAME = NO
STRICT_PROTO_MATCHING = NO
GENERATE_TODOLIST = NO
GENERATE_TESTLIST = NO
GENERATE_BUGLIST = NO
GENERATE_DEPRECATEDLIST= YES
ENABLED_SECTIONS =
MAX_INITIALIZER_LINES = 30
SHOW_USED_FILES = YES
SHOW_FILES = YES
SHOW_NAMESPACES = YES
FILE_VERSION_FILTER =
LAYOUT_FILE = DoxygenLayout.xml
CITE_BIB_FILES =
#---------------------------------------------------------------------------
# configuration options related to warning and progress messages
#---------------------------------------------------------------------------
QUIET = NO
WARNINGS = YES
WARN_IF_UNDOCUMENTED = YES
WARN_IF_DOC_ERROR = YES
WARN_NO_PARAMDOC = NO
WARN_FORMAT = "$file:$line: $text"
WARN_LOGFILE =
#---------------------------------------------------------------------------
# configuration options related to the input files
#---------------------------------------------------------------------------
INPUT = ./mainpage.dox \
../src \
../include/qpOASES \
../include/qpOASES/extras \
../examples
INPUT_ENCODING = UTF-8
FILE_PATTERNS = *.cpp \
*.ipp \
*.hpp \
*.c
RECURSIVE = YES
EXCLUDE =
EXCLUDE_SYMLINKS = NO
EXCLUDE_PATTERNS =
EXCLUDE_SYMBOLS =
EXAMPLE_PATH = ../examples
EXAMPLE_PATTERNS =
EXAMPLE_RECURSIVE = NO
IMAGE_PATH =
INPUT_FILTER =
FILTER_PATTERNS =
FILTER_SOURCE_FILES = NO
FILTER_SOURCE_PATTERNS =
#---------------------------------------------------------------------------
# configuration options related to source browsing
#---------------------------------------------------------------------------
SOURCE_BROWSER = NO
INLINE_SOURCES = NO
STRIP_CODE_COMMENTS = YES
REFERENCED_BY_RELATION = YES
REFERENCES_RELATION = YES
REFERENCES_LINK_SOURCE = YES
USE_HTAGS = NO
VERBATIM_HEADERS = YES
#---------------------------------------------------------------------------
# configuration options related to the alphabetical class index
#---------------------------------------------------------------------------
ALPHABETICAL_INDEX = NO
COLS_IN_ALPHA_INDEX = 5
IGNORE_PREFIX =
#---------------------------------------------------------------------------
# configuration options related to the HTML output
#---------------------------------------------------------------------------
GENERATE_HTML = YES
HTML_OUTPUT = html
HTML_FILE_EXTENSION = .html
HTML_HEADER =
HTML_FOOTER =
HTML_STYLESHEET =
HTML_EXTRA_STYLESHEET =
HTML_EXTRA_FILES =
HTML_COLORSTYLE_HUE = 220
HTML_COLORSTYLE_SAT = 100
HTML_COLORSTYLE_GAMMA = 80
HTML_TIMESTAMP = YES
HTML_DYNAMIC_SECTIONS = NO
HTML_INDEX_NUM_ENTRIES = 100
GENERATE_DOCSET = NO
DOCSET_FEEDNAME = "Doxygen generated docs"
DOCSET_BUNDLE_ID = org.doxygen.Project
DOCSET_PUBLISHER_ID = org.doxygen.Publisher
DOCSET_PUBLISHER_NAME = Publisher
GENERATE_HTMLHELP = NO
CHM_FILE =
HHC_LOCATION =
GENERATE_CHI = NO
CHM_INDEX_ENCODING =
BINARY_TOC = NO
TOC_EXPAND = NO
GENERATE_QHP = NO
QCH_FILE =
QHP_NAMESPACE = org.doxygen.Project
QHP_VIRTUAL_FOLDER = doc
QHP_CUST_FILTER_NAME =
QHP_CUST_FILTER_ATTRS =
QHP_SECT_FILTER_ATTRS =
QHG_LOCATION =
GENERATE_ECLIPSEHELP = NO
ECLIPSE_DOC_ID = org.doxygen.Project
DISABLE_INDEX = NO
GENERATE_TREEVIEW = NO
ENUM_VALUES_PER_LINE = 4
TREEVIEW_WIDTH = 250
EXT_LINKS_IN_WINDOW = NO
FORMULA_FONTSIZE = 10
FORMULA_TRANSPARENT = YES
USE_MATHJAX = NO
MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest
MATHJAX_EXTENSIONS =
SEARCHENGINE = NO
SERVER_BASED_SEARCH = NO
#---------------------------------------------------------------------------
# configuration options related to the LaTeX output
#---------------------------------------------------------------------------
GENERATE_LATEX = NO
LATEX_OUTPUT = latex
LATEX_CMD_NAME = latex
MAKEINDEX_CMD_NAME = makeindex
COMPACT_LATEX = NO
PAPER_TYPE = a4wide
EXTRA_PACKAGES =
LATEX_HEADER =
LATEX_FOOTER =
PDF_HYPERLINKS = YES
USE_PDFLATEX = NO
LATEX_BATCHMODE = NO
LATEX_HIDE_INDICES = NO
LATEX_SOURCE_CODE = NO
LATEX_BIB_STYLE = plain
#---------------------------------------------------------------------------
# configuration options related to the RTF output
#---------------------------------------------------------------------------
GENERATE_RTF = NO
RTF_OUTPUT = RTF
COMPACT_RTF = NO
RTF_HYPERLINKS = NO
RTF_STYLESHEET_FILE =
RTF_EXTENSIONS_FILE =
#---------------------------------------------------------------------------
# configuration options related to the man page output
#---------------------------------------------------------------------------
GENERATE_MAN = NO
MAN_OUTPUT = MAN
MAN_EXTENSION = .3
MAN_LINKS = NO
#---------------------------------------------------------------------------
# configuration options related to the XML output
#---------------------------------------------------------------------------
GENERATE_XML = NO
XML_OUTPUT = XML
XML_SCHEMA =
XML_DTD =
XML_PROGRAMLISTING = YES
#---------------------------------------------------------------------------
# configuration options for the AutoGen Definitions output
#---------------------------------------------------------------------------
GENERATE_AUTOGEN_DEF = NO
#---------------------------------------------------------------------------
# configuration options related to the Perl module output
#---------------------------------------------------------------------------
GENERATE_PERLMOD = NO
PERLMOD_LATEX = NO
PERLMOD_PRETTY = YES
PERLMOD_MAKEVAR_PREFIX =
#---------------------------------------------------------------------------
# Configuration options related to the preprocessor
#---------------------------------------------------------------------------
ENABLE_PREPROCESSING = YES
MACRO_EXPANSION = NO
EXPAND_ONLY_PREDEF = NO
SEARCH_INCLUDES = YES
INCLUDE_PATH =
INCLUDE_FILE_PATTERNS =
PREDEFINED =
EXPAND_AS_DEFINED =
SKIP_FUNCTION_MACROS = YES
#---------------------------------------------------------------------------
# Configuration::additions related to external references
#---------------------------------------------------------------------------
TAGFILES =
GENERATE_TAGFILE =
ALLEXTERNALS = NO
EXTERNAL_GROUPS = YES
PERL_PATH = /usr/bin/perl
#---------------------------------------------------------------------------
# Configuration options related to the dot tool
#---------------------------------------------------------------------------
CLASS_DIAGRAMS = YES
MSCGEN_PATH =
HIDE_UNDOC_RELATIONS = YES
HAVE_DOT = NO
DOT_NUM_THREADS = 0
DOT_FONTNAME = Helvetica
DOT_FONTSIZE = 10
DOT_FONTPATH =
CLASS_GRAPH = YES
COLLABORATION_GRAPH = NO
GROUP_GRAPHS = YES
UML_LOOK = NO
UML_LIMIT_NUM_FIELDS = 10
TEMPLATE_RELATIONS = NO
INCLUDE_GRAPH = YES
INCLUDED_BY_GRAPH = YES
CALL_GRAPH = NO
CALLER_GRAPH = NO
GRAPHICAL_HIERARCHY = YES
DIRECTORY_GRAPH = YES
DOT_IMAGE_FORMAT = png
INTERACTIVE_SVG = NO
DOT_PATH =
DOTFILE_DIRS =
MSCFILE_DIRS =
DOT_GRAPH_MAX_NODES = 50
MAX_DOT_GRAPH_DEPTH = 0
DOT_TRANSPARENT = NO
DOT_MULTI_TARGETS = NO
GENERATE_LEGEND = YES
DOT_CLEANUP = YES
@@ -0,0 +1,135 @@
/**
* \mainpage Main Page
*
* <p>&nbsp;</p>
*
* \section sec_copyright Copyright
*
* qpOASES -- An Implementation of the Online Active Set Strategy. \n
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* <p>&nbsp;</p>
*
*
* \section sec_developers Authors and Contributors
*
* qpOASES's core functionality and software design have been developed by
* the following main developers (in alphabetical order):
* <ul>
* <li>Hans Joachim Ferreau
* <li>Christian Kirches
* <li>Andreas Potschka
* </ul>
*
* Moreover, the following developers have contributed code to qpOASES's
* third-party interfaces or provided additional functionality
* (in alphabetical order):
* <ul>
* <li>Alexander Buchner
* <li>Holger Diedam
* <li>Dennis Janka
* <li>Manuel Kudruss
* <li>Andreas Waechter
* <li>Sebastian F. Walter
* </ul>
*
* Finally, the following people have not contributed to the source code,
* but have helped making qpOASES even more useful by testing, reporting
* bugs or proposing algorithmic improvements (in alphabetical order):
* <ul>
* <li>Eckhard Arnold
* <li>Joris Gillis
* <li>Boris Houska
* <li>D. Kwame Minde Kufoalor
* <li>Aude Perrin
* <li>Milan Vukov
* <li>Thomas Wiese
* <li>Leonard Wirsching
* </ul>
*
* We also would like to thank two persons who had a major share in making
* qpOASES a success. Not by writing even a single line of code, but by
* establishing the idea of using a homotopy-based approach for high-speed
* QP solutions and by excellent scientific guidance during the development
* process:
* <ul>
* <li>Hans Georg Bock
* <li>Moritz Diehl
* </ul>
*
* All users are invited to further improve qpOASES by providing comments, code enhancements,
* bug reports, additional documentation or whatever you feel is missing. The preferred way
* of doing so is to <b>create a <a href="https://projects.coin-or.org/qpOASES/newticket">new ticket</a>
* at the qpOASES webpage</b>. In case you do not want to disclose your feedback to the public,
* you may send an e-mail to <a href="mailto:[email protected]">[email protected]</a>
* or contact one of the main developers directly.
* <p>&nbsp;</p>
*
*
* \section sec_citing Citing qpOASES
*
* If you use qpOASES within your scientific work, we strongly encourage you to cite at least
* one of the following publications:
*
* <ul>
* <li>Reference to the <b>software</b>:
* \code
* @ARTICLE{Ferreau2014,
* author = {H.J. Ferreau and C. Kirches and A. Potschka and H.G. Bock and M. Diehl},
* title = {{qpOASES}: A parametric active-set algorithm for quadratic programming},
* journal = {Mathematical Programming Computation},
* year = {2014},
* volume = {6},
* number = {4},
* pages = {327--363},
* keywords = {qpOASES, parametric quadratic programming, active set method, model predictive control}
* }
* \endcode
*
* <li>Reference to the <b>online active set strategy</b>:
* \code
* @ARTICLE{Ferreau2008,
* author = {H.J. Ferreau and H.G. Bock and M. Diehl},
* title = {An online active set strategy to overcome the limitations of explicit MPC},
* journal = {International Journal of Robust and Nonlinear Control},
* year = {2008},
* volume = {18},
* number = {8},
* pages = {816--830},
* keywords = {model predictive control, parametric quadratic programming, online active set strategy}
* }
* \endcode
*
* <li>Reference to the <b>webpage</b>:
* \code
* @MISC{qpOASES2017,
* author = {H.J. Ferreau and A. Potschka and C. Kirches},
* title = {{qpOASES} webpage},
* howpublished = {http://www.qpOASES.org/},
* year = {2007--2017},
* keywords = {qpOASES, model predictive control, parametric quadratic programming, online active set strategy}
* }
* \endcode
* </ul>
* <p>&nbsp;</p>
*
* \section sec_moreinfo More Information
*
* More information can be found on <a href="http://www.qpOASES.org/">http://www.qpOASES.org/</a>
* and in the <a href="../manual.pdf">qpOASES User's Manual</a>.
* <p>&nbsp;</p>
*/
Binary file not shown.
@@ -0,0 +1,107 @@
##
## This file is part of qpOASES.
##
## qpOASES -- An Implementation of the Online Active Set Strategy.
## Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
## Christian Kirches et al. All rights reserved.
##
## qpOASES is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public
## License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your option) any later version.
##
## qpOASES is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
## See the GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public
## License along with qpOASES; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
##
##
## Filename: examples/Makefile
## Author: Hans Joachim Ferreau
## Version: 3.2
## Date: 2007-2017
##
include ../make.mk
##
## flags
##
IFLAGS = -I. \
-I${IDIR}
QPOASES_EXES = \
${BINDIR}/example1${EXE} \
${BINDIR}/example1a${EXE} \
${BINDIR}/example1b${EXE} \
${BINDIR}/example2${EXE} \
${BINDIR}/example3${EXE} \
${BINDIR}/example3b${EXE} \
${BINDIR}/example4${EXE} \
${BINDIR}/example5${EXE} \
${BINDIR}/exampleLP${EXE} \
${BINDIR}/qrecipe${EXE} \
${BINDIR}/qrecipeSchur${EXE}
##
## targets
##
all: ${QPOASES_EXES}
${BINDIR}/%${EXE}: %.${OBJEXT} ${LINK_DEPENDS}
@${ECHO} "Creating" $@
@${CPP} ${DEF_TARGET} ${CPPFLAGS} $< ${QPOASES_LINK} ${LINK_LIBRARIES}
${BINDIR}/example4${EXE}: example4.${OBJEXT} example4CP.cpp ${LINK_DEPENDS}
@${ECHO} "Creating" $@
@${CPP} ${DEF_TARGET} ${CPPFLAGS} $< ${QPOASES_LINK} ${LINK_LIBRARIES}
${BINDIR}/qrecipe${EXE}: qrecipe.${OBJEXT} qrecipe_data.hpp ${LINK_DEPENDS}
@${ECHO} "Creating" $@
@${CPP} ${DEF_TARGET} ${CPPFLAGS} $< ${QPOASES_LINK} ${LINK_LIBRARIES}
${BINDIR}/qrecipeSchur${EXE}: qrecipeSchur.${OBJEXT} qrecipe_data.hpp ${LINK_DEPENDS}
@${ECHO} "Creating" $@
@${CPP} ${DEF_TARGET} ${CPPFLAGS} $< ${QPOASES_LINK} ${LINK_LIBRARIES}
clean:
@${ECHO} "Cleaning up (examples)"
@${RM} -f *.${OBJEXT} ${QPOASES_EXES}
clobber: clean
${LINK_DEPENDS}:
@cd ..; ${MAKE} -s src
example4.${OBJEXT}: example4.cpp example4CP.cpp
@${ECHO} "Creating" $@
@${CPP} ${DEF_TARGET} -c ${IFLAGS} ${CPPFLAGS} $<
qrecipe.${OBJEXT}: qrecipe.cpp qrecipe_data.hpp
@${ECHO} "Creating" $@
@${CPP} ${DEF_TARGET} ${IFLAGS} ${CPPFLAGS} -c $<
qrecipeSchur.${OBJEXT}: qrecipeSchur.cpp qrecipe_data.hpp
@${ECHO} "Creating" $@
@${CPP} ${DEF_TARGET} ${IFLAGS} ${CPPFLAGS} -c $<
%.${OBJEXT}: %.cpp
@${ECHO} "Creating" $@
@${CPP} ${DEF_TARGET} -c ${IFLAGS} ${CPPFLAGS} $<
##
## end of file
##
@@ -0,0 +1,104 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file examples/example1.cpp
* \author Hans Joachim Ferreau
* \version 3.2
* \date 2007-2017
*
* Very simple example for testing qpOASES using the QProblem class.
*/
#include <qpOASES.hpp>
/** Example for qpOASES main function using the QProblem class. */
int main()
{
USING_NAMESPACE_QPOASES
/* Setup data of first QP. */
real_t H[2 * 2] = {1.0, 0.0, 0.0, 0.5};
real_t A[1 * 2] = {1.0, 1.0};
real_t g[2] = {1.5, 1.0};
real_t lb[2] = {0.5, -2.0};
real_t ub[2] = {5.0, 2.0};
real_t lbA[1] = {-1.0};
real_t ubA[1] = {2.0};
/* Setup data of second QP. */
real_t g_new[2] = {1.0, 1.5};
real_t lb_new[2] = {0.0, -1.0};
real_t ub_new[2] = {5.0, -0.5};
real_t lbA_new[1] = {-2.0};
real_t ubA_new[1] = {1.0};
/* Setting up QProblem object. */
QProblem example(2, 1);
Options options;
example.setOptions(options);
/* Solve first QP. */
int_t nWSR = 10;
example.init(H, g, A, lb, ub, lbA, ubA, nWSR);
/* Get and print solution of first QP. */
real_t xOpt[2];
real_t yOpt[2 + 1];
example.getPrimalSolution(xOpt);
example.getDualSolution(yOpt);
printf("\nxOpt = [ %e, %e ]; yOpt = [ %e, %e, %e ]; objVal = %e\n\n",
xOpt[0],
xOpt[1],
yOpt[0],
yOpt[1],
yOpt[2],
example.getObjVal());
/* Solve second QP. */
nWSR = 10;
example.hotstart(g_new, lb_new, ub_new, lbA_new, ubA_new, nWSR);
/* Get and print solution of second QP. */
example.getPrimalSolution(xOpt);
example.getDualSolution(yOpt);
printf("\nxOpt = [ %e, %e ]; yOpt = [ %e, %e, %e ]; objVal = %e\n\n",
xOpt[0],
xOpt[1],
yOpt[0],
yOpt[1],
yOpt[2],
example.getObjVal());
example.printOptions();
/*example.printProperties();*/
/*getGlobalMessageHandler()->listAllMessages();*/
return 0;
}
/*
* end of file
*/
@@ -0,0 +1,79 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file examples/example1a.cpp
* \author Hans Joachim Ferreau
* \version 3.2
* \date 2007-2017
*
* Very simple example for testing qpOASES using the SQProblem class.
*/
#include <qpOASES.hpp>
/** Example for qpOASES main function using the SQProblem class. */
int main()
{
USING_NAMESPACE_QPOASES
/* Setup data of first QP. */
real_t H[2 * 2] = {1.0, 0.0, 0.0, 0.5};
real_t A[1 * 2] = {1.0, 1.0};
real_t g[2] = {1.5, 1.0};
real_t lb[2] = {0.5, -2.0};
real_t ub[2] = {5.0, 2.0};
real_t lbA[1] = {-1.0};
real_t ubA[1] = {2.0};
/* Setup data of second QP. */
real_t H_new[2 * 2] = {1.0, 0.5, 0.5, 0.5};
real_t A_new[1 * 2] = {1.0, 5.0};
real_t g_new[2] = {1.0, 1.5};
real_t lb_new[2] = {0.0, -1.0};
real_t ub_new[2] = {5.0, -0.5};
real_t lbA_new[1] = {-2.0};
real_t ubA_new[1] = {1.0};
/* Setting up SQProblem object. */
SQProblem example(2, 1);
/* Solve first QP. */
int_t nWSR = 10;
example.init(H, g, A, lb, ub, lbA, ubA, nWSR, 0);
/* Solve second QP. */
nWSR = 10;
example.hotstart(H_new, g_new, A_new, lb_new, ub_new, lbA_new, ubA_new, nWSR, 0);
/* Get and print solution of second QP. */
real_t xOpt[2];
example.getPrimalSolution(xOpt);
printf("\nxOpt = [ %e, %e ]; objVal = %e\n\n", xOpt[0], xOpt[1], example.getObjVal());
return 0;
}
/*
* end of file
*/
@@ -0,0 +1,84 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file examples/example1b.cpp
* \author Hans Joachim Ferreau
* \version 3.2
* \date 2007-2017
*
* Very simple example for testing qpOASES using the QProblemB class.
*/
#include <qpOASES.hpp>
/** Example for qpOASES main function using the QProblemB class. */
int main()
{
USING_NAMESPACE_QPOASES
/* Setup data of first QP. */
real_t H[2 * 2] = {1.0, 0.0, 0.0, 0.5};
real_t g[2] = {1.5, 1.0};
real_t lb[2] = {0.5, -2.0};
real_t ub[2] = {5.0, 2.0};
/* Setup data of second QP. */
real_t g_new[2] = {1.0, 1.5};
real_t lb_new[2] = {0.0, -1.0};
real_t ub_new[2] = {5.0, -0.5};
/* Setting up QProblemB object. */
QProblemB example(2);
Options options;
// options.enableFlippingBounds = BT_FALSE;
options.initialStatusBounds = ST_INACTIVE;
options.numRefinementSteps = 1;
options.enableCholeskyRefactorisation = 1;
example.setOptions(options);
/* Solve first QP. */
int_t nWSR = 10;
example.init(H, g, lb, ub, nWSR, 0);
/* Get and print solution of first QP. */
real_t xOpt[2];
example.getPrimalSolution(xOpt);
printf("\nxOpt = [ %e, %e ]; objVal = %e\n\n", xOpt[0], xOpt[1], example.getObjVal());
/* Solve second QP. */
nWSR = 10;
example.hotstart(g_new, lb_new, ub_new, nWSR, 0);
// printf( "\nnWSR = %d\n\n", nWSR );
/* Get and print solution of second QP. */
example.getPrimalSolution(xOpt);
printf("\nxOpt = [ %e, %e ]; objVal = %e\n\n", xOpt[0], xOpt[1], example.getObjVal());
return 0;
}
/*
* end of file
*/
@@ -0,0 +1,115 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file examples/example2.cpp
* \author Hans Joachim Ferreau (thanks to Boris Houska)
* \version 3.2
* \date 2008-2017
*
* Very simple example for testing qpOASES in combination
* with the SolutionAnalysis class.
*/
#include <qpOASES.hpp>
/** Example for qpOASES main function using the SolutionAnalysis class. */
int main()
{
USING_NAMESPACE_QPOASES
/* Setup data of first QP. */
real_t H[2 * 2] = {1.0, 0.0, 0.0, 0.5};
real_t A[1 * 2] = {1.0, 1.0};
real_t g[2] = {1.5, 1.0};
real_t lb[2] = {0.5, -2.0};
real_t ub[2] = {5.0, 2.0};
real_t lbA[1] = {-1.0};
real_t ubA[1] = {2.0};
/* Setup data of second QP. */
real_t H_new[2 * 2] = {1.0, 0.5, 0.5, 0.5};
real_t A_new[1 * 2] = {1.0, 5.0};
real_t g_new[2] = {1.0, 1.5};
real_t lb_new[2] = {0.0, -1.0};
real_t ub_new[2] = {5.0, -0.5};
real_t lbA_new[1] = {-2.0};
real_t ubA_new[1] = {1.0};
/* Setting up SQProblem object and solution analyser. */
SQProblem example(2, 1);
SolutionAnalysis analyser;
/* Solve first QP ... */
int_t nWSR = 10;
example.init(H, g, A, lb, ub, lbA, ubA, nWSR, 0);
/* ... and analyse it. */
real_t maxKktViolation = analyser.getKktViolation(&example);
printf("maxKktViolation: %e\n", maxKktViolation);
/* Solve second QP ... */
nWSR = 10;
example.hotstart(H_new, g_new, A_new, lb_new, ub_new, lbA_new, ubA_new, nWSR, 0);
/* ... and analyse it. */
maxKktViolation = analyser.getKktViolation(&example);
printf("maxKktViolation: %e\n", maxKktViolation);
// ------------ VARIANCE-COVARIANCE EVALUATION --------------------
real_t * Var = new real_t[5 * 5];
real_t * Primal_Dual_Var = new real_t[5 * 5];
int_t run1, run2;
for (run1 = 0; run1 < 5 * 5; run1++)
Var[run1] = 0.0;
Var[0] = 1.0;
Var[6] = 1.0;
// ( 1 0 0 0 0 )
// ( 0 1 0 0 0 )
// Var = ( 0 0 0 0 0 )
// ( 0 0 0 0 0 )
// ( 0 0 0 0 0 )
analyser.getVarianceCovariance(&example, Var, Primal_Dual_Var);
printf("\nPrimal_Dual_VAR = \n");
for (run1 = 0; run1 < 5; run1++) {
for (run2 = 0; run2 < 5; run2++) {
printf(" %10f", Primal_Dual_Var[run1 * 5 + run2]);
}
printf("\n");
}
delete[] Primal_Dual_Var;
delete[] Var;
return 0;
}
/*
* end of file
*/
@@ -0,0 +1,82 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file examples/example3.cpp
* \author Hans Joachim Ferreau
* \version 3.2
* \date 2008-2017
*
* Example demonstrating usage of qpOASES for solving a QP sequence of the
* Online QP Benchmark Collection. In order to run it, you have to download
* "Example 02" from from http://www.qpOASES.org/onlineQP/ and store it into
* the directory bin/chain80w/.
*/
#include <qpOASES.hpp>
/** Example for qpOASES main function using the OQP interface. */
int main()
{
USING_NAMESPACE_QPOASES
/* 1) Define benchmark arguments. */
BooleanType isSparse = BT_FALSE;
Options options;
options.setToMPC();
options.printLevel = PL_NONE;
int_t nWSR = 600;
real_t maxCPUtime = 10.0; /* seconds */
real_t maxStationarity, maxFeasibility, maxComplementarity;
/* 2) Run benchmark. */
if (runOqpBenchmark("./chain80w/",
isSparse,
options,
nWSR,
maxCPUtime,
maxStationarity,
maxFeasibility,
maxComplementarity) != SUCCESSFUL_RETURN) {
myPrintf("In order to run this example, you need to download example no. 02\nfrom the Online QP "
"Benchmark Collection website first!\n");
return -1;
}
/* 3) Print results. */
printf("\n\n");
printf("OQP Benchmark Results:\n");
printf("======================\n\n");
printf("maximum violation stationarity: %.3e\n", maxStationarity);
printf("maximum violation feasibility: %.3e\n", maxFeasibility);
printf("maximum violation complementarity: %.3e\n", maxComplementarity);
printf("\n");
printf("maximum CPU time: %.3f milliseconds\n\n", 1000.0 * maxCPUtime);
return 0;
}
/*
* end of file
*/
@@ -0,0 +1,82 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file examples/example3b.cpp
* \author Hans Joachim Ferreau
* \version 3.2
* \date 2008-2017
*
* Example demonstrating usage of qpOASES for solving a QP sequence of the
* Online QP Benchmark Collection. In order to run it, you have to download
* "Example 02" from http://www.qpOASES.org/onlineQP/ and store it into
* the directory bin/chain80/.
*/
#include <qpOASES.hpp>
/** Example for qpOASES main function using the OQP interface. */
int main()
{
USING_NAMESPACE_QPOASES
/* 1) Define benchmark arguments. */
BooleanType isSparse = BT_FALSE;
Options options;
options.setToMPC();
options.printLevel = PL_NONE;
int_t nWSR = 300;
real_t maxCPUtime = 10.0; /* seconds */
real_t maxStationarity, maxFeasibility, maxComplementarity;
/* 2) Run benchmark. */
if (runOqpBenchmark("./chain80/",
isSparse,
options,
nWSR,
maxCPUtime,
maxStationarity,
maxFeasibility,
maxComplementarity) != SUCCESSFUL_RETURN) {
myPrintf("In order to run this example, you need to download example no. 02\nfrom the Online QP "
"Benchmark Collection website first!\n");
return -1;
}
/* 3) Print results. */
printf("\n\n");
printf("OQP Benchmark Results:\n");
printf("======================\n\n");
printf("maximum violation stationarity: %.3e\n", maxStationarity);
printf("maximum violation feasibility: %.3e\n", maxFeasibility);
printf("maximum violation complementarity: %.3e\n", maxComplementarity);
printf("\n");
printf("maximum CPU time: %.3f milliseconds\n\n", 1000.0 * maxCPUtime);
return 0;
}
/*
* end of file
*/
@@ -0,0 +1,161 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file examples/example4.cpp
* \author Hans Joachim Ferreau
* \version 3.2
* \date 2009-2017
*
* Very simple example for testing qpOASES (using the possibility to specify
* user-defined constraint product function).
*/
#include <stdlib.h>
#include "example4CP.cpp"
#include <qpOASES.hpp>
/** Example for qpOASES main function using the possibility to specify
* user-defined constraint product function. */
int main()
{
USING_NAMESPACE_QPOASES
int_t i, j;
/* Setup data of first QP... */
real_t H[7 * 7];
real_t A[50 * 7];
real_t g[7];
real_t lbA[50];
/* ( 1.0 0.5 | )
* ( 0.5 2.0 | )
* ( --------+------------------- )
* H = ( | 1e-6 )
* ( | 1e-6 )
* ( | ... )
* ( | 1e-6 ) */
for (i = 0; i < 7 * 7; ++i)
H[i] = 0.0;
for (i = 2; i < 7; ++i)
H[i * 7 + i] = 1.0e-6;
H[0] = 1.0;
H[1] = 0.5;
H[7] = 0.5;
H[8] = 2.0;
/* ( x.x x.x | 1.0 )
* ( x.x x.x | ... )
* ( x.x x.x | 1.0 )
* ( x.x x.x | 1.0 )
* A = ( x.x x.x | ... )
* ( x.x x.x | 1.0 )
* ( x.x x.x | ... )
* ( x.x x.x | 1.0 )
* ( x.x x.x | ... )
* ( x.x x.x | 1.0 ) */
for (i = 0; i < 50 * 7; ++i)
A[i] = 0.0;
for (i = 0; i < 50; ++i) {
for (j = 0; j < 2; ++j)
A[i * 7 + j] = (real_t)rand() / (real_t)RAND_MAX;
A[i * 7 + (i / 10) + 2] = 1.0;
}
/* ( -1.0 )
* ( -0.5 )
* ( ---- )
* g = ( )
* ( )
* ( )
* ( ) */
for (i = 0; i < 7; ++i)
g[i] = 0.0;
g[0] = -1.0;
g[1] = -0.5;
for (i = 0; i < 50; ++i)
lbA[i] = 1.0;
/* ... and setting up user-defined constraint product function. */
MyConstraintProduct myCP(7, 50, A);
/* Setting up QProblem object and set construct product function. */
QProblem exampleCP(7, 50);
exampleCP.setPrintLevel(PL_NONE);
exampleCP.setConstraintProduct(&myCP);
/* Solve first QP. */
real_t cputime = 1.0;
int_t nWSR = 100;
exampleCP.init(H, g, A, 0, 0, lbA, 0, nWSR, &cputime);
/* Solve second QP using a modified gradient. */
g[0] = -2.0;
g[1] = 0.5;
cputime = 1.0;
nWSR = 100;
exampleCP.hotstart(g, 0, 0, lbA, 0, nWSR, &cputime);
/* Get and print solution of second QP. */
real_t xOpt[7];
exampleCP.getPrimalSolution(xOpt);
printf("\nxOpt = [ %e, %e, %e ... ]; objVal = %e\n", xOpt[0], xOpt[1], xOpt[2], exampleCP.getObjVal());
printf("CPU time: %.3f microseconds\n\n", cputime * 1.0e6);
/* Do the same without specifying constraint product. */
QProblem example(7, 50);
example.setPrintLevel(PL_NONE);
/* Solve first QP. */
g[0] = -1.0;
g[1] = -0.5;
cputime = 1.0;
nWSR = 100;
example.init(H, g, A, 0, 0, lbA, 0, nWSR, &cputime);
/* Solve second QP using a modified gradient. */
g[0] = -2.0;
g[1] = 0.5;
cputime = 1.0;
nWSR = 100;
example.hotstart(g, 0, 0, lbA, 0, nWSR, &cputime);
/* Get and print solution of second QP. */
example.getPrimalSolution(xOpt);
printf("\nxOpt = [ %e, %e, %e ... ]; objVal = %e\n", xOpt[0], xOpt[1], xOpt[2], example.getObjVal());
printf("CPU time: %.3f microseconds\n\n", cputime * 1.0e6);
return 0;
}
/*
* end of file
*/
@@ -0,0 +1,98 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file examples/example4CP.cpp
* \author Hans Joachim Ferreau
* \version 3.2
* \date 2009-2017
*
* Sample implementation of the ConstraintProduct class tailored for Example4.
*/
BEGIN_NAMESPACE_QPOASES
/**
* \brief Example illustrating the use of the \a ConstraintProduct class.
*
* Example illustrating the use of the \a ConstraintProduct class.
*
* \author Hans Joachim Ferreau
* \version 3.2
* \date 2007-2017
*/
class MyConstraintProduct : public ConstraintProduct
{
public:
/** Default constructor. */
MyConstraintProduct(){};
/** Constructor. */
MyConstraintProduct(int_t _nV, int_t _nC, real_t * _A)
{
nV = _nV;
nC = _nC;
A = _A;
};
/** Copy constructor (flat copy). */
MyConstraintProduct(const MyConstraintProduct & rhs)
{
nV = rhs.nV;
nC = rhs.nC;
A = rhs.A;
};
/** Destructor. */
virtual ~MyConstraintProduct(){};
/** Assignment operator (flat copy). */
MyConstraintProduct & operator=(const MyConstraintProduct & rhs)
{
if (this != &rhs) {
nV = rhs.nV;
nC = rhs.nC;
A = rhs.A;
}
return *this;
};
virtual int_t operator()(int_t constrIndex, const real_t * const x, real_t * const constrValue) const
{
int_t i;
constrValue[0] = 1.0 * x[(constrIndex / 10) + 2];
for (i = 0; i < 2; ++i)
constrValue[0] += A[constrIndex * nV + i] * x[i];
return 0;
};
protected:
int_t nV; /**< Number of variables. */
int_t nC; /**< Number of constraints. */
real_t * A; /**< Pointer to full constraint matrix (typically not needed!). */
};
END_NAMESPACE_QPOASES
@@ -0,0 +1,190 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file examples/example5.cpp
* \author Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2011-2017
*
* Very simple example for testing qpOASES (using the possibility to
* compute the local linear feedback law)
*/
#include <stdlib.h>
#include "example4CP.cpp"
#include <qpOASES.hpp>
/** Example for qpOASES main function using the possibility to specify
* user-defined constraint product function. */
int main()
{
USING_NAMESPACE_QPOASES
int_t i, j, jj;
real_t d = 0.0;
/* Setup data of first QP... */
real_t H[7 * 7];
real_t A[50 * 7];
real_t g[7];
real_t lbA[50];
/* ( 1.0 0.5 | )
* ( 0.5 2.0 | )
* ( --------+------------------- )
* H = ( | 1e-6 )
* ( | 1e-6 )
* ( | ... )
* ( | 1e-6 ) */
for (i = 0; i < 7 * 7; ++i)
H[i] = 0.0;
for (i = 2; i < 7; ++i)
H[i * 7 + i] = 1.0e-6;
H[0] = 1.0;
H[1] = 0.5;
H[7] = 0.5;
H[8] = 2.0;
/* ( x.x x.x | 1.0 )
* ( x.x x.x | ... )
* ( x.x x.x | 1.0 )
* ( x.x x.x | 1.0 )
* A = ( x.x x.x | ... )
* ( x.x x.x | 1.0 )
* ( x.x x.x | ... )
* ( x.x x.x | 1.0 )
* ( x.x x.x | ... )
* ( x.x x.x | 1.0 ) */
for (i = 0; i < 50 * 7; ++i)
A[i] = 0.0;
for (i = 0; i < 50; ++i) {
for (j = 0; j < 2; ++j)
A[i * 7 + j] = (real_t)rand() / (real_t)RAND_MAX;
A[i * 7 + (i / 10) + 2] = 1.0;
}
/* ( -1.0 )
* ( -0.5 )
* ( ---- )
* g = ( )
* ( )
* ( )
* ( ) */
for (i = 0; i < 7; ++i)
g[i] = 0.0;
g[0] = -1.0;
g[1] = -0.5;
for (i = 0; i < 50; ++i)
lbA[i] = 1.0;
/* ... and setting up user-defined constraint product function. */
MyConstraintProduct myCP(7, 50, A);
/* Setting up QProblem object and set construct product function. */
QProblem example(7, 50);
example.setConstraintProduct(&myCP);
/* Solve first QP. */
real_t cputime = 1.0;
int_t nWSR = 100;
example.init(H, g, A, 0, 0, lbA, 0, nWSR, &cputime);
/* Get and print solution of QP. */
real_t xOpt[7], yOpt[7 + 50];
example.getPrimalSolution(xOpt);
example.getDualSolution(yOpt);
/* Compute local linear feedback law */
const int_t n_rhs = 7 + 7 + 50;
real_t g_in[7 * n_rhs];
real_t b_in[7 * n_rhs];
real_t bA_in[50 * n_rhs];
real_t x_out[7 * n_rhs];
real_t y_out[(7 + 50) * n_rhs];
int_t ii;
memset(g_in, 0, sizeof(g_in));
memset(b_in, 0, sizeof(b_in));
memset(bA_in, 0, sizeof(bA_in));
for (ii = 0; ii < 7; ++ii)
g_in[ii * 7 + ii] = 1.0;
for (ii = 0; ii < 7; ++ii)
b_in[(ii + 7) * 7 + ii] = 1.0;
for (ii = 0; ii < 50; ++ii)
bA_in[(ii + 14) * 50 + ii] = 1.0;
example.solveCurrentEQP(n_rhs, g_in, b_in, b_in, bA_in, bA_in, x_out, y_out);
/* Verify validity of local feedback law by perturbation and hot starts */
real_t perturb = 1.0e-6;
real_t nrm = 0.0;
for (ii = 0; ii < n_rhs; ++ii) {
for (jj = 0; jj < 7; ++jj)
g_in[ii * 7 + jj] = g[jj] + g_in[ii * 7 + jj] * perturb;
for (jj = 0; jj < 50; ++jj)
bA_in[ii * 50 + jj] = lbA[jj] + bA_in[ii * 50 + jj] * perturb;
nWSR = 100;
example.hotstart(&g_in[ii * 7], 0, 0, &bA_in[ii * 50], 0, nWSR, 0);
real_t xPer[7], yPer[7 + 50];
example.getPrimalSolution(xPer);
example.getDualSolution(yPer);
for (jj = 0; jj < 7; ++jj) {
d = getAbs(x_out[ii * 7 + jj] * perturb - (xPer[jj] - xOpt[jj]));
if (nrm < d)
nrm = d;
}
for (jj = 0; jj < 7 + 50; ++jj) {
d = getAbs(y_out[ii * (7 + 50) + jj] * perturb - (yPer[jj] - yOpt[jj]));
if (nrm < d)
nrm = d;
}
}
printf("Maximum perturbation over all directions: %e\n", nrm);
/* // print feedback matrix
for (ii = 0; ii < n_rhs; ++ii)
{
printf ("x: ");
for (jj = 0; jj < 7; ++jj )
printf ("%8.2e ", x_out[ii*7+jj]);
printf (" y: ");
for (jj = 0; jj < 7+50; ++jj )
printf ("%8.2e ", y_out[ii*(7+50)+jj]);
printf("\n");
}
*/
return 0;
}
/*
* end of file
*/
@@ -0,0 +1,80 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file examples/exampleLP.cpp
* \author Hans Joachim Ferreau
* \version 3.2
* \date 2008-2017
*
* Very simple example for solving a LP sequence using qpOASES.
*/
#include <qpOASES.hpp>
/** Example for qpOASES main function solving LPs. */
int main()
{
USING_NAMESPACE_QPOASES
/* Setup data of first LP. */
real_t A[1 * 2] = {1.0, 1.0};
real_t g[2] = {1.5, 1.0};
real_t lb[2] = {0.5, -2.0};
real_t ub[2] = {5.0, 2.0};
real_t lbA[1] = {-1.0};
real_t ubA[1] = {2.0};
/* Setup data of second LP. */
real_t g_new[2] = {1.0, 1.5};
real_t lb_new[2] = {0.0, -1.0};
real_t ub_new[2] = {5.0, -0.5};
real_t lbA_new[1] = {-2.0};
real_t ubA_new[1] = {1.0};
/* Setting up QProblem object with zero Hessian matrix. */
QProblem example(2, 1, HST_ZERO);
Options options;
// options.setToMPC();
example.setOptions(options);
/* Solve first LP. */
int_t nWSR = 10;
example.init(0, g, A, lb, ub, lbA, ubA, nWSR, 0);
/* Solve second LP. */
nWSR = 10;
example.hotstart(g_new, lb_new, ub_new, lbA_new, ubA_new, nWSR, 0);
/* Get and print solution of second LP. */
real_t xOpt[2];
example.getPrimalSolution(xOpt);
printf("\nxOpt = [ %e, %e ]; objVal = %e\n\n", xOpt[0], xOpt[1], example.getObjVal());
return 0;
}
/*
* end of file
*/
@@ -0,0 +1,58 @@
import numpy as np
import scipy as sp
from scipy.sparse import csc_matrix, coo_matrix, csr_matrix, lil_matrix, random
from jinja2 import Environment
from jinja2.loaders import FileSystemLoader
import os
seed = 42
density = 0.1
gamma = 0.01
out_file_name = 'qp_data.hpp'
in_file_name = 'qp_data.in.hpp'
NV = 100
NC = 10
H = csc_matrix((NV, NV))
A = csc_matrix((NV, NV))
myinf = 1e10
for i in range(NV):
H[i,i] = 1.0
# H = H + gamma*random(NV, NV, density=density, format='csc', random_state=seed)
# H = H.T*H
for i in range(NC):
A[i,i] = 1.0
H_ri = H.indices
H_cp = H.indptr
H_val = H.data
H_nnz = H.nnz
A_ri = A.indices
A_cp = A.indptr
A_val = A.data
A_nnz = A.nnz
g = np.ones((NV,1))
lb = -myinf*np.ones((NV, 1))
ub = myinf*np.ones((NV, 1))
lbA = -np.ones((NC, 1))
ubA = np.ones((NC, 1))
print('rendering templated C++ code...')
env = Environment(loader=FileSystemLoader(os.path.dirname(os.path.abspath(__file__))))
tmpl = env.get_template(in_file_name)
code = tmpl.render(NV = NV, NC = NC, H_cp = H_cp, H_ri = H_ri, H_val = H_val, H_nnz = H_nnz, \
A_cp = A_cp, A_ri = A_ri, A_val = A_val, A_nnz = A_nnz, g = g, lb = lb, ub = ub, lbA = lbA, ubA = ubA)
with open(out_file_name, "w+") as f:
f.write(code.replace('inf', 'Inf'))
@@ -0,0 +1,116 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \author Andrea Zanelli
* \version 3.2
* \date 2022
*
* QP data generated by a Python script for testing purposes.
*/
USING_NAMESPACE_QPOASES
#define NV \
{ \
{ \
NV \
} \
}
#define NC \
{ \
{ \
NC \
} \
}
const real_t Inf = INFTY;
sparse_int_t H_ri[] = {
{% for d in H_ri %}
{{ d }},
{%- endfor %}
};
sparse_int_t H_cp[] = {
{% for d in H_cp %}
{{ d }},
{%- endfor %}
};
real_t H_val[] = {
{% for d in H_val %}
{{ d }},
{%- endfor %}
};
sparse_int_t A_ri[] = {
{% for d in A_ri %}
{{ d }},
{%- endfor %}
};
sparse_int_t A_cp[] = {
{% for d in A_cp %}
{{ d }},
{%- endfor %}
};
real_t A_val[] = {
{% for d in A_val %}
{{ d }},
{%- endfor %}
};
real_t g[] = {
{% for d in g %}
{{ d[0] }},
{%- endfor %}
};
real_t lb[] = {
{% for d in lb %}
{{ d[0] }},
{%- endfor %}
};
real_t ub[] = {
{% for d in ub %}
{{ d[0] }},
{%- endfor %}
};
real_t lbA[] = {
{% for d in lbA %}
{{ d[0] }},
{%- endfor %}
};
real_t ubA[] = {
{% for d in ubA %}
{{ d[0] }},
{%- endfor %}
};
long H_nnz = {{H_nnz}};
long A_nnz = {{A_nnz}};
@@ -0,0 +1,826 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \author Andrea Zanelli
* \version 3.2
* \date 2022
*
* QP data generated by a Python script for testing purposes.
*/
USING_NAMESPACE_QPOASES
#define NV 100
#define NC 10
const real_t Inf = INFTY;
sparse_int_t H_ri[] = {
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63,
64,
65,
66,
67,
68,
69,
70,
71,
72,
73,
74,
75,
76,
77,
78,
79,
80,
81,
82,
83,
84,
85,
86,
87,
88,
89,
90,
91,
92,
93,
94,
95,
96,
97,
98,
99,
};
sparse_int_t H_cp[] = {
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63,
64,
65,
66,
67,
68,
69,
70,
71,
72,
73,
74,
75,
76,
77,
78,
79,
80,
81,
82,
83,
84,
85,
86,
87,
88,
89,
90,
91,
92,
93,
94,
95,
96,
97,
98,
99,
100,
};
real_t H_val[] = {
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
};
sparse_int_t A_ri[] = {
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
};
sparse_int_t A_cp[] = {
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
10,
};
real_t A_val[] = {
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
};
real_t g[] = {
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
};
real_t lb[] = {
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
-10000000000.0,
};
real_t ub[] = {
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
10000000000.0,
};
real_t lbA[] = {
-1.0,
-1.0,
-1.0,
-1.0,
-1.0,
-1.0,
-1.0,
-1.0,
-1.0,
-1.0,
};
real_t ubA[] = {
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
};
long H_nnz = 100;
long A_nnz = 10;
@@ -0,0 +1,112 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file examples/qrecipe.cpp
* \author Andreas Potschka
* \version 3.2
* \date 2007-2017
*
* QRECIPE example from the CUTEr test set with sparse matrices.
*/
#include <qpOASES.hpp>
#include "qrecipe_data.hpp"
int main()
{
USING_NAMESPACE_QPOASES
long i;
int_t nWSR;
real_t err, tic, toc;
real_t * x1 = new real_t[180];
real_t * y1 = new real_t[271];
real_t * x2 = new real_t[180];
real_t * y2 = new real_t[271];
/* create sparse matrices */
SymSparseMat * H = new SymSparseMat(180, 180, H_ri, H_cp, H_val);
SparseMatrix * A = new SparseMatrix(91, 180, A_ri, A_cp, A_val);
H->createDiagInfo();
real_t * H_full = H->full();
real_t * A_full = A->full();
SymDenseMat * Hd = new SymDenseMat(180, 180, 180, H_full);
DenseMatrix * Ad = new DenseMatrix(91, 180, 180, A_full);
/* solve with dense matrices */
nWSR = 1000;
QProblem qrecipeD(180, 91);
tic = getCPUtime();
qrecipeD.init(Hd, g, Ad, lb, ub, lbA, ubA, nWSR, 0);
toc = getCPUtime();
qrecipeD.getPrimalSolution(x1);
qrecipeD.getDualSolution(y1);
fprintf(stdFile, "Solved dense problem in %d iterations, %.3f seconds.\n", (int)nWSR, toc - tic);
/* solve with sparse matrices */
nWSR = 1000;
QProblem qrecipeS(180, 91);
tic = getCPUtime();
qrecipeS.init(H, g, A, lb, ub, lbA, ubA, nWSR, 0);
toc = getCPUtime();
qrecipeS.getPrimalSolution(x2);
qrecipeS.getDualSolution(y2);
fprintf(stdFile, "Solved sparse problem in %d iterations, %.3f seconds.\n", (int)nWSR, toc - tic);
/* check distance of solutions */
err = 0.0;
for (i = 0; i < 180; i++)
if (getAbs(x1[i] - x2[i]) > err)
err = getAbs(x1[i] - x2[i]);
fprintf(stdFile, "Primal error: %9.2e\n", err);
err = 0.0;
for (i = 0; i < 271; i++)
if (getAbs(y1[i] - y2[i]) > err)
err = getAbs(y1[i] - y2[i]);
fprintf(stdFile, "Dual error: %9.2e (might not be unique)\n", err);
delete H;
delete A;
delete[] H_full;
delete[] A_full;
delete Hd;
delete Ad;
delete[] y2;
delete[] x2;
delete[] y1;
delete[] x1;
return 0;
}
/*
* end of file
*/
@@ -0,0 +1,164 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file examples/qrecipeSchur.cpp
* \author Dennis Janka
* \version 3.2
* \date 2007-2017
*
* QRECIPE example from the CUTEr test set with sparse matrices.
* Comparison between nullspace factorization (dense and sparse) and
* Schur complement approach.
*/
#include "qrecipe_data.hpp"
#include <qpOASES.hpp>
// #include "generate_sparse_qp/qp_data.hpp"
// #include "generate_sparse_qp/simple_qp_data.hpp"
// #include "generate_sparse_qp/trivial_qp_data.hpp"
int main()
{
USING_NAMESPACE_QPOASES
long i;
int_t nWSR;
real_t errP1, errP2, errP3, errD1, errD2, errD3, tic, toc;
real_t * x1 = new real_t[NV];
real_t * y1 = new real_t[NV + NC];
real_t * x2 = new real_t[NV];
real_t * y2 = new real_t[NV + NC];
real_t * x3 = new real_t[NV];
real_t * y3 = new real_t[NV + NC];
/* create sparse matrices */
SymSparseMat * H = new SymSparseMat(NV, NV, H_ri, H_cp, H_val);
SparseMatrix * A = new SparseMatrix(NC, NV, A_ri, A_cp, A_val);
H->createDiagInfo();
real_t * H_full = H->full();
for (int i = 0; i < NV; i++)
for (int j = 0; j < NV; j++)
printf("H[%i,%i] = %f\n", i, j, H_full[i * NV + j]);
real_t * A_full = A->full();
SymDenseMat * Hd = new SymDenseMat(NV, NV, NV, H_full);
DenseMatrix * Ad = new DenseMatrix(NC, NV, NV, A_full);
/* solve with dense matrices */
nWSR = 1000;
QProblem qrecipeD(NV, NC);
tic = getCPUtime();
qrecipeD.init(Hd, g, Ad, lb, ub, lbA, ubA, nWSR, 0);
toc = getCPUtime();
qrecipeD.getPrimalSolution(x1);
qrecipeD.getDualSolution(y1);
fprintf(stdFile, "Solved dense problem in %d iterations, %.3f seconds.\n", (int)nWSR, toc - tic);
/* solve with sparse matrices (nullspace factorization) */
nWSR = 1000;
QProblem qrecipeS(NV, NC);
tic = getCPUtime();
qrecipeS.init(H, g, A, lb, ub, lbA, ubA, nWSR, 0);
toc = getCPUtime();
qrecipeS.getPrimalSolution(x2);
qrecipeS.getDualSolution(y2);
fprintf(stdFile, "Solved sparse problem in %d iterations, %.3f seconds.\n", (int)nWSR, toc - tic);
/* solve with sparse matrices (Schur complement) */
nWSR = 1000;
SQProblemSchur qrecipeSchur(NV, NC);
tic = getCPUtime();
qrecipeSchur.init(H, g, A, lb, ub, lbA, ubA, nWSR, 0);
toc = getCPUtime();
qrecipeSchur.getPrimalSolution(x3);
qrecipeSchur.getDualSolution(y3);
fprintf(stdFile,
"Solved sparse problem (Schur complement approach) in %d iterations, %.3f seconds.\n",
(int)nWSR,
toc - tic);
/* check distance of solutions */
errP1 = 0.0;
errP2 = 0.0;
errP3 = 0.0;
#ifndef SOLVER_NONE
for (i = 0; i < NV; i++) {
fprintf(stdFile, "x3[%i]=%f\n", i, x3[i]);
if (getAbs(x1[i] - x2[i]) > errP1)
errP1 = getAbs(x1[i] - x2[i]);
}
for (i = 0; i < NV; i++)
if (getAbs(x1[i] - x3[i]) > errP2)
errP2 = getAbs(x1[i] - x3[i]);
for (i = 0; i < NV; i++)
if (getAbs(x2[i] - x3[i]) > errP3)
errP3 = getAbs(x2[i] - x3[i]);
#endif /* SOLVER_NONE */
fprintf(stdFile, "Primal error (dense and sparse): %9.2e\n", errP1);
fprintf(stdFile, "Primal error (dense and Schur): %9.2e\n", errP2);
fprintf(stdFile, "Primal error (sparse and Schur): %9.2e\n", errP3);
errD1 = 0.0;
errD2 = 0.0;
errD3 = 0.0;
for (i = 0; i < NV + NC; i++)
if (getAbs(y1[i] - y2[i]) > errD1)
errD1 = getAbs(y1[i] - y2[i]);
#ifndef SOLVER_NONE
for (i = 0; i < NV + NC; i++)
if (getAbs(y1[i] - y3[i]) > errD2)
errD2 = getAbs(y1[i] - y3[i]);
for (i = 0; i < NV + NC; i++)
if (getAbs(y2[i] - y3[i]) > errD3)
errD3 = getAbs(y2[i] - y3[i]);
#endif /* SOLVER_NONE */
fprintf(stdFile, "Dual error (dense and sparse): %9.2e (might not be unique)\n", errD1);
fprintf(stdFile, "Dual error (dense and Schur): %9.2e (might not be unique)\n", errD2);
fprintf(stdFile, "Dual error (sparse and Schur): %9.2e (might not be unique)\n", errD3);
delete H;
delete A;
delete[] H_full;
delete[] A_full;
delete Hd;
delete Ad;
delete[] y3;
delete[] x3;
delete[] y2;
delete[] x2;
delete[] y1;
delete[] x1;
return 0;
}
/*
* end of file
*/
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,71 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES.hpp
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*/
#if defined(__SINGLE_OBJECT__) || defined(__C_WRAPPER__)
#include <Bounds.cpp>
#include <Constraints.cpp>
#include <Indexlist.cpp>
#include <MessageHandling.cpp>
#include <SubjectTo.cpp>
#include <Utils.cpp>
#if !defined(__MATLAB__) || defined(WIN32)
#include <BLASReplacement.cpp>
#include <LAPACKReplacement.cpp>
#endif
#include <Flipper.cpp>
#include <Matrices.cpp>
#include <Options.cpp>
#include <QProblem.cpp>
#include <QProblemB.cpp>
#include <SQProblem.cpp>
#if defined(SOLVER_MA27) || defined(SOLVER_MA57)
#include <SQProblemSchur.cpp>
#include <SparseSolver.cpp>
#endif
#if !defined(__C_WRAPPER__) && !defined(__MATLAB__)
#include <OQPinterface.cpp>
#include <SolutionAnalysis.cpp>
#endif
#else /* default compilation mode */
#include <qpOASES/QProblem.hpp>
#include <qpOASES/QProblemB.hpp>
#include <qpOASES/SQProblem.hpp>
#include <qpOASES/SQProblemSchur.hpp>
#include <qpOASES/extras/OQPinterface.hpp>
#include <qpOASES/extras/SolutionAnalysis.hpp>
#endif
@@ -0,0 +1,240 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/Bounds.hpp
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*
* Declaration of the Bounds class designed to manage working sets of
* bounds within a QProblem.
*/
#ifndef QPOASES_BOUNDS_HPP
#define QPOASES_BOUNDS_HPP
#include <qpOASES/SubjectTo.hpp>
BEGIN_NAMESPACE_QPOASES
/**
* \brief Manages working sets of bounds (i.e. box constraints).
*
* This class manages working sets of bounds (= box constraints)
* by storing index sets and other status information.
*
* \author Hans Joachim Ferreau
* \version 3.2
* \date 2007-2017
*/
class Bounds : public SubjectTo
{
/*
* PUBLIC MEMBER FUNCTIONS
*/
public:
/** Default constructor. */
Bounds();
/** Constructor which takes the number of bounds. */
Bounds(int_t _n /**< Number of bounds. */
);
/** Copy constructor (deep copy). */
Bounds(const Bounds & rhs /**< Rhs object. */
);
/** Destructor. */
virtual ~Bounds();
/** Assignment operator (deep copy). */
Bounds & operator=(const Bounds & rhs /**< Rhs object. */
);
/** Initialises object with given number of bounds.
* \return SUCCESSFUL_RETURN \n
RET_INVALID_ARGUMENTS */
returnValue init(int_t _n = 0 /**< Number of bounds. */
);
/** Initially adds number of a new (i.e. not yet in the list) bound to
* given index set.
* \return SUCCESSFUL_RETURN \n
RET_SETUP_BOUND_FAILED \n
RET_INDEX_OUT_OF_BOUNDS \n
RET_INVALID_ARGUMENTS */
returnValue setupBound(int_t number, /**< Number of new bound. */
SubjectToStatus _status /**< Status of new bound. */
);
/** Initially adds all numbers of new (i.e. not yet in the list) bounds to
* to the index set of free bounds; the order depends on the SujectToType
* of each index.
* \return SUCCESSFUL_RETURN \n
RET_SETUP_BOUND_FAILED */
returnValue setupAllFree();
/** Initially adds all numbers of new (i.e. not yet in the list) bounds to
* to the index set of fixed bounds (on their lower bounds);
* the order depends on the SujectToType of each index.
* \return SUCCESSFUL_RETURN \n
RET_SETUP_BOUND_FAILED */
returnValue setupAllLower();
/** Initially adds all numbers of new (i.e. not yet in the list) bounds to
* to the index set of fixed bounds (on their upper bounds);
* the order depends on the SujectToType of each index.
* \return SUCCESSFUL_RETURN \n
RET_SETUP_BOUND_FAILED */
returnValue setupAllUpper();
/** Moves index of a bound from index list of fixed to that of free bounds.
* \return SUCCESSFUL_RETURN \n
RET_MOVING_BOUND_FAILED \n
RET_INDEX_OUT_OF_BOUNDS */
returnValue moveFixedToFree(int_t number /**< Number of bound to be freed. */
);
/** Moves index of a bound from index list of free to that of fixed bounds.
* \return SUCCESSFUL_RETURN \n
RET_MOVING_BOUND_FAILED \n
RET_INDEX_OUT_OF_BOUNDS */
returnValue moveFreeToFixed(int_t number, /**< Number of bound to be fixed. */
SubjectToStatus _status /**< Status of bound to be fixed. */
);
/** Flip fixed bound.
* \return SUCCESSFUL_RETURN \n
RET_MOVING_BOUND_FAILED \n
RET_INDEX_OUT_OF_BOUNDS */
returnValue flipFixed(int_t number);
/** Swaps the indices of two free bounds within the index set.
* \return SUCCESSFUL_RETURN \n
RET_SWAPINDEX_FAILED */
returnValue swapFree(int_t number1, /**< Number of first constraint or bound. */
int_t number2 /**< Number of second constraint or bound. */
);
/** Returns number of variables.
* \return Number of variables. */
inline int_t getNV() const;
/** Returns number of implicitly fixed variables.
* \return Number of implicitly fixed variables. */
inline int_t getNFV() const;
/** Returns number of bounded (but possibly free) variables.
* \return Number of bounded (but possibly free) variables. */
inline int_t getNBV() const;
/** Returns number of unbounded variables.
* \return Number of unbounded variables. */
inline int_t getNUV() const;
/** Returns number of free variables.
* \return Number of free variables. */
inline int_t getNFR() const;
/** Returns number of fixed variables.
* \return Number of fixed variables. */
inline int_t getNFX() const;
/** Returns a pointer to free variables index list.
* \return Pointer to free variables index list. */
inline Indexlist * getFree();
/** Returns a pointer to fixed variables index list.
* \return Pointer to fixed variables index list. */
inline Indexlist * getFixed();
/** Shifts forward type and status of all bounds by a given
* offset. This offset has to lie within the range [0,n/2] and has to
* be an integer divisor of the total number of bounds n.
* Type and status of the first \<offset\> bounds is thrown away,
* type and status of the last \<offset\> bounds is doubled,
* e.g. for offset = 2: \n
* shift( {b1,b2,b3,b4,b5,b6} ) = {b3,b4,b5,b6,b5,b6}
* \return SUCCESSFUL_RETURN \n
RET_INDEX_OUT_OF_BOUNDS \n
RET_INVALID_ARGUMENTS \n
RET_SHIFTING_FAILED */
virtual returnValue shift(
int_t offset /**< Shift offset within the range [0,n/2] and integer divisor of n. */
);
/** Rotates forward type and status of all bounds by a given
* offset. This offset has to lie within the range [0,n].
* Example for offset = 2: \n
* rotate( {b1,b2,b3,b4,b5,b6} ) = {b3,b4,b5,b6,b1,b2}
* \return SUCCESSFUL_RETURN \n
RET_INDEX_OUT_OF_BOUNDS \n
RET_ROTATING_FAILED */
virtual returnValue rotate(int_t offset /**< Rotation offset within the range [0,n]. */
);
/** Prints information on bounds object
* (in particular, lists of free and fixed bounds.
* \return SUCCESSFUL_RETURN \n
RET_INDEXLIST_CORRUPTED */
returnValue print();
/*
* PROTECTED MEMBER FUNCTIONS
*/
protected:
/** Frees all allocated memory.
* \return SUCCESSFUL_RETURN */
returnValue clear();
/** Copies all members from given rhs object.
* \return SUCCESSFUL_RETURN */
returnValue copy(const Bounds & rhs /**< Rhs object. */
);
/** Initially adds all numbers of new (i.e. not yet in the list) bounds to
* to the index set corresponding to the desired status;
* the order depends on the SujectToType of each index.
* \return SUCCESSFUL_RETURN \n
RET_SETUP_BOUND_FAILED */
returnValue setupAll(SubjectToStatus _status /**< Desired initial status for all bounds. */
);
/*
* PROTECTED MEMBER VARIABLES
*/
protected:
Indexlist freee; /**< Index list of free variables. */
Indexlist fixed; /**< Index list of fixed variables. */
};
END_NAMESPACE_QPOASES
#include <qpOASES/Bounds.ipp>
#endif /* QPOASES_BOUNDS_HPP */
/*
* end of file
*/
@@ -0,0 +1,120 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/Bounds.ipp
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*
* Implementation of inlined member functions of the Bounds class designed
* to manage working sets of bounds within a QProblem.
*/
BEGIN_NAMESPACE_QPOASES
/*****************************************************************************
* P U B L I C *
*****************************************************************************/
/*
* g e t N V
*/
inline int_t Bounds::getNV( ) const
{
return n;
}
/*
* g e t N F V
*/
inline int_t Bounds::getNFV( ) const
{
return getNumberOfType( ST_EQUALITY );
}
/*
* g e t N B V
*/
inline int_t Bounds::getNBV( ) const
{
return getNumberOfType( ST_BOUNDED );
}
/*
* g e t N U V
*/
inline int_t Bounds::getNUV( ) const
{
return getNumberOfType( ST_UNBOUNDED );
}
/*
* g e t N F R
*/
inline int_t Bounds::getNFR( ) const
{
return freee.getLength( );
}
/*
* g e t N F X
*/
inline int_t Bounds::getNFX( ) const
{
return fixed.getLength( );
}
/*
* g e t F r e e
*/
inline Indexlist* Bounds::getFree( )
{
return &freee;
}
/*
* g e t F i x e d
*/
inline Indexlist* Bounds::getFixed( )
{
return &fixed;
}
END_NAMESPACE_QPOASES
/*
* end of file
*/
@@ -0,0 +1,67 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/Constants.hpp
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*
* Definition of all global constants.
*/
#ifndef QPOASES_CONSTANTS_HPP
#define QPOASES_CONSTANTS_HPP
#include <qpOASES/Types.hpp>
BEGIN_NAMESPACE_QPOASES
/** Numerical value of machine precision (min eps, s.t. 1+eps > 1).
* Note: this value has to be positive! */
#ifdef __USE_SINGLE_PRECISION__
const real_t EPS = 1.193e-07f;
#else
const real_t EPS = 2.221e-16;
#endif /* __USE_SINGLE_PRECISION__ */
/** Numerical value of zero (for situations in which it would be
* unreasonable to compare with 0.0).
* Note: this value has to be positive! */
const real_t ZERO = 1.0e-25;
/** Numerical value of infinity (e.g. for non-existing bounds).
Note: this value has to be positive! */
const real_t INFTY = 1.0e20;
/** Maximum number of characters within a string.
* Note: this value should be at least 41! */
const uint_t MAX_STRING_LENGTH = 160;
END_NAMESPACE_QPOASES
#endif /* QPOASES_CONSTANTS_HPP */
/*
* end of file
*/
@@ -0,0 +1,87 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/ConstraintProduct.hpp
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2009-2017
*
* Declaration of the ConstraintProduct class which allows to specify a
* user-defined function for evaluating the constraint product at the
* current iterate to speed-up QP solution in case of a specially structured
* constraint matrix.
*/
#ifndef QPOASES_CONSTRAINT_PRODUCT_HPP
#define QPOASES_CONSTRAINT_PRODUCT_HPP
#include <qpOASES/Types.hpp>
BEGIN_NAMESPACE_QPOASES
/**
* \brief Interface for specifying user-defined evaluations of constraint products.
*
* A class which allows to specify a user-defined function for evaluating the
* constraint product at the current iterate to speed-up QP solution in case
* of a specially structured constraint matrix.
*
* \author Hans Joachim Ferreau
* \version 3.2
* \date 2009-2017
*/
class ConstraintProduct
{
public:
/** Default constructor. */
ConstraintProduct(){};
/** Copy constructor. */
ConstraintProduct(const ConstraintProduct & toCopy /**< Rhs object. */
){};
/** Destructor. */
virtual ~ConstraintProduct(){};
/** Assignment operator. */
ConstraintProduct & operator=(const ConstraintProduct & toCopy /**< Rhs object. */
)
{
return *this;
}
/** Evaluates the product of a given constraint with the current iterate.
* This function needs to be implemented in a derived class for the
* user-defined constraint product function.
* \return 0: successful \n
otherwise: not successful */
virtual int_t operator()(int_t constrIndex, /**< Number of constraint to be evaluated. */
const real_t * const x, /**< Array containing current primal iterate. */
real_t * const constrValue /**< Output: Scalar value of the evaluated constraint. */
) const = 0;
};
END_NAMESPACE_QPOASES
#endif /* QPOASES_CONSTRAINT_PRODUCT_HPP */
@@ -0,0 +1,231 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/Constraints.hpp
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*
* Declaration of the Constraints class designed to manage working sets of
* constraints within a QProblem.
*/
#ifndef QPOASES_CONSTRAINTS_HPP
#define QPOASES_CONSTRAINTS_HPP
#include <qpOASES/SubjectTo.hpp>
BEGIN_NAMESPACE_QPOASES
/**
* \brief Manages working sets of constraints.
*
* This class manages working sets of constraints by storing
* index sets and other status information.
*
* \author Hans Joachim Ferreau
* \version 3.2
* \date 2007-2017
*/
class Constraints : public SubjectTo
{
/*
* PUBLIC MEMBER FUNCTIONS
*/
public:
/** Default constructor. */
Constraints();
/** Constructor which takes the number of constraints. */
Constraints(int_t _n /**< Number of constraints. */
);
/** Copy constructor (deep copy). */
Constraints(const Constraints & rhs /**< Rhs object. */
);
/** Destructor. */
virtual ~Constraints();
/** Assignment operator (deep copy). */
Constraints & operator=(const Constraints & rhs /**< Rhs object. */
);
/** Initialises object with given number of constraints.
* \return SUCCESSFUL_RETURN \n
RET_INVALID_ARGUMENTS */
returnValue init(int_t _n = 0 /**< Number of constraints. */
);
/** Initially adds number of a new (i.e. not yet in the list) constraint to
* a given index set.
* \return SUCCESSFUL_RETURN \n
RET_SETUP_CONSTRAINT_FAILED \n
RET_INDEX_OUT_OF_BOUNDS \n
RET_INVALID_ARGUMENTS */
returnValue setupConstraint(int_t number, /**< Number of new constraint. */
SubjectToStatus _status /**< Status of new constraint. */
);
/** Initially adds all enabled numbers of new (i.e. not yet in the list) constraints to
* to the index set of inactive constraints; the order depends on the SujectToType
* of each index. Only disabled constraints are added to index set of disabled constraints!
* \return SUCCESSFUL_RETURN \n
RET_SETUP_CONSTRAINT_FAILED */
returnValue setupAllInactive();
/** Initially adds all enabled numbers of new (i.e. not yet in the list) constraints to
* to the index set of active constraints (on their lower bounds); the order depends on the SujectToType
* of each index. Only disabled constraints are added to index set of disabled constraints!
* \return SUCCESSFUL_RETURN \n
RET_SETUP_CONSTRAINT_FAILED */
returnValue setupAllLower();
/** Initially adds all enabled numbers of new (i.e. not yet in the list) constraints to
* to the index set of active constraints (on their upper bounds); the order depends on the SujectToType
* of each index. Only disabled constraints are added to index set of disabled constraints!
* \return SUCCESSFUL_RETURN \n
RET_SETUP_CONSTRAINT_FAILED */
returnValue setupAllUpper();
/** Moves index of a constraint from index list of active to that of inactive constraints.
* \return SUCCESSFUL_RETURN \n
RET_MOVING_CONSTRAINT_FAILED */
returnValue moveActiveToInactive(int_t number /**< Number of constraint to become inactive. */
);
/** Moves index of a constraint from index list of inactive to that of active constraints.
* \return SUCCESSFUL_RETURN \n
RET_MOVING_CONSTRAINT_FAILED */
returnValue moveInactiveToActive(int_t number, /**< Number of constraint to become active. */
SubjectToStatus _status /**< Status of constraint to become active. */
);
/** Flip fixed constraint.
* \return SUCCESSFUL_RETURN \n
RET_MOVING_CONSTRAINT_FAILED \n
RET_INDEX_OUT_OF_BOUNDS */
returnValue flipFixed(int_t number);
/** Returns the number of constraints.
* \return Number of constraints. */
inline int_t getNC() const;
/** Returns the number of implicit equality constraints.
* \return Number of implicit equality constraints. */
inline int_t getNEC() const;
/** Returns the number of "real" inequality constraints.
* \return Number of "real" inequality constraints. */
inline int_t getNIC() const;
/** Returns the number of unbounded constraints (i.e. without any bounds).
* \return Number of unbounded constraints (i.e. without any bounds). */
inline int_t getNUC() const;
/** Returns the number of active constraints.
* \return Number of active constraints. */
inline int_t getNAC() const;
/** Returns the number of inactive constraints.
* \return Number of inactive constraints. */
inline int_t getNIAC() const;
/** Returns a pointer to active constraints index list.
* \return Pointer to active constraints index list. */
inline Indexlist * getActive();
/** Returns a pointer to inactive constraints index list.
* \return Pointer to inactive constraints index list. */
inline Indexlist * getInactive();
/** Shifts forward type and status of all constraints by a given
* offset. This offset has to lie within the range [0,n/2] and has to
* be an integer divisor of the total number of constraints n.
* Type and status of the first \<offset\> constraints is thrown away,
* type and status of the last \<offset\> constraints is doubled,
* e.g. for offset = 2: \n
* shift( {c1,c2,c3,c4,c5,c6} ) = {c3,c4,c5,c6,c5,c6}
* \return SUCCESSFUL_RETURN \n
RET_INDEX_OUT_OF_BOUNDS \n
RET_INVALID_ARGUMENTS \n
RET_SHIFTING_FAILED */
virtual returnValue shift(
int_t offset /**< Shift offset within the range [0,n/2] and integer divisor of n. */
);
/** Rotates forward type and status of all constraints by a given
* offset. This offset has to lie within the range [0,n].
* Example for offset = 2: \n
* rotate( {c1,c2,c3,c4,c5,c6} ) = {c3,c4,c5,c6,c1,c2}
* \return SUCCESSFUL_RETURN \n
RET_INDEX_OUT_OF_BOUNDS \n
RET_ROTATING_FAILED */
virtual returnValue rotate(int_t offset /**< Rotation offset within the range [0,n]. */
);
/** Prints information on constraints object
* (in particular, lists of inactive and active constraints.
* \return SUCCESSFUL_RETURN \n
RET_INDEXLIST_CORRUPTED */
returnValue print();
/*
* PROTECTED MEMBER FUNCTIONS
*/
protected:
/** Frees all allocated memory.
* \return SUCCESSFUL_RETURN */
returnValue clear();
/** Copies all members from given rhs object.
* \return SUCCESSFUL_RETURN */
returnValue copy(const Constraints & rhs /**< Rhs object. */
);
/** Initially adds all numbers of new (i.e. not yet in the list) bounds to
* to the index set corresponding to the desired status;
* the order depends on the SujectToType of each index.
* \return SUCCESSFUL_RETURN \n
RET_SETUP_CONSTRAINT_FAILED */
returnValue setupAll(SubjectToStatus _status /**< Desired initial status for all bounds. */
);
/*
* PROTECTED MEMBER VARIABLES
*/
protected:
Indexlist active; /**< Index list of active constraints. */
Indexlist inactive; /**< Index list of inactive constraints. */
};
END_NAMESPACE_QPOASES
#include <qpOASES/Constraints.ipp>
#endif /* QPOASES_CONSTRAINTS_HPP */
/*
* end of file
*/
@@ -0,0 +1,122 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/Constraints.ipp
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*
* Declaration of inlined member functions of the Constraints class designed
* to manage working sets of constraints within a QProblem.
*/
BEGIN_NAMESPACE_QPOASES
/*****************************************************************************
* P U B L I C *
*****************************************************************************/
/*
* g e t N C
*/
inline int_t Constraints::getNC( ) const
{
return n;
}
/*
* g e t N E C
*/
inline int_t Constraints::getNEC( ) const
{
return getNumberOfType( ST_EQUALITY );
}
/*
* g e t N I C
*/
inline int_t Constraints::getNIC( ) const
{
return getNumberOfType( ST_BOUNDED );
}
/*
* g e t N U C
*/
inline int_t Constraints::getNUC( ) const
{
return getNumberOfType( ST_UNBOUNDED );
}
/*
* g e t N A C
*/
inline int_t Constraints::getNAC( ) const
{
return active.getLength( );
}
/*
* g e t N I A C
*/
inline int_t Constraints::getNIAC( ) const
{
return inactive.getLength( );
}
/*
* g e t A c t i v e
*/
inline Indexlist* Constraints::getActive( )
{
return &active;
}
/*
* g e t I n a c t i v e
*/
inline Indexlist* Constraints::getInactive( )
{
return &inactive;
}
END_NAMESPACE_QPOASES
/*
* end of file
*/
@@ -0,0 +1,143 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/Flipper.hpp
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*
* Declaration of the Options class designed to manage user-specified
* options for solving a QProblem.
*/
#ifndef QPOASES_FLIPPER_HPP
#define QPOASES_FLIPPER_HPP
#include <qpOASES/Bounds.hpp>
#include <qpOASES/Constraints.hpp>
BEGIN_NAMESPACE_QPOASES
/**
* \brief Auxiliary class for storing a copy of the current matrix factorisations.
*
* This auxiliary class stores a copy of the current matrix factorisations. It
* is used by the classe QProblemB and QProblem in case flipping bounds are enabled.
*
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*/
class Flipper
{
friend class QProblemB;
friend class QProblem;
/*
* PUBLIC MEMBER FUNCTIONS
*/
public:
/** Default constructor. */
Flipper();
/** Constructor which takes the number of bounds and constraints. */
Flipper(uint_t _nV, /**< Number of bounds. */
uint_t _nC = 0 /**< Number of constraints. */
);
/** Copy constructor (deep copy). */
Flipper(const Flipper & rhs /**< Rhs object. */
);
/** Destructor. */
~Flipper();
/** Assignment operator (deep copy). */
Flipper & operator=(const Flipper & rhs /**< Rhs object. */
);
/** Initialises object with given number of bounds and constraints.
* \return SUCCESSFUL_RETURN \n
RET_INVALID_ARGUMENTS */
returnValue init(uint_t _nV = 0, /**< Number of bounds. */
uint_t _nC = 0 /**< Number of constraints. */
);
/** Copies current values to non-null arguments (assumed to be allocated with consistent size).
* \return SUCCESSFUL_RETURN */
returnValue get(Bounds * const _bounds, /**< Pointer to new bounds. */
real_t * const R, /**< New matrix R. */
Constraints * const _constraints = 0, /**< Pointer to new constraints. */
real_t * const _Q = 0, /**< New matrix Q. */
real_t * const _T = 0 /**< New matrix T. */
) const;
/** Assigns new values to non-null arguments.
* \return SUCCESSFUL_RETURN */
returnValue set(const Bounds * const _bounds, /**< Pointer to new bounds. */
const real_t * const _R, /**< New matrix R. */
const Constraints * const _constraints = 0, /**< Pointer to new constraints. */
const real_t * const _Q = 0, /**< New matrix Q. */
const real_t * const _T = 0 /**< New matrix T. */
);
/*
* PROTECTED MEMBER FUNCTIONS
*/
protected:
/** Frees all allocated memory.
* \return SUCCESSFUL_RETURN */
returnValue clear();
/** Copies all members from given rhs object.
* \return SUCCESSFUL_RETURN */
returnValue copy(const Flipper & rhs /**< Rhs object. */
);
/** Returns dimension of matrix T.
* \return Dimension of matrix T. */
uint_t getDimT() const;
/*
* PROTECTED MEMBER VARIABLES
*/
protected:
uint_t nV; /**< Number of variables. */
uint_t nC; /**< Number of constraints. */
Bounds bounds; /**< Data structure for problem's bounds. */
Constraints constraints; /**< Data structure for problem's constraints. */
real_t * R; /**< Cholesky factor of H (i.e. H = R^T*R). */
real_t * Q; /**< Orthonormal quadratic matrix, A = [0 T]*Q'. */
real_t * T; /**< Reverse triangular matrix, A = [0 T]*Q'. */
};
END_NAMESPACE_QPOASES
#endif /* QPOASES_FLIPPER_HPP */
/*
* end of file
*/
@@ -0,0 +1,185 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/Indexlist.hpp
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*
* Declaration of the Indexlist class designed to manage index lists of
* constraints and bounds within a SubjectTo object.
*/
#ifndef QPOASES_INDEXLIST_HPP
#define QPOASES_INDEXLIST_HPP
#include <qpOASES/Utils.hpp>
BEGIN_NAMESPACE_QPOASES
/**
* \brief Stores and manages index lists.
*
* This class manages index lists of active/inactive bounds/constraints.
*
* \author Hans Joachim Ferreau
* \version 3.2
* \date 2007-2017
*/
class Indexlist
{
/*
* FRIENDS
*/
friend class DenseMatrix;
friend class SymDenseMat;
friend class SparseMatrix;
friend class SparseMatrixRow;
friend class SymSparseMat;
/*
* PUBLIC MEMBER FUNCTIONS
*/
public:
/** Default constructor. */
Indexlist();
/** Constructor which takes the desired physical length of the index list. */
Indexlist(int_t n /**< Physical length of index list. */
);
/** Copy constructor (deep copy). */
Indexlist(const Indexlist & rhs /**< Rhs object. */
);
/** Destructor. */
~Indexlist();
/** Assingment operator (deep copy). */
Indexlist & operator=(const Indexlist & rhs /**< Rhs object. */
);
/** Initialises index list of desired physical length.
* \return SUCCESSFUL_RETURN \n
RET_INVALID_ARGUMENTS */
returnValue init(int_t n = 0 /**< Physical length of index list. */
);
/** Creates an array of all numbers within the index set in correct order.
* \return SUCCESSFUL_RETURN \n
RET_INDEXLIST_CORRUPTED */
returnValue getNumberArray(int_t ** const numberarray /**< Output: Array of numbers (NULL on error). */
) const;
/** Creates an array of all numbers within the index set in correct order.
* \return SUCCESSFUL_RETURN \n
RET_INDEXLIST_CORRUPTED */
returnValue getISortArray(int_t ** const iSortArray /**< Output: iSort Array. */
) const;
/** Determines the index within the index list at which a given number is stored.
* \return >= 0: Index of given number. \n
-1: Number not found. */
int_t getIndex(int_t givennumber /**< Number whose index shall be determined. */
) const;
/** Returns the number stored at a given physical index.
* \return >= 0: Number stored at given physical index. \n
-RET_INDEXLIST_OUTOFBOUNDS */
int_t getNumber(int_t physicalindex /**< Physical index of the number to be returned. */
) const;
/** Returns the current length of the index list.
* \return Current length of the index list. */
inline int_t getLength() const;
/** Returns last number within the index list.
* \return Last number within the index list. */
inline int_t getLastNumber() const;
/** Adds number to index list.
* \return SUCCESSFUL_RETURN \n
RET_INDEXLIST_MUST_BE_REORDERD \n
RET_INDEXLIST_EXCEEDS_MAX_LENGTH */
returnValue addNumber(int_t addnumber /**< Number to be added. */
);
/** Removes number from index list.
* \return SUCCESSFUL_RETURN */
returnValue removeNumber(int_t removenumber /**< Number to be removed. */
);
/** Swaps two numbers within index list.
* \return SUCCESSFUL_RETURN */
returnValue swapNumbers(int_t number1, /**< First number for swapping. */
int_t number2 /**< Second number for swapping. */
);
/** Determines if a given number is contained in the index set.
* \return BT_TRUE iff number is contain in the index set */
inline BooleanType isMember(int_t _number /**< Number to be tested for membership. */
) const;
/*
* PROTECTED MEMBER FUNCTIONS
*/
protected:
/** Frees all allocated memory.
* \return SUCCESSFUL_RETURN */
returnValue clear();
/** Copies all members from given rhs object.
* \return SUCCESSFUL_RETURN */
returnValue copy(const Indexlist & rhs /**< Rhs object. */
);
/** Find first index j between -1 and length in sorted list of indices
* iSort such that numbers[iSort[j]] <= i < numbers[iSort[j+1]]. Uses
* bisection.
* \return j. */
int_t findInsert(int_t i) const;
/*
* PROTECTED MEMBER VARIABLES
*/
protected:
int_t * number; /**< Array to store numbers of constraints or bounds. */
int_t * iSort; /**< Index list to sort vector \a number */
int_t length; /**< Length of index list. */
int_t first; /**< Physical index of first element. */
int_t last; /**< Physical index of last element. */
int_t lastusedindex; /**< Physical index of last entry in index list. */
int_t physicallength; /**< Physical length of index list. */
};
END_NAMESPACE_QPOASES
#include <qpOASES/Indexlist.ipp>
#endif /* QPOASES_INDEXLIST_HPP */
/*
* end of file
*/
@@ -0,0 +1,92 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/Indexlist.ipp
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*
* Implementation of inlined member functions of the Indexlist class designed
* to manage index lists of constraints and bounds within a QProblem_SubjectTo.
*/
BEGIN_NAMESPACE_QPOASES
/*****************************************************************************
* P U B L I C *
*****************************************************************************/
/*
* g e t N u m b e r
*/
inline int_t Indexlist::getNumber( int_t physicalindex ) const
{
/* consistency check */
if ( ( physicalindex < 0 ) || ( physicalindex > length ) )
return -RET_INDEXLIST_OUTOFBOUNDS;
return number[physicalindex];
}
/*
* g e t L e n g t h
*/
inline int_t Indexlist::getLength( ) const
{
return length;
}
/*
* g e t L a s t N u m b e r
*/
inline int_t Indexlist::getLastNumber( ) const
{
return number[length-1];
}
/*
* g e t L a s t N u m b e r
*/
inline BooleanType Indexlist::isMember( int_t _number ) const
{
if ( getIndex( _number ) >= 0 )
return BT_TRUE;
else
return BT_FALSE;
}
END_NAMESPACE_QPOASES
/*
* end of file
*/
@@ -0,0 +1,177 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/LapackBlasReplacement.hpp
* \author Andreas Potschka, Hans Joachim Ferreau, Christian Kirches
* \version 3.2
* \date 2009-2017
*
* Declarations for external LAPACK/BLAS functions.
*/
#ifndef QPOASES_LAPACKBLASREPLACEMENT_HPP
#define QPOASES_LAPACKBLASREPLACEMENT_HPP
#include <qpOASES/Types.hpp>
#ifdef __AVOID_LA_NAMING_CONFLICTS__
#define SGEMM qpOASES_sgemm
#define DGEMM qpOASES_gemm
#define SPOTRF qpOASES_spotrf
#define DPOTRF qpOASES_dpotrf
#define STRTRS qpOASES_strtrs
#define DTRTRS qpOASES_dtrtrs
#define STRCON qpOASES_strcon
#define DTRCON qpOASES_dtrcon
#else
#define SGEMM sgemm_
#define DGEMM dgemm_
#define SPOTRF spotrf_
#define DPOTRF dpotrf_
#define STRTRS strtrs_
#define DTRTRS dtrtrs_
#define STRCON strcon_
#define DTRCON dtrcon_
#endif
#ifdef __USE_SINGLE_PRECISION__
/** Macro for calling level 3 BLAS operation in single precision. */
#define GEMM SGEMM
/** Macro for calling level 3 BLAS operation in single precision. */
#define POTRF SPOTRF
/** Macro for calling level 3 BLAS operation in single precision. */
#define TRTRS STRTRS
/** Macro for calling level 3 BLAS operation in single precision. */
#define TRCON strcon_
#else
/** Macro for calling level 3 BLAS operation in double precision. */
#define GEMM DGEMM
/** Macro for calling level 3 BLAS operation in double precision. */
#define POTRF DPOTRF
/** Macro for calling level 3 BLAS operation in double precision. */
#define TRTRS DTRTRS
/** Macro for calling level 3 BLAS operation in double precision. */
#define TRCON DTRCON
#endif /* __USE_SINGLE_PRECISION__ */
extern "C"
{
/** Performs one of the matrix-matrix operation in double precision. */
void DGEMM(const char *,
const char *,
const la_uint_t *,
const la_uint_t *,
const la_uint_t *,
const double *,
const double *,
const la_uint_t *,
const double *,
const la_uint_t *,
const double *,
double *,
const la_uint_t *);
/** Performs one of the matrix-matrix operation in single precision. */
void SGEMM(const char *,
const char *,
const la_uint_t *,
const la_uint_t *,
const la_uint_t *,
const float *,
const float *,
const la_uint_t *,
const float *,
const la_uint_t *,
const float *,
float *,
const la_uint_t *);
/** Calculates the Cholesky factorization of a real symmetric positive definite matrix in double
* precision. */
void DPOTRF(const char *, const la_uint_t *, double *, const la_uint_t *, la_int_t *);
/** Calculates the Cholesky factorization of a real symmetric positive definite matrix in single
* precision. */
void SPOTRF(const char *, const la_uint_t *, float *, const la_uint_t *, la_int_t *);
/** Solves a triangular system (double precision) */
void DTRTRS(const char * UPLO,
const char * TRANS,
const char * DIAG,
const la_uint_t * N,
const la_uint_t * NRHS,
double * A,
const la_uint_t * LDA,
double * B,
const la_uint_t * LDB,
la_int_t * INFO);
/** Solves a triangular system (single precision) */
void STRTRS(const char * UPLO,
const char * TRANS,
const char * DIAG,
const la_uint_t * N,
const la_uint_t * NRHS,
float * A,
const la_uint_t * LDA,
float * B,
const la_uint_t * LDB,
la_int_t * INFO);
/** Estimate the reciprocal of the condition number of a triangular matrix in double precision */
void DTRCON(const char * NORM,
const char * UPLO,
const char * DIAG,
const la_uint_t * N,
double * A,
const la_uint_t * LDA,
double * RCOND,
double * WORK,
const la_uint_t * IWORK,
la_int_t * INFO);
/** Estimate the reciprocal of the condition number of a triangular matrix in single precision */
void STRCON(const char * NORM,
const char * UPLO,
const char * DIAG,
const la_uint_t * N,
float * A,
const la_uint_t * LDA,
float * RCOND,
float * WORK,
const la_uint_t * IWORK,
la_int_t * INFO);
}
#endif /* QPOASES_LAPACKBLASREPLACEMENT_HPP */
/*
* end of file
*/
@@ -0,0 +1,971 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/Matrices.hpp
* \author Andreas Potschka, Hans Joachim Ferreau, Christian Kirches
* \version 3.2
* \date 2009-2017
*
* Various matrix classes: Abstract base matrix class, dense and sparse matrices,
* including symmetry exploiting specializations.
*/
#ifndef QPOASES_MATRICES_HPP
#define QPOASES_MATRICES_HPP
#include <qpOASES/Indexlist.hpp>
#include <qpOASES/Utils.hpp>
BEGIN_NAMESPACE_QPOASES
/**
* \brief Abstract base class for interfacing tailored matrix-vector operations.
*
* Abstract base matrix class. Supplies interface to matrix vector
* products, including products with submatrices given by (ordered) working set
* index lists (see \a SubjectTo).
*
* \author Andreas Potschka, Christian Kirches, Hans Joachim Ferreau
* \version 3.2
* \date 2011-2017
*/
class Matrix
{
public:
/** Default constructor. */
Matrix() { doNotFreeMemory(); };
/** Destructor. */
virtual ~Matrix(){};
/** Frees all internal memory. */
virtual void free() = 0;
/** Returns a deep-copy of the Matrix object.
* \return Deep-copy of Matrix object */
virtual Matrix * duplicate() const = 0;
/** Returns i-th diagonal entry.
* \return i-th diagonal entry */
virtual real_t diag(int_t i /**< Index. */
) const = 0;
/** Checks whether matrix is square and diagonal.
* \return BT_TRUE iff matrix is square and diagonal; \n
* BT_FALSE otherwise. */
virtual BooleanType isDiag() const = 0;
/** Get the N-norm of the matrix
* \return N-norm of the matrix
*/
virtual real_t getNorm(int_t type = 2 /**< Norm type, 1: one-norm, 2: Euclidean norm. */
) const = 0;
/** Get the N-norm of a row
* \return N-norm of row \a rNum
*/
virtual real_t getRowNorm(int_t rNum, /**< Row number. */
int_t type = 2 /**< Norm type, 1: one-norm, 2: Euclidean norm. */
) const = 0;
/** Get the N-norm of all rows
* \return SUCCESSFUL_RETURN */
virtual returnValue getRowNorm(real_t * norm, /**< Norm of each row. */
int_t type = 2 /**< Norm type, 1: one-norm, 2: Euclidean norm. */
) const = 0;
/** Retrieve indexed entries of matrix row multiplied by alpha.
* \return SUCCESSFUL_RETURN */
virtual returnValue getRow(int_t rNum, /**< Row number. */
const Indexlist * const icols, /**< Index list specifying columns. */
real_t alpha, /**< Scalar factor. */
real_t * row /**< Output row vector. */
) const = 0;
/** Retrieve indexed entries of matrix column multiplied by alpha.
* \return SUCCESSFUL_RETURN */
virtual returnValue getCol(int_t cNum, /**< Column number. */
const Indexlist * const irows, /**< Index list specifying rows. */
real_t alpha, /**< Scalar factor. */
real_t * col /**< Output column vector. */
) const = 0;
/** Retrieve entries of submatrix in Harwell-Boeing sparse format.
* If irn, jcn, and avals are null, this only counts the number of nonzeros.
* Otherwise, numNonzeros containts the size of irn, jcn, and avals on entry,
* and the written number of entries on return.
* \return SUCCESSFUL_RETURN */
virtual returnValue getSparseSubmatrix(const Indexlist * const irows, /**< Index list specifying rows. */
const Indexlist * const icols, /**< Index list specifying columns. */
int_t rowoffset, /**< Offset for row entries. */
int_t coloffset, /**< Offset for row entries. */
int_t & numNonzeros, /**< Number of nonzeros in submatrix. */
int_t * irn, /**< Row position of entries (as position in irows) plus rowoffset. */
int_t * jcn, /**< Column position of entries (as position in irows) plus coloffset. */
real_t * avals, /**< Numerical values of the entries. */
BooleanType only_lower_triangular =
BT_FALSE /**< if true, only the lower triangular portion is returned. This can only be true for
symmetric matrices and if irows==jcols. */
) const;
/** Retrieve entries of submatrix in Harwell-Boeing sparse format.
* If irn, jcn, and avals are null, this only counts the number of nonzeros.
* Otherwise, numNonzeros containts the size of irn, jcn, and avals on entry,
* and the written number of entries on return. This version retrieves one
* column.
* \return SUCCESSFUL_RETURN */
virtual returnValue getSparseSubmatrix(const Indexlist * const irows, /**< Index list specifying rows. */
int_t idx_icol, /**< Index list specifying columns. */
int_t rowoffset, /**< Offset for row entries. */
int_t coloffset, /**< Offset for row entries. */
int_t & numNonzeros, /**< Number of nonzeros in submatrix. */
int_t * irn, /**< Row position of entries (as position in irows) plus rowoffset. */
int_t * jcn, /**< Column position of entries (as position in irows) plus coloffset. */
real_t * avals, /**< Numerical values of the entries. */
BooleanType only_lower_triangular =
BT_FALSE /**< if true, only the lower triangular portion is returned. This can only be true for
symmetric matrices and if irows==jcols. */
) const;
/** Retrieve entries of submatrix in Harwell-Boeing sparse format.
* If irn, jcn, and avals are null, this only counts the number of nonzeros.
* Otherwise, numNonzeros containts the size of irn, jcn, and avals on entry,
* and the written number of entries on return. This version retrieves one row.
* \return SUCCESSFUL_RETURN */
virtual returnValue getSparseSubmatrix(int_t idx_row, /**< Row number. */
const Indexlist * const icols, /**< Index list specifying columns. */
int_t rowoffset, /**< Offset for row entries. */
int_t coloffset, /**< Offset for row entries. */
int_t & numNonzeros, /**< Number of nonzeros in submatrix. */
int_t * irn, /**< Row position of entries (as position in irows) plus rowoffset. */
int_t * jcn, /**< Column position of entries (as position in irows) plus coloffset. */
real_t * avals, /**< Numerical values of the entries. */
BooleanType only_lower_triangular =
BT_FALSE /**< if true, only the lower triangular portion is returned. This can only be true for
symmetric matrices and if irows==jcols. */
) const;
/** Retrieve entries of submatrix in Harwell-Boeing sparse format.
* If irn, jcn, and avals are null, this only counts the number of nonzeros.
* Otherwise, numNonzeros containts the size of irn, jcn, and avals on entry,
* and the written number of entries on return.
* \return SUCCESSFUL_RETURN */
virtual returnValue getSparseSubmatrix(int_t irowsLength, /**< Number of rows. */
const int_t * const irowsNumber, /**< Array with row numbers. */
int_t icolsLength, /**< Number of columns. */
const int_t * const icolsNumber, /**< Array with column numbers. */
int_t rowoffset, /**< Offset for row entries. */
int_t coloffset, /**< Offset for row entries. */
int_t & numNonzeros, /**< Number of nonzeros in submatrix. */
int_t * irn, /**< Row position of entries (as position in irows) plus rowoffset. */
int_t * jcn, /**< Column position of entries (as position in irows) plus coloffset. */
real_t * avals, /**< Numerical values of the entries. */
BooleanType only_lower_triangular =
BT_FALSE /**< if true, only the lower triangular portion is returned. This can only be true for
symmetric matrices and if irows==jcols. */
) const = 0;
/** Evaluate Y=alpha*A*X + beta*Y.
* \return SUCCESSFUL_RETURN */
virtual returnValue times(int_t xN, /**< Number of vectors to multiply. */
real_t alpha, /**< Scalar factor for matrix vector product. */
const real_t * x, /**< Input vector to be multiplied. */
int_t xLD, /**< Leading dimension of input x. */
real_t beta, /**< Scalar factor for y. */
real_t * y, /**< Output vector of results. */
int_t yLD /**< Leading dimension of output y. */
) const = 0;
/** Evaluate Y=alpha*A'*X + beta*Y.
* \return SUCCESSFUL_RETURN */
virtual returnValue transTimes(int_t xN, /**< Number of vectors to multiply. */
real_t alpha, /**< Scalar factor for matrix vector product. */
const real_t * x, /**< Input vector to be multiplied. */
int_t xLD, /**< Leading dimension of input x. */
real_t beta, /**< Scalar factor for y. */
real_t * y, /**< Output vector of results. */
int_t yLD /**< Leading dimension of output y. */
) const = 0;
/** Evaluate matrix vector product with submatrix given by Indexlist.
* \return SUCCESSFUL_RETURN */
virtual returnValue times(const Indexlist * const irows, /**< Index list specifying rows. */
const Indexlist * const icols, /**< Index list specifying columns. */
int_t xN, /**< Number of vectors to multiply. */
real_t alpha, /**< Scalar factor for matrix vector product. */
const real_t * x, /**< Input vector to be multiplied. */
int_t xLD, /**< Leading dimension of input x. */
real_t beta, /**< Scalar factor for y. */
real_t * y, /**< Output vector of results. */
int_t yLD, /**< Leading dimension of output y. */
BooleanType yCompr = BT_TRUE /**< Compressed storage for y. */
) const = 0;
/** Evaluate matrix transpose vector product.
* \return SUCCESSFUL_RETURN */
virtual returnValue transTimes(const Indexlist * const irows, /**< Index list specifying rows. */
const Indexlist * const icols, /**< Index list specifying columns. */
int_t xN, /**< Number of vectors to multiply. */
real_t alpha, /**< Scalar factor for matrix vector product. */
const real_t * x, /**< Input vector to be multiplied. */
int_t xLD, /**< Leading dimension of input x. */
real_t beta, /**< Scalar factor for y. */
real_t * y, /**< Output vector of results. */
int_t yLD /**< Leading dimension of output y. */
) const = 0;
/** Adds given offset to diagonal of matrix.
* \return SUCCESSFUL_RETURN \n
RET_NO_DIAGONAL_AVAILABLE */
virtual returnValue addToDiag(real_t alpha /**< Diagonal offset. */
) = 0;
/** Allocates and creates dense matrix array in row major format.
*
* Note: Calling function has to free allocated memory!
*
* \return Pointer to matrix array.
*/
virtual real_t * full() const = 0;
/** Prints matrix to screen.
* \return SUCCESSFUL_RETURN */
virtual returnValue print(const char * name = 0 /** Name of matrix. */
) const = 0;
/** Write matrix to file.
* \return SUCCESSFUL_RETURN */
virtual returnValue writeToFile(FILE * output_file, const char * prefix) const = 0;
/** Returns whether internal memory needs to be de-allocated.
* \return BT_TRUE iff internal memory needs to be de-allocated, \n
BT_FALSE otherwise */
BooleanType needToFreeMemory() const { return freeMemory; };
/** Enables de-allocation of internal memory. */
void doFreeMemory() { freeMemory = BT_TRUE; };
/** Disables de-allocation of internal memory. */
void doNotFreeMemory() { freeMemory = BT_FALSE; };
protected:
BooleanType freeMemory; /**< Indicating whether internal memory needs to be de-allocated. */
};
/**
* \brief Abstract base class for interfacing matrix-vector operations tailored to symmetric matrices.
*
* Abstract base class for symmetric matrices. Extends Matrix interface with
* bilinear form evaluation.
*
* \author Andreas Potschka, Christian Kirches, Hans Joachim Ferreau
* \version 3.2
* \date 2011-2017
*/
class SymmetricMatrix : public virtual Matrix
{
public:
/** Default constructor. */
SymmetricMatrix(){};
/** Destructor. */
virtual ~SymmetricMatrix(){};
/** Returns a deep-copy of the SymmetricMatrix object.
* \return Deep-copy of SymmetricMatrix object */
virtual SymmetricMatrix * duplicateSym() const = 0;
/** Compute bilinear form y = x'*H*x using submatrix given by index list.
* \return SUCCESSFUL_RETURN */
virtual returnValue bilinear(const Indexlist * const icols, /**< Index list specifying columns of x. */
int_t xN, /**< Number of vectors to multiply. */
const real_t * x, /**< Input vector to be multiplied (uncompressed). */
int_t xLD, /**< Leading dimension of input x. */
real_t * y, /**< Output vector of results (compressed). */
int_t yLD /**< Leading dimension of output y. */
) const = 0;
};
/**
* \brief Interfaces matrix-vector operations tailored to general dense matrices.
*
* Dense matrix class (row major format).
*
* \author Andreas Potschka, Christian Kirches, Hans Joachim Ferreau
* \version 3.2
* \date 2011-2017
*/
class DenseMatrix : public virtual Matrix
{
public:
/** Default constructor. */
DenseMatrix() : nRows(0), nCols(0), leaDim(0), val(0){};
/** Constructor from vector of values.
* Caution: Data pointer must be valid throughout lifetime
*/
DenseMatrix(int_t m, /**< Number of rows. */
int_t n, /**< Number of columns. */
int_t lD, /**< Leading dimension. */
real_t * v /**< Values. */
)
: nRows(m), nCols(n), leaDim(lD), val(v)
{
}
/** Destructor. */
virtual ~DenseMatrix();
/** Frees all internal memory. */
virtual void free();
/** Returns a deep-copy of the Matrix object.
* \return Deep-copy of Matrix object */
virtual Matrix * duplicate() const;
/** Returns i-th diagonal entry.
* \return i-th diagonal entry */
virtual real_t diag(int_t i /**< Index. */
) const;
/** Checks whether matrix is square and diagonal.
* \return BT_TRUE iff matrix is square and diagonal; \n
* BT_FALSE otherwise. */
virtual BooleanType isDiag() const;
/** Get the N-norm of the matrix
* \return N-norm of the matrix
*/
virtual real_t getNorm(int_t type = 2 /**< Norm type, 1: one-norm, 2: Euclidean norm. */
) const;
/** Get the N-norm of a row
* \return N-norm of row \a rNum
*/
virtual real_t getRowNorm(int_t rNum, /**< Row number. */
int_t type = 2 /**< Norm type, 1: one-norm, 2: Euclidean norm. */
) const;
/** Get the N-norm of all rows
* \return SUCCESSFUL_RETURN */
virtual returnValue getRowNorm(real_t * norm, /**< Norm of each row. */
int_t type = 2 /**< Norm type, 1: one-norm, 2: Euclidean norm. */
) const;
/** Retrieve indexed entries of matrix row multiplied by alpha.
* \return SUCCESSFUL_RETURN */
virtual returnValue getRow(int_t rNum, /**< Row number. */
const Indexlist * const icols, /**< Index list specifying columns. */
real_t alpha, /**< Scalar factor. */
real_t * row /**< Output row vector. */
) const;
/** Retrieve indexed entries of matrix column multiplied by alpha.
* \return SUCCESSFUL_RETURN */
virtual returnValue getCol(int_t cNum, /**< Column number. */
const Indexlist * const irows, /**< Index list specifying rows. */
real_t alpha, /**< Scalar factor. */
real_t * col /**< Output column vector. */
) const;
/** Retrieve entries of submatrix in Harwell-Boeing sparse format.
* If irn, jcn, and avals are null, this only counts the number of nonzeros.
* Otherwise, numNonzeros containts the size of irn, jcn, and avals on entry,
* and the written number of entries on return.
* \return SUCCESSFUL_RETURN */
virtual returnValue getSparseSubmatrix(int_t irowsLength, /**< Number of rows. */
const int_t * const irowsNumber, /**< Array with row numbers. */
int_t icolsLength, /**< Number of columns. */
const int_t * const icolsNumber, /**< Array with column numbers. */
int_t rowoffset, /**< Offset for row entries. */
int_t coloffset, /**< Offset for row entries. */
int_t & numNonzeros, /**< Number of nonzeros in submatrix. */
int_t * irn, /**< Row position of entries (as position in irows) plus rowoffset. */
int_t * jcn, /**< Column position of entries (as position in irows) plus coloffset. */
real_t * avals, /**< Numerical values of the entries. */
BooleanType only_lower_triangular =
BT_FALSE /**< if true, only the lower triangular portion is returned. This can only be true for
symmetric matrices and if irows==jcols. */
) const;
/** Evaluate Y=alpha*A*X + beta*Y.
* \return SUCCESSFUL_RETURN. */
virtual returnValue times(int_t xN, /**< Number of vectors to multiply. */
real_t alpha, /**< Scalar factor for matrix vector product. */
const real_t * x, /**< Input vector to be multiplied. */
int_t xLD, /**< Leading dimension of input x. */
real_t beta, /**< Scalar factor for y. */
real_t * y, /**< Output vector of results. */
int_t yLD /**< Leading dimension of output y. */
) const;
/** Evaluate Y=alpha*A'*X + beta*Y.
* \return SUCCESSFUL_RETURN. */
virtual returnValue transTimes(int_t xN, /**< Number of vectors to multiply. */
real_t alpha, /**< Scalar factor for matrix vector product. */
const real_t * x, /**< Input vector to be multiplied. */
int_t xLD, /**< Leading dimension of input x. */
real_t beta, /**< Scalar factor for y. */
real_t * y, /**< Output vector of results. */
int_t yLD /**< Leading dimension of output y. */
) const;
/** Evaluate matrix vector product with submatrix given by Indexlist.
* \return SUCCESSFUL_RETURN */
virtual returnValue times(const Indexlist * const irows, /**< Index list specifying rows. */
const Indexlist * const icols, /**< Index list specifying columns. */
int_t xN, /**< Number of vectors to multiply. */
real_t alpha, /**< Scalar factor for matrix vector product. */
const real_t * x, /**< Input vector to be multiplied. */
int_t xLD, /**< Leading dimension of input x. */
real_t beta, /**< Scalar factor for y. */
real_t * y, /**< Output vector of results. */
int_t yLD, /**< Leading dimension of output y. */
BooleanType yCompr = BT_TRUE /**< Compressed storage for y. */
) const;
/** Evaluate matrix transpose vector product.
* \return SUCCESSFUL_RETURN */
virtual returnValue transTimes(const Indexlist * const irows, /**< Index list specifying rows. */
const Indexlist * const icols, /**< Index list specifying columns. */
int_t xN, /**< Number of vectors to multiply. */
real_t alpha, /**< Scalar factor for matrix vector product. */
const real_t * x, /**< Input vector to be multiplied. */
int_t xLD, /**< Leading dimension of input x. */
real_t beta, /**< Scalar factor for y. */
real_t * y, /**< Output vector of results. */
int_t yLD /**< Leading dimension of output y. */
) const;
/** Adds given offset to diagonal of matrix.
* \return SUCCESSFUL_RETURN \n
RET_NO_DIAGONAL_AVAILABLE */
virtual returnValue addToDiag(real_t alpha /**< Diagonal offset. */
);
/** Allocates and creates dense matrix array in row major format.
*
* Note: Calling function has to free allocated memory!
*
* \return Pointer to matrix array.
*/
virtual real_t * full() const;
/** Prints matrix to screen.
* \return SUCCESSFUL_RETURN */
virtual returnValue print(const char * name = 0 /** Name of matrix. */
) const;
/** Write matrix to file.
* \return SUCCESSFUL_RETURN */
virtual returnValue writeToFile(FILE * output_file, const char * prefix) const;
protected:
int_t nRows; /**< Number of rows. */
int_t nCols; /**< Number of columns. */
int_t leaDim; /**< Leading dimension. */
real_t * val; /**< Vector of entries. */
};
/**
* \brief Interfaces matrix-vector operations tailored to symmetric dense matrices.
*
* Symmetric dense matrix class.
*
* \author Andreas Potschka, Christian Kirches, Hans Joachim Ferreau
* \version 3.2
* \date 2011-2017
*/
class SymDenseMat
: public DenseMatrix
, public SymmetricMatrix
{
public:
/** Default constructor. */
SymDenseMat() : DenseMatrix(){};
/** Constructor from vector of values. */
SymDenseMat(int_t m, /**< Number of rows. */
int_t n, /**< Number of columns. */
int_t lD, /**< Leading dimension. */
real_t * v /**< Values. */
)
: DenseMatrix(m, n, lD, v){};
/** Destructor. */
virtual ~SymDenseMat(){};
/** Returns a deep-copy of the Matrix object.
* \return Deep-copy of Matrix object */
virtual Matrix * duplicate() const;
/** Returns a deep-copy of the SymmetricMatrix object.
* \return Deep-copy of SymmetricMatrix object */
virtual SymmetricMatrix * duplicateSym() const;
/** Compute bilinear form y = x'*H*x using submatrix given by index list.
* \return SUCCESSFUL_RETURN */
virtual returnValue bilinear(const Indexlist * const icols, /**< Index list specifying columns of x. */
int_t xN, /**< Number of vectors to multiply. */
const real_t * x, /**< Input vector to be multiplied (uncompressed). */
int_t xLD, /**< Leading dimension of input x. */
real_t * y, /**< Output vector of results (compressed). */
int_t yLD /**< Leading dimension of output y. */
) const;
};
/**
* \brief Interfaces matrix-vector operations tailored to general sparse matrices.
*
* Sparse matrix class (col compressed format).
*
* \author Andreas Potschka, Christian Kirches, Hans Joachim Ferreau
* \version 3.2
* \date 2011-2017
*/
class SparseMatrix : public virtual Matrix
{
public:
/** Default constructor. */
SparseMatrix();
/** Constructor with arguments. */
SparseMatrix(int_t nr, /**< Number of rows. */
int_t nc, /**< Number of columns. */
sparse_int_t * r, /**< Row indices (length). */
sparse_int_t * c, /**< Indices to first entry of columns (nCols+1). */
real_t * v /**< Vector of entries (length). */
);
/** Constructor from dense matrix. */
SparseMatrix(int_t nr, /**< Number of rows. */
int_t nc, /**< Number of columns. */
int_t ld, /**< Leading dimension. */
const real_t * const v /**< Row major stored matrix elements. */
);
/** Destructor. */
virtual ~SparseMatrix();
/** Frees all internal memory. */
virtual void free();
/** Returns a deep-copy of the Matrix object.
* \return Deep-copy of Matrix object */
virtual Matrix * duplicate() const;
/** Sets value array.
*
* Thanks to Frank Chuang.
*/
virtual void setVal(const real_t * newVal /**< ... */
);
/** Returns i-th diagonal entry.
* \return i-th diagonal entry (or INFTY if diagonal does not exist)*/
virtual real_t diag(int_t i /**< Index. */
) const;
/** Checks whether matrix is square and diagonal.
* \return BT_TRUE iff matrix is square and diagonal; \n
* BT_FALSE otherwise. */
virtual BooleanType isDiag() const;
/** Get the N-norm of the matrix
* \return N-norm of the matrix
*/
virtual real_t getNorm(int_t type = 2 /**< Norm type, 1: one-norm, 2: Euclidean norm. */
) const;
/** Get the N-norm of a row
* \return N-norm of row \a rNum
*/
virtual real_t getRowNorm(int_t rNum, /**< Row number. */
int_t type = 2 /**< Norm type, 1: one-norm, 2: Euclidean norm. */
) const;
/** Get the N-norm of all rows
* \return SUCCESSFUL_RETURN */
virtual returnValue getRowNorm(real_t * norm, /**< Norm of each row. */
int_t type = 2 /**< Norm type, 1: one-norm, 2: Euclidean norm. */
) const;
/** Retrieve indexed entries of matrix row multiplied by alpha. */
virtual returnValue getRow(int_t rNum, /**< Row number. */
const Indexlist * const icols, /**< Index list specifying columns. */
real_t alpha, /**< Scalar factor. */
real_t * row /**< Output row vector. */
) const;
/** Retrieve indexed entries of matrix column multiplied by alpha. */
virtual returnValue getCol(int_t cNum, /**< Column number. */
const Indexlist * const irows, /**< Index list specifying rows. */
real_t alpha, /**< Scalar factor. */
real_t * col /**< Output column vector. */
) const;
/** Retrieve entries of submatrix in Harwell-Boeing sparse format.
* If irn, jcn, and avals are null, this only counts the number of nonzeros.
* Otherwise, numNonzeros containts the size of irn, jcn, and avals on entry,
* and the written number of entries on return.
* \return SUCCESSFUL_RETURN */
virtual returnValue getSparseSubmatrix(int_t irowsLength, /**< Number of rows. */
const int_t * const irowsNumber, /**< Array with row numbers. */
int_t icolsLength, /**< Number of columns. */
const int_t * const icolsNumber, /**< Array with column numbers. */
int_t rowoffset, /**< Offset for row entries. */
int_t coloffset, /**< Offset for row entries. */
int_t & numNonzeros, /**< Number of nonzeros in submatrix. */
int_t * irn, /**< Row position of entries (as position in irows) plus rowoffset. */
int_t * jcn, /**< Column position of entries (as position in irows) plus coloffset. */
real_t * avals, /**< Numerical values of the entries. */
BooleanType only_lower_triangular =
BT_FALSE /**< if true, only the lower triangular portion is returned. This can only be true for
symmetric matrices and if irows==jcols. */
) const;
/** Evaluate Y=alpha*A*X + beta*Y. */
virtual returnValue times(int_t xN, /**< Number of vectors to multiply. */
real_t alpha, /**< Scalar factor for matrix vector product. */
const real_t * x, /**< Input vector to be multiplied. */
int_t xLD, /**< Leading dimension of input x. */
real_t beta, /**< Scalar factor for y. */
real_t * y, /**< Output vector of results. */
int_t yLD /**< Leading dimension of output y. */
) const;
/** Evaluate Y=alpha*A'*X + beta*Y. */
virtual returnValue transTimes(int_t xN, /**< Number of vectors to multiply. */
real_t alpha, /**< Scalar factor for matrix vector product. */
const real_t * x, /**< Input vector to be multiplied. */
int_t xLD, /**< Leading dimension of input x. */
real_t beta, /**< Scalar factor for y. */
real_t * y, /**< Output vector of results. */
int_t yLD /**< Leading dimension of output y. */
) const;
/** Evaluate matrix vector product with submatrix given by Indexlist. */
virtual returnValue times(const Indexlist * const irows, /**< Index list specifying rows. */
const Indexlist * const icols, /**< Index list specifying columns. */
int_t xN, /**< Number of vectors to multiply. */
real_t alpha, /**< Scalar factor for matrix vector product. */
const real_t * x, /**< Input vector to be multiplied. */
int_t xLD, /**< Leading dimension of input x. */
real_t beta, /**< Scalar factor for y. */
real_t * y, /**< Output vector of results. */
int_t yLD, /**< Leading dimension of output y. */
BooleanType yCompr = BT_TRUE /**< Compressed storage for y. */
) const;
/** Evaluate matrix transpose vector product. */
virtual returnValue transTimes(const Indexlist * const irows, /**< Index list specifying rows. */
const Indexlist * const icols, /**< Index list specifying columns. */
int_t xN, /**< Number of vectors to multiply. */
real_t alpha, /**< Scalar factor for matrix vector product. */
const real_t * x, /**< Input vector to be multiplied. */
int_t xLD, /**< Leading dimension of input x. */
real_t beta, /**< Scalar factor for y. */
real_t * y, /**< Output vector of results. */
int_t yLD /**< Leading dimension of output y. */
) const;
/** Adds given offset to diagonal of matrix.
* \return SUCCESSFUL_RETURN \n
RET_NO_DIAGONAL_AVAILABLE */
virtual returnValue addToDiag(real_t alpha /**< Diagonal offset. */
);
/** Create jd field from ir and jc.
* \return Pointer to jd. */
sparse_int_t * createDiagInfo();
/** Allocates and creates dense matrix array in row major format.
*
* Note: Calling function has to free allocated memory!
*
* \return Pointer to matrix array.
*/
virtual real_t * full() const;
/** Prints matrix to screen.
* \return SUCCESSFUL_RETURN */
virtual returnValue print(const char * name = 0 /** Name of matrix. */
) const;
/** Write matrix to file.
* \return SUCCESSFUL_RETURN */
virtual returnValue writeToFile(FILE * output_file, const char * prefix) const;
protected:
int_t nRows; /**< Number of rows. */
int_t nCols; /**< Number of columns. */
sparse_int_t * ir; /**< Row indices (length). */
sparse_int_t * jc; /**< Indices to first entry of columns (nCols+1). */
sparse_int_t * jd; /**< Indices to first entry of lower triangle (including diagonal) (nCols). */
real_t * val; /**< Vector of entries (length). */
};
/**
* \brief Interfaces matrix-vector operations tailored to general sparse matrices.
*
* Sparse matrix class (row compressed format).
*
* \author Andreas Potschka, Christian Kirches, Hans Joachim Ferreau
* \version 3.2
* \date 2011-2017
*/
class SparseMatrixRow : public virtual Matrix
{
public:
/** Default constructor. */
SparseMatrixRow();
/** Constructor with arguments. */
SparseMatrixRow(int_t nr, /**< Number of rows. */
int_t nc, /**< Number of columns. */
sparse_int_t * r, /**< Indices to first entry of rows (nRows+1). */
sparse_int_t * c, /**< Column indices (length). */
real_t * v /**< Vector of entries (length). */
);
/** Constructor from dense matrix. */
SparseMatrixRow(int_t nr, /**< Number of rows. */
int_t nc, /**< Number of columns. */
int_t ld, /**< Leading dimension. */
const real_t * const v /**< Row major stored matrix elements. */
);
/** Destructor. */
virtual ~SparseMatrixRow();
/** Frees all internal memory. */
virtual void free();
/** Returns a deep-copy of the Matrix object.
* \return Deep-copy of Matrix object */
virtual Matrix * duplicate() const;
/** Returns i-th diagonal entry.
* \return i-th diagonal entry (or INFTY if diagonal does not exist)*/
virtual real_t diag(int_t i /**< Index. */
) const;
/** Checks whether matrix is square and diagonal.
* \return BT_TRUE iff matrix is square and diagonal; \n
* BT_FALSE otherwise. */
virtual BooleanType isDiag() const;
/** Get the N-norm of the matrix
* \return N-norm of the matrix
*/
virtual real_t getNorm(int_t type = 2 /**< Norm type, 1: one-norm, 2: Euclidean norm. */
) const;
/** Get the N-norm of a row
* \return N-norm of row \a rNum
*/
virtual real_t getRowNorm(int_t rNum, /**< Row number. */
int_t type = 2 /**< Norm type, 1: one-norm, 2: Euclidean norm. */
) const;
/** Get the N-norm of all rows
* \return SUCCESSFUL_RETURN */
virtual returnValue getRowNorm(real_t * norm, /**< Norm of each row. */
int_t type = 2 /**< Norm type, 1: one-norm, 2: Euclidean norm. */
) const;
/** Retrieve indexed entries of matrix row multiplied by alpha. */
virtual returnValue getRow(int_t rNum, /**< Row number. */
const Indexlist * const icols, /**< Index list specifying columns. */
real_t alpha, /**< Scalar factor. */
real_t * row /**< Output row vector. */
) const;
/** Retrieve indexed entries of matrix column multiplied by alpha. */
virtual returnValue getCol(int_t cNum, /**< Column number. */
const Indexlist * const irows, /**< Index list specifying rows. */
real_t alpha, /**< Scalar factor. */
real_t * col /**< Output column vector. */
) const;
/** Retrieve entries of submatrix in Harwell-Boeing sparse format.
* If irn, jcn, and avals are null, this only counts the number of nonzeros.
* Otherwise, numNonzeros containts the size of irn, jcn, and avals on entry,
* and the written number of entries on return.
* \return SUCCESSFUL_RETURN */
virtual returnValue getSparseSubmatrix(int_t irowsLength, /**< Number of rows. */
const int_t * const irowsNumber, /**< Array with row numbers. */
int_t icolsLength, /**< Number of columns. */
const int_t * const icolsNumber, /**< Array with column numbers. */
int_t rowoffset, /**< Offset for row entries. */
int_t coloffset, /**< Offset for row entries. */
int_t & numNonzeros, /**< Number of nonzeros in submatrix. */
int_t * irn, /**< Row position of entries (as position in irows) plus rowoffset. */
int_t * jcn, /**< Column position of entries (as position in irows) plus coloffset. */
real_t * avals, /**< Numerical values of the entries. */
BooleanType only_lower_triangular =
BT_FALSE /**< if true, only the lower triangular portion is returned. This can only be true for
symmetric matrices and if irows==jcols. */
) const;
/** Evaluate Y=alpha*A*X + beta*Y. */
virtual returnValue times(int_t xN, /**< Number of vectors to multiply. */
real_t alpha, /**< Scalar factor for matrix vector product. */
const real_t * x, /**< Input vector to be multiplied. */
int_t xLD, /**< Leading dimension of input x. */
real_t beta, /**< Scalar factor for y. */
real_t * y, /**< Output vector of results. */
int_t yLD /**< Leading dimension of output y. */
) const;
/** Evaluate Y=alpha*A'*X + beta*Y. */
virtual returnValue transTimes(int_t xN, /**< Number of vectors to multiply. */
real_t alpha, /**< Scalar factor for matrix vector product. */
const real_t * x, /**< Input vector to be multiplied. */
int_t xLD, /**< Leading dimension of input x. */
real_t beta, /**< Scalar factor for y. */
real_t * y, /**< Output vector of results. */
int_t yLD /**< Leading dimension of output y. */
) const;
/** Evaluate matrix vector product with submatrix given by Indexlist. */
virtual returnValue times(const Indexlist * const irows, /**< Index list specifying rows. */
const Indexlist * const icols, /**< Index list specifying columns. */
int_t xN, /**< Number of vectors to multiply. */
real_t alpha, /**< Scalar factor for matrix vector product. */
const real_t * x, /**< Input vector to be multiplied. */
int_t xLD, /**< Leading dimension of input x. */
real_t beta, /**< Scalar factor for y. */
real_t * y, /**< Output vector of results. */
int_t yLD, /**< Leading dimension of output y. */
BooleanType yCompr = BT_TRUE /**< Compressed storage for y. */
) const;
/** Evaluate matrix transpose vector product. */
virtual returnValue transTimes(const Indexlist * const irows, /**< Index list specifying rows. */
const Indexlist * const icols, /**< Index list specifying columns. */
int_t xN, /**< Number of vectors to multiply. */
real_t alpha, /**< Scalar factor for matrix vector product. */
const real_t * x, /**< Input vector to be multiplied. */
int_t xLD, /**< Leading dimension of input x. */
real_t beta, /**< Scalar factor for y. */
real_t * y, /**< Output vector of results. */
int_t yLD /**< Leading dimension of output y. */
) const;
/** Adds given offset to diagonal of matrix.
* \return SUCCESSFUL_RETURN \n
RET_NO_DIAGONAL_AVAILABLE */
virtual returnValue addToDiag(real_t alpha /**< Diagonal offset. */
);
/** Create jd field from ir and jc.
* \return Pointer to jd. */
sparse_int_t * createDiagInfo();
/** Allocates and creates dense matrix array in row major format.
*
* Note: Calling function has to free allocated memory!
*
* \return Pointer to matrix array.
*/
virtual real_t * full() const;
/** Prints matrix to screen.
* \return SUCCESSFUL_RETURN */
virtual returnValue print(const char * name = 0 /** Name of matrix. */
) const;
/** Write matrix to file.
* \return SUCCESSFUL_RETURN */
virtual returnValue writeToFile(FILE * output_file, const char * prefix) const;
protected:
int_t nRows; /**< Number of rows. */
int_t nCols; /**< Number of columns. */
sparse_int_t * jr; /**< Indices to first entry of row (nRows+1). */
sparse_int_t * ic; /**< Column indices (length). */
sparse_int_t * jd; /**< Indices to first entry of upper triangle (including diagonal) (nRows). */
real_t * val; /**< Vector of entries (length). */
};
/**
* \brief Interfaces matrix-vector operations tailored to symmetric sparse matrices.
*
* Symmetric sparse matrix class (column compressed format).
*
* \author Andreas Potschka, Christian Kirches, Hans Joachim Ferreau
* \version 3.2
* \date 2011-2017
*/
class SymSparseMat
: public SymmetricMatrix
, public SparseMatrix
{
public:
/** Default constructor. */
SymSparseMat() : SparseMatrix(){};
/** Constructor with arguments. */
SymSparseMat(int_t nr, /**< Number of rows. */
int_t nc, /**< Number of columns. */
sparse_int_t * r, /**< Row indices (length). */
sparse_int_t * c, /**< Indices to first entry of columns (nCols+1). */
real_t * v /**< Vector of entries (length). */
)
: SparseMatrix(nr, nc, r, c, v){};
/** Constructor from dense matrix. */
SymSparseMat(int_t nr, /**< Number of rows. */
int_t nc, /**< Number of columns. */
int_t ld, /**< Leading dimension. */
const real_t * const v /**< Row major stored matrix elements. */
)
: SparseMatrix(nr, nc, ld, v){};
/** Destructor. */
virtual ~SymSparseMat(){};
/** Returns a deep-copy of the Matrix object.
* \return Deep-copy of Matrix object */
virtual Matrix * duplicate() const;
/** Returns a deep-copy of the SymmetricMatrix object.
* \return Deep-copy of SymmetricMatrix object */
virtual SymmetricMatrix * duplicateSym() const;
/** Compute bilinear form y = x'*H*x using submatrix given by index list.
* \return SUCCESSFUL_RETURN */
virtual returnValue bilinear(const Indexlist * const icols, /**< Index list specifying columns of x. */
int_t xN, /**< Number of vectors to multiply. */
const real_t * x, /**< Input vector to be multiplied (uncompressed). */
int_t xLD, /**< Leading dimension of input x. */
real_t * y, /**< Output vector of results (compressed). */
int_t yLD /**< Leading dimension of output y. */
) const;
};
END_NAMESPACE_QPOASES
#endif /* QPOASES_MATRICES_HPP */
@@ -0,0 +1,475 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/MessageHandling.hpp
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches (thanks to Leonard Wirsching)
* \version 3.2
* \date 2007-2017
*
* Declaration of the MessageHandling class including global return values.
*/
#ifndef QPOASES_MESSAGEHANDLING_HPP
#define QPOASES_MESSAGEHANDLING_HPP
#include <stdio.h>
#include <string.h>
#ifdef __DEBUG__
#include <assert.h>
#endif
#include <qpOASES/Constants.hpp>
BEGIN_NAMESPACE_QPOASES
/** Default file to display messages. */
extern FILE * stdFile;
/**
* \brief Defines all symbols for global return values.
*
* The enumeration returnValueType defines all symbols for global return values.
* Important: All return values are assumed to be nonnegative!
*
* \author Hans Joachim Ferreau
*/
enum returnValue
{
TERMINAL_LIST_ELEMENT = -1, /**< Terminal list element, internal usage only! */
/* miscellaneous */
SUCCESSFUL_RETURN = 0, /**< Successful return. */
RET_DIV_BY_ZERO, /**< Division by zero. */
RET_INDEX_OUT_OF_BOUNDS, /**< Index out of bounds. */
RET_INVALID_ARGUMENTS, /**< At least one of the arguments is invalid. */
RET_ERROR_UNDEFINED, /**< Error number undefined. */
RET_WARNING_UNDEFINED, /**< Warning number undefined. */
RET_INFO_UNDEFINED, /**< Info number undefined. */
RET_EWI_UNDEFINED, /**< Error/warning/info number undefined. */
RET_AVAILABLE_WITH_LINUX_ONLY, /**< This function is available under Linux only. */
RET_UNKNOWN_BUG, /**< The error occurred is not yet known. */
RET_PRINTLEVEL_CHANGED, /**< Print level changed. (10) */
RET_NOT_YET_IMPLEMENTED, /**< Requested function is not yet implemented in this version of qpOASES. */
/* Indexlist */
RET_INDEXLIST_MUST_BE_REORDERD, /**< Index list has to be reordered. */
RET_INDEXLIST_EXCEEDS_MAX_LENGTH, /**< Index list exceeds its maximal physical length. */
RET_INDEXLIST_CORRUPTED, /**< Index list corrupted. */
RET_INDEXLIST_OUTOFBOUNDS, /**< Physical index is out of bounds. */
RET_INDEXLIST_ADD_FAILED, /**< Adding indices from another index set failed. */
RET_INDEXLIST_INTERSECT_FAILED, /**< Intersection with another index set failed. */
/* SubjectTo / Bounds / Constraints */
RET_INDEX_ALREADY_OF_DESIRED_STATUS, /**< Index is already of desired status. (18) */
RET_ADDINDEX_FAILED, /**< Adding index to index set failed. */
RET_REMOVEINDEX_FAILED, /**< Removing index from index set failed. (20) */
RET_SWAPINDEX_FAILED, /**< Cannot swap between different indexsets. */
RET_NOTHING_TO_DO, /**< Nothing to do. */
RET_SETUP_BOUND_FAILED, /**< Setting up bound index failed. */
RET_SETUP_CONSTRAINT_FAILED, /**< Setting up constraint index failed. */
RET_MOVING_BOUND_FAILED, /**< Moving bound between index sets failed. */
RET_MOVING_CONSTRAINT_FAILED, /**< Moving constraint between index sets failed. */
RET_SHIFTING_FAILED, /**< Shifting of bounds/constraints failed. */
RET_ROTATING_FAILED, /**< Rotating of bounds/constraints failed. */
/* QProblem */
RET_QPOBJECT_NOT_SETUP, /**< The QP object has not been setup correctly, use another constructor. */
RET_QP_ALREADY_INITIALISED, /**< QProblem has already been initialised. (30) */
RET_NO_INIT_WITH_STANDARD_SOLVER, /**< Initialisation via extern QP solver is not yet implemented. */
RET_RESET_FAILED, /**< Reset failed. */
RET_INIT_FAILED, /**< Initialisation failed. */
RET_INIT_FAILED_TQ, /**< Initialisation failed due to TQ factorisation. */
RET_INIT_FAILED_CHOLESKY, /**< Initialisation failed due to Cholesky decomposition. */
RET_INIT_FAILED_HOTSTART, /**< Initialisation failed! QP could not be solved! */
RET_INIT_FAILED_INFEASIBILITY, /**< Initial QP could not be solved due to infeasibility! */
RET_INIT_FAILED_UNBOUNDEDNESS, /**< Initial QP could not be solved due to unboundedness! */
RET_INIT_FAILED_REGULARISATION, /**< Initialisation failed as Hessian matrix could not be regularised. */
RET_INIT_SUCCESSFUL, /**< Initialisation done. (40) */
RET_OBTAINING_WORKINGSET_FAILED, /**< Failed to obtain working set for auxiliary QP. */
RET_SETUP_WORKINGSET_FAILED, /**< Failed to setup working set for auxiliary QP. */
RET_SETUP_AUXILIARYQP_FAILED, /**< Failed to setup auxiliary QP for initialised homotopy. */
RET_NO_CHOLESKY_WITH_INITIAL_GUESS, /**< Externally computed Cholesky factor cannot be combined with an
initial guess. */
RET_NO_EXTERN_SOLVER, /**< No extern QP solver available. */
RET_QP_UNBOUNDED, /**< QP is unbounded. */
RET_QP_INFEASIBLE, /**< QP is infeasible. */
RET_QP_NOT_SOLVED, /**< Problems occurred while solving QP with standard solver. */
RET_QP_SOLVED, /**< QP successfully solved. */
RET_UNABLE_TO_SOLVE_QP, /**< Problems occurred while solving QP. (50) */
RET_INITIALISATION_STARTED, /**< Starting problem initialisation... */
RET_HOTSTART_FAILED, /**< Unable to perform homotopy due to internal error. */
RET_HOTSTART_FAILED_TO_INIT, /**< Unable to initialise problem. */
RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED, /**< Unable to perform homotopy as previous QP is not solved.
*/
RET_ITERATION_STARTED, /**< Iteration... */
RET_SHIFT_DETERMINATION_FAILED, /**< Determination of shift of the QP data failed. */
RET_STEPDIRECTION_DETERMINATION_FAILED, /**< Determination of step direction failed. */
RET_STEPLENGTH_DETERMINATION_FAILED, /**< Determination of step direction failed. */
RET_OPTIMAL_SOLUTION_FOUND, /**< Optimal solution of neighbouring QP found. */
RET_HOMOTOPY_STEP_FAILED, /**< Unable to perform homotopy step. (60) */
RET_HOTSTART_STOPPED_INFEASIBILITY, /**< Premature homotopy termination because QP is infeasible. */
RET_HOTSTART_STOPPED_UNBOUNDEDNESS, /**< Premature homotopy termination because QP is unbounded. */
RET_WORKINGSET_UPDATE_FAILED, /**< Unable to update working sets according to initial guesses. */
RET_MAX_NWSR_REACHED, /**< Maximum number of working set recalculations performed. */
RET_CONSTRAINTS_NOT_SPECIFIED, /**< Problem does comprise constraints! You also have to specify new
constraints' bounds. */
RET_INVALID_FACTORISATION_FLAG, /**< Invalid factorisation flag. */
RET_UNABLE_TO_SAVE_QPDATA, /**< Unable to save QP data. */
RET_STEPDIRECTION_FAILED_TQ, /**< Abnormal termination due to TQ factorisation. */
RET_STEPDIRECTION_FAILED_CHOLESKY, /**< Abnormal termination due to Cholesky factorisation. */
RET_CYCLING_DETECTED, /**< Cycling detected. (70) */
RET_CYCLING_NOT_RESOLVED, /**< Cycling cannot be resolved, QP probably infeasible. */
RET_CYCLING_RESOLVED, /**< Cycling probably resolved. */
RET_STEPSIZE, /**< For displaying performed stepsize. */
RET_STEPSIZE_NONPOSITIVE, /**< For displaying non-positive stepsize. */
RET_SETUPSUBJECTTOTYPE_FAILED, /**< Setup of SubjectToTypes failed. */
RET_ADDCONSTRAINT_FAILED, /**< Addition of constraint to working set failed. */
RET_ADDCONSTRAINT_FAILED_INFEASIBILITY, /**< Addition of constraint to working set failed (due to QP
infeasibility). */
RET_ADDBOUND_FAILED, /**< Addition of bound to working set failed. */
RET_ADDBOUND_FAILED_INFEASIBILITY, /**< Addition of bound to working set failed (due to QP infeasibility).
*/
RET_REMOVECONSTRAINT_FAILED, /**< Removal of constraint from working set failed. (80) */
RET_REMOVEBOUND_FAILED, /**< Removal of bound from working set failed. */
RET_REMOVE_FROM_ACTIVESET, /**< Removing from active set... */
RET_ADD_TO_ACTIVESET, /**< Adding to active set... */
RET_REMOVE_FROM_ACTIVESET_FAILED, /**< Removing from active set failed. */
RET_ADD_TO_ACTIVESET_FAILED, /**< Adding to active set failed. */
RET_CONSTRAINT_ALREADY_ACTIVE, /**< Constraint is already active. */
RET_ALL_CONSTRAINTS_ACTIVE, /**< All constraints are active, no further constraint can be added. */
RET_LINEARLY_DEPENDENT, /**< New bound/constraint is linearly dependent. */
RET_LINEARLY_INDEPENDENT, /**< New bound/constraint is linearly independent. */
RET_LI_RESOLVED, /**< Linear independence of active constraint matrix successfully resolved. (90) */
RET_ENSURELI_FAILED, /**< Failed to ensure linear independence of active constraint matrix. */
RET_ENSURELI_FAILED_TQ, /**< Abnormal termination due to TQ factorisation. */
RET_ENSURELI_FAILED_NOINDEX, /**< QP is infeasible. */
RET_ENSURELI_FAILED_CYCLING, /**< QP is infeasible. */
RET_BOUND_ALREADY_ACTIVE, /**< Bound is already active. */
RET_ALL_BOUNDS_ACTIVE, /**< All bounds are active, no further bound can be added. */
RET_CONSTRAINT_NOT_ACTIVE, /**< Constraint is not active. */
RET_BOUND_NOT_ACTIVE, /**< Bound is not active. */
RET_HESSIAN_NOT_SPD, /**< Projected Hessian matrix not positive definite. */
RET_HESSIAN_INDEFINITE, /**< Hessian matrix is indefinite. (100) */
RET_MATRIX_SHIFT_FAILED, /**< Unable to update matrices or to transform vectors. */
RET_MATRIX_FACTORISATION_FAILED, /**< Unable to calculate new matrix factorisations. */
RET_PRINT_ITERATION_FAILED, /**< Unable to print information on current iteration. */
RET_NO_GLOBAL_MESSAGE_OUTPUTFILE, /**< No global message output file initialised. */
RET_DISABLECONSTRAINTS_FAILED, /**< Unable to disbable constraints. */
RET_ENABLECONSTRAINTS_FAILED, /**< Unable to enbable constraints. */
RET_ALREADY_ENABLED, /**< Bound or constraint is already enabled. */
RET_ALREADY_DISABLED, /**< Bound or constraint is already disabled. */
RET_NO_HESSIAN_SPECIFIED, /**< No Hessian matrix has been specified. */
RET_USING_REGULARISATION, /**< Using regularisation as Hessian matrix is not positive definite. (110) */
RET_EPS_MUST_BE_POSITVE, /**< Eps for regularisation must be sufficiently positive. */
RET_REGSTEPS_MUST_BE_POSITVE, /**< Maximum number of regularisation steps must be non-negative. */
RET_HESSIAN_ALREADY_REGULARISED, /**< Hessian has been already regularised. */
RET_CANNOT_REGULARISE_IDENTITY, /**< Identity Hessian matrix cannot be regularised. */
RET_CANNOT_REGULARISE_SPARSE, /**< Sparse matrix cannot be regularised as diagonal entry is missing. */
RET_NO_REGSTEP_NWSR, /**< No additional regularisation step could be performed due to limits. */
RET_FEWER_REGSTEPS_NWSR, /**< Fewer additional regularisation steps have been performed due to limits. */
RET_CHOLESKY_OF_ZERO_HESSIAN, /**< Cholesky decomposition of (unregularised) zero Hessian matrix. */
RET_ZERO_HESSIAN_ASSUMED, /**< Zero Hessian matrix assumed as null pointer passed without specifying
hessianType. */
RET_CONSTRAINTS_ARE_NOT_SCALED, /**< (no longer in use) (120) */
RET_INITIAL_BOUNDS_STATUS_NYI, /**< (no longer in use) */
RET_ERROR_IN_CONSTRAINTPRODUCT, /**< Error in user-defined constraint product function. */
RET_FIX_BOUNDS_FOR_LP, /**< All initial bounds must be fixed when solving an (unregularised) LP. */
RET_USE_REGULARISATION_FOR_LP, /**< Set options.enableRegularisation=BT_TRUE for solving LPs. */
/* SQProblem */
RET_UPDATEMATRICES_FAILED, /**< Unable to update QP matrices. */
RET_UPDATEMATRICES_FAILED_AS_QP_NOT_SOLVED, /**< Unable to update matrices as previous QP is not solved.
*/
/* Utils */
RET_UNABLE_TO_OPEN_FILE, /**< Unable to open file. */
RET_UNABLE_TO_WRITE_FILE, /**< Unable to write into file. */
RET_UNABLE_TO_READ_FILE, /**< Unable to read from file. */
RET_FILEDATA_INCONSISTENT, /**< File contains inconsistent data. (130) */
/* Options */
RET_OPTIONS_ADJUSTED, /**< Options needed to be adjusted for consistency reasons. */
/* SolutionAnalysis */
RET_UNABLE_TO_ANALYSE_QPROBLEM, /**< Unable to analyse (S)QProblem(B) object. */
/* Benchmark */
RET_NWSR_SET_TO_ONE, /**< Maximum number of working set changes was set to 1. */
RET_UNABLE_TO_READ_BENCHMARK, /**< Unable to read benchmark data. */
RET_BENCHMARK_ABORTED, /**< Benchmark aborted. */
RET_INITIAL_QP_SOLVED, /**< Initial QP solved. */
RET_QP_SOLUTION_STARTED, /**< Solving QP... */
RET_BENCHMARK_SUCCESSFUL, /**< Benchmark terminated successfully. */
/* Sparse matrices */
RET_NO_DIAGONAL_AVAILABLE, /**< Sparse matrix does not have entries on full diagonal. */
RET_DIAGONAL_NOT_INITIALISED, /**< Diagonal data of sparse matrix has not been initialised. (140) */
/* Dropping of infeasible constraints */
RET_ENSURELI_DROPPED, /**< Linear independence resolved by dropping blocking constraint. */
/* Schur complement computations */
RET_KKT_MATRIX_SINGULAR, /**< KKT matrix is singular. */
RET_QR_FACTORISATION_FAILED, /**< QR factorization of Schur complement failed. */
RET_INERTIA_CORRECTION_FAILED, /**< Inertia correction failed after KKT matrix had too many negative
eigenvalues. */
RET_NO_SPARSE_SOLVER, /**< No factorization routine for the KKT matrix installed. */
/* Simple exitflags */
RET_SIMPLE_STATUS_P1, /**< QP problem could not be solved within given number of iterations. */
RET_SIMPLE_STATUS_P0, /**< QP problem solved. */
RET_SIMPLE_STATUS_M1, /**< QP problem could not be solved due to an internal error. */
RET_SIMPLE_STATUS_M2, /**< QP problem is infeasible (and thus could not be solved). */
RET_SIMPLE_STATUS_M3 /**< QP problem is unbounded (and thus could not be solved). (150) */
};
/**
* \brief Handles all kind of error messages, warnings and other information.
*
* This class handles all kinds of messages (errors, warnings, infos) initiated
* by qpOASES modules and stores the corresponding global preferences.
*
* \author Hans Joachim Ferreau (thanks to Leonard Wirsching)
* \version 3.2
* \date 2007-2017
*/
class MessageHandling
{
/*
* INTERNAL DATA STRUCTURES
*/
public:
/**
* \brief Data structure for entries in global message list.
*
* Data structure for entries in global message list.
*
* \author Hans Joachim Ferreau
*/
typedef struct
{
returnValue key; /**< Global return value. */
const char * data; /**< Corresponding message. */
VisibilityStatus
globalVisibilityStatus; /**< Determines if message can be printed.
* If this value is set to VS_HIDDEN, no message is printed! */
} ReturnValueList;
/*
* PUBLIC MEMBER FUNCTIONS
*/
public:
/** Default constructor. */
MessageHandling();
/** Constructor which takes the desired output file. */
MessageHandling(FILE * _outputFile /**< Output file. */
);
/** Constructor which takes the desired visibility states. */
MessageHandling(VisibilityStatus _errorVisibility, /**< Visibility status for error messages. */
VisibilityStatus _warningVisibility, /**< Visibility status for warning messages. */
VisibilityStatus _infoVisibility /**< Visibility status for info messages. */
);
/** Constructor which takes the desired output file and desired visibility states. */
MessageHandling(FILE * _outputFile, /**< Output file. */
VisibilityStatus _errorVisibility, /**< Visibility status for error messages. */
VisibilityStatus _warningVisibility, /**< Visibility status for warning messages. */
VisibilityStatus _infoVisibility /**< Visibility status for info messages. */
);
/** Copy constructor (deep copy). */
MessageHandling(const MessageHandling & rhs /**< Rhs object. */
);
/** Destructor. */
~MessageHandling();
/** Assignment operator (deep copy). */
MessageHandling & operator=(const MessageHandling & rhs /**< Rhs object. */
);
/** Prints an error message(a simplified macro THROWERROR is also provided). \n
* Errors are defined as abnormal events which cause an immediate termination of the current (sub)
* function. Errors of a sub function should be commented by the calling function by means of a warning
* message (if this error does not cause an error of the calling function, either)! \return Error number
* returned by sub function call
*/
returnValue throwError(returnValue Enumber, /**< Error number returned by sub function call. */
const char * additionaltext, /**< Additional error text (0, if none). */
const char * functionname, /**< Name of function which caused the error. */
const char * filename, /**< Name of file which caused the error. */
const unsigned long linenumber, /**< Number of line which caused the error.incompatible binary file */
VisibilityStatus localVisibilityStatus /**< Determines (locally) if error message can be printed to
* stdFile. If GLOBAL visibility status of the message is set to
* VS_HIDDEN, no message is printed, anyway! */
);
/** Prints a warning message (a simplified macro THROWWARNING is also provided).
* Warnings are definied as abnormal events which does NOT cause an immediate termination of the current
* (sub) function. \return Warning number returned by sub function call
*/
returnValue throwWarning(returnValue Wnumber, /**< Warning number returned by sub function call. */
const char * additionaltext, /**< Additional warning text (0, if none). */
const char * functionname, /**< Name of function which caused the warning. */
const char * filename, /**< Name of file which caused the warning. */
const unsigned long linenumber, /**< Number of line which caused the warning. */
VisibilityStatus localVisibilityStatus /**< Determines (locally) if warning message can be printed to
* stdFile. If GLOBAL visibility status of the message is set to
* VS_HIDDEN, no message is printed, anyway! */
);
/** Prints a info message (a simplified macro THROWINFO is also provided).
* \return Info number returned by sub function call
*/
returnValue throwInfo(returnValue Inumber, /**< Info number returned by sub function call. */
const char * additionaltext, /**< Additional warning text (0, if none). */
const char * functionname, /**< Name of function which submitted the info. */
const char * filename, /**< Name of file which submitted the info. */
const unsigned long linenumber, /**< Number of line which submitted the info. */
VisibilityStatus localVisibilityStatus /**< Determines (locally) if info message can be printed to
* stdFile. If GLOBAL visibility status of the message is set to
* VS_HIDDEN, no message is printed, anyway! */
);
/** Resets all preferences to default values.
* \return SUCCESSFUL_RETURN */
returnValue reset();
/** Prints a complete list of all messages to output file.
* \return SUCCESSFUL_RETURN */
returnValue listAllMessages();
/** Returns visibility status for error messages.
* \return Visibility status for error messages. */
inline VisibilityStatus getErrorVisibilityStatus() const;
/** Returns visibility status for warning messages.
* \return Visibility status for warning messages. */
inline VisibilityStatus getWarningVisibilityStatus() const;
/** Returns visibility status for info messages.
* \return Visibility status for info messages. */
inline VisibilityStatus getInfoVisibilityStatus() const;
/** Returns pointer to output file.
* \return Pointer to output file. */
inline FILE * getOutputFile() const;
/** Returns error count value.
* \return Error count value. */
inline int_t getErrorCount() const;
/** Changes visibility status for error messages. */
inline void setErrorVisibilityStatus(
VisibilityStatus _errorVisibility /**< New visibility status for error messages. */
);
/** Changes visibility status for warning messages. */
inline void setWarningVisibilityStatus(
VisibilityStatus _warningVisibility /**< New visibility status for warning messages. */
);
/** Changes visibility status for info messages. */
inline void setInfoVisibilityStatus(
VisibilityStatus _infoVisibility /**< New visibility status for info messages. */
);
/** Changes output file for messages. */
inline void setOutputFile(FILE * _outputFile /**< New output file for messages. */
);
/** Changes error count.
* \return SUCCESSFUL_RETURN \n
* RET_INVALID_ARGUMENT */
inline returnValue setErrorCount(int_t _errorCount /**< New error count value. */
);
/** Provides message text corresponding to given \a returnValue.
* \return String containing message text. */
static const char * getErrorCodeMessage(const returnValue _returnValue);
/*
* PROTECTED MEMBER FUNCTIONS
*/
protected:
/** Prints a info message to stdFile (auxiliary function).
* \return Error/warning/info number returned by sub function call
*/
returnValue throwMessage(
returnValue RETnumber, /**< Error/warning/info number returned by sub function call. */
const char * additionaltext, /**< Additional warning text (0, if none). */
const char * functionname, /**< Name of function which caused the error/warning/info. */
const char * filename, /**< Name of file which caused the error/warning/info. */
const unsigned long linenumber, /**< Number of line which caused the error/warning/info. */
VisibilityStatus localVisibilityStatus, /**< Determines (locally) if info message can be printed to
* stdFile. If GLOBAL visibility status of the message is set to
* VS_HIDDEN, no message is printed, anyway! */
const char * RETstring /**< Leading string of error/warning/info message. */
);
/*
* PROTECTED MEMBER VARIABLES
*/
protected:
VisibilityStatus errorVisibility; /**< Error messages visible? */
VisibilityStatus warningVisibility; /**< Warning messages visible? */
VisibilityStatus infoVisibility; /**< Info messages visible? */
FILE * outputFile; /**< Output file for messages. */
int_t errorCount; /**< Counts number of errors (for nicer output only). */
};
#ifndef __FILE__
/** Ensures that __FILE__ macro is defined. */
#define __FILE__ 0
#endif
#ifndef __LINE__
/** Ensures that __LINE__ macro is defined. */
#define __LINE__ 0
#endif
/** Define __FUNC__ macro providing current function for debugging. */
/*#define __FUNC__ 0*/
#define __FUNC__ ("(no function name provided)")
/*#define __FUNC__ __func__*/
/*#define __FUNC__ __FUNCTION__*/
/** Short version of throwError with default values, only returnValue is needed */
#define THROWERROR(retval) \
(getGlobalMessageHandler()->throwError((retval), 0, __FUNC__, __FILE__, __LINE__, VS_VISIBLE))
/** Short version of throwWarning with default values, only returnValue is needed */
#define THROWWARNING(retval) \
(getGlobalMessageHandler()->throwWarning((retval), 0, __FUNC__, __FILE__, __LINE__, VS_VISIBLE))
/** Short version of throwInfo with default values, only returnValue is needed */
#define THROWINFO(retval) \
(getGlobalMessageHandler()->throwInfo((retval), 0, __FUNC__, __FILE__, __LINE__, VS_VISIBLE))
/** Returns a pointer to global message handler.
* \return Pointer to global message handler.
*/
MessageHandling * getGlobalMessageHandler();
END_NAMESPACE_QPOASES
#include <qpOASES/MessageHandling.ipp>
#endif /* QPOASES_MESSAGEHANDLING_HPP */
/*
* end of file
*/
@@ -0,0 +1,144 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/MessageHandling.ipp
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*
* Implementation of inlined member functions of the MessageHandling class.
*/
BEGIN_NAMESPACE_QPOASES
/*****************************************************************************
* P U B L I C *
*****************************************************************************/
/*
* g e t E r r o r V i s i b i l i t y S t a t u s
*/
inline VisibilityStatus MessageHandling::getErrorVisibilityStatus( ) const
{
return errorVisibility;
}
/*
* g e t W a r n i n g V i s i b i l i t y S t a t u s
*/
inline VisibilityStatus MessageHandling::getWarningVisibilityStatus( ) const
{
return warningVisibility;
}
/*
* g e t I n f o V i s i b i l i t y S t a t u s
*/
inline VisibilityStatus MessageHandling::getInfoVisibilityStatus( ) const
{
return infoVisibility;
}
/*
* g e t O u t p u t F i l e
*/
inline FILE* MessageHandling::getOutputFile( ) const
{
return outputFile;
}
/*
* g e t E r r o r C o u n t
*/
inline int_t MessageHandling::getErrorCount( ) const
{
return errorCount;
}
/*
* s e t E r r o r V i s i b i l i t y S t a t u s
*/
inline void MessageHandling::setErrorVisibilityStatus( VisibilityStatus _errorVisibility )
{
errorVisibility = _errorVisibility;
}
/*
* s e t W a r n i n g V i s i b i l i t y S t a t u s
*/
inline void MessageHandling::setWarningVisibilityStatus( VisibilityStatus _warningVisibility )
{
warningVisibility = _warningVisibility;
}
/*
* s e t I n f o V i s i b i l i t y S t a t u s
*/
inline void MessageHandling::setInfoVisibilityStatus( VisibilityStatus _infoVisibility )
{
infoVisibility = _infoVisibility;
}
/*
* s e t O u t p u t F i l e
*/
inline void MessageHandling::setOutputFile( FILE* _outputFile )
{
outputFile = _outputFile;
}
/*
* s e t E r r o r C o u n t
*/
inline returnValue MessageHandling::setErrorCount( int_t _errorCount )
{
if ( _errorCount >= -1 )
{
errorCount = _errorCount;
return SUCCESSFUL_RETURN;
}
else
return RET_INVALID_ARGUMENTS;
}
END_NAMESPACE_QPOASES
/*
* end of file
*/
@@ -0,0 +1,166 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/Options.hpp
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*
* Declaration of the Options class designed to manage user-specified
* options for solving a QProblem.
*/
#ifndef QPOASES_OPTIONS_HPP
#define QPOASES_OPTIONS_HPP
#include <qpOASES/Utils.hpp>
BEGIN_NAMESPACE_QPOASES
/**
* \brief Manages all user-specified options for solving QPs.
*
* This class manages all user-specified options used for solving
* quadratic programs.
*
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*/
class Options
{
/*
* PUBLIC MEMBER FUNCTIONS
*/
public:
/** Default constructor. */
Options();
/** Copy constructor (deep copy). */
Options(const Options & rhs /**< Rhs object. */
);
/** Destructor. */
~Options();
/** Assignment operator (deep copy). */
Options & operator=(const Options & rhs /**< Rhs object. */
);
/** Sets all options to default values.
* \return SUCCESSFUL_RETURN */
returnValue setToDefault();
/** Sets all options to values resulting in maximum reliabilty.
* \return SUCCESSFUL_RETURN */
returnValue setToReliable();
/** Sets all options to values resulting in minimum solution time.
* \return SUCCESSFUL_RETURN */
returnValue setToMPC();
/** Same as setToMPC( ), for ensuring backwards compatibility.
* \return SUCCESSFUL_RETURN */
returnValue setToFast();
/** Ensures that all options have consistent values by automatically
* adjusting inconsistent ones.
* Note: This routine cannot (and does not try to) ensure that values
* are set to reasonable values that make the QP solution work!
* \return SUCCESSFUL_RETURN \n
* RET_OPTIONS_ADJUSTED */
returnValue ensureConsistency();
/** Prints values of all options.
* \return SUCCESSFUL_RETURN */
returnValue print() const;
/*
* PROTECTED MEMBER FUNCTIONS
*/
protected:
/** Copies all members from given rhs object.
* \return SUCCESSFUL_RETURN */
returnValue copy(const Options & rhs /**< Rhs object. */
);
/*
* PUBLIC MEMBER VARIABLES
*/
public:
PrintLevel printLevel; /**< Print level. */
BooleanType enableRamping; /**< Specifies whether ramping shall be enabled or not. */
BooleanType enableFarBounds; /**< Specifies whether far bounds shall be used or not. */
BooleanType enableFlippingBounds; /**< Specifies whether flipping bounds shall be used or not. */
BooleanType enableRegularisation; /**< Specifies whether Hessian matrix shall be regularised in case
semi-definiteness is detected. */
BooleanType enableFullLITests; /**< Specifies whether condition-hardened LI test shall be used or not. */
BooleanType enableNZCTests; /**< Specifies whether nonzero curvature tests shall be used. */
int_t enableDriftCorrection; /**< Specifies the frequency of drift corrections (0 = off). */
int_t enableCholeskyRefactorisation; /**< Specifies the frequency of full refactorisation of proj. Hessian
(otherwise updates). */
BooleanType
enableEqualities; /**< Specifies whether equalities shall be always treated as active constraints. */
real_t terminationTolerance; /**< Termination tolerance. */
real_t boundTolerance; /**< Lower/upper (constraints') bound tolerance (an inequality constraint whose
lower and upper bounds differ by less is regarded to be an equality constraint). */
real_t boundRelaxation; /**< Offset for relaxing (constraints') bounds at beginning of an initial
homotopy. It is also as initial value for far bounds. */
real_t epsNum; /**< Numerator tolerance for ratio tests. */
real_t epsDen; /**< Denominator tolerance for ratio tests. */
real_t maxPrimalJump; /**< Maximum allowed jump in primal variables in nonzero curvature tests. */
real_t maxDualJump; /**< Maximum allowed jump in dual variables in linear independence tests. */
real_t initialRamping; /**< Start value for Ramping Strategy. */
real_t finalRamping; /**< Final value for Ramping Strategy. */
real_t initialFarBounds; /**< Initial size of Far Bounds. */
real_t growFarBounds; /**< Factor to grow Far Bounds. */
SubjectToStatus initialStatusBounds; /**< Initial status of bounds at first iteration. */
real_t epsFlipping; /**< Tolerance of squared Cholesky diagonal factor which triggers flipping bound. */
int_t numRegularisationSteps; /**< Maximum number of successive regularisation steps. */
real_t epsRegularisation; /**< Scaling factor of identity matrix used for Hessian regularisation. */
int_t numRefinementSteps; /**< Maximum number of iterative refinement steps. */
real_t epsIterRef; /**< Early termination tolerance for iterative refinement. */
real_t epsLITests; /**< Tolerance for linear independence tests. */
real_t epsNZCTests; /**< Tolerance for nonzero curvature tests. */
real_t rcondSMin; /**< Minimum reciprocal condition number of S before refactorization is triggered */
BooleanType enableInertiaCorrection; /**< Specifies whether the working set should be repaired when
negative curvature is discovered during hotstart. */
BooleanType enableDropInfeasibles; /**< ... */
int_t dropBoundPriority; /**< ... */
int_t dropEqConPriority; /**< ... */
int_t dropIneqConPriority; /**< ... */
};
END_NAMESPACE_QPOASES
#endif /* QPOASES_OPTIONS_HPP */
/*
* end of file
*/
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,284 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/QProblem.ipp
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*
* Implementation of inlined member functions of the QProblem class which
* is able to use the newly developed online active set strategy for
* parametric quadratic programming.
*/
BEGIN_NAMESPACE_QPOASES
/*****************************************************************************
* P U B L I C *
*****************************************************************************/
/*
* g e t C o n s t r a i n t s
*/
inline returnValue QProblem::getConstraints( Constraints& _constraints ) const
{
int_t nV = getNV( );
if ( nV == 0 )
return THROWERROR( RET_QPOBJECT_NOT_SETUP );
_constraints = constraints;
return SUCCESSFUL_RETURN;
}
/*
* g e t N C
*/
inline int_t QProblem::getNC( ) const
{
return constraints.getNC( );
}
/*
* g e t N E C
*/
inline int_t QProblem::getNEC( ) const
{
return constraints.getNEC( );
}
/*
* g e t N A C
*/
inline int_t QProblem::getNAC( ) const
{
return constraints.getNAC( );
}
/*
* g e t N I A C
*/
inline int_t QProblem::getNIAC( ) const
{
return constraints.getNIAC( );
}
/*****************************************************************************
* P R O T E C T E D *
*****************************************************************************/
/*
* s e t A
*/
inline returnValue QProblem::setA( Matrix *A_new )
{
int_t j;
int_t nV = getNV( );
int_t nC = getNC( );
if ( nV == 0 )
return THROWERROR( RET_QPOBJECT_NOT_SETUP );
if ( A_new == 0 )
return THROWERROR( RET_INVALID_ARGUMENTS );
/* Set constraint matrix AND update member AX. */
if ( ( freeConstraintMatrix == BT_TRUE ) && ( A != 0 ) )
{
delete A;
A = 0;
}
A = A_new;
freeConstraintMatrix = BT_FALSE;
A->times(1, 1.0, x, nV, 0.0, Ax, nC);
A->getRowNorm(tempC);
for( j=0; j<nC; ++j )
{
Ax_u[j] = ubA[j] - Ax[j];
Ax_l[j] = Ax[j] - lbA[j];
// (ckirches) disable constraints with empty rows
if ( isZero( tempC[j] ) == BT_TRUE )
constraints.setType ( j, ST_DISABLED );
}
return SUCCESSFUL_RETURN;
}
/*
* s e t A
*/
inline returnValue QProblem::setA( const real_t* const A_new )
{
int_t j;
int_t nV = getNV( );
int_t nC = getNC( );
DenseMatrix* dA;
if ( nV == 0 )
return THROWERROR( RET_QPOBJECT_NOT_SETUP );
if ( A_new == 0 )
return THROWERROR( RET_INVALID_ARGUMENTS );
/* Set constraint matrix AND update member AX. */
if ( ( freeConstraintMatrix == BT_TRUE ) && ( A != 0 ) )
{
delete A;
A = 0;
}
A = dA = new DenseMatrix(nC, nV, nV, (real_t*) A_new);
freeConstraintMatrix = BT_TRUE;
A->times(1, 1.0, x, nV, 0.0, Ax, nC);
for( j=0; j<nC; ++j )
{
Ax_u[j] = ubA[j] - Ax[j];
Ax_l[j] = Ax[j] - lbA[j];
}
return SUCCESSFUL_RETURN;
}
/*
* s e t L B A
*/
inline returnValue QProblem::setLBA( const real_t* const lbA_new )
{
uint_t i;
uint_t nV = (uint_t)getNV( );
uint_t nC = (uint_t)getNC( );
if ( nV == 0 )
return THROWERROR( RET_QPOBJECT_NOT_SETUP );
if ( lbA_new != 0 )
{
memcpy( lbA,lbA_new,nC*sizeof(real_t) );
}
else
{
/* if no lower constraints' bounds are specified, set them to -infinity */
for( i=0; i<nC; ++i )
lbA[i] = -INFTY;
}
return SUCCESSFUL_RETURN;
}
/*
* s e t L B A
*/
inline returnValue QProblem::setLBA( int_t number, real_t value )
{
int_t nV = getNV( );
int_t nC = getNC( );
if ( nV == 0 )
return THROWERROR( RET_QPOBJECT_NOT_SETUP );
if ( ( number >= 0 ) && ( number < nC ) )
{
lbA[number] = value;
return SUCCESSFUL_RETURN;
}
else
return THROWERROR( RET_INDEX_OUT_OF_BOUNDS );
}
/*
* s e t U B A
*/
inline returnValue QProblem::setUBA( const real_t* const ubA_new )
{
uint_t i;
uint_t nV = (uint_t)getNV( );
uint_t nC = (uint_t)getNC( );
if ( nV == 0 )
return THROWERROR( RET_QPOBJECT_NOT_SETUP );
if ( ubA_new != 0 )
{
memcpy( ubA,ubA_new,nC*sizeof(real_t) );
}
else
{
/* if no upper constraints' bounds are specified, set them to infinity */
for( i=0; i<nC; ++i )
ubA[i] = INFTY;
}
return SUCCESSFUL_RETURN;
}
/*
* s e t U B A
*/
inline returnValue QProblem::setUBA( int_t number, real_t value )
{
int_t nV = getNV( );
int_t nC = getNC( );
if ( nV == 0 )
return THROWERROR( RET_QPOBJECT_NOT_SETUP );
if ( ( number >= 0 ) && ( number < nC ) )
{
ubA[number] = value;
return SUCCESSFUL_RETURN;
}
else
return THROWERROR( RET_INDEX_OUT_OF_BOUNDS );
}
END_NAMESPACE_QPOASES
/*
* end of file
*/
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,496 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/QProblemB.ipp
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*
* Implementation of inlined member functions of the QProblemB class which
* is able to use the newly developed online active set strategy for
* parametric quadratic programming.
*/
BEGIN_NAMESPACE_QPOASES
/*****************************************************************************
* P U B L I C *
*****************************************************************************/
/*
* g e t B o u n d s
*/
inline returnValue QProblemB::getBounds( Bounds& _bounds ) const
{
int_t nV = getNV( );
if ( nV == 0 )
return THROWERROR( RET_QPOBJECT_NOT_SETUP );
_bounds = bounds;
return SUCCESSFUL_RETURN;
}
/*
* g e t N V
*/
inline int_t QProblemB::getNV( ) const
{
return bounds.getNV( );
}
/*
* g e t N F R
*/
inline int_t QProblemB::getNFR( ) const
{
return bounds.getNFR( );
}
/*
* g e t N F X
*/
inline int_t QProblemB::getNFX( ) const
{
return bounds.getNFX( );
}
/*
* g e t N F V
*/
inline int_t QProblemB::getNFV( ) const
{
return bounds.getNFV( );
}
/*
* g e t S t a t u s
*/
inline QProblemStatus QProblemB::getStatus( ) const
{
return status;
}
/*
* i s I n i t i a l i s e d
*/
inline BooleanType QProblemB::isInitialised( ) const
{
if ( status == QPS_NOTINITIALISED )
return BT_FALSE;
else
return BT_TRUE;
}
/*
* i s S o l v e d
*/
inline BooleanType QProblemB::isSolved( ) const
{
if ( status == QPS_SOLVED )
return BT_TRUE;
else
return BT_FALSE;
}
/*
* i s I n f e a s i b l e
*/
inline BooleanType QProblemB::isInfeasible( ) const
{
return infeasible;
}
/*
* i s U n b o u n d e d
*/
inline BooleanType QProblemB::isUnbounded( ) const
{
return unbounded;
}
/*
* g e t H e s s i a n T y p e
*/
inline HessianType QProblemB::getHessianType( ) const
{
return hessianType;
}
/*
* s e t H e s s i a n T y p e
*/
inline returnValue QProblemB::setHessianType( HessianType _hessianType )
{
hessianType = _hessianType;
return SUCCESSFUL_RETURN;
}
/*
* u s i n g R e g u l a r i s a t i o n
*/
inline BooleanType QProblemB::usingRegularisation( ) const
{
if ( regVal > ZERO )
return BT_TRUE;
else
return BT_FALSE;
}
/*
* g e t O p t i o n s
*/
inline Options QProblemB::getOptions( ) const
{
return options;
}
/*
* s e t O p t i o n s
*/
inline returnValue QProblemB::setOptions( const Options& _options
)
{
options = _options;
options.ensureConsistency( );
setPrintLevel( options.printLevel );
return SUCCESSFUL_RETURN;
}
/*
* g e t P r i n t L e v e l
*/
inline PrintLevel QProblemB::getPrintLevel( ) const
{
return options.printLevel;
}
/*
* g e t C o u n t
*/
inline uint_t QProblemB::getCount( ) const
{
return count;
}
/*
* r e s e t C o u n t e r
*/
inline returnValue QProblemB::resetCounter( )
{
count = 0;
return SUCCESSFUL_RETURN;
}
/*****************************************************************************
* P R O T E C T E D *
*****************************************************************************/
/*
* s e t H
*/
inline returnValue QProblemB::setH( SymmetricMatrix* H_new )
{
if ( ( freeHessian == BT_TRUE ) && ( H != 0 ) )
{
delete H;
H = 0;
}
H = H_new;
freeHessian = BT_FALSE;
return SUCCESSFUL_RETURN;
}
/*
* s e t H
*/
inline returnValue QProblemB::setH( const real_t* const H_new )
{
int_t nV = getNV();
SymDenseMat* dH;
/* if null pointer is passed, Hessian is set to zero matrix
* (or stays identity matrix) */
if ( H_new == 0 )
{
if ( hessianType == HST_IDENTITY )
return SUCCESSFUL_RETURN;
hessianType = HST_ZERO;
if ( ( freeHessian == BT_TRUE ) && ( H != 0 ) )
delete H;
H = 0;
freeHessian = BT_FALSE;
}
else
{
if ( ( freeHessian == BT_TRUE ) && ( H != 0 ) )
delete H;
H = dH = new SymDenseMat( nV, nV, nV, (real_t*) H_new );
freeHessian = BT_TRUE;
}
return SUCCESSFUL_RETURN;
}
/*
* s e t G
*/
inline returnValue QProblemB::setG( const real_t* const g_new )
{
uint_t nV = (uint_t)getNV( );
if ( nV == 0 )
return THROWERROR( RET_QPOBJECT_NOT_SETUP );
if ( g_new == 0 )
return THROWERROR( RET_INVALID_ARGUMENTS );
memcpy( g,g_new,nV*sizeof(real_t) );
return SUCCESSFUL_RETURN;
}
/*
* s e t L B
*/
inline returnValue QProblemB::setLB( const real_t* const lb_new )
{
uint_t i;
uint_t nV = (uint_t)getNV( );
if ( nV == 0 )
return THROWERROR( RET_QPOBJECT_NOT_SETUP );
if ( lb_new != 0 )
{
memcpy( lb,lb_new,nV*sizeof(real_t) );
}
else
{
/* if no lower bounds are specified, set them to -infinity */
for( i=0; i<nV; ++i )
lb[i] = -INFTY;
}
return SUCCESSFUL_RETURN;
}
/*
* s e t L B
*/
inline returnValue QProblemB::setLB( int_t number, real_t value )
{
int_t nV = getNV( );
if ( nV == 0 )
return THROWERROR( RET_QPOBJECT_NOT_SETUP );
if ( ( number >= 0 ) && ( number < nV ) )
{
lb[number] = value;
return SUCCESSFUL_RETURN;
}
else
{
return THROWERROR( RET_INDEX_OUT_OF_BOUNDS );
}
}
/*
* s e t U B
*/
inline returnValue QProblemB::setUB( const real_t* const ub_new )
{
uint_t i;
uint_t nV = (uint_t)getNV( );
if ( nV == 0 )
return THROWERROR( RET_QPOBJECT_NOT_SETUP );
if ( ub_new != 0 )
{
memcpy( ub,ub_new,nV*sizeof(real_t) );
}
else
{
/* if no upper bounds are specified, set them to infinity */
for( i=0; i<nV; ++i )
ub[i] = INFTY;
}
return SUCCESSFUL_RETURN;
}
/*
* s e t U B
*/
inline returnValue QProblemB::setUB( int_t number, real_t value )
{
int_t nV = getNV( );
if ( nV == 0 )
return THROWERROR( RET_QPOBJECT_NOT_SETUP );
if ( ( number >= 0 ) && ( number < nV ) )
{
ub[number] = value;
return SUCCESSFUL_RETURN;
}
else
{
return THROWERROR( RET_INDEX_OUT_OF_BOUNDS );
}
}
/*
* c o m p u t e G i v e n s
*/
inline void QProblemB::computeGivens( real_t xold, real_t yold, real_t& xnew, real_t& ynew,
real_t& c, real_t& s
) const
{
real_t t, mu;
if ( isZero( yold ) == BT_TRUE )
{
c = 1.0;
s = 0.0;
xnew = xold;
ynew = yold;
}
else
{
mu = getAbs( xold );
if ( getAbs( yold ) > mu )
mu = getAbs( yold );
t = mu * getSqrt( (xold/mu)*(xold/mu) + (yold/mu)*(yold/mu) );
if ( xold < 0.0 )
t = -t;
c = xold/t;
s = yold/t;
xnew = t;
ynew = 0.0;
}
return;
}
/*
* a p p l y G i v e n s
*/
inline void QProblemB::applyGivens( real_t c, real_t s, real_t nu, real_t xold, real_t yold,
real_t& xnew, real_t& ynew
) const
{
#ifdef __USE_THREE_MULTS_GIVENS__
/* Givens plane rotation requiring only three multiplications,
* cf. Hammarling, S.: A note on modifications to the givens plane rotation.
* J. Inst. Maths Applics, 13:215-218, 1974. */
xnew = xold*c + yold*s;
ynew = (xnew+xold)*nu - yold;
#else
/* Usual Givens plane rotation requiring four multiplications. */
xnew = c*xold + s*yold;
ynew = -s*xold + c*yold;
#endif
return;
}
/*
* i s B l o c k i n g
*/
inline BooleanType QProblemB::isBlocking( real_t num,
real_t den,
real_t epsNum,
real_t epsDen,
real_t& t
) const
{
if ( ( den >= epsDen ) && ( num >= epsNum ) )
{
if ( num < t*den )
return BT_TRUE;
}
return BT_FALSE;
}
END_NAMESPACE_QPOASES
/*
* end of file
*/
@@ -0,0 +1,359 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/SQProblem.hpp
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*
* Declaration of the SQProblem class which is able to use the newly
* developed online active set strategy for parametric quadratic programming
* with varying matrices.
*/
#ifndef QPOASES_SQPROBLEM_HPP
#define QPOASES_SQPROBLEM_HPP
#include <qpOASES/QProblem.hpp>
BEGIN_NAMESPACE_QPOASES
/**
* \brief Implements the online active set strategy for QPs with varying matrices.
*
* A class for setting up and solving quadratic programs with varying QP matrices.
* The main feature is the possibily to use the newly developed online active set strategy
* for parametric quadratic programming.
*
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*/
class SQProblem : public QProblem
{
/* allow SolutionAnalysis class to access private members */
friend class SolutionAnalysis;
/*
* PUBLIC MEMBER FUNCTIONS
*/
public:
/** Default constructor. */
SQProblem();
/** Constructor which takes the QP dimension and Hessian type
* information. If the Hessian is the zero (i.e. HST_ZERO) or the
* identity matrix (i.e. HST_IDENTITY), respectively, no memory
* is allocated for it and a NULL pointer can be passed for it
* to the init() functions. */
SQProblem(int_t _nV, /**< Number of variables. */
int_t _nC, /**< Number of constraints. */
HessianType _hessianType = HST_UNKNOWN, /**< Type of Hessian matrix. */
BooleanType allocDenseMats = BT_TRUE /**< Enable allocation of dense matrices. */
);
/** Copy constructor (deep copy). */
SQProblem(const SQProblem & rhs /**< Rhs object. */
);
/** Destructor. */
virtual ~SQProblem();
/** Assignment operator (deep copy). */
virtual SQProblem & operator=(const SQProblem & rhs /**< Rhs object. */
);
/** Solves an initialised QP sequence with matrix shift using
* the online active set strategy.
* \return SUCCESSFUL_RETURN \n
RET_MAX_NWSR_REACHED \n
RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n
RET_HOTSTART_FAILED \n
RET_MATRIX_SHIFT_FAILED \n
RET_SHIFT_DETERMINATION_FAILED \n
RET_STEPDIRECTION_DETERMINATION_FAILED \n
RET_STEPLENGTH_DETERMINATION_FAILED \n
RET_HOMOTOPY_STEP_FAILED \n
RET_HOTSTART_STOPPED_INFEASIBILITY \n
RET_HOTSTART_STOPPED_UNBOUNDEDNESS \n
RET_SETUP_AUXILIARYQP_FAILED */
returnValue hotstart(
SymmetricMatrix * H_new, /**< Hessian matrix of neighbouring QP to be solved (a shallow copy is made).
\n If Hessian matrix is trivial, a NULL pointer can be passed. */
const real_t * const g_new, /**< Gradient of neighbouring QP to be solved. */
Matrix * A_new, /**< Constraint matrix of neighbouring QP to be solved (a shallow copy is made). \n
If QP sequence does not involve constraints, a NULL pointer can be passed. */
const real_t * const lb_new, /**< Lower bounds of neighbouring QP to be solved. \n
If no lower bounds exist, a NULL pointer can be passed. */
const real_t * const ub_new, /**< Upper bounds of neighbouring QP to be solved. \n
If no upper bounds exist, a NULL pointer can be passed. */
const real_t * const lbA_new, /**< Lower constraints' bounds of neighbouring QP to be solved. \n
If no lower constraints' bounds exist, a NULL pointer can be passed. */
const real_t * const ubA_new, /**< Upper constraints' bounds of neighbouring QP to be solved. \n
If no upper constraints' bounds exist, a NULL pointer can be passed. */
int_t & nWSR, /**< Input: Maximum number of working set recalculations; \n
Output: Number of performed working set recalculations. */
real_t * const cputime = 0, /**< Input: Maximum CPU time allowed for QP solution. \n
Output: CPU time spen for QP solution (or to perform nWSR iterations). */
const Bounds * const guessedBounds = 0, /**< Optimal working set of bounds for solution (xOpt,yOpt). \n
(If a null pointer is passed, the previous working set of bounds is kept!) */
const Constraints * const guessedConstraints =
0 /**< Optimal working set of constraints for solution (xOpt,yOpt). \n
(If a null pointer is passed, the previous working set of constraints is kept!) */
);
/** Solves an initialised QP sequence with matrix shift using
* the online active set strategy.
* \return SUCCESSFUL_RETURN \n
RET_MAX_NWSR_REACHED \n
RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n
RET_HOTSTART_FAILED \n
RET_MATRIX_SHIFT_FAILED \n
RET_SHIFT_DETERMINATION_FAILED \n
RET_STEPDIRECTION_DETERMINATION_FAILED \n
RET_STEPLENGTH_DETERMINATION_FAILED \n
RET_HOMOTOPY_STEP_FAILED \n
RET_HOTSTART_STOPPED_INFEASIBILITY \n
RET_HOTSTART_STOPPED_UNBOUNDEDNESS \n
RET_SETUP_AUXILIARYQP_FAILED */
returnValue hotstart(
const real_t * const H_new, /**< Hessian matrix of neighbouring QP to be solved (a shallow copy is
made). \n If Hessian matrix is trivial, a NULL pointer can be passed. */
const real_t * const g_new, /**< Gradient of neighbouring QP to be solved. */
const real_t * const A_new, /**< Constraint matrix of neighbouring QP to be solved (a shallow copy is
made). \n If QP sequence does not involve constraints, a NULL pointer can be passed. */
const real_t * const lb_new, /**< Lower bounds of neighbouring QP to be solved. \n
If no lower bounds exist, a NULL pointer can be passed. */
const real_t * const ub_new, /**< Upper bounds of neighbouring QP to be solved. \n
If no upper bounds exist, a NULL pointer can be passed. */
const real_t * const lbA_new, /**< Lower constraints' bounds of neighbouring QP to be solved. \n
If no lower constraints' bounds exist, a NULL pointer can be passed. */
const real_t * const ubA_new, /**< Upper constraints' bounds of neighbouring QP to be solved. \n
If no upper constraints' bounds exist, a NULL pointer can be passed. */
int_t & nWSR, /**< Input: Maximum number of working set recalculations; \n
Output: Number of performed working set recalculations. */
real_t * const cputime = 0, /**< Input: Maximum CPU time allowed for QP solution. \n
Output: CPU time spent for QP solution (or to perform nWSR iterations). */
const Bounds * const guessedBounds = 0, /**< Optimal working set of bounds for solution (xOpt,yOpt). \n
(If a null pointer is passed, the previous working set of bounds is kept!) */
const Constraints * const guessedConstraints =
0 /**< Optimal working set of constraints for solution (xOpt,yOpt). \n
(If a null pointer is passed, the previous working set of constraints is kept!) */
);
/** Solves an initialised QP sequence with matrix shift using
* the online active set strategy, where QP data is read from files.
* \return SUCCESSFUL_RETURN \n
RET_MAX_NWSR_REACHED \n
RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n
RET_HOTSTART_FAILED \n
RET_MATRIX_SHIFT_FAILED \n
RET_SHIFT_DETERMINATION_FAILED \n
RET_STEPDIRECTION_DETERMINATION_FAILED \n
RET_STEPLENGTH_DETERMINATION_FAILED \n
RET_HOMOTOPY_STEP_FAILED \n
RET_HOTSTART_STOPPED_INFEASIBILITY \n
RET_HOTSTART_STOPPED_UNBOUNDEDNESS \n
RET_SETUP_AUXILIARYQP_FAILED \n
RET_UNABLE_TO_READ_FILE \n
RET_INVALID_ARGUMENTS */
returnValue hotstart(const char * const H_file, /**< Name of file where Hessian matrix is stored. \n
If Hessian matrix is trivial, a NULL pointer can be passed. */
const char * const
g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */
const char * const A_file, /**< Name of file where constraint matrix is stored. \n
If QP sequence does not involve constraints, a NULL pointer can be passed. */
const char * const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is
stored. \n If no lower bounds exist, a NULL pointer can be passed. */
const char * const ub_file, /**< Name of file where upper bounds, of neighbouring QP to be solved, is
stored. \n If no upper bounds exist, a NULL pointer can be passed. */
const char * const
lbA_file, /**< Name of file where lower constraints' bounds, of neighbouring QP to be solved, is
stored. \n If no lower constraints' bounds exist, a NULL pointer can be passed. */
const char * const
ubA_file, /**< Name of file where upper constraints' bounds, of neighbouring QP to be solved, is
stored. \n If no upper constraints' bounds exist, a NULL pointer can be passed. */
int_t & nWSR, /**< Input: Maximum number of working set recalculations; \n
Output: Number of performed working set recalculations. */
real_t * const cputime = 0, /**< Input: Maximum CPU time allowed for QP solution. \n
Output: CPU time spent for QP solution (or to perform nWSR iterations). */
const Bounds * const guessedBounds = 0, /**< Optimal working set of bounds for solution (xOpt,yOpt). \n
(If a null pointer is passed, the previous working set of bounds is kept!) */
const Constraints * const guessedConstraints =
0 /**< Optimal working set of constraints for solution (xOpt,yOpt). \n
(If a null pointer is passed, the previous working set of constraints is kept!) */
);
/** Solves an initialised QP sequence (without matrix shift) using
* the online active set strategy.
* By default, QP solution is started from previous solution. If a guess
* for the working set is provided, an initialised homotopy is performed.
*
* Note: This functions just forwards to the corresponding
* QProblem::hotstart member function.
*
* \return SUCCESSFUL_RETURN \n
RET_MAX_NWSR_REACHED \n
RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n
RET_HOTSTART_FAILED \n
RET_SHIFT_DETERMINATION_FAILED \n
RET_STEPDIRECTION_DETERMINATION_FAILED \n
RET_STEPLENGTH_DETERMINATION_FAILED \n
RET_HOMOTOPY_STEP_FAILED \n
RET_HOTSTART_STOPPED_INFEASIBILITY \n
RET_HOTSTART_STOPPED_UNBOUNDEDNESS */
returnValue hotstart(const real_t * const g_new, /**< Gradient of neighbouring QP to be solved. */
const real_t * const lb_new, /**< Lower bounds of neighbouring QP to be solved. \n
If no lower bounds exist, a NULL pointer can be passed. */
const real_t * const ub_new, /**< Upper bounds of neighbouring QP to be solved. \n
If no upper bounds exist, a NULL pointer can be passed. */
const real_t * const lbA_new, /**< Lower constraints' bounds of neighbouring QP to be solved. \n
If no lower constraints' bounds exist, a NULL pointer can be passed. */
const real_t * const ubA_new, /**< Upper constraints' bounds of neighbouring QP to be solved. \n
If no upper constraints' bounds exist, a NULL pointer can be passed. */
int_t & nWSR, /**< Input: Maximum number of working set recalculations; \n
Output: Number of performed working set recalculations. */
real_t * const cputime = 0, /**< Input: Maximum CPU time allowed for QP solution. \n
Output: CPU time spent for QP solution (or to perform nWSR iterations). */
const Bounds * const guessedBounds = 0, /**< Optimal working set of bounds for solution (xOpt,yOpt). \n
(If a null pointer is passed, the previous working set of bounds is kept!) */
const Constraints * const guessedConstraints =
0 /**< Optimal working set of constraints for solution (xOpt,yOpt). \n
(If a null pointer is passed, the previous working set of constraints is kept!) */
);
/** Solves an initialised QP sequence (without matrix shift) using
* the online active set strategy, where QP data is read from files.
* By default, QP solution is started from previous solution. If a guess
* for the working set is provided, an initialised homotopy is performed.
*
* Note: This functions just forwards to the corresponding
* QProblem::hotstart member function.
*
* \return SUCCESSFUL_RETURN \n
RET_MAX_NWSR_REACHED \n
RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n
RET_HOTSTART_FAILED \n
RET_SHIFT_DETERMINATION_FAILED \n
RET_STEPDIRECTION_DETERMINATION_FAILED \n
RET_STEPLENGTH_DETERMINATION_FAILED \n
RET_HOMOTOPY_STEP_FAILED \n
RET_HOTSTART_STOPPED_INFEASIBILITY \n
RET_HOTSTART_STOPPED_UNBOUNDEDNESS \n
RET_UNABLE_TO_READ_FILE \n
RET_INVALID_ARGUMENTS */
returnValue hotstart(
const char * const
g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */
const char * const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is
stored. \n If no lower bounds exist, a NULL pointer can be passed. */
const char * const ub_file, /**< Name of file where upper bounds, of neighbouring QP to be solved, is
stored. \n If no upper bounds exist, a NULL pointer can be passed. */
const char * const
lbA_file, /**< Name of file where lower constraints' bounds, of neighbouring QP to be solved, is
stored. \n If no lower constraints' bounds exist, a NULL pointer can be passed. */
const char * const
ubA_file, /**< Name of file where upper constraints' bounds, of neighbouring QP to be solved, is
stored. \n If no upper constraints' bounds exist, a NULL pointer can be passed. */
int_t & nWSR, /**< Input: Maximum number of working set recalculations; \n
Output: Number of performed working set recalculations. */
real_t * const cputime = 0, /**< Input: Maximum CPU time allowed for QP solution. \n
Output: CPU time spent for QP solution (or to perform nWSR iterations). */
const Bounds * const guessedBounds = 0, /**< Optimal working set of bounds for solution (xOpt,yOpt). \n
(If a null pointer is passed, the previous working set of bounds is kept!) */
const Constraints * const guessedConstraints =
0 /**< Optimal working set of constraints for solution (xOpt,yOpt). \n
(If a null pointer is passed, the previous working set of constraints is kept!) */
);
#ifdef __MATLAB__
/** Sets pointer of Hessian and constraint matrix to zero.
* QUICK HACK FOR MAKING THE MATLAB INTERFACE RUN! TO BE REMOVED!
* \return SUCCESSFUL_RETURN */
returnValue resetMatrixPointers();
#endif
/*
* PROTECTED MEMBER FUNCTIONS
*/
protected:
/** Sets new matrices and calculates their factorisations. If the
* current Hessian is trivial (i.e. HST_ZERO or HST_IDENTITY) but a
* non-trivial one is given, memory for Hessian is allocated and
* it is set to the given one. Afterwards, all QP vectors are
* transformed in order to start from an optimal solution.
* \return SUCCESSFUL_RETURN \n
* RET_MATRIX_FACTORISATION_FAILED \n
* RET_NO_HESSIAN_SPECIFIED */
virtual returnValue setupNewAuxiliaryQP(SymmetricMatrix * H_new, /**< New Hessian matrix. \n
If Hessian matrix is trivial, a NULL pointer can be passed. */
Matrix * A_new, /**< New constraint matrix. \n
If QP sequence does not involve constraints, a NULL pointer can be passed. */
const real_t * lb_new, /**< New lower bounds. \n
If no lower bounds exist, a NULL pointer can be passed. */
const real_t * ub_new, /**< New upper bounds. \n
If no lower bounds exist, a NULL pointer can be passed. */
const real_t * lbA_new, /**< New lower constraints' bounds. \n
If no lower constraints' bounds exist, a NULL pointer can be passed. */
const real_t * ubA_new /**< New lower constraints' bounds. \n
If no lower constraints' bounds exist, a NULL pointer can be passed. */
);
/** Sets new matrices and calculates their factorisations. If the
* current Hessian is trivial (i.e. HST_ZERO or HST_IDENTITY) but a
* non-trivial one is given, memory for Hessian is allocated and
* it is set to the given one. Afterwards, all QP vectors are
* transformed in order to start from an optimal solution.
* \return SUCCESSFUL_RETURN \n
* RET_MATRIX_FACTORISATION_FAILED \n
* RET_NO_HESSIAN_SPECIFIED */
virtual returnValue setupNewAuxiliaryQP(const real_t * const H_new, /**< New Hessian matrix. \n
If Hessian matrix is trivial, a NULL pointer can be passed. */
const real_t * const A_new, /**< New constraint matrix. \n
If QP sequence does not involve constraints, a NULL pointer can be passed. */
const real_t * lb_new, /**< New lower bounds. \n
If no lower bounds exist, a NULL pointer can be passed. */
const real_t * ub_new, /**< New upper bounds. \n
If no lower bounds exist, a NULL pointer can be passed. */
const real_t * lbA_new, /**< New lower constraints' bounds. \n
If no lower constraints' bounds exist, a NULL pointer can be passed. */
const real_t * ubA_new /**< New lower constraints' bounds. \n
If no lower constraints' bounds exist, a NULL pointer can be passed. */
);
/*
* PROTECTED MEMBER VARIABLES
*/
protected:
};
END_NAMESPACE_QPOASES
#include <qpOASES/SQProblem.ipp>
#endif /* QPOASES_SQPROBLEM_HPP */
/*
* end of file
*/
@@ -0,0 +1,51 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/SQProblem.ipp
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*
* Implementation of inlined member functions of the SQProblem class which
* is able to use the newly developed online active set strategy for
* parametric quadratic programming with varying matrices.
*/
/*****************************************************************************
* P U B L I C *
*****************************************************************************/
BEGIN_NAMESPACE_QPOASES
END_NAMESPACE_QPOASES
/*
* end of file
*/
@@ -0,0 +1,487 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2014 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/SQProblemSchur.hpp
* \author Andreas Waechter and Dennis Janka, based on QProblem.hpp by Hans Joachim Ferreau, Andreas
*Potschka, Christian Kirches \version 3.2 \date 2012-2017
*
* Declaration of the SQProblemSchur class which is able to use the newly
* developed online active set strategy for parametric quadratic programming
* with varying matrices and uses a Schur Complement approach to solve
* the linear systems.
*/
#ifndef QPOASES_SQPROBLEMSCHUR_HPP
#define QPOASES_SQPROBLEMSCHUR_HPP
#include <qpOASES/SQProblem.hpp>
#include <qpOASES/SparseSolver.hpp>
BEGIN_NAMESPACE_QPOASES
/**
* \brief Implements the online active set strategy for QPs with varying, sparse matrices.
*
* A class for setting up and solving quadratic programs with varying,
* sparse QP matrices. Here, sparsity is exploited by means of a
* Schur complement approach to solve the linear systems.
*
* \author Andreas Waechter, Dennis Janka
* \version 3.2
* \date 2012-2017
*/
class SQProblemSchur : public SQProblem
{
/* allow SolutionAnalysis class to access private members */
friend class SolutionAnalysis;
/*
* PUBLIC MEMBER FUNCTIONS
*/
public:
/** Default constructor. */
SQProblemSchur();
/** Constructor which takes the QP dimension and Hessian type
* information. If the Hessian is the zero (i.e. HST_ZERO) or the
* identity matrix (i.e. HST_IDENTITY), respectively, no memory
* is allocated for it and a NULL pointer can be passed for it
* to the init() functions. */
SQProblemSchur(int_t _nV, /**< Number of variables. */
int_t _nC, /**< Number of constraints. */
HessianType _hessianType = HST_UNKNOWN, /**< Type of Hessian matrix. */
int_t maxSchurUpdates = 75 /**< Maximal number of Schur updates */
);
/** Copy constructor (deep copy). */
SQProblemSchur(const SQProblemSchur & rhs /**< Rhs object. */
);
/** Destructor. */
virtual ~SQProblemSchur();
/** Assignment operator (deep copy). */
virtual SQProblemSchur & operator=(const SQProblemSchur & rhs /**< Rhs object. */
);
/** Clears all data structures of QProblem except for QP data.
* \return SUCCESSFUL_RETURN \n
RET_RESET_FAILED */
virtual returnValue reset();
/** Resets Schur complement. This sets up the KKT matrix for the
current activities, copies the activities, etc. TODO: Return values */
returnValue resetSchurComplement(BooleanType allowInertiaCorrection);
/** Return the total number of sparse matrix factorizations performed so far. */
inline int_t getNumFactorizations() const;
/*
* PROTECTED MEMBER FUNCTIONS
*/
protected:
/** Frees all allocated memory.
* \return SUCCESSFUL_RETURN */
returnValue clear();
/** Copies all members from given rhs object.
* \return SUCCESSFUL_RETURN */
returnValue copy(const SQProblemSchur & rhs /**< Rhs object. */
);
/** Computes the Cholesky decomposition of the projected Hessian (i.e. R^T*R = Z^T*H*Z).
* For the Schur complement version, this function only returns SUCCESSFUL_RETURN. */
virtual returnValue computeProjectedCholesky();
/** Computes initial Cholesky decomposition of the projected Hessian making
* use of the function setupCholeskyDecomposition() or setupCholeskyDecompositionProjected().
* For the Schur complement version, this function only returns SUCCESSFUL_RETURN. */
virtual returnValue computeInitialCholesky();
/** Initialises TQ factorisation of A (i.e. A*Q = [0 T]) if NO constraint is active.
* For the Schur complement version, this function only returns SUCCESSFUL_RETURN. */
virtual returnValue setupTQfactorisation();
/** This method is overloaded from SQProblem.
* Sets new matrices and calculates their factorisations. If the
* current Hessian is trivial (i.e. HST_ZERO or HST_IDENTITY) but a
* non-trivial one is given, memory for Hessian is allocated and
* it is set to the given one. Afterwards, all QP vectors are
* transformed in order to start from an optimal solution.
* \return SUCCESSFUL_RETURN \n
* RET_MATRIX_FACTORISATION_FAILED \n
* RET_NO_HESSIAN_SPECIFIED */
virtual returnValue setupAuxiliaryQP(SymmetricMatrix * H_new, /**< New Hessian matrix. \n
If Hessian matrix is trivial, a NULL pointer can be passed. */
Matrix * A_new, /**< New constraint matrix. \n
If QP sequence does not involve constraints, a NULL pointer can be passed. */
const real_t * lb_new,
const real_t * ub_new,
const real_t * lbA_new,
const real_t * ubA_new);
/** Setup bounds and constraints data structures according to auxiliaryBounds/Constraints.
* Calls the sparse solver to obtain the factorization for the initial active set.
* \return SUCCESSFUL_RETURN \n
RET_SETUP_WORKINGSET_FAILED \n
RET_INVALID_ARGUMENTS \n
RET_UNKNOWN_BUG */
virtual returnValue setupAuxiliaryWorkingSet(const Bounds * const auxiliaryBounds,
const Constraints * const auxiliaryConstraints,
BooleanType setupAfresh);
/** Adds a constraint to active set.
* \return SUCCESSFUL_RETURN \n
RET_ADDCONSTRAINT_FAILED \n
RET_ADDCONSTRAINT_FAILED_INFEASIBILITY \n
RET_ENSURELI_FAILED */
virtual returnValue addConstraint(int_t number, /**< Number of constraint to be added to active set. */
SubjectToStatus C_status, /**< Status of new active constraint. */
BooleanType updateCholesky, /**< Flag indicating if Cholesky decomposition shall be updated. */
BooleanType ensureLI = BT_TRUE /**< Ensure linear independence by exchange rules by default. */
);
/** Checks if new active constraint to be added is linearly dependent from
* from row of the active constraints matrix.
* \return RET_LINEARLY_DEPENDENT \n
RET_LINEARLY_INDEPENDENT \n
RET_INDEXLIST_CORRUPTED */
virtual returnValue addConstraint_checkLI(
int_t number /**< Number of constraint to be added to active set. */
);
/** Ensures linear independence of constraint matrix when a new constraint is added.
* To this end a bound or constraint is removed simultaneously if necessary.
* \return SUCCESSFUL_RETURN \n
RET_LI_RESOLVED \n
RET_ENSURELI_FAILED \n
RET_ENSURELI_FAILED_TQ \n
RET_ENSURELI_FAILED_NOINDEX \n
RET_REMOVE_FROM_ACTIVESET */
virtual returnValue addConstraint_ensureLI(
int_t number, /**< Number of constraint to be added to active set. */
SubjectToStatus C_status /**< Status of new active bound. */
);
/** Adds a bound to active set.
* \return SUCCESSFUL_RETURN \n
RET_ADDBOUND_FAILED \n
RET_ADDBOUND_FAILED_INFEASIBILITY \n
RET_ENSURELI_FAILED */
virtual returnValue addBound(int_t number, /**< Number of bound to be added to active set. */
SubjectToStatus B_status, /**< Status of new active bound. */
BooleanType updateCholesky, /**< Flag indicating if Cholesky decomposition shall be updated. */
BooleanType ensureLI = BT_TRUE /**< Ensure linear independence by exchange rules by default. */
);
/** Checks if new active bound to be added is linearly dependent from
* from row of the active constraints matrix.
* \return RET_LINEARLY_DEPENDENT \n
RET_LINEARLY_INDEPENDENT */
virtual returnValue addBound_checkLI(int_t number /**< Number of bound to be added to active set. */
);
/** Ensures linear independence of constraint matrix when a new bound is added.
* To this end a bound or constraint is removed simultaneously if necessary.
* \return SUCCESSFUL_RETURN \n
RET_LI_RESOLVED \n
RET_ENSURELI_FAILED \n
RET_ENSURELI_FAILED_TQ \n
RET_ENSURELI_FAILED_NOINDEX \n
RET_REMOVE_FROM_ACTIVESET */
virtual returnValue addBound_ensureLI(int_t number, /**< Number of bound to be added to active set. */
SubjectToStatus B_status /**< Status of new active bound. */
);
/** Removes a constraint from active set.
* \return SUCCESSFUL_RETURN \n
RET_CONSTRAINT_NOT_ACTIVE \n
RET_REMOVECONSTRAINT_FAILED \n
RET_HESSIAN_NOT_SPD */
virtual returnValue removeConstraint(
int_t number, /**< Number of constraint to be removed from active set. */
BooleanType updateCholesky, /**< Flag indicating if Cholesky decomposition shall be updated. */
BooleanType allowFlipping = BT_FALSE, /**< Flag indicating if flipping bounds are allowed. */
BooleanType ensureNZC =
BT_FALSE /**< Flag indicating if non-zero curvature is ensured by exchange rules. */
);
/** Removes a bounds from active set.
* \return SUCCESSFUL_RETURN \n
RET_BOUND_NOT_ACTIVE \n
RET_HESSIAN_NOT_SPD \n
RET_REMOVEBOUND_FAILED */
virtual returnValue removeBound(int_t number, /**< Number of bound to be removed from active set. */
BooleanType updateCholesky, /**< Flag indicating if Cholesky decomposition shall be updated. */
BooleanType allowFlipping = BT_FALSE, /**< Flag indicating if flipping bounds are allowed. */
BooleanType ensureNZC =
BT_FALSE /**< Flag indicating if non-zero curvature is ensured by exchange rules. */
);
/** Solves the system Ta = b or T^Ta = b where T is a reverse upper triangular matrix.
* This must not be called for the Schur complement version. */
virtual returnValue backsolveT(const real_t * const b, /**< Right hand side vector. */
BooleanType transposed, /**< Indicates if the transposed system shall be solved. */
real_t * const a /**< Output: Solution vector */
) const;
/** Solves the system Ra = b or R^Ta = b where R is an upper triangular matrix.
* This must not be called for the Schur complement version. */
virtual returnValue backsolveR(const real_t * const b, /**< Right hand side vector. */
BooleanType transposed, /**< Indicates if the transposed system shall be solved. */
real_t * const a /**< Output: Solution vector */
) const;
/** Solves the system Ra = b or R^Ta = b where R is an upper triangular matrix. \n
* This must not be called for the Schur complement version. */
virtual returnValue backsolveR(const real_t * const b, /**< Right hand side vector. */
BooleanType transposed, /**< Indicates if the transposed system shall be solved. */
BooleanType removingBound, /**< Indicates if function is called from "removeBound()". */
real_t * const a /**< Output: Solution vector */
) const;
/** Determines step direction of the homotopy path.
* \return SUCCESSFUL_RETURN \n
RET_STEPDIRECTION_FAILED_TQ \n
RET_STEPDIRECTION_FAILED_CHOLESKY */
virtual returnValue determineStepDirection(
const real_t * const delta_g, /**< Step direction of gradient vector. */
const real_t * const delta_lbA, /**< Step direction of lower constraints' bounds. */
const real_t * const delta_ubA, /**< Step direction of upper constraints' bounds. */
const real_t * const delta_lb, /**< Step direction of lower bounds. */
const real_t * const delta_ub, /**< Step direction of upper bounds. */
BooleanType Delta_bC_isZero, /**< Indicates if active constraints' bounds are to be shifted. */
BooleanType Delta_bB_isZero, /**< Indicates if active bounds are to be shifted. */
real_t * const delta_xFX, /**< Output: Primal homotopy step direction of fixed variables. */
real_t * const delta_xFR, /**< Output: Primal homotopy step direction of free variables. */
real_t * const
delta_yAC, /**< Output: Dual homotopy step direction of active constraints' multiplier. */
real_t * const delta_yFX /**< Output: Dual homotopy step direction of fixed variables' multiplier. */
);
virtual returnValue determineStepDirection2(
const real_t * const delta_g, /**< Step direction of gradient vector. */
const real_t * const delta_lbA, /**< Step direction of lower constraints' bounds. */
const real_t * const delta_ubA, /**< Step direction of upper constraints' bounds. */
const real_t * const delta_lb, /**< Step direction of lower bounds. */
const real_t * const delta_ub, /**< Step direction of upper bounds. */
BooleanType Delta_bC_isZero, /**< Indicates if active constraints' bounds are to be shifted. */
BooleanType Delta_bB_isZero, /**< Indicates if active bounds are to be shifted. */
real_t * const delta_xFX, /**< Output: Primal homotopy step direction of fixed variables. */
real_t * const delta_xFR, /**< Output: Primal homotopy step direction of free variables. */
real_t * const
delta_yAC, /**< Output: Dual homotopy step direction of active constraints' multiplier. */
real_t * const delta_yFX /**< Output: Dual homotopy step direction of fixed variables' multiplier. */
);
/*
* PRIVATE MEMBER FUNCTION
*/
private:
/** Checks if new active bound to be added is linearly dependent from
* from row of the active constraints matrix. This version computes
* the multipliers in the (full) test.
* \return RET_LINEARLY_DEPENDENT \n
RET_LINEARLY_INDEPENDENT */
returnValue addBound_checkLISchur(int_t number, /**< Number of bound to be added to active set. */
real_t * const xiC, /**< Output: Multipliers in linear independence test for active constraints. */
real_t * const xiX /**< Output: Multipliers in linear independence test for fixed variables. */
);
/** Checks if new active bound to be added is linearly dependent from
* from row of the active constraints matrix. This version computes
* the multipliers in the (full) test.
* \return RET_LINEARLY_DEPENDENT \n
RET_LINEARLY_INDEPENDENT */
returnValue addConstraint_checkLISchur(int_t number, /**< Number of bound to be added to active set. */
real_t * const xiC, /**< Output: Multipliers in linear independence test for active constraints. */
real_t * const xiX /**< Output: Multipliers in linear independence test for fixed variables. */
);
/** Compute product of "M" matrix (additional columns in KKT
matrix) with vector. y = alpha * M * x + beta * y */
returnValue computeMTimes(real_t alpha, const real_t * const x, real_t beta, real_t * const y);
/** Compute product of transpose of "M" matrix (additional columns in KKT
matrix) with vector. y = alpha * M^T * x + beta * y */
returnValue computeMTransTimes(real_t alpha, const real_t * const x, real_t beta, real_t * const y);
/** Add a row/column to the Schur complement. */
returnValue addToSchurComplement(int_t number,
SchurUpdateType update,
int_t numNonzerosM,
const sparse_int_t * M_pos,
const real_t * const M_vals,
int_t numNonzerosN,
const sparse_int_t * Npos,
const real_t * const Nvals,
real_t N_diag);
/** Remove a row/column from the Schur complement. */
returnValue deleteFromSchurComplement(int_t idx, BooleanType allowUndo = BT_FALSE);
/** Undo the last deletion from the Schur complement by moving the nS+1th row/column to position idx. */
returnValue undoDeleteFromSchurComplement(int_t idx);
/** Compute determinant of new nS*nS Schur complement from old factorization */
real_t calcDetSchur(int_t idxDel);
/** Update QR factorization and determinant of Schur complement after a row and column have been added or
* removed */
returnValue updateSchurQR(int_t idxDel);
/** Compute the solution to QRx = rhs and store it in sol */
returnValue backsolveSchurQR(int_t dimS, const real_t * const rhs, int_t dimRhs, real_t * const sol);
/** If negative curvature is discovered in the reduced Hessian, add bounds until all eigenvalues are
* positive */
returnValue correctInertia();
/** If the KKT matrix is declared singular during refactorization, remove linearly dependent constraints
* or add bounds */
returnValue repairSingularWorkingSet();
returnValue stepCalcRhs(int_t nFR,
int_t nFX,
int_t nAC,
int_t * FR_idx,
int_t * FX_idx,
int_t * AC_idx,
real_t & rhs_max,
const real_t * const delta_g,
const real_t * const delta_lbA,
const real_t * const delta_ubA,
const real_t * const delta_lb,
const real_t * const delta_ub,
BooleanType Delta_bC_isZero,
BooleanType Delta_bB_isZero,
real_t * const delta_xFX,
real_t * const delta_xFR,
real_t * const delta_yAC,
real_t * const delta_yFX);
returnValue stepCalcReorder(int_t nFR,
int_t nAC,
int_t * FR_idx,
int_t * AC_idx,
int_t nFRStart,
int_t nACStart,
int_t * FR_idxStart,
int_t * AC_idxStart,
int_t * FR_iSort,
int_t * FR_iSortStart,
int_t * AC_iSort,
int_t * AC_iSortStart,
real_t * rhs);
returnValue stepCalcBacksolveSchur(int_t nFR,
int_t nFX,
int_t nAC,
int_t * FR_idx,
int_t * FX_idx,
int_t * AC_idx,
int_t dim,
real_t * rhs,
real_t * sol);
returnValue stepCalcReorder2(int_t nFR,
int_t nAC,
int_t * FR_idx,
int_t * AC_idx,
int_t nFRStart,
int_t nACStart,
int_t * FR_idxStart,
int_t * AC_idxStart,
int_t * FR_iSort,
int_t * FR_iSortStart,
int_t * AC_iSort,
int_t * AC_iSortStart,
real_t * sol,
real_t * const delta_xFR,
real_t * const delta_yAC);
returnValue stepCalcResid(int_t nFR,
int_t nFX,
int_t nAC,
int_t * FR_idx,
int_t * FX_idx,
int_t * AC_idx,
BooleanType Delta_bC_isZero,
real_t * const delta_xFX,
real_t * const delta_xFR,
real_t * const delta_yAC,
const real_t * const delta_g,
const real_t * const delta_lbA,
const real_t * const delta_ubA,
real_t & rnrm);
returnValue stepCalcDeltayFx(int_t nFR,
int_t nFX,
int_t nAC,
int_t * FX_idx,
const real_t * const delta_g,
real_t * const delta_xFX,
real_t * const delta_xFR,
real_t * const delta_yAC,
real_t * const delta_yFX);
/*
* PROTECTED MEMBER VARIABLES
*/
protected:
SparseSolver * sparseSolver; /**< Interface to the sparse linear solver. */
real_t * S; /**< Schur complement matrix. (This is actually the negative of the Schur complement!) */
int_t nS; /**< Current size of Schur complement matrix. -1 means that the Schur complement has not yet
been initialized. */
int_t nSmax; /**< Maximum size of Schur complement matrix. */
real_t * Q_; /**< QR factorization of S: orthogonal matrix Q */
real_t * R_; /**< QR factorization of S: upper triangular matrix R */
real_t detS; /**< Determinant of Schur complement */
real_t rcondS; /**< Reciprocal of condition number of S (estimate) */
int_t numFactorizations; /**< Total number of factorizations performed */
int_t * schurUpdateIndex; /**< Indices of variables or constraints for each update in Schur complement. */
SchurUpdateType * schurUpdate; /**< Type of update for each update in Schur complement. */
int_t M_physicallength; /**< Allocated size of the M_vals and M_ir arrays. */
real_t * M_vals; /**< Values of the sparse M matrix containing the vectors with the additional rows
defining the Schur complement (length). */
sparse_int_t * M_ir; /**< Row indices (length). */
sparse_int_t * M_jc; /**< Indices in M to first entry of columns (nS+1). */
Indexlist boundsFreeStart; /**< Index list for free bounds when major iteration started. */
Indexlist constraintsActiveStart; /**< Index list for active constraints when major iteration started. */
};
END_NAMESPACE_QPOASES
#include <qpOASES/SQProblemSchur.ipp>
#endif /* QPOASES_QPROBLEMSCHUR_HPP */
/*
* end of file
*/
@@ -0,0 +1,57 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2013 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/SQProblemSchur.ipp
* \author Andreas Waechter, Dennis Janka
* \version 3.2
* \date 2012-2017
*
* Implementation of inlined member functions of the SQProblemSchur class which
* is able to use the newly developed online active set strategy for
* parametric quadratic programming.
*/
BEGIN_NAMESPACE_QPOASES
/*****************************************************************************
* P U B L I C *
*****************************************************************************/
/*
* g e t N u m F a c t o r i z a t i o n s
*/
inline int_t SQProblemSchur::getNumFactorizations( ) const
{
return numFactorizations;
}
END_NAMESPACE_QPOASES
/*
* end of file
*/
@@ -0,0 +1,562 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/SparseSolver.hpp
* \author Andreas Waechter, Dennis Janka
* \version 3.2
* \date 2012-2017
*
* Interfaces to sparse linear solvers that are used in a Schur-complement
* implementation in qpOASES.
*/
#ifndef QPOASES_SPARSESOLVER_HPP
#define QPOASES_SPARSESOLVER_HPP
#include <limits>
#include <sstream>
#include <qpOASES/Utils.hpp>
BEGIN_NAMESPACE_QPOASES
/**
* \brief Base class for linear solvers that are used in a Schur-complement
* implementation in qpOASES.
*
* \author Andreas Waechter, Dennis Janka
* \version 3.2
* \date 2012-2017
*/
class SparseSolver
{
/*
* PUBLIC MEMBER FUNCTIONS
*/
public:
/** Default constructor. */
SparseSolver();
/** Copy constructor (deep copy). */
SparseSolver(const SparseSolver & rhs /**< Rhs object. */
);
/** Destructor. */
virtual ~SparseSolver();
/** Assignment operator (deep copy). */
virtual SparseSolver & operator=(const SparseSolver & rhs /**< Rhs object. */
);
/** Set new matrix data. The matrix is to be provided
in the Harwell-Boeing format. Only the lower
triangular part should be set. */
virtual returnValue setMatrixData(int_t dim, /**< Dimension of the linear system. */
int_t numNonzeros, /**< Number of nonzeros in the matrix. */
const int_t * const airn, /**< Row indices for each matrix entry. */
const int_t * const acjn, /**< Column indices for each matrix entry. */
const real_t * const avals /**< Values for each matrix entry. */
) = 0;
/** Compute factorization of current matrix. This method must be called before solve.*/
virtual returnValue factorize() = 0;
/** Solve linear system with most recently set matrix data. */
virtual returnValue solve(int_t dim, /**< Dimension of the linear system. */
const real_t * const rhs, /**< Values for the right hand side. */
real_t * const sol /**< Solution of the linear system. */
) = 0;
/** Clears all data structures. */
virtual returnValue reset();
/** Return the number of negative eigenvalues. */
virtual int_t getNegativeEigenvalues();
/** Return the rank after a factorization */
virtual int_t getRank();
/** Returns the zero pivots in case the matrix is rank deficient */
virtual returnValue getZeroPivots(int_t *& zeroPivots);
/*
* PROTECTED MEMBER FUNCTIONS
*/
protected:
/** Frees all allocated memory.
* \return SUCCESSFUL_RETURN */
returnValue clear();
/** Copies all members from given rhs object.
* \return SUCCESSFUL_RETURN */
returnValue copy(const SparseSolver & rhs /**< Rhs object. */
);
/*
* PROTECTED MEMBER VARIABLES
*/
protected:
};
#ifdef SOLVER_MA27
/**
* \brief Implementation of the linear solver interface using Harwell's MA27.
*
* \author Andreas Waechter, Dennis Janka
* \version 3.2
* \date 2012-2017
*/
class Ma27SparseSolver : public SparseSolver
{
/*
* PUBLIC MEMBER FUNCTIONS
*/
public:
/** Default constructor. */
Ma27SparseSolver();
/** Copy constructor (deep copy). */
Ma27SparseSolver(const Ma27SparseSolver & rhs /**< Rhs object. */
);
/** Destructor. */
virtual ~Ma27SparseSolver();
/** Assignment operator (deep copy). */
virtual Ma27SparseSolver & operator=(const SparseSolver & rhs /**< Rhs object. */
);
/** Set new matrix data. The matrix is to be provided
in the Harwell-Boeing format. Only the lower
triangular part should be set. */
virtual returnValue setMatrixData(int_t dim, /**< Dimension of the linear system. */
int_t numNonzeros, /**< Number of nonzeros in the matrix. */
const int_t * const airn, /**< Row indices for each matrix entry. */
const int_t * const acjn, /**< Column indices for each matrix entry. */
const real_t * const avals /**< Values for each matrix entry. */
);
/** Compute factorization of current matrix. This method must be called before solve.*/
virtual returnValue factorize();
/** Solve linear system with most recently set matrix data. */
virtual returnValue solve(int_t dim, /**< Dimension of the linear system. */
const real_t * const rhs, /**< Values for the right hand side. */
real_t * const sol /**< Solution of the linear system. */
);
/** Clears all data structures. */
virtual returnValue reset();
/** Return the number of negative eigenvalues. */
virtual int_t getNegativeEigenvalues();
/** Return the rank after a factorization */
virtual int getRank();
/*
* PROTECTED MEMBER FUNCTIONS
*/
protected:
/** Frees all allocated memory.
* \return SUCCESSFUL_RETURN */
returnValue clear();
/** Copies all members from given rhs object.
* \return SUCCESSFUL_RETURN */
returnValue copy(const Ma27SparseSolver & rhs /**< Rhs object. */
);
/*
* PRIVATE MEMBER FUNCTIONS
*/
private:
/*
* PRIVATE MEMBER VARIABLES
*/
private:
fint_t dim; /**< Dimension of the current linear system. */
fint_t numNonzeros; /**< Number of nonzeros in the current linear system. */
fint_t la_ma27; /**< size of a_ma27 (LA in MA27) */
double *
a_ma27; /**< matrix/factor for MA27 (A in MA27). If have_factorization is false, it contains the matrix
entries (and has length numNonzeros), otherwise the factor (and has length la_ma27). */
fint_t * irn_ma27; /**< Row entries of matrix (IRN in MA27) */
fint_t * jcn_ma27; /**< Column entries of matrix (JCN in MA27) */
fint_t icntl_ma27[30]; /**< integer control values (ICNRL in MA27) */
double cntl_ma27[5]; /**< real control values (CNRL in MA27) */
fint_t liw_ma27; /**< length of integer work space (LIW in MA27) */
fint_t * iw_ma27; /**< integer work space (IW in MA27) */
fint_t * ikeep_ma27; /**< IKEEP in MA27 */
fint_t nsteps_ma27; /**< NSTEPS in MA27 */
fint_t maxfrt_ma27; /**< MAXFRT in MA27 */
bool have_factorization; /**< flag indicating whether factorization for current matrix has already been
computed */
fint_t neig; /**< number of negative eigenvalues */
fint_t rank; /**< rank of matrix */
};
#endif /* SOLVER_MA27 */
#ifdef SOLVER_MA57
/**
* \brief Implementation of the linear solver interface using Harwell's MA57.
*
* \author Andreas Waechter, Dennis Janka
* \version 3.2
* \date 2013-2017
*/
class Ma57SparseSolver : public SparseSolver
{
/*
* PUBLIC MEMBER FUNCTIONS
*/
public:
/** Default constructor. */
Ma57SparseSolver();
/** Copy constructor (deep copy). */
Ma57SparseSolver(const Ma57SparseSolver & rhs /**< Rhs object. */
);
/** Destructor. */
virtual ~Ma57SparseSolver();
/** Assignment operator (deep copy). */
virtual Ma57SparseSolver & operator=(const SparseSolver & rhs /**< Rhs object. */
);
/** Set new matrix data. The matrix is to be provided
in the Harwell-Boeing format. Only the lower
triangular part should be set. */
virtual returnValue setMatrixData(int_t dim, /**< Dimension of the linear system. */
int_t numNonzeros, /**< Number of nonzeros in the matrix. */
const int_t * const airn, /**< Row indices for each matrix entry. */
const int_t * const acjn, /**< Column indices for each matrix entry. */
const real_t * const avals /**< Values for each matrix entry. */
);
/** Compute factorization of current matrix. This method must be called before solve.*/
virtual returnValue factorize();
/** Solve linear system with most recently set matrix data. */
virtual returnValue solve(int_t dim, /**< Dimension of the linear system. */
const real_t * const rhs, /**< Values for the right hand side. */
real_t * const sol /**< Solution of the linear system. */
);
/** Clears all data structures. */
virtual returnValue reset();
/** Return the number of negative eigenvalues. */
virtual int_t getNegativeEigenvalues();
/** Return the rank after a factorization */
virtual int_t getRank();
/** Returns the zero pivots in case the matrix is rank deficient */
virtual returnValue getZeroPivots(int_t *& zeroPivots /**< ... */
);
/*
* PROTECTED MEMBER FUNCTIONS
*/
protected:
/** Frees all allocated memory.
* \return SUCCESSFUL_RETURN */
returnValue clear();
/** Copies all members from given rhs object.
* \return SUCCESSFUL_RETURN */
returnValue copy(const Ma57SparseSolver & rhs /**< Rhs object. */
);
/*
* PRIVATE MEMBER FUNCTIONS
*/
private:
/*
* PRIVATE MEMBER VARIABLES
*/
private:
fint_t dim; /**< Dimension of the current linear system. */
fint_t numNonzeros; /**< Number of nonzeros in the current linear system. */
double * a_ma57; /**< matrix for MA57 (A in MA57) */
fint_t * irn_ma57; /**< Row entries of matrix (IRN in MA57) */
fint_t * jcn_ma57; /**< Column entries of matrix (JCN in MA57) */
fint_t icntl_ma57[30]; /**< integer control values (ICNRL in MA57) */
double cntl_ma57[5]; /**< real control values (CNRL in MA57) */
double * fact_ma57; /**< array for storing the factors */
fint_t lfact_ma57; /**< length of fact_ma57 */
fint_t * ifact_ma57; /**< indexing information about the factors */
fint_t lifact_ma57; /**< length of ifact_ma57 */
bool have_factorization; /**< flag indicating whether factorization for current matrix has already been
computed */
fint_t neig; /**< number of negative eigenvalues */
fint_t rank; /**< rank of matrix */
fint_t * pivots; /**< sequence of pivots used in factorization */
};
#endif /* SOLVER_MA57 */
#ifdef SOLVER_MUMPS
/**
* \brief Implementation of the linear solver interface using MUMPS.
*
* \author Andrea Zanelli
* \version 3.2
* \date 2022
*/
class MumpsSparseSolver : public SparseSolver
{
/*
* PUBLIC MEMBER FUNCTIONS
*/
public:
/** Default constructor. */
MumpsSparseSolver();
/** Copy constructor (deep copy). */
MumpsSparseSolver(const MumpsSparseSolver & rhs /**< Rhs object. */
);
/** Destructor. */
virtual ~MumpsSparseSolver();
/** Assignment operator (deep copy). */
virtual MumpsSparseSolver & operator=(const SparseSolver & rhs /**< Rhs object. */
);
/** Set new matrix data. The matrix is to be provided
in the Harwell-Boeing format. Only the lower
triangular part should be set. */
virtual returnValue setMatrixData(int_t dim, /**< Dimension of the linear system. */
int_t numNonzeros, /**< Number of nonzeros in the matrix. */
const int_t * const airn, /**< Row indices for each matrix entry. */
const int_t * const acjn, /**< Column indices for each matrix entry. */
const real_t * const avals /**< Values for each matrix entry. */
);
/** Compute factorization of current matrix. This method must be called before solve.*/
virtual returnValue factorize();
/** Solve linear system with most recently set matrix data. */
virtual returnValue solve(int_t dim, /**< Dimension of the linear system. */
const real_t * const rhs, /**< Values for the right hand side. */
real_t * const sol /**< Solution of the linear system. */
);
/** Clears all data structures. */
virtual returnValue reset();
/** Return the number of negative eigenvalues. */
virtual int_t getNegativeEigenvalues();
/** Return the rank after a factorization */
virtual int_t getRank();
/** Returns the zero pivots in case the matrix is rank deficient */
virtual returnValue getZeroPivots(int_t *& zeroPivots /**< ... */
);
/*
* PROTECTED MEMBER FUNCTIONS
*/
protected:
/** Frees all allocated memory.
* \return SUCCESSFUL_RETURN */
returnValue clear();
/** Copies all members from given rhs object.
* \return SUCCESSFUL_RETURN */
returnValue copy(const MumpsSparseSolver & rhs /**< Rhs object. */
);
/*
* PRIVATE MEMBER FUNCTIONS
*/
private:
/*
* PRIVATE MEMBER VARIABLES
*/
private:
void * mumps_ptr_; /** Primary MUMPS data structure */
int dim; /**< Dimension of the current linear system. */
int numNonzeros; /**< Number of nonzeros in the current linear system. */
double * a_mumps; /**< matrix for MUMPS (A in MUMPS) */
int * irn_mumps; /**< Row entries of matrix (IRN in MUMPS) */
int * jcn_mumps; /**< Column entries of matrix (JCN in MUMPS) */
bool have_factorization; /**< flag indicating whether factorization for current matrix has already been
computed */
int negevals_; /**< number of negative eigenvalues */
int mumps_pivot_order_; /* pivot order*/
bool initialized_;
/** Flag indicating if the matrix has to be refactorized because
* the pivot tolerance has been changed.
*/
bool pivtol_changed_;
/** Flag that is true if we just requested the values of the
* matrix again (SYMSOLVER_CALL_AGAIN) and have to factorize
* again.
*/
bool refactorize_;
///@}
/** @name Solver specific data/options */
///@{
/** Pivot tolerance */
double pivtol_;
/** Maximal pivot tolerance */
double pivtolmax_;
/** Percent increase in memory */
int mem_percent_;
/** Permutation and scaling method in MUMPS */
int mumps_permuting_scaling_;
/** Scaling in MUMPS */
int mumps_scaling_;
/** Threshold in MUMPS to state that a constraint is linearly dependent */
double mumps_dep_tol_;
/** Flag indicating whether the TNLP with identical structure has
* already been solved before.
*/
bool warm_start_same_structure_;
///@}
/** Flag indicating if symbolic factorization has already been called */
bool have_symbolic_factorization_;
};
template <typename T>
inline void ComputeMemIncrease(T & len, ///< current length on input, new length on output
double recommended, ///< recommended size
T min, ///< minimal size that should ensured
const char *
context ///< context from where this function is called - used to setup message for exception
)
{
if (recommended >= std::numeric_limits<T>::max()) {
// increase len to the maximum possible, if that is still an increase
if (len < std::numeric_limits<T>::max()) {
len = std::numeric_limits<T>::max();
} else {
std::stringstream what;
what << "Cannot allocate more than " << std::numeric_limits<T>::max() * sizeof(T) << " bytes for "
<< context << " due to limitation on integer type";
throw std::overflow_error(what.str());
}
} else {
len = std::max(min, (T)recommended);
}
}
#endif /* SOLVER_MUMPS */
#ifdef SOLVER_NONE
/**
* \brief Implementation of a dummy sparse solver. An error is thrown if a factorization is attempted.
*
* \author Dennis Janka
* \version 3.2
* \date 2015-2017
*/
class DummySparseSolver : public SparseSolver
{
/*
* PUBLIC MEMBER FUNCTIONS
*/
public:
/** Set new matrix data. The matrix is to be provided
in the Harwell-Boeing format. Only the lower
triangular part should be set. */
virtual returnValue setMatrixData(int_t dim, /**< Dimension of the linear system. */
int_t numNonzeros, /**< Number of nonzeros in the matrix. */
const int_t * const airn, /**< Row indices for each matrix entry. */
const int_t * const acjn, /**< Column indices for each matrix entry. */
const real_t * const avals /**< Values for each matrix entry. */
);
/** Compute factorization of current matrix. This method must be called before solve.*/
virtual returnValue factorize();
/** Solve linear system with most recently set matrix data. */
virtual returnValue solve(int_t dim, /**< Dimension of the linear system. */
const real_t * const rhs, /**< Values for the right hand side. */
real_t * const sol /**< Solution of the linear system. */
);
};
#endif /* SOLVER_NONE */
END_NAMESPACE_QPOASES
#endif /* QPOASES_SPARSESOLVER_HPP */
/*
* end of file
*/
@@ -0,0 +1,216 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/SubjectTo.hpp
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*
* Declaration of the SubjectTo class designed to manage working sets of
* constraints and bounds within a QProblem.
*/
#ifndef QPOASES_SUBJECTTO_HPP
#define QPOASES_SUBJECTTO_HPP
#include <qpOASES/Indexlist.hpp>
BEGIN_NAMESPACE_QPOASES
/**
* \brief Base class for managing working sets of bounds and constraints.
*
* This class manages working sets of bounds and constraints by storing
* index sets and other status information.
*
* \author Hans Joachim Ferreau
* \version 3.2
* \date 2007-2017
*/
class SubjectTo
{
/*
* PUBLIC MEMBER FUNCTIONS
*/
public:
/** Default constructor. */
SubjectTo();
/** Constructor which takes the number of constraints or bounds. */
SubjectTo(int_t _n /**< Number of constraints or bounds. */
);
/** Copy constructor (deep copy). */
SubjectTo(const SubjectTo & rhs /**< Rhs object. */
);
/** Destructor. */
virtual ~SubjectTo();
/** Assignment operator (deep copy). */
SubjectTo & operator=(const SubjectTo & rhs /**< Rhs object. */
);
/** Initialises object with given number of constraints or bounds.
* \return SUCCESSFUL_RETURN \n
RET_INVALID_ARGUMENTS */
returnValue init(int_t _n = 0 /**< Number of constraints or bounds. */
);
/** Returns number of constraints/bounds with given SubjectTo type.
* \return Number of constraints/bounds with given type. */
inline int_t getNumberOfType(SubjectToType _type /**< Type of (constraints') bound. */
) const;
/** Returns type of (constraints') bound.
* \return Type of (constraints') bound \n
RET_INDEX_OUT_OF_BOUNDS */
inline SubjectToType getType(int_t i /**< Number of (constraints') bound. */
) const;
/** Returns status of (constraints') bound.
* \return Status of (constraints') bound \n
ST_UNDEFINED */
inline SubjectToStatus getStatus(int_t i /**< Number of (constraints') bound. */
) const;
/** Sets type of (constraints') bound.
* \return SUCCESSFUL_RETURN \n
RET_INDEX_OUT_OF_BOUNDS */
inline returnValue setType(int_t i, /**< Number of (constraints') bound. */
SubjectToType value /**< Type of (constraints') bound. */
);
/** Sets status of (constraints') bound.
* \return SUCCESSFUL_RETURN \n
RET_INDEX_OUT_OF_BOUNDS */
inline returnValue setStatus(int_t i, /**< Number of (constraints') bound. */
SubjectToStatus value /**< Status of (constraints') bound. */
);
/** Sets status of lower (constraints') bounds. */
inline void setNoLower(BooleanType _status /**< Status of lower (constraints') bounds. */
);
/** Sets status of upper (constraints') bounds. */
inline void setNoUpper(BooleanType _status /**< Status of upper (constraints') bounds. */
);
/** Returns status of lower (constraints') bounds.
* \return BT_TRUE if there is no lower (constraints') bound on any variable. */
inline BooleanType hasNoLower() const;
/** Returns status of upper bounds.
* \return BT_TRUE if there is no upper (constraints') bound on any variable. */
inline BooleanType hasNoUpper() const;
/** Shifts forward type and status of all constraints/bounds by a given
* offset. This offset has to lie within the range [0,n/2] and has to
* be an integer divisor of the total number of constraints/bounds n.
* Type and status of the first \<offset\> constraints/bounds is thrown away,
* type and status of the last \<offset\> constraints/bounds is doubled,
* e.g. for offset = 2: \n
* shift( {c/b1,c/b2,c/b3,c/b4,c/b5,c/b6} ) = {c/b3,c/b4,c/b5,c/b6,c/b5,c/b6}
* \return SUCCESSFUL_RETURN \n
RET_INDEX_OUT_OF_BOUNDS \n
RET_INVALID_ARGUMENTS \n
RET_SHIFTING_FAILED */
virtual returnValue shift(
int_t offset /**< Shift offset within the range [0,n/2] and integer divisor of n. */
) = 0;
/** Rotates forward type and status of all constraints/bounds by a given
* offset. This offset has to lie within the range [0,n].
* Example for offset = 2: \n
* rotate( {c/b1,c/b2,c/b3,c/b4,c/b5,c/b6} ) = {c/b3,c/b4,c/b5,c/b6,c/b1,c/b2}
* \return SUCCESSFUL_RETURN \n
RET_INDEX_OUT_OF_BOUNDS \n
RET_ROTATING_FAILED */
virtual returnValue rotate(int_t offset /**< Rotation offset within the range [0,n]. */
) = 0;
/*
* PROTECTED MEMBER FUNCTIONS
*/
protected:
/** Frees all allocated memory.
* \return SUCCESSFUL_RETURN */
returnValue clear();
/** Copies all members from given rhs object.
* \return SUCCESSFUL_RETURN */
returnValue copy(const SubjectTo & rhs /**< Rhs object. */
);
/** Adds the index of a new constraint or bound to index set.
* \return SUCCESSFUL_RETURN \n
RET_ADDINDEX_FAILED \n
RET_INVALID_ARGUMENTS */
returnValue addIndex(
Indexlist * const indexlist, /**< Index list to which the new index shall be added. */
int_t newnumber, /**< Number of new constraint or bound. */
SubjectToStatus newstatus /**< Status of new constraint or bound. */
);
/** Removes the index of a constraint or bound from index set.
* \return SUCCESSFUL_RETURN \n
RET_REMOVEINDEX_FAILED \n
RET_INVALID_ARGUMENTS */
returnValue removeIndex(
Indexlist * const indexlist, /**< Index list from which the new index shall be removed. */
int_t removenumber /**< Number of constraint or bound to be removed. */
);
/** Swaps the indices of two constraints or bounds within the index set.
* \return SUCCESSFUL_RETURN \n
RET_SWAPINDEX_FAILED \n
RET_INVALID_ARGUMENTS */
returnValue swapIndex(
Indexlist * const indexlist, /**< Index list in which the indices shold be swapped. */
int_t number1, /**< Number of first constraint or bound. */
int_t number2 /**< Number of second constraint or bound. */
);
/*
* PROTECTED MEMBER VARIABLES
*/
protected:
int_t n; /**< Total number of constraints/bounds. */
SubjectToType * type; /**< Type of constraints/bounds. */
SubjectToStatus * status; /**< Status of constraints/bounds. */
BooleanType noLower; /**< This flag indicates if there is no lower bound on any variable. */
BooleanType noUpper; /**< This flag indicates if there is no upper bound on any variable. */
};
END_NAMESPACE_QPOASES
#include <qpOASES/SubjectTo.ipp>
#endif /* QPOASES_SUBJECTTO_HPP */
/*
* end of file
*/
@@ -0,0 +1,158 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/SubjectTo.ipp
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*
* Implementation of the inlined member functions of the SubjectTo class
* designed to manage working sets of constraints and bounds within a QProblem.
*/
BEGIN_NAMESPACE_QPOASES
/*****************************************************************************
* P U B L I C *
*****************************************************************************/
/*
* g e t N u m b e r O f T y p e
*/
inline int_t SubjectTo::getNumberOfType( SubjectToType _type ) const
{
int_t i;
int_t numberOfType = 0;
if ( type != 0 )
{
for( i=0; i<n; ++i )
if ( type[i] == _type )
++numberOfType;
}
return numberOfType;
}
/*
* g e t T y p e
*/
inline SubjectToType SubjectTo::getType( int_t i ) const
{
if ( ( i >= 0 ) && ( i < n ) )
return type[i];
return ST_UNKNOWN;
}
/*
* g e t S t a t u s
*/
inline SubjectToStatus SubjectTo::getStatus( int_t i ) const
{
if ( ( i >= 0 ) && ( i < n ) )
return status[i];
return ST_UNDEFINED;
}
/*
* s e t T y p e
*/
inline returnValue SubjectTo::setType( int_t i, SubjectToType value )
{
if ( ( i >= 0 ) && ( i < n ) )
{
type[i] = value;
return SUCCESSFUL_RETURN;
}
else
return THROWERROR( RET_INDEX_OUT_OF_BOUNDS );
}
/*
* s e t S t a t u s
*/
inline returnValue SubjectTo::setStatus( int_t i, SubjectToStatus value )
{
if ( ( i >= 0 ) && ( i < n ) )
{
status[i] = value;
return SUCCESSFUL_RETURN;
}
else
return THROWERROR( RET_INDEX_OUT_OF_BOUNDS );
}
/*
* s e t N o L o w e r
*/
inline void SubjectTo::setNoLower( BooleanType _status )
{
noLower = _status;
}
/*
* s e t N o U p p e r
*/
inline void SubjectTo::setNoUpper( BooleanType _status )
{
noUpper = _status;
}
/*
* h a s N o L o w e r
*/
inline BooleanType SubjectTo::hasNoLower( ) const
{
return noLower;
}
/*
* h a s N o U p p p e r
*/
inline BooleanType SubjectTo::hasNoUpper( ) const
{
return noUpper;
}
END_NAMESPACE_QPOASES
/*
* end of file
*/
@@ -0,0 +1,318 @@
/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/qpOASES/Types.hpp
* \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
* \version 3.2
* \date 2007-2017
*
* Declaration of all non-built-in types (except for classes).
*/
#ifndef QPOASES_TYPES_HPP
#define QPOASES_TYPES_HPP
/* If your compiler does not support the snprintf() function,
* uncomment the following line and try to compile again. */
/* #define __NO_SNPRINTF__ */
/* Uncomment the following line for setting the __DSPACE__ flag. */
/* #define __DSPACE__ */
/* Uncomment the following line for setting the __XPCTARGET__ flag. */
/* #define __XPCTARGET__ */
/* Uncomment the following line for setting the __NO_FMATH__ flag. */
/* #define __NO_FMATH__ */
/* Uncomment the following line to enable debug information. */
/* #define __DEBUG__ */
/* Uncomment the following line to enable suppress any kind of console output. */
/* #define __SUPPRESSANYOUTPUT__ */
/** Forces to always include all implicitly fixed bounds and all equality constraints
* into the initial working set when setting up an auxiliary QP. */
#define __ALWAYS_INITIALISE_WITH_ALL_EQUALITIES__
/* Uncomment the following line to activate the use of an alternative Givens
* plane rotation requiring only three multiplications. */
/* #define __USE_THREE_MULTS_GIVENS__ */
/* Uncomment the following line to activate the use of single precision arithmetic. */
/* #define __USE_SINGLE_PRECISION__ */
/* Work-around for Borland BCC 5.5 compiler. */
#ifdef __BORLANDC__
#if __BORLANDC__ < 0x0561
#define __STDC__ 1
#endif
#endif
/* Work-around for Microsoft compilers. */
#ifdef _MSC_VER
#define __NO_SNPRINTF__
#pragma warning(disable : 4061 4100 4250 4514 4996)
#endif
#ifdef __DSPACE__
/** Macro for switching on/off the beginning of the qpOASES namespace definition. */
#define BEGIN_NAMESPACE_QPOASES
/** Macro for switching on/off the end of the qpOASES namespace definition. */
#define END_NAMESPACE_QPOASES
/** Macro for switching on/off the use of the qpOASES namespace. */
#define USING_NAMESPACE_QPOASES
/** Macro for switching on/off references to the qpOASES namespace. */
#define REFER_NAMESPACE_QPOASES ::
#else
/** Macro for switching on/off the beginning of the qpOASES namespace definition. */
#define BEGIN_NAMESPACE_QPOASES namespace qpOASES {
/** Macro for switching on/off the end of the qpOASES namespace definition. */
#define END_NAMESPACE_QPOASES }
/** Macro for switching on/off the use of the qpOASES namespace. */
#define USING_NAMESPACE_QPOASES using namespace qpOASES;
/** Macro for switching on/off references to the qpOASES namespace. */
#define REFER_NAMESPACE_QPOASES qpOASES::
#endif
/* Avoid any printing on embedded platforms. */
#if defined(__DSPACE__) || defined(__XPCTARGET__)
#define __SUPPRESSANYOUTPUT__
#define __NO_SNPRINTF__
#endif
#ifdef __NO_SNPRINTF__
#if (!defined(_MSC_VER)) || defined(__DSPACE__) || defined(__XPCTARGET__)
/* If snprintf is not available, provide an empty implementation... */
int snprintf(char * s, size_t n, const char * format, ...);
#else
/* ... or substitute snprintf by _snprintf for Microsoft compilers. */
#define snprintf _snprintf
#endif
#endif /* __NO_SNPRINTF__ */
/** Macro for accessing the Cholesky factor R. */
#define RR(I, J) R[(I) + nV * (J)]
/** Macro for accessing the orthonormal matrix Q of the QT factorisation. */
#define QQ(I, J) Q[(I) + nV * (J)]
/** Macro for accessing the triangular matrix T of the QT factorisation. */
#define TT(I, J) T[(I)*sizeT + (J)]
/* If neither MA57 nor MA27 nor MUMPS are selected, activate the dummy solver */
#if !defined(SOLVER_MA27) && !defined(SOLVER_MA57) && !defined(SOLVER_MUMPS) && !defined(SOLVER_NONE)
#define SOLVER_NONE
#endif
/**
* Defined integer type for calling BLAS/LAPACK. Should usually be
* "(unsigned) int", currently set to "(unsigned) long" for backwards
* compatibility. This will change in a future release.
*/
typedef long la_int_t;
typedef unsigned long la_uint_t;
BEGIN_NAMESPACE_QPOASES
/** Defines real_t for facilitating switching between double and float. */
#ifdef __USE_SINGLE_PRECISION__
typedef float real_t;
#else
typedef double real_t;
#endif /* __USE_SINGLE_PRECISION__ */
/** Defines int_t for facilitating switching between int and long int. */
#ifdef __USE_LONG_INTEGERS__
typedef long int_t;
typedef unsigned long uint_t;
#else
typedef int int_t;
typedef unsigned int uint_t;
#endif /* __USE_LONG_INTEGERS__ */
/** Defines FORTRAN integer type. Might be platform dependent! */
#ifdef __USE_LONG_FINTS__
typedef long fint_t;
#else
typedef int fint_t;
#endif /* __USE_LONG_FINTS__ */
/**
* Integer type for sparse matrix row/column entries. Make this "int"
* for 32 bit entries, and "long" for 64-bit entries on x86_64 platform.
*
* Most sparse codes still assume 32-bit entries here (HSL, BQPD, ...)
*/
typedef int_t sparse_int_t;
/** Summarises all possible logical values. */
enum BooleanType
{
BT_FALSE, /**< Logical value for "false". */
BT_TRUE /**< Logical value for "true". */
};
/** Summarises all possible print levels. Print levels are used to describe
* the desired amount of output during runtime of qpOASES. */
enum PrintLevel
{
PL_DEBUG_ITER = -2, /**< Full tabular debugging output. */
PL_TABULAR, /**< Normal tabular output. */
PL_NONE, /**< No output. */
PL_LOW, /**< Print error messages only. */
PL_MEDIUM, /**< Print error and warning messages as well as concise info messages. */
PL_HIGH /**< Print all messages with full details. */
};
/** Defines visibility status of a message. */
enum VisibilityStatus
{
VS_HIDDEN, /**< Message not visible. */
VS_VISIBLE /**< Message visible. */
};
/** Summarises all possible states of the (S)QProblem(B) object during the
solution process of a QP sequence. */
enum QProblemStatus
{
QPS_NOTINITIALISED, /**< QProblem object is freshly instantiated or reset. */
QPS_PREPARINGAUXILIARYQP, /**< An auxiliary problem is currently setup, either at the very beginning
* via an initial homotopy or after changing the QP matrices. */
QPS_AUXILIARYQPSOLVED, /**< An auxilary problem was solved, either at the very beginning
* via an initial homotopy or after changing the QP matrices. */
QPS_PERFORMINGHOMOTOPY, /**< A homotopy according to the main idea of the online active
* set strategy is performed. */
QPS_HOMOTOPYQPSOLVED, /**< An intermediate QP along the homotopy path was solved. */
QPS_SOLVED /**< The solution of the actual QP was found. */
};
/** Summarises all possible types of the QP's Hessian matrix. */
enum HessianType
{
HST_ZERO, /**< Hessian is zero matrix (i.e. LP formulation). */
HST_IDENTITY, /**< Hessian is identity matrix. */
HST_POSDEF, /**< Hessian is (strictly) positive definite. */
HST_POSDEF_NULLSPACE, /**< Hessian is positive definite on null space of active bounds/constraints. */
HST_SEMIDEF, /**< Hessian is positive semi-definite. */
HST_INDEF, /**< Hessian is indefinite. */
HST_UNKNOWN /**< Hessian type is unknown. */
};
/** Summarises all possible types of bounds and constraints. */
enum SubjectToType
{
ST_UNBOUNDED, /**< Bound/constraint is unbounded. */
ST_BOUNDED, /**< Bound/constraint is bounded but not fixed. */
ST_EQUALITY, /**< Bound/constraint is fixed (implicit equality bound/constraint). */
ST_DISABLED, /**< Bound/constraint is disabled (i.e. ignored when solving QP). */
ST_UNKNOWN /**< Type of bound/constraint unknown. */
};
/** Summarises all possible states of bounds and constraints. */
enum SubjectToStatus
{
ST_LOWER = -1, /**< Bound/constraint is at its lower bound. */
ST_INACTIVE, /**< Bound/constraint is inactive. */
ST_UPPER, /**< Bound/constraint is at its upper bound. */
ST_INFEASIBLE_LOWER, /**< (to be documented) */
ST_INFEASIBLE_UPPER, /**< (to be documented) */
ST_UNDEFINED /**< Status of bound/constraint undefined. */
};
/** Flag indicating which type of update generated column in Schur complement. */
enum SchurUpdateType
{
SUT_VarFixed, /**< Free variable gets fixed. */
SUT_VarFreed, /**< Fixed variable gets freed. */
SUT_ConAdded, /**< Constraint becomes active. */
SUT_ConRemoved, /**< Constraint becomes inactive. */
SUT_UNDEFINED /**< Type of Schur update is undefined. */
};
/**
* \brief Stores internal information for tabular (debugging) output.
*
* Struct storing internal information for tabular (debugging) output
* when using the (S)QProblem(B) objects.
*
* \author Hans Joachim Ferreau
* \version 3.2
* \date 2013-2017
*/
struct TabularOutput
{
int_t idxAddB; /**< Index of bound that has been added to working set. */
int_t idxRemB; /**< Index of bound that has been removed from working set. */
int_t idxAddC; /**< Index of constraint that has been added to working set. */
int_t idxRemC; /**< Index of constraint that has been removed from working set. */
int_t excAddB; /**< Flag indicating whether a bound has been added to working set to keep a regular
projected Hessian. */
int_t excRemB; /**< Flag indicating whether a bound has been removed from working set to keep a regular
projected Hessian. */
int_t excAddC; /**< Flag indicating whether a constraint has been added to working set to keep a regular
projected Hessian. */
int_t excRemC; /**< Flag indicating whether a constraint has been removed from working set to keep a
regular projected Hessian. */
};
/**
* \brief Struct containing the variable header for mat file.
*
* Struct storing the header of a variable to be stored in
* Matlab's binary format (using the outdated Level 4 variant
* for simplictiy).
*
* Note, this code snippet has been inspired from the document
* "Matlab(R) MAT-file Format, R2013b" by MathWorks
*
* \author Hans Joachim Ferreau
* \version 3.2
* \date 2013-2017
*/
typedef struct
{
long numericFormat; /**< Flag indicating numerical format. */
long nRows; /**< Number of rows. */
long nCols; /**< Number of rows. */
long imaginaryPart; /**< (to be documented) */
long nCharName; /**< Number of character in name. */
} MatMatrixHeader;
END_NAMESPACE_QPOASES
#endif /* QPOASES_TYPES_HPP */
/*
* end of file
*/

Some files were not shown because too many files have changed in this diff Show More