コード例 #1
0
ファイル: GaitGenerator.py プロジェクト: JenLM/Cadence
 def toCadenceData(self):
     cd = CadenceData(name=self.name, configs=self.configs)
     cd.addChannels(self._leftHind.channels)
     cd.addChannels(self._leftFore.channels)
     cd.addChannels(self._rightHind.channels)
     cd.addChannels(self._rightFore.channels)
     return cd
コード例 #2
0
ファイル: plotTest.py プロジェクト: JenLM/Cadence
class PlotTest(object):
    LH = 0.8
    LF = 0.6
    RF = 0.4
    RH = 0.2
    BACKGROUND_COLOR = 'lightslategray'

    def __init__(self, name):
        self.channelLH = None
        self.channelLF = None
        self.channelRF = None
        self.channelRH = None
        self._name     = name
        self._figure   = plt.figure(name, figsize=(8, 3))
        self._ax1      = plt.subplot(111)
        self._cd       = None

        
    def loadData(self, fileName ="GaitGenerator/PH-0_F-50_H-50.cadence"):
        self._cd = CadenceData()
        self._cd.loadFile(fileName)


    def mapValueToColor(self, v):
        return 'yellow' if v else 'blue'
        
    def plotData(self):
        plt.figure(self._name)
        plt.axes(self._ax1)
        channels = self._cd.getChannelsByKind(ChannelsEnum.GAIT_PHASE) # get the four gait phase channels
        for c in channels:
            if   c.target == TargetsEnum.LEFT_HIND:  self.channelLH = c
            elif c.target == TargetsEnum.LEFT_FORE:  self.channelLF = c
            elif c.target == TargetsEnum.RIGHT_FORE: self.channelRF = c
            elif c.target == TargetsEnum.RIGHT_HIND: self.channelRH = c
            else:
                raise Exception, "Unknown Channel Target:  " + str(c.target)

        prevKey   = self.channelLF.keys[0]
        startTime = prevKey.time
        stopTime  = self.channelLF.keys[-1].time

        for key in self.channelRF.keys[1:]:
            self._ax1.plot([prevKey.time, key.time], [PlotTest.LH, PlotTest.LH], linewidth=10, color=self.mapValueToColor(prevKey.value))
            prevKey = key

        rect = self._ax1.patch
        rect.set_facecolor(PlotTest.BACKGROUND_COLOR)

        plt.xlim([startTime, stopTime])
        plt.show()
コード例 #3
0
ファイル: GaitPlot.py プロジェクト: sernst/Cadence
    def loadGait(self, fileName):
        """
        1) Loads the four GAIT_PHASE channels from the specified file
        2) sets _channelStartbTime and _channelStopTime based on the left hind limb channel
        3) sets _plotStart and _plotStopTime to the overall channel times by default
        """
        self._cd = CadenceData()
        self._cd.loadFile(fileName)
        channel_s = self._cd.getChannelsByKind(ChannelsEnum.GAIT_PHASE) # get the four gait phase channels
        for c in channel_s:
            if   c.target == TargetsEnum.LEFT_HIND:  self._channel_LH = c
            elif c.target == TargetsEnum.LEFT_FORE:  self._channel_LF = c
            elif c.target == TargetsEnum.RIGHT_FORE: self._channel_RF = c
            elif c.target == TargetsEnum.RIGHT_HIND: self._channel_RH = c
            else:
                raise Exception("Unknown Channel_ Target:  " + str(c.target))

        # this method presumes that all channels have the same start and stop times
        # hence we use the left hind limb (channel_LH) as representative
        self._channelStartTime = self._channel_LH.keys[ 0].time
        self._channelStopTime  = self._channel_LH.keys[-1].time
        # and use that interval as the default plotting interval
        self.setPlotInterval(self._channelStartTime, self._channelStopTime)

        return True
コード例 #4
0
ファイル: GaitVisualizer.py プロジェクト: JenLM/Cadence
    def __init__(self, *args, **kwargs):
        """Creates a new instance of GaitVisualizer."""

        self._data = CadenceData()

        self._filename = ArgsUtils.get('filename', None, kwargs)
        if self._filename:
            self._data.loadFile(self._filename)
        else:
            data = ArgsUtils.get('data', None, kwargs)
            if isinstance(data, CadenceData):
                self._data = data
            elif data:
                self._data.load(data)
            else:
                self._data = None

        self._group     = None
        self._leftHind  = None
        self._rightHind = None
        self._leftFore  = None
        self._rightFore = None
        self._hips      = None
        self._pecs      = None
