collision_pairs.py 8.02 KB
Newer Older
1 2 3 4 5
#
#  Copyright (c) CNRS
#  Author: Joseph Mirabel
#

Joseph Mirabel's avatar
Joseph Mirabel committed
6 7
from PythonQt import QtGui, Qt
import xml.etree.ElementTree as ET
8

Joseph Mirabel's avatar
Joseph Mirabel committed
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
import re

def _makeCheckBox(active):
    item = QtGui.QCheckBox()
    item.checked = active
    return item

def _makeTableWidgetItem(lbl, checkable, editable):
    item = QtGui.QTableWidgetItem(lbl)
    f = Qt.Qt.ItemIsEnabled | Qt.Qt.ItemIsSelectable
    if editable:
        f = f | Qt.Qt.ItemIsEditable
    if checkable:
        f = f | Qt.Qt.ItemIsUserCheckable
    item.setFlags(f)
    return item

def _bodyNameToUrdfLinkName(n):
    return re.sub("_[0-9]+$", "", n)

class _Pair:
    def __init__(self, l1, l2):
        self.l1 = l1
        self.l2 = l2
        if l1 > l2:
            self.key = (l1, l2)
        else:
            self.key = (l2, l1)
        self.hash = hash(self.key)

    def __eq__(x,y):
        return (x.key == y.key)

    def __hash__(self):
        return self.hash

class CollisionPairs(QtGui.QWidget):
    ACTIVE=0
    LINK_1=1
    LINK_2=2
    REASON=3
    CURRENT_CONFIG=4
    PERCENTAGE=5

    def __init__ (self, parent):
        super(CollisionPairs, self).__init__ (parent)
        self.plugin = parent
        # parent.widgetToRefresh.append(self)
        self.orderedPairs = list()
        self.pairToRow = dict()
        box = QtGui.QVBoxLayout(self)

61 62 63 64 65
        button = QtGui.QPushButton("Toggle between collision and visual robot bodies", self)
        button.checkable = True
        button.connect("clicked(bool)", self.toggleVisual)
        box.addWidget(button)

Joseph Mirabel's avatar
Joseph Mirabel committed
66 67 68 69 70 71 72
        button = QtGui.QPushButton(QtGui.QIcon.fromTheme("view-refresh"), "Refresh list", self)
        button.connect("clicked()", self.refresh)
        box.addWidget(button)

        # Create table
        self.table = QtGui.QTableWidget(0, 6)
        self.table.setHorizontalHeaderLabels(["Active", "Link 1", "Link 2", "Reason", "Current configuration", "% of collision"])
73 74 75 76
        if Qt.qVersion().startswith('4'):
            self.table.horizontalHeader().setResizeMode(QtGui.QHeaderView.Interactive)
        else:
            self.table.horizontalHeader().setSectionResizeMode(QtGui.QHeaderView.Interactive)
Joseph Mirabel's avatar
Joseph Mirabel committed
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
        self.table.selectionBehavior = QtGui.QAbstractItemView.SelectRows
        self.table.connect("currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)", self.currentItemChanged)
        box.addWidget(self.table)

        # "Number of random configuration (log scale)"
        self.sliderRandomCfg = QtGui.QSlider(Qt.Qt.Horizontal, self)
        self.sliderRandomCfg.setRange(20, 60)
        self.sliderRandomCfg.setValue(30)
        box.addWidget(self.sliderRandomCfg)
        button = QtGui.QPushButton("Compute percentage of collision", self)
        button.connect("clicked()", self.computePercentageOfCollision)
        box.addWidget(button)

        button = QtGui.QPushButton("Save to file...", self)
        button.connect("clicked()", self.writeToFile)
        box.addWidget(button)

        obj = self.plugin.main.getFromSlot("getHppIIOPurl")
        if obj is not None:
            obj.connect("configurationValidationStatus(QStringList)", self.currentBodyInCollisions)
        else:
            print("Could not find obj")

    def showEvent(self, event):
        self.plugin.main.connect('configurationValidation()', self.configValidation)

    def hideEvent(self, event):
        self.plugin.main.disconnect('configurationValidation()', self.configValidation)

    def statusChanged(self, row, checked):
        row[self.REASON].setText("User defined")
        self.plugin.client.robot.setAutoCollision(str(row[self.LINK_1].text()), str(row[self.LINK_2].text()), checked)

    def currentItemChanged(self, current, previous):
        if current is not None and ( current.column() == 1 or current.column() == 2):
            self.plugin.main.bodyTree().selectBodyByName(self.robotName + "/" + current.text())

    def configValidation(self):
        collide = self.plugin.client.robot.autocollisionCheck()
116
        for p, c in zip(self.orderedPairs, collide):
Joseph Mirabel's avatar
Joseph Mirabel committed
117 118 119 120 121 122 123
            if c:
                self.pairToRow[p][self.CURRENT_CONFIG].setText("Collision")
            else:
                self.pairToRow[p][self.CURRENT_CONFIG].setText("Free")

    def setCollisionPair(self, r, l1, l2, active, reason):
        pair = _Pair(l1, l2)
