File size: 14,754 Bytes
7b0de7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
"""slides/slide_v2_mine.pdf: the filtered deck. Only what the user has approved goes in here; add a slide only when asked.
Times New Roman, pure black text. usage: python slides/make_slide_v2.py"""
import os
import matplotlib; matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.lines import Line2D
import make_slides as ms                                   # reuses the diagram code, so the diagrams stay identical to the main deck

OUT = "slides/slide_v2_mine.pdf"
plt.rcParams.update(ms.FONT_RC)

def title_slide(pdf, title):
    fig = plt.figure(figsize=(16, 9))
    fig.text(0.5, 0.5, title, ha="center", va="center", fontsize=44, weight="bold", color="#000000")
    pdf.savefig(fig); plt.close(fig)

BLACK, RED, GREEN, LEFT, RIGHT = "#000000", "#c62828", "#1b7f37", 0.02, 0.98

def heading(fig, title):
    """Left-aligned title with a thin black line under it."""
    fig.text(LEFT, 0.935, title, ha="left", va="center", fontsize=26, weight="bold", color=BLACK)
    fig.add_artist(Line2D([LEFT, RIGHT], [0.89, 0.89], color=BLACK, lw=0.8))

def gap_cell(value, paper):
    """Gap to the paper, with its sign: red below the paper, green above it."""
    gap = round(value, 2) - paper
    return (f"{gap:+.2f}".replace("-", "−"), RED if gap < 0 else GREEN if gap > 0 else BLACK)

def black_table(fig, top, header, rows, col_x, aligns, row_h=0.05, fontsize=15):
    """Plain table: pure black text and thin black rules. A cell may be (text, colour)."""
    for x, v, al in zip(col_x, header, aligns): fig.text(x, top, v, ha=al, va="center", fontsize=fontsize, weight="bold", color=BLACK)
    fig.add_artist(Line2D([LEFT, RIGHT], [top - row_h / 2] * 2, color=BLACK, lw=0.8))
    y = top
    for row in rows:
        y -= row_h
        for x, v, al in zip(col_x, row, aligns):
            text, colour = v if isinstance(v, tuple) else (v, BLACK)
            fig.text(x, y, text, ha=al, va="center", fontsize=fontsize, color=colour)
    fig.add_artist(Line2D([LEFT, RIGHT], [y - row_h / 2] * 2, color=BLACK, lw=0.8))

REGION, PAPER_AVG = "Chesapeake Bay", ms.PAPER[0][1][6]

def model_table(fig, row, extra=()):
    """The comparison table under a diagram: the paper's row, then one model's row (plus any extra rows)."""
    black_table(fig, 0.29, ["Model", "Train", "Test", "Built-up", "Tree", "Low veg.", "Water", "Test avg", "Gap"],
                [[ms.PAPER[0][0], REGION, REGION, "", "", "", "", f"{PAPER_AVG:.2f}", ""], row, *extra],
                col_x=[LEFT, 0.20, 0.32, 0.50, 0.57, 0.66, 0.74, 0.85, RIGHT], aligns=["left"] * 3 + ["right"] * 6)

def base_diagram_slide(pdf):
    """Base: heading, the block diagram of slide 47 of the main deck, and the Base and paper rows of the all-models table."""
    fig = plt.figure(figsize=(16, 9))
    heading(fig, "Base: the baseline Paraformer (ImageNet ViT-B/16)")
    ms._serial_diagram(fig, *ms.BASE_DIAGRAM, dy=0.035)
    _, _, t, _ = ms._best_scores("paraformer_adamw_lr1e-4_w128_bs8"); t = ms._row_dict(t)
    model_table(fig, ["Paraformer reproduce", REGION, REGION] + [f"{t[c]:.1f}" for c in ms.CLASS_COLS] + [f"{t['avg']:.2f}", gap_cell(t["avg"], PAPER_AVG)])
    pdf.savefig(fig); plt.close(fig)

RGB_NOAUG_RUN = "paraformer_rgb_noaug_adamw_lr1e-4_w128_bs16_50ep"
RGB_EXT_RUN, RGB_EXT_EPOCH = "paraformer_rgb_noaug_adamw_lr1e-4_w128_bs16_ep50to99", 90   # epochs 50-99 continued from epoch 49

def rgb_scores():
    """The six score cells of the Paraformer RGB row: '--' until all checkpoints are scored, then the val-chosen one."""
    if not os.path.exists(os.path.join(ms.RUNS_DIR, RGB_NOAUG_RUN, "eval", "history_test.csv")): return ["--"] * 6
    _, _, t, scored = ms._best_scores(RGB_NOAUG_RUN)
    if 49 not in scored: return ["--"] * 6
    t = ms._row_dict(t)
    ext = os.path.join(ms.RUNS_DIR, RGB_EXT_RUN, "eval", "history_test.csv")   # user's choice (4 Nov): show epoch 90 of the continued run
    if os.path.exists(ext): t = ms._hist_row(ext, RGB_EXT_EPOCH)
    return [f"{t[c]:.1f}" for c in ms.CLASS_COLS] + [f"{t['avg']:.2f}", gap_cell(t["avg"], PAPER_AVG)]