コード例 #5
0
ファイル: test_GaitGenerator.py プロジェクト: JenLM/Cadence
print 'INITIALIZING Config file: ' + configFile

#---------------------------------------------------------------------------------------------------
# GET CONFIG FILE
g = GaitGenerator(gaitConfig=configFile)
if g.run():
    print 'SUCCESS: GaitGenerator.run()'
    g.echo()
else:
    print 'FAILED: GaitGenerator.run()'
    sys.exit(1)

if g.saveToFile():
    print 'SUCCESS: GaitGenerator.saveToFile()'
    print 'Saved output as: ' + g.name
else:
    print 'FAILED: GaitGenerator.saveToFile()'
    print 'Unable to save output as: ' + g.name
    sys.exit(1)

cd = CadenceData()
if cd.loadFile(g.dataFilename):
    print 'SUCCESS: CadenceData.loadFile()'
    print 'Loaded from output file: ' + g.dataFilename
else:
    print 'FAILED: CadenceData.loadFile()'
    print 'Unable to load output file: ' + g.dataFilename
    sys.exit(1)

print 'Test complete.'
コード例 #6
0
ファイル: GaitPlot.py プロジェクト: sernst/Cadence
class GaitPlot(object):

#===============================================================================
#                                                                                   C L A S S
    """
    A GaitPlot instance can have multiple individual graphs arranged into a single column, one graph per row. The
    number of rows is determined at construction time, and defaults to 1. Multiple graphs are composed on
    successive rows, addressed numerically by row number (starting at one and increasing downward).  All graphs
    share a common specified width and are scaled to fit within the specified overall height of the GaitPlot figure.

    The GaitPlot class is designed for plotting Cadence GAIT_PHASE channel data, as loaded from a given Cadence
    data file. The duration of the data is stored in the read-only properties channelStartTime and channelStopTime,
    ase determined from the data.  By default all keys within this interval are plotted. A more restricted interval
    can be specified by setPlotInterval.

    The following indicates how to display two graphs within a GaitPlot, with a width of 8 inches and an overall
    height of 6 inches.
        gp = GaitPlot(2, 8, 6)
        gp.loadData(<fileName>)
        gp.setColorMap('rainbow')     # use one of the predefined color maps
        gp.setPlotInterval(0.0, 24.0) # only plot keys within the interval (0.0, 24.0)
        gp.plotGait(1)                # graph the GAIT_PHASE data in the top graph (other graphs will be below)
        gp.clearGraph(1, 'black')     # clear the top row's graph
        gp.plotCurve(1, xs, ys)       # plot a continuous curve into graph 1 from lists of x and y coordinates
        gp.save(<file>)               # save as a .png
        gp.show()                     # launch the display popup
    """
#_______________________________________________________________________________

    def __init__(self, rows=1, width=8, height=4):
        self._cd         = None
        self._channel_LH = None
        self._channel_LF = None
        self._channel_RF = None
        self._channel_RH = None
        self._colorMap   = None
        self._lineColor  = None
        self._background = None
        self._figureSize = None
        self._numberRows = rows
        self._figureSize = (width, height)
        self._figure     = plt.figure(figsize=self._figureSize)

        self._channelStartTime = None
        self._channelStopTime  = None
        self._plotStartTime    = None
        self._plotStopTime     = None

        self.setColorMap('Greys')
        self.setLineColor('sandybrown')

#===============================================================================
#                                                                                   G E T / S E T

#__________________________________________________________________________________________________GS: channelStartTime
    @property
    def channelStartTime(self):
        return self._channelStartTime

#__________________________________________________________________________________________________GS: channelStopTime
    @property
    def channelStopTime(self):
        return self._channelStopTime

#__________________________________________________________________________________________________GS: plotStartTime
    @property
    def plotlStartTime(self):
        return self._plotStartTime

#__________________________________________________________________________________________________GS: plotStopTime
    @property
    def plotStopTime(self):
        return self._plotStopTime

#===============================================================================
#                                                                                     P U B L I C

