def a_star_function(X, Y, taskX, taskY):
    # load the map
    gmap = OccupancyGridMap.from_png('among-us-edges-fixed-ai1.png', .05)

    # set a start and an end node (in meters)
    start_node = (X, Y)  ##AMONG US: Where we are
    goal_node = (taskX, taskY)  ##AMONG US: Where the task is :)

    # run A*
    path, path_px = a_star(start_node, goal_node, gmap, movement='4N')

    gmap.plot()

    if path:
        # plot resulting path in pixels over the map
        plot_path(path_px)
    else:
        print('Goal is not reachable')

        # plot start and goal points over the map (in pixels)
        start_node_px = gmap.get_index_from_coordinates(
            start_node[0], start_node[1])
        goal_node_px = gmap.get_index_from_coordinates(goal_node[0],
                                                       goal_node[1])

        plt.plot(start_node_px[0], start_node_px[1], 'ro')
        plt.plot(goal_node_px[0], goal_node_px[1], 'go')

    plt.show()
def _create_ash79_initial_string(savepath=None, plot=True):
    cvs = load_object(cvs_len5path + "cvs")
    asp79_path = np.loadtxt(
        "/home/oliver/slask/holo5-optimized-avg-strings/stringaverage150-175.txt"
    )
    rescale = True
    asp79_path = colvars.scale_evals(asp79_path,
                                     cvs) if rescale else asp79_path
    ash79_path = asp79_path[::2]
    ash79_path[-1] = asp79_path[-1]
    logger.info("Changed length from %s to %s", asp79_path.shape,
                ash79_path.shape)
    logger.debug("The endpoints differ by %s and %s",
                 np.linalg.norm(ash79_path[0] - asp79_path[0]),
                 np.linalg.norm(ash79_path[-1] - asp79_path[-1]))
    # print(asp79_path)
    ash79_path = utils.reparametrize_path_iter(ash79_path)
    if savepath is not None:
        np.savetxt(savepath, ash79_path)
        logger.info("Saved stringpath of %s points to %s", len(ash79_path),
                    savepath)
    if plot:
        utils.plot_path(asp79_path, twoD=False, label="asp79_path")
        utils.plot_path(ash79_path, twoD=False, label="ash79_path")
        plt.show()
def plot_frames(cvs, string_path, frames):
    string_traj = to_single_trajectory(frames)
    utils.plot_path(string_path, label="String path coordinates", twoD=False)
    utils.plot_path(colvars.eval_cvs(string_traj, cvs),
                    label="String path from simulation frames",
                    twoD=False)
    plt.legend()
    plt.show()
def _update_beta2_endpoints(outpath, plot=True):
    startpoint, endpoint = _create_beta2_endpoints(plot=plot)
    freeendpoint_stringpath = np.loadtxt(
        utils.project_dir +
        "gpcr/cvs/len5/asp79/string-paths/dror_path_looseep.txt")
    new_stringpath = change_endpoints(freeendpoint_stringpath, startpoint,
                                      endpoint)
    np.savetxt(outpath, new_stringpath)
    if plot:
        utils.plot_path(freeendpoint_stringpath, label="old")
        utils.plot_path(new_stringpath, label="new")
        plt.show()
def create_endpoint_from_equilibration(cvs, traj, plot=True):
    """
    :param cvs:
    :param traj: an equilibration trajectory
    :param plot
    :return: np.array with coordinates of the endpoints
    """
    evals = colvars.eval_cvs(traj, cvs)
    point = evals.mean(axis=0)
    if plot:
        utils.plot_path(evals)
        utils.plot_path(point, scatter=True, text="Average")
        plt.show()
    return point
Exemple #6
0
def respond(request):
    """Respond to an HTTP request

    Parameters
    ----------
    request

    Returns
    -------

    """
    text = request.form.get("text", None)
    channel = request.form.get("channel_id")
    start, end = text.split(" to ")
    path_nodes, path_edges = get_directions(start, end)
    plot_path(path_nodes, path_edges)
    plt.savefig("directions.png", format="png", dpi=200)
    client = slack.WebClient(token=os.environ['SLACK_API_TOKEN'])
    response = client.files_upload(channels=channel, file="directions.png")
