promo.morph_utils.plot_morphed_data API documentation

# promo.morph_utils.plot_morphed_data

Created on Sep 18, 2013

@author: timmahrt

View Source

      1"""
      2Created on Sep 18, 2013
      3
      4@author: timmahrt
      5"""
      6
      7import math
      8
      9try:
     10    import matplotlib.pyplot as plt
     11    import matplotlib.cm as cm
     12except ImportError:
     13    hasMatplotlib = False
     14else:
     15    hasMatplotlib = True
     16
     17
     18def _matplotlibCheck():
     19    if not hasMatplotlib:
     20        raise ImportError(
     21            "Matplotlib required to generate plots. "
     22            "Install matplotlib or disable plotting"
     23        )
     24
     25
     26def plotSinglePitchTrack(fromTuple, fnFullPath):
     27    _matplotlibCheck()
     28
     29    fig, (ax0) = plt.subplots(nrows=1)
     30
     31    # Old data
     32    plot1 = ax0.plot(
     33        fromTuple,
     34        color="red",
     35        linewidth=2,
     36    )
     37
     38    plt.ylabel("Pitch (Hz)")
     39    plt.xlabel("Sample number")
     40
     41    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0)
     42    #     plt.legend([plot1, plot2, plot3], ["From", "To", "Merged line"])
     43
     44    plt.savefig(fnFullPath, dpi=300, bbox_inches="tight")
     45    plt.close(fig)
     46
     47
     48def plotTwoPitchTracks(fromTuple, toTuple, fnFullPath):
     49    _matplotlibCheck()
     50
     51    fig, (ax0, ax1) = plt.subplots(nrows=2)
     52
     53    # Old data
     54    plot1 = ax0.plot(
     55        fromTuple,
     56        color="red",
     57        linewidth=2,
     58        # label="From"
     59    )
     60    ax0.set_title("Mary is going to the mall (statement)")
     61
     62    plot2 = ax1.plot(
     63        toTuple,
     64        color="red",
     65        linewidth=2,
     66        # label="From"
     67    )
     68
     69    ax1.set_title("Mary is going to the mall (question)")
     70
     71    plt.ylabel("Pitch (Hz)")
     72    plt.xlabel("Sample number")
     73
     74    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0)
     75    #     plt.legend([plot1, plot2, plot3], ["From", "To", "Merged line"])
     76
     77    plt.savefig(fnFullPath, dpi=300, bbox_inches="tight")
     78    plt.close(fig)
     79
     80
     81def plotF0(fromTuple, toTuple, mergeTupleList, fnFullPath):
     82    """
     83    Plots the original data in a graph above the plot of the dtw'ed data
     84    """
     85    _matplotlibCheck()
     86
     87    fig, (ax0) = plt.subplots(nrows=1)
     88
     89    # Old data
     90    plot1 = ax0.plot(fromTuple[0], fromTuple[1], color="red", linewidth=2, label="From")
     91    plot2 = ax0.plot(toTuple[0], toTuple[1], color="blue", linewidth=2, label="To")
     92    ax0.set_title("Plot of F0 Morph")
     93    plt.ylabel("Pitch (hz)")
     94    plt.xlabel("Time (s)")
     95
     96    # Merge data
     97    colorValue = 0
     98    colorStep = 255.0 / len(mergeTupleList)
     99    for timeList, valueList in mergeTupleList:
    100        colorValue += colorStep
    101        hexValue = "#%02x0000" % int(255 - colorValue)
    102        if int(colorValue) == 255:
    103            ax0.plot(
    104                timeList,
    105                valueList,
    106                color=hexValue,
    107                linewidth=1,
    108                label="Merged line, final iteration",
    109            )
    110        else:
    111            ax0.plot(timeList, valueList, color=hexValue, linewidth=1)
    112
    113    plt.legend(loc=1, borderaxespad=0.0)
    114    #     plt.legend([plot1, plot2, plot3], ["From", "To", "Merged line"])
    115
    116    plt.savefig(fnFullPath, dpi=300, bbox_inches="tight")
    117    plt.close(fig)
    118
    119
    120def plotIntensity(fromDataList, toDataList, mergeTupleList, controlPoints, fnFullPath):
    121    def mag2DB(valueList):
    122        stepSize = 500
    123
    124        returnList = []
    125        for i in range(int(math.ceil(len(valueList) / float(stepSize)))):
    126            subList = valueList[i * stepSize : (i + 1) * stepSize]
    127            value = math.sqrt(sum([val ** 2 for val in subList]))
    128
    129            returnList.append(20.0 * math.log10(value))
    130
    131        return returnList
    132
    133    _matplotlibCheck()
    134
    135    fromDataList = mag2DB(fromDataList)
    136    toDataList = mag2DB(toDataList)
    137
    138    print(max(fromDataList))
    139    print(max(toDataList))
    140
    141    fig, ax0 = plt.subplots(nrows=1)
    142    #     fig, (ax0, ax1, ax2) = plt.subplots(nrows=3)
    143
    144    # Old data
    145    plot1 = ax0.plot(fromDataList, color="red", linewidth=2, label="From")
    146    #     plot1.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    147
    148    plot2 = ax0.plot(toDataList, color="blue", linewidth=2, label="To")
    149    #     plot2.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    150
    151    ax0.set_title("Plot of Intensity Morph")
    152    plt.ylabel("RMS intensity (db)")
    153    plt.xlabel("Time (s)")
    154
    155    # Merge data
    156
    157    colorValue = 0
    158    colorStep = 255.0 / len(mergeTupleList)
    159    for valueList in mergeTupleList:
    160
    161        valueList = mag2DB(valueList)
    162
    163        print(max(valueList))
    164
    165        colorValue += colorStep
    166        hexValue = "#%02x0000" % int(255 - colorValue)
    167        xValues = [i for i in range(len(valueList))]
    168        if colorValue == 255.0:
    169            plot3 = ax0.plot(
    170                xValues, valueList, color=hexValue, linewidth=1, label="Merged line"
    171            )
    172        else:
    173            plot3 = ax0.plot(xValues, valueList, color=hexValue, linewidth=1)
    174
    175    controlPoints = mag2DB(controlPoints)
    176    xValues = [i for i in range(len(controlPoints))]
    177    ax0.scatter(xValues, controlPoints, color="pink", label="Control points")
    178
    179    plt.legend(
    180        loc=1,
    181        # bbox_to_anchor=(1.05, 1), loc=2,
    182        borderaxespad=0.0,
    183    )
    184
    185    plt.savefig(fnFullPath, dpi=300, bbox_inches="tight")
    186    plt.close(fig)
    187
    188
    189def plotDuration(
    190    fromDurationList, toDurationList, resultDataList, labelList, fnFullPath
    191):
    192
    193    _matplotlibCheck()
    194
    195    dataList = (
    196        [
    197            fromDurationList,
    198        ]
    199        + resultDataList
    200        + [
    201            toDurationList,
    202        ]
    203    )
    204
    205    # Sanity check
    206    for subList in dataList:
    207        assert len(subList) == len(fromDurationList)
    208
    209    # Constants
    210    colorTuple = ["red", "yellow", "blue"]
    211    width = 0.2
    212    n = len(dataList)
    213    iterN = range(n)
    214
    215    # Pre-plotting work
    216    fig, ax0 = plt.subplots(nrows=1)
    217
    218    # Labels
    219    ax0.set_title("Plot of Duration Morph")
    220    plt.ylabel("Duration (s)")
    221    plt.xlabel("Iterations")
    222    plt.title("Duration morph")
    223
    224    # Draw x ticks (iteration numbers)
    225    xLabelList = []
    226    for i in range(len(resultDataList)):
    227        xLabelList.append(str(i + 1))  # 1 based
    228
    229    xLabelList = (
    230        [
    231            "From",
    232        ]
    233        + xLabelList
    234        + [
    235            "To",
    236        ]
    237    )
    238    iterN2 = [val + width / 2.0 for val in iterN]
    239    plt.xticks(iterN2, xLabelList)
    240
    241    # Plot the data
    242    transposedList = zip(*dataList)
    243    bottom = [0 for i in iterN]
    244    for i, row in enumerate(transposedList):
    245
    246        # Horizontal line that sits on the tallest column
    247        ax0.axhline(bottom[0], color="black")
    248
    249        # Word label that appears after the final column
    250        bottomAppend = max(row)
    251        ax0.text(n - 1.0 + 0.5, (bottom[0] + (bottomAppend / 3.0)), labelList[i])
    252
    253        # The column data
    254        ax0.bar(
    255            x=iterN,
    256            height=row,
    257            bottom=bottom,
    258            width=width,
    259            alpha=0.6,
    260            color=colorTuple[i % 3],
    261        )
    262
    263        # Update the start positions for the next iteration
    264
    265        bottom = [origBottom + bottomAppend for origBottom in bottom]
    266
    267    # Draw a final horizontal line over the highest column
    268    ax0.axhline(bottom[0], color="black")
    269
    270    # Save and cleanup
    271    plt.savefig(fnFullPath, dpi=300, bbox_inches="tight")
    272    plt.close(fig)