#_______________________________________________________________________________

    def loadGait(self, fileName):
        """
        1) Loads the four GAIT_PHASE channels from the specified file
        2) sets _channelStartbTime and _channelStopTime based on the left hind limb channel
        3) sets _plotStart and _plotStopTime to the overall channel times by default
        """
        self._cd = CadenceData()
        self._cd.loadFile(fileName)
        channel_s = self._cd.getChannelsByKind(ChannelsEnum.GAIT_PHASE) # get the four gait phase channels
        for c in channel_s:
            if   c.target == TargetsEnum.LEFT_HIND:  self._channel_LH = c
            elif c.target == TargetsEnum.LEFT_FORE:  self._channel_LF = c
            elif c.target == TargetsEnum.RIGHT_FORE: self._channel_RF = c
            elif c.target == TargetsEnum.RIGHT_HIND: self._channel_RH = c
            else:
                raise Exception("Unknown Channel_ Target:  " + str(c.target))

        # this method presumes that all channels have the same start and stop times
        # hence we use the left hind limb (channel_LH) as representative
        self._channelStartTime = self._channel_LH.keys[ 0].time
        self._channelStopTime  = self._channel_LH.keys[-1].time
        # and use that interval as the default plotting interval
        self.setPlotInterval(self._channelStartTime, self._channelStopTime)

        return True
    #_______________________________________________________________________________

    def setPlotInterval(self, startTime, stopTime):
        self._plotStartTime = startTime
        self._plotStopTime  = stopTime

    #_______________________________________________________________________________

    def setColorMap(self, name):
       self._colorMap = plt.get_cmap(name)

#_______________________________________________________________________________

    def setLineColor(self, name):
        self._lineColor = name

#_______________________________________________________________________________

    def setBackground(self, name):
        self._background = name

#_______________________________________________________________________________

    def mapValueToColor(self, v):
        return self._colorMap(v)

#_______________________________________________________________________________

    def plotChannel(self, channel, graph, y, lineWidth=10):
        plt.axes(graph)
        prevKey = channel.keys[0]

        plt.xticks(plt.arange(self._plotStartTime, self._plotStopTime, 1.0))

        for key in channel.keys[1:]:
            if key.time >= self._plotStartTime and key.time <= self._plotStopTime:
                graph.plot([prevKey.time, key.time],
                           [y, y],
                           linewidth=lineWidth,
                           color=self.mapValueToColor(key.value))
            prevKey = key

#_______________________________________________________________________________

    def plotGait(self, graphNumber=1, background='gray', lineWidth=10):
        graph = self._figure.add_subplot(self._numberRows, 1, graphNumber)

        self.setBackground(background)
        rect = graph.patch
        rect.set_facecolor(background)

        y_RH, y_RF, y_LF, y_LH = 0.2, 0.4, 0.6, 0.8

        self.plotChannel(self._channel_LH, graph, y_LH, lineWidth)
        self.plotChannel(self._channel_LF, graph, y_LF, lineWidth)
        self.plotChannel(self._channel_RF, graph, y_RF, lineWidth)
        self.plotChannel(self._channel_RH, graph, y_RH, lineWidth)

        plt.xlim([self._plotStartTime, self._plotStopTime])

        plt.ylim(0, 1)
        positions = (y_RH, y_RF, y_LF, y_LH)
        labels    = ('Right Hind', 'Right Fore', 'Left Fore','Left Hind')
  #      plt.xlim([self._plotStartTime, self._plotStopTime - 1])
        plt.yticks(positions, labels)
    #    plt.xticks(plt.arange(0.0, 24.0, 1.0))
        return True

#_______________________________________________________________________________

    def value(self, channel, time):
        prevKey = channel.keys[0]
        for key in channel.keys[1:]:
            if prevKey.time <= time and time <= key.time:
                return key.value
            prevKey = key
        return channel.keys[0].value

#_______________________________________________________________________________

    def values(self, channel, times):
        values = []

        for t in times:
            values.append(self.value(channel, t))
        return values

