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
def get_consultation_dates_structured(
    note: DataFrame,
    vo: Optional[DataFrame] = None,
    kept_note_class_source_value: Optional[Union[str, List[str]]] = "CR-CONS",
    kept_visit_source_value: Optional[Union[str, List[str]]] = "consultation externe",
) -> DataFrame:
    """
    Uses `note_datetime` value to infer *true* consultation dates

    Parameters
    ----------
    note : DataFrame
        A `note` DataFrame with at least the following columns:

        - `note_id`
        - `note_datetime`
        - `note_source_value` **if** `kept_note_class_source_value is not None`
        - `visit_occurrence_id` **if** `kept_visit_source_value is not None`
    vo : Optional[DataFrame]
        A visit_occurrence DataFrame to provide **if** `kept_visit_source_value is not None`,
        with at least the following columns:

        - `visit_occurrence_id`
        - `visit_source_value` **if** `kept_visit_source_value is not None`
    kept_note_class_source_value : Optional[Union[str, List[str]]]
        Value(s) allowed for the `note_class_source_value` column.
    kept_visit_source_value : Optional[Union[str, List[str]]], optional
        Value(s) allowed for the `visit_source_value` column.

    Returns
    -------
    Dataframe
        With 2 added columns corresponding to the following concept:

        - `CONSULTATION_DATE`, containing the date
        - `CONSULTATION_DATE_EXTRACTION`, containing `"STRUCTURED"`
    """

    kept_note = note

    if kept_note_class_source_value is not None:
        if type(kept_note_class_source_value) == str:
            kept_note_class_source_value = [kept_note_class_source_value]
        kept_note = note[
            note.note_class_source_value.isin(set(kept_note_class_source_value))
        ]

    if kept_visit_source_value is not None:
        if type(kept_visit_source_value) == str:
            kept_visit_source_value = [kept_visit_source_value]
        kept_note = kept_note.merge(
            vo[
                [
                    "visit_occurrence_id",
                    "visit_source_value",
                ]
            ][vo.visit_source_value.isin(set(kept_visit_source_value))],
            on="visit_occurrence_id",
        )

    dates_per_note = kept_note[["note_datetime", "note_id"]].rename(
        columns={
            "note_datetime": "CONSULTATION_DATE",
        }
    )

    dates_per_note["CONSULTATION_DATE_EXTRACTION"] = "STRUCTURED"

    return dates_per_note.set_index("note_id")