def create_straight_path_between_structures(cvs,
                                            start_traj,
                                            end_traj,
                                            number_points,
                                            savepath=None,
                                            plot=True):
    logger.info("Creating straight path with %s points for cvs %",
                number_points, [cv.id for cv in cvs])
    start_evals = colvars.eval_cvs(start_traj, cvs).squeeze()
    end_evals = colvars.eval_cvs(end_traj, cvs).squeeze()
    stringpath = utils.get_straight_path(start_evals,
                                         end_evals,
                                         number_points=number_points)
    if savepath is not None:
        np.savetxt(savepath, stringpath)
        logger.info("Saved stringpath of %s points to %s", len(stringpath),
                    savepath)
    if plot:
        utils.plot_path(stringpath, twoD=False)
        plt.title("Generated stringpath")
        plt.show()
    return stringpath
Exemple #8
0
def localize(env, policy, filt, x0, num_steps, plot=False):
    # Collect data from an entire rollout
    states_noisefree, states_real, action_noisefree, obs_noisefree, obs_real = \
            env.rollout(x0, policy, num_steps)
    states_filter = np.zeros(states_real.shape)
    states_filter[0, :] = x0.ravel()

    errors = np.zeros((num_steps, 3))
    position_errors = np.zeros(num_steps)
    mahalanobis_errors = np.zeros(num_steps)

    if plot:
        fig = env.get_figure()

    for i in range(num_steps):
        x_real = states_real[i+1, :].reshape((-1, 1))
        u_noisefree = action_noisefree[i, :].reshape((-1, 1))
        z_real = obs_real[i, :].reshape((-1, 1))
        marker_id = env.get_marker_id(i)

        if filt is None:
            mean, cov = x_real, np.eye(3)
        else:
            # filters only know the action and observation
            mean, cov = filt.update(env, u_noisefree, z_real, marker_id)
        states_filter[i+1, :] = mean.ravel()

        if plot:
            fig.clear()
            plot_field(env, marker_id)
            plot_robot(env, x_real, z_real)
            plot_path(env, states_noisefree[:i+1, :], 'g', 0.5)
            plot_path(env, states_real[:i+1, :], 'b')
            if filt is not None:
                plot_path(env, states_filter[:i+1, :2], 'r')
            fig.canvas.flush_events()

        errors[i, :] = (mean - x_real).ravel()
        errors[i, 2] = minimized_angle(errors[i, 2])
        position_errors[i] = np.linalg.norm(errors[i, :2])

        cond_number = np.linalg.cond(cov)
        if cond_number > 1e12:
            print('Badly conditioned cov (setting to identity):', cond_number)
            print(cov)
            cov = np.eye(3)
        mahalanobis_errors[i] = \
                errors[i:i+1, :].dot(np.linalg.inv(cov)).dot(errors[i:i+1, :].T)

    mean_position_error = position_errors.mean()
    mean_mahalanobis_error = mahalanobis_errors.mean()
    anees = mean_mahalanobis_error / 3

    if filt is not None:
        print('-' * 80)
        print('Mean position error:', mean_position_error)
        print('Mean Mahalanobis error:', mean_mahalanobis_error)
        print('ANEES:', anees)

    if plot:
        plt.show(block=True)

    return position_errors
Exemple #9
0
            simulation = load_freemd(
                "/data/oliver/pnas2011b-Dror-gpcr/targetedmd/2018/targetedmd-beta1/",
                "targetedmd-restrained.xtc", "targetedmd-restrained.gro")
    logger.info("Done. Using %s simulations with %s frames", len(simulation),
                sum(len(s.traj) for s in simulation))
    ###START EVALS#########
    simulation_evals = evaluate_simulations(simulation, cvs)
    cv_coordinates = get_cv_coordinates(simulation_evals, cvs)
    density = compute_density_field(simulation_evals, cvs, cv_coordinates)
    frame_count = sum(len(s.traj) for s in simulation)
    free_energy = to_free_energy(density, norm=frame_count)
    plot_field(cvs,
               cv_coordinates,
               free_energy,
               ngrid=40,
               heatmap=True,
               scatter=False)
    # plt.title("{}-{}, CVs{}".format(protein, traj_type, cv_indices))
    axis_labels = np.array(
        [get_cv_description(cv.id, use_simpler_names=True) for cv in cvs])
    # plt.scatter(cv_coordinates[0, :], cv_coordinates[1, :], alpha=0.05, label="Simulation frames", color="orange")
    for (label, sp) in stringpaths:
        utils.plot_path(sp[:, cv_indices],
                        label=label,
                        axis_labels=axis_labels,
                        scatter=False)
    # plt.text(cv_coordinates[0, 0], cv_coordinates[1, 0], "START", color="blue")
    # plt.text(cv_coordinates[0, -1], cv_coordinates[1, -1], "END", color="blue")
    plt.show()
    logger.info("Done")
