Exemple #1
0
    def test_slicing(self):

        self.failUnlessEqual(
            slice_streamframe_on_intervals(
                self.stream, self.ifr)['framenumber'][1341393414961], 45776.0)
        self.failUnlessEqual(
            slice_intervalframe_by_time(self.tier1, 578.171, 698.440).index[0],
            5)
        self.failUnlessEqual(
            slice_intervalframe_by_time(self.tier1, 578.171,
                                        698.440).index[-1], 21)

        self.failUnlessEqual(
            slice_pointframe_by_time(self.withPoint['P'], 10,
                                     100)['mark'].iloc[0], 'B')
    def test_slicing(self):

        self.failUnlessEqual(slice_streamframe_on_intervals(self.stream,
                                      self.ifr)['framenumber'][1341393414961],
                                                            45776.0)
        self.failUnlessEqual(slice_intervalframe_by_time(self.tier1,
                                                         578.171,
                                                         698.440).index[0],
                                                         5)
        self.failUnlessEqual(slice_intervalframe_by_time(self.tier1,
                                                         578.171,
                                                         698.440).index[-1],
                                                         21)

        self.failUnlessEqual(slice_pointframe_by_time(self.withPoint['P'],
                                                      10, 100)['mark'].iloc[0],
                             'B')
Exemple #3
0
 def get_slice(self, t1, t2):
     if self.__load__() < 0:
         return
     tiertype = get_tier_type(self.__cached_object__)
     if tiertype == "interval":
         return slice_intervalframe_by_time(self.__cached_object__, t1, t2)
     elif tiertype == "point":
         return slice_pointframe_by_time(self.__cached_object__, t1, t2)
Exemple #4
0
 def get_slice(self, t1, t2):
     if self.__load__() < 0:
         return
     tiertype = get_tier_type(self.__cached_object__)
     if tiertype == 'interval':
         return slice_intervalframe_by_time(self.__cached_object__, t1, t2)
     elif tiertype == 'point':
         return slice_pointframe_by_time(self.__cached_object__, t1, t2)
Exemple #5
0
def plot_annotations(tierdict, time_begin=None, time_end=None, tierorder=None,
                     colorindex=None, hscale=1, vscale=1, linespan=20,
                     pointwidth=0.05, tickspacing=1,
                     text_kwargs=None, filepath=None):

    """Plot ELAN annotations, imported from textgrids

    arguments:
    tierdict    a dictionary of intervalframes

    keyword arguments:

    time_begin     -- minimum time (in seconds) of plot. If set to None, the
                       minimum time is found from the data
    time_end       -- maximum time (in seconds) of plot. If set to None, the
                       maximum time is found from the data
    tierorder      -- list of tierKey names to set the order of plotting.
                      Specifying less names than in the tierdict itself
                      results in only those tiers being drawn

    colorindex     -- list of colors to cycle through for each tier, or

                dictionary with labels as keys and colorcodes as values,
                for plotting annotation tiers with finite label sets

    hscale, vscale -- horizontal/vertical scaling of the plot

    linespan       -- time displayed per line of the plot (default 20 seconds)

    pointwidth     -- width of lines for point tiers (in seconds)

    tickspacing    -- number of seconds between ticks on x axis (default 1)

    text_kwargs    -- a fontdict for plt.text() in order to print the
                      text labels. Set to None to avoid printing any text

    filepath       -- path to filename to save the figure, e.g:
                      '~/Desktop/myfile.pdf'

                      The file must have one of the matplolib-supported
                      extensions, e.g. 'pdf', 'png', 'jpg'

    """
    if colorindex == None:
        colorindex = ['r', 'g', 'b', 'c', 'm', 'y', 'k']
    #determine tiers to draw and the order
    thekeys = []
    if tierorder == None:
        thekeys = tierdict.keys()
    else:
        thekeys = tierorder

    if len(thekeys) == 0:
        return "No tiers to plot!"

    #find boundaries
    tiermin = min([get_tier_boundaries(tierdict[tierkey])[0] for tierkey \
                   in thekeys])
    tiermax = max([get_tier_boundaries(tierdict[tierkey])[1] for tierkey \
                   in thekeys])
    if time_begin == None:
        time_begin = tiermin
    else:
        time_begin = max(time_begin, tiermin)
    if time_end == None:
        time_end = tiermax
    else:
        time_end = min(time_end, tiermax)

    #Check time limits
    duration = time_end - time_begin
    if duration <= 0:
        return "Wrong time limits!"
    elif duration < linespan:
        linespan = duration
        number_of_lines = 1
    else:
        number_of_lines = int((float(duration) / linespan)) + 1

    fig = plt.figure(figsize=(hscale * linespan,
                              vscale * number_of_lines * len(thekeys)))

    for line in range(number_of_lines):
        #Drawing loop of tiers
        for tiernumber, tierkey in enumerate(thekeys):
            #Trim tier at time limits
            t1 = time_begin + line * linespan
            t2 = min(t1 + linespan, time_end)


            if get_tier_type(tierdict[tierkey]) == 'point':
                tier = slice_intervalframe_by_time(\
                       __point_tier_to_intervals__(tierdict[tierkey],
                                                   pointwidth), t1, t2)
            elif get_tier_type(tierdict[tierkey]) == 'interval':
                tier = slice_intervalframe_by_time(tierdict[tierkey], t1, t2)
            else:
                continue
            #Add subplots
            ax = fig.add_subplot(number_of_lines * len(thekeys), 1,
                                 line * len(thekeys) + tiernumber + 1)
            xticks = range(int(t1), int(t2) + 1, tickspacing)
            if tiernumber == len(thekeys)-1:
                xlabels = xticks
            else:
                xlabels = []

            #Set the color
            if isinstance(colorindex, list):
                tiercolor = colorindex[tiernumber % len(colorindex)]
            elif isinstance(colorindex, dict):
                tiercolor = colorindex

            __draw_tier__(ax, fig.canvas.get_renderer(), tier, xmin=t1,
                          xmax=(t1 + linespan), ymin=0, ymax=1,
                          xticks=xticks, xlabels=xlabels, tierkey=tierkey,
                          tiercolor=tiercolor, edgecolor='w',
                          textkwargs=text_kwargs)
    fig.subplots_adjust(hspace=0.5)
    if filepath is not None:
        fig.savefig(filepath, format=filepath.split('.')[1])
