Popular Searches

Recommend Opening Slots with Evidence

PythonBeginner
Practice Now

Introduction

A large visitor total does not by itself identify the best opening slot. A high hourly rate from one recording is also a weak basis for a decision. You will apply an explicit exhibition rule to decide which comparisons have enough recorded evidence, keep every tied leader, and communicate the limits alongside a real chart.

This lab assumes the preceding hourly-observation lab or equivalent knowledge of composite keys, missing recordings, hourly rates and coverage, plus basic Python, pandas and Matplotlib. This environment starts independently with original synthetic data and a complete observe.py; it needs no files from your previous environment. The time is an author estimate, not a measured completion time.

Apply an Explicit Evidence Rule

In this step, you will separate eligibility from ranking by implementing a policy function. Open Terminal. Use Results for saved outputs: All files / Refresh reads current files, View opens an available file, and Download returns its original bytes. Missing files stay missing; Results does not compute or redraw anything. Return to Terminal for commands. Opening or reconnecting Terminal does not recreate your workspace.

Run the supplied complete observation program. It is independently prepared here, not copied from your previous environment. The two arguments are input and output directories.

cd /home/labex/project/opening-hours
python3 observe.py data results
cat results/summary.csv

Read the evidence first: morning totals 40 with rate 10; afternoon and evening have rate 12. short has rate 20 from one recorded hour; sparse has three recordings but coverage 0.6. quiet is observed at zero, while unlogged has an unknown rate. Before implementing the rule, predict whether short and sparse should qualify and why.

The exhibition's public training rule requires at least three observed hours and coverage at least 0.75. Equality qualifies: three observations out of four planned open hours meet both boundaries. Rank only eligible slots by visitors per observed hour. Retain all slots within absolute rate difference 1e-9 of the highest eligible rate. The tolerance handles floating-point representation, not meaningful business differences. If no slot qualifies, defer. These are exercise rules, not universal statistical confidence thresholds.

Keep a reason for every slot using this precedence: no_open_hours for zero planned hours; otherwise too_few_observations below three observed hours; otherwise low_coverage below 0.75; otherwise eligible. A slot may violate several conditions, so the order matters. Never remove ineligible rows from the comparison.

Read the prepared source:

cat recommend.py

Trace main: read the summary with slot as its index, call decide, save its returned comparison and decision, call the chart function, and save advice from that same decision. The current decide raises NotImplementedError; it does not invent an initial winner. plot_columns returns None, so chart generation is deliberately postponed until step 2. You will implement these functions, keeping the prepared command-line reading, writing and layout.

summary.copy() makes a separate comparison table. .ge() means greater than or equal to; & combines elementwise conditions. .loc changes matching rows. Setting the weakest reason first and overwriting with higher-priority reasons produces the public precedence. set_index('slot') in the prepared reader gives each stable identity a row label. Subtracting the best rate then using .abs().le(1e-9) selects every tie; sorted stabilizes the displayed identities. None becomes JSON null; json.dumps preserves the list of identities rather than choosing whichever row appears first.

Make a backup with cp, then open nano. The command-local LC_ALL=C.UTF-8 selects UTF-8 for the editor only. In nano, ^ means Ctrl; Ctrl+W, the function name and Enter locate it, Home starts its line, and Ctrl+K cuts one line. Keep four-space Python indentation.

cp recommend.py recommend.py.bak
LC_ALL=C.UTF-8 nano recommend.py

Find def decide, press Home, then cut its two lines with Ctrl+K twice. Replace them with this complete function, leaving the next function intact:

def decide(summary):
    summary = summary.copy()
    summary['eligible'] = summary['observed_hours'].ge(3) & summary['coverage'].ge(0.75)
    summary['reason'] = 'eligible'
    summary.loc[summary['coverage'].lt(0.75), 'reason'] = 'low_coverage'
    summary.loc[summary['observed_hours'].lt(3), 'reason'] = 'too_few_observations'
    summary.loc[summary['planned_hours'].eq(0), 'reason'] = 'no_open_hours'
    candidates = summary.loc[summary['eligible']]
    best = float(candidates['rate'].max()) if len(candidates) else None
    winners = sorted(candidates.index[(candidates['rate'] - best).abs().le(1e-9)].tolist()) if best is not None else []
    decision = {'status': 'compare' if winners else 'defer', 'slots': winners, 'rate': best}
    return summary, decision

Save with Ctrl+O, Enter to confirm the filename, and Ctrl+X to exit. To discard an unwanted unsaved edit, Ctrl+X, N returns without changing the file.

python3 recommend.py results/summary.csv results
cat results/decision.json
{
  "status": "compare",
  "slots": [
    "afternoon",
    "evening"
  ],
  "rate": 12.0
}

Both tied slots remain. short is excluded for too few observations, and sparse for low coverage, matching the prediction. quiet remains eligible at rate zero: quiet is not invalid. If all eligible rates were zero, all eligible slots would tie at zero; if none qualified, the result would be defer, an empty slots list and rate: null.

In Results, refresh and view results/comparison.csv, including every reason. Return to Terminal. The reusable contract is python3 recommend.py SUMMARY_CSV OUTPUT_DIRECTORY; do not hardcode slot names or winners. A missing-file error is a path problem: use pwd and ls, correct the argument and rerun. For syntax or indentation errors, read Python's line number, reopen the affected function, correct it, save and rerun. cp recommend.py.bak recommend.py restores only this starter if needed, after which you must reapply your function; do not restart setup or change the source data.