Exemple #10
0
    # load the map
    gmap = OccupancyGridMap.from_png(
        '~/ros_workspaces/project/src/stdr_simulator/stdr_resources/maps/among-us-edges-map.png',
        1)

    # set a start and an end node (in meters)
    start_node = (12, 9)  ##AMONG US: Where we are
    goal_node = (8, 5)  ##AMONG US: Where the task is :)

    # run A*
    path, path_px = a_star(start_node, goal_node, gmap, movement='8N')

    gmap.plot()

    if path:
        # plot resulting path in pixels over the map
        plot_path(path_px)
    else:
        print('Goal is not reachable')

        # plot start and goal points over the map (in pixels)
        start_node_px = gmap.get_index_from_coordinates(
            start_node[0], start_node[1])
        goal_node_px = gmap.get_index_from_coordinates(goal_node[0],
                                                       goal_node[1])

        plt.plot(start_node_px[0], start_node_px[1], 'ro')
        plt.plot(goal_node_px[0], goal_node_px[1], 'go')

    plt.show()
def plot_field(runner,
               fields,
               cvs,
               gridmin,
               gridmax,
               rescale=False,
               stringpath=None,
               cutoff=12,
               stringlabel=None,
               title="Free Energy",
               cv_labels=None,
               field_label=r'$\Delta G$',
               axisdata=None,
               plot_reference_structures=True):
    simu_id = runner.simu_id
    description = simuid_to_label.get(simu_id, simu_id)
    if cv_labels is None:
        cv_labels = [cv.id for cv in cvs]
    if axisdata is None:
        axisdata = get_axis(gridmin, gridmax, fields)
    ref_structs = utils.load_many_reference_structures()
    # Remove undefined values for field
    if len(cvs) == 1:
        i = 0
        cvi = cvs[i]
        y, boxplot_data = _fix_field_and_data(fields, cutoff)
        x = colvars.rescale_evals(axisdata, [cvi]) if rescale else axisdata
        # plot_color = simuid_to_color.get(simu_id)
        # plt.plot(x, field, label=description, color=plot_color, linewidth=linewidth)
        # plt.scatter(x, field, s=marker_size, color=plot_color)
        # plt.ylabel(field_label, fontsize=label_fontsize)
        # plt.xlabel(cv_labels[i], fontsize=label_fontsize)
        # plt.tick_params(labelsize=ticks_labelsize)
        utils.plot_path(y,
                        label=description,
                        scatter=False,
                        legend=True,
                        twoD=False,
                        ncols=1,
                        color=simuid_to_color.get(simu_id),
                        boxplot_data=boxplot_data,
                        ticks=x,
                        xticks=np.arange(x.min(), x.max(),
                                         (x.max() - x.min()) / 10),
                        axis_labels=[cv_labels[i], field_label])
        if plot_reference_structures:
            for text, struct in ref_structs:
                try:
                    ci = cvi.eval(struct)
                    if rescale:
                        ci = colvars.rescale_evals(ci, [cvi])[0]
                    yvalue = 0  # 0.5 + np.random.rand()
                    plt.scatter(ci,
                                yvalue,
                                marker="d",
                                color="black",
                                s=marker_size)
                    plt.text(ci,
                             yvalue,
                             text,
                             color="gray",
                             fontsize=pdb_fontsize,
                             rotation=45)
                except Exception as ex:
                    logger.exception(ex)
        # plt.legend(fontsize=label_fontsize)
        # plt.grid()
        plt.title(title)
    elif len(cvs) == 2:
        i, j = 0, 1
        cvi = cvs[i]
        cvj = cvs[j]

        def twoD_plot(z,
                      levels,
                      field_label=field_label,
                      xlabel=cv_labels[i],
                      ylabel=cv_labels[j]):
            im = plt.contourf(x,
                              y,
                              z,
                              levels=levels,
                              norm=field_color_norm,
                              cmap=field_cmap)
            ct = plt.contour(
                x,
                y,
                z,
                levels=levels,
                # extent=[xmin, xmax, ymin, ymax],
                alpha=0.3,
                colors=('k', ))
            plt.grid()
            if xlabel is not None:
                plt.xlabel(xlabel, fontsize=label_fontsize)
            if ylabel is not None:
                plt.ylabel(ylabel, fontsize=label_fontsize)
            plt.tick_params(labelsize=ticks_labelsize)
            # Colorbar
            cbar = plt.colorbar(im, orientation='vertical')
            cbar.set_label(field_label, fontsize=label_fontsize)
            cbar.ax.tick_params(labelsize=ticks_labelsize)
            if title is not None:
                plt.title(title + "," + description)
            # cbar.set_clim(vmin=0, vmax=cutoff)
            # Additional stuff to plot
            if plot_reference_structures:
                for text, struct in ref_structs:
                    try:
                        ci, cj = cvi.eval(struct), cvj.eval(struct)
                        if rescale:
                            ci = colvars.rescale_evals(ci, [cvi])[0]
                            cj = colvars.rescale_evals(cj, [cvj])[0]
                        plt.scatter(ci,
                                    cj,
                                    marker="d",
                                    color="black",
                                    s=marker_size)
                        plt.text(ci + 0.01,
                                 cj,
                                 text,
                                 color="gray",
                                 fontsize=pdb_fontsize)
                    except Exception as ex:
                        logger.error("Failed to display pdb structure %s",
                                     text)
                        logger.exception(ex)

            if stringpath is not None:
                plt.plot(stringpath[:, 0],
                         stringpath[:, 1],
                         '-',
                         label=stringlabel,
                         linewidth=linewidth,
                         color=string_color)
                # plt.scatter(stringpath[:, 0], stringpath[:, 1])
                plt.legend(fontsize=label_fontsize)
                plt.scatter(stringpath[0, 0],
                            stringpath[0, 1],
                            marker="*",
                            color='black',
                            s=marker_size)  # s=200
                plt.scatter(stringpath[-1, 0],
                            stringpath[-1, 1],
                            marker="^",
                            color='black',
                            s=marker_size)
                for point_idx, text in simuid_to_string_events.get(
                        simu_id, []):
                    plt.text(stringpath[point_idx, 0],
                             stringpath[point_idx, 1],
                             text,
                             color="black",
                             fontsize=pdb_fontsize - 6,
                             bbox=dict(facecolor='white', alpha=0.5))

        delta_z = None
        if len(fields.shape) == 3:
            z = np.mean(fields, axis=0)
            if fields.shape[0] > 1:
                delta_z = np.std(fields, axis=0)
                delta_z = delta_z.T
        else:
            z = fields
        z = _fix_range(z, cutoff)
        z = z.T  # Transpose it here so that it plots properly. In matplot lib field[i,:] gives us a row along the x-axis for the i:th y-value
        if rescale:
            x = colvars.rescale_evals(axisdata, [cvi])
            y = colvars.rescale_evals(axisdata, [cvj])
        else:
            x, y = axisdata, axisdata
        # Set the levels parameter of the plots so that we resolve regions of lower FE  (since those are typically statistically more accurate and biologically interesting)
        # levels = np.append(np.arange(0, 2.0, 0.25),np.arange(2.0, 6.0, 0.5))
        field_levels = np.array([0.06 * step**2 for step in range(0, 30)])
        field_levels = field_levels[field_levels < 5]
        if delta_z is None:
            plt.subplot(1, 1, 1)
            twoD_plot(z, field_levels)
        else:
            plt.subplot(1, 2, 1)
            twoD_plot(z, field_levels)
            plt.subplot(1, 2, 2)
            twoD_plot(delta_z,
                      None,
                      field_label=r'$\sigma$ [kcal/mol]',
                      ylabel=None)
        # plt.tight_layout()
    else:
        raise Exception(
            "Plotting more than 2 dimensions not supported yet. Size: %s" %
            (len(cvs)))