Exemple #6
0
def plot_reco(**kwargs):
    """Plot an inc_reco file

    The function accepts only kwargs, so as to be used with IPython
    widgets. These kwargs have to be passed

    iframe -- an intervalframe dict that represents the imported reco,
              with each update on a separate tier

    latest_tiers -- the number of updates to display as separate tier
                    subplots. If there are yet more updates than subplots
                    available, they appear as grey diamonds on the tier subplot
                    representing the earliest visible update (yellow diamond)

    current_time -- the current time. Only updates up to this time will be
                    plotted on any tier

    optional kwargs:

    max_history -- set the earliest time in the past (relative to current time)
                   that will be shown on any tier

    printing -- if True, the latest update is also printed as text

    filepath -- a valid file path and name for saving the plot as
                a figure on disk (no figure will be saved if filename is
                None)

    hscale, vscale -- enlarge the resulting plot horizontally or vertically,
                      (must be positive integers)

    textfontsize -- fontsize for the interval (IU) labels

    tickfontsize -- fontsize for the ticks

    labelfontsize -- fontsize for the Y (updates) labels

    tickspacing -- spacing for the x axis ticks (positive int)

    """
    intervalframe = kwargs['iframe']
    latest_tiers = kwargs['latest_tiers']
    current_time = kwargs['current_time']

    #dict of optional kwargs and default values:

    optional = {'printing': False,
                'filepath': False,
                'max_history': 0,
                'hscale': 1,
                'vscale': 1,
                'textfontsize': 16,
                'tickfontsize': 14,
                'labelfontsize': 14,
                'tickspacing': 1}

    for opt in optional:
        if opt not in kwargs or kwargs[opt] <= 0:
            kwargs[opt] = optional[opt]


    if kwargs['max_history'] > 0:
        min_time = max(current_time - kwargs['max_history'], 0)
        max_time = max(kwargs['max_history'], current_time)
    else:
        min_time = 0
        max_time = max([float(k) for k in intervalframe.keys()])

    min_time = int(min_time)
    max_time = int(max_time + 1)

    updates = []
    for key in intervalframe.keys():
        if float(key) <= current_time:
            updates.append(float(key))

    fig = plt.figure(figsize=(16 * kwargs['hscale'],
                              2 * latest_tiers * kwargs['vscale']))
    ax = fig.add_subplot(latest_tiers, 1, 1)
    splots = min(latest_tiers, len(updates))
    if len(updates) > 0:
        for i, u in enumerate(sorted(updates)):
            tier = slice_intervalframe_by_time(intervalframe[str(u)],
                                               min_time, max_time)
            last_time = intervalframe[str(u)]['end_time'].iloc[-1]
            if i >= len(updates) - latest_tiers:
                ax = fig.add_subplot(latest_tiers, 1, splots)
                __draw_tier__(ax, fig.canvas.get_renderer(),
                              tier,
                              xmin=min_time,
                              xmax=max_time,
                              xticks=range(min_time, max_time + 1,
                                           kwargs['tickspacing']),
                              xlabels=range(min_time,
                                            max_time + 1,
                                            kwargs['tickspacing']),
                              tierkey='',
                              tiercolor='w', edgecolor='b', ymin=0.3, ymax=0.7,
                              textkwargs={'color': 'k',
                                          'fontsize': kwargs['textfontsize']})
                splots -= 1
                ax.plot([last_time], [0.9], 'yD', markersize=10)
                if i < len(updates) - 1:
                    ax.vlines(last_time, 0, 1, linewidth=2, color='r')
                    ax.set_ylabel(str(u))
                else:
                    ax.vlines(current_time, 0, 1, linewidth=2, color='r')
                    ax.set_ylabel(current_time)
            else:
                ax = fig.add_subplot(latest_tiers, 1, latest_tiers)
                ax.plot([last_time], [0.9], 'D', color='grey', markersize=10)

        if kwargs['printing']:
            print "update at:", u
            print intervalframe[str(u)]
    else:
        ax.set_yticks([])
        ax.set_xlim(0, max_time)
    if kwargs['filepath']:
        fig.savefig(filepath)
