예제 #1
0
    def output_fig(self,figure_filename,xlabel='Temp [degC]',display=True):


        months=list(self.profile.keys())
        number_of_loops=len(months)
        
        spec = strategies.SquareStrategy().get_grid(number_of_loops)
        fig = plt.gcf()
        fig.set_dpi(100)
        fig.constrained_layout=True
        fig.set_figheight(11.69)
        fig.set_figwidth(8.27)
        xmin=np.inf
        xmax=-np.inf

        for month in months:
            xmin=min(xmin,np.nanmin(self.profile[month]))
            xmax=max(xmax,np.nanmax(self.profile[month]))

        for j,sub in enumerate(spec):
            ax = plt.subplot(sub)
            ax.plot(self.profile[months[j]],self.x*-1)

            ax.set_xlabel(xlabel)
            ax.set_ylabel('Water depth (m)')
            ax.set_title(months[j])
            ax.set_xlim(xmin,xmax)
        
        fig.align_labels()
      
        if display:
            plt.show(block=~display)

        plt.savefig(figure_filename)
def plot(subunits):
    """Plots actuators

    Arguments:
        subunits {list} -- List of subunit ORIENTATION VECTORS
    """

    num_plots = len(subunits)

    specs = strategies.SquareStrategy('center').get_grid(num_plots)

    fig = plt.figure(1)

    for vec, sub in zip(subunits, specs):
        ax = fig.add_subplot(sub)

        l = Limb()
        l.build(vec)

        ax.plot([0, 0], [-2, 2], color='black')
        ax.plot(l.XY[0], l.XY[1], color='red')

        ax.set_aspect('equal', adjustable='datalim')
        ax.margins(1.5, 1.5)
        ax.autoscale(False)
        overlay_images(ax, l)
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)

    plt.show()
def show_image_grid(images):
    import matplotlib.pyplot as plt
    from grid_strategy import strategies
    batch_size = images.shape[0]
    specs = strategies.SquareStrategy("center").get_grid(batch_size)
    for b, subplot in enumerate(specs):
        plt.subplot(subplot)
        plt.xticks([])
        plt.yticks([])
        ax = plt.gca()
        if b == 0:
            ax.set_title(r"$I_t$")
            ax.imshow(images[b, 0, :, :, :3])
        elif b == 1:
            ax.set_title(r"$I_{t+1}$")
            ax.imshow(images[b - 1, 1, :, :, :3])
        else:
            ax.imshow(images[b - 1, 1, :, :, :3])
    plt.show()
예제 #4
0
def square_strategy():
    return strategies.SquareStrategy()
def plot_limb(limbs, objt=None, curve=None):
    for i in range(len(limbs[0])):
        if isinstance(limbs[0][i], list):
            vec_ind = i

    limbs = np.array(limbs)

    if len(limbs.shape) > 1:
        num_plots = len(limbs)
        limbs = limbs[:, vec_ind]
    else:
        num_plots = len(limbs.shape)
        limbs = [limbs]

    specs = strategies.SquareStrategy('center').get_grid(num_plots)

    fig = plt.figure(1, constrained_layout=False)
    fig.canvas.set_window_title('Actuator')

    for vec, sub in zip(limbs, specs):
        ax = fig.add_subplot(sub)

        limb = Limb()
        limb.build(vec)

        end = np.array((limb.XY[0, -num_points:], limb.XY[1, -num_points:]))
        segs = len(limb.orient)

        coordinates = np.copy(limb.XY)

        # ax.set_title("Soft actuator\n" + "Number of segments: {}".format(segs))
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
        ax.plot([0, 0], [-2, 2], color='black')
        ax.xaxis.set_major_locator(MultipleLocator(1))

        normal = np.zeros((len(vec) + 1))
        ''' PLOT UNACTUATED LINE '''
        # ax.plot(normal, color='grey',
        #         label="Initial pressure (P=P" + r'$_i$' + ")")
        """------ACTUATED-------"""
        ax.plot(coordinates[0, :],
                coordinates[1, :],
                color='red',
                label="Final pressure (P=P" + r'$_f$' + ")",
                alpha=0.6)

        if isinstance(objt, np.ndarray):
            ax.plot(objt[0], objt[1], color='black')
        elif isinstance(objt, Polygon):
            ax.plot(objt.exterior.xy[0], objt.exterior.xy[1], color='black')

        ax.plot(curve[0], curve[1], color='blue', alpha=0.6)
        ''' VISUALISATION OF CURVE FIT '''
        if zdist(end, curve) > zdist(end, curve[::-1]):
            ax.plot([end[0], curve[0][::-1]], [end[1], curve[1][::-1]],
                    linewidth=2,
                    color='green')
        else:
            ax.plot([end[0], curve[0]], [end[1], curve[1]],
                    linewidth=2,
                    color='green')

        ax.margins(0.5, 0.5)
        ax.set_aspect('equal', adjustable='datalim')
        ax.autoscale(False)
        overlay_images(ax, limb)

    plt.tight_layout()
    plt.show()
