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5f1fdca
 
 
 
 
 
 
 
 
 
7850d17
 
5f1fdca
 
 
7850d17
 
 
 
 
 
5f1fdca
 
7850d17
 
 
5f1fdca
 
 
 
 
 
 
 
 
 
 
 
 
 
7850d17
 
 
 
 
 
 
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
import marimo

__generated_with = "0.14.16"
app = marimo.App(
    width="medium",
    app_title="Open Syndrome Definition - Data Browser",
)


@app.cell
def _():
    import marimo as mo
    import json
    from pathlib import Path

    import polars as pl
    import plotly.graph_objects as go

    import yaml
    from opensyndrome.filter import OSDEngine, load_profile
    from opensyndrome.artifacts import get_definition_dir

    return (
        OSDEngine,
        Path,
        get_definition_dir,
        go,
        json,
        load_profile,
        mo,
        pl,
        yaml,
    )


@app.cell
def _(go, pl):
    def plot_cases(
        _df_filtered, definitions, date_column="date", date_format="%Y-%m-%d %H:%M:%S"
    ):
        _definitions_columns_sum = [
            pl.col(definition).sum().alias(definition) for definition in definitions
        ]
        _agg_df = (
            _df_filtered.with_columns(
                pl.col(date_column)
                .str.to_datetime(format=date_format, strict=False)
                .cast(pl.Date)
                .dt.truncate("1mo")
                .alias("_month")
            )
            .group_by("_month")
            .agg(_definitions_columns_sum)
            .sort("_month")
        )
        _fig = go.Figure()
        for definition in definitions:
            _fig.add_trace(
                go.Scatter(
                    x=_agg_df["_month"],
                    y=_agg_df[definition],
                    mode="lines+markers",
                    name=definition,
                )
            )
        _fig.update_layout(yaxis=dict(tickformat="d", rangemode="tozero"))
        return _fig

    return (plot_cases,)


@app.cell
def _(go, pl):
    def groupped_bar(_df_filtered, definitions, group_by_column="code", top_n=10):
        _agg_df = (
            _df_filtered.group_by(group_by_column)
            .agg([pl.col(definition).sum() for definition in definitions])
            .sort(group_by_column)
        )

        _agg_df = _agg_df.with_columns(
            (sum([pl.col(definition) for definition in definitions])).alias("total")
        )
        _agg_df = _agg_df.sort("total", descending=True).head(
            top_n
        )  # .sort(group_by_column)
        _fig = go.Figure(
            data=[
                go.Bar(
                    name=definition, x=_agg_df[group_by_column], y=_agg_df[definition]
                )
                for definition in definitions
            ]
        )
        _fig.update_layout(barmode="group")
        return _fig

    return (groupped_bar,)


@app.cell
def _(mo):
    mo.md(r"""# Open Syndrome Definition πŸ‘©πŸ½β€πŸ”¬""")
    return


@app.cell
def _(mo):
    mo.callout(
        mo.md(
            "This is a prototype of how to filter your data using definitions from the Open Syndrome Initiative.\n\n"
            "We do not store any data."
        ),
        kind="neutral",
    )
    return


@app.cell
def _(Path):
    EXAMPLE_DATASETS = {
        "Toy dataset": {
            "csv": Path("toy_dataset.csv"),
            "mapping": Path("mapping.yaml"),
            "date_column": "recording_ts",
        },
    }
    return (EXAMPLE_DATASETS,)


@app.cell
def _(EXAMPLE_DATASETS, mo):
    data_source = mo.ui.radio(
        options=["Load example", "Upload your own"],
        value="Load example",
    )
    example_picker = mo.ui.dropdown(
        options=list(EXAMPLE_DATASETS.keys()),
        label="Example dataset",
    )
    sample_file = mo.ui.file(kind="area", filetypes=[".csv"])

    return data_source, example_picker, sample_file


@app.cell
def _(data_source, example_picker, mo, sample_file):
    mo.vstack(
        [
            mo.md("## Load your data"),
            data_source,
            example_picker if data_source.value == "Load example" else sample_file,
        ]
    )
    return


