Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ The command is `mogs`.

## Usage

Create an assignment (replace `<name`> with your assignment name) and edit it in marimo's editor:
Create an assignment (replace `<name>` with your assignment name) and edit it in marimo's editor:

```bash
mogs init <name>
Expand All @@ -41,7 +41,7 @@ This will create a directory called `<name>` with `<name>.py` inside.
You can change `<name>.py` if you want.
This Python file is a marimo notebook and it has a short guide and two example questions (see docs; full example [here](https://github.com/wiseodd/mogs/tree/main/examples/demo)).

Say, the assignment name is `demo` directory (relative to the current working directory) and named `hw.py`.
Say the assignment is in the directory `demo`, with the notebook `demo/hw.py`.
Then:

```bash
Expand Down
17 changes: 15 additions & 2 deletions docs/src/content/docs/instructors.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ The source notebook is a regular marimo notebook with a few conventions.

Put all imports in the setup cell (`with app.setup:`).
This includes `import mogs` and any library the tests need.
Tests don't need `import pytest`.
If the notebook imports it, e.g., for `pytest.raises`, list `pytest` in `dependencies`.

```python
with app.setup:
Expand Down Expand Up @@ -209,8 +211,10 @@ Put the public tests of each question in their own cell, with nothing else in it
A public test cell can't contain solution markers.
Students get the public tests as written.
The tests are plain `pytest` functions, and you can run them all with `pytest notebook.py`.
Fixtures such as `capsys` don't work: the grader calls each test without arguments.

Hidden tests go in a separate cell with a `# HIDDEN` line:
Hidden tests go in a separate cell with a `# HIDDEN` line.
The line hides the whole cell wherever it sits in it, as long as it is on a line of its own:

```python
@app.cell
Expand All @@ -234,6 +238,9 @@ def _():
return
```

The points are split evenly across the question's public and hidden tests.
Tests have no weights of their own, and a test that uses random numbers sets its own seed.

In the student notebook, the grade cell shows the question's points and whether each public test passes.
It updates whenever the student edits their code.
In your source notebook it also runs the hidden tests, but it doesn't rerun when you edit a solution: run it again by hand.
Expand Down Expand Up @@ -276,17 +283,21 @@ To check what each question's text is, read the output of `mogs build` or the `m
Both list the first line of each text cell of a written question, or "no question text".

When the student clicks the export button, the answers go into a PDF, each after its text, with the LaTeX math rendered.
Each question starts on a new page under its title.
The PDF doesn't carry the student's name.
The PDF goes into the submission zip, together with the notebook.
An answer the student left blank or unchanged shows as *No answer.* in the PDF, and the export warns about it.

A written question can be worth 0 points, e.g., `mogs.grade("q5", points=0)`.
Its answer goes into the PDF, but it doesn't count toward the total.
Use this for a written exercise that you want to read but not grade.

