Exemplo n.º 1
0
def main(name, arguments):
    parser.prog = name
    options, args = parser.parse_args(arguments)
    args = cli_tools.glob_args(args)
    reference = cli_tools.glob_args(options.reference)

    if (len(args) < 2) or (len(args) + len(reference) < 3):
        raise ValueError(
            'A data column and at least two datasets (at least one of which must not be a reference) must be provided!'
        )

    data_column, datasets = args[0], args[1:]

    # if the data column is convertible to an integer, do so and
    # then convert from 1-indexed to 0-indexed
    try:
        data_column = int(data_column)
        data_column -= 1
    except:
        pass

    if options.show_progress:
        datasets = terminal_tools.progress_list(datasets, "Reading input data")
    names, pops = read_files(datasets, data_column)
    if options.show_progress and len(reference) > 0:
        reference = terminal_tools.progress_list(reference,
                                                 "Reading reference data")
    ref_names, ref_pops = read_files(reference, data_column)

    if options.show_progress:
        pb = terminal_tools.IndeterminantProgressBar("Resampling data")
    if len(ref_pops) > 0:
        pvals = ks_resample.compare_to_ref(pops, ref_pops, options.n)
        if len(ref_names) > 1:
            ref_name = 'reference (%s)' % (', '.join(ref_names))
        else:
            ref_name = ref_names[0]
        rows = [[None, 'difference from %s' % ref_name]]
        for name, p in zip(names, pvals):
            rows.append([name, format_pval(p, options.n)])
    else:  # no ref pops
        pvals = ks_resample.symmetric_comparison(pops, options.n)
        rows = [[None] + names]
        for i, (name, p_row) in enumerate(zip(names, pvals)):
            rows.append([name] + [format_pval(p, options.n) for p in p_row])
            rows[-1][i +
                     1] = None  # empty out the self-self comparison diagonal

    datafile.write_data_file(rows, options.output_file)
Exemplo n.º 2
0
def _get_contours_and_images(filenames, show_progress = True):
    contours = []
    image_names = []
    if show_progress:
        filenames = terminal_tools.progress_list(filenames, 'Loading Contours and Images')
    for filename in filenames:
        filename = path.path(filename)
        if not filename.exists():
            raise ValueError('File "%s" does not exist.'%filename)
        try:
            freeimage.read_metadata(filename)
            image_names.append(filename)
        except IOError as e:
            # print e
            # print Image.ID
            try:
                contours.append(contour_class.from_file(filename))
            except IOError as e:
                # print e
                raise ValueError('Could not open file "%s" as an image or a contour.'%filename)
    return contours, image_names
Exemplo n.º 3
0
def _get_contours_and_images(filenames, show_progress=True):
    contours = []
    image_names = []
    if show_progress:
        filenames = terminal_tools.progress_list(
            filenames, 'Loading Contours and Images')
    for filename in filenames:
        filename = path.path(filename)
        if not filename.exists():
            raise ValueError('File "%s" does not exist.' % filename)
        try:
            Image.open(filename)
            image_names.append(filename)
        except IOError, e:
            # print e
            # print Image.ID
            try:
                contours.append(contour_class.from_file(filename))
            except IOError, e:
                # print e
                raise ValueError(
                    'Could not open file "%s" as an image or a contour.' %
                    filename)