#_______________________________________________________________________________

    def plotGait2(self, graphNumber=1, background='gray', lineWidth=10):
        graph = self._figure.add_subplot(self._numberRows, 1, graphNumber)

        self.setBackground(background)
        rect = graph.patch
        rect.set_facecolor(background)

        y_RH, y_RF, y_LF, y_LH = 0.2, 0.4, 0.6, 0.8

        stop  = self._cd.configs.get(GeneralConfigEnum.STOP_TIME)
        start = self._cd.configs.get(GeneralConfigEnum.START_TIME)
        steps = self._cd.configs.get(GeneralConfigEnum.STEPS)
        delta = (stop - start)/steps

        times  = plt.arange(self._plotStartTime, self._plotStopTime, delta)
        valuesRH = self.values(self._channel_RH, times)
        valuesRF = self.values(self._channel_RF, times)
        valuesLF = self.values(self._channel_LF, times)
        valuesLH = self.values(self._channel_LH, times)

        self.setColorMap('RdYlGn')

        for i in range(len(times)):
            time  = times[i]
            lh, lf, rf, rh = valuesLH[i], valuesLF[i], valuesRF[i], valuesRH[i]

            if   lh and lf and rf and rh:                  support = 1.0
            elif (lh and rf and rh) or (lh and lf and rh): support = 0.95
            elif (lh and lf and rf) or (lf and rf and rh): support = 0.85
            elif lh and rh:                                support = 0.75
            elif (lh and rf) or (lf and rh):               support = 0.7
            elif lf and rf:                                support = 0.2
            elif (lh and lf) or (rf and rh):               support = 0.1
            else:                                          support = 0.0
            if support > 0.0:
                plt.axvspan(time - 2.0*delta, time, fc=self.mapValueToColor(support), ec='none')

        self.setColorMap('gray')
        self.plotChannel(self._channel_LH, graph, y_LH, lineWidth)
        self.plotChannel(self._channel_LF, graph, y_LF, lineWidth)
        self.plotChannel(self._channel_RF, graph, y_RF, lineWidth)
        self.plotChannel(self._channel_RH, graph, y_RH, lineWidth)

        plt.xlim([self._plotStartTime, self._plotStopTime - 1])

        plt.ylim(0, 1)
        positions = (y_RH, y_RF, y_LF, y_LH)
        labels    = ('Right Hind', 'Right Fore', 'Left Fore','Left Hind')
        plt.yticks(positions, labels)
        return True

    #_______________________________________________________________________________

    def clearGraph(self, graphNumber=1, background='black'):
        graph = self._figure.add_subplot(self._numberRows, 1, graphNumber)
        rect = graph.patch
        rect.set_facecolor(background)

#_______________________________________________________________________________

    def save(self, fileName, backgroundColor=None):
        """ Specifying backgroundColor overrides the GaitPlot's background color."""
        if backgroundColor == None:
            backgroundColor = self._figure.get_facecolor()
        self._figure.saveFig(fileName, backgroundColor=backgroundColor)

#_______________________________________________________________________________

    def plotCurve(self, xValues, yValues, graphNumber, color='black', lineWidth=1.0):
        graph = self._figure.add_subplot(self._numberRows, 1, graphNumber)
        graph.plot(xValues, yValues, linewidth=lineWidth, color=color)
        graph.xaxis.grid(color='darkgray')
        plt.xlim([self._plotStartTime, self._plotStopTime-1])
       # plt.xticks(xValues)
        return True

#_______________________________________________________________________________

    def show(self):
        plt.show()
        return True