POLAND_RGB = "Paraformer_hr_landcover/runs/poland_rgb_e90/summary.csv"   # epoch 90 of the continued RGB run (was poland_rgb = epoch 49)

def poland_raw_row():
    """Paraformer RGB (epoch 90, see POLAND_RGB) zero-shot on Poland, raw colour, 1 m: pooled class IoU, mean over the 14 provinces. No gap (paper avg is Chesapeake)."""
    if not os.path.exists(POLAND_RGB): return []
    import pandas as pd
    s = pd.read_csv(POLAND_RGB); s = s[(s.scale == "1m") & (s.colour == "raw")].iloc[0]
    cls = ["IoU_built-up", "IoU_tree canopy", "IoU_low vegetation", "IoU_water"]
    paper_pl = [ms.PAPER[0][0], "Poland", "Poland", "", "", "", "", "49.39", ""]   # paper Table 2, trained on Poland with GLC FCS30 (30 m)
    return [paper_pl, ["Paraformer RGB", REGION, "Poland"] + [f"{s[c]:.1f}" for c in cls] + [f"{s['mean_over_provinces_mIoU']:.2f}", gap_cell(s["mean_over_provinces_mIoU"], 49.39)]]

def rgb_diagram_slide(pdf):
    """Base-RGB without augmentation: same diagram with three input bands; the row stays '--' until the run has been scored."""
    fig = plt.figure(figsize=(16, 9))
    heading(fig, "Base-RGB: the baseline Paraformer on RGB only (no augmentation)")
    ms._serial_diagram(fig, *ms.BASE_DIAGRAM, dy=0.035, bands="R, G, B", cnn_reads="reads 3 bands")
    model_table(fig, ["Paraformer RGB", REGION, REGION] + rgb_scores(), extra=poland_raw_row())
    pdf.savefig(fig); plt.close(fig)

def model3_rgb_slide(pdf):
    """Model 3-RGB: Base-RGB + SAM 3 masks, trained late fusion, with the same 224 x 224 chip going into both models
    (SAM 3's processor resizes it to 1008). Grey fill = data, solid border = frozen model, dashed border = trained part. Diagram only."""
    from matplotlib.patches import FancyArrowPatch
    fig = plt.figure(figsize=(16, 9)); LIGHT = "#ececec"
    heading(fig, "Model 3-RGB: Base-RGB + SAM 3 masks, trained late fusion")
    S = dict(tfs=17, bfs=14, lw=1.8)
    box = lambda *a, **k: ms._bw_box(fig, *a, **{**S, **k})
    line = lambda xs, ys: fig.add_artist(Line2D(xs, ys, transform=fig.transFigure, color=BLACK, lw=1.8, solid_capstyle="butt"))
    arrow = lambda p, q, **k: fig.patches.append(FancyArrowPatch(p, q, transform=fig.transFigure, arrowstyle="-|>", mutation_scale=18,
                                                                 color=BLACK, lw=1.8, shrinkA=0, shrinkB=1, **k))
    note = lambda x, y, s, ha="left": fig.text(x, y, s, ha=ha, va="center", fontsize=13, color=BLACK, style="italic")
    CY = 0.60                                                                     # centre line of the main flow
    # data and models
    box(0.02, CY - 0.11, 0.135, 0.22, "Input", "NAIP chip\n224 × 224 px, 1 m\nR, G, B", fill=LIGHT)
    box(0.205, 0.63, 0.23, 0.22, "Base-RGB Paraformer (frozen)", "input 224 × 224, epoch 49\ntrained on NLCD only\nout: 17 NLCD probabilities")
    box(0.205, 0.35, 0.23, 0.22, "SAM 3 (frozen)", "resizes 224 → 1008 (4.5× zoom)\n6 text prompts: building, road,\nparking lot, runway, water, river\nmasks resized back to 224")
    box(0.53, CY - 0.08, 0.10, 0.16, "concat", "23 × 224 × 224", fill=LIGHT)
    box(0.655, CY - 0.13, 0.165, 0.26, "Fusion head (trained)", "1 × 1 conv, 23 → 17\n408 weights\nstarts as Paraformer\n(SAM 3 weights = 0)", dashed=True, lw=2.4)
    box(0.85, CY - 0.08, 0.13, 0.16, "Output", "17 NLCD classes\n224 × 224", fill=LIGHT)
    # training
    box(0.205, 0.095, 0.23, 0.12, "NLCD label", "30 m", fill=LIGHT)
    box(0.655, 0.06, 0.325, 0.19, "Training (L1)", "per-pixel cross entropy\nAdamW, 5 epochs, all 582 training tiles\nno selection on CCLC")
    # the same chip goes into both frozen models
    line([0.155, 0.18], [CY, CY]); line([0.18, 0.18], [0.46, 0.74])
    arrow((0.18, 0.74), (0.205, 0.74)); arrow((0.18, 0.46), (0.205, 0.46))
    # the two outputs merge into concat
    line([0.435, 0.46], [0.74, 0.74]); line([0.46, 0.46], [0.74, CY + 0.025]); arrow((0.46, CY + 0.025), (0.53, CY + 0.025))
    line([0.435, 0.46], [0.46, 0.46]); line([0.46, 0.46], [0.46, CY - 0.025]); arrow((0.46, CY - 0.025), (0.53, CY - 0.025))
    note(0.467, 0.705, "17 × 224 × 224"); note(0.467, 0.495, "6 × 224 × 224")
    arrow((0.63, CY), (0.655, CY)); arrow((0.82, CY), (0.85, CY))
    # loss: output and NLCD in, gradient back to the head only
    arrow((0.915, CY - 0.08), (0.915, 0.25)); arrow((0.435, 0.155), (0.655, 0.155))
    fig.patches.append(FancyArrowPatch((0.7375, 0.25), (0.7375, CY - 0.13), transform=fig.transFigure, arrowstyle="-|>", mutation_scale=18,
                                       color=BLACK, lw=1.8, ls=(0, (5, 3)), shrinkA=0, shrinkB=1))
    note(0.745, 0.36, "updates the head only")
    pdf.savefig(fig); plt.close(fig)