Exemplo n.º 4
0
def main(name, arguments):
    parser.prog = name
    options, args = parser.parse_args(arguments)
    data_files = []
    new_args = []
    for arg in args:
        if type(arg) == list:
            data_files.append(arg)
        else:
            new_args.append(arg)
    args = cli_tools.glob_args(new_args)
    if len(args) + len(data_files) == 0:
        raise ValueError('Some data files (and optionally contour files, for 2D plots) must be specified!')
    
    # if the x, y, and name columns are convertible to integers, do so and 
    # then convert them from 1-indexed to 0-indexed
    try:
        options.name_column = int(options.name_column)
        options.name_column -= 1
    except:
        pass
    try:
        options.x_column = int(options.x_column)
        options.x_column -= 1
    except:
        pass
    try:
        options.y_column = int(options.y_column)
        options.y_column -= 1
    except:
        pass
    contours = {}
    if options.show_progress:
        args = terminal_tools.progress_list(args, "Reading input data and contours")
    for arg in args:
        contour = None
        try:
            contour = contour_class.from_file(arg)
        except:
            data_files.append(arg)
        if contour is not None:
            contours[contour.simple_name()] = contour
    if len(data_files) == 0:
        raise ValueError('No data files were specified!')
    headers, data_ranges, data_names, data_files, row_ranges = get_data(data_files)
    if not options.x_title:
            if isinstance(options.x_column, int):
                try: options.x_title = headers[0][options.x_column]
                except: pass
            else:
                options.x_title = options.x_column
    if options.y_column is not None:
        # make scatterplot
        if not options.y_title:
            if isinstance(options.y_column, int):
                try: options.y_title = headers[0][options.y_column]
                except: pass
            else:
                options.y_title = options.y_column
        contour_groups = get_contour_groups(data_ranges, contours, data_files, row_ranges, options.name_column, options.x_column, options.y_column)
        if numpy.alltrue([len(cg)==0 for cg in contour_groups]):
            raise RuntimeError('No contours found for data rows specified (perhaps the names mismatch or there were no data rows?).')
        plot_tools.contour_scatterplot(contour_groups, options.output_file, options.scale,
            (options.x_title, options.y_title), options.title, names=data_names, 
            axes_at_origin=options.axes_at_origin, fix_xrange=(options.x_min, options.x_max),
            fix_yrange=(options.y_min, options.y_max), show_contour_axes=options.contour_axes, 
            show_progress=options.show_progress)
    else:
        data_groups = [[row[options.x_column] for row in data_range] for data_range in data_ranges]
        plot_tools.distribution_plot(data_groups, options.output_file, options.x_title,
            options.title, names=data_names, axes_at_origin=options.axes_at_origin, 
            fix_xrange=(options.x_min, options.x_max))
Exemplo n.º 5
0
def main(name, arguments):
    parser.prog = name
    options, args = parser.parse_args(arguments)
    data_files = []
    new_args = []
    for arg in args:
        if type(arg) == list:
            data_files.append(arg)
        else:
            new_args.append(arg)
    args = cli_tools.glob_args(new_args)
    if len(args) + len(data_files) == 0:
        raise ValueError(
            'Some data files (and optionally contour files, for 2D plots) must be specified!'
        )

    # if the x, y, and name columns are convertible to integers, do so and
    # then convert them from 1-indexed to 0-indexed
    try:
        options.name_column = int(options.name_column)
        options.name_column -= 1
    except:
        pass
    try:
        options.x_column = int(options.x_column)
        options.x_column -= 1
    except:
        pass
    try:
        options.y_column = int(options.y_column)
        options.y_column -= 1
    except:
        pass
    contours = {}
    if options.show_progress:
        args = terminal_tools.progress_list(args,
                                            "Reading input data and contours")
    for arg in args:
        contour = None
        try:
            contour = contour_class.from_file(arg)
        except:
            data_files.append(arg)
        if contour is not None:
            contours[contour.simple_name()] = contour
    if len(data_files) == 0:
        raise ValueError('No data files were specified!')
    headers, data_ranges, data_names, data_files, row_ranges = get_data(
        data_files)
    if not options.x_title:
        if isinstance(options.x_column, int):
            try:
                options.x_title = headers[0][options.x_column]
            except:
                pass
        else:
            options.x_title = options.x_column
    if options.y_column is not None:
        # make scatterplot
        if not options.y_title:
            if isinstance(options.y_column, int):
                try:
                    options.y_title = headers[0][options.y_column]
                except:
                    pass
            else:
                options.y_title = options.y_column
        contour_groups = get_contour_groups(data_ranges, contours, data_files,
                                            row_ranges, options.name_column,
                                            options.x_column, options.y_column)
        if numpy.alltrue([len(cg) == 0 for cg in contour_groups]):
            raise RuntimeError(
                'No contours found for data rows specified (perhaps the names mismatch or there were no data rows?).'
            )
        plot_tools.contour_scatterplot(contour_groups,
                                       options.output_file,
                                       options.scale,
                                       (options.x_title, options.y_title),
                                       options.title,
                                       names=data_names,
                                       axes_at_origin=options.axes_at_origin,
                                       fix_xrange=(options.x_min,
                                                   options.x_max),
                                       fix_yrange=(options.y_min,
                                                   options.y_max),
                                       show_contour_axes=options.contour_axes,
                                       show_progress=options.show_progress)
    else:
        data_groups = [[row[options.x_column] for row in data_range]
                       for data_range in data_ranges]
        plot_tools.distribution_plot(data_groups,
                                     options.output_file,
                                     options.x_title,
                                     options.title,
                                     names=data_names,
                                     axes_at_origin=options.axes_at_origin,
                                     fix_xrange=(options.x_min, options.x_max))