def plotSinglePitchTrack(fromTuple, fnFullPath): View Source

    27def plotSinglePitchTrack(fromTuple, fnFullPath):
    28    _matplotlibCheck()
    29
    30    fig, (ax0) = plt.subplots(nrows=1)
    31
    32    # Old data
    33    plot1 = ax0.plot(
    34        fromTuple,
    35        color="red",
    36        linewidth=2,
    37    )
    38
    39    plt.ylabel("Pitch (Hz)")
    40    plt.xlabel("Sample number")
    41
    42    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0)
    43    #     plt.legend([plot1, plot2, plot3], ["From", "To", "Merged line"])
    44
    45    plt.savefig(fnFullPath, dpi=300, bbox_inches="tight")
    46    plt.close(fig)

def plotTwoPitchTracks(fromTuple, toTuple, fnFullPath): View Source

    49def plotTwoPitchTracks(fromTuple, toTuple, fnFullPath):
    50    _matplotlibCheck()
    51
    52    fig, (ax0, ax1) = plt.subplots(nrows=2)
    53
    54    # Old data
    55    plot1 = ax0.plot(
    56        fromTuple,
    57        color="red",
    58        linewidth=2,
    59        # label="From"
    60    )
    61    ax0.set_title("Mary is going to the mall (statement)")
    62
    63    plot2 = ax1.plot(
    64        toTuple,
    65        color="red",
    66        linewidth=2,
    67        # label="From"
    68    )
    69
    70    ax1.set_title("Mary is going to the mall (question)")
    71
    72    plt.ylabel("Pitch (Hz)")
    73    plt.xlabel("Sample number")
    74
    75    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0)
    76    #     plt.legend([plot1, plot2, plot3], ["From", "To", "Merged line"])
    77
    78    plt.savefig(fnFullPath, dpi=300, bbox_inches="tight")
    79    plt.close(fig)