#_______________________________________________________________________________

    def colorNames(self):
        """ These are named colors available in matplotlib"""
        return {
        'aliceblue':'#F0F8FF','antiquewhite':'#FAEBD7','aqua':'#00FFFF','aquamarine':'#7FFFD4','azure':'#F0FFFF',
        'beige':'#F5F5DC','bisque':'#FFE4C4','black':'#000000','blanchedalmond':'#FFEBCD','blue':'#0000FF',
        'blueviolet':'#8A2BE2','brown':'#A52A2A','burlywood':'#DEB887','cadetblue':'#5F9EA0','chartreuse':'#7FFF00',
        'chocolate':'#D2691E','coral':'#FF7F50','cornflowerblue':'#6495ED','cornsilk':'#FFF8DC','crimson':'#DC143C',
        'cyan':'#00FFFF', 'darkblue':'#00008B', 'darkcyan':'#008B8B', 'darkgoldenrod':'#B8860B','darkgray':'#A9A9A9',
        'darkgreen':'#006400', 'darkkhaki':'#BDB76B', 'darkmagenta':'#8B008B','darkolivegreen':'#556B2F',
        'darkorange':'#FF8C00', 'darkorchid':'#9932CC', 'darkred':'#8B0000','darksalmon':'#E9967A',
        'darkseagreen':'#8FBC8F', 'darkslateblue':'#483D8B', 'darkslategray':'#2F4F4F', 'darkturquoise':'#00CED1',
        'darkviolet':'#9400D3', 'deeppink':'#FF1493', 'deepskyblue':'#00BFFF', 'dimgray':'#696969',
        'dodgerblue':'#1E90FF', 'firebrick':'#B22222','floralwhite':'#FFFAF0', 'forestgreen':'#228B22',
        'fuchsia':'#FF00FF', 'gainsboro':'#DCDCDC', 'ghostwhite':'#F8F8FF', 'gold':'#FFD700', 'goldenrod':'#DAA520',
        'gray':'#808080','green':'#008000', 'greenyellow':'#ADFF2F', 'honeydew':'#F0FFF0', 'hotpink':'#FF69B4',
        'indianred':'#CD5C5C', 'indigo':'#4B0082', 'ivory':'#FFFFF0', 'khaki':'#F0E68C', 'lavender':'#E6E6FA',
        'lavenderblush':'#FFF0F5', 'lawngreen':'#7CFC00', 'lemonchiffon':'#FFFACD', 'lightblue':'#ADD8E6',
        'lightcoral':'#F08080', 'lightcyan':'#E0FFFF', 'lightgoldenrodyellow':'#FAFAD2', 'lightgreen':'#90EE90',
        'lightgray':'#D3D3D3', 'lightpink':'#FFB6C1', 'lightsalmon':'#FFA07A', 'lightseagreen':'#20B2AA',
        'lightskyblue':'#87CEFA', 'lightslategray':'#778899', 'lightsteelblue':'#B0C4DE', 'lightyellow':'#FFFFE0',
        'lime':'#00FF00', 'limegreen':'#32CD32', 'linen':'#FAF0E6', 'magenta':'#FF00FF', 'maroon':'#800000',
        'mediumaquamarine':'#66CDAA', 'mediumblue':'#0000CD', 'mediumorchid':'#BA55D3', 'mediumpurple':'#9370DB',
        'mediumseagreen':'#3CB371', 'mediumslateblue':'#7B68EE', 'mediumspringgreen':'#00FA9A',
        'mediumturquoise':'#48D1CC', 'mediumvioletred':'#C71585', 'midnightblue':'#191970', 'mintcream':'#F5FFFA',
        'mistyrose':'#FFE4E1', 'moccasin':'#FFE4B5', 'navajowhite':'#FFDEAD', 'navy':'#000080', 'oldlace':'#FDF5E6',
        'olive':'#808000', 'olivedrab':'#6B8E23', 'orange':'#FFA500', 'orangered':'#FF4500', 'orchid':'#DA70D6',
        'palegoldenrod':'#EEE8AA', 'palegreen':'#98FB98', 'palevioletred':'#AFEEEE', 'papayawhip':'#FFEFD5',
        'peachpuff':'#FFDAB9', 'peru':'#CD853F', 'pink':'#FFC0CB', 'plum':'#DDA0DD', 'powderblue':'#B0E0E6',
        'purple':'#800080', 'red':'#FF0000', 'rosybrown':'#BC8F8F', 'royalblue':'#4169E1', 'saddlebrown':'#8B4513',
        'salmon':'#FA8072', 'sandybrown':'#FAA460', 'seagreen':'#2E8B57', 'seashell':'#FFF5EE', 'sienna':'#A0522D',
        'silver':'#C0C0C0',  'skyblue':'#87CEEB', 'slateblue':'#6A5ACD', 'slategray':'#708090', 'snow':'#FFFAFA',
        'springgreen':'#00FF7F', 'steelblue':'#4682B4', 'tan':'#D2B48C', 'teal':'#008080', 'thistle':'#D8BFD8',
        'tomato':'#FF6347', 'turquoise':'#40E0D0', 'violet':'#EE82EE', 'wheat':'#F5DEB3', 'white':'#FFFFFF',
        'whitesmoke':'#F5F5F5', 'yellow':'#FFFF00', 'yellowgreen':'#9ACD32',
        }

#_______________________________________________________________________________
    def colorMapNames(self):
        """ These are named color maps available in matplotlib"""
        maps = [m for m in plt.cm.datad if not m.endswith("_r")]
        return maps
コード例 #7
0
ファイル: plotTest.py プロジェクト: JenLM/Cadence
 def loadData(self, fileName ="GaitGenerator/PH-0_F-50_H-50.cadence"):
     self._cd = CadenceData()
     self._cd.loadFile(fileName)
コード例 #8
0
ファイル: GaitVisualizer.py プロジェクト: JenLM/Cadence
class GaitVisualizer(object):
    """A class for..."""

#===================================================================================================
#                                                                                       C L A S S