@app.cell
def _(EXAMPLE_DATASETS, data_source, example_picker, pl, sample_file):
    if data_source.value == "Load example":
        df_selected = (
            pl.read_csv(EXAMPLE_DATASETS[example_picker.value]["csv"])
            if example_picker.value
            else None
        )
    else:
        df_selected = pl.read_csv(sample_file.contents()) if sample_file.value else None
    return (df_selected,)


@app.cell
def _(EXAMPLE_DATASETS, data_source, example_picker):
    _default_yaml = """\
    profiles:
    - name: my_dataset
      # value_encodings:  # optional β€” map OSD canonical values to dataset-specific ones
      #   sex:
      #     male: "M"
      #     female: "F"
      columns:
    # Rename the keys below to match your dataset column names.
    # Available concepts: diagnosis, demographic_criteria, symptom,
    #                     diagnostic_test, epidemiological_history
    my_diagnosis_column:
      concept: diagnosis
      dtype: string
    # my_age_column:
    #   concept: demographic_criteria
    #   attribute: age
    #   dtype: integer
    """
    if data_source.value == "Load example" and example_picker.value:
        _example = EXAMPLE_DATASETS[example_picker.value]
        initial_yaml = _example["mapping"].read_text()
        initial_date_column = _example["date_column"]
    else:
        initial_yaml = _default_yaml
        initial_date_column = None
    return initial_date_column, initial_yaml


@app.cell
def _(df_selected, initial_date_column, initial_yaml, mo):
    mo.stop(df_selected is None)

    yaml_editor = mo.ui.code_editor(
        value=initial_yaml,
        language="yaml",
    ).form(label="Data to OSD mapping", show_clear_button=True, bordered=True)

    date_column_picker = mo.ui.dropdown(
        options=df_selected.columns,
        label="Date column",
        value=initial_date_column,
    )

    date_format_input = mo.ui.text(
        value="%Y-%m-%d %H:%M:%S",
        label="Date format",
    )

    _cols_hint = "`, `".join(df_selected.columns)

    mo.vstack(
        [
            mo.md("### Mapping your data to the format"),
            mo.md(
                "Edit the YAML below to map your dataset columns to OSD concepts, "
                "then click **Submit**. "
                "Select the date column separately for the time-series view.\n\n"
                f"Your dataset columns: `{_cols_hint}`"
            ),
            mo.hstack(
                [yaml_editor, mo.vstack([date_column_picker, date_format_input])],
                widths=[3, 1],
                align="start",
            ),
        ]
    )
    return date_column_picker, date_format_input, yaml_editor


@app.cell
def _(df_selected, load_profile, mo, yaml, yaml_editor):
    mo.stop(yaml_editor.value is None)

    try:
        _parsed = yaml.safe_load(yaml_editor.value)
    except yaml.YAMLError as _e:
        mo.stop(True, mo.callout(mo.md(f"**Invalid YAML:** {_e}"), kind="danger"))

    if not _parsed["profiles"][0]["columns"]:
        mo.stop(
            True,
            mo.callout(mo.md("You need to map **at least one column**"), kind="danger"),
        )

    not_found = []
    for declared_column in _parsed["profiles"][0]["columns"]:
        if declared_column not in df_selected.columns:
            not_found.append(declared_column)

    if not_found:
        mo.stop(
            True,
            mo.callout(
                mo.md(f"**Columns not found:** {', '.join(not_found)}"), kind="danger"
            ),
        )

    try:
        _profile_name = _parsed["profiles"][0]["name"]
        profile = load_profile(_parsed, _profile_name)
    except (KeyError, IndexError, ValueError) as _e:
        mo.stop(True, mo.callout(mo.md(f"**Profile error:** {_e}"), kind="danger"))
    return (profile,)


@app.cell
def _(date_column_picker, mo, profile):
    mo.stop(date_column_picker.value is None)
    date_column = date_column_picker.value
    _diagnosis_cols = [c.col_name for c in profile.columns if c.concept == "diagnosis"]
    code_column = _diagnosis_cols[0] if _diagnosis_cols else None
    return code_column, date_column