The PDF renders inline math in `$...$` and display math in `$$...$$`, including environments such as `aligned`, `cases` and `pmatrix`.
The PDF renders inline math in `$...$` or `\(...\)` and display math in `$$...$$` or `\[...\]`, as marimo does, including environments such as `aligned`, `cases` and `pmatrix`.
A paragraph that is only an `align`, `equation` or `gather` environment (starred or not) is display math too, without the `$$`, as in marimo.
The environment has to start the paragraph and end it, with no blank line inside.
Other environments without `$$` show as source.
A `$...$` formula on a line of its own is still inline math.
[MiTeX](https://github.com/mitex-rs/mitex) converts the math to Typst.

Some things can't be rendered.
LaTeX that the PDF doesn't support (e.g., TikZ) shows as source, and so does question text that isn't plain `mo.md(...)`.
Expand Down Expand Up @@ -363,6 +374,7 @@ mogs grade examples/demo submission.py
```

This uses the same grader and the same requirements as Gradescope.
Use it to try the autograder on a submission before you upload the zip.
The submission can be the zip a student exported, a directory with the notebook (e.g., an upload downloaded from Gradescope), or the notebook's `.py` file.
A zip is unpacked into a temporary directory and searched the same way Gradescope searches an upload.
Any other file is refused.
Expand Down Expand Up @@ -406,6 +418,7 @@ To set up the assignment on Gradescope:
2. Pick an Ubuntu 22.04 base image and upload the autograder zip.
3. Pick a container with more memory than `memory`, and a timeout longer than `budget`.
4. If the assignment has written answers, add manually graded questions to the same assignment.
Graders read the answers in the PDF, which is one of the submission's files.

Then, upload `dist/autograder/hw.py` as a test submission to check the autograder.
It should get full marks.
Expand Down
53 changes: 39 additions & 14 deletions src/mogs/pdf.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
"""PDF of the written answers, for questions graded by hand.
r"""PDF of the written answers, for questions graded by hand.

Typst renders the PDF in-process, from the `typst` package of the `pdf` extra. Per question
the PDF has a heading, then the `prompt_<qid>` and `answer_<qid>` cells in notebook order, so
each answer follows its own prompt. A page break separates questions. A cell that is just
`mo.md("...")` shows as Markdown with LaTeX math (through the vendored Typst packages cmarker
and mitex); any other cell shows its source. As in marimo, a paragraph that is just an `align`,
`equation` or `gather` environment, starred or not, is display math too.
and mitex); any other cell shows its source. As in marimo, `\(...\)` and `\[...\]` are math,
and a paragraph that is just an `align`, `equation` or `gather` environment, starred or not, is
display math too.

The cell text reaches Typst as data in `sys.inputs`, never as Typst source. Typst cannot
recover from an error inside a document, so a cell that breaks the document is rendered again
Expand Down Expand Up @@ -208,21 +209,24 @@ class Question:

@dataclass(frozen=True, slots=True)
class Formula:
r"""A `$...$` or `$$...$$` formula in Markdown, or a bare display environment.
r"""A `$...$`, `$$...$$`, `\(...\)` or `\[...\]` formula in Markdown, or a bare environment.

Attributes:
start: Offset of the opening dollar sign or `\begin`.
end: Offset just past the closing dollar sign or `\end{...}`.
source: The LaTeX between the dollar signs, or the whole environment.
start: Offset of the opening delimiter or `\begin`.
end: Offset just past the closing delimiter or `\end{...}`.
source: The LaTeX between the delimiters, or the whole environment.
display: Whether it is display math.
environment: Whether it is a bare environment, which Typst gets inside `$$`.
bracket: Whether it is written `\(...\)` or `\[...\]`, which Typst gets inside `$` or
`$$` instead.
"""

start: int
end: int
source: str
display: bool
environment: bool = False
bracket: bool = False


def render_manual_pdf(
Expand Down Expand Up @@ -352,10 +356,10 @@ def cell_markdown(nb: Notebook, cell: Cell) -> str:


def find_formulas(text: str) -> list[Formula]:
r"""The `$...$` and `$$...$$` formulas in Markdown, in order.
r"""The `$...$`, `$$...$$`, `\(...\)` and `\[...\]` formulas in Markdown, in order.

Code spans, fenced code blocks and `\$` are skipped. A formula does not span a blank
line; a dollar sign without a partner is text. A paragraph that is just an `align`,
line; a delimiter without a partner is text. A paragraph that is just an `align`,
`equation` or `gather` environment, starred or not, is a display formula, as in marimo.
"""

Expand All @@ -369,6 +373,18 @@ def find_formulas(text: str) -> list[Formula]:
case "\\" if environment := _environment(text, start, end, index):
formulas.append(environment)
index = environment.end
case "\\" if text.startswith(("\\(", "\\["), index):
closing = "\\)" if text[index + 1] == "(" else "\\]"
close = _closing(text, index + 2, end, closing)

if close is None:
index += 2
continue

source = text[index + 2 : close]
display = closing == "\\]"
formulas.append(Formula(index, close + 2, source, display, bracket=True))
index = close + 2
case "\\":
index += 2
case "`":
Expand Down Expand Up @@ -429,11 +445,19 @@ def _paragraph_starts(text: str, start: int, index: int) -> bool:


def _delimited(text: str) -> str:
"""`text` with each bare environment put inside `$$`, so cmarker hands it to mitex."""
r"""`text` with its formulas in dollar signs, so cmarker hands them to mitex.

A bare environment goes inside `$$`; `\(...\)` and `\[...\]` become `$...$` and `$$...$$`.
"""

for formula in reversed(find_formulas(text)):
before, after = text[: formula.start], text[formula.end :]

if formula.environment:
text = f"{text[: formula.start]}$$\n{formula.source}\n$$\n{text[formula.end :]}"
text = f"{before}$$\n{formula.source}\n$$\n{after}"
elif formula.bracket:
dollars = "$$" if formula.display else "$"
text = f"{before}{dollars}{formula.source}{dollars}{after}"

return text

Expand Down Expand Up @@ -471,10 +495,11 @@ def _closing(text: str, start: int, end: int, delimiter: str) -> int | None:
index = start

while index < end:
if text[index] == "\\":
index += 2
elif text.startswith(delimiter, index):
# The delimiter first: `\)` and `\]` start with the escape character.
if text.startswith(delimiter, index):
return index
elif text[index] == "\\":
index += 2
elif BLANK_LINE.match(text, index):
return None
else:
Expand Down
20 changes: 11 additions & 9 deletions src/mogs/scaffold.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ def instructor_guide():
1. The question text, as Markdown.
2. The function students write. Put your solution between `# BEGIN SOLUTION` and
`# END SOLUTION`, or by putting an inline comment `# SOLUTION`.
3. Public tests: functions named `test_q1_<anything>`.
4. Hidden tests, optional: the same, with `# HIDDEN` as the first line.
3. Public tests: a cell of functions named `test_q1_<anything>`.
4. Hidden tests, optional: another such cell, with `# HIDDEN` as its first line.
5. `mogs.grade("q1", points=4)`

**Written question `q2`:**
Expand Down Expand Up @@ -72,15 +72,17 @@ def mean(xs):
# END SOLUTION


@app.function
def test_q1_basic():
assert mean([1, 2, 3]) == 2
@app.cell
def _():
def test_q1_basic():
assert mean([1, 2, 3]) == 2


@app.function
# HIDDEN
def test_q1_single():
assert mean([7]) == 7
@app.cell
def _():
# HIDDEN
def test_q1_single():
assert mean([7]) == 7


@app.cell
Expand Down
37 changes: 37 additions & 0 deletions tests/test_pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,23 @@ def test_find_formulas_ignores_an_unclosed_dollar():
assert spans("Unbalanced: $\\frac{1}{2 end.\n\nNext paragraph $x$.") == ["$x$"]


def test_find_formulas_backslash_brackets():
text = "a \\(x^2\\) b \\[\\int f\\] c\n\n\\[\ny\n\\]"

assert spans(text) == ["\\(x^2\\)", "\\[\\int f\\]", "\\[\ny\n\\]"]
assert [formula.display for formula in find_formulas(text)] == [False, True, True]
assert find_formulas("a \\(x^2\\)")[0] == Formula(
start=2, end=9, source="x^2", display=False, bracket=True
)


@pytest.mark.parametrize(
"text", ["`\\(x\\)` in code", "\\(x unclosed", "\\(x\n\ny\\)", "```\n\\[x\\]\n```"]
)
def test_find_formulas_skips_backslash_brackets_that_are_not_math(text):
assert spans(text) == []


ALIGN = "\\begin{align}\na &= b \\\\\nc &= d\n\\end{align}"


Expand Down Expand Up @@ -285,6 +302,26 @@ def test_display_environments_render(tmp_path, env, dollars):
assert "could not be rendered" not in text


def test_backslash_bracket_math_renders(tmp_path):
answer = "Inline \\(a = b\\) here.\n\n\\[\nc = d\n\\]\n\nAfter."

text = text_of(render(tmp_path, {"q1": answer}))

assert "Inline 𝑎 = 𝑏 here." in text, text
assert "𝑐 = 𝑑" in text, text
assert "\\(" not in text and "\\[" not in text
assert "could not be rendered" not in text


def test_failing_backslash_bracket_formula_is_shown_as_its_source(tmp_path):
formula = "\\iftypst \\begin{gather*} a \\end{gather*}"

text = text_of(render(tmp_path, {"q1": f"Code: \\({formula}\\) and \\(x = 1\\)."}))

assert formula in text, text
assert "𝑥 = 1" in text, text


def test_gather_star_in_formula_text_keeps_its_star(tmp_path):
text = text_of(render(tmp_path, {"q1": "Name: $\\text{gather*}$."}))

Expand Down
14 changes: 10 additions & 4 deletions tests/test_scaffold.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,21 +59,27 @@ def test_init_notebook_names_only_the_guide(tmp_path):
cells = read_assignment(tmp_path / "A12").nb.cells
named = [cell.name for cell in cells if cell.name not in ("_", "setup")]

assert named == ["instructor_guide", "mean", "test_q1_basic", "test_q1_single"]
assert named == ["instructor_guide", "mean"]


def test_init_notebook_tests_are_functions(tmp_path):
def test_init_notebook_tests_are_cells_as_in_the_docs(tmp_path):
init(tmp_path / "A12")

cells = read_assignment(tmp_path / "A12").nb.cells
tests = [(cell.kind, cell.tests, cell.hidden) for cell in cells if cell.tests]

assert tests == [
(CellKind.FUNCTION, ("test_q1_basic",), False),
(CellKind.FUNCTION, ("test_q1_single",), True),
(CellKind.CELL, ("test_q1_basic",), False),
(CellKind.CELL, ("test_q1_single",), True),
]


def test_init_notebook_hidden_marker_opens_its_cell(tmp_path):
text = init(tmp_path / "A12").read_text(encoding="utf-8")

assert "@app.cell\ndef _():\n # HIDDEN\n def test_q1_single():\n" in text


def test_init_notebook_names_the_installed_marimo(tmp_path):
text = init(tmp_path / "A12").read_text(encoding="utf-8")

Expand Down
Loading