Exemplo n.º 1
0
def generate_2d_traj(start_pos, start_vel, start_acc, end_pos, end_vel, end_acc, time_ahead, plot, points=500, fuzzy=False, num=1):
    car_object = Car.Car()
    car_object.SetParams(5,int(points))
    res = car_object.Generate2DTrajectory(json.loads(start_pos), json.loads(start_vel), json.loads(start_acc), json.loads(end_pos), json.loads(end_vel), json.loads(end_acc), float(time_ahead), bool(fuzzy), int(num))
    num_feas_traj = int(len(res)/2);
    if (num_feas_traj < 1):
        return 'No feasible trajectories found.'
    helper.create_multi_plot(res[0::2], res[1::2], plot, 'Trajectory', 's [m]', 'd [m]', '')
    helper.create_plot(res[0], res[1], plot+'_best', 'Best Trajectory', 's [m]', 'd [m]', '')
    return str(num_feas_traj) + ' feasible trajectories generated. Type gdisplay ' + plot + ' to display the trajectories or gdisplay ' + plot + '_best to display the lowest cost trajectory.'
Exemplo n.º 2
0
def orb_transfer_lobatto3(mu, m0, Isp, T, r0, days, timestep_hrs, N, plot):
    orb_ins = OrbitTransfer.OrbitTransfer()
    status = orb_ins.run(float(mu), float(m0), float(Isp), float(T), float(r0), float(days), float(timestep_hrs), int(N))
    if (status == 1):
        return 'Max number of iterations exhausted.'

    if (status == 2):
        return 'Collocation scheme failed.  Try decreasing the timestep.'

    ts = orb_ins.getX()
    ys = orb_ins.getY()
    helper.create_plot(ts, ys, plot, 'Orbit Transfer', 'x [km]', 'y [km]', 'r')
    ts = orb_ins.getT()
    ys = orb_ins.getAngle()
    helper.create_plot(ts, ys, plot, 'Steering Control', 't [sec]', 'angle [deg]', 'steering', height=300)

    return 'Orbital transfer plot created. Type gdisplay ' + plot + ' to display the trajectory or gdisplay ' + plot + '_control to display the steering angle'