#___________________________________________________________________________________________________ __init__
    def __init__(self, *args, **kwargs):
        """Creates a new instance of GaitVisualizer."""

        self._data = CadenceData()

        self._filename = ArgsUtils.get('filename', None, kwargs)
        if self._filename:
            self._data.loadFile(self._filename)
        else:
            data = ArgsUtils.get('data', None, kwargs)
            if isinstance(data, CadenceData):
                self._data = data
            elif data:
                self._data.load(data)
            else:
                self._data = None

        self._group     = None
        self._leftHind  = None
        self._rightHind = None
        self._leftFore  = None
        self._rightFore = None
        self._hips      = None
        self._pecs      = None

#===================================================================================================
#                                                                                   G E T / S E T

#___________________________________________________________________________________________________ GS: filename
    @property
    def filename(self):
        return self._filename

#___________________________________________________________________________________________________ GS: data
    @property
    def data(self):
        return self._data

#___________________________________________________________________________________________________ GS: group
    @property
    def group(self):
        return self._group

#___________________________________________________________________________________________________ GS: leftHind
    @property
    def leftHind(self):
        return self._leftHind if not self.group else (self.group + u'|' + self._leftHind)

#___________________________________________________________________________________________________ GS: rightHind
    @property
    def rightHind(self):
        return self._rightHind if not self.group else (self.group + u'|' + self._rightHind)

#___________________________________________________________________________________________________ GS: leftFore
    @property
    def leftFore(self):
        return self._leftFore if not self.group else (self.group + u'|' + self._leftFore)

#___________________________________________________________________________________________________ GS: rightFore
    @property
    def rightFore(self):
        return self._rightFore if not self.group else (self.group + u'|' + self._rightFore)

#___________________________________________________________________________________________________ GS: hips
    @property
    def hips(self):
        return self._hips if not self.group else (self.group + u'|' + self._hips)

#___________________________________________________________________________________________________ GS: pecs
    @property
    def pecs(self):
        return self._pecs if not self.group else (self.group + u'|' + self._pecs)

#===================================================================================================
#                                                                                     P U B L I C