예제 #6
0
def plot_limb(limbs):
    def on_click(event):
        ax = event.inaxes

        if ax is None:
            return

        if event.button != 1:
            return

        if zoomed_axes[0] is None:
            zoomed_axes[0] = (ax, ax.get_position())
            ax.set_position([0.1, 0.1, 0.8, 0.8])
            ax.legend(loc='best')
            ax.get_xaxis().set_visible(True)
            ax.get_yaxis().set_visible(True)
            ax.xaxis.set_major_locator(MultipleLocator(5))
            ax.grid(linestyle=':')
            ax.set_ylim(0)
            ax.margins(x=0, y=-0.25)

            for axis in event.canvas.figure.axes:
                if axis is not ax:
                    axis.set_visible(False)

        else:
            zoomed_axes[0][0].set_position(zoomed_axes[0][1])
            zoomed_axes[0] = None
            ax.get_legend().remove()
            ax.get_xaxis().set_visible(False)
            ax.get_yaxis().set_visible(False)

            for axis in event.canvas.figure.axes:
                axis.set_visible(True)

        event.canvas.draw()

    zoomed_axes = [None]

    for i in range(len(limbs[0])):
        if isinstance(limbs[0][i], list):
            vec_ind = i

    limbs = np.array(limbs)

    if len(limbs.shape) > 1:
        num_plots = len(limbs)
        limbs = limbs[:, vec_ind]
    else:
        num_plots = len(limbs.shape)
        limbs = [limbs]

    # fig = vp.Fig(size=(600,500), show=False)

    # limb = Limb()
    # limb.build(limbs[0])

    # points = np.copy(limb.XY)

    # line = fig[0, 0].plot((points[0, :], points[1, :]), color='red')

    # fig.show(run=True)

    specs = strategies.SquareStrategy('center').get_grid(num_plots)

    fig = plt.figure(1, constrained_layout=False)
    # fig.canvas.set_window_title('Top ' + str(num_plots))

    for vec, sub in zip(limbs, specs):
        ax = fig.add_subplot(sub)

        limb = Limb()
        limb.build(vec)

        segs = len(limb.orient)

        points = np.copy(limb.XY)
        rots = limb.curvature

        # ax.set_title("Soft actuator\n" + "Number of segments: {}".format(segs))
        # ax.get_xaxis().set_visible(False)
        # ax.get_yaxis().set_visible(False)
        ax.plot([0, 0], [-2, 2], color='black')
        # ax.xaxis.set_major_locator(MultipleLocator(1))

        if settings.get('Rainbow'):
            colors = cm.rainbow(np.linspace(0, 1, segs))
            """------NORMAL-------"""
            for i in range(0, segs - 1):
                ax.plot([i, i + 2], [0, 0], color=colors[i])
            """------ACTUATED-------"""
            for i in range(0, segs - 1):
                ax.plot(points[0, i:i + 2],
                        points[1, i:i + 2],
                        color=colors[i])
        else:
            """------NORMAL-------"""
            # normal = np.zeros((segs+1))
            # ax.plot(normal, color='grey',
            # label="Initial pressure (P=P" + r'$_i$' + ")")
            """------ACTUATED-------"""
            ax.plot(points[0, :],
                    points[1, :],
                    color='red',
                    label="Reduced-order model")

        if any(value == True
               for value in parameters.get('Curve fitting').values()):
            m = points[0][-1] / (2 * pi)
            if parameters.get('Curve fitting').get('Sin'):
                curve = 20 * np.sin(points[0] / m)
            elif parameters.get('Curve fitting').get('Cos'):
                curve = 25 * np.cos(points[0] / m) - 25
            elif parameters.get('Curve fitting').get('Custom'):
                curve = []
                func = parameters.get('Curve fitting').get('Custom func')
                for ea in points[0] / m:
                    x = ea
                    curve.append(eval(func))

            ax.plot(points[0],
                    curve,
                    color='black',
                    alpha=0.85,
                    linestyle='--',
                    label='Desired profile')

        # ax.margins(0.5, 0.5)
        # ax.set_xlim(0)
        # ax.margins(x=0, y=-0.25)

        if settings.get('Plot boundaries'):
            to_tuple = [(x, y) for x, y in zip(limb.XY[0], limb.XY[1])]
            line_check = LineString(to_tuple)
            line_top = line_check.parallel_offset(1.9, side='left')
            line_bottom = line_check.parallel_offset(1.9, side='right')

            ax.plot(line_top.xy[0], line_top.xy[1])
            ax.plot(line_bottom.xy[0], line_bottom.xy[1])

        if settings.get('Overlay images'):

            def imshow_affine(ax, z, *args, **kwargs):
                im = ax.imshow(z, *args, **kwargs)
                _, x2, y1, _ = im.get_extent()
                im._image_skew_coordinate = (x2, y1)
                return im

            # width = 2.57
            # height = 3.9

            width = 22.5
            height = 35

            image_directory = os.path.dirname(
                os.path.realpath(__file__)) + '\\box.png'
            # img = plt.imread(image_directory, format='png')
            # img = Image.open(image_directory)
            img = mpimg.imread(image_directory)

            cps = [[], []]
            for i in range(segs):
                cps[0].append((points[0][i] + points[0][i + 1]) / 2)
                cps[1].append((points[1][i] + points[1][i + 1]) / 2)
            cps = np.asarray(cps)

            for i in range(cps.shape[1]):
                img_show = imshow_affine(
                    ax,
                    img,
                    interpolation='none',
                    extent=[0, width, 0, height],
                )

                c_x, c_y = width / 2, (16 * cos(radians(11)))

                if limb.orient[i] == "TOP":
                    rot_angle = 180 + degrees(rots[i + 1])
                elif limb.orient[i] == "BOTTOM":
                    rot_angle = degrees(rots[i + 1])
                else:
                    rot_angle = degrees(rots[i + 1])

                transform_data = (transforms.Affine2D().rotate_deg_around(
                    c_x, c_y, rot_angle).translate(
                        (cps[0][i] - c_x), (cps[1][i] - c_y)) + ax.transData)

                img_show.set_transform(transform_data)
    diff = 20
    x_min = min(points[0, :]) - diff
    x_max = max(points[0, :]) + diff
    y_min = min(points[1, :]) - diff
    y_max = max(points[1, :]) + diff
    # fig.canvas.mpl_connect('button_press_event', on_click)
    # ax.set_aspect('equal', adjustable='datalim')
    # ax.autoscale()
    # plt.tight_layout()
    plt.xlim(x_min, x_max)
    plt.ylim(y_min, y_max)
    plt.xlabel('X [mm]')
    plt.ylabel('Y [mm]')
    ax.xaxis.set_major_locator(MultipleLocator(20))

    ax.grid(linestyle=':')
    # ax.margins(0.5, 0.1)
    plotDavid(ax)

    figManager = plt.get_current_fig_manager()
    figManager.window.state('zoomed')
    lgd = ax.legend(loc='lower center', bbox_to_anchor=(0.5, 1))
    # plt.show()
    plt.savefig('C:\\Users\\zjmon\\Documents\\Meesters\\Thesis\\figs\\Cos.pgf')