Exemplo n.º 6
0
def point_order_plot(contours, filename, plot_title = None, label_points = True,
        colorbar = True, begin = None, end = None, gradient_factory = default_gradient,
        scalebar = True, color_by_point = True, show_progress = False, scale=None):
    """Plot the order of points in one or more contours to an SVG file.

    One or more contours are plotted from point 'begin' to point 'end', optionally
    colored by their point ordering. Optionally some of the points are labeled,
    and/or a colorbar showing the ordering is provided.

    Parameters:
        contours -- a list of Contour objects to plot.
        filename -- file to write the SVG out to.
        plot_title -- title for the plot.
        label_points -- if True, points will be labeled at evenly-spaced intervals.
        colorbar -- if True, a colorbar will be added.
        begin -- if not None, only contour points after this index will be plotted.
        end -- if not None, the contour points before this index will be plotted.
        gradient_factory -- GradientFactory object to supply the color gradient.
        scalebar -- if True, add a scale bar to the plot (denominated in the units
            that the contours are scaled in).
        color_by_point -- if True, contours are colored by their points; if false
            by their order in the 'contours' list.
        scale -- output-pixels-per-contour-unit scale factor.
    """
    if not utility_tools.all_same_shape([c.points for c in contours]):
        raise ValueError('All contours must have the same number of points.')
    units = _check_units(contours)
    point_range = utility_tools.inclusive_periodic_slice(list(range(len(contours[0].points))), begin, end)
    num_points = len(point_range)
    contours = [contour.as_recentered() for contour in contours]
    bounds = _find_bounds(contours)
    data_xrange, data_yrange = bounds.transpose()
    colorbar_width = 30
    equal_axis_spacing = True
    plot = plot_class.Plot(_CANVAS_WIDTH, _CANVAS_HEIGHT, data_xrange, data_yrange,
        equal_axis_spacing, _LEFT_PAD, _RIGHT_PAD + colorbar_width, _TOP_PAD, _BOTTOM_PAD)
    if scale is None:
        print("Automatically-chosen scale is %g pixels per %s."%(plot.data_to_world_scaling[0], units))
    else:
        plot.data_to_world_scaling = numpy.array([scale, scale])
    if show_progress:
        contours_prog = progress_list(contours, 'Plotting Contours', lambda c: c.simple_name())
    else:
        contours_prog = contours
    plot.style.selectors['.data'].pop('stroke')
    landmarks = _have_landmarks(contours)
    if landmarks:
        plot.style.add_selector('circle.data.landmark', stroke='none')
    color_func = None
    if gradient_factory is not None:
        plot.style.add_selector('path.data.range', stroke_width='2.5', fill='none', stroke_linecap='round')
        if color_by_point:
            color_func = _gradient_color_namer([0, num_points-1], gradient_factory)
            if landmarks:
                plot.style.add_selector('circle.data.landmark', fill='darkgray')
        else:
            style_color_func = _gradient_color_namer((0, len(contours)-1), gradient_factory)
            for i, contour in enumerate(contours):
                plot.style.add_selector('[id="%s"]'%contour.simple_name(), stroke=style_color_func(i))
                if landmarks:
                    plot.style.add_selector('circle.data.landmark[id~="%s"]'%contour.simple_name(), fill=style_color_func(i))
    else:
        plot.style.add_selector('path.data.range', stroke_width='2.5', fill='none', stroke='black', stroke_linecap='round')
        if landmarks:
            plot.style.add_selector('circle.data.landmark', fill='black')
    svg_groups = [_gradient_contour(plot, contour, begin, end, list(range(num_points)), color_func) for contour in contours_prog]
    if begin is not None or end is not None:
        plot.style.add_selector('path.data.fullpath', stroke_width='0.5', fill='none', stroke='darkgray')
    contour_layer = plot.make_layer('contours')
    for g in svg_groups:
        contour_layer.addElement(g)
    if gradient_factory is not None and colorbar:
        def namer(x):
            if int(x) != x: return ''
            else: return str(point_range[int(x)]+1)
        #namer = lambda x: str(point_range[int(x)]+1)
        _add_colorbar(plot, [0, len(point_range)-1], colorbar_width, gradient_factory, _FONT_SIZE_SMALL, namer)
    if scalebar:
        _add_scalebar(plot, units)
    if label_points:
        _add_point_labels(plot, contours, begin, end)
    if plot_title is not None:
        plot.add_title(plot_title, _FONT_SIZE)
    plot.to_svg(filename, plot_title)
    return plot
