forked from data-to-insight/SEND-tool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
1520 lines (1274 loc) · 50.8 KB
/
main.js
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function run_analysis () {
const files = csvFile.files;
const csv_array = []
Object.keys(files).forEach(i => {
const file = files[i];
const reader = new FileReader();
reader.onload = (e) => {
const text = e.target.result
csv_array.push(text)
};
reader.readAsText(file);
window.files = csv_array
window.excel_file = csvFile.files
})
run_python();
}
async function run_python() {
let pyodide = await loadPyodide();
await pyodide.loadPackage(["pandas", "micropip"]);
// load initial python packages
await pyodide.runPythonAsync(`
import micropip
await micropip.install('plotly==5.0.0')
await micropip.install('openpyxl')
import openpyxl
import xml.etree.ElementTree as ET
import pandas as pd
import js
import pyodide_js
import json
import io
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
import openpyxl
import warnings
from pandas.core.common import SettingWithCopyWarning
warnings.simplefilter(action="ignore", category=SettingWithCopyWarning)
input_type = None
try:
from js import files, refDateVal
except:
js.alert("Did you upload the correct files, more info in the instructions.")
dfs = {}
#if len(files) != 5:
# js.alert("Wrong number of files uploaded, expected 5. See the 'About' page for more info.")
if len(files) > 1:
for i, v in enumerate(files):
dfs[i] = pd.read_csv(io.StringIO(files[i]))
js.console.log("csvs sucessfully read")
input_type = 'csv'
js.console.log('input type csv')
elif len(files) == 1:
dta = files[0]
# js.console.log(dta)
try:
root = ET.fromstring(dta)
input_type = 'xml'
js.window.input_type = input_type
js.console.log('input type xml')
except:
js.alert("Did you upload the correct files, more info in the instructions.")
else:
js.alert("Did you upload the correct files, more info in the instructions.")
`)
// run main Python script
await pyodide.runPythonAsync(`
"""
Plots to do:
Normalised ethnicity breakdown vs national results
Plot national age/gender breakdown on age plot
"""
import pandas as pd
import js
# from js import files, postcode_data
import pyodide_js
import json
import io
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
import openpyxl
import warnings
from pandas.core.common import SettingWithCopyWarning
warnings.simplefilter(action="ignore", category=SettingWithCopyWarning)
# Initial variables
try:
ref_date = pd.to_datetime(refDateVal, format="%Y-%m-%d")
days_to_ref_date = pd.to_datetime("today") - ref_date
days_to_ref_date = int(days_to_ref_date / pd.Timedelta(1, "d"))
timeframe = 365 + days_to_ref_date
except:
js.alert("Did you enter a date value? Refresh and try again.")
module_columns = {
"m1": [
"Person ID",
"Surname",
"Forename",
"Dob (ccyy-mm-dd)",
"Gender",
"Ethnicity",
"Postcode",
"UPN - Unique Pupil Number",
"ULN - Young Persons Unique Learner Number",
"UPN and ULN unavailable reason",
],
"m2": [
"Person ID",
"Requests Record ID",
"Date Request Was Received",
"Initial Request Whilst In RYA",
"Request Outcome Date",
"Request Outcome",
"Request Mediation",
"Request Tribunal",
"Exported - Child Or Young Person Moves Out Of LA Before Assessment Is Completed",
"New start date",
],
"m3": [
"Person ID",
"Requests Record ID",
"Assessment Outcome To Issue EHCP",
"Assessment Outcome Date",
"Assessment Mediation",
"Assessment Tribunal",
"Other Mediation",
"Other Tribunal",
"Twenty Weeks Time Limit Exceptions Apply",
],
"m4": [
"Person ID",
"Request Records ID",
"EHC Plan Start Date",
"Residential Settings",
"Worked based learning activity",
"Personal budget taken up",
"Personal budget - organised arrangements",
"Personal budget - direct payments",
"Date EHC Plan Ceased",
"Reason EHC Plan Ceased",
],
"m5": [
"Person ID",
"Request Records ID",
"EHC Plan (Transfer)",
"Residential Settings",
"Worked based learning activity",
"EHCP review decisions date",
],
}
# Utilities
def age_buckets(age):
if age < 1:
return "Under 1"
elif age <= 4:
return "1-4 years"
elif age <= 9:
return "5-9 years"
elif age <= 15:
return "10-15 years"
else:
return "16 & over"
def timeliness_buckets(time_delta):
if time_delta <= pd.Timedelta(45, "d"):
return "45 days or less"
elif time_delta <= pd.Timedelta(90, "d"):
return "46-90 days"
elif time_delta <= pd.Timedelta(150, "d"):
return "91-150 days"
elif time_delta <= pd.Timedelta(365, "d"):
return "151-365 days"
elif time_delta <= pd.Timedelta(720, "d"):
return "1-2 years"
elif time_delta <= pd.Timedelta(1085, "d"):
return "2-3 years"
elif time_delta <= pd.Timedelta(1450, "d"):
return "3-4 years"
else:
return "over 4 years"
def add_identifiers(identifiers, m2, m3, m4, m5):
identifiers["Gender"] = identifiers["Gender"].map(
{1: "Male",
2: "Female",
0: "Not Stated",
9: "Neither",
'M':'Male',
'F':'Female'}
)
identifiers["Age"] = pd.to_datetime("today") - pd.to_datetime(
identifiers["Dob (ccyy-mm-dd)"], format="%Y-%m-%d", errors="coerce"
)
identifiers["Age"] = round((identifiers["Age"] / np.timedelta64(1, "Y")))
identifiers["Age Group"] = identifiers["Age"].apply(age_buckets)
m2 = pd.merge(m2, identifiers, on="Person ID", how="left")
m3 = pd.merge(m3, identifiers, on="Person ID", how="left")
m4 = pd.merge(m4, identifiers, on="Person ID", how="left")
m5 = pd.merge(m5, identifiers, on="Person ID", how="left")
return m2, m3, m4, m5
def html_plot(plot, width, tall=False):
# Used to centralise arguments for making html plots
if tall == True:
plot = plot.to_html(
include_plotlyjs=False,
full_html=False,
default_height="600px",
default_width="1295px",
)
elif width == "n":
plot = plot.to_html(
include_plotlyjs=False,
full_html=False,
default_height="400px",
default_width="640px",
)
elif width == "w":
plot = plot.to_html(
include_plotlyjs=False,
full_html=False,
default_height="400px",
default_width="1295px",
)
return plot
# Plotting functions
def hist_for_categories(df):
hist_gender = px.histogram(df, x="Gender").update_layout(
title_x=0.5, yaxis_title="Number of children"
)
hist_ethnicity = px.histogram(df, x="Ethnicity").update_layout(
title_x=0.5, yaxis_title="Number of children"
)
hist_age = px.histogram(df, x="Age Group", color="Gender").update_layout(
title_x=0.5, yaxis_title="Number of children"
)
return hist_gender, hist_ethnicity, hist_age
def box_for_categories(df, y):
box_gender = px.box(df, x="Gender", y=y).update_layout(title_x=0.5)
box_ethnicity = px.box(df, x="Ethnicity", y=y).update_layout(title_x=0.5)
box_age = px.box(df, x="Age Group", y=y, color="Gender").update_layout(title_x=0.5)
return box_gender, box_ethnicity, box_age
# Calculation functions
def entire_cohort(df):
gender, ethnicity, age = hist_for_categories(df)
js.console.log('got here')
gender.update_layout(title="Entire cohort by gender")
ethnicity.update_layout(title="Entire cohort ethnicity")
age.update_layout(title="Entire cohort age and gender")
count = len(df["Person ID"].unique())
fig_count = go.Figure(go.Indicator(value=count))
fig_count.update_layout(
title={
"text": "Total children in SEN2 data",
"y": 0.6,
"x": 0.5,
"xanchor": "center",
"yanchor": "top",
}
)
gender = html_plot(gender, "n")
ethnicity = html_plot(ethnicity, "w")
age = html_plot(age, "n")
fig_count = html_plot(fig_count, "n")
return gender, ethnicity, age, fig_count
def ehc_ceased_year(df):
"""
df = module 4
"""
df = df[df["Date EHC Plan Ceased"].notna()]
df["Date EHC Plan Ceased"] = pd.to_datetime(
df["Date EHC Plan Ceased"], dayfirst=True
) # format="%d/%m/%Y", errors="corece")
df["Time Since EHC Ceased"] = np.datetime64("today") - df["Date EHC Plan Ceased"]
ehc_ceased_in_year = df[df["Time Since EHC Ceased"] <= pd.Timedelta(timeframe, "d")]
count_ehc_ceased = len(ehc_ceased_in_year)
reason_ech_ceased = (
ehc_ceased_in_year.groupby("Reason EHC Plan Ceased")["Reason EHC Plan Ceased"]
.count()
.reset_index(name="count")
)
fig_count_ceased = go.Figure(go.Indicator(value=count_ehc_ceased))
fig_count_ceased.update_layout(
title={
"text": "EHC ceased in the last year",
"y": 0.6,
"x": 0.5,
"xanchor": "center",
"yanchor": "top",
}
)
gender_hist, ethnicity_hist, age_hist = hist_for_categories(ehc_ceased_in_year)
gender_hist.update_layout(title="EHC ceased this year by gender")
ethnicity_hist.update_layout(title="EHC ceased this year by ethnicity")
age_hist.update_layout(title="EHC ceased this year by age and gender")
reason_ceased_pie = px.pie(
reason_ech_ceased,
values="count",
names="Reason EHC Plan Ceased",
title="Reason EHC ceased",
).update_layout(title_x=0.5)
fig_count_ceased = html_plot(fig_count_ceased, "n")
gender_hist = html_plot(gender_hist, "n")
ethnicity_hist = html_plot(ethnicity_hist, "w")
age_hist = html_plot(age_hist, "n")
reason_ceased_pie = html_plot(reason_ceased_pie, "n")
return fig_count_ceased, gender_hist, ethnicity_hist, age_hist, reason_ceased_pie
def ehc_starting_year(df):
"""
df = module 4
"""
df = df[df["EHC Plan Start Date"].notna()]
df["EHC Plan Start Date"] = pd.to_datetime(
df["EHC Plan Start Date"], format="%Y-%m-%d", errors="coerce"
)
df["Time since EHC Started"] = np.datetime64("today") - df["EHC Plan Start Date"]
ehc_started_in_year = df[
df["Time since EHC Started"] <= pd.Timedelta(timeframe, "d")
]
count_ehc_started = len(ehc_started_in_year)
fig_count_started = go.Figure(go.Indicator(value=count_ehc_started))
fig_count_started.update_layout(
title={
"text": "EHC started in the last year",
"y": 0.6,
"x": 0.5,
"xanchor": "center",
"yanchor": "top",
}
)
gender_hist, ethnicity_hist, age_hist = hist_for_categories(ehc_started_in_year)
gender_hist.update_layout(title="EHC started this year by gender")
ethnicity_hist.update_layout(title="EHC started this year by ethnicity")
age_hist.update_layout(title="EHC started this year by age and gender")
fig_count_started = html_plot(fig_count_started, "n")
gender_hist = html_plot(gender_hist, "n")
ethnicity_hist = html_plot(ethnicity_hist, "w")
age_hist = html_plot(age_hist, "n")
return fig_count_started, gender_hist, ethnicity_hist, age_hist
def ass_completed_year(df):
"""
df = module 3
"""
df_completed = df[df["Assessment Outcome Date"].notna()]
df_completed["Time Since Ass Completion"] = np.datetime64("today") - pd.to_datetime(
df_completed["Assessment Outcome Date"], format="%Y-%m-%d", errors="coerce"
)
ass_this_year = df_completed[
df_completed["Time Since Ass Completion"] <= pd.Timedelta(timeframe, "d")
]
ass_year_outcomes = (
ass_this_year.groupby("Assessment Outcome To Issue EHCP")[
"Assessment Outcome To Issue EHCP"
]
.count()
.reset_index(name="count")
)
ass_outcomes_pie = px.pie(
ass_year_outcomes,
values="count",
names="Assessment Outcome To Issue EHCP",
title="Outcomes of assessments closed this year",
).update_layout(title_x=0.5)
assessments_completed_this_year = len(ass_this_year)
fig_count_completed = go.Figure(go.Indicator(value=assessments_completed_this_year))
fig_count_completed.update_layout(
title={
"text": "Assessments completed in the last year",
"y": 0.6,
"x": 0.5,
"xanchor": "center",
"yanchor": "top",
}
)
gender_hist, ethnicity_hist, age_hist = hist_for_categories(ass_this_year)
gender_hist.update_layout(title="Assessments completed this year by gender")
ethnicity_hist.update_layout(title="Assessments completed this year by ethnicity")
age_hist.update_layout(title="Assessments completed this year by age and gender")
fig_count_completed = html_plot(fig_count_completed, "n")
gender_hist = html_plot(gender_hist, "n")
ethnicity_hist = html_plot(ethnicity_hist, "w")
age_hist = html_plot(age_hist, "n")
ass_outcomes_pie = html_plot(ass_outcomes_pie, "n")
return fig_count_completed, gender_hist, ethnicity_hist, age_hist, ass_outcomes_pie
def closed_ass_timeframes(df1, df2):
"""
Time between request being recieved in module 2, and now, (filtering closed assessments from module 3).
df1 = module 2
df2 = module 3
"""
df = pd.merge(
df1,
df2,
on=[
"Person ID",
"Requests Record ID",
"Gender",
"Ethnicity",
"Age",
"Age Group",
],
how="inner",
)
df["Date Request Was Received"] = pd.to_datetime(
df["Date Request Was Received"], format="%Y-%m-%d", errors="coerce"
)
df["Assessment Outcome Date"] = pd.to_datetime(
df["Assessment Outcome Date"], format="%Y-%m-%d", errors="coerce"
)
df = df[
(df["Assessment Outcome Date"].notna())
& (
(pd.to_datetime("today") - df["Assessment Outcome Date"])
<= pd.Timedelta(timeframe, "d")
)
]
df["closed_ass_timeliness"] = (
df["Assessment Outcome Date"] - df["Date Request Was Received"]
) / pd.Timedelta(1, "day")
df["closed_ass_timeliness"] = df["closed_ass_timeliness"].round()
gender_box, ethnicity_box, age_box = box_for_categories(df, "closed_ass_timeliness")
gender_box.update_layout(
title="Closed assessment timeliness distribution by gender",
yaxis_title="Timeliness (days)",
)
ethnicity_box.update_layout(
title="Closed assessment timeliness distribution by ethnicity",
yaxis_title="Timeliness (days)",
)
age_box.update_layout(
title="Closed assessment timeliness distribution by age",
yaxis_title="Timeliness (days)",
)
gender_box = html_plot(gender_box, "n")
ethnicity_box = html_plot(ethnicity_box, "w")
age_box = html_plot(age_box, "n")
return gender_box, ethnicity_box, age_box
def open_ass_timeframes(df1, df2):
"""
Time between request being recieved in module 2, and now, (filtering closed assessments from module 3).
df1 = module 2
df2 = module 3
"""
df = pd.merge(
df1,
df2,
on=[
"Person ID",
"Requests Record ID",
"Gender",
"Ethnicity",
"Age",
"Age Group",
],
how="inner",
)
df = df[df["Date Request Was Received"].notna()]
uncompleted_assessment_requests = len(df[df["Assessment Outcome Date"].isna()])
uncompleted_requests = go.Figure(
go.Indicator(value=uncompleted_assessment_requests)
)
uncompleted_requests.update_layout(
title={
"text": "Uncompleted assessment requests",
"y": 0.6,
"x": 0.5,
"xanchor": "center",
"yanchor": "top",
}
)
df = df[df["Assessment Outcome Date"].isna()]
df["Date Request Was Received"] = pd.to_datetime(
df["Date Request Was Received"], format="%Y-%m-%d", errors="coerce"
)
df["open_ass_timeliness"] = (
np.datetime64("today") - df["Date Request Was Received"]
) / pd.Timedelta(1, "day")
df["open_ass_timeliness"] = df["open_ass_timeliness"].round()
gender_box, ethnicity_box, age_box = box_for_categories(df, "open_ass_timeliness")
gender_box.update_layout(
title="Open assessment timeliness distribution by gender",
yaxis_title="Timeliness (days)",
)
ethnicity_box.update_layout(
title="Open assessment timeliness distribution by ethnicity",
yaxis_title="Timeliness (days)",
)
age_box.update_layout(
title="Open assessment timeliness distribution by age",
yaxis_title="Timeliness (days)",
)
uncompleted_requests = html_plot(uncompleted_requests, "n")
gender_box = html_plot(gender_box, "n")
ethnicity_box = html_plot(ethnicity_box, "w")
age_box = html_plot(age_box, "n")
return uncompleted_requests, gender_box, ethnicity_box, age_box
def requests_fn(df):
df = df[df["Date Request Was Received"].notna()]
df["Date Request Was Received"] = pd.to_datetime(
df["Date Request Was Received"], format="%Y-%m-%d", errors="coerce"
)
df["Request Outcome Date"] = pd.to_datetime(
df["Request Outcome Date"], format="%Y-%m-%d", errors="coerce"
)
req_timeliness_df = df[df["Request Outcome Date"].notna()]
req_timeliness_df["Request Delta"] = (
req_timeliness_df["Request Outcome Date"]
- req_timeliness_df["Date Request Was Received"]
) / pd.Timedelta(1, "days")
req_timeliness_df["Request Delta"] = req_timeliness_df["Request Delta"].round()
df["Request Timeframe"] = np.datetime64("today") - df["Date Request Was Received"]
requests_this_year = df[df["Request Timeframe"] <= pd.Timedelta(timeframe, "d")]
count_requests_this_year = len(requests_this_year)
fig_count_req = go.Figure(go.Indicator(value=count_requests_this_year))
fig_count_req.update_layout(
title={
"text": "Requests this year",
"y": 0.6,
"x": 0.5,
"xanchor": "center",
"yanchor": "top",
}
)
request_outcomes = (
df.groupby("Request Outcome")["Request Outcome"]
.count()
.reset_index(name="count")
)
requests_pie = px.pie(
request_outcomes, values="count", names="Request Outcome"
).update_layout(title_x=0.5)
gender_hist, ethnicity_hist, age_hist = hist_for_categories(df)
gender_hist.update_layout(
title="Distribution of gender for requests this year",
yaxis_title="Timeliness (days)",
)
ethnicity_hist.update_layout(
title="Distribution of ethnicity for requests this year",
yaxis_title="Timeliness (days)",
)
age_hist.update_layout(
title="Distribution of age for requests this year",
yaxis_title="Timeliness (days)",
)
fig_count_req = html_plot(fig_count_req, "n")
gender_hist = html_plot(gender_hist, "n")
ethnicity_hist = html_plot(ethnicity_hist, "w")
age_hist = html_plot(age_hist, "n")
requests_pie = html_plot(requests_pie, "n")
return fig_count_req, gender_hist, ethnicity_hist, age_hist, requests_pie
def multiple_appearances(m2, m3):
m2 = m2.groupby("Person ID")["Person ID"].count().reset_index(name="count")
m2 = m2[m2["count"] > 1]
multiple_m2 = go.Figure(go.Indicator(value=len(m2)))
multiple_m2.update_layout(
title={
"text": "Children appearing in the requests list multiple times",
"y": 0.6,
"x": 0.5,
"xanchor": "center",
"yanchor": "top",
}
)
m3 = m3.groupby("Person ID")["Person ID"].count().reset_index(name="count")
m3 = m3[m3["count"] > 1]
multiple_m3 = go.Figure(go.Indicator(value=len(m2)))
multiple_m3.update_layout(
title={
"text": "Children appearing in the assessments list multiple times",
"y": 0.6,
"x": 0.5,
"xanchor": "center",
"yanchor": "top",
}
)
multiple_m2 = html_plot(multiple_m2, "n")
multiple_m3 = html_plot(multiple_m3, "n")
return multiple_m2, multiple_m3
def journeys(m2, m3):
m2 = m2[m2["Date Request Was Received"].notna()]
m2["Request"] = "Request Made"
m3["Assessment Complete"] = m3["Assessment Outcome Date"].apply(
lambda x: (
"Assessment Completed" if pd.notna(x) else "Assessment not yet completed"
)
)
df = pd.merge(
m2,
m3[
[
"Requests Record ID",
"Person ID",
"Assessment Outcome To Issue EHCP",
"Assessment Complete",
]
],
on=["Person ID", "Requests Record ID"],
how="left",
)
df["Assessment Complete"] = df["Assessment Complete"].fillna(
"Assessment uncompleted"
)
df["Assessment Outcome To Issue EHCP"] = df[
"Assessment Outcome To Issue EHCP"
].fillna("No assessment outcome")
fig = px.parallel_categories(
df,
dimensions=[
"Request",
"Request Outcome",
"Assessment Complete",
"Assessment Outcome To Issue EHCP",
],
)
fig.update_layout(margin=dict(l=50, r=50, t=50, b=50))
fig = html_plot(fig, "w")
return fig
def plan_length_plots(m4):
m4["EHC Plan Start Date"] = pd.to_datetime(
m4["EHC Plan Start Date"], format="%Y-%m-%d"
)
m4["Date EHC Plan Ceased"] = pd.to_datetime(
m4["Date EHC Plan Ceased"], format="%Y-%m-%d"
)
df_open = m4[m4["Date EHC Plan Ceased"].isna() & m4["EHC Plan Start Date"].notna()]
df_open["Plan length"] = pd.to_datetime("today") - df_open["EHC Plan Start Date"]
df_open["Plan length"] = df_open["Plan length"].apply(timeliness_buckets)
open_gender_hist = px.histogram(
df_open,
x="Plan length",
color="Gender",
title="Currently open plan lengths by gender",
category_orders={
"Plan length": [
"45 days or less",
"46-90 days",
"91-150 days",
"151-365 days",
"1-2 years",
"2-3 years",
"3-4 years",
"over 4 years",
]
},
)
open_ethnicity_hist = px.histogram(
df_open,
x="Plan length",
color="Ethnicity",
title="Currently open plan lengths by ethnicity",
category_orders={
"Plan length": [
"45 days or less",
"46-90 days",
"91-150 days",
"151-365 days",
"1-2 years",
"2-3 years",
"3-4 years",
"over 4 years",
]
},
)
open_age_hist = px.histogram(
df_open,
x="Plan length",
color="Age Group",
title="Currently open plan lengths by age",
category_orders={
"Plan length": [
"45 days or less",
"46-90 days",
"91-150 days",
"151-365 days",
"1-2 years",
"2-3 years",
"3-4 years",
"over 4 years",
]
},
)
df_closed = m4[
m4["Date EHC Plan Ceased"].notna() & m4["EHC Plan Start Date"].notna()
]
df_closed["Plan length"] = (
df_closed["Date EHC Plan Ceased"] - df_closed["EHC Plan Start Date"]
)
df_closed["Plan length"] = df_closed["Plan length"].apply(timeliness_buckets)
closed_gender_hist = px.histogram(
df_closed,
x="Plan length",
color="Gender",
title="Closed plan lengths by gender",
category_orders={
"Plan length": [
"45 days or less",
"46-90 days",
"91-150 days",
"151-365 days",
"1-2 years",
"2-3 years",
"3-4 years",
"over 4 years",
]
},
)
closed_ethnicity_hist = px.histogram(
df_closed,
x="Plan length",
color="Ethnicity",
title="Closed plan lengths by ethnicity",
category_orders={
"Plan length": [
"45 days or less",
"46-90 days",
"91-150 days",
"151-365 days",
"1-2 years",
"2-3 years",
"3-4 years",
"over 4 years",
]
},
)
closed_age_hist = px.histogram(
df_closed,
x="Plan length",
color="Age Group",
title="Closed plan lengths by age",
category_orders={
"Plan length": [
"45 days or less",
"46-90 days",
"91-150 days",
"151-365 days",
"1-2 years",
"2-3 years",
"3-4 years",
"over 4 years",
]
},
)
open_gender_hist = html_plot(open_gender_hist, "n")
open_ethnicity_hist = html_plot(open_ethnicity_hist, "w", tall=True)
open_age_hist = html_plot(open_age_hist, "n")
closed_gender_hist = html_plot(closed_gender_hist, "n")
closed_ethnicity_hist = html_plot(closed_ethnicity_hist, "w", tall=True)
closed_age_hist = html_plot(closed_age_hist, "n")
return (
open_gender_hist,
open_ethnicity_hist,
open_age_hist,
closed_gender_hist,
closed_ethnicity_hist,
closed_age_hist,
)
####################################
# XML INGRESS
####################################
def get_values(xml_elements, table_dict: dict, xml_block):
# st.write(table_dict)
# st.write(xml_block)
for element in xml_elements:
try:
table_dict[element] = xml_block.find(element).text
except:
table_dict[element] = pd.NA
return table_dict
class XMLtoCSV:
header = pd.DataFrame(columns=["Collection", "Year", "Reference Date"])
persons = pd.DataFrame(
columns=[
"Surname",
"Forename",
"PersonBirthDate",
"Sex",
"Ethnicity",
"PostCode",
"UPN",
"UniqueLearnerNumber",
"UPNunknown",
]
)
requests = pd.DataFrame(
columns=[
"ReceivedDate",
"RYA",
"RequestOutcomeDate",
"RequestOutcome",
"RequestMediation",
"RequestTribunal",
"Exported",
]
)
assessments = pd.DataFrame(
columns=[
"AssessmentOutcome",
"AssessmentOutcomeDate",
"AssessmentMediation",
"AssessmentTribunal",
"OtherMediation",
"OtherTribunal",
"Week20",
]
)
named_plan = pd.DataFrame(
columns=[
"StartDate",
"URN",
"UKPRN",
"SENSetting",
"PlacementRank",
"SENunitIndicator",
"ResourcedProvisionIndicator",
"PlanRes",
"PlanWPB",
"PB",
"OA",
"DP",
"CeaseDate",
"CeaseReason",
]
)
active_plans = pd.DataFrame(
columns=[
"TransferLA",
"URN",
"UKPRN",
"SENSetting",
"SENSettingOther",
"PlacementRank",
"EntryDate",
"LeavingDate",
"SENunitIndicator",
"ResourcedProvisionIndicator",
"RES",
"WPB",
"SENtype",
"SENtypeRank",
"ReviewMeeting",
"ReviewOutcome",
"LastReview",
]
)
def __init__(self, root):
self.child_id = 0
header = root.find("Header")
self.Header = self.create_header(header)
self.name = None
children = root.find("Persons")
for child in children.findall("Person"):
self.create_child(child)
self.named_plan = self.named_plan[self.named_plan["StartDate"].notna()].copy()
def create_header(self, header):
header_dict = {}
collection_details = header.find("CollectionDetails")
collection_elements = ["Collection", "Year", "ReferenceDate"]
header_dict = get_values(collection_elements, header_dict, collection_details)
source = header.find("Source")
source_elements = [
"SourceLevel",
"LEA",
"SoftwareCode",
"Release",
"SerialNo",
"DateTime",
]
header_dict = get_values(source_elements, header_dict, source)
header_df = pd.DataFrame.from_dict([header_dict])
return header_df
def create_child(self, person):
self.create_person(person)
self.create_requests(person)