#___________________________________________________________________________________________________ buildScene
    def buildScene(self):
        """Doc..."""

        groupItems = []
        hinds      = []
        fores      = []

        for c in self._data.getChannelsByKind(ChannelsEnum.POSITION):
            isHind = c.target in [TargetsEnum.LEFT_HIND, TargetsEnum.RIGHT_HIND]
            radius = 20 if isHind else 15
            res    = cmds.polySphere(radius=radius, name=c.target)
            groupItems.append(res[0])
            if isHind:
                hinds.append(res[0])
            else:
                fores.append(res[0])

            if c.target == TargetsEnum.LEFT_HIND:
                self._leftHind = res[0]
            elif c.target == TargetsEnum.RIGHT_HIND:
                self._rightHind = res[0]
            elif c.target == TargetsEnum.RIGHT_FORE:
                self._rightFore = res[0]
            elif c.target == TargetsEnum.LEFT_FORE:
                self._leftFore = res[0]

            for k in c.keys:
                frames = [
                    ['translateX', k.value.x, k.inTangentMaya[0], k.outTangentMaya[0]],
                    ['translateY', k.value.y, k.inTangentMaya[1], k.outTangentMaya[1]],
                    ['translateZ', k.value.z, k.inTangentMaya[2], k.outTangentMaya[2]]
                ]
                for f in frames:
                    cmds.setKeyframe(
                        res[0],
                        attribute=f[0],
                        time=k.time,
                        value=f[1],
                        inTangentType=f[2],
                        outTangentType=f[3]
                    )

                if k.event == 'land':
                    printResult = cmds.polyCylinder(
                        name=c.target + '_print1',
                        radius=radius,
                        height=(1.0 if isHind else 5.0)
                    )
                    cmds.move(k.value.x, k.value.y, k.value.z, printResult[0])
                    groupItems.append(printResult[0])

        cfg = self._data.configs
        name = 'cyc' + str(int(cfg.get(GaitConfigEnum.CYCLES))) + \
               '_ph' + str(int(cfg.get(GaitConfigEnum.PHASE))) + \
               '_gad' + str(int(cfg.get(SkeletonConfigEnum.FORE_OFFSET).z)) + \
               '_step' + str(int(cfg.get(SkeletonConfigEnum.STRIDE_LENGTH)))

        cube        = cmds.polyCube(name='pelvic_reference', width=20, height=20, depth=20)
        self._hips  = cube[0]
        groupItems.append(cube[0])
        cmds.move(0, 100, 0, cube[0])

        backLength = self._data.configs.get(SkeletonConfigEnum.FORE_OFFSET).z - \
                     self._data.configs.get(SkeletonConfigEnum.HIND_OFFSET).z

        cube2 = cmds.polyCube(name='pectoral_comparator', width=15, height=15, depth=15)
        cmds.move(0, 115, backLength, cube2[0])
        cmds.parent(cube2[0], cube[0], absolute=True)

        cmds.expression(
            string="%s.translateZ = 0.5*abs(%s.translateZ - %s.translateZ) + min(%s.translateZ, %s.translateZ)" %
            (cube[0], hinds[0], hinds[1], hinds[0], hinds[1])
        )

        cube = cmds.polyCube(name='pectoral_reference', width=15, height=15, depth=15)
        self._pecs = cube[0]
        groupItems.append(cube[0])
        cmds.move(0, 100, 0, cube[0])
        cmds.expression(
            string="%s.translateZ = 0.5*abs(%s.translateZ - %s.translateZ) + min(%s.translateZ, %s.translateZ)" %
            (cube[0], fores[0], fores[1], fores[0], fores[1])
        )

        self._group = cmds.group(*groupItems, world=True, name=name)

        cfg = self._data.configs
        info = 'Gait Phase: ' + \
                str(cfg.get(GaitConfigEnum.PHASE)) + \
                '\nGleno-Acetabular Distance (GAD): ' + \
                str(cfg.get(SkeletonConfigEnum.FORE_OFFSET).z) + \
                '\nStep Length: ' + \
                str(cfg.get(SkeletonConfigEnum.STRIDE_LENGTH)) + \
                '\nHind Duty Factor: ' + \
                str(cfg.get(GaitConfigEnum.DUTY_FACTOR_HIND)) + \
                '\nFore Duty Factor: ' + \
                str(cfg.get(GaitConfigEnum.DUTY_FACTOR_FORE)) + \
                '\nCycles: ' + \
                str(cfg.get(GaitConfigEnum.CYCLES))

        cmds.select(self._group)
        if not cmds.attributeQuery('notes', node=self._group, exists=True):
            cmds.addAttr(longName='notes', dataType='string')
            cmds.setAttr(self._group + '.notes', info, type='string')

        self.createShaders()
        self.createRenderEnvironment()

        minTime = min(0, int(cmds.playbackOptions(query=True, minTime=True)))

        deltaTime = cfg.get(GeneralConfigEnum.STOP_TIME) - cfg.get(GeneralConfigEnum.START_TIME)
        maxTime = max(
            int(float(cfg.get(GaitConfigEnum.CYCLES))*float(deltaTime)),
            int(cmds.playbackOptions(query=True, maxTime=True))
        )

        cmds.playbackOptions(
            minTime=minTime, animationStartTime=minTime, maxTime= maxTime, animationEndTime=maxTime
        )

        cmds.currentTime(0, update=True)

        cmds.select(self._group)

#===================================================================================================
#                                                                               P R O T E C T E D

#___________________________________________________________________________________________________ createShaders
    def createShaders(self):
        shader, shaderEngine = self.createShader('HindPrint_Blinn')
        cmds.setAttr(shader + '.color', 0.618, 0.551421, 0.368328, type='double3')
        cmds.select(
            cmds.ls(self.group + '|left_hind_*', objectsOnly=True, exactType='transform', long=True)
        )
        cmds.sets(forceElement=shaderEngine)

        cmds.select(
            cmds.ls(self.group + '|right_hind_*', objectsOnly=True, exactType='transform', long=True)
        )
        cmds.sets(forceElement=shaderEngine)

        shader, shaderEngine = self.createShader('ForePrint_Blinn')
        cmds.setAttr(shader + '.color', 0.309, 0.8618, 1.0, type='double3')
        cmds.select(
            cmds.ls(self.group + '|left_fore_*', objectsOnly=True, exactType='transform', long=True)
        )
        cmds.sets(forceElement=shaderEngine)

        cmds.select(
            cmds.ls(self.group + '|right_fore_*', objectsOnly=True, exactType='transform', long=True)
        )
        cmds.sets(forceElement=shaderEngine)

        shader, shaderEngine = self.createShader('HindFoot_Blinn')
        cmds.setAttr(shader + '.color', 0.792, 0.383566, 0.338184, type='double3')
        cmds.select([self.leftHind, self.rightHind])
        cmds.sets(forceElement=shaderEngine)

        shader, shaderEngine = self.createShader('ForeFoot_Blinn')
        cmds.setAttr(shader + '.color', 0.287, 0.762333, 1.0, type='double3')
        cmds.select([self.leftFore, self.rightFore])
        cmds.sets(forceElement=shaderEngine)

        shader, shaderEngine = self.createShader('Hips_Blinn')
        cmds.setAttr(shader + '.color', 1.0, 0.376, 0.376, type='double3')
        cmds.select([self.hips])
        cmds.sets(forceElement=shaderEngine)

        shader, shaderEngine = self.createShader('Pecs_Blinn')
        cmds.setAttr(shader + '.color', 0.629483, 1.0, 0.483, type='double3')
        cmds.select([self.pecs])
        cmds.sets(forceElement=shaderEngine)