@app.cell
def _(get_definition_dir):
    definition_options = {
        filepath.name.replace(".json", ""): filepath
        for filepath in get_definition_dir().glob("**/*.json")
    }
    return (definition_options,)


@app.cell
def _(definition_options, mo):
    definitions_dropdown = mo.ui.multiselect(
        label="Select Syndromic Indicators", options=sorted(definition_options.keys())
    )
    return (definitions_dropdown,)


@app.cell
def _(mo):
    mo.md(r"""### Data sample""")
    return


@app.cell
def _(df_selected):
    df_selected.sample(10)
    return


@app.cell
def _(mo):
    mo.md(r"""---""")
    return


@app.cell
def _(mo):
    mo.md(r"""## Data & Definitions""")
    return


@app.cell
def _(definitions_dropdown, mo):
    mo.hstack([mo.md("**::lucide:filter:: Filters:**"), definitions_dropdown])
    return


@app.cell
def _(
    OSDEngine,
    definition_options,
    definitions_dropdown,
    df_selected,
    json,
    mo,
    profile,
):
    mo.stop(
        df_selected is None or df_selected.is_empty() or not definitions_dropdown.value
    )

    definitions = definitions_dropdown.value

    # skip criteria that can't be evaluated (e.g. professional_judgment)
    engine = OSDEngine(profile, skip_unresolvable=True)

    defs_dict = {
        name: json.loads(definition_options[name].read_text()) for name in definitions
    }
    df_filtered = engine.label(df_selected, defs_dict)
    return definitions, df_filtered


@app.cell
def _(definitions, df_filtered, df_selected, mo):
    mo.stop(definitions is None or df_filtered is None)

    _cards = [
        mo.stat(
            label="Syndromic Indicators",
            value=len(definitions),
            caption=", ".join([definition for definition in definitions]),
            bordered=True,
        ),
        mo.stat(
            label="Rows",
            value=df_selected.shape[0],
        ),
        mo.stat(
            label="Columns",
            value=df_selected.shape[1],
        ),
    ]

    mo.hstack(_cards, widths="equal", align="center")
    return


@app.cell
def _(definition_options, json):
    def load_definition(name: str) -> dict:
        return json.loads(definition_options[name].read_text())

    return (load_definition,)


@app.cell
def _(mo):
    top_n = mo.ui.number(start=1, stop=10, label="Number of top codes", value=3, step=1)
    return (top_n,)


@app.cell
def _(
    code_column,
    date_column,
    date_format_input,
    definitions,
    df_filtered,
    df_selected,
    groupped_bar,
    mo,
    plot_cases,
    top_n,
):
    mo.stop(definitions is None or df_selected is None)

    if code_column:
        diagnosis_chart = [
            mo.md("### Codes comparison per syndromic indicator"),
            top_n.left(),
            groupped_bar(
                df_filtered,
                definitions,
                top_n=top_n.value or 3,
                group_by_column=code_column,
            ),
        ]
    else:
        diagnosis_chart = []

    timeseries = [
        mo.md("### Time series"),
        plot_cases(
            df_filtered,
            definitions,
            date_column=date_column,
            date_format=date_format_input.value,
        ),
    ]

    mo.vstack(
        [
            mo.md("## Findings from the data πŸ“Š"),
            *timeseries,
            *diagnosis_chart,
        ]
    )
    return


@app.cell
def _(definitions, load_definition, mo):
    mo.stop(definitions is None)

    mo.vstack(
        [
            mo.md("### Definitions details"),
            mo.md(
                "Here the definitions used to filter the data. See here what criteria were applied. πŸ”Ž"
            ),
            mo.accordion(
                {
                    "JSONs": mo.accordion(
                        {
                            definition: mo.json(load_definition(definition))
                            for definition in definitions
                        }
                    ),
                },
            ),
        ]
    )
    return


if __name__ == "__main__":
    app.run()