Exemple #7
0
def plot_annotations(tierdict,
                     time_begin=None,
                     time_end=None,
                     tierorder=None,
                     colorindex=None,
                     hscale=1,
                     vscale=1,
                     linespan=20,
                     pointwidth=0.05,
                     tickspacing=1,
                     text_kwargs=None,
                     filepath=None):
    """Plot ELAN annotations, imported from textgrids

    arguments:
    tierdict    a dictionary of intervalframes

    keyword arguments:

    time_begin     -- minimum time (in seconds) of plot. If set to None, the
                       minimum time is found from the data
    time_end       -- maximum time (in seconds) of plot. If set to None, the
                       maximum time is found from the data
    tierorder      -- list of tierKey names to set the order of plotting.
                      Specifying less names than in the tierdict itself
                      results in only those tiers being drawn

    colorindex     -- list of colors to cycle through for each tier, or

                dictionary with labels as keys and colorcodes as values,
                for plotting annotation tiers with finite label sets

    hscale, vscale -- horizontal/vertical scaling of the plot

    linespan       -- time displayed per line of the plot (default 20 seconds)

    pointwidth     -- width of lines for point tiers (in seconds)

    tickspacing    -- number of seconds between ticks on x axis (default 1)

    text_kwargs    -- a fontdict for plt.text() in order to print the
                      text labels. Set to None to avoid printing any text

    filepath       -- path to filename to save the figure, e.g:
                      '~/Desktop/myfile.pdf'

                      The file must have one of the matplolib-supported
                      extensions, e.g. 'pdf', 'png', 'jpg'

    """
    if colorindex == None:
        colorindex = ['r', 'g', 'b', 'c', 'm', 'y', 'k']
    #determine tiers to draw and the order
    thekeys = []
    if tierorder == None:
        thekeys = tierdict.keys()
    else:
        thekeys = tierorder

    if len(thekeys) == 0:
        return "No tiers to plot!"

    #find boundaries
    tiermin = min([get_tier_boundaries(tierdict[tierkey])[0] for tierkey \
                   in thekeys])
    tiermax = max([get_tier_boundaries(tierdict[tierkey])[1] for tierkey \
                   in thekeys])
    if time_begin == None:
        time_begin = tiermin
    else:
        time_begin = max(time_begin, tiermin)
    if time_end == None:
        time_end = tiermax
    else:
        time_end = min(time_end, tiermax)

    #Check time limits
    duration = time_end - time_begin
    if duration <= 0:
        return "Wrong time limits!"
    elif duration < linespan:
        linespan = duration
        number_of_lines = 1
    else:
        number_of_lines = int((float(duration) / linespan)) + 1

    fig = plt.figure(figsize=(hscale * linespan,
                              vscale * number_of_lines * len(thekeys)))

    for line in range(number_of_lines):
        #Drawing loop of tiers
        for tiernumber, tierkey in enumerate(thekeys):
            #Trim tier at time limits
            t1 = time_begin + line * linespan
            t2 = min(t1 + linespan, time_end)

            if get_tier_type(tierdict[tierkey]) == 'point':
                tier = slice_intervalframe_by_time(\
                       __point_tier_to_intervals__(tierdict[tierkey],
                                                   pointwidth), t1, t2)
            elif get_tier_type(tierdict[tierkey]) == 'interval':
                tier = slice_intervalframe_by_time(tierdict[tierkey], t1, t2)
            else:
                continue
            #Add subplots
            ax = fig.add_subplot(number_of_lines * len(thekeys), 1,
                                 line * len(thekeys) + tiernumber + 1)
            xticks = range(int(t1), int(t2) + 1, tickspacing)
            if tiernumber == len(thekeys) - 1:
                xlabels = xticks
            else:
                xlabels = []

            #Set the color
            if isinstance(colorindex, list):
                tiercolor = colorindex[tiernumber % len(colorindex)]
            elif isinstance(colorindex, dict):
                tiercolor = colorindex

            __draw_tier__(ax,
                          fig.canvas.get_renderer(),
                          tier,
                          xmin=t1,
                          xmax=(t1 + linespan),
                          ymin=0,
                          ymax=1,
                          xticks=xticks,
                          xlabels=xlabels,
                          tierkey=tierkey,
                          tiercolor=tiercolor,
                          edgecolor='w',
                          textkwargs=text_kwargs)
    fig.subplots_adjust(hspace=0.5)
    if filepath is not None:
        fig.savefig(filepath, format=filepath.split('.')[1])
Exemple #8
0
def plot_reco(**kwargs):
    """Plot an inc_reco file

    The function accepts only kwargs, so as to be used with IPython
    widgets. These kwargs have to be passed

    iframe -- an intervalframe dict that represents the imported reco,
              with each update on a separate tier

    latest_tiers -- the number of updates to display as separate tier
                    subplots. If there are yet more updates than subplots
                    available, they appear as grey diamonds on the tier subplot
                    representing the earliest visible update (yellow diamond)

    current_time -- the current time. Only updates up to this time will be
                    plotted on any tier

    optional kwargs:

    max_history -- set the earliest time in the past (relative to current time)
                   that will be shown on any tier

    printing -- if True, the latest update is also printed as text

    filepath -- a valid file path and name for saving the plot as
                a figure on disk (no figure will be saved if filename is
                None)

    hscale, vscale -- enlarge the resulting plot horizontally or vertically,
                      (must be positive integers)

    textfontsize -- fontsize for the interval (IU) labels

    tickfontsize -- fontsize for the ticks

    labelfontsize -- fontsize for the Y (updates) labels

    tickspacing -- spacing for the x axis ticks (positive int)

    """
    intervalframe = kwargs['iframe']
    latest_tiers = kwargs['latest_tiers']
    current_time = kwargs['current_time']

    #dict of optional kwargs and default values:

    optional = {
        'printing': False,
        'filepath': False,
        'max_history': 0,
        'hscale': 1,
        'vscale': 1,
        'textfontsize': 16,
        'tickfontsize': 14,
        'labelfontsize': 14,
        'tickspacing': 1
    }

    for opt in optional:
        if opt not in kwargs or kwargs[opt] <= 0:
            kwargs[opt] = optional[opt]

    if kwargs['max_history'] > 0:
        min_time = max(current_time - kwargs['max_history'], 0)
        max_time = max(kwargs['max_history'], current_time)
    else:
        min_time = 0
        max_time = max([float(k) for k in intervalframe.keys()])

    min_time = int(min_time)
    max_time = int(max_time + 1)

    updates = []
    for key in intervalframe.keys():
        if float(key) <= current_time:
            updates.append(float(key))

    fig = plt.figure(figsize=(16 * kwargs['hscale'],
                              2 * latest_tiers * kwargs['vscale']))
    ax = fig.add_subplot(latest_tiers, 1, 1)
    splots = min(latest_tiers, len(updates))
    if len(updates) > 0:
        for i, u in enumerate(sorted(updates)):
            tier = slice_intervalframe_by_time(intervalframe[str(u)], min_time,
                                               max_time)
            last_time = intervalframe[str(u)]['end_time'].iloc[-1]
            if i >= len(updates) - latest_tiers:
                ax = fig.add_subplot(latest_tiers, 1, splots)
                __draw_tier__(ax,
                              fig.canvas.get_renderer(),
                              tier,
                              xmin=min_time,
                              xmax=max_time,
                              xticks=range(min_time, max_time + 1,
                                           kwargs['tickspacing']),
                              xlabels=range(min_time, max_time + 1,
                                            kwargs['tickspacing']),
                              tierkey='',
                              tiercolor='w',
                              edgecolor='b',
                              ymin=0.3,
                              ymax=0.7,
                              textkwargs={
                                  'color': 'k',
                                  'fontsize': kwargs['textfontsize']
                              })
                splots -= 1
                ax.plot([last_time], [0.9], 'yD', markersize=10)
                if i < len(updates) - 1:
                    ax.vlines(last_time, 0, 1, linewidth=2, color='r')
                    ax.set_ylabel(str(u))
                else:
                    ax.vlines(current_time, 0, 1, linewidth=2, color='r')
                    ax.set_ylabel(current_time)
            else:
                ax = fig.add_subplot(latest_tiers, 1, latest_tiers)
                ax.plot([last_time], [0.9], 'D', color='grey', markersize=10)

        if kwargs['printing']:
            print "update at:", u
            print intervalframe[str(u)]
    else:
        ax.set_yticks([])
        ax.set_xlim(0, max_time)
    if kwargs['filepath']:
        fig.savefig(filepath)