
Impressionist painting with thick, textured strokes: a Paris cafe with a red scalloped awning and glowing amber windows, rattan bistro chairs on the wet terrace, an ornate street lamp, and a rainy cobblestone street of Haussmann buildings fading into blue-violet mist, with people under umbrellas and gold and red reflections.
An impressionist painting of a Parisian cafe terrace on a rainy evening, landscape 4:3, with thick, visible, textured brushstrokes like an oil or pastel painting. On the left, a cafe with a large red scalloped awning glows from within through tall amber windows, with two round potted green shrubs by the facade. Small round bistro tables with woven rattan chairs stand on the wet pavement in the foreground. In the center, an ornate black street lamp with a glowing lantern rises above the curb. On the right, a long wet cobblestone street recedes into a misty blue-violet distance between tall Haussmann-style buildings dotted with small warm lights. A person in a brown coat holding a dark umbrella walks away from the viewer down the street, with two more figures under umbrellas further back. Rain falls softly, and the glossy cobblestones are full of broken reflections of gold, amber, and red. Blue-violet dusk sky, warm light against cool shadows, romantic and quiet mood. No readable signs, no text, no logos.
Animate the step 2 floating market image as the first frame into a calm 6-second shot: vendors in conical straw hats paddle and the fruit-laden boats glide slowly toward the camera, gentle wakes and ripples spread and reflections shimmer, more small boats appear far back in the misty canal, and golden mist drifts between the palms with a very slight push-in. Step 3 of the Floating Market at Sunrise workflow.
Start from the step 2 image "Floating Market Boats Laden with Tropical Fruit on a Misty Canal at Sunrise" as the exact first frame, and animate it into a calm 6-second cinematic shot. Keep the weathered stilt house with its rusty tin roof and potted plants on the left bank, the coconut palms and tropical greenery on both banks, the brown-green canal, the wooden boats with their vendors in conical straw hats, the bananas, pineapples, limes, mangoes, and dragon fruit on each boat, the golden backlight from the top right, and the composition exactly as in the image. The vendors paddle steadily with wooden paddles, and the boats glide slowly forward toward the camera, keeping roughly their formation. Gentle ripples and wakes spread across the water around each boat, and the reflections shimmer. As the scene settles, a few more small boats become visible further back in the misty canal. Golden morning mist drifts slowly between the palms, while the camera makes a very slight, steady push-in. The shot ends calm in warm sunrise light. Natural, realistic motion, no cuts, no text, no signs. Soft sound of paddles dipping into the water, quiet lapping of small waves, and distant birdsong.
Photoreal sunrise scene: five long wooden boats piled with bananas, pineapples, limes, mangoes, pomelos, and pink dragon fruit, each paddled by a vendor in a conical straw hat, on a calm brown-green canal with a rusty-roofed wooden stilt house on the left bank, coconut palms on both banks, golden morning mist, and soft backlight on the water. Step 2 of the Floating Market at Sunrise workflow.
Long wooden boats piled with tropical fruit gliding along a calm, misty canal at a floating market at sunrise, seen from eye level on the water looking straight down the canal, in a wide landscape 16:9 frame. On the left bank stands a weathered wooden stilt house with a rusty corrugated tin roof and a balcony with railings full of potted plants, above lush green bushes. Tall coconut palms and dense tropical greenery line both banks and fade into soft golden morning mist in the distance. Five long, narrow wooden boats are on the brown-green water, each paddled by one woman vendor in a conical straw hat and a long-sleeve patterned shirt: the front-left boat carries yellow bananas, green mangoes and limes, and pink dragon fruit; the front-center boat carries golden pineapples and big green pomelos and coconuts; the front-right boat is piled with green limes and yellow mangoes; two smaller boats further back in the center carry pineapples and mixed fruit; and one tiny boat sits far away in the mist. Soft golden backlight comes from the top right, with warm reflections and gentle wakes on the water. Photoreal travel and documentary photography, natural colors, peaceful, warm, and timeless mood. No text, no signs, no logos.
Turn a short idea into an image-ready and motion-ready brief for one hero shot of a floating market at sunrise: vendors in conical straw hats paddling long wooden boats piled with tropical fruit along a calm, misty canal lined with palms and a stilt house. Covers the boats and vendors, fruit cargo, canal and reflections, banks, mist and light, fixed details, a motion map, and two prompt seeds: a 16:9 still image and an image-to-video animation.
Act as a cinematic travel scene designer who writes image-ready and motion-ready scene briefs. Help me design one hero shot of a floating market at sunrise: long wooden boats piled with tropical fruit gliding along a calm, misty canal lined with palms and a wooden stilt house. The shot will first be generated as a still image and then animated into a short video that uses that image as its first frame. Your brief must make the still image rich in elements that can move naturally (vendors paddling, boats gliding slowly, soft wakes and ripples, golden mist drifting between the palms, light shimmering on the water) while keeping the composition calm, balanced, readable, and easy to animate. My starting idea: a quiet floating market at sunrise, with women vendors in conical straw hats paddling wooden boats full of fruit along a misty tropical canal My starting choices: - Boats: five long, narrow wooden boats, each with one vendor, three in the foreground and two smaller ones further back, plus one tiny boat far away in the mist - Cargo: bananas, pineapples, green mangoes, limes, pomelos, coconuts, and pink dragon fruit piled high - Vendors: women in conical straw hats and long-sleeve patterned shirts, holding wooden paddles - Canal: a calm brown-green canal running straight away from the camera into the distance - Left bank: a weathered wooden stilt house with a rusty corrugated tin roof and a balcony full of potted plants - Banks and trees: tall coconut palms and dense tropical greenery on both banks, fading into the mist - Time and light: just after sunrise, soft golden backlight from the top right, warm haze - Visual style: photoreal travel and documentary photography, natural colors - Mood words: peaceful, warm, lively but unhurried, timeless First ask me, in one short message, for anything missing: the camera height (water level, eye level from a boat, or a little above), how many boats and vendors I want and how close the nearest ones are, which fruits must be visible, how thick the mist should be, whether the boats should glide toward the camera or across the frame in the video, whether more boats may appear in the distance as the shot settles, and anything to avoid (signs, text, logos, motors, modern clothing, brand packaging, recognizable faces, or copying a specific real market, photograph, or named landmark). Then produce the brief with these sections: 1. **Scene Overview**: two or three sentences on the place, the moment, the light, and the feeling. Describe an imagined floating market in the spirit of a tropical river delta, not a copy of a specific real market or a famous photograph. 2. **The Boats and Vendors**: how many boats, their shape and wood, their positions in the frame, how they are spaced, each vendor's hat, clothing, and pose, and the paddles. 3. **The Fruit Cargo**: what each boat carries, how it is piled, the colors that should stand out (yellow bananas, pink dragon fruit, green limes and mangoes, golden pineapples), and how the light catches it. 4. **The Canal and Reflections**: the water color, how calm it is, the soft wakes and reflections around the boats, and where the water catches the golden light. 5. **Banks, Stilt House, and Palms**: the stilt house on the left bank with its tin roof, balcony, and potted plants, the palms and greenery on both banks, and how they fade into the distance. 6. **Mist and Light**: how thick the morning mist is, where it lies (between the palms, over the far canal, softening the background), the direction and warmth of the backlight, and how it should read as soft morning haze rather than smoke. 7. **Fixed Visual Details**: a numbered list of 8 to 10 details that must stay identical in the still image and in the video (camera position, canal line, stilt house on the left bank, palm lines, boat count and order, vendors and hats, fruit on each boat, light direction, framing, mist zone). 8. **Motion Map**: a table of every element that can move in the video, with columns: element, type of motion, direction, speed (very slow, slow, medium), and how strongly it should move. Include the paddles and the vendors' arms, the boats gliding forward, the wakes and ripples, the shimmering reflections, the mist, palm fronds swaying slightly, any small boats appearing far back, and the camera move. Keep total motion subtle and physically plausible. 9. **Prompt Seed A - Hero Still Image**: a ready-to-paste image prompt under 170 words for a wide landscape 16:9 frame, with the fruit-laden wooden boats, the vendors in conical hats, and the misty canal at sunrise in the first sentence, ending with: no text, no signs, no logos. 10. **Prompt Seed B - Image-to-Video Animation**: a ready-to-paste video prompt under 120 words that starts from the hero still as the first frame, describes the vendors paddling and the boats gliding slowly toward the camera for about 6 seconds, gentle wakes and ripples spreading, reflections shimmering, golden mist drifting between the palms, a very slight camera push-in, and says to keep the stilt house, banks, palms, boats, fruit, and framing exactly as in the image with no new close-up objects. Rules: no text, signs, or logos; no motorboats, phones, or modern brand packaging; no fast camera moves or cuts; and no motion that breaks physics (boats move only in the direction they are paddled and keep their shape and cargo, paddles enter and leave the water with small splashes, wakes spread outward and fade, the stilt house and banks never move, mist drifts slowly and does not swirl violently, the light does not flicker or jump). Use short paragraphs and lists.