예제 #7
0
def do_perc_of_occurence(time, mag, drr, mag_interval, xlabel, time_blocking,
                         dir_int, fileout, show):

    ## Input
    gd_value = ~np.isnan(mag)
    time = time[gd_value]
    mag = mag[gd_value]
    if drr is not None:
        drr = drr[gd_value]
    else:
        drr = np.ones((len(mag), ))
        dir_int = [0, 360]

    if isinstance(mag_interval, int) or isinstance(mag_interval, float):
        s = np.arange(0, np.max(mag), mag_interval)
    elif isinstance(mag_interval, list):
        if len(mag_interval) < 2:
            s = np.linspace(0, np.max(mag), 10)
        else:
            s = np.array(mag_interval)
    else:
        s = np.linspace(0, np.max(mag), 10)

    month = time.month
    number_of_loops, identifiers, month_identifier = get_number_of_loops(
        time_blocking)

    index = []
    nj = []
    for j in range(0, number_of_loops):
        tmp = np.in1d(month, month_identifier[j])
        if np.any(tmp):
            #index .append(tmp)
            nj.append(j)

    number_of_real_loops = len(nj)

    spec = strategies.SquareStrategy().get_grid(number_of_real_loops)
    fig = plt.gcf()
    fig.set_dpi(100)
    fig.constrained_layout = True
    fig.set_figheight(11.69)
    fig.set_figwidth(8.27)

    for i, sub in enumerate(spec):
        ax = plt.subplot(sub)

        #Pull out relevant indices for particular month/months
        index = np.in1d(month, month_identifier[nj[i]])
        big_length = len(index.nonzero()[0])
        if big_length > 0:
            SPD = mag[index]
            DIR = drr[index]

            jet = cm = plt.get_cmap('jet')
            cNorm = colors.Normalize(vmin=0, vmax=len(dir_int) - 2)
            scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)

            for jj in range(0, len(dir_int) - 1):
                if dir_int[jj + 1] <= dir_int[jj]:
                    D = np.logical_or(
                        np.mod(DIR, 360) > dir_int[jj],
                        np.mod(DIR, 360) <= dir_int[jj + 1])
                else:
                    D = (np.mod(DIR, 360) > dir_int[jj]) & (np.mod(DIR, 360) <=
                                                            dir_int[jj + 1])

                colorVal = scalarMap.to_rgba(jj)
                perc = get_perc(s, SPD[D]) / big_length
                plt.plot(s[:-1] + np.diff(s) / 2,
                         perc,
                         color=colorVal,
                         label=degToCompass([dir_int[jj], dir_int[jj + 1]]))

        ax.set_title(identifiers[nj[i]])

        if i == number_of_real_loops - 1 and len(dir_int) > 2:
            # if number_of_loops>3 and number_of_loops<10:
            #     ax.legend(loc='best',bbox_to_anchor=(0.6, -0.4),ncol=len(dir_int)-1)#bbox_to_anchor=(0.8,-1.0, 0.5, 0.5))
            # elif number_of_loops>10:
            #     ax.legend(loc='best',bbox_to_anchor=(0.6, -3.4),ncol=len(dir_int)-1)#bbox_to_anchor=(0.8,-1.0, 0.5, 0.5))
            # else:
            ax.legend(loc='best')

        #if int(y)==0:
        ax.set_ylabel('% Occurence')

        #if int(x)==maxx :
        ax.set_xlabel(xlabel)

    fig.align_labels()

    # if number_of_loops>10:
    #     plt.subplots_adjust(left=0.075,right=0.970,bottom=0.075,top=0.97,hspace=.5,wspace=0.415)
    #     ax.set_xlabel(xlabel)

    # elif number_of_loops>2 and number_of_loops<10:
    #     plt.subplots_adjust(left=0.08,right=0.975,bottom=0.05,top=0.7,hspace=.5,wspace=0.3)
    #     ax.set_xlabel(xlabel)
    # else:
    #     plt.subplots_adjust(bottom=0.05,top=.95,hspace=.5)

    if show:
        plt.show(block=~show)
    plt.savefig(fileout)