def plotF0(fromTuple, toTuple, mergeTupleList, fnFullPath): View Source

     82def plotF0(fromTuple, toTuple, mergeTupleList, fnFullPath):
     83    """
     84    Plots the original data in a graph above the plot of the dtw'ed data
     85    """
     86    _matplotlibCheck()
     87
     88    fig, (ax0) = plt.subplots(nrows=1)
     89
     90    # Old data
     91    plot1 = ax0.plot(fromTuple[0], fromTuple[1], color="red", linewidth=2, label="From")
     92    plot2 = ax0.plot(toTuple[0], toTuple[1], color="blue", linewidth=2, label="To")
     93    ax0.set_title("Plot of F0 Morph")
     94    plt.ylabel("Pitch (hz)")
     95    plt.xlabel("Time (s)")
     96
     97    # Merge data
     98    colorValue = 0
     99    colorStep = 255.0 / len(mergeTupleList)
    100    for timeList, valueList in mergeTupleList:
    101        colorValue += colorStep
    102        hexValue = "#%02x0000" % int(255 - colorValue)
    103        if int(colorValue) == 255:
    104            ax0.plot(
    105                timeList,
    106                valueList,
    107                color=hexValue,
    108                linewidth=1,
    109                label="Merged line, final iteration",
    110            )
    111        else:
    112            ax0.plot(timeList, valueList, color=hexValue, linewidth=1)
    113
    114    plt.legend(loc=1, borderaxespad=0.0)
    115    #     plt.legend([plot1, plot2, plot3], ["From", "To", "Merged line"])
    116
    117    plt.savefig(fnFullPath, dpi=300, bbox_inches="tight")
    118    plt.close(fig)

Plots the original data in a graph above the plot of the dtw'ed data