Risograph travel poster in sunflower yellow, fluorescent pink, teal, and navy: about seventeen patterned hot air balloons (stripes, zigzags, polka dots, a checkerboard) over cone-shaped fairy chimney rock towers with glowing cave windows, a big pink sun behind teal hills, with paper grain, halftone speckle, and slight misregistration.
A risograph print poster of hot air balloons drifting over the fairy chimneys of Cappadocia at sunrise, vertical portrait 3:4. Limited ink palette of sunflower yellow, fluorescent pink, teal, and deep navy on uncoated paper. The whole sky is flat sunflower yellow. About seventeen hot air balloons of different sizes float across the upper two thirds, near and far, each with a small basket below: some with horizontal pink and navy stripes, some with vertical stripes, zigzag and chevron bands, navy polka dots, and one with a navy-and-yellow checkerboard pattern; the largest navy balloon with pink stripes sits near the top center. A large fluorescent pink sun disc sits low on the left behind rolling teal hills. The lower third is filled with tall cone-shaped fairy chimney rock towers in navy, teal, pink, and yellow, carved with many small square and arched cave windows and doorways, a few glowing yellow, the tallest on the right. Teal hills and a valley stretch behind them, and dark teal shrubs fill the bottom edge. Visible paper grain, halftone speckle, overprinted inks, and slight color misregistration, a bold, cheerful, retro travel poster feel. No text, no logos.
Splits a CSV ledger of shared costs for a trip, flat or event - equal, shares, exact, percent and itemized bills with tax/tip pro rata, 'all except' exclusions, several payers, refunds, repayments and multiple currencies at agreed rates - in cents, then finds the provably fewest settle-up transfers (exact zero-sum subgroup search). Returns balances, a per-person audit and a chat message. Includes a stdlib Python planner with --self-test.
---
name: shared-expense-bill-splitter-and-settle-up-planner
description: Splits a CSV ledger of shared costs for a trip, flat or event - equal, shares, exact, percent and itemized bills with tax/tip pro rata, 'all except' exclusions, several payers, refunds, repayments and multiple currencies at agreed rates - in cents, then finds the provably fewest settle-up transfers (exact zero-sum subgroup search). Returns balances, a per-person audit and a chat message. Includes a stdlib Python planner with --self-test.
---
# Shared Expense Bill Splitter and Settle-Up Planner
You turn a messy list of shared spending into a fair, checkable split and the shortest possible list of payments. You keep the ledger as a CSV the group can edit in any spreadsheet, apply the split rule each line really needs (who was there, who ordered what, who stayed fewer nights), convert currencies at rates the group agrees on, and settle everyone with the fewest transfers. Every cent is accounted for, and anyone can trace their own number line by line.
## Files in this skill
- `scripts/settle_up.py` - reads the CSV ledger, splits each line in integer cents (largest-remainder rounding), computes paid/share/net per person, and searches all zero-sum subgroups to find the minimum number of transfers (exact up to 18 people with a balance, greedy beyond) (Python 3.8+ standard library only)
- `references/split-methods.md` - the CSV format, which split to use for which cost, itemized bills with tax and tip, exclusions, payers, refunds and repayments
- `references/settle-up-and-currency.md` - why the minimum can be below "people - 1", how the search works, rounding, exchange rates and card fees, payment etiquette
- `templates/settle-up-summary.md` - the summary to hand back and paste into the group chat
- `examples/lisbon-trip.csv` - 5 friends, 11 lines: shares by nights, an excluded person, an itemized dinner, a USD booking, premium seats, two payers, a refund, GBP snacks and a repayment already made
- `examples/lisbon-settle-output.md` - the real output of the planner on that ledger
- `examples/flat-october.csv` - 6 flatmates where the minimum (4 transfers) beats paying largest debt to largest credit (5)
## Workflow
### 1. Collect the ledger
Ask for every shared cost with: what, who paid (and how much each, if several people paid), the amount and currency, and who it was for. Ask the questions that change the split: Did anyone arrive late or leave early? Did anyone skip a meal or an activity? Was a dinner shared or ordered individually? Has anyone already paid someone back? Agree the base currency and the rates (one rate per currency for the whole trip unless the group wants card statement rates). Write it as the CSV in `references/split-methods.md`, with `# people:` so typos in names are caught.
### 2. Run the planner
```
python3 scripts/settle_up.py examples/lisbon-trip.csv
python3 scripts/settle_up.py flat.csv --base GBP --rates EUR=0.86 --detail Ben
python3 scripts/settle_up.py ledger.csv --json
python3 scripts/settle_up.py --self-test
```
Exit 0 = plan printed (read the Warnings section), 2 = the ledger has an error (sums that do not match, missing rate, unknown split or name) - fix the line it names. If you cannot run code, follow the same steps by hand: convert each line to base cents, split, sum paid minus share per person, then match debtors to creditors, looking first for people or small groups whose balances cancel exactly.
### 3. Check the result with the group
- The check line must read `nets add up to 0.00`; paid and shares must be equal.
- Read the balances aloud in plain words ("Ana paid 990.00, her share is 377.31 and Eli already gave her 100.00, so she gets back 512.69").
- Point out lines that drive the result and are easy to dispute (shares by nights, itemized meals, a refund, a repayment), and offer `--detail <name>` for anyone who wants their own breakdown.
- If someone prefers to pay someone else (or cannot pay a person directly), rerun after adding the agreed transfer as a `payment` line; the plan recomputes the rest.
### 4. Deliver
Fill `templates/settle-up-summary.md`: totals, the balances table, the numbered transfers, the assumptions (rates, who was excluded where, how tax/tip was spread), and the short group-chat message. Suggest marking each transfer as done by adding it to the ledger as a `payment` line, so a second run shows everyone at 0.00.
## Example result
On `examples/lisbon-trip.csv` (5 people, 1,583.07 EUR spent) Ana paid the apartment and the fado tickets and gets back 512.69 EUR; the plan is 4 transfers: Ben pays Ana 243.17, Dara pays Ana 140.94, Eli pays Ana 128.58 and Eli pays Cem 0.85 (Eli's earlier 100.00 repayment is already counted). On `examples/flat-october.csv` Bo and Finn cancel each other out, so 6 flatmates settle in 4 transfers where paying largest debt to largest credit would take 5.
## Rules
- Never invent amounts, rates or who took part; ask, or mark the line as an assumption in the summary.
- Use one agreed rate per currency and show it; do not mix live rates into a finished split.
- Keep all arithmetic in cents and show where rounding cents went (largest remainder, ties to the person listed first).
- Do not judge spending; flag only lines that look like duplicates, typos or missing participants.
- A repayment is a `payment` line, never a negative expense; a refund is a negative expense shared by the same people as the original cost.
- Present the plan as a proposal; the group can swap who pays whom as long as each person's net is unchanged.
FILE:references/split-methods.md
# Split methods and CSV format
## Columns
`date,description,paid_by,amount,currency,split,participants,details` - header row required; any spreadsheet can export it. Optional comment lines before the header:
```
# people: Ana, Ben, Cem, Dara, Eli (strict list: a misspelt name is an error)
# base: EUR
# rates: USD=0.92, GBP=1.16 (1 USD = 0.92 EUR)
```
Without `# people:` everyone named anywhere in the file is a member and `all` means all of them; names are matched case-insensitively.
## Choosing a split
| Cost | Split | Example `participants` / `details` |
|---|---|---|
| Groceries, taxi, fuel, shared tickets | `equal` | `all`, `Ana;Ben`, `all-Eli` |
| Accommodation when people stayed different nights, rooms of different size | `shares` | `Ana:3;Ben:3;Dara:2` (nights or room weights) |
| Tickets with different prices, a known per-person amount | `exact` | `Ana:30;Ben:45` (others in participants split the rest equally) |
| Agreed percentages (rent by income, wine for those who drank) | `percent` | `Ana:25;Ben:25;Dara:50` (must total 100) |
| Restaurant bill where people ordered separately | `itemized` | `Ana:31;Ben:28.50;shared:42` |
| Someone already paid someone back | `payment` | participants = the one recipient |
## Itemized bills
- `details` lists each person's items before tax, service and tip; `shared` is the sum of starters, bottles or anything everyone shared (split equally among `participants`).
- `amount` is the final bill. The difference (amount - items) is tax, service and tip, spread in proportion to what each person had, so a person who ordered more pays more tip. The output shows it as `+17.3% tax/tip`.
- If the items add up to more than the bill (a discount or a typo), the planner stops; enter the discount by lowering the item prices it applied to.
## Exclusions and partial participation
- `all-Eli` or `all except Eli` = everyone but Eli; chain several: `all-Bo-Finn`.
- For people present part of the time, use `shares` with nights or days instead of excluding them.
- A child or a guest paid for by one member: list them under the member's name (`shares` weight 1.5) or add them to `# people:` and settle with their parent.
## Payers
- One payer: `Ana`. Several payers on one bill: `Ben:40;Cem:20` (amounts in the row currency, must add up to `amount`).
- A card shared by a couple: treat the couple as one person or split the payer amount.
## Refunds, deposits, repayments
- Refund received after a cancellation: negative `amount`, `paid_by` = who received the money, same participants as the original cost.
- Deposit returned by a landlord: negative `amount` split the same way as the deposit.
- Money handed over between members: `payment` (from `paid_by` to the one person in `participants`). Record settle-up transfers the same way; rerunning then shows who is still open.
## Common mistakes the planner catches
- Exact amounts or percentages that do not add up, payer amounts that differ from the bill, items over the bill.
- A currency without a rate, an unknown split word, a misspelt name when `# people:` is set.
- Two identical lines (same date, description, amount and payer) - reported as a warning, not removed.
- Zero amounts - skipped with a warning.
FILE:references/settle-up-and-currency.md
# Settle-up and currency
## Net balance
For every person: `net = paid + payments sent - share - payments received`. Positive = gets money back, negative = owes. The nets always add up to exactly 0.00 because every line is split in integer cents that sum to the line total.
## Why "fewest transfers" can be less than people - 1
- Any group with k people who have a balance can settle in at most k - 1 transfers (each transfer clears at least one person).
- If the group splits into subgroups whose balances each add up to zero, each subgroup settles on its own: with g such subgroups the minimum is k - g. Example: Bo +300 and Finn -300 cancel, so 6 flatmates need 4 transfers, not 5.
- Paying the largest debt to the largest credit (the usual app approach) does not look for these subgroups and can take more transfers.
- Finding the best split into zero-sum subgroups is a hard problem in general; the planner solves it exactly for up to 18 people with a non-zero balance (dynamic programming over subsets, under a second) and falls back to the greedy plan above that, saying so.
- Within each subgroup the plan pays largest debt to largest credit, which uses exactly (subgroup size - 1) transfers.
- Several plans can have the same minimum count; any of them is fair, because each person's total in or out is fixed by their net.
## Rounding
- Each line is converted to base cents once (`amount x rate`, rounded half up), then split with the largest-remainder method: everyone gets the rounded-down amount, and the leftover cents go to the largest fractions, ties to the person listed first in `# people:`.
- Over a whole trip this moves at most a few cents per person; say so if someone asks why 10.00 / 3 is 3.34 for one person.
## Exchange rates
- Agree one rate per currency before splitting: the rate on the day most costs were paid, the average of the trip, or the rate on the payer's card statement (which includes the bank's markup).
- If the payer's card charged a foreign transaction fee, either include it in the amount (the group shares it) or leave it out (the payer absorbs it) - decide once for the whole trip.
- Enter amounts in the currency actually paid and let the planner convert; do not pre-convert some lines by hand.
- Settle in the base currency. If someone pays in another currency, convert the transfer at the same agreed rate and record it as a `payment` line in that currency.
## Payment etiquette
- Send the group-chat message with the transfers and a link to the ledger; give people a day or two to dispute a line before paying.
- Small transfers (under ~2 EUR/USD) can be waived or rolled into the next shared cost if both people agree - record that as a `payment` line so the ledger stays exact.
- When everyone has paid, add each transfer as a `payment` line and rerun: every net should be 0.00.
FILE:templates/settle-up-summary.md
# Settle-up: <trip / flat / event>, <dates>
**Group:** <Ana, Ben, Cem, Dara, Eli> **Base currency:** <EUR> **Total spent:** <1,583.07 EUR> over <11> lines
**Rates agreed:** <1 USD = 0.92 EUR, 1 GBP = 1.16 EUR (trip average)>
## Balances
| Person | Paid | Fair share | Already sent / received | Net |
|---|---|---|---|---|
| <Ana> | <990.00> | <377.31> | <received 100.00> | <+512.69 gets back> |
| <Ben> | <64.00> | <307.17> | <-> | <-243.17 owes> |
## Transfers (<n>, the minimum possible)
1. <Ben pays Ana 243.17 EUR>
2. <Dara pays Ana 140.94 EUR>
3. <...>
## How lines were split
- <Apartment: by nights, Dara and Eli 2 of 3 nights>
- <Airport taxi: everyone except Eli (came by train)>
- <Dinner: itemized, 17.3% tax and tip spread by what each person ordered; starters 42.00 shared>
- <Palace tickets refund: back to Ben and Cem, who paid for them>
- <Eli's 100.00 to Ana is already counted>
## Assumptions and open points
- <rates above; card fees not included>
- <check line 5 (surf lesson): was Ben in?>
## Group chat message
```
Settle-up (<EUR>, <11> lines, rates: <USD 0.92, GBP 1.16>):
- <Ben -> Ana: 243.17 EUR>
- <Dara -> Ana: 140.94 EUR>
Full table: <link to the sheet>. Shout within 2 days if a line is wrong.
```
**When paid:** add each transfer as a `payment` line and rerun - every net should read 0.00.
FILE:examples/lisbon-trip.csv
# people: Ana, Ben, Cem, Dara, Eli
# base: EUR
# rates: USD=0.92, GBP=1.16
date,description,paid_by,amount,currency,split,participants,details
2026-10-02,Apartment 3 nights (Dara and Eli 2 nights),Ana,840.00,EUR,shares,all,Ana:3;Ben:3;Cem:3;Dara:2;Eli:2
2026-10-02,Airport taxi (Eli came by train),Ben,48.00,EUR,equal,all-Eli,
2026-10-02,Groceries for the flat,Eli,63.75,EUR,equal,all,
2026-10-03,Dinner at Taberna do Mar,Cem,212.40,EUR,itemized,all,Ana:31;Ben:28.50;Cem:24;Dara:36;Eli:19.50;shared:42
2026-10-03,Surf lesson (booked on a US site),Dara,180.00,USD,equal,Ana;Dara;Eli,
2026-10-03,Fado tickets (premium seats for Dara and Eli),Ana,150.00,EUR,exact,all-Cem,Ana:30;Ben:30;Dara:45;Eli:45
2026-10-04,Train to Sintra,Ben:40;Cem:20,60.00,EUR,equal,all,
2026-10-04,Wine for the flat,Dara,36.00,EUR,percent,,Ana:25;Ben:25;Dara:50
2026-10-04,Palace tickets refunded (rain),Ben,-24.00,EUR,equal,Ben;Cem,
2026-10-05,Snacks at the London layover,Cem,27.00,GBP,equal,all,
2026-10-05,Eli paid Ana back for the apartment,Eli,100.00,EUR,payment,Ana,
FILE:examples/lisbon-settle-output.md
# Settle-up plan
Base currency: EUR People: 5 Lines: 11 Total spent: 1,583.07 EUR
Rates used: 1 GBP = 1.16 EUR, 1 USD = 0.92 EUR
## Expenses
| # | Date | What | Paid by | Amount | In EUR | Split | Among |
|---|---|---|---|---|---|---|---|
| 1 | 2026-10-02 | Apartment 3 nights (Dara and Eli 2 nights) | Ana | 840.00 EUR | 840.00 | shares | all |
| 2 | 2026-10-02 | Airport taxi (Eli came by train) | Ben | 48.00 EUR | 48.00 | equal | Ana, Ben, Cem, Dara |
| 3 | 2026-10-02 | Groceries for the flat | Eli | 63.75 EUR | 63.75 | equal | all |
| 4 | 2026-10-03 | Dinner at Taberna do Mar | Cem | 212.40 EUR | 212.40 | itemized (+17.3% tax/tip) | all |
| 5 | 2026-10-03 | Surf lesson (booked on a US site) | Dara | 180.00 USD | 165.60 | equal | Ana, Dara, Eli |
| 6 | 2026-10-03 | Fado tickets (premium seats for Dara and Eli) | Ana | 150.00 EUR | 150.00 | exact | Ana, Ben, Dara, Eli |
| 7 | 2026-10-04 | Train to Sintra | Ben 40.00, Cem 20.00 | 60.00 EUR | 60.00 | equal | all |
| 8 | 2026-10-04 | Wine for the flat | Dara | 36.00 EUR | 36.00 | percent | Ana, Ben, Dara |
| 9 | 2026-10-04 | Palace tickets refunded (rain) | Ben | -24.00 EUR | -24.00 | equal | Ben, Cem |
| 10 | 2026-10-05 | Snacks at the London layover | Cem | 27.00 GBP | 31.32 | equal | all |
| 11 | 2026-10-05 | Eli paid Ana back for the apartment | Eli | 100.00 EUR | 100.00 | payment | to Ana |
## Balances
| Person | Paid | Share | Sent | Received | Net |
|---|---|---|---|---|---|
| Ana | 990.00 | 377.31 | 0.00 | 100.00 | 512.69 (gets back) |
| Ben | 64.00 | 307.17 | 0.00 | 0.00 | -243.17 (owes) |
| Cem | 263.72 | 262.87 | 0.00 | 0.00 | 0.85 (gets back) |
| Dara | 201.60 | 342.54 | 0.00 | 0.00 | -140.94 (owes) |
| Eli | 63.75 | 293.18 | 100.00 | 0.00 | -129.43 (owes) |
Check: nets add up to 0.00 (paid 1,583.07 = shares 1,583.07).
## Transfers (4)
1. Ben pays Ana **243.17 EUR**
2. Dara pays Ana **140.94 EUR**
3. Eli pays Ana **128.58 EUR**
4. Eli pays Cem **0.85 EUR**
Minimum possible: 4 transfers for 5 people with a balance (no smaller subgroup evens out on its own).
## Message for the group chat
```
Settle-up (EUR, 11 lines, rates: GBP 1.16, USD 0.92):
- Ben -> Ana: 243.17 EUR
- Dara -> Ana: 140.94 EUR
- Eli -> Ana: 128.58 EUR
- Eli -> Cem: 0.85 EUR
Full table in the shared sheet. Shout within 2 days if a line is wrong.
```
FILE:examples/flat-october.csv
# people: Asha, Bo, Chen, Dev, Ema, Finn
# base: EUR
date,description,paid_by,amount,currency,split,participants,details
2026-10-01,Festival tickets for Bo and Finn,Bo,600,EUR,exact,Bo;Finn,Bo:300;Finn:300
2026-10-31,October groceries (Bo and Finn on tour),Asha,800,EUR,equal,all-Bo-Finn,
2026-10-31,Electricity Sep-Oct (Bo and Finn on tour),Chen,600,EUR,equal,all-Bo-Finn,
2026-10-20,Second-hand sofa (Dev and Ema's part),Asha,250,EUR,exact,Dev;Ema,Dev:150;Ema:100
FILE:scripts/settle_up.py
#!/usr/bin/env python3
"""Shared expense bill splitter and settle-up planner (Python 3.8+ standard library only).
Reads a CSV ledger of shared costs (a trip, a flat, an event), splits every line in
integer cents, and finds the SMALLEST possible number of transfers that settles the group
(exact search over zero-sum subgroups, not just "at most people - 1").
CSV columns (header row required, extra columns ignored):
date,description,paid_by,amount,currency,split,participants,details
paid_by Ana one payer
Ana:40;Ben:20 several payers (amounts in the row currency, must add up)
amount total in the row currency; negative = refund received by paid_by
currency blank = base currency
split equal | shares | exact | percent | itemized | payment
participants all | Ana;Ben;Cem | all-Eli (everyone except Eli) | blank = names in details
details shares: Ana:3;Ben:2 (people in participants but not listed get 1)
exact: Ana:30;Ben:45 (rest, if any, split equally among the other participants)
percent: Ana:50;Ben:30;Cem:20 (must total 100)
itemized: Ana:18;Ben:22.50;shared:12 (item prices before tax/tip; "shared"
items are split equally; amount - items = tax/service/tip, split in
proportion to what each person ordered)
payment: (none) paid_by gave `amount` to the one person in participants
Comment lines at the top set the group and the rates (or use the CLI flags):
# people: Ana, Ben, Cem
# base: EUR
# rates: USD=0.92, GBP=1.16 (1 unit of that currency = rate units of base)
Usage:
python3 settle_up.py ledger.csv [--base EUR] [--rates USD=0.92,GBP=1.16] [--people Ana,Ben]
[--detail Ana] [--json]
python3 settle_up.py --self-test
Exit codes: 0 = settled plan printed, 2 = bad input (unknown split, sums that do not
match, missing exchange rate, unknown person in a strict list).
"""
import argparse
import csv
import io
import json
import re
import sys
from decimal import Decimal, ROUND_HALF_UP, InvalidOperation
MAX_EXACT = 18 # people with a non-zero balance for the exact minimum search (2^18 states)
SPLITS = ("equal", "shares", "exact", "percent", "itemized", "payment")
class LedgerError(ValueError):
pass
def dec(s, what):
try:
return Decimal(str(s).replace(",", "").strip())
except (InvalidOperation, AttributeError):
raise LedgerError("%s: %r is not a number" % (what, s))
def to_cents(amount):
return int((amount * 100).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
def fmt(cents, cur=""):
sign = "-" if cents < 0 else ""
c = abs(cents)
s = "%s%d.%02d" % (sign, c // 100, c % 100)
s = re.sub(r"(\d)(?=(\d{3})+\.)", r"\1,", s)
return (s + " " + cur).strip()
def allocate(total, weights, order):
"""Split integer `total` cents in proportion to `weights` (dict name -> Decimal >= 0).
Largest remainder method; ties go to the earlier name in `order`. Sum is exact."""
names = [n for n in order if n in weights]
wsum = sum(weights[n] for n in names)
if wsum <= 0:
raise LedgerError("weights add up to zero")
sign = -1 if total < 0 else 1
t = abs(total)
raw = {n: Decimal(t) * weights[n] / wsum for n in names}
base = {n: int(raw[n]) for n in names}
left = t - sum(base.values())
rank = sorted(names, key=lambda n: (-(raw[n] - base[n]), order.index(n)))
for n in rank[:left]:
base[n] += 1
return {n: sign * v for n, v in base.items() if v}
def parse_pairs(text, what):
out = {}
for part in [p for p in re.split(r"[;|]", text or "") if p.strip()]:
if ":" not in part:
raise LedgerError("%s: %r should look like Name:value" % (what, part.strip()))
k, v = part.split(":", 1)
k = k.strip()
out[k] = out.get(k, Decimal(0)) + dec(v, what)
return out
class Ledger:
def __init__(self, text, base=None, rates=None, people=None):
self.warnings = []
self.base = base
self.rates = {}
self.people = []
self._canon = {}
header_people = None
body = []
for line in text.splitlines():
s = line.strip()
if s.startswith("#"):
m = re.match(r"#\s*(people|base|rates?)\s*:\s*(.*)$", s, re.I)
if m:
key, val = m.group(1).lower(), m.group(2)
if key == "people":
header_people = [p.strip() for p in re.split(r"[,;]", val) if p.strip()]
elif key == "base" and not self.base:
self.base = val.strip().upper()
elif key.startswith("rate"):
self._add_rates(val)
continue
body.append(line)
self.base = (self.base or "EUR").upper()
if rates:
self._add_rates(rates)
self.rates[self.base] = Decimal(1)
for p in (people or header_people or []):
self._person(p, declare=True)
self.strict = bool(people or header_people)
rows = list(csv.DictReader(io.StringIO("\n".join(body))))
if not rows:
raise LedgerError("no expense rows found (need a header row and at least one line)")
need = {"description", "paid_by", "amount", "split"}
cols = {c.strip().lower() for c in rows[0].keys() if c}
if not need <= cols:
raise LedgerError("missing CSV columns: %s" % ", ".join(sorted(need - cols)))
self.rows = []
for r in rows:
r = {(k or "").strip().lower(): (v or "").strip() for k, v in r.items()}
if not any(r.values()):
continue
self.rows.append(r)
# first pass: learn every name when no people list was given
if not self.strict:
for r in self.rows:
for p in self._names_in(r):
self._person(p, declare=True)
self.lines = [self._line(n, r) for n, r in enumerate(self.rows, 1)]
self._check_duplicates()
# -- people and rates
def _add_rates(self, text):
for part in re.split(r"[,;]", text):
if not part.strip():
continue
if "=" not in part:
raise LedgerError("rate %r should look like USD=0.92" % part.strip())
k, v = part.split("=", 1)
r = dec(v, "rate " + k.strip())
if r <= 0:
raise LedgerError("rate for %s must be positive" % k.strip())
self.rates[k.strip().upper()] = r
def _person(self, name, declare=False):
key = name.strip().lower()
if not key:
raise LedgerError("empty person name")
if key in self._canon:
canon = self._canon[key]
if canon != name.strip() and declare:
self.warnings.append("'%s' and '%s' treated as the same person" % (canon, name.strip()))
return canon
if not declare:
raise LedgerError("unknown person %r (not in the people list)" % name.strip())
self._canon[key] = name.strip()
self.people.append(name.strip())
return name.strip()
def _names_in(self, r):
names = []
pb = r.get("paid_by", "")
names += list(parse_pairs(pb, "paid_by").keys()) if ":" in pb else [pb]
part = r.get("participants", "")
if part and not part.lower().startswith("all"):
names += [p for p in re.split(r"[;|]", part) if p.strip()]
if r.get("split", "").lower() != "payment":
names += [k for k in parse_pairs(r.get("details", ""), "details") if k.lower() != "shared"]
return [n for n in names if n.strip()]
def _participants(self, r, ln):
part = r.get("participants", "").strip()
if not part:
return None
if part.lower().startswith("all"):
rest = part[3:].strip()
excl = []
if rest:
rest = re.sub(r"^(except|but|without)\s+", "", rest.lstrip("-").strip(), flags=re.I)
excl = [self._person(x) for x in re.split(r"[-;|,]", rest) if x.strip()]
return [p for p in self.people if p not in excl]
return [self._person(p) for p in re.split(r"[;|]", part) if p.strip()]
# -- one CSV line -> paid / share in base cents
def _line(self, ln, r):
desc = r.get("description") or "line %d" % ln
where = "line %d (%s)" % (ln, desc)
split = (r.get("split") or "equal").lower()
if split not in SPLITS:
raise LedgerError("%s: unknown split %r (use %s)" % (where, split, ", ".join(SPLITS)))
cur = (r.get("currency") or self.base).upper()
if cur not in self.rates:
raise LedgerError("%s: no exchange rate for %s (add '# rates: %s=...' or --rates)" % (where, cur, cur))
amount = dec(r.get("amount"), where + " amount")
if amount == 0:
self.warnings.append("%s has amount 0 and was skipped" % where)
total = to_cents(amount * self.rates[cur])
# payers
pb = r.get("paid_by", "")
if ":" in pb:
pays = {self._person(k): v for k, v in parse_pairs(pb, where + " paid_by").items()}
if sum(pays.values()) != amount:
raise LedgerError("%s: payers add up to %s but amount is %s" % (where, sum(pays.values()), amount))
paid = allocate(total, {k: abs(v) for k, v in pays.items()}, self.people) if total else {}
if total < 0:
paid = {k: -abs(v) for k, v in paid.items()}
else:
paid = {self._person(pb): total} if total else {}
people = self._participants(r, ln)
details = parse_pairs(r.get("details", ""), where + " details") if split != "payment" else {}
share = {}
if split == "payment":
if not people or len(people) != 1:
raise LedgerError("%s: a payment needs exactly one recipient in participants" % where)
share = {people[0]: total}
elif split == "equal":
people = people or self.people
share = allocate(total, {p: Decimal(1) for p in people}, self.people)
elif split == "shares":
d = {self._person(k): v for k, v in details.items()}
people = people or list(d)
w = {p: d.get(p, Decimal(1)) for p in people}
extra = [p for p in d if p not in people]
if extra:
raise LedgerError("%s: %s in details but not in participants" % (where, ", ".join(extra)))
if any(v < 0 for v in w.values()):
raise LedgerError("%s: shares cannot be negative" % where)
share = allocate(total, w, self.people)
elif split == "percent":
d = {self._person(k): v for k, v in details.items()}
if sum(d.values()) != 100:
raise LedgerError("%s: percentages add up to %s, not 100" % (where, sum(d.values())))
people = list(d)
share = allocate(total, d, self.people)
elif split == "exact":
d = {self._person(k): v for k, v in details.items()}
people = people or list(d)
fixed = sum(d.values())
rest_people = [p for p in people if p not in d]
if fixed > abs(amount) or (fixed != abs(amount) and not rest_people):
raise LedgerError("%s: exact amounts add up to %s but the bill is %s" % (where, fixed, amount))
w = dict(d)
if rest_people:
each = (abs(amount) - fixed) / len(rest_people)
for p in rest_people:
w[p] = each
share = allocate(total, w, self.people)
elif split == "itemized":
people = people or self.people
shared = details.pop("shared", details.pop("Shared", Decimal(0)))
d = {self._person(k): v for k, v in details.items()}
items = sum(d.values()) + shared
if items > abs(amount):
raise LedgerError("%s: items add up to %s, more than the bill %s" % (where, items, amount))
per = {p: d.get(p, Decimal(0)) + (shared / len(people) if shared else 0) for p in people}
for p in d:
if p not in per:
per[p] = d[p]
if sum(per.values()) <= 0:
raise LedgerError("%s: no items to split" % where)
# tax/tip proportional to each person's items == allocate the total by item weights
share = allocate(total, per, self.people)
rec = {"n": ln, "date": r.get("date", ""), "desc": desc, "split": split, "currency": cur,
"amount": amount, "total": total, "paid": paid, "share": share,
"among": sorted(share, key=self.people.index)}
if split == "itemized":
rec["extra_pct"] = (abs(amount) - items) / items * 100 if items else Decimal(0)
if sum(paid.values()) != sum(share.values()):
raise LedgerError("%s: internal rounding error" % where) # never expected
return rec
def _check_duplicates(self):
seen = {}
for l in self.lines:
key = (l["date"], l["desc"].lower(), l["total"], tuple(sorted(l["paid"])))
if key in seen:
self.warnings.append("line %d looks like a duplicate of line %d (%s, %s)" % (l["n"], seen[key], l["desc"], fmt(l["total"], self.base)))
else:
seen[key] = l["n"]
def balances(self):
b = {p: {"paid": 0, "share": 0, "sent": 0, "received": 0} for p in self.people}
for l in self.lines:
if l["split"] == "payment":
for p, c in l["paid"].items():
b[p]["sent"] += c
for p, c in l["share"].items():
b[p]["received"] += c
else:
for p, c in l["paid"].items():
b[p]["paid"] += c
for p, c in l["share"].items():
b[p]["share"] += c
for p in b:
b[p]["net"] = b[p]["paid"] + b[p]["sent"] - b[p]["share"] - b[p]["received"]
return b
# ----------------------------------------------------------------------------- settle-up
def greedy(net, order):
"""Largest debtor pays largest creditor until everyone is even (at most k-1 transfers)."""
cred = {p: v for p, v in net.items() if v > 0}
debt = {p: -v for p, v in net.items() if v < 0}
out = []
while cred and debt:
c = max(cred, key=lambda p: (cred[p], -order.index(p)))
d = max(debt, key=lambda p: (debt[p], -order.index(p)))
x = min(cred[c], debt[d])
out.append((d, c, x))
cred[c] -= x
debt[d] -= x
if not cred[c]:
del cred[c]
if not debt[d]:
del debt[d]
return out
def minimal(net, order):
"""Fewest transfers: n - (max number of disjoint zero-sum groups). Returns (transfers, groups, exact)."""
people = [p for p in order if net.get(p)]
n = len(people)
if n == 0:
return [], [], True
if n > MAX_EXACT:
return greedy(net, order), [people], False
vals = [net[p] for p in people]
size = 1 << n
sums = [0] * size
for m in range(1, size):
low = m & -m
sums[m] = sums[m ^ low] + vals[low.bit_length() - 1]
dp = [0] * size
for m in range(1, size):
best = 0
mm = m
while mm:
low = mm & -mm
v = dp[m ^ low]
if v > best:
best = v
mm ^= low
dp[m] = best + (1 if sums[m] == 0 else 0)
# walk down, cutting a group at each zero-sum checkpoint
groups, m, last = [], size - 1, size - 1
while m:
mm, pick = m, None
target = dp[m] - (1 if sums[m] == 0 else 0)
while mm:
low = mm & -mm
if dp[m ^ low] == target:
pick = low
break
mm ^= low
m ^= pick
if sums[m] == 0:
groups.append(last ^ m)
last = m
out, named = [], []
for g in reversed(groups):
members = [people[i] for i in range(n) if g >> i & 1]
named.append(members)
out += greedy({p: net[p] for p in members}, order)
return out, named, True
# ----------------------------------------------------------------------------- output
def render(led, detail=None):
b = led.balances()
net = {p: b[p]["net"] for p in led.people}
tr, groups, exact = minimal(net, led.people)
gr = greedy(net, led.people)
B = led.base
o = ["# Settle-up plan", "",
"Base currency: %s People: %d Lines: %d Total spent: %s" % (
B, len(led.people), len(led.lines),
fmt(sum(l["total"] for l in led.lines if l["split"] != "payment"), B))]
others = sorted(c for c in led.rates if c != B)
if others:
o.append("Rates used: " + ", ".join("1 %s = %s %s" % (c, led.rates[c].normalize(), B) for c in others))
o += ["", "## Expenses", "", "| # | Date | What | Paid by | Amount | In %s | Split | Among |" % B, "|---|---|---|---|---|---|---|---|"]
for l in led.lines:
payer = ", ".join("%s %s" % (p, fmt(c)) if len(l["paid"]) > 1 else p for p, c in l["paid"].items())
among = "all" if len(l["among"]) == len(led.people) and l["split"] != "payment" else ", ".join(l["among"])
split = l["split"] + (" (+%.1f%% tax/tip)" % l["extra_pct"] if l["split"] == "itemized" else "")
if l["split"] == "payment":
among = "to " + among
o.append("| %d | %s | %s | %s | %s %s | %s | %s | %s |" % (l["n"], l["date"], l["desc"].replace("|", "/"), payer,
fmt(to_cents(l["amount"])), l["currency"], fmt(l["total"]), split, among))
o += ["", "## Balances", "", "| Person | Paid | Share | Sent | Received | Net |", "|---|---|---|---|---|---|"]
for p in led.people:
x = b[p]
state = "gets back" if x["net"] > 0 else ("owes" if x["net"] < 0 else "even")
o.append("| %s | %s | %s | %s | %s | %s (%s) |" % (p, fmt(x["paid"]), fmt(x["share"]), fmt(x["sent"]), fmt(x["received"]),
fmt(x["net"]), state))
o.append("")
o.append("Check: nets add up to %s (paid %s = shares %s)." % (fmt(sum(net.values())), fmt(sum(x["paid"] for x in b.values())),
fmt(sum(x["share"] for x in b.values()))))
nz = sum(1 for v in net.values() if v)
o += ["", "## Transfers (%d)" % len(tr), ""]
if not tr:
o.append("Everyone is even. Nothing to pay.")
else:
for i, (d, c, x) in enumerate(tr, 1):
o.append("%d. %s pays %s **%s**" % (i, d, c, fmt(x, B)))
o.append("")
if exact:
if len(groups) > 1:
o.append("Minimum possible: %d transfers. The group splits into %d sets that settle among themselves (%s), so %d people need only %d transfers; paying largest debt to largest credit would take %d." % (
len(tr), len(groups), "; ".join(" + ".join(g) for g in groups), nz, len(tr), len(gr)))
else:
o.append("Minimum possible: %d transfers for %d people with a balance (no smaller subgroup evens out on its own)." % (len(tr), nz))
else:
o.append("%d people have a balance; exact minimum search skipped (limit %d), greedy plan uses at most %d transfers." % (nz, MAX_EXACT, nz - 1))
if detail:
p = led._person(detail)
o += ["", "## Detail: %s" % p, "", "| # | What | Paid | Share | Running net |", "|---|---|---|---|---|"]
run = 0
for l in led.lines:
pd, sh = l["paid"].get(p, 0), l["share"].get(p, 0)
if not pd and not sh:
continue
run += pd - sh
o.append("| %d | %s | %s | %s | %s |" % (l["n"], l["desc"], fmt(pd), fmt(sh), fmt(run)))
if led.warnings:
o += ["", "## Warnings", ""] + ["- " + w for w in led.warnings]
o += ["", "## Message for the group chat", "", "```"]
msg = ["Settle-up (%s, %d lines, rates: %s):" % (B, len(led.lines), ", ".join("%s %s" % (c, led.rates[c].normalize()) for c in others) or "none")]
msg += ["- %s -> %s: %s" % (d, c, fmt(x, B)) for d, c, x in tr] or ["- everyone is even"]
msg.append("Full table in the shared sheet. Shout within 2 days if a line is wrong.")
o += msg + ["```"]
return "\n".join(o) + "\n"
def as_json(led):
b = led.balances()
net = {p: b[p]["net"] for p in led.people}
tr, groups, exact = minimal(net, led.people)
return {"base": led.base, "people": led.people, "balances_cents": b,
"transfers": [{"from": d, "to": c, "cents": x} for d, c, x in tr],
"groups": groups, "exact_minimum": exact, "warnings": led.warnings}
# ----------------------------------------------------------------------------- self-test
def self_test():
import random
cases = []
def case(name, fn):
try:
ok, err = bool(fn()), ""
except Exception as e: # noqa
ok, err = False, repr(e)
cases.append((name, ok, err))
H = "date,description,paid_by,amount,currency,split,participants,details\n"
def L(rows, **kw):
return Ledger(H + rows, **kw)
def nets(led):
b = led.balances()
return {p: b[p]["net"] for p in led.people}
def raises(fn):
try:
fn()
except LedgerError:
return True
return False
case("equal split to the cent", lambda: nets(L(",Taxi,Ana,10.00,,equal,Ana;Ben;Cem,\n")) == {"Ana": 666, "Ben": -333, "Cem": -333})
case("remainder cent goes to first in order", lambda: L(",X,Ana,0.10,,equal,Ana;Ben;Cem,\n").lines[0]["share"] == {"Ana": 4, "Ben": 3, "Cem": 3})
case("all minus exclusion", lambda: Ledger("# people: Ana, Ben, Cem\n" + H + ",X,Ana,30,,equal,all-Cem,\n").lines[0]["among"] == ["Ana", "Ben"])
case("all except words", lambda: Ledger("# people: Ana, Ben, Cem\n" + H + ",X,Ana,30,,equal,all except Ben,\n").lines[0]["among"] == ["Ana", "Cem"])
case("shares weights", lambda: L(",Room,Ana,100,,shares,,Ana:3;Ben:1\n").lines[0]["share"] == {"Ana": 7500, "Ben": 2500})
case("shares default 1 for unlisted participants", lambda: L(",Room,Ana,90,,shares,Ana;Ben;Cem,Ana:2;Ben:0\n").lines[0]["share"] == {"Ana": 6000, "Cem": 3000})
case("exact amounts", lambda: L(",Tickets,Ana,75,,exact,,Ana:30;Ben:45\n").lines[0]["share"] == {"Ana": 3000, "Ben": 4500})
case("exact with rest split equally", lambda: L(",T,Ana,100,,exact,Ana;Ben;Cem,Ana:40\n").lines[0]["share"] == {"Ana": 4000, "Ben": 3000, "Cem": 3000})
case("exact mismatch rejected", lambda: raises(lambda: L(",T,Ana,80,,exact,,Ana:30;Ben:45\n")))
case("percent", lambda: L(",Wine,Ana,36,,percent,,Ana:25;Ben:25;Cem:50\n").lines[0]["share"] == {"Ana": 900, "Ben": 900, "Cem": 1800})
case("percent not 100 rejected", lambda: raises(lambda: L(",W,Ana,36,,percent,,Ana:25;Ben:25\n")))
case("itemized with shared and tax/tip", lambda: L(",Dinner,Ana,66,,itemized,Ana;Ben,Ana:20;Ben:30;shared:10\n").lines[0]["share"] == {"Ana": 2750, "Ben": 3850})
case("itemized over bill rejected", lambda: raises(lambda: L(",D,Ana,40,,itemized,Ana;Ben,Ana:20;Ben:30\n")))
case("payment row", lambda: nets(L(",Food,Ana,20,,equal,Ana;Ben,\n,Paid back,Ben,10,,payment,Ana,\n")) == {"Ana": 0, "Ben": 0})
case("payment needs one recipient", lambda: raises(lambda: L(",P,Ben,10,,payment,Ana;Cem,\n")))
case("several payers", lambda: L(",Train,Ana:40;Ben:20,60,,equal,Ana;Ben;Cem,\n").lines[0]["paid"] == {"Ana": 4000, "Ben": 2000})
case("several payers must add up", lambda: raises(lambda: L(",Train,Ana:40;Ben:10,60,,equal,Ana;Ben,\n")))
case("refund (negative amount)", lambda: nets(L(",Museum refund,Ben,-24,,equal,Ben;Cem,\n")) == {"Ben": -1200, "Cem": 1200})
case("currency conversion", lambda: L(",Surf,Ana,100,USD,equal,Ana;Ben,\n", rates="USD=0.92").lines[0]["total"] == 9200)
case("rates from comment line", lambda: Ledger("# base: EUR\n# rates: USD=0.92, GBP=1.16\n" + H + ",S,Ana,10,GBP,equal,Ana;Ben,\n").lines[0]["total"] == 1160)
case("missing rate rejected", lambda: raises(lambda: L(",S,Ana,10,CHF,equal,Ana;Ben,\n")))
case("unknown split rejected", lambda: raises(lambda: L(",S,Ana,10,,halves,Ana;Ben,\n")))
case("strict people list rejects typo", lambda: raises(lambda: Ledger("# people: Ana, Ben\n" + H + ",S,Anna,10,,equal,all,\n")))
case("case-insensitive names merge", lambda: L(",A,Ana,10,,equal,ana;Ben,\n").people == ["Ana", "Ben"])
case("duplicate line warning", lambda: any("duplicate" in w for w in L("1,Taxi,Ana,10,,equal,Ana;Ben,\n1,Taxi,Ana,10,,equal,Ana;Ben,\n").warnings))
case("missing columns rejected", lambda: raises(lambda: Ledger("what,who\nx,y\n")))
case("bad number rejected", lambda: raises(lambda: L(",S,Ana,ten,,equal,Ana;Ben,\n")))
# minimum transfers
case("zero-sum pairs found (4 people -> 2 transfers)", lambda: len(minimal({"A": 500, "B": -500, "C": 300, "D": -300}, list("ABCD"))[0]) == 2)
case("no zero-sum subgroup -> people - 1 transfers", lambda: len(greedy({"A": 600, "B": 400, "C": -500, "D": -500}, list("ABCD"))) == 3 and len(minimal({"A": 600, "B": 400, "C": -500, "D": -500}, list("ABCD"))[0]) == 3)
case("min beats greedy on 6 people", lambda: (lambda n: len(minimal(n, list("ABCDEF"))[0]) == 4 and len(greedy(n, list("ABCDEF"))) == 5)({"A": 700, "B": 300, "C": 250, "D": -500, "E": -450, "F": -300}))
case("everyone even -> no transfers", lambda: minimal({"A": 0, "B": 0}, ["A", "B"])[0] == [])
def brute_min(net):
ps = [p for p in net if net[p]]
best = len(ps) - 1 if ps else 0
for parts in _partitions(ps):
if all(sum(net[p] for p in g) == 0 for g in parts):
best = min(best, len(ps) - len(parts))
return best
def check_random():
rnd = random.Random(7)
for _ in range(60):
k = rnd.randint(2, 7)
vals = [rnd.choice([-1, 1]) * rnd.choice([100, 200, 300, 500, 250, 50]) for _ in range(k - 1)]
vals.append(-sum(vals))
net = {chr(65 + i): v for i, v in enumerate(vals)}
tr = minimal(net, list(net))[0]
bal = dict(net)
for d, c, x in tr:
assert x > 0
bal[d] += x
bal[c] -= x
if any(bal.values()) or len(tr) != brute_min(net):
return False
return True
case("minimal == brute force on 60 random groups and settles everyone", check_random)
case("transfers settle the example-like ledger", lambda: _settles(L(",Flat,Ana,840,,shares,,Ana:3;Ben:3;Cem:2\n,Food,Cem,63.75,,equal,all,\n,Wine,Ben,36,,percent,,Ana:25;Ben:25;Cem:50\n")))
case("render has transfers and chat message", lambda: "Message for the group chat" in render(L(",Taxi,Ana,10,,equal,Ana;Ben,\n")))
case("detail view", lambda: "Detail: Ben" in render(L(",Taxi,Ana,10,,equal,Ana;Ben,\n"), "ben"))
case("json output", lambda: as_json(L(",Taxi,Ana,10,,equal,Ana;Ben,\n"))["transfers"] == [{"from": "Ben", "to": "Ana", "cents": 500}])
case("format thousands", lambda: fmt(123456789, "EUR") == "1,234,567.89 EUR" and fmt(-5) == "-0.05")
passed = sum(1 for _, ok, _ in cases if ok)
for name, ok, err in cases:
print(("PASS " if ok else "FAIL ") + name + ((" " + err) if err else ""))
print("%d/%d passed" % (passed, len(cases)))
return 0 if passed == len(cases) else 1
def _partitions(items):
if not items:
yield []
return
first, rest = items[0], items[1:]
for p in _partitions(rest):
for i in range(len(p)):
yield p[:i] + [[first] + p[i]] + p[i + 1:]
yield [[first]] + p
def _settles(led):
b = led.balances()
net = {p: b[p]["net"] for p in led.people}
for d, c, x in minimal(net, led.people)[0]:
net[d] += x
net[c] -= x
return not any(net.values())
def main(argv=None):
ap = argparse.ArgumentParser(description="Split shared expenses and plan the fewest settle-up transfers.")
ap.add_argument("file", nargs="?", help="CSV ledger ('-' = stdin)")
ap.add_argument("--base", default=None, help="base currency (default: '# base:' line or EUR)")
ap.add_argument("--rates", default=None, help="USD=0.92,GBP=1.16 (1 unit = rate units of base)")
ap.add_argument("--people", default=None, help="comma-separated group members (strict: typos are errors)")
ap.add_argument("--detail", default=None, help="show the line-by-line breakdown for one person")
ap.add_argument("--json", action="store_true")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.file:
ap.error("give a CSV ledger or --self-test")
try:
text = sys.stdin.read() if a.file == "-" else open(a.file, encoding="utf-8-sig").read()
people = [p.strip() for p in a.people.split(",")] if a.people else None
led = Ledger(text, a.base, a.rates, people)
out = json.dumps(as_json(led), indent=2) + "\n" if a.json else render(led, a.detail)
except (OSError, LedgerError) as e:
print("error: %s" % e, file=sys.stderr)
return 2
sys.stdout.write(out)
return 0
if __name__ == "__main__":
sys.exit(main())Animate the step 2 covered bridge image as the first frame into a calm 6-second shot: a slow push-in toward the red bridge with overhanging maple branches entering at the top edge, low mist drifting over the water, red and orange leaves fluttering down and landing on the river with spreading circular ripples, and the reflection shimmering in soft sunrise light. Step 3 of the Red Covered Bridge in Autumn Mist workflow.
Start from the step 2 image "Red Covered Bridge Over a Misty River in Peak Autumn Foliage" as the exact first frame, and animate it into a calm 6-second cinematic shot. Keep the red covered bridge with its dark grey shingled roof, the white-trimmed entrance on the left end, the stone abutments, the orange, red, and yellow trees on both banks, the mirror-still river with its reflection, the pale blue sky with golden haze, and the composition exactly as in the image. The camera makes a slow, steady push-in toward the bridge, so the bridge grows larger and moves toward the center of the frame, while a few overhanging orange and red maple branches from the near bank come into view along the top edge as natural foreground framing. Low mist keeps drifting slowly over the water and under the bridge. Several red and orange maple leaves flutter down in front of the bridge and land softly on the water, each making circular ripples that spread outward across the lower foreground and fade, while the reflection of the bridge shimmers gently in the ripples. The shot ends calm in soft golden sunrise light. Natural, realistic motion, no cuts, no people, no animals, no boats, no text. Soft sound of the river, a light breeze in the leaves, and quiet drips as the leaves touch the water.
Photoreal autumn sunrise scene: a long red wooden covered bridge with a dark grey shingled roof, a white-trimmed entrance on the left end, and stone abutments spans a calm river slightly right of center, with low mist on the water, blazing orange, red, and yellow trees on both banks, a mirror-like reflection, fallen leaves floating in the foreground, and a pale blue sky with golden haze. Step 2 of the Red Covered Bridge in Autumn Mist workflow.
A red wooden covered bridge over a calm, misty river in peak autumn foliage at sunrise, seen from the water level a little downstream, in a wide landscape 16:9 frame. The long bridge, with red vertical board siding and a dark grey shingled roof, spans the river slightly right of center; its open entrance on the left end is framed in white trim, and it rests on grey stone abutments at both ends. A thin layer of low white mist drifts over the water surface and under the bridge. Dense autumn trees crowd both banks: on the left, bright orange, red, and yellow maples lit by the soft golden sun; on the right, deeper red and orange foliage. The still river fills the lower half of the frame and mirrors the bridge and the trees like glass, and many small fallen orange and red leaves float on the water in the foreground. The sky is a clear pale blue with a warm golden haze near the treetops, with soft sunrise light coming from the left. Photoreal landscape and travel photography, natural colors, quiet, crisp, and nostalgic mood. No people, no cars, no text, no logos.
Turn a short idea into an image-ready and motion-ready brief for one hero shot of a red wooden covered bridge over a calm, misty river in peak autumn foliage at sunrise: the bridge, the river and its reflection, low mist, autumn trees and sky, light and color, fixed details, a motion map, and two prompt seeds: a 16:9 still image and an image-to-video animation.
Act as a cinematic landscape designer who writes image-ready and motion-ready scene briefs. Help me design one hero shot of a red wooden covered bridge over a calm, misty river in peak autumn foliage at sunrise. The shot will first be generated as a still image and then animated into a short video that uses that image as its first frame. Your brief must make the still image rich in elements that can move naturally (low mist drifting over the water, a few leaves falling and floating, soft ripples, light shimmering on the reflection, branches swaying slightly) while keeping the composition calm, balanced, readable, and easy to animate. My starting idea: a classic red covered bridge over a still river at sunrise, with low mist on the water and blazing autumn trees on both banks My starting choices: - Bridge: a long red wooden covered bridge with a dark grey shingled roof, an open entrance with white trim on the left end, resting on stone abutments - Position: spanning the river slightly right of center, seen from the water level a little downstream - River: a calm, mirror-still river filling the lower half of the frame, reflecting the bridge and the trees - Mist: a thin low layer of mist drifting over the water and under the bridge - Trees: dense orange, red, and yellow maples and birches on both banks, brighter and sunlit on the left, deeper red on the right - Leaves on the water: many small fallen leaves floating in the foreground - Time and light: just after sunrise, soft golden light from the left and a clear pale blue sky with warm haze - Visual style: photoreal landscape and travel photography, natural colors - Mood words: quiet, crisp, warm, nostalgic, peaceful First ask me, in one short message, for anything missing: the camera height (just above the water, bank level, or slightly raised), how much of the frame the bridge should take, how thick the mist should be, how many floating leaves I want, whether I want overhanging branches at the top edge to frame the shot, whether the video should include a few leaves falling onto the water and making ripples, and anything to avoid (people, cars, animals, boats, text, signs, logos, or copying a specific real bridge, photograph, or named landmark). Then produce the brief with these sections: 1. **Scene Overview**: two or three sentences on the place, the moment, the light, and the feeling. Describe an imagined rural covered bridge in a classic countryside spirit, not a copy of a specific real bridge or a famous photograph. 2. **The Covered Bridge**: its length and position in the frame, the red board siding, the shingled roof, the open entrance and its trim, the stone abutments, and how the morning light falls on it. 3. **The River and Reflection**: the water surface, how still it is, how clearly it mirrors the bridge and trees, where it catches warm light, and the floating leaves in the foreground. 4. **Mist**: how thick it is, where it lies (on the water, under the bridge, along the far bank), which way it drifts, and how it should read as soft morning river mist rather than smoke or fog filling the whole frame. 5. **Autumn Trees and Sky**: the colors and density of the foliage on each bank, where the sunlight hits, the edge of the woods against the sky, and the pale blue sky with warm golden haze. 6. **Light and Color**: the direction and warmth of the sunrise light, the cool shadows, the balance of red, orange, and yellow against blue, and how soft the contrast is. 7. **Fixed Visual Details**: a numbered list of 8 to 10 details that must stay identical in the still image and in the video (bridge position and length, roof line, entrance on the left end, stone abutments, both tree lines, river edges, reflection, camera position, framing, overall mist zone). 8. **Motion Map**: a table of every element that can move in the video, with columns: element, type of motion, direction, speed (very slow, slow, medium), and how strongly it should move. Include the mist, a few leaves falling and landing on the water, the floating leaves, the ripples they make, the shimmer on the reflection, a slight sway of branches, and the camera move. Keep total motion subtle and physically plausible, with one gentle air direction. 9. **Prompt Seed A - Hero Still Image**: a ready-to-paste image prompt under 170 words for a wide landscape 16:9 frame, with the red covered bridge, the misty river, and the peak autumn trees at sunrise in the first sentence, ending with: no people, no text, no logos. 10. **Prompt Seed B - Image-to-Video Animation**: a ready-to-paste video prompt under 120 words that starts from the hero still as the first frame, describes a slow gentle push-in toward the bridge for about 6 seconds, mist drifting over the water and under the bridge, a few red and orange maple leaves fluttering down and landing on the water with soft spreading ripples, and the reflection shimmering, and says to keep the bridge, banks, trees, river, and framing exactly as in the image with no new objects. Rules: no people, cars, boats, or animals; no text, signs, or logos; no fast camera moves or cuts; and no motion that breaks physics (the bridge, stone abutments, and banks never move, the water stays calm and flows gently in one direction, leaves fall slowly and float on the surface, ripples spread outward in circles and fade, mist drifts and does not pour or swirl violently, the light does not flicker or jump). Use short paragraphs and lists.
When your checked bag is delayed, lost, or damaged, get a strict JSON claim plan: immediate actions, the official report details to keep, a tracking and delivery plan, airline rules and deadlines to confirm officially, an interim essentials expenses log, a contents inventory with values and proof, a damaged bag section, a claim package checklist, a timeline, a polite claim letter, a follow-up message, and an escalation path. Organization help, not legal advice.
1{2 "role": "Calm, organized traveler-side baggage claim assistant who helps people whose checked luggage is delayed, lost, or damaged on a flight report it correctly, track it, keep reasonable interim expenses documented, and file a complete, well-supported claim with the airline on time, without giving legal advice or inventing airline policies, compensation limits, or deadlines",3 "task": "Turn my flight, what happened to my bag, what was inside, what I have spent so far, and what the airline has told me into a single strict JSON luggage claim plan: a situation summary, immediate actions at the airport or right after, the official report and reference details to keep, a tracking and follow-up plan, rules and deadlines I must confirm officially, an interim expenses plan, a contents inventory with values and proof, a damaged bag section if relevant, a claim package checklist, a timeline with dates, a polite claim letter, a follow-up message, an escalation path, and mistakes to avoid. Never invent airline rules, compensation amounts, deadlines, or facts I did not give.",4 "context": {5 "route_and_flights": "${flights:Lisbon to Chicago with a connection in London, two different airlines on one ticket}",6 "travel_date": "${travel_date:yesterday}",7 "where_i_am_now": "${location:at my hotel in Chicago, staying 6 nights for a work conference}",8 "bag_status": "${bag_status:my checked suitcase did not arrive, the tracker says it is still in London}",9 "report_filed": "${report:yes, I filed a report at the arrivals baggage desk and got a reference number on a paper slip}",10 "bag_description": "${bag:large dark blue hard-shell suitcase with a red strap and a luggage tag with my name and phone number}",...+177 more lines
Compares commute options - car (fuel or EV), transit, bike, e-bike, walking, day-share mixes and park-and-ride legs - per month and year with cash cost, door-to-door time, time cost at your own hourly value, cost per trip and CO2. Picks pass vs pay-per-ride for the days you ride, separates car running costs from fixed costs, and shows the break-even value of an hour. Includes a stdlib Python calculator with --self-test.
---
name: commute-cost-comparison-calculator
description: Compares commute options - car (fuel or EV), transit, bike, e-bike, walking, day-share mixes and park-and-ride legs - per month and year with cash cost, door-to-door time, time cost at your own hourly value, cost per trip and CO2. Picks pass vs pay-per-ride for the days you ride, separates car running costs from fixed costs, and shows the break-even value of an hour. Includes a stdlib Python calculator with --self-test.
---
# Commute Cost Comparison Calculator
You help someone decide how to get to work by putting every option on the same footing: what it costs in cash, how much of their life it takes, and what that time is worth to them. You count what really changes with the choice (fuel, parking, fares, the bike), keep costs they pay anyway out unless they would actually sell the car, and show the trade-off as a clear number: "driving saves 32 lost hours a year and costs $3,697 more, so it pays only if your hour is worth more than $115".
## Files in this skill
- `scripts/commute_cost.py` - reads a scenario JSON (distance, commute days, value of time, options) and prints a comparison table, headline, break-even values of time and per-option notes; supports metric (km, L/100 km) and imperial (mi, mpg), EVs, transit passes with daily caps and employer subsidies, day-share mixes and multi-leg trips (Python 3.8+ standard library only)
- `references/cost-components.md` - every option field, what to include for each mode, where to find the numbers, and typical ranges
- `references/time-value-and-assumptions.md` - how to choose a value of time, usable time on transit, what the totals leave out (health, safety, weather, flexibility) and how to run sensitivity checks
- `templates/commute-comparison.md` - the decision summary to hand back
- `examples/commute.json` - an 11-mile commute with driving, bus + light rail, an e-bike, an e-bike/transit mix and park-and-ride
- `examples/comparison-output.md` - the real output of the calculator for that scenario
## Workflow
### 1. Collect the facts
One-way distance, commute days per week (hybrid work matters a lot) and weeks worked per year, door-to-door minutes per option (including walking, waiting, parking and transfers: ask for a real trip, not the map estimate), and per mode: car fuel economy, fuel or electricity price, parking and tolls, whether they would keep the car anyway; transit fare, pass price, daily cap, employer subsidy; bike or e-bike price, expected life and upkeep. Ask what an hour of their time is worth, or offer a default (half their hourly pay) and show the sensitivity.
### 2. Run the calculator
```
python3 scripts/commute_cost.py examples/commute.json
python3 scripts/commute_cost.py scenario.json --days-per-week 3
python3 scripts/commute_cost.py scenario.json --value-of-time 0 --json
python3 scripts/commute_cost.py --self-test
```
Exit 0 = comparison printed, 2 = bad input (missing field, mix shares not adding up to 1, unknown mode, negative price). Without code, follow the formulas in `references/cost-components.md`.
### 3. Read the result
- The table is sorted by total (cash + time cost); the headline names the cheapest in cash, the cheapest once time counts and the fastest.
- **Break-even value of time** compares every option with the cheapest in cash: an option that costs more is worth it only if your hour is worth more than the number shown. "Never" means it costs more and does not save usable time.
- Time spent on transit that you can use (reading, email) is discounted with `usable_time_share`; the same field can credit bike time that replaces exercise you would do anyway. Say which you used.
- Check the transit note: on 2-3 commute days a week a monthly pass is often dearer than pay-per-ride; the calculator picks the cheaper and says so.
### 4. Deliver
Fill `templates/commute-comparison.md`: recommendation in one sentence, the table, break-even values, what changes the answer (hybrid days, fuel price, parking, value of time), what is not priced, and a trial suggestion (e.g. two weeks of the mix before buying anything).
## Example result
11 miles each way, 5 days a week, 46 weeks, time valued at $20/hour (`examples/commute.json`). Cheapest in cash: bus + light rail at $49/month after a $50 employer subsidy (the $99 pass beats $105 of single fares). Cheapest once time counts: park and ride ($95 cash, $361/month total) because 80 % of the train leg is usable. Driving downtown is fastest (28 min) but costs $357/month with $12/day parking and pays off only if an hour is worth more than $115. The e-bike costs $67/month all-in and emits nothing, but it does not save usable time at these numbers; it wins if the ride replaces gym time. See `examples/comparison-output.md`.
## Rules
- Count only costs that change with the choice; include car insurance, registration and loan costs only if the person would actually give up the car (`count_fixed`).
- Use real door-to-door times, including walking, waiting, parking and transfers.
- Never present the value of time as a fact: it is the person's own choice; show at least one sensitivity run (e.g. `--value-of-time 0` and their wage).
- Keep health, safety and weather out of the money totals but mention them; do not moralize about cars or bikes.
- State every assumption with its number (fuel price, parking, depreciation per mile) so the person can change it.
- Give currency and units as the person uses them; do not mix miles and kilometres in one scenario.
FILE:references/cost-components.md
# Cost components and option fields
Scenario fields: `currency` (USD, EUR, GBP, TRY, ...), `units` (`metric`: km, L/100 km, price per litre; `imperial`: miles, mpg, price per US gallon), `one_way_distance`, `days_per_week` (default 5), `weeks_per_year` (default 46: holidays, sick days, travel), `value_of_time_per_hour`, `options`.
Every option: `name`, `mode`, `minutes_one_way` (door to door), optional `distance_one_way` (defaults to the scenario distance), optional `usable_time_share` (0..1).
## Car (`mode: car`)
| Field | Meaning | Typical |
|---|---|---|
| `fuel_economy_mpg` / `fuel_l_per_100km` | real-world consumption on this route (city driving is worse than the label) | 25-35 mpg / 6-9 L/100 km |
| `fuel_price` | per gallon / per litre | local pump price |
| `fuel: "diesel"` | uses the diesel CO2 factor | petrol default |
| `kwh_per_100` + `electricity_price` | electric car instead of fuel (kWh per 100 mi or km) | 25-35 kWh/100 mi, 16-22 kWh/100 km |
| `grid_kg_co2_per_kwh` | grid intensity for EV CO2 | 0.4 default; 0.05 hydro/nuclear, 0.7 coal-heavy |
| `maintenance_per_distance` | tyres, servicing, repairs per mile/km | $0.08-0.12/mi, 0.05-0.08/km |
| `depreciation_per_distance` | value lost from extra mileage only (not age) | $0.05-0.15/mi |
| `parking_per_day`, `tolls_per_day` | per commute day | workplace parking can dominate |
| `fixed_per_year` + `count_fixed` | insurance, registration, loan interest, age depreciation; counted only when `count_fixed` is true | true only if commuting is the reason to own the car |
Fuel cost = 2 x distance x days / mpg x price (or x L/100 km / 100 x price). CO2: petrol 2.35 kg/L (8.89 kg per US gallon), diesel 2.68 kg/L (10.18 kg/gal), EV kWh x grid factor.
All-in per-mile rates (tax mileage rates, AAA "Your Driving Costs") include fixed costs; they overstate the marginal cost of a commute when the car is kept anyway.
## Transit (`mode: transit`)
| Field | Meaning |
|---|---|
| `fare_per_ride`, `rides_per_day` (default 2) | single fares; add a ride for each paid transfer that is not free |
| `daily_cap` | fare capping per day, if the system has it |
| `monthly_pass` | price per month; the calculator compares 12 passes with pay-per-ride for the actual days and picks the cheaper |
| `subsidy_per_month` | employer or tax-free benefit, deducted (never below zero) |
| `co2_g_per_passenger_km` | default 80 g; electric rail 20-40, diesel bus 80-120 at average load |
| `usable_time_share` | share of the trip you can read or work (seat, no transfer stress): 0.2-0.8 |
## Bike, e-bike, walk (`mode: bike | ebike | walk`)
| Field | Meaning | Typical |
|---|---|---|
| `purchase_price`, `life_years` | spread over the life (default 5 years); not used for walk | e-bike $1,500-3,500 |
| `maintenance_per_year` | tyres, chain, brake pads, battery fund for e-bikes | $100-300 |
| `gear_per_year` | lights, lock, rain gear, helmet replacement | $50-150 |
| `kwh_per_100`, `electricity_price` | e-bike charging | 1-2 kWh per 100 mi |
| `other_per_month` | bike parking, locker, shower membership | 0-30 |
Ownership costs are counted in full even in a mix: you pay for the bike whether you ride 3 or 5 days.
## Mix (`mode: mix`)
`"shares": {"E-bike": 0.6, "Bus + light rail": 0.4}` splits commute days between other options (shares add up to 1). Each part is costed for its own days, so a transit part on 2 days a week usually goes pay-per-ride. Use it for weather-dependent cycling, hybrid driving, or carpool days.
## Multi-leg (`mode: multi`)
`"legs": [ {car leg}, {transit leg} ]` with `transfer_minutes`. Each leg needs its own `distance_one_way` and `minutes_one_way`; costs and minutes are summed. Use it for park and ride, bike + train, or walk + bus.
## Where to get the numbers
- Fuel economy: the car's trip computer over a week of commuting.
- Parking and fares: the operator's price page; check employer benefits (pre-tax transit, parking cash-out).
- Door-to-door time: time one real trip each way at commute hours; add 5 minutes for parking or waiting variability.
FILE:references/time-value-and-assumptions.md
# Value of time and what the totals leave out
## Choosing a value of time
- There is no correct number: it is what an hour of this person's commute is worth to them.
- Common anchor: about half of hourly take-home pay for personal travel (the US Department of Transportation's travel-time guidance uses 50 % of hourly income for personal local trips; business travel is valued at 100 %).
- Someone on a fixed salary who cannot earn more by commuting less may choose a lower value; a freelancer who bills the saved hours may choose a higher one.
- Always show a sensitivity: `--value-of-time 0` (cash only), the chosen value, and their full hourly wage. If the ranking does not change, the decision is robust.
## Usable time
`usable_time_share` discounts time you can use. Rough guide:
| Situation | Share |
|---|---|
| Driving, cycling in traffic, standing on a crowded bus | 0 |
| Bus with a seat, short hops, transfers | 0.2-0.4 |
| Train with a seat and table, 20+ minutes without changes | 0.6-0.8 |
| Bike or walk that replaces exercise you would otherwise do | 0.3-0.7 (say so explicitly) |
## Not in the money totals (mention them)
- **Health:** regular cycling or walking is associated with better cardiovascular health; some people value it highly, others not at all. Use `usable_time_share` if they want it priced.
- **Safety:** road risk per mile differs by mode and route; a protected bike route changes the picture.
- **Weather and season:** use a mix (e.g. 60 % bike days) rather than assuming every day is a bike day.
- **Reliability:** a 40-minute train with a 10-minute spread may beat a 30-minute drive that ranges from 25 to 60; ask about late penalties (childcare pick-up).
- **Flexibility and option value:** having a car for errands on the way, or for emergencies; car share or taxi credits can replace it for rare days (add them as `other_per_month`).
- **Stress and comfort:** do not price it, but ask.
## Sensitivity runs worth doing
- Hybrid work: `--days-per-week 3` often flips pass vs pay-per-ride and makes owning a second car look worse.
- Parking: a change in parking price (or employer parking cash-out) is often the biggest single lever.
- Fuel or electricity price +-25 %.
- Selling a second car: rerun with `count_fixed: true` on the car to see the full saving.
## Sanity checks before presenting
- Cash per trip for driving should be at least fuel + parking per trip.
- Transit cash per month should not exceed the pass price unless the pass does not cover the route.
- Hours per month = minutes one way x 2 x days per month / 60.
- If the "winner" depends on a value of time far from what the person said, say so plainly.
FILE:templates/commute-comparison.md
# Commute options: <home> to <work>
**Trip:** <11 mi each way, 5 days/week, 46 weeks/year> **Value of time used:** <$20/hour (about half of hourly pay)>
**Recommendation:** <one sentence, e.g. "Park and ride: $95/month cash, 40 min door to door, most of the train ride usable for email">
## Comparison (per month)
| Option | Cash | Door to door | Hours | Time cost | Total | CO2 kg/year |
|---|---|---|---|---|---|---|
| <Park and ride> | <$95> | <40 min> | <25.6> | <$266> | <$361> | <999> |
| <Bus + light rail> | <$49> | <46 min> | <29.4> | <$411> | <$460> | <651> |
## When a dearer option pays off
| Option | Extra per year | Lost hours saved | Worth it above |
|---|---|---|---|
| <Drive downtown> | <$3,697> | <32> | <$115/hour> |
## What would change the answer
- <Hybrid work (3 days): transit pass no longer pays; pay per ride ...>
- <Parking cash-out from the employer would make driving $230/month dearer still>
- <If the e-bike ride replaces the gym, the e-bike moves to ...>
## Not priced
- <health, safety on the route, weather days, reliability, needing the car for school pick-up>
## Assumptions
- <fuel $3.40/gal at 28 mpg; maintenance $0.10/mi; mileage depreciation $0.08/mi; parking $12/day>
- <transit pass $99, employer subsidy $50/month, 30 % of the bus/rail time usable>
- <car kept for weekends, so insurance and registration are not counted>
## Next step
<Try the mix for two weeks before buying the e-bike; time each trip door to door.>
FILE:examples/commute.json
{
"currency": "USD",
"units": "imperial",
"one_way_distance": 11,
"days_per_week": 5,
"weeks_per_year": 46,
"value_of_time_per_hour": 20,
"options": [
{
"name": "Drive downtown",
"mode": "car",
"minutes_one_way": 28,
"fuel_economy_mpg": 28,
"fuel_price": 3.4,
"maintenance_per_distance": 0.1,
"depreciation_per_distance": 0.08,
"parking_per_day": 12,
"tolls_per_day": 0,
"fixed_per_year": 1900,
"count_fixed": false
},
{
"name": "Bus + light rail",
"mode": "transit",
"minutes_one_way": 46,
"fare_per_ride": 2.75,
"monthly_pass": 99,
"subsidy_per_month": 50,
"usable_time_share": 0.3
},
{
"name": "E-bike",
"mode": "ebike",
"minutes_one_way": 42,
"purchase_price": 2200,
"life_years": 5,
"maintenance_per_year": 250,
"gear_per_year": 100,
"kwh_per_100": 1.5,
"electricity_price": 0.17
},
{
"name": "E-bike 3 days, transit 2 days",
"mode": "mix",
"shares": {"E-bike": 0.6, "Bus + light rail": 0.4}
},
{
"name": "Park and ride",
"mode": "multi",
"transfer_minutes": 6,
"legs": [
{"mode": "car", "distance_one_way": 4, "minutes_one_way": 10, "fuel_economy_mpg": 28, "fuel_price": 3.4,
"maintenance_per_distance": 0.1, "depreciation_per_distance": 0.08, "parking_per_day": 0},
{"mode": "transit", "distance_one_way": 7, "minutes_one_way": 24, "fare_per_ride": 2.75, "monthly_pass": 99,
"subsidy_per_month": 50, "usable_time_share": 0.8}
]
}
]
}
FILE:examples/comparison-output.md
# Commute cost comparison
One way: 11 mi Commute days: 19.2/month (230/year) Value of time: $20.00/hour Currency: USD
| Option | Cash / month | Cash / year | Per trip | Door to door (one way) | Hours / month | Time cost / month | Total / month | CO2 kg / year |
|---|---|---|---|---|---|---|---|---|
| Park and ride | $95.22 | $1,143 | $2.48 | 40 min | 25.6 | $266 | **$361** | 999 |
| Bus + light rail | $49.00 | $588 | $1.28 | 46 min | 29.4 | $411 | **$460** | 651 |
| E-bike 3 days, transit 2 days | $66.48 | $798 | $1.73 | 44 min | 27.9 | $487 | **$553** | 261 |
| E-bike | $66.91 | $803 | $1.75 | 42 min | 26.8 | $537 | **$604** | 0 |
| Drive downtown | $357 | $4,285 | $9.32 | 28 min | 17.9 | $358 | **$715** | 1,607 |
Sorted by total (cash + time cost).
## Headline
- Cheapest in cash: **Bus + light rail** ($49.00/month).
- Cheapest once time counts: **Park and ride** ($361/month at $20.00/hour).
- Fastest: **Drive downtown** (28 min one way, 17.9 h/month).
## Break-even value of time (vs Bus + light rail, the cheapest in cash)
| Option | Extra cash / year | Lost hours saved / year | Worth it if your hour is worth more than |
|---|---|---|---|
| Drive downtown | $3,697 | 32 | $115/hour |
| E-bike | $215 | none (75 more lost) | never on cost: it does not save usable time |
| E-bike 3 days, transit 2 days | $210 | none (45 more lost) | never on cost: it does not save usable time |
| Park and ride | $555 | 87 | $6.35/hour |
## Notes per option
- **Drive downtown** (car): per month: fuel/energy $51.20, maintenance + depreciation $75.90, parking + tolls $230; fixed costs (insurance, registration) not counted: you keep the car anyway
- **Bus + light rail** (transit): per month: fares $49.00; monthly pass (cheaper than $105/month pay per ride at 19.2 days/month); employer subsidy $50.00/month deducted
- **E-bike** (ebike): per month: bike + upkeep $65.83, fuel/energy $1.08; ownership costs counted in full (they do not shrink on days you do not ride)
- **E-bike 3 days, transit 2 days** (mix): E-bike 60 % of days (11.5/month): ownership costs counted in full (they do not shrink on days you do not ride); Bus + light rail 40 % of days (7.7/month): pay per ride (pass would cost $99.00/month at 7.7 days/month)
- **Park and ride** (multi): leg 2 (transit): monthly pass (cheaper than $105/month pay per ride at 19.2 days/month); leg 2 (transit): employer subsidy $50.00/month deducted
Time cost = hours x value of time x (1 - share of the trip you can use for reading or work). Not included: health benefits, accident risk, weather days and the option value of having a car; see references/time-value-and-assumptions.md.
FILE:scripts/commute_cost.py
#!/usr/bin/env python3
"""Commute cost comparison calculator (Python 3.8+ standard library only).
Compares commute options - car (fuel or electric), transit, bike, e-bike, walking,
day-share mixes ("bike 3 days, train 2 days") and same-day multi-leg trips ("drive to
the station, then train") - per month and per year: cash cost, time spent, time cost at
your own hourly value, total, cost per trip and CO2. For transit it picks the cheaper of
pay-per-ride (with a daily cap) and a monthly pass for the days you actually ride; for
cars it separates running costs from fixed costs you would keep paying anyway. It also
prints break-even values of time: how much an hour must be worth to you before a faster,
dearer option pays off.
Usage:
python3 commute_cost.py scenario.json [--value-of-time 25] [--days-per-week 3] [--json]
python3 commute_cost.py --self-test
scenario.json: {"currency": "USD", "units": "imperial"|"metric", "one_way_distance": 11,
"days_per_week": 5, "weeks_per_year": 46, "value_of_time_per_hour": 20,
"options": [{"name": "...", "mode": "car|transit|bike|ebike|walk|mix|multi", ...}]}
See references/cost-components.md for every option field.
Exit codes: 0 = comparison printed, 2 = bad input.
"""
import argparse, json, sys
PETROL_CO2 = {"metric": 2.35, "imperial": 8.89} # kg CO2 per litre / per US gallon burned (diesel: 2.68 / 10.18)
DIESEL_CO2 = {"metric": 2.68, "imperial": 10.18}
KM_PER_UNIT = {"metric": 1.0, "imperial": 1.609344}
LABELS = {"energy": "fuel/energy", "running": "maintenance + depreciation", "parking_tolls": "parking + tolls",
"fixed": "fixed costs", "fares": "fares", "ownership": "bike + upkeep", "other": "other"}
MODES = {"car", "transit", "bike", "ebike", "walk", "mix", "multi"}
SYMBOLS = {"USD": "$", "EUR": "€", "GBP": "£", "TRY": "₺", "CAD": "C$", "AUD": "A$", "JPY": "¥", "INR": "₹"}
class InputError(Exception):
pass
def num(o, key, default=None, lo=0.0, hi=None, who=""):
v = o.get(key, default)
if v is None:
raise InputError(f"{who}: '{key}' is required")
if isinstance(v, bool) or not isinstance(v, (int, float)):
raise InputError(f"{who}: '{key}' must be a number")
if v < lo or (hi is not None and v > hi):
raise InputError(f"{who}: '{key}' = {v} is out of range" + (f" ({lo}..{hi})" if hi is not None else f" (>= {lo})"))
return float(v)
def car_cost(o, sc, days, who):
"""Annual cost dict for a car over `days` commute days."""
units = sc["units"]
d = num(o, "distance_one_way", sc["distance"], who=who) * 2 * days # user units per year
if "kwh_per_100" in o:
kwh = d / 100 * num(o, "kwh_per_100", who=who)
energy = kwh * num(o, "electricity_price", who=who)
co2 = kwh * num(o, "grid_kg_co2_per_kwh", 0.4, who=who)
else:
if units == "imperial":
vol = d / num(o, "fuel_economy_mpg", lo=1, who=who)
else:
vol = d / 100 * num(o, "fuel_l_per_100km", lo=0.5, who=who)
energy = vol * num(o, "fuel_price", who=who)
co2 = vol * (DIESEL_CO2 if o.get("fuel") == "diesel" else PETROL_CO2)[units]
running = d * (num(o, "maintenance_per_distance", 0, who=who) + num(o, "depreciation_per_distance", 0, who=who))
daily = days * (num(o, "parking_per_day", 0, who=who) + num(o, "tolls_per_day", 0, who=who))
fixed = num(o, "fixed_per_year", 0, who=who) if o.get("count_fixed", False) else 0.0
return {"energy": energy, "running": running, "parking_tolls": daily, "fixed": fixed,
"co2": co2, "notes": ([] if o.get("count_fixed", False) or not o.get("fixed_per_year") else
["fixed costs (insurance, registration) not counted: you keep the car anyway"])}
def transit_cost(o, sc, days, who):
rides = num(o, "rides_per_day", 2, lo=1, who=who)
fare = num(o, "fare_per_ride", who=who)
cap = o.get("daily_cap")
per_day = fare * rides if cap is None else min(fare * rides, num(o, "daily_cap", who=who))
payg_year = per_day * days
best, note = payg_year, "pay per ride"
if o.get("monthly_pass") is not None:
pass_year = num(o, "monthly_pass", who=who) * 12
months_days = days / 12
if pass_year < payg_year:
best, note = pass_year, f"monthly pass (cheaper than {fmt_plain(payg_year / 12, sc['sym'])}/month pay per ride at {months_days:.1f} days/month)"
else:
note = f"pay per ride (pass would cost {fmt_plain(pass_year / 12, sc['sym'])}/month at {months_days:.1f} days/month)"
subsidy = num(o, "subsidy_per_month", 0, who=who) * 12
best = max(0.0, best - subsidy)
km = num(o, "distance_one_way", sc["distance"], who=who) * 2 * days * KM_PER_UNIT[sc["units"]]
co2 = km * num(o, "co2_g_per_passenger_km", 80, who=who) / 1000
return {"fares": best, "co2": co2, "notes": [note] + ([f"employer subsidy {fmt_plain(subsidy / 12, sc['sym'])}/month deducted"] if subsidy else [])}
def bike_cost(o, sc, days, who, mode):
d = num(o, "distance_one_way", sc["distance"], who=who) * 2 * days
own = 0.0
if mode != "walk":
life = num(o, "life_years", 5, lo=0.5, who=who)
own = num(o, "purchase_price", 0, who=who) / life
own += num(o, "maintenance_per_year", 0, who=who) + num(o, "gear_per_year", 0, who=who)
energy = 0.0
if mode == "ebike":
kwh = d / 100 * num(o, "kwh_per_100", 1.2, who=who)
energy = kwh * num(o, "electricity_price", 0, who=who)
extra = num(o, "other_per_month", 0, who=who) * 12
return {"ownership": own, "energy": energy, "other": extra, "co2": 0.0,
"notes": ["ownership costs counted in full (they do not shrink on days you do not ride)"] if own else []}
def option_cost(o, sc, days, who):
mode = o.get("mode")
if mode == "car":
c = car_cost(o, sc, days, who)
elif mode == "transit":
c = transit_cost(o, sc, days, who)
elif mode in ("bike", "ebike", "walk"):
c = bike_cost(o, sc, days, who, mode)
else:
raise InputError(f"{who}: mode '{mode}' is not allowed here (use car, transit, bike, ebike, walk)")
minutes = num(o, "minutes_one_way", who=who, lo=1)
cash = sum(v for k, v in c.items() if k not in ("co2", "notes"))
return {"cash": cash, "minutes": minutes, "co2": c["co2"], "notes": c["notes"],
"usable": num(o, "usable_time_share", 0, hi=1, who=who),
"breakdown": {k: v for k, v in c.items() if k not in ("co2", "notes")}}
def evaluate(sc_raw, value_override=None, dpw_override=None):
if not isinstance(sc_raw, dict) or not isinstance(sc_raw.get("options"), list) or not sc_raw["options"]:
raise InputError("scenario needs an 'options' list")
units = sc_raw.get("units", "metric")
if units not in KM_PER_UNIT:
raise InputError("units must be 'metric' or 'imperial'")
cur = sc_raw.get("currency", "USD")
sc = {"units": units, "distance": num(sc_raw, "one_way_distance", who="scenario", lo=0.1),
"sym": SYMBOLS.get(cur, f"{cur} ")}
dpw = dpw_override if dpw_override is not None else num(sc_raw, "days_per_week", 5, lo=0.5, hi=7, who="scenario")
wpy = num(sc_raw, "weeks_per_year", 46, lo=1, hi=52, who="scenario")
days = dpw * wpy
vot = value_override if value_override is not None else num(sc_raw, "value_of_time_per_hour", 0, who="scenario")
by_name = {}
for i, o in enumerate(sc_raw["options"]):
if not isinstance(o, dict) or not o.get("name") or o.get("mode") not in MODES:
raise InputError(f"option {i + 1}: needs a 'name' and a 'mode' ({', '.join(sorted(MODES))})")
if o["name"] in by_name:
raise InputError(f"option name '{o['name']}' is used twice")
by_name[o["name"]] = o
results = []
for o in sc_raw["options"]:
who = o["name"]
if o["mode"] == "mix":
shares = o.get("shares")
if not isinstance(shares, dict) or not shares:
raise InputError(f"{who}: mix needs 'shares', e.g. {{\"Bike\": 0.6, \"Transit\": 0.4}}")
tot = sum(shares.values())
if abs(tot - 1) > 0.001:
raise InputError(f"{who}: shares add up to {tot:g}, not 1")
cash = co2 = hours = eff = 0.0
notes, parts = [], []
for nm, sh in shares.items():
if nm not in by_name or by_name[nm]["mode"] in ("mix",):
raise InputError(f"{who}: share '{nm}' must name another non-mix option")
sub = by_name[nm]
part = multi_cost(sub, sc, days * sh, nm) if sub["mode"] == "multi" else option_cost(sub, sc, days * sh, nm)
cash += part["cash"]; co2 += part["co2"]
h = part["minutes"] * 2 * days * sh / 60
hours += h; eff += h * (1 - part["usable"])
parts.append(f"{nm} {sh * 100:.0f} % of days ({days * sh / 12:.1f}/month): {part['notes'][0] if part['notes'] else 'as above'}")
minutes = hours * 60 / (2 * days)
results.append(row(who, "mix", cash, minutes, hours, eff, vot, co2, days, parts))
continue
part = multi_cost(o, sc, days, who) if o["mode"] == "multi" else option_cost(o, sc, days, who)
hours = part["minutes"] * 2 * days / 60
results.append(row(who, o["mode"], part["cash"], part["minutes"], hours, hours * (1 - part["usable"]), vot,
part["co2"], days, part["notes"], part.get("breakdown")))
return {"currency": sc_raw.get("currency", "USD"), "units": units, "one_way_distance": sc["distance"],
"days_per_year": days, "days_per_month": days / 12, "value_of_time_per_hour": vot,
"options": results, "break_even": break_even(results)}
def multi_cost(o, sc, days, who):
legs = o.get("legs")
if not isinstance(legs, list) or len(legs) < 2:
raise InputError(f"{who}: multi needs at least two 'legs'")
cash = co2 = minutes = 0.0
notes, usable_min = [], 0.0
for j, leg in enumerate(legs, 1):
if leg.get("mode") in ("mix", "multi"):
raise InputError(f"{who} leg {j}: legs cannot be mix or multi")
if "distance_one_way" not in leg:
raise InputError(f"{who} leg {j}: each leg needs its own 'distance_one_way'")
p = option_cost(leg, sc, days, f"{who} leg {j}")
cash += p["cash"]; co2 += p["co2"]; minutes += p["minutes"]
usable_min += p["minutes"] * p["usable"]
notes += [f"leg {j} ({leg['mode']}): {n}" for n in p["notes"]]
minutes += num(o, "transfer_minutes", 0, who=who)
return {"cash": cash, "co2": co2, "minutes": minutes, "notes": notes or ["legs summed"],
"usable": usable_min / minutes if minutes else 0.0}
def row(name, mode, cash, minutes, hours, eff_hours, vot, co2, days, notes, breakdown=None):
tcost = eff_hours * vot
return {"name": name, "mode": mode, "cash_year": cash, "cash_month": cash / 12, "minutes_one_way": minutes,
"hours_month": hours / 12, "lost_hours_month": eff_hours / 12, "time_cost_month": tcost / 12, "total_month": (cash + tcost) / 12,
"total_year": cash + tcost, "cost_per_trip": cash / (2 * days), "co2_kg_year": co2,
"notes": notes, "breakdown": breakdown or {}}
def break_even(results):
"""For each option, the hourly value of time at which it ties with the cheapest-cash option.
Uses lost hours (time you cannot use for reading or work), the same basis as the time cost."""
base = min(results, key=lambda r: r["cash_year"])
out = []
for r in results:
if r is base:
continue
extra = r["cash_year"] - base["cash_year"]
hours_saved = (base["lost_hours_month"] - r["lost_hours_month"]) * 12
if hours_saved > 0.01:
out.append({"option": r["name"], "vs": base["name"], "extra_cash_year": extra,
"hours_saved_year": hours_saved, "break_even_per_hour": extra / hours_saved})
else:
out.append({"option": r["name"], "vs": base["name"], "extra_cash_year": extra,
"hours_saved_year": hours_saved, "break_even_per_hour": None})
return out
def fmt_plain(v, sym="$"):
return f"{sym}{v:,.0f}" if abs(v) >= 100 else f"{sym}{v:,.2f}"
def render(res):
sym = SYMBOLS.get(res["currency"], res["currency"] + " ")
f = lambda v: fmt_plain(v, sym)
du = "mi" if res["units"] == "imperial" else "km"
out = [f"# Commute cost comparison", "",
f"One way: {res['one_way_distance']:g} {du} Commute days: {res['days_per_month']:.1f}/month ({res['days_per_year']:.0f}/year) "
f"Value of time: {f(res['value_of_time_per_hour'])}/hour Currency: {res['currency']}", "",
"| Option | Cash / month | Cash / year | Per trip | Door to door (one way) | Hours / month | Time cost / month | Total / month | CO2 kg / year |",
"|---|---|---|---|---|---|---|---|---|"]
rs = res["options"]
for r in sorted(rs, key=lambda r: r["total_month"]):
out.append(f"| {r['name']} | {f(r['cash_month'])} | {f(r['cash_year'])} | {f(r['cost_per_trip'])} | {r['minutes_one_way']:.0f} min | "
f"{r['hours_month']:.1f} | {f(r['time_cost_month'])} | **{f(r['total_month'])}** | {r['co2_kg_year']:,.0f} |")
cheapest = min(rs, key=lambda r: r["cash_year"])
best_total = min(rs, key=lambda r: r["total_year"])
fastest = min(rs, key=lambda r: r["minutes_one_way"])
out += ["", "Sorted by total (cash + time cost).", "",
"## Headline", "",
f"- Cheapest in cash: **{cheapest['name']}** ({f(cheapest['cash_month'])}/month).",
f"- Cheapest once time counts: **{best_total['name']}** ({f(best_total['total_month'])}/month at {f(res['value_of_time_per_hour'])}/hour).",
f"- Fastest: **{fastest['name']}** ({fastest['minutes_one_way']:.0f} min one way, {fastest['hours_month']:.1f} h/month)."]
out += ["", f"## Break-even value of time (vs {cheapest['name']}, the cheapest in cash)", "",
"| Option | Extra cash / year | Lost hours saved / year | Worth it if your hour is worth more than |", "|---|---|---|---|"]
for b in res["break_even"]:
if b["break_even_per_hour"] is None:
verdict = "never on cost: it does not save usable time" if b["extra_cash_year"] > 0 else "always: same cash, no more lost time"
hs = f"{b['hours_saved_year']:.0f}" if b["hours_saved_year"] >= 0 else f"none ({-b['hours_saved_year']:.0f} more lost)"
out.append(f"| {b['option']} | {f(b['extra_cash_year'])} | {hs} | {verdict} |")
else:
out.append(f"| {b['option']} | {f(b['extra_cash_year'])} | {b['hours_saved_year']:.0f} | {f(b['break_even_per_hour'])}/hour |")
out += ["", "## Notes per option", ""]
for r in rs:
bd = ", ".join(f"{LABELS.get(k, k)} {f(v / 12)}" for k, v in r["breakdown"].items() if v) if r["breakdown"] else ""
out.append(f"- **{r['name']}** ({r['mode']}): " + "; ".join(([f"per month: {bd}"] if bd else []) + r["notes"]))
out += ["", "Time cost = hours x value of time x (1 - share of the trip you can use for reading or work). "
"Not included: health benefits, accident risk, weather days and the option value of having a car; "
"see references/time-value-and-assumptions.md."]
return "\n".join(out) + "\n"
def self_test():
base = {"currency": "USD", "units": "metric", "one_way_distance": 10, "days_per_week": 5, "weeks_per_year": 48,
"value_of_time_per_hour": 20}
car = {"name": "Car", "mode": "car", "minutes_one_way": 20, "fuel_l_per_100km": 8, "fuel_price": 1.5,
"maintenance_per_distance": 0.05, "parking_per_day": 5}
tr = {"name": "Transit", "mode": "transit", "minutes_one_way": 40, "fare_per_ride": 2.5, "monthly_pass": 80}
bike = {"name": "Bike", "mode": "bike", "minutes_one_way": 35, "purchase_price": 1000, "life_years": 5, "maintenance_per_year": 100}
def ev(*opts, **kw):
sc = dict(base, options=list(opts)); sc.update(kw.pop("sc", {}))
return evaluate(sc, **kw)
def get(res, n):
return next(r for r in res["options"] if r["name"] == n)
cases = []
def case(name, fn):
try:
ok, err = bool(fn()), ""
except Exception as e: # noqa
ok, err = False, repr(e)
cases.append((name, ok, err))
# car: 240 days * 20 km = 4800 km; fuel 384 L * 1.5 = 576; maint 240; parking 1200 -> 2016/year
case("car annual cash (fuel + maintenance + parking)", lambda: abs(get(ev(car), "Car")["cash_year"] - 2016) < 0.01)
case("car CO2 petrol 2.35 kg/L", lambda: abs(get(ev(car), "Car")["co2_kg_year"] - 384 * 2.35) < 0.01)
case("diesel CO2 factor", lambda: abs(get(ev(dict(car, fuel="diesel")), "Car")["co2_kg_year"] - 384 * 2.68) < 0.01)
case("fixed costs excluded unless count_fixed", lambda: get(ev(dict(car, fixed_per_year=1500)), "Car")["cash_year"] == get(ev(car), "Car")["cash_year"])
case("fixed costs included with count_fixed", lambda: abs(get(ev(dict(car, fixed_per_year=1500, count_fixed=True)), "Car")["cash_year"] - 3516) < 0.01)
case("EV uses kWh and electricity price", lambda: abs(get(ev(dict(car, kwh_per_100=18, electricity_price=0.3, fuel_l_per_100km=None)), "Car")["breakdown"]["energy"] - 4800 / 100 * 18 * 0.3) < 0.01)
case("imperial mpg and $/gal", lambda: abs(get(ev({"name": "Car", "mode": "car", "minutes_one_way": 20, "fuel_economy_mpg": 30, "fuel_price": 3.6}, sc={"units": "imperial"}), "Car")["cash_year"] - 4800 / 30 * 3.6) < 0.01)
case("imperial CO2 8.89 kg/gal", lambda: abs(get(ev({"name": "Car", "mode": "car", "minutes_one_way": 20, "fuel_economy_mpg": 30, "fuel_price": 3.6}, sc={"units": "imperial"}), "Car")["co2_kg_year"] - 160 * 8.89) < 0.01)
# transit: per ride 5/day*240 = 1200 vs pass 960 -> pass
case("transit picks monthly pass when cheaper", lambda: abs(get(ev(tr), "Transit")["cash_year"] - 960) < 0.01)
case("transit picks pay-per-ride at 2 days/week", lambda: abs(get(ev(tr, dpw_override=2), "Transit")["cash_year"] - 5 * 96) < 0.01)
case("daily cap applied", lambda: abs(get(ev(dict(tr, monthly_pass=None, daily_cap=4)), "Transit")["cash_year"] - 4 * 240) < 0.01)
case("employer subsidy deducted, never below 0", lambda: get(ev(dict(tr, subsidy_per_month=100)), "Transit")["cash_year"] == 0)
case("bike ownership spread over life", lambda: abs(get(ev(bike), "Bike")["cash_year"] - 300) < 0.01)
case("ebike electricity", lambda: abs(get(ev(dict(bike, name="E", mode="ebike", kwh_per_100=1.5, electricity_price=0.3)), "E")["breakdown"]["energy"] - 4800 / 100 * 1.5 * 0.3) < 0.01)
case("walk has no purchase cost", lambda: get(ev({"name": "Walk", "mode": "walk", "minutes_one_way": 120, "purchase_price": 999}), "Walk")["cash_year"] == 0)
case("time cost = hours x value", lambda: abs(get(ev(car), "Car")["time_cost_month"] - 20 * 2 * 240 / 60 * 20 / 12) < 0.01)
case("usable time share discounts transit time", lambda: abs(get(ev(dict(tr, usable_time_share=0.5)), "Transit")["time_cost_month"] - 40 * 2 * 240 / 60 * 20 * 0.5 / 12) < 0.01)
case("value-of-time override", lambda: get(ev(car, value_override=0), "Car")["time_cost_month"] == 0)
case("per trip = annual cash / trips", lambda: abs(get(ev(car), "Car")["cost_per_trip"] - 2016 / 480) < 0.001)
# mix: bike 60 % of days, transit 40 % -> transit 96 days: per ride 480 vs pass 960 -> per ride
mixo = {"name": "Mix", "mode": "mix", "shares": {"Bike": 0.6, "Transit": 0.4}}
case("mix: bike ownership full + transit pay-per-ride on its days", lambda: abs(get(ev(bike, tr, mixo), "Mix")["cash_year"] - (300 + 480)) < 0.01)
case("mix: time weighted by days", lambda: abs(get(ev(bike, tr, mixo), "Mix")["minutes_one_way"] - (0.6 * 35 + 0.4 * 40)) < 0.01)
multi = {"name": "P+R", "mode": "multi", "transfer_minutes": 5, "legs": [
{"mode": "car", "distance_one_way": 3, "minutes_one_way": 8, "fuel_l_per_100km": 8, "fuel_price": 1.5, "parking_per_day": 2},
{"mode": "transit", "distance_one_way": 7, "minutes_one_way": 20, "fare_per_ride": 2.5, "monthly_pass": 80}]}
case("multi: legs summed + transfer", lambda: (lambda r: abs(r["minutes_one_way"] - 33) < 0.01 and abs(r["cash_year"] - (1440 * 0.08 * 1.5 + 480 + 960)) < 0.01)(get(ev(multi), "P+R")))
case("break-even: car vs cheapest", lambda: (lambda res: (lambda b: abs(b["break_even_per_hour"] - (2016 - 300) / ((35 - 20) * 2 * 240 / 60)) < 0.01)(next(b for b in res["break_even"] if b["option"] == "Car")))(ev(car, bike)))
case("break-even uses lost hours (usable transit time)", lambda: next(b for b in ev(dict(tr, usable_time_share=0.75, subsidy_per_month=60), bike)["break_even"] if b["option"] == "Bike")["break_even_per_hour"] is None)
case("break-even: slower and dearer -> None", lambda: next(b for b in ev(car, tr, bike)["break_even"] if b["option"] == "Transit")["break_even_per_hour"] is None)
case("render has headline and table", lambda: "Cheapest in cash: **Bike**" in render(ev(car, tr, bike)) and "| Car |" in render(ev(car, tr, bike)))
case("render uses currency symbol", lambda: "€" in render(ev(car, sc={"currency": "EUR"})))
def bad(*opts, **sc):
try:
ev(*opts, sc=sc); return False
except InputError:
return True
case("mix shares must sum to 1", lambda: bad(bike, tr, dict(mixo, shares={"Bike": 0.6, "Transit": 0.6})))
case("mix share must name an option", lambda: bad(bike, dict(mixo, shares={"Bike": 0.5, "Train": 0.5})))
case("unknown mode rejected", lambda: bad({"name": "Boat", "mode": "boat", "minutes_one_way": 5}))
case("duplicate names rejected", lambda: bad(car, car))
case("missing fuel economy rejected", lambda: bad({"name": "Car", "mode": "car", "minutes_one_way": 20, "fuel_price": 1.5}))
case("negative price rejected", lambda: bad(dict(car, fuel_price=-1)))
case("bad units rejected", lambda: bad(car, units="furlongs"))
case("usable share above 1 rejected", lambda: bad(dict(tr, usable_time_share=1.5)))
passed = 0
for name, ok, err in cases:
passed += ok
print(("PASS " if ok else "FAIL ") + name + ("" if ok else f" {err}"))
print(f"{passed}/{len(cases)} passed")
return 0 if passed == len(cases) else 1
def main(argv=None):
ap = argparse.ArgumentParser(description="Compare commute options per month and year, including time value")
ap.add_argument("scenario", nargs="?")
ap.add_argument("--value-of-time", type=float, help="override value_of_time_per_hour")
ap.add_argument("--days-per-week", type=float, help="override days_per_week (e.g. 3 for hybrid work)")
ap.add_argument("--json", action="store_true")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.scenario:
ap.error("give a scenario JSON file, or --self-test")
try:
with open(a.scenario, encoding="utf-8") as fh:
sc = json.load(fh)
if a.days_per_week is not None and not 0.5 <= a.days_per_week <= 7:
raise InputError("--days-per-week must be 0.5..7")
res = evaluate(sc, a.value_of_time, a.days_per_week)
except json.JSONDecodeError as e:
print(f"error: scenario is not valid JSON: {e}", file=sys.stderr)
return 2
except (OSError, InputError, UnicodeDecodeError) as e:
print(f"error: {e}", file=sys.stderr)
return 2
print(json.dumps(res, indent=2) if a.json else render(res), end="" if not a.json else "\n")
return 0
if __name__ == "__main__":
sys.exit(main())Animate the step 2 hot spring image as the first frame into a calm 6-second shot: a slow push-in toward the pool and the inn, steam drifting and curling over the teal water, snow falling, lanterns and windows glowing steadily, and a clump of snow dropping from a pine branch into the pool with a small splash and spreading ripples. Step 3 of the Snowy Mountain Onsen at Dusk workflow.
Start from the step 2 image "Steaming Outdoor Hot Spring Beside a Snowy Mountain Inn at Blue Hour" as the exact first frame, and animate it into a calm 6-second cinematic shot. Keep the teal hot spring pool, the dark snow-capped rocks around it, the small stone lantern on the left, the larger stone lantern on the right, the two-storey wooden inn with its snowy roofs and warmly lit windows, the snow-laden pine trees, the dark mountain slope, the deep blue twilight sky, and the composition exactly as in the image. The camera makes a slow, gentle push-in toward the pool and the inn. Thick white steam drifts and curls slowly over the water and rises toward the trees. Large soft snowflakes keep falling evenly across the scene. The lanterns and the inn windows glow steadily without flickering. About two thirds of the way through, a small clump of snow slips off a pine branch above the pool and drops straight down into the water near the center, making a small white splash and soft ripples that spread outward and fade. The shot ends calm, with the steam still drifting. Natural, realistic motion, no cuts, no people, no animals, no new objects, no text. Soft sound of bubbling water, a quiet splash, and the hush of falling snow.
Photoreal blue-hour snowfall scene: a steaming rock-lined hot spring of clear teal water fills the foreground, framed by dark snow-capped rocks, with a small glowing stone lantern on the left, a larger one beside a two-storey wooden inn with snowy tiled roofs and warmly lit windows on the right, snow-laden pines, and a dark mountain slope under a deep blue sky. Step 2 of the Snowy Mountain Onsen at Dusk workflow.
A steaming outdoor hot spring pool beside a traditional Japanese mountain inn during gentle snowfall at blue hour, lit by two glowing stone lanterns, seen from a low viewpoint at the edge of the water, in a wide landscape 16:9 frame. A natural pool of clear teal water with a faint green glow fills the center and lower middle of the frame, framed by dark, rounded volcanic rocks with thick caps of fresh snow in the foreground and along both sides. Thick white steam rises from the water, strongest over the left and center of the pool, drifting up and softening the trees behind. On the left rocks stands a small snow-capped stone lantern with a warm glowing window; on the right, close to the inn, stands a larger stone lantern with a wide snow-covered cap, also glowing warm amber. On the right side of the frame rises a two-storey traditional wooden inn with dark timber walls, deep eaves, and snow-covered tiled roofs, its long rows of paper and glass windows glowing warm amber from inside. Behind the pool, tall pine trees are heavy with snow, and on the left a dark forested mountain slope rises against a deep blue twilight sky. Large soft snowflakes fall across the whole scene. Cool blue ambient light with warm amber accents from the windows and lanterns, photoreal travel and landscape photography, natural colors, quiet, warm, and peaceful mood. No people, no text, no logos.
Turn a short idea into an image-ready and motion-ready brief for one hero shot of a steaming outdoor hot spring beside a snowy traditional mountain inn at blue hour: pool and rocks, steam, the inn and its lit windows, stone lanterns, pines and mountain, light and snowfall, fixed details, a motion map, and two prompt seeds: a 16:9 still image and an image-to-video animation.
Act as a cinematic landscape designer who writes image-ready and motion-ready scene briefs. Help me design one hero shot of a steaming outdoor hot spring (onsen) beside a traditional mountain inn during snowfall at dusk. The shot will first be generated as a still image and then animated into a short video that uses that image as its first frame. Your brief must make the still image rich in elements that can move naturally (steam drifting and curling over the water, snowflakes falling, soft snow slipping off a pine branch, gentle ripples on the pool, the warm glow of lanterns and windows) while keeping the composition calm, balanced, readable, and easy to animate. My starting idea: a steaming rock-lined hot spring in the snow next to an old wooden inn, at blue hour, with stone lanterns My starting choices: - Pool: a natural outdoor pool of clear teal water framed by dark volcanic rocks capped with snow, filling the center and foreground - Steam: thick white steam rising from the water and drifting to one side - Inn: a two-storey traditional Japanese wooden inn on the right with snow-covered tiled roofs and rows of warmly lit windows - Lanterns: two snow-capped stone lanterns glowing softly, one small on the left rocks and one larger near the inn - Trees and mountains: snow-laden pine trees behind the pool and a dark forested mountain slope on the left - Weather: large soft snowflakes falling slowly - Time and light: deep blue twilight just after sunset, warm amber light from the inn and lanterns - Visual style: photoreal travel and landscape photography, natural colors - Mood words: quiet, warm, peaceful, wintry, inviting First ask me, in one short message, for anything missing: the camera height (low near the water, eye level, or slightly raised), how much of the frame the inn should take, how dense the steam and snowfall should be, how bright the windows and lanterns are, whether I want one small natural event in the video (for example a clump of snow sliding off a pine branch into the pool), and anything to avoid (people, bathers, animals, text, signs, logos, or copying a specific real inn, photograph, or named landmark). Then produce the brief with these sections: 1. **Scene Overview**: two or three sentences on the place, the moment, the light, and the feeling. Describe an imagined mountain hot spring inn in a Japanese spirit, not a copy of a specific real ryokan or a famous photograph. 2. **The Pool and Rocks**: the pool's shape and size in the frame, the water color and clarity, the dark rocks around it and the snow on their tops, and where the water catches warm and cool light. 3. **Steam**: how thick it is, where it rises most, which way it drifts, how it softens the background, and how it should read as warm vapor rather than fog or smoke. 4. **The Inn**: its position, number of storeys, roof shape and the snow on it, the wooden walls, the rows of lit windows, and how much detail is visible through the steam and snow. 5. **Lanterns, Trees, and Mountain**: the two stone lanterns with snow caps and their glow, the snow-laden pines behind the pool (including one branch above the water that could shed snow), and the dark mountain slope against the sky. 6. **Light, Sky, and Snow**: the deep blue twilight sky, the cool ambient light on the snow, the warm amber accents from the windows and lanterns, the size and density of the falling snowflakes, and how soft the shadows are. 7. **Fixed Visual Details**: a numbered list of 8 to 10 details that must stay identical in the still image and in the video (pool shape and position, rock edges, inn position and roofline, window pattern, both lantern positions, pine trees, mountain silhouette, camera position, framing, overall steam zone). 8. **Motion Map**: a table of every element that can move in the video, with columns: element, type of motion, direction, speed (very slow, slow, medium), and how strongly it should move. Include the steam, the snowfall, the water surface, the lantern and window glow, one optional snow clump falling from a pine branch into the pool with a small splash and ripples, and the camera move. Keep total motion subtle and physically plausible, with one gentle air direction. 9. **Prompt Seed A - Hero Still Image**: a ready-to-paste image prompt under 170 words for a wide landscape 16:9 frame, with the steaming hot spring, the snowy inn, and the stone lanterns at blue hour in the first sentence, ending with: no people, no text, no logos. 10. **Prompt Seed B - Image-to-Video Animation**: a ready-to-paste video prompt under 120 words that starts from the hero still as the first frame, describes the steam drifting and curling, snow falling, the steady glow of lanterns and windows, a slow gentle push-in toward the pool and the inn for about 6 seconds, and (if I want it) one clump of snow falling from a pine branch into the pool with a small splash and spreading ripples, and says to keep the pool, rocks, inn, lanterns, trees, and framing exactly as in the image with no new objects. Rules: no people, bathers, or animals; no text, signs, or logos; no fast camera moves or cuts; and no motion that breaks physics (rocks, lanterns, and the inn never move, steam rises and drifts and does not pour downward, snow falls slowly and evenly, a falling snow clump drops straight down under gravity and makes only a small splash, the light does not flicker or jump). Use short paragraphs and lists.

Flat mid-century screen-print travel poster in portrait 3:4, no text: a big mustard sun disc in a pale yellow sky, steep grey and green cliffs with snow patches and a thin white waterfall framing the fjord, snowy peaks at its end, deep teal water with white wave lines, a small red-and-white ferry with a wake in the lower left, and red wooden houses with white roofs on the right shore.
A mid-century modern travel poster illustration of a Norwegian fjord with a small red ferry, in a portrait 3:4 frame, in a flat screen-print style with no text. A large, perfectly round mustard-yellow sun disc hangs at the top center in a pale butter-yellow sky. Steep cliffs rise on both sides like a gateway: on the left, tall slate-grey rock faces with olive-green grassy ledges and white snow patches, with a long, thin white waterfall tumbling down the cliff into the water; on the right, a grey cliff with snow on its upper slopes and a dark green forested hillside below. At the far end of the fjord, sharp snow-covered mountain peaks in white and pale grey close the view in the center. The deep teal-blue water fills the lower third, drawn with simple white and light-blue wave lines and reflections. In the lower left foreground, a small red-and-white ferry with a white cabin, a red upper deck, and a short mast sails toward the right, leaving a white wake trailing behind it to the left. On a grassy point along the right shore sits a small village of about six red wooden houses with white roofs, with a few dark green trees and a pale rocky shoreline. Limited palette of slate grey, teal blue, olive and forest green, red, cream, and mustard yellow, crisp simplified shapes, subtle halftone and visible paper grain texture, vintage 1950s travel advertising mood. No text, no lettering, no logos.
Animate the step 2 bamboo forest footpath image as the first frame into a calm 6-second shot: the camera dollies slowly along the stepping stones toward the wooden footbridge, fireflies drift and blink, bamboo sways gently, low mist rolls over the path, the stream glints, and the deep blue twilight holds. Step 3 of the Bamboo Forest Firefly Path workflow.
Start from the step 2 image "Bamboo Forest Footpath with Fireflies and a Wooden Footbridge at Dusk" as the exact first frame, and animate it into a calm 6-second cinematic shot. Keep the stepping-stone path, the shallow stream running down its center, the small arched wooden footbridge in the middle distance, the tall bamboo walls on both sides, the gap of deep blue twilight sky, the mist around the bridge, and the composition exactly as in the image. The camera makes a very slow, smooth dolly forward along the path toward the bridge. The yellow-green fireflies drift gently through the air and blink softly on and off at different times. The bamboo stems and leaves sway slightly in a light breeze, all in the same direction. Low mist rolls slowly over the path and around the bridge, and the stream glints and ripples as it flows toward the camera. The cool blue twilight light stays steady. Natural, realistic motion, no cuts, no people, no animals, no new objects, no text. Soft sound of trickling water, rustling bamboo leaves, and evening insects.
Photoreal dusk landscape: a stepping-stone path runs straight ahead between tall bamboo walls toward a small arched wooden footbridge, a shallow stream trickles down the middle of the path from under the bridge, hundreds of yellow-green fireflies glow in the air and undergrowth, low mist hangs around the bridge, and a deep blue twilight sky shows through the canopy. Step 2 of the Bamboo Forest Firefly Path workflow.
A quiet stepping-stone footpath runs straight ahead through a tall bamboo forest at dusk, lit by hundreds of glowing fireflies, toward a small arched wooden footbridge in the middle distance, seen from a low, centered viewpoint at the start of the path, in a wide landscape 16:9 frame. Large flat grey stepping stones lead from the bottom center of the frame toward the bridge, with a shallow stream trickling down the middle of the path over small stones, flowing out from under the bridge and catching faint blue light. Dense walls of tall, slender green bamboo with visible nodes rise on both sides and lean slightly inward, their leafy tops framing a narrow gap of deep blue twilight sky with soft clouds at the top center. The small wooden bridge has a gentle arch and simple railings, with a pale opening beneath it. Low white mist hangs around the bridge and drifts over the path and the undergrowth. Many tiny yellow-green fireflies glow scattered through the air, among the bamboo, and over the ferns, grasses, and mossy rocks along both edges of the path. Cool blue twilight ambience with warm green-yellow firefly accents, photoreal night landscape photography, natural colors, calm and magical mood. No people, no text, no logos.
Turn a short idea into an image-ready and motion-ready brief for one hero shot of a stepping-stone path through a tall bamboo forest at dusk with fireflies and a small wooden footbridge: path and stream, bamboo walls and canopy, bridge, fireflies, light and mist, fixed details, a motion map, and two prompt seeds: a 16:9 still image and an image-to-video animation.
Act as a cinematic landscape designer who writes image-ready and motion-ready scene briefs. Help me design one hero shot of a quiet footpath through a tall bamboo forest at dusk, lit by fireflies. The shot will first be generated as a still image and then animated into a short video that uses that image as its first frame. Your brief must make the still image rich in elements that can move naturally (fireflies drifting and blinking, bamboo stems and leaves swaying, low mist rolling over the ground, a shallow stream glinting, the last blue light of twilight) while keeping the composition calm, symmetrical, readable, and easy to animate. My starting idea: a stone path between tall bamboo at dusk, with fireflies and a little wooden bridge My starting choices: - Path: an old stepping-stone path running straight away from the camera toward the center of the frame - Bamboo: tall, dense green bamboo stems rising on both sides, their tops closing into a canopy with a gap of sky in the middle - Water: a shallow stream trickling down the middle of the path over stones - Focal point: a small arched wooden footbridge with railings crossing in the middle distance - Fireflies: many small glowing yellow-green fireflies scattered through the air and the undergrowth - Atmosphere: low mist hanging around the bridge and over the path - Time and light: deep blue twilight just after sunset, a few clouds in the sky gap - Visual style: photoreal night landscape photography, natural colors - Mood words: calm, magical, hushed, inviting First ask me, in one short message, for anything missing: the camera height (low near the stones, standing eye level, or slightly raised), how centered and symmetrical I want the path, how bright and how many fireflies, how much mist, whether the bridge should be close or far, and anything to avoid (people, animals, lanterns, buildings, text, logos, or copying a specific real photograph or a named landmark). Then produce the brief with these sections: 1. **Scene Overview**: two or three sentences on the place, the moment, the light, and the feeling. Describe an imagined bamboo forest in an East Asian spirit, not a copy of a specific photograph or a famous real grove. 2. **Path and Stream**: the shape and line of the stepping stones toward the vanishing point, the stone texture and moss, how the shallow stream runs down the path from under the bridge, and where the water catches light. 3. **Bamboo Walls and Canopy**: stem thickness, spacing, and nodes on each side, how they rise and lean inward, the leaf canopy, the gap of sky, and the ferns and grasses at their feet. 4. **The Footbridge**: size in the frame, shape of the arch, the wooden railings, the darker opening under it, and how mist gathers around it. 5. **Fireflies**: density, size, color, how they are spread through the air, the undergrowth, and the depth layers, and how their glow should read against the dark bamboo without looking like stars or bokeh dust. 6. **Light, Sky, and Mist**: the twilight sky gradient in the canopy gap, the cool blue ambient light, the warm-green firefly accents, the layers of mist, and how soft the shadows are. 7. **Fixed Visual Details**: a numbered list of 8 to 10 details that must stay identical in the still image and in the video (path line, stream position, bridge position and shape, bamboo walls on both sides, sky gap shape, mist zones, camera position, framing, overall firefly distribution). 8. **Motion Map**: a table of every element that can move in the video, with columns: element, type of motion, direction, speed (very slow, slow, medium), and how strongly it should move. Include the fireflies (drift and blink), the bamboo stems and leaves, the mist, the stream, the light, and the camera move. Keep total motion subtle and physically plausible, with one breeze direction. 9. **Prompt Seed A - Hero Still Image**: a ready-to-paste image prompt under 170 words for a wide landscape 16:9 frame, with the bamboo path, the fireflies, and the footbridge at dusk in the first sentence, ending with: no people, no text, no logos. 10. **Prompt Seed B - Image-to-Video Animation**: a ready-to-paste video prompt under 120 words that starts from the hero still as the first frame, describes the fireflies drifting and blinking, the bamboo swaying gently, the mist rolling low, the stream glinting, one very slow dolly forward along the path toward the bridge for about 6 seconds, and says to keep the path, bamboo, bridge, sky, and framing exactly as in the image with no new objects. Rules: no people, animals, lanterns, or buildings; no text, signs, or logos; no fast camera moves or cuts; and no motion that breaks physics (bamboo bends from the base and does not stretch, the bridge and stones never move, fireflies drift slowly and do not streak, the light does not jump). Use short paragraphs and lists.

Loose watercolor on textured paper: three covered black gondolas moored beside red-and-white striped mooring poles on the Grand Canal at dawn, a domed baroque basilica silhouette and hazy palazzos with a bell tower across the water, a soft peach and lavender sky, and broken violet and pink reflections in calm water.
A loose, atmospheric watercolor painting of covered gondolas moored on the Grand Canal in Venice at dawn, in a landscape 4:3 frame on textured cold-press watercolor paper. In the lower left, three long black gondolas rest side by side, wrapped in dark blue-grey covers, one with a pale tan tarp, the front gondola's curved prow and metal prow ornament rising at the far left edge. Tall wooden mooring poles with red-and-white spiral stripes and small pointed caps stand in the water across the middle and right of the frame, some linked to the gondolas by sagging ropes and chains. Across the canal, a hazy, softly painted skyline of old palazzos stretches to the right, with a slender bell tower, and on the left a large domed baroque basilica with smaller domes and lanterns, in the spirit of Santa Maria della Salute, silhouetted against the light. The sky glows in soft peach, apricot, and lavender washes with drifting clouds. The calm water reflects the poles, gondolas, and sky in broken vertical strokes of violet, pink, and white. Visible brushstrokes, wet-in-wet blooms, granulating pigments, soft edges, and white paper showing through. Peaceful, romantic early-morning mood. No people, no text, no signature.
Turn your family, campground, dates, and gear into a YAML camping weekend plan: booking and rules to confirm, weather, water, fire, and lost-child safety, a packing list by category with own, borrow, rent, or buy, campsite setup, kid-friendly meals and a cooler plan, a daily schedule around naps with rainy-day backups, sleep tips, family jobs, leave-no-trace pack-up, and a post-trip review.
1role: Friendly, safety-minded family camping planner who helps parents organize a relaxed campground weekend with children, from booking and packing to meals, sleep, activities, and leaving no trace, so the trip is fun for the kids and manageable for the adults2task: >3 Turn my family, destination, dates, and gear into a complete family camping weekend plan as YAML:4 a trip summary with readiness and risks, a booking and permits checklist, a weather and safety plan,5 a shared and per-person packing list by category, a campsite setup plan, a simple meal plan with a6 cooler and food storage strategy, a kid-friendly schedule for each day with quiet times and backup7 rainy-day ideas, sleep and comfort tips for children, chores for every family member, a pack-up and8 leave-no-trace checklist, and a short post-trip review.910inputs:...+113 more lines
Animate the step 2 Dutch windmill canal image as the first frame into a calm 6-second shot: the nearest windmill's lattice sails turn clearly while the distant sails turn too, the camera pushes slowly along the canal, reflections shimmer, reeds sway, the moored rowboat stays still, and the soft pink and gold sunrise light holds. Step 3 of the Dutch Windmill Canal workflow.
Start from the step 2 image "Five Brick Windmills Along a Misty Dutch Canal at Sunrise" as the exact first frame, and animate it into a calm 6-second cinematic shot. Keep the five brick windmills on the left bank, the large nearest windmill in the left third with its wooden tail brace, the straight canal, the moored rowboat in the lower left, the grassy dike path and reeds on the right bank, the misty meadow, the horizon line, and the composition exactly as in the image. In a gentle breeze, the lattice sails of the nearest windmill turn slowly and clearly around their hub, and the sails of the distant windmills turn too, all in the same direction. The camera makes a very slow, steady push-in along the canal toward the vanishing point. The mirror reflections on the canal shimmer softly, the reeds along both banks sway gently, and the rowboat stays still at its mooring. The light stays a soft pink and gold sunrise glow. Natural, realistic motion, no cuts, no people, no new buildings or objects, no text. Soft sound of a light breeze, creaking sails, and distant birdsong.

Photoreal sunrise landscape: five brick windmills with dark caps and lattice sails in a row along the left bank of a straight, mirror-calm polder canal, the nearest one large on the left with a wooden tail brace, a small wooden rowboat moored lower left, a grassy dike path with reeds on the right, low mist over the meadow, and a pink, lilac, and gold sky. Step 2 of the Dutch Windmill Canal workflow.
Five traditional brick windmills stand in a row along the left bank of a long, straight, calm Dutch polder canal at sunrise, seen from a low viewpoint at the water's edge, in a wide landscape 16:9 frame. The nearest windmill is large in the left third: a round, tapered brown brick body with small windows, a dark cap, and four wooden lattice sails in a tilted X shape, with a long wooden tail and brace poles slanting down to the ground on its left side. The other four windmills recede along the same left bank toward a vanishing point near the center, each smaller and softer in the mist. The canal runs straight into the distance with mirror-like reflections of the windmills and the sky. In the lower left, a small dark wooden rowboat is moored among green reeds, tied with a rope. On the right bank, a grassy dike with tall reeds along the water and a narrow dirt path runs into the distance, beside a flat meadow with low morning mist and a faint distant tree line. The sky glows soft lilac, pink, and gold with thin streaky clouds, brightest near the horizon just right of center. Photoreal landscape photography, wide angle, natural colors, peaceful mood. No people, no text, no logos.
Build an image-ready and motion-ready brief for one hero shot of brick windmills along a straight, calm Dutch polder canal at sunrise: windmills, canal reflections, banks and rowboat, landscape depth, light, fixed details, a motion map, and two prompt seeds: a 16:9 still image and an image-to-video animation.
Act as a cinematic landscape designer who writes image-ready and motion-ready scene briefs. Help me design one hero shot of traditional brick windmills standing along a straight, calm Dutch polder canal at sunrise. The shot will first be generated as a still image and then animated into a short video that uses that image as its first frame. Your brief must make the still image rich in elements that can move naturally (windmill sails turning slowly, mirror reflections shimmering on the canal, reeds swaying at the water's edge, low morning mist over the meadows, the soft sunrise glow) while keeping the composition calm, readable, and easy to animate. My starting choices: - Windmills: five round tapered brick windmills with dark caps and wooden lattice sails, standing in a row along one bank - Canal: a long straight canal with still, mirror-like water receding to a vanishing point - Banks: grass and reeds on both sides, a narrow dirt path along a grassy dike on the opposite bank - Foreground detail: a small dark wooden rowboat moored at the water's edge - Landscape: flat green meadows with low mist and a distant line of trees - Time and light: sunrise, soft pink, lilac, and gold sky with a warm glow near the horizon - Visual style: photoreal landscape photography, natural colors - Mood words: peaceful, quiet, timeless, fresh First ask me, in one short message, for anything missing: the camera position I prefer (low at the water's edge, standing height on the bank, or slightly elevated), which bank the windmills should stand on, how close the nearest windmill should be, where the sunrise glow should sit, how much mist I want, and anything to avoid (people, cyclists, boats in motion, cars, modern wind turbines, power lines, signs, text, logos, or copying a specific real photograph). Then produce the brief with these sections: 1. **Scene Overview**: two or three sentences describing the place, the time, the light, and the feeling of the moment. Describe an imagined polder scene in the spirit of the Netherlands, not a copy of a specific photograph or a named landmark. 2. **Windmills**: how many windmills, which bank they stand on, the size of the nearest one in the frame, their brick bodies, caps, small windows, lattice sails and the angle of the sails, the wooden tail or brace structure, and how the low light falls on them. 3. **Canal and Reflections**: the line of the canal toward the vanishing point, how still the water is, which shapes are mirrored, and how the sky colors appear in the water. 4. **Banks and Foreground**: the reeds and grass on each bank, the dike path, the moored rowboat and its rope, and the texture of the closest plants. 5. **Landscape and Depth**: the depth layers from the foreground boat and reeds to the nearest windmill, the receding windmills, the meadows, and the distant tree line, and how mist softens each layer. 6. **Light and Sky**: the position of the sunrise glow, the sky gradient from lilac to pink to gold, the shape of the thin clouds, and how soft the shadows are. 7. **Fixed Visual Details**: a numbered list of 8 to 10 details that must stay identical in the still image and in the video (number and bank of the windmills, nearest windmill position and sail angle, canal line, rowboat position, dike path, horizon line, glow position, cloud layout, camera position, framing). 8. **Motion Map**: a table of every element that can move in the video, with columns: element, type of motion, direction, speed (very slow, slow, medium), and how strongly it should move. Include the sails of each windmill, the reflections, the reeds, the mist, the light, the rowboat, and the camera move. Keep total motion subtle and physically plausible, with one wind direction and all sails turning the same way. 9. **Prompt Seed A - Hero Still Image**: a ready-to-paste image prompt under 170 words for a wide landscape 16:9 frame, with the windmills, the canal, and the sunrise in the first sentence, ending with: no people, no text, no logos. 10. **Prompt Seed B - Image-to-Video Animation**: a ready-to-paste video prompt under 120 words that starts from the hero still as the first frame, describes the sails turning slowly, the reflections shimmering, the reeds swaying, one very slow push-in along the canal for about 6 seconds, and says to keep the windmills, canal, banks, boat, and framing exactly as in the image with no new objects. Rules: no people, animals that must move convincingly, vehicles, or modern turbines; no text, signs, or logos; no fast camera moves or cuts; and no motion that breaks physics (sails rotate around their hub without changing shape, buildings never move, reflections follow the objects above them, the light does not jump). Use short paragraphs and lists.

Photoreal long-exposure night shot: an empty yellow sea kayak in the center of a calm tropical bay, electric-blue bioluminescent trails swirling behind it toward the lower left, a dark mangrove shoreline on the left, the Milky Way arching over the upper right, and a few tiny distant lights on the horizon.
A photorealistic night photograph of a single empty yellow sea kayak floating on a calm tropical bay that glows with electric-blue bioluminescent plankton, under the Milky Way, in a wide landscape 16:9 frame. The long yellow kayak sits in the center of the frame, angled toward the upper right, with black round deck hatches, a dark open cockpit, and thin deck lines; no paddle and no person. Behind and around it, bright electric-blue glowing trails swirl and spread across the dark water toward the lower left corner, like light ribbons stirred up by its passage. A dark silhouette of a mangrove tree line runs along the left shore, its tangled roots just above the waterline, tapering into a low horizon near the center. The Milky Way arches across the upper right of the sky with soft dust lanes and a pale glow, over a dense field of tiny stars in deep navy blue. The water is glassy and dark, with faint star reflections and gentle ripples, and a few tiny warm lights twinkle on the far horizon at the right. Long-exposure astrophotography look, wide-angle lens, sharp detail, natural colors, quiet and magical mood. No people, no text.