def model2_rgb_slide(pdf):
    """Model 2 (slide 4): the earlier setup, SAM 3 masks from its own 1008-px windows. Model 3 of slide 53 of the main deck, RGB only: the RGB Base (no augmentation, epoch 49) + SAM 3 masks, trained late fusion.
    Black and white. Grey fill = data, solid border = frozen model, dashed border = trained part. Diagram only, no scores."""
    from matplotlib.patches import FancyArrowPatch
    fig = plt.figure(figsize=(16, 9)); LIGHT = "#ececec"
    heading(fig, "Model 2: Base-RGB + SAM 3 masks, trained late fusion")
    S = dict(tfs=17, bfs=14, lw=1.8)
    box = lambda *a, **k: ms._bw_box(fig, *a, **{**S, **k})
    line = lambda xs, ys: fig.add_artist(Line2D(xs, ys, transform=fig.transFigure, color=BLACK, lw=1.8, solid_capstyle="butt"))
    arrow = lambda p, q, **k: fig.patches.append(FancyArrowPatch(p, q, transform=fig.transFigure, arrowstyle="-|>", mutation_scale=18,
                                                                 color=BLACK, lw=1.8, shrinkA=0, shrinkB=1, **k))
    note = lambda x, y, s, ha="left": fig.text(x, y, s, ha=ha, va="center", fontsize=13, color=BLACK, style="italic")
    CY = 0.60                                                                     # centre line of the main flow
    # data and models
    box(0.025, CY - 0.11, 0.11, 0.22, "Input", "NAIP tile\n1 m\nR, G, B", fill=LIGHT)
    box(0.185, 0.64, 0.25, 0.20, "Base-RGB Paraformer (frozen)", "input 224 × 224\nepoch 49, trained on NLCD only\nout: 17 NLCD probabilities per pixel")
    box(0.185, 0.35, 0.25, 0.22, "SAM 3 (frozen)", "1008 × 1008 windows\n6 text prompts: building, road,\nparking lot, runway, water, river\nout: 6 mask scores per pixel (0 to 1)")
    box(0.495, CY - 0.08, 0.085, 0.16, "concat", "23 channels\nper pixel", fill=LIGHT)
    box(0.615, CY - 0.13, 0.175, 0.26, "Fusion head (trained)", "1 × 1 conv, 23 → 17\n408 weights\nstarts as Paraformer\n(SAM 3 weights = 0)", dashed=True, lw=2.4)
    box(0.825, CY - 0.08, 0.15, 0.16, "Output", "17 NLCD classes\nper pixel", fill=LIGHT)
    # training
    box(0.185, 0.095, 0.25, 0.12, "NLCD label", "30 m", fill=LIGHT)
    box(0.615, 0.06, 0.36, 0.19, "Training (L1)", "per-pixel cross entropy\nAdamW, 5 epochs, all 582 training tiles\nno selection on CCLC")
    # input splits to the two frozen models
    line([0.135, 0.16], [CY, CY]); line([0.16, 0.16], [0.46, 0.74])
    arrow((0.16, 0.74), (0.185, 0.74)); arrow((0.16, 0.46), (0.185, 0.46))
    # the two outputs merge into concat
    line([0.435, 0.47], [0.74, 0.74]); line([0.47, 0.47], [0.74, CY + 0.025]); arrow((0.47, CY + 0.025), (0.495, CY + 0.025))
    line([0.435, 0.47], [0.46, 0.46]); line([0.47, 0.47], [0.46, CY - 0.025]); arrow((0.47, CY - 0.025), (0.495, CY - 0.025))
    note(0.477, 0.705, "17 ch."); note(0.477, 0.495, "6 ch.")
    arrow((0.58, CY), (0.615, CY)); arrow((0.79, CY), (0.825, CY))
    # loss: output and NLCD in, gradient back to the head only
    arrow((0.90, CY - 0.08), (0.90, 0.25)); arrow((0.435, 0.155), (0.615, 0.155))
    fig.patches.append(FancyArrowPatch((0.70, 0.25), (0.70, CY - 0.13), transform=fig.transFigure, arrowstyle="-|>", mutation_scale=18,
                                       color=BLACK, lw=1.8, ls=(0, (5, 3)), shrinkA=0, shrinkB=1))
    note(0.708, 0.36, "updates the head only")
    pdf.savefig(fig); plt.close(fig)