#___________________________________________________________________________________________________ createShader
    def createShader(self, shaderName, shaderType ='blinn'):
        shaderEngine = None
        if not cmds.objExists(shaderName):
            shader       = cmds.shadingNode(shaderType, asShader=True)
            shader       = cmds.rename(shader, shaderName)
            shaderEngine = cmds.sets(renderable=True, empty=True, noSurfaceShader=True, name=shader + '_SG')
            cmds.connectAttr(shader + '.outColor', shaderEngine + '.surfaceShader')
        else:
            shader  = shaderName
            engines = cmds.listConnections(shader + '.outColor')
            if engines:
                shaderEngine = engines[0]

        return shader, shaderEngine

    def createRenderEnvironment(self):
        lightName = 'scenic_light1'
        if not cmds.objExists(lightName):
            lightName = cmds.directionalLight(name=lightName, intensity=0.5)
            cmds.move(0, 2500, 0, lightName)
            cmds.rotate('-45deg', '-45deg', 0, lightName)

        lightName = 'scenic_light2'
        if not cmds.objExists(lightName):
            lightName = cmds.directionalLight(name=lightName, intensity=0.5)
            cmds.move(0, 2500, 0, lightName)
            cmds.rotate('-45deg', '135deg', 0, lightName)

        floorName = 'floor'
        if not cmds.objExists(floorName):
            floorName = cmds.polyPlane(width=10000, height=10000, name=floorName)[0]
        shader, shaderEngine = self.createShader('Whiteout_Surface', 'surfaceShader')
        cmds.setAttr(shader + '.outColor', 1.0, 1.0, 1.0, type='double3')
        cmds.select([floorName])
        cmds.sets(forceElement=shaderEngine)

#===================================================================================================
#                                                                               I N T R I N S I C

#___________________________________________________________________________________________________ __repr__
    def __repr__(self):
        return self.__str__()

#___________________________________________________________________________________________________ __unicode__
    def __unicode__(self):
        return unicode(self.__str__())

#___________________________________________________________________________________________________ __str__
    def __str__(self):
        return '<%s>' % self.__class__.__name__
コード例 #9
0
ファイル: test_cadenceDataLoad.py プロジェクト: JenLM/Cadence
import sys

from cadence.config.enum.GeneralConfigEnum import GeneralConfigEnum
from cadence.shared.io.CadenceData import CadenceData

filename = 'GaitGenerator/PH-20_F-70_H-70.cadence'

cd = CadenceData()
if cd.loadFile(filename):
    print 'SUCCESS: CadenceData.loadFile()'
    print 'Loaded from output file: ' + filename
else:
    print 'FAILED: CadenceData.loadFile()'
    print 'Unable to load output file: ' + filename
    sys.exit(1)

print cd.configs
if cd.configs:
    print 'SUCCESS: Configs available'
    print cd.configs.toDict()

print '\n',100*'-'
print 'CONFIGS TESTS:'
print 'TEST [GeneralConfigEnum.STEPS]:', cd.configs.get(GeneralConfigEnum.STEPS)
print 'TEST [GeneralConfigEnum.START_TIME]:', cd.configs.get(GeneralConfigEnum.START_TIME)

print '\n',100*'-'
print 'CHANNEL ACCESS TESTS:'
print 'TEST [getChannelByName()]:', cd.getChannelByName(cd.channels[0].name)
print 'TEST [getChannelsByKind()]:', cd.getChannelsByKind(cd.channels[0].kind)
print 'TEST [getChannelsByTarget()]:', cd.getChannelsByTarget(cd.channels[0].target)