def plotIntensity(fromDataList, toDataList, mergeTupleList, controlPoints, fnFullPath): View Source

    121def plotIntensity(fromDataList, toDataList, mergeTupleList, controlPoints, fnFullPath):
    122    def mag2DB(valueList):
    123        stepSize = 500
    124
    125        returnList = []
    126        for i in range(int(math.ceil(len(valueList) / float(stepSize)))):
    127            subList = valueList[i * stepSize : (i + 1) * stepSize]
    128            value = math.sqrt(sum([val ** 2 for val in subList]))
    129
    130            returnList.append(20.0 * math.log10(value))
    131
    132        return returnList
    133
    134    _matplotlibCheck()
    135
    136    fromDataList = mag2DB(fromDataList)
    137    toDataList = mag2DB(toDataList)
    138
    139    print(max(fromDataList))
    140    print(max(toDataList))
    141
    142    fig, ax0 = plt.subplots(nrows=1)
    143    #     fig, (ax0, ax1, ax2) = plt.subplots(nrows=3)
    144
    145    # Old data
    146    plot1 = ax0.plot(fromDataList, color="red", linewidth=2, label="From")
    147    #     plot1.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    148
    149    plot2 = ax0.plot(toDataList, color="blue", linewidth=2, label="To")
    150    #     plot2.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    151
    152    ax0.set_title("Plot of Intensity Morph")
    153    plt.ylabel("RMS intensity (db)")
    154    plt.xlabel("Time (s)")
    155
    156    # Merge data
    157
    158    colorValue = 0
    159    colorStep = 255.0 / len(mergeTupleList)
    160    for valueList in mergeTupleList:
    161
    162        valueList = mag2DB(valueList)
    163
    164        print(max(valueList))
    165
    166        colorValue += colorStep
    167        hexValue = "#%02x0000" % int(255 - colorValue)
    168        xValues = [i for i in range(len(valueList))]
    169        if colorValue == 255.0:
    170            plot3 = ax0.plot(
    171                xValues, valueList, color=hexValue, linewidth=1, label="Merged line"
    172            )
    173        else:
    174            plot3 = ax0.plot(xValues, valueList, color=hexValue, linewidth=1)
    175
    176    controlPoints = mag2DB(controlPoints)
    177    xValues = [i for i in range(len(controlPoints))]
    178    ax0.scatter(xValues, controlPoints, color="pink", label="Control points")
    179
    180    plt.legend(
    181        loc=1,
    182        # bbox_to_anchor=(1.05, 1), loc=2,
    183        borderaxespad=0.0,
    184    )
    185
    186    plt.savefig(fnFullPath, dpi=300, bbox_inches="tight")
    187    plt.close(fig)

def plotDuration( fromDurationList, toDurationList, resultDataList, labelList, fnFullPath): View Source

    190def plotDuration(
    191    fromDurationList, toDurationList, resultDataList, labelList, fnFullPath
    192):
    193
    194    _matplotlibCheck()
    195
    196    dataList = (
    197        [
    198            fromDurationList,
    199        ]
    200        + resultDataList
    201        + [
    202            toDurationList,
    203        ]
    204    )
    205
    206    # Sanity check
    207    for subList in dataList:
    208        assert len(subList) == len(fromDurationList)
    209
    210    # Constants
    211    colorTuple = ["red", "yellow", "blue"]
    212    width = 0.2
    213    n = len(dataList)
    214    iterN = range(n)
    215
    216    # Pre-plotting work
    217    fig, ax0 = plt.subplots(nrows=1)
    218
    219    # Labels
    220    ax0.set_title("Plot of Duration Morph")
    221    plt.ylabel("Duration (s)")
    222    plt.xlabel("Iterations")
    223    plt.title("Duration morph")
    224
    225    # Draw x ticks (iteration numbers)
    226    xLabelList = []
    227    for i in range(len(resultDataList)):
    228        xLabelList.append(str(i + 1))  # 1 based
    229
    230    xLabelList = (
    231        [
    232            "From",
    233        ]
    234        + xLabelList
    235        + [
    236            "To",
    237        ]
    238    )
    239    iterN2 = [val + width / 2.0 for val in iterN]
    240    plt.xticks(iterN2, xLabelList)
    241
    242    # Plot the data
    243    transposedList = zip(*dataList)
    244    bottom = [0 for i in iterN]
    245    for i, row in enumerate(transposedList):
    246
    247        # Horizontal line that sits on the tallest column
    248        ax0.axhline(bottom[0], color="black")
    249
    250        # Word label that appears after the final column
    251        bottomAppend = max(row)
    252        ax0.text(n - 1.0 + 0.5, (bottom[0] + (bottomAppend / 3.0)), labelList[i])
    253
    254        # The column data
    255        ax0.bar(
    256            x=iterN,
    257            height=row,
    258            bottom=bottom,
    259            width=width,
    260            alpha=0.6,
    261            color=colorTuple[i % 3],
    262        )
    263
    264        # Update the start positions for the next iteration
    265
    266        bottom = [origBottom + bottomAppend for origBottom in bottom]
    267
    268    # Draw a final horizontal line over the highest column
    269    ax0.axhline(bottom[0], color="black")
    270
    271    # Save and cleanup
    272    plt.savefig(fnFullPath, dpi=300, bbox_inches="tight")
    273    plt.close(fig)