Exemplo n.º 3
0
def update_graph(make_selected, model_selected, year_selected, trim_selected,
                 mileage_selected, make_selected2, model_selected2,
                 year_selected2, tab):
    show_first_car = {**styles.drop_down_group_style, "display": "block"}
    show_second_car = {**styles.drop_down_group_style, "display": "none"}
    show_graph = {"display": "none"}
    description = html.P()
    show_description = {"display": "none", **styles.description_box_style}
    mileage_box = {**styles.drop_down_style, "display": "none"}
    trim_box = {**styles.drop_down_style, "display": "none"}
    first_vehicle_title = "Select Vehicle"
    fig = go.Figure()
    show_arch_fig = {"display": "none", **styles.arch_fig_style}

    if tab == "tab-1":
        if make_selected and model_selected:
            car = " ".join(
                [str(year_selected or ""), make_selected, model_selected])
            df = data.get_grouped_data(make_selected, model_selected,
                                       year_selected)

            marker = dict(color="#d64161")
            text = [f"Sample size: {cnt}" for cnt in df.Count.tolist()]
            hovertemplate = "<br><i>Mileage Range</i>: %{x} miles<br>" + \
            "<i>Average Price</i>: $%{y}<br>" + "<i>%{text}</i>"

            fig = helper.create_plot("bar",
                                     df.Mileage_range,
                                     df.Average_Price,
                                     error_y=dict(array=df.STD_Price.tolist()),
                                     marker=marker,
                                     text=text,
                                     template=hovertemplate,
                                     title=f"{car} Listing Price",
                                     xaxis_title="Mileage (miles)",
                                     yaxis_title="Average Price ($)",
                                     opacity=0.7)
            desc = helper.generate_description(
                df,
                "#d64161",
                make_selected,
                model_selected,
                year_selected,
                style=styles.description_tablets_style)
            if desc:
                description = [
                    html.Br(),
                    html.Br(), desc,
                    html.
                    P("Hover over the bars to check the sample size. " +
                      "Larger sample size has a higher chance of yielding accurate statistics",
                      style=styles.description_tablets_style)
                ]
                show_description["display"] = "inline-block"
            show_graph["display"] = "block"

    elif tab == "tab-2":
        if all(
            [make_selected, model_selected, make_selected2, model_selected2]):
            df = data.get_grouped_data(make_selected,
                                       model_selected,
                                       year_selected,
                                       make2=make_selected2,
                                       model2=model_selected2,
                                       year2=year_selected2)
            try:
                makemodel1, makemodel2 = df.MakeModel.unique().tolist()
            except ValueError:
                makemodel1 = df.MakeModel.unique().tolist()[0]
                makemodel2 = makemodel1
            car1 = df[df["MakeModel"] == makemodel1]
            car2 = df[df["MakeModel"] == makemodel2]

            name = [makemodel1, makemodel2]
            x = [car1.Mileage_range, car2.Mileage_range]
            y = [car1.Average_Price, car2.Average_Price]
            error_y = [
                dict(array=car1.STD_Price.tolist()),
                dict(array=car2.STD_Price.tolist())
            ]
            marker = [dict(color="rgb(82,188,163)"), dict(color="#d64161")]
            text = [[f"Sample size: {cnt}" for cnt in car1.Count.tolist()],
                    [f"Sample size: {cnt}" for cnt in car2.Count.tolist()]]
            hovertemplate = "<br><i>Mileage Range</i>: %{x} miles<br>" + \
            "<i>Average Price</i>: $%{y}<br>" + "<i>%{text}</i>"

            fig = helper.create_plot("groupbar",
                                     x,
                                     y,
                                     error_y=error_y,
                                     marker=marker,
                                     text=text,
                                     template=hovertemplate,
                                     name=name,
                                     title=f"{makemodel1} vs {makemodel2}",
                                     xaxis_title="Mileage (miles)",
                                     yaxis_title="Average Price ($)",
                                     opacity=0.7)

            desc1 = helper.generate_description(
                car1,
                "rgb(82,188,163)",
                make_selected,
                model_selected,
                year_selected,
                style=styles.description_tablets_style)
            desc2 = helper.generate_description(
                car2,
                "#d64161",
                make_selected2,
                model_selected2,
                year_selected2,
                style=styles.description_tablets_style)
            if desc1 or desc2:
                description = [
                    html.Br(),
                    html.Br(), desc1, desc2,
                    html.
                    P("Hover over the bars to check the sample size. " +
                      "Larger sample size has a higher chance of yielding accurate statistics",
                      style=styles.description_tablets_style)
                ]
                show_description["display"] = "inline-block"
            show_graph["display"] = "block"
        show_second_car = {**styles.drop_down_group_style, "display": "block"}
        first_vehicle_title = "Vehicle 1"

    elif tab == "tab-3":
        if all([
                make_selected, model_selected, year_selected, trim_selected,
                mileage_selected
        ]):
            df = data.get_data(Make=make_selected, Model=model_selected)
            df.sort_values(by="Mileage", inplace=True)
            mileage_per_year = 12000
            mileage_std = df.Mileage.std()
            mileage_std = round(mileage_std / 5000) * 5000

            # Select only the dataframe columns relevant for estimating price
            df = df[["Mileage", "Year", "Price", "clean_trim"]]
            predicted, model, transform, score, trim_columns = estimate.main(
                df, mileage_per_year)

            # A scatter plot of mileage vs price
            marker = dict(color="rgb(82,188,163)")
            text = [
                f"Year: {year}<br>Trim: {trim}"
                for year, trim in zip(df.Year.astype("int"), df.clean_trim)
            ]
            hovertemplate = "<br><i>Mileage</i>: %{x}<br>" + "<i>%{text}</i>" + \
            "<br><i>Price</i>: $%{y}<br>"
            title = f"Regression Estimator: {year_selected} {make_selected} {model_selected}"
            fig = helper.create_plot("scatter",
                                     df.Mileage,
                                     df.Price,
                                     mode="markers",
                                     name="Data points",
                                     marker=marker,
                                     text=text,
                                     template=hovertemplate,
                                     title=title,
                                     xaxis_title="Mileage (miles)",
                                     yaxis_title="Price ($)",
                                     opacity=0.5)

            # Compute estimated average price using the reg. model
            mileage_selected = int(mileage_selected)
            if transform == "std":
                mileage = (mileage_selected - df.Mileage.mean()) / mileage_std
            elif transform == "log":
                mileage = np.log2(mileage_selected)
            trim_columns.remove("clean_trim_Other")
            trim_binary = [
                1 if column.strip("clean_trim_") == trim_selected else 0
                for column in trim_columns
            ]
            estimated = int(
                model.predict(
                    [[mileage,
                      df.Year.max() - year_selected, *trim_binary]])[0])
            print(f"Estimated Price {estimated}")
            print(
                f"R2 on Test {score}",
                f"Mileage coeff = {model.coef_[0]}, Year coff = {model.coef_[1]}",
                f"Other coefs: {model.coef_[2:]}")

            # Show estimate as a scatter plot
            marker = dict(color="#d64161", size=10)
            text = [f"Year: {year_selected}<br>Trim: {trim_selected}"]
            hovertemplate = "<br><i>Mileage</i>: %{x}<br>" + "<i>%{text}</i>" + \
            "<br><i>Estimated Avg. Price</i>: $%{y}<br>"
            helper.create_plot("scatter", [mileage_selected], [estimated],
                               mode="markers",
                               name="Est. Average Price",
                               marker=marker,
                               text=text,
                               template=hovertemplate,
                               title=title,
                               xaxis_title="Mileage (miles)",
                               yaxis_title="Price ($)",
                               base_fig=fig)

            # Generate and plot a 'trend line' using the reg model
            generated_mileage = list(range(0, 150000, mileage_per_year))
            generated_year = [
                int(df.Year.max() - (mileage // mileage_per_year))
                for mileage in generated_mileage
            ]
            text = [f"Year: {year}" for year in generated_year]
            line = dict(color="#d64161", width=3)
            hovertemplate = "<br><i>Mileage</i>: %{x}<br>" + "<i>%{text}</i>" + \
            "<br><i>Estimated Avg. Price</i>: $%{y}<br>"
            helper.create_plot("scatter",
                               generated_mileage,
                               predicted,
                               mode="lines",
                               name="Regression line",
                               text=text,
                               template=hovertemplate,
                               line=line,
                               base_fig=fig)

            description = helper.generate_description(
                df,
                "#d64161",
                make_selected,
                model_selected,
                year_selected,
                model,
                mileage_selected,
                estimated,
                score,
                mileage_std,
                style=styles.description_tablets_style)
            show_description["display"] = "inline-block"
            show_graph["display"] = "block"

        mileage_box = {
            **styles.drop_down_style, "margin-top": "10px",
            "width": "100%",
            "display": "block"
        }
        trim_box = {
            **styles.drop_down_style, "margin-top": "10px",
            "display": "block"
        }
    elif tab == "tab-4":
        description = html.P([
            html.Font("This dashboard provides used car listing price "),
            html.Font("statistics and estimates. Listing prices are scrapped"),
            html.Font(
                " from major car listing websites on a weekly basis. The processed"
            ),
            html.Font(
                "data is stored in S3 and used to build estimation models. "),
            html.Font(
                "The figure on the side shows how the project is setup in AWS. Checkout the "
            ),
            html.A("Github page",
                   href="https://github.com/mEyob/used-car-analytics",
                   target="_blank")
        ],
                             style=styles.description_tablets_style)
        show_arch_fig["display"] = "inline-block"
        show_description["display"] = "inline-block"
        show_first_car["display"] = "none"
        show_second_car["display"] = "none"

    return show_graph, show_description, description, fig, show_first_car, show_second_car, first_vehicle_title, mileage_box, trim_box, show_arch_fig
Exemplo n.º 4
0
def generate_optimal_stop_traj(vel, dist, plot):
    orb_ins = Car.Car()
    orb_ins.SetParams(5,500)
    res = orb_ins.GenerateOptimalStoppingTrajectory([-dist, 0], [vel, 0])
    helper.create_plot(res[0::2], res[1::2], plot, 'Trajectory', 't [s]', 'acceleration control [m/s^2]', 'u(t)')
    return 'Trajectory plot created. Type gdisplay ' + plot + ' to display the trajectory'