MODEL2_TEST = "Paraformer_hr_landcover/runs/model2_rgb/M2_L1_ext/eval/history_test.csv"     # 15-epoch head (epochs 0-14), last epoch
MODEL2_POLAND = "Paraformer_hr_landcover/runs/poland_model2_e90/summary.csv"   # 5 Nov: head retrained on the epoch-90 RGB Base (was poland_model2_15ep, epoch-49 Base)

def model2_results_slide(pdf):
    """Model 2 performance: the paper rows and Model 2 (15-epoch head) on Chesapeake test and zero-shot on Poland (raw colour).
    Class columns are pooled IoU, Test avg is the mean over states / provinces, as on slides 2 and 3."""
    import pandas as pd
    fig = plt.figure(figsize=(16, 9))
    heading(fig, "Model 2: performance")
    rows = [[ms.PAPER[0][0], REGION, REGION, "", "", "", "", f"{PAPER_AVG:.2f}", ""]]
    rows.append(["Paraformer RGB", REGION, REGION] + rgb_scores())      # the epoch-49 RGB Paraformer under Model 2 (as on slide 3)
    if os.path.exists(MODEL2_TEST):
        t = ms._hist_row(MODEL2_TEST, 14)
        rows.append(["Model 2", REGION, REGION] + [f"{t[c]:.1f}" for c in ms.CLASS_COLS] + [f"{t['avg']:.2f}", gap_cell(t["avg"], PAPER_AVG)])
    rows.append([ms.PAPER[0][0], "Poland", "Poland", "", "", "", "", "49.39", ""])
    if os.path.exists(MODEL2_POLAND):
        S = pd.read_csv(MODEL2_POLAND); cls = ["IoU_built-up", "IoU_tree canopy", "IoU_low vegetation", "IoU_water"]
        rows += poland_raw_row()[1:]                    # Paraformer RGB epoch 90, raw colour, same row as slide 3
        s = S[S.model == "Model 2"].iloc[0]
        rows.append(["Model 2", REGION, "Poland"] + [f"{s[c]:.1f}" for c in cls] + [f"{s['mean_over_provinces_mIoU']:.2f}", gap_cell(s["mean_over_provinces_mIoU"], 49.39)])
    black_table(fig, 0.70, ["Model", "Train", "Test", "Built-up", "Tree", "Low veg.", "Water", "Test avg", "Gap"], rows,
                col_x=[LEFT, 0.20, 0.32, 0.50, 0.57, 0.66, 0.74, 0.85, RIGHT], aligns=["left"] * 3 + ["right"] * 6)
    pdf.savefig(fig); plt.close(fig)

class NumberedPdf:
    """PdfPages that writes the slide number in the bottom-right corner of every slide (black, Times New Roman)."""
    def __init__(self, pdf): self.pdf, self.n = pdf, 0
    def savefig(self, fig):
        self.n += 1; fig.text(0.985, 0.02, str(self.n), ha="right", va="bottom", fontsize=14, color=BLACK); self.pdf.savefig(fig)

if __name__ == "__main__":
    with PdfPages(OUT) as raw:
        pdf = NumberedPdf(raw)
        title_slide(pdf, "Project Map")
        base_diagram_slide(pdf)
        rgb_diagram_slide(pdf)
        model2_rgb_slide(pdf)
        model2_results_slide(pdf)
        model3_rgb_slide(pdf)
    print("wrote", OUT)