124
        if pair in self.pairToRow:
Joseph Mirabel's avatar
Joseph Mirabel committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
            self.pairToRow[pair][self.ACTIVE].checked = active
            self.pairToRow[pair][self.REASON].setText(reason)
            return
        row = (_makeCheckBox (active),
               _makeTableWidgetItem(l1,     True , False),
               _makeTableWidgetItem(l2,     False, False),
               _makeTableWidgetItem(reason, False, True ),
               _makeTableWidgetItem("NA"  , False, False),
               _makeTableWidgetItem("NA"  , False, False))
        self.table.setCellWidget(r, self.ACTIVE, row[self.ACTIVE])
        self.table.setItem(r, self.LINK_1, row[self.LINK_1])
        self.table.setItem(r, self.LINK_2, row[self.LINK_2])
        self.table.setItem(r, self.REASON, row[self.REASON])
        self.table.setItem(r, self.CURRENT_CONFIG, row[self.CURRENT_CONFIG])
        self.table.setItem(r, self.PERCENTAGE, row[self.PERCENTAGE])
        row[self.ACTIVE].connect("toggled(bool)", lambda c: self.statusChanged(row, c))
        self.pairToRow[pair] = row
        self.orderedPairs.append(pair)

    def currentBodyInCollisions(self, bodies):
        self.bodies = bodies

    def computePercentageOfCollision(self):
        from math import pow
        ncfg = int(pow(10, self.sliderRandomCfg.value / 10))
        nbCol = [0] * len(self.pairToRow)
        r = self.plugin.client.robot
152
        for i in range(ncfg):
Joseph Mirabel's avatar
Joseph Mirabel committed
153 154 155
            cfg = r.shootRandomConfig()
            r.setCurrentConfig(cfg)
            collide = r.autocollisionCheck()
156
            for i in range(len(collide)):
Joseph Mirabel's avatar
Joseph Mirabel committed
157 158 159
                if collide[i]:
                    nbCol[i] += 1

160
        for p, n in zip(self.orderedPairs, nbCol):
Joseph Mirabel's avatar
Joseph Mirabel committed
161 162 163 164 165 166 167 168 169 170 171
            self.pairToRow[p][self.PERCENTAGE].setData(Qt.Qt.DisplayRole, n * 100. / ncfg)

    def refresh(self):
        self.pairToRow.clear()
        self.orderedPairs = list()
        import time
        start_time = time.time()
        self.robotName = self.plugin.client.robot.getRobotName()
        inner, outer, active = self.plugin.client.robot.autocollisionPairs()
        self.table.sortingEnabled = False
        self.table.setRowCount(len(inner))
172
        for r, l1, l2, a in zip(range(len(inner)), inner, outer, active):
Joseph Mirabel's avatar
Joseph Mirabel committed
173 174 175 176
            self.setCollisionPair(r, l1, l2, a, "From SRDF")
        self.table.sortingEnabled = True
        print(time.time() - start_time)

177 178 179 180 181
    def toggleVisual(self, visual):
        rn = self.plugin.client.robot.getRobotName()
        for n in self.plugin.gui.gui.getGroupNodeList(rn):
            self.plugin.gui.gui.setBoolProperty(n, "ShowVisual", visual)

Joseph Mirabel's avatar
Joseph Mirabel committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    def writeToFile(self):
        _ = _bodyNameToUrdfLinkName
        filename = QtGui.QFileDialog.getSaveFileName(self, "SRDF file", "", "SRDF files (*.srdf)")
        file = Qt.QFileInfo(filename)
        if file.exists():
            tree = ET.parse(filename)
        else:
            tree = ET.ElementTree(ET.Element("robot", { "name": "name" }))
            tree.getroot().append(ET.Comment("Generated by hpp-gui Python plugin"))

        robot = tree.getroot()
        pairsInFile = dict()
        for dc in robot.findall("disable_collisions"):
            p = _Pair(dc.attrib["link1"], dc.attrib["link2"])
            pairsInFile[p] = dc

198
        for p, row in self.pairToRow.items():
Joseph Mirabel's avatar
Joseph Mirabel committed
199 200 201 202
            if row[self.ACTIVE].checked:
                continue
            reason = str(row[self.REASON].text())
            pp = _Pair(_(p.l1), _(p.l2))
203
            if pp in pairsInFile:
Joseph Mirabel's avatar
Joseph Mirabel committed
204 205 206 207 208 209 210
                dc.attrib["reason"] = reason
            else:
                attrib = dict()
                attrib["link1"]  = pp.l1
                attrib["link2"]  = pp.l2
                attrib["reason"] = reason
                el = ET.Element("disable_collisions", attrib = attrib)
211 212
                if len(robot.getchildren()) > 0:
                    robot.getchildren()[-1].tail = "\n  "
Joseph Mirabel's avatar
Joseph Mirabel committed
213 214 215
                robot.append(el)

        tree.write(filename)