Self-check: the comparison preserves every slot, qualification happens before ranking, and an empty or zero-rate candidate set has its own correct outcome. The chart is still missing because you have not implemented its data bindings.

Show the Evidence Beside the Recommendation

In this step, you will bind the prepared chart layout to actual totals, rates and recording evidence. Continue in Terminal at /home/labex/project/opening-hours.

The public chart contract has two vertical-bar panels with slot identities as horizontal ticks and vertical labels Total visitors and Visitors per recorded hour. Each slot, including ineligible ones, shows its observed hours and coverage. An unknown numeric value has no numeric bar and is labeled unknown, unlike a genuinely observed zero. Colors, fonts, dimensions and slot order may differ, but unchanged input and the current script must reproduce image pixels. Avoid random styles and timestamps; PNG metadata may differ.

Read draw_comparison in recommend.py: it creates the two axes, uses the columns supplied by plot_columns, draws each actual summary[column], and calls evidence_note for every row and value. zip pairs an axis with a column/unit tuple; iterrows() visits each slot and row, while enumerate supplies its numeric position. .set_xticks binds positions to identities. annotate places text at that value, or at the baseline for an unknown, with a five-point offset. These layout operations are prepared; the choice of data and explanation are yours to implement.

plot_columns will return a list of (column, unit) pairs. evidence_note will return the string for one row and plotted value. An f-string's :.0% formats a fraction as a whole percentage. pd.notna checks whether coverage can be formatted; otherwise use n/a. pd.isna(value) identifies an unknown plotted value; \n puts its unknown marker on a separate line. A recorded zero is not missing.

Keep your working decision stage before editing:

cp recommend.py recommend-decision.py.bak
LC_ALL=C.UTF-8 nano recommend.py

Find def plot_columns, press Home, cut its two lines, and insert:

def plot_columns():
    return [('visitors', 'Total visitors'), ('rate', 'Visitors per recorded hour')]

Find def evidence_note in the same editor, press Home, cut its two lines and insert:

def evidence_note(row, value):
    coverage = f"{row['coverage']:.0%}" if pd.notna(row['coverage']) else 'n/a'
    note = f"n={int(row['observed_hours'])}; cov={coverage}"
    if pd.isna(value):
        note = 'unknown\n' + note
    return note

Save with Ctrl+O, Enter, then Ctrl+X. You have changed the column/unit mapping and actual evidence logic, without recopying the canvas and I/O code.

python3 recommend.py results/summary.csv results

In Results, refresh and view results/comparison.png. Read both panels: morning's higher total does not beat afternoon or evening's rate. short shows n=1; sparse shows cov=60%. quiet is a real zero. unlogged and closed have unknown rates, and closed has cov=n/a. A zero-height rate bar must not substitute for either unknown. Return to Terminal.

cat results/advice.txt
Decision: compare
Slots: afternoon, evening
Evidence: historical description
Effect of extending hours: not established

The prepared advice writer reads the same decision. Its four public fields are Decision (compare or defer), Slots (comma-separated identities or none), Evidence (historical description), and Effect of extending hours (not established). Field and slot order may vary; extra explanation is allowed. This describes historical opportunities under the exercise rule, not a causal effect of changing hours. Collecting missing observations could improve the evidence before a future decision.

To explore a zero-rate comparison and a deferred decision without altering original inputs, use separate practice directories. mkdir -p creates directories if missing. The quoted python3 -c '...' executes a short Python expression as one shell argument; the outer single quotes protect it from shell expansion, and double quotes inside are Python strings. Semicolons separate statements. Both commands read the original counts and write only a practice copy; .iloc[:0] keeps the columns with no data rows.

mkdir -p practice-zero practice-defer
cp data/plan.csv practice-zero/plan.csv
cp data/plan.csv practice-defer/plan.csv
python3 -c 'import pandas as pd; rows = pd.read_csv("data/counts.csv"); rows["visitors"] = 0; rows.to_csv("practice-zero/counts.csv", index=False)'
python3 -c 'import pandas as pd; rows = pd.read_csv("data/counts.csv"); rows.iloc[:0].to_csv("practice-defer/counts.csv", index=False)'
python3 observe.py practice-zero results/zero
python3 recommend.py results/zero/summary.csv results/zero
cat results/zero/decision.json

Every eligible slot ties at zero: afternoon, evening, morning and quiet. Ineligible slots do not become eligible simply because all visitor counts are zero.

python3 observe.py practice-defer results/defer
python3 recommend.py results/defer/summary.csv results/defer
cat results/defer/decision.json

This decision has status: defer, slots: [] and rate: null. Empty recordings are not observed zeros. Practice outputs live in their own subdirectories; the Results reader lists the main required outputs, so use Terminal to read these practice files.

Keep both scripts, original CSVs and the main six analysis files. Rerunning the two programs replaces their outputs without modifying inputs. If an edit breaks the decision stage, cp recommend-decision.py.bak recommend.py restores that stage; reapply the two chart functions in nano, save and rerun. Do not append a second program or repair a plot by rewriting its data.

Self-check: chart values, tick identities, evidence annotations and decision agree on the same input, unknown differs from zero, and both zero and empty-recording variations remain meaningful. The challenge changes the venue while retaining these rules.

Summary

You separated eligibility from ranking, retained all tied leaders, and gave every excluded slot a reason. A pair of real bar charts shows total visitors beside visitors per recorded hour, with observation counts and coverage visible. Unknown rates remain unknown, and the advice states the causal limit of descriptive historical data.

Your scripts can recompute another venue's results. A correct analysis may defer, retain several ties, or compare a genuinely quiet eligible slot; it need not produce a single exciting winner.