예제 #8
0
def plot_limb(limbs):
    def on_click(event):
        ax = event.inaxes

        if ax is None:
            return

        if event.button != 1:
            return

        if zoomed_axes[0] is None:
            zoomed_axes[0] = (ax, ax.get_position())
            ax.set_position([0.1, 0.1, 0.8, 0.8])
            ax.legend(loc='best')
            ax.get_xaxis().set_visible(True)
            ax.get_yaxis().set_visible(True)
            ax.xaxis.set_major_locator(MultipleLocator(5))
            ax.grid(linestyle=':')
            ax.set_ylim(0)
            ax.margins(x=0, y=-0.25)

            for axis in event.canvas.figure.axes:
                if axis is not ax:
                    axis.set_visible(False)

        else:
            zoomed_axes[0][0].set_position(zoomed_axes[0][1])
            zoomed_axes[0] = None
            ax.get_legend().remove()
            ax.get_xaxis().set_visible(False)
            ax.get_yaxis().set_visible(False)

            for axis in event.canvas.figure.axes:
                axis.set_visible(True)

        event.canvas.draw()

    zoomed_axes = [None]

    for i in range(len(limbs[0])):
        if isinstance(limbs[0][i], list):
            vec_ind = i

    limbs = np.array(limbs)

    if len(limbs.shape) > 1:
        num_plots = len(limbs)
        limbs = limbs[:, vec_ind]
    else:
        num_plots = len(limbs.shape)
        limbs = [limbs]

    specs = strategies.SquareStrategy('center').get_grid(num_plots)

    fig = plt.figure(1, constrained_layout=False)
    fig.canvas.set_window_title('Top ' + str(num_plots))

    for vec, sub in zip(limbs, specs):
        ax = fig.add_subplot(sub)

        limb = Limb()
        limb.build(vec)

        segs = len(limb.orient)

        points = np.copy(limb.XY)
        rots = limb.curvature

        ax.plot([0, 0], [-2, 2], color='black')

        if settings.get('Rainbow'):
            colors = cm.rainbow(np.linspace(0, 1, segs))
            """------NORMAL-------"""
            for i in range(0, segs - 1):
                ax.plot([i, i + 2], [0, 0], color=colors[i])
            """------ACTUATED-------"""
            for i in range(0, segs - 1):
                ax.plot(points[0, i:i + 2],
                        points[1, i:i + 2],
                        color=colors[i])
        else:
            """------NORMAL-------"""
            ''' PLOT UNACTUATED LINE HERE '''
            # normal = np.zeros((segs+1))
            # ax.plot(normal, color='grey',
            # label="Initial pressure (P=P" + r'$_i$' + ")")
            """------ACTUATED-------"""
            ax.plot(points[0, :],
                    points[1, :],
                    color='red',
                    label="Reduced-order model")

        if any(value == True
               for value in parameters.get('Curve fitting').values()):
            m = points[0][-1] / (2 * pi)
            if parameters.get('Curve fitting').get('Sin'):
                curve = 20 * np.sin(points[0] / m)
            elif parameters.get('Curve fitting').get('Cos'):
                curve = 25 * np.cos(points[0] / m) - 25
            elif parameters.get('Curve fitting').get('Custom'):
                curve = []
                func = parameters.get('Curve fitting').get('Custom func')
                for _ in points[0] / m:
                    curve.append(eval(func))

            ax.plot(points[0],
                    curve,
                    color='black',
                    alpha=0.85,
                    linestyle='--',
                    label='Desired profile')

        if settings.get('Plot boundaries'):
            to_tuple = [(x, y) for x, y in zip(limb.XY[0], limb.XY[1])]
            line_check = LineString(to_tuple)
            line_top = line_check.parallel_offset(1.9, side='left')
            line_bottom = line_check.parallel_offset(1.9, side='right')

            ax.plot(line_top.xy[0], line_top.xy[1])
            ax.plot(line_bottom.xy[0], line_bottom.xy[1])

        if settings.get('Overlay images'):
            overlay_images(ax, limb)

    diff = 20
    x_min = min(points[0, :]) - diff
    x_max = max(points[0, :]) + diff
    y_min = min(points[1, :]) - diff
    y_max = max(points[1, :]) + diff
    ''' THIS SETTING ALLOWS TO FOCUS THE WINDOW ON THE SELECTED SUBPLOT IF Top > 1 '''
    # fig.canvas.mpl_connect('button_press_event', on_click)

    plt.xlim(x_min, x_max)
    plt.ylim(y_min, y_max)
    plt.xlabel('X [mm]')
    plt.ylabel('Y [mm]')
    ax.xaxis.set_major_locator(MultipleLocator(20))

    ax.grid(linestyle=':')

    figManager = plt.get_current_fig_manager()
    figManager.window.state('zoomed')
    ax.legend(loc='lower center', bbox_to_anchor=(0.5, 1))
    plt.show()