Exemplo n.º 7
0
def contour_plot(contours, filename, plot_title = None, scalebar = True,
    gradient_factory = default_gradient, show_progress = False,
    radii = False, radius_steps = 1, scale = None):
    """Plot    one or more contours to an SVG file.

    Parameters:
        contours -- a list of Contour objects to plot.
        filename -- file to write the SVG out to.
        plot_title -- title for the plot.
        scalebar -- if True, add a scale bar to the plot (denominated in the units
            that the contours are scaled in).
        gradient_factory -- GradientFactory object to supply the color gradient
            for contour colorings. If none, do not color...
        radii and radius_steps are used for contours with central axes defined:
            if radii is True, then the every radius_steps along the axis, the radius
            will be plotted.
        scale -- output-pixels-per-contour-unit scale factor.
    """
    units = _check_units(contours)
    bounds = _find_bounds(contours)
    data_xrange, data_yrange = bounds.transpose()
    equal_axis_spacing = True
    plot = plot_class.Plot(_CANVAS_WIDTH, _CANVAS_HEIGHT, data_xrange, data_yrange,
        equal_axis_spacing, _LEFT_PAD, _RIGHT_PAD, _TOP_PAD, _BOTTOM_PAD)
    if scale is None:
        print("Automatically-chosen scale is %g pixels per %s."%(plot.data_to_world_scaling[0], units))
    else:
        plot.data_to_world_scaling = numpy.array([scale, scale])
    landmarks = _have_landmarks(contours)
    axis = _have_axis(contours)
    if gradient_factory is None:
        plot.style.add_selector('path.data.contour', stroke='black', stroke_width='2.5', fill='none')
        if landmarks:
            plot.style.add_selector('circle.data.landmark', fill='black', stroke='none')
        if axis:
            plot.style.add_selector('path.data.contour.axis', stroke='black', stroke_width='1', fill='none')
            if radii:
                plot.style.add_selector('polyline.data.contour.radius', stroke='black', stroke_width='1', fill='none')
    else:
        plot.style.add_selector('path.data.contour', stroke_width='2.5', fill='none')
        if landmarks:
            plot.style.add_selector('circle.data.landmark', stroke='none')
        if axis:
            plot.style.add_selector('path.data.contour.axis', stroke_width='1', fill='none')
            if radii:
                plot.style.add_selector('polyline.data.contour.radius', stroke_width='1', fill='none')
        if len(contours) > 1:
            color_func = _gradient_color_namer((0, len(contours)-1), gradient_factory)
        else:
            def color_func(*args):
                return 'black'
    if show_progress:
        econtours = progress_list(enumerate(contours), 'Plotting Contours', lambda ic: ic[1].simple_name())
    else:
        econtours = enumerate(contours)
    for i, contour in econtours:
        name = contour.simple_name().replace(' ', '_')
        if landmarks or axis:
            g = svg_draw.group(id=name)
            lm = _get_landmark_points(plot, contour, name)
            if lm is not None:
                g.addElement(lm)
            ap = _get_axis_points(plot, contour, name, radii, radius_steps)
            if ap is not None:
                g.addElement(ap)
            p = plot._bezier_to_path(contour.to_bezier(), id=name, svg_class='data contour', in_data_coords=True)
            g.addElement(p)
            plot.add_to_layer('contours', g)
        else:
            plot.add_bezier(contour.to_bezier(), id=name, svg_class='data contour', layer='contours')
        if gradient_factory is not None:
            plot.style.add_selector('[id~="%s"]'%name, fill='none', stroke=color_func(i))
            if landmarks:
                plot.style.add_selector('circle.data.landmark[id~="%s"]'%name, fill=color_func(i))
    if scalebar:
        _add_scalebar(plot, units)
    if plot_title is not None:
        plot.add_title(plot_title, _FONT_SIZE)
    plot.to_svg(filename, plot_title)
    return plot