-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp_22_new_dev.py
2285 lines (2023 loc) · 101 KB
/
app_22_new_dev.py
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
from requests.sessions import DEFAULT_REDIRECT_LIMIT
import streamlit as st
from pathlib import Path
import requests
import pandas as pd
import numpy as np
import altair as alt
from pandas.io.json import json_normalize
import base64
import SessionState
from streamlit import caching
# git+https://github.com/HCDigitalScholarship/intervals.git@main
# sets up function to call Markdown File for "about"
def read_markdown_file(markdown_file):
return Path(markdown_file).read_text()
def download_link(object_to_download, download_filename, download_link_text):
"""
Generates a link to download the given object_to_download.
object_to_download (str, pd.DataFrame): The object to be downloaded.
download_filename (str): filename and extension of file. e.g. mydata.csv, some_txt_output.txt
download_link_text (str): Text to display for download link.
Examples:
download_link(YOUR_DF, 'YOUR_DF.csv', 'Click here to download data!')
download_link(YOUR_STRING, 'YOUR_STRING.txt', 'Click here to download your text!')
"""
if isinstance(object_to_download,pd.DataFrame):
object_to_download = object_to_download.to_csv(index=False)
# some strings <-> bytes conversions necessary here
b64 = base64.b64encode(object_to_download.encode()).decode()
return f'<a href="data:file/txt;base64,{b64}" download="{download_filename}">{download_link_text}</a>'
def download_csv(origdf, filename):
tmp_download_link = download_link(origdf, filename, 'Click here to download your data!')
st.markdown(tmp_download_link, unsafe_allow_html=True)
def filter_by(filterer, select_data, full_data, key):
options = select_data[filterer].unique().tolist()
selected_options = st.sidebar.multiselect('', options, key = key)
list_of_selected = list(selected_options)
if list_of_selected:
chosen_columns = select_data[filterer].isin(selected_options)
subframe = select_data[chosen_columns]
fullframe = full_data[chosen_columns]
else:
subframe = select_data
fullframe = full_data
return [fullframe, subframe]
def draw_chart(col_name, count_name, origdf):
chart_data = origdf.copy()
chart_data[count_name] = chart_data.groupby(by=col_name)[col_name].transform('count')
# st.write(chart_data)
#TODO: Format chart for easier view
chart = alt.Chart(chart_data).mark_bar().encode(
x = count_name,
y = col_name,
)
text = chart.mark_text(
align='left',
baseline='middle',
dx=3
).encode(
text = count_name
)
st.write(chart+text)
def draw_mt_chart(origdf):
cf_count = df['musical_type'].str.match('cantus firmus').values.sum()
sog_count = df['musical_type'].str.match('soggetto').values.sum()
csog_count = df['musical_type'].str.match('counter soggetto').values.sum()
cd_count = df['musical_type'].str.match('contrapuntal duo').values.sum()
fg_count = df['musical_type'].str.match('fuga').values.sum()
id_count = df['musical_type'].str.match('imitative duo').values.sum()
nid_count = df['musical_type'].str.match('non-imitative duo').values.sum()
pe_count = df['musical_type'].str.match('periodic entry').values.sum()
cad_count = df['musical_type'].str.match('cadence').values.sum()
hr_count = df['musical_type'].str.match('homorhythm').values.sum()
mt_dict = {'types':['Cantus firmus', 'Soggetto', 'Counter-soggetto', 'Contrapuntal duo', 'Fuga', 'Imitative Duo', 'Non-imitative duo', 'Periodc entries', 'Cadence', 'Homorhythm'],
'count': [cf_count, sog_count, csog_count, cd_count, fg_count, id_count, nid_count, pe_count, cad_count, hr_count ]}
df_mt = pd.DataFrame(data=mt_dict)
chart_mt = alt.Chart(df_mt).mark_bar().encode(
x = 'count',
y = 'types',
)
text_mt = chart_mt.mark_text(
align='left',
baseline='middle',
dx=3
).encode(
text = 'count'
)
st.write(chart_mt+text_mt)
def draw_rt_chart(origdf):
qt_count = df_r['relationship_type'].str.match('quotation').values.sum()
tm_count = df_r['relationship_type'].str.match('mechanical transformation').values.sum()
tnm_count = df_r['relationship_type'].str.match('non-mechanical transformation').values.sum()
om_count = df_r['relationship_type'].str.match('omission').values.sum()
nm_count = df_r['relationship_type'].str.match('new material').values.sum()
rt_dict = {'types':['Quotation', 'Mechanical transformation', 'Non-mechanical transformation', 'Omission', 'New Materia'],
'count': [qt_count, tm_count, tnm_count, om_count, nm_count]}
df_rt = pd.DataFrame(data=rt_dict)
chart_rt = alt.Chart(df_rt).mark_bar().encode(
x = 'count',
y = 'types',
)
text_rt = chart_rt.mark_text(
align='left',
baseline='middle',
dx=3
).encode(
text = 'count'
)
st.write(chart_rt+text_rt)
# no longer needed
def get_subtype_count(origdf, mt, stname):
mt_selected = ""
subtype = mt_selected
subtype_count = origdf[subtype].shape[0]
return int(subtype_count)
# no longer needed
def get_cdtype_count(origdf, stname):
subtype = (origdf['mt_cad_type'].isin(stname))
subtype_count = origdf[subtype].shape[0]
return int(subtype_count)
# no longer needed
def get_mt_count(origdf, mtname):
musicaltype = (origdf[mtname] == 1)
musicaltype_count = origdf[musicaltype].shape[0]
return int(musicaltype_count)
def get_subtype_charts(selected_type, origdf):
if selected_type.lower() == "cadence":
mt_selected = 'cadence'
cd_chosen = df['musical_type'].str.match('cadence')
cd_full = origdf[cd_chosen]
#separate cd type chart (3 types and counts of each)
authentic = df['musical_type'].str.match('cadence') & df['type'].str.match('authentic')
phrygian = df['musical_type'].str.match('cadence') & df['type'].str.match('phrygian')
plagal = df['musical_type'].str.match('cadence') & df['type'].str.match('plagal')
irregular = df['musical_type'].str.match('cadence') & df['firreg_cadence']
cd_dict = {'Cadence Type':['authentic','phrygian','plagal'],
'countcdtypes': [
authentic.sum(),
phrygian.sum(),
plagal.sum(),
irregular.sum(),
]}
df_cd = pd.DataFrame(data=cd_dict)
chart_cd = alt.Chart(df_cd).mark_bar().encode(
x = 'countcdtypes',
y = 'Cadence Type',
)
text_cd = chart_cd.mark_text(
align='left',
baseline='middle',
dx=3
).encode(
text = 'countcdtypes'
)
st.write(chart_cd+text_cd)
if selected_type.lower() == "cadence":
mt_selected = 'cadence'
cd_chosen = df['musical_type'].str.match('cadence')
cd_full = origdf[cd_chosen]
#separate cd tone chart (many tone and counts of each)
C = df['musical_type'].str.match('cadence') & df['cadence_tone'].str.match('C')
D = df['musical_type'].str.match('cadence') & df['cadence_tone'].str.match('D')
E_flat = df['musical_type'].str.match('cadence') & df['cadence_tone'].str.match('E-flat')
E = df['musical_type'].str.match('cadence') & df['cadence_tone'].str.match('E')
F = df['musical_type'].str.match('cadence') & df['cadence_tone'].str.match('F')
G = df['musical_type'].str.match('cadence') & df['cadence_tone'].str.match('G')
A = df['musical_type'].str.match('cadence') & df['cadence_tone'].str.match('A')
B_flat = df['musical_type'].str.match('cadence') & df['cadence_tone'].str.match('B-flat')
B = df['musical_type'].str.match('cadence') & df['cadence_tone'].str.match('B')
ct_dict = {'Cadence Tone':['C','D','E-flat', 'E', 'F', 'G', 'A', 'B-flat', 'B'],
'countcdtones': [
C.sum(),
D.sum(),
E_flat.sum(),
E.sum(),
F.sum(),
G.sum(),
A.sum(),
B.sum(),
B_flat.sum(),
]}
df_cd = pd.DataFrame(data=ct_dict)
chart_ct = alt.Chart(df_cd).mark_bar().encode(
x = 'countcdtones',
y = 'Cadence Tone',
)
text_ct = chart_ct.mark_text(
align='left',
baseline='middle',
dx=3
).encode(
text = 'countcdtones'
)
st.write(chart_ct+text_ct)
if selected_type.lower() == "fuga":
mt_selected = 'fuga'
fg_chosen = df['musical_type'].str.match('fuga')
fg_full = origdf[fg_chosen]
fg_dict = {'Subtypes':['periodic', 'sequential', 'inverted', 'retrograde'],
'count': [
df['periodic'].sum(),
df['sequential'].sum(),
df['inverted'].sum(),
df['retrograde'].sum(),
]}
df_fg = pd.DataFrame(data=fg_dict)
chart_fg = alt.Chart(df_fg).mark_bar().encode(
x = 'count',
y = 'Subtypes',
)
text_fg = chart_fg.mark_text(
align='left',
baseline='middle',
dx=3
).encode(
text = 'count'
)
st.write(chart_fg+text_fg)
if selected_type.lower() == "periodic entry":
mt_selected = 'periodic entry'
pe_chosen = df['musical_type'].str.match('periodic entry')
pe_full = origdf[pe_chosen]
pe_dict = {'Subtypes':['sequential', 'invertible counterpoint', 'added entries'],
'count': [
df['sequential'].sum(),
df['invertible_counterpoint'].sum(),
df['added_entries'].sum(),
]}
df_pe = pd.DataFrame(data=pe_dict)
chart_pe = alt.Chart(df_pe).mark_bar().encode(
x = 'count',
y = 'Subtypes',
)
text_pe = chart_pe.mark_text(
align='left',
baseline='middle',
dx=3
).encode(
text = 'count'
)
st.write(chart_pe+text_pe)
if selected_type.lower() == "imitative duo":
mt_selected = 'imitative duo'
id_chosen = df['musical_type'].str.match('imitative duo')
id_full = origdf[id_chosen]
id_dict = {'Subtypes':['invertible counterpoint', 'added entries'],
'count': [
df['invertible_counterpoint'].sum(),
df['details.added_entries'].sum(),
]}
df_id = pd.DataFrame(data=id_dict)
chart_id = alt.Chart(df_id).mark_bar().encode(
x = 'count',
y = 'Subtypes',
)
text_id = chart_id.mark_text(
align='left',
baseline='middle',
dx=3
).encode(
text = 'count'
)
st.write(chart_id+text_id)
if selected_type.lower() == "non-imitative duo":
mt_selected = 'non-imitative duo'
nid_chosen = df['musical_type'].str.match('non-imitative duo')
nid_full = origdf[nid_chosen]
nid_dict = {'Subtypes':['sequential', 'invertible counterpoint', 'added entries'],
'count': [
df['fields.details.sequential'].sum(),
df['fields.details.invertible counterpoint'].sum(),
df['fields.details.added entries'].sum(),
]}
df_nid = pd.DataFrame(data=nid_dict)
chart_nid = alt.Chart(df_nid).mark_bar().encode(
x = 'count',
y = 'Subtypes',
)
text_nid = chart_nid.mark_text(
align='left',
baseline='middle',
dx=3
).encode(
text = 'count'
)
st.write(chart_nid+text_nid)
if selected_type.lower() == "homorhythm":
mt_selected = 'homorhythm'
hr_chosen = df['musical_type'].str.match('homorhythm')
hr_full = origdf[hr_chosen]
simple = df['musical_type'].str.match('homorhythm') & df['type'].str.match('simple')
staggered = df['musical_type'].str.match('homorhythm') & df['type'].str.match('staggered')
sequential = df['musical_type'].str.match('homorhythm') & df['type'].str.match('sequential')
fauxbourdon = df['musical_type'].str.match('homorhythm') & df['type'].str.match('fauxbourdon')
hr_dict = {'Subtypes':['simple', 'staggered', 'sequential', 'fauxbourdon'],
'count': [
simple.sum(),
staggered.sum(),
sequential.sum(),
fauxbourdon.sum(),
]}
df_hr = pd.DataFrame(data=hr_dict)
chart_hr = alt.Chart(df_hr).mark_bar().encode(
x = 'count',
y = 'Subtypes',
)
text_hr = chart_hr.mark_text(
align='left',
baseline='middle',
dx=3
).encode(
text = 'count'
)
st.write(chart_hr+text_hr)
def create_bar_chart(variable, count, color, data, condition, *selectors):
# if type(data.iloc[0, :][variable]) != str:
# raise Exception("Label difficult to see!")
observer_chart = alt.Chart(data).mark_bar().encode(
y=variable,
x=count,
color=color,
opacity=alt.condition(condition, alt.value(1), alt.value(0.2))
).add_selection(
*selectors
)
return observer_chart
def create_heatmap(x, x2, y, color, data, heat_map_width, heat_map_height, selector_condition, *selectors, tooltip):
# if type(data.iloc[0, :][y]) != str:
# raise Exception("Label difficult to see!")
heatmap = alt.Chart(data).mark_bar().encode(
x=x,
x2=x2,
y=y,
color=color,
opacity=alt.condition(selector_condition, alt.value(1), alt.value(0.2)),
tooltip=tooltip
).properties(
width=heat_map_width,
height=heat_map_height
).add_selection(
*selectors
)
return heatmap
def _process_ngrams_df_helper(ngrams_df, main_col):
"""
The output from the getNgram is usually a table with
four voices and ngram of notes properties (duration or
pitch). This method stack this property onto one column
and mark which voices they are from.
:param ngrams_df: direct output from getNgram with 1 columns
for each voices and ngrams of notes' properties.
:param main_col: the name of the property
:return: a dataframe with ['start', main_col, 'voice'] as columns
"""
# copy to avoid changing original ngrams df
ngrams_df = ngrams_df.copy()
# add a start column containing offsets
ngrams_df.index.name = "start"
ngrams_df = ngrams_df.reset_index().melt(id_vars=["start"], value_name=main_col, var_name="voice")
ngrams_df["start"] = ngrams_df["start"].astype(float)
return ngrams_df
def process_ngrams_df(ngrams_df, ngrams_duration=None, selected_pattern=None, voices=None):
"""
This method combines ngrams from all voices in different columns
into one column and calculates the starts and end points of the
patterns. It could also filter out specific voices or patterns
for the users to analyze.
:param ngrams_df: dataframe we got from getNgram in crim-interval
:param ngrams_duration: if not None, simply output the offsets of the
ngrams. If we have durations, calculate the end by adding the offsets and
the durations.
:param selected_pattern: list of specific patterns the users want (optional)
:param voices: list of specific voices the users want (optional)
:return a new, processed dataframe with only desired patterns from desired voices
combined into one column with start and end points
"""
ngrams_df = _process_ngrams_df_helper(ngrams_df, 'pattern')
if ngrams_duration is not None:
ngrams_duration = _process_ngrams_df_helper(ngrams_duration, 'duration')
ngrams_df['end'] = ngrams_df['start'] + ngrams_duration['duration']
else:
# make end=start+1 just to display offsets
ngrams_df['end'] = ngrams_df['start'] + 1
# filter according to voices and patterns (after computing durations for correct offsets)
if voices:
voice_condition = ngrams_df['voice'].isin(voices)
ngrams_df = ngrams_df[voice_condition].dropna(how='all')
if selected_pattern:
pattern_condition = ngrams_df['pattern'].isin(selected_pattern)
ngrams_df = ngrams_df[pattern_condition].dropna(how='all')
return ngrams_df
def _plot_ngrams_df_heatmap(processed_ngrams_df, heatmap_width=800, heatmap_height=300):
"""
Plot a heatmap for crim-intervals getNgram's processed output.
:param ngrams_df: processed crim-intervals getNgram's output.
:param selected_pattern: list of specific patterns the users want (optional)
:param voices: list of specific voices the users want (optional)
:param heatmap_width: the width of the final heatmap (optional)
:param heatmap_height: the height of the final heatmap (optional)
:return: a bar chart that displays the different patterns and their counts,
and a heatmap with the start offsets of chosen voices / patterns
"""
processed_ngrams_df = processed_ngrams_df.dropna(how='any')
selector = alt.selection_multi(fields=['pattern'])
# # turns patterns into string to make it easier to see
# processed_ngrams_df['pattern'] = processed_ngrams_df['pattern'].map(lambda cell: ", ".join(str(item) for item in cell), na_action='ignore').copy()
patterns_bar = create_bar_chart('pattern', 'count(pattern)', 'pattern', processed_ngrams_df, selector, selector)
heatmap = create_heatmap('start', 'end', 'voice', 'pattern', processed_ngrams_df, heatmap_width, heatmap_height,
selector, selector, tooltip=['start', 'end', 'pattern'])
return alt.vconcat(patterns_bar, heatmap)
def plot_ngrams_heatmap(ngrams_df, ngrams_duration=None, selected_patterns=[], voices=[], heatmap_width=800,
heatmap_height=300):
"""
Plot a heatmap for crim-intervals getNgram's output.
:param ngrams_df: crim-intervals getNgram's output
:param ngrams_duration: if not None, rely on durations in the
df to calculate the durations of the ngrams.
:param selected_patterns: list of specific patterns the users want (optional)
:param voices: list of specific voices the users want (optional)
:param heatmap_width: the width of the final heatmap (optional)
:param heatmap_height: the height of the final heatmap (optional)
:return: a bar chart that displays the different patterns and their counts,
and a heatmap with the start offsets of chosen voices / patterns
"""
processed_ngrams_df = process_ngrams_df(ngrams_df, ngrams_duration=ngrams_duration,
selected_pattern=selected_patterns,
voices=voices)
return _plot_ngrams_df_heatmap(processed_ngrams_df, heatmap_width=heatmap_width, heatmap_height=heatmap_height)
def _from_ema_to_offsets(df, ema_column):
"""
This method adds a columns of start and end measure of patterns into
the relationship dataframe using the column with the ema address.
:param df: dataframe containing relationships between patterns retrieved
from CRIM relationship json
:param ema_column: the name of the column storing ema address.
:return: the processed dataframe with two new columns start and end
"""
# retrieve the measures from ema address and create start and end in place
df['locations'] = df[ema_column].str.split("/", n=1, expand=True)[0]
df['locations'] = df['locations'].str.split(",")
df = df.explode('locations')
df[['start', 'end']] = df['locations'].str.split("-", expand=True).fillna(method='ffill')
df['start'] = df['start'].astype(float)
df['end'] = df['end'].astype(float)
return df
def _process_crim_json_url(url_column):
# remove 'data' from http://crimproject.org/data/observations/1/ or http://crimproject.org/data/relationships/5/
url_column = url_column.map(lambda cell: cell.replace('data/', ''))
return url_column
def plot_comparison_heatmap(df, ema_col, main_category='musical_type', other_category='observer.name', option=1,
heat_map_width=600, heat_map_height=300):
"""
This method plots a chart for relationships/observations dataframe retrieved from their
corresponding json files. This chart has two bar charts displaying the count of variables
the users selected, and a heatmap displaying the locations of the relationship.
:param df: relationships or observations dataframe
:param ema_col: name of the ema column
:param main_category: name of the main category for the first bar chart.
The chart would be colored accordingly (default='musical_type').
:param other_category: name of the other category for the zeroth bar chart.
(default='observer.name')
:param heat_map_width: the width of the final heatmap (default=800)
:param heat_map_height: the height of the final heatmap (default =300)
:return: a big chart containing two smaller bar chart and a heatmap
"""
df = df.copy() # create a deep copy of the selected observations to protect the original dataframe
df = _from_ema_to_offsets(df, ema_col)
# sort by id
df.sort_values(by=main_category, inplace=True)
df = _from_ema_to_offsets(df, ema_col)
df['website_url'] = _process_crim_json_url(df['url'])
df['id'] = df['id'].astype(str)
# because altair doesn't work when the categories' names have periods,
# a period is replaced with a hyphen.
new_other_category = other_category.replace(".", "_")
new_main_category = main_category.replace(".", "_")
df.rename(columns={other_category: new_other_category, main_category: new_main_category}, inplace=True)
other_selector = alt.selection_multi(fields=[new_other_category])
main_selector = alt.selection_multi(fields=[new_main_category])
other_category = new_other_category
main_category = new_main_category
bar1 = create_bar_chart(main_category, str('count(' + main_category + ')'), main_category, df,
other_selector | main_selector, main_selector)
bar0 = create_bar_chart(other_category, str('count(' + other_category + ')'), main_category, df,
other_selector | main_selector, other_selector)
heatmap = alt.Chart(df).mark_bar().encode(
x='start',
x2='end',
y='id',
href='website_url',
color=main_category,
opacity=alt.condition(other_selector | main_selector, alt.value(1), alt.value(0.2)),
tooltip=['website_url', main_category, other_category, 'start', 'end', 'id']
).properties(
width=heat_map_width,
height=heat_map_height
).add_selection(
main_selector
).interactive()
chart = alt.vconcat(
alt.hconcat(
bar1,
bar0
),
heatmap
)
# inserting url fix here
# chart['usermeta'] = {
# "embedOptions": {
# 'loader': {'target': '_blank'}
# }
return chart
def _recognize_integers(num_str):
if num_str[0] == '-':
return num_str[1:].isdigit()
else:
return num_str.isdigit()
def _close_match_helper(cell):
# process each cell into an interator of *floats* for easy comparisons
if type(cell) == str:
cell = cell.split(",")
if _recognize_integers(cell[0]):
cell = tuple(int(item) for item in cell)
return cell
def _close_match(ngrams_df, key_pattern):
ngrams_df['pattern'] = ngrams_df['pattern'].map(lambda cell: _close_match_helper(cell), na_action='ignore')
# making sure that key pattern and other patterns are tuple of string or ints
if not (type(ngrams_df.iloc[0, :]['pattern']) == type(key_pattern) == tuple
or type(ngrams_df.iloc[0, :]['pattern'][0]) == type(key_pattern[0])):
raise Exception("Input patterns and patterns inside dataframe aren't tuple of strings/ints")
ngrams_df['score'] = ngrams_df['pattern'].map(
lambda cell: 100 * textdistance.levenshtein.normalized_similarity(key_pattern, cell), na_action='ignore')
return ngrams_df
def plot_close_match_heatmap(ngrams_df, key_pattern, ngrams_duration=None, selected_patterns=[], voices=[],
heatmap_width=800, heatmap_height=300):
"""
Plot how closely the other vectors match a selected vector.
Uses the Levenshtein distance.
:param ngrams_df: crim-intervals getNgram's output
:param key_pattern: a pattern the users selected to compare other patterns with (tuple of floats)
:param selected_pattern: the specific other vectors the users selected
:param ngrams_duration: if None, simply output the offsets. If the users input a
list of durations, caculate the end by adding durations with offsets and
display the end on the heatmap accordingly.
:param selected_patterns: list of specific patterns the users want (optional)
:param voices: list of specific voices the users want (optional)
:param heatmap_width: the width of the final heatmap (optional)
:param heatmap_height: the height of the final heatmap (optional)
:return: a bar chart that displays the different patterns and their counts,
and a heatmap with the start offsets of chosen voices / patterns
"""
ngrams = process_ngrams_df(ngrams_df, ngrams_duration=ngrams_duration, selected_pattern=selected_patterns,
voices=voices)
ngrams.dropna(how='any',
inplace=True) # only the pattern column can be NaN because all columns have starts (==offsets) and voices
# calculate the score
key_pattern = _close_match_helper(key_pattern)
score_ngrams = _close_match(ngrams, key_pattern)
slider = alt.binding_range(min=0, max=100, step=1, name='cutoff:')
selector = alt.selection_single(name="SelectorName", fields=['cutoff'],
bind=slider, init={'cutoff': 50})
return create_heatmap('start', 'end', 'voice', 'score', score_ngrams, heatmap_width, heatmap_height,
alt.datum.score > selector.cutoff, selector, tooltip=['start', 'end', 'pattern', 'score'])
def generate_ngrams_and_duration(model, df, n=3, exclude=['Rest'],
interval_settings=('d', True, True), offsets='first'):
"""
This method accept a model and a dataframe with the melody or notes
and rests and generate an ngram (in columnwise and unit=0 setting)
and a corresponding duration ngram
:param model: an Imported Piece object.
:param df: dataframe containing consecutive notes.
:param n: accept any positive integers and would output ngrams of the corresponding sizes
can't handle the n=-1 option (refer to getNgrams documentation for more)
:param exclude: (refer to getNgrams documentation)
:param interval_settings: (refer to getNgrams documentation)
:param offsets: (refer to getNgrams documentation)
:return: ngram and corresponding duration dataframe!
"""
if n == -1:
raise Exception("Cannot calculate the duration for this type of ngrams")
# compute dur for the ngrams
dur = model.getDuration(df)
dur = dur.reindex_like(df).applymap(str, na_action='ignore')
# combine them and generate ngrams and duration at the same time
notes_dur = pd.concat([df, dur])
ngrams = model.getNgrams(df=df, n=n, exclude=exclude,
interval_settings=interval_settings, unit=0, offsets=offsets)
dur_ngrams = model.getNgrams(df=dur, n=n, exclude=exclude,
interval_settings=interval_settings, unit=0, offsets=offsets)
dur_ngrams = dur_ngrams.reindex_like(ngrams)
# sum up durations!
dur_ngrams = dur_ngrams.applymap(lambda cell: sum([float(element) for element in cell]), na_action='ignore')
return ngrams, dur_ngrams
# Network visualizations
def process_network_df(df, interval_column_name, ema_column_name):
"""
Create a small dataframe containing network
"""
result_df = pd.DataFrame()
result_df[['piece.piece_id', 'url', interval_column_name]] = \
df[['piece.piece_id', 'url', interval_column_name]].copy()
result_df[['segments']] = \
df[ema_column_name].astype(str).str.split("/", 1, expand=True)[0]
result_df['segments'] = result_df['segments'].str.split(",")
return result_df
# add nodes to graph
def create_interval_networks(interval_column, interval_type):
"""
Helper method to create networks for observations' intervals
:param interval_column: column containing the intervals users want to
examine
:param interval_type: 'melodic' or 'time'
:return: a dictionary of networks describing the intervals
"""
# dictionary maps the first time/melodic interval to its corresponding
# network
networks_dict = {'all': Network(directed=True, notebook=True)}
interval_column = interval_column.astype(str)
networks_dict['all'].add_node('all', color='red', shape='circle', level=0)
# create nodes from the patterns
for node in interval_column:
# create nodes according to the interval types
if interval_type == 'melodic':
nodes = re.sub(r'([+-])(?!$)', r'\1,', node).split(",")
separator = ''
elif interval_type == 'time':
nodes = node.split("/")
separator = '/'
else:
raise Exception("Please put either 'time' or 'melodic' for `type_interval`")
# nodes would be grouped according to the first interval
group = nodes[0]
if not group in networks_dict:
networks_dict[group] = Network(directed=True, notebook=True)
prev_node = 'all'
for i in range(1, len(nodes)):
node_id = separator.join(node for node in nodes[:i])
# add to its own family network
networks_dict[group].add_node(node_id, group=group, physics=False, level=i)
if prev_node != "all":
networks_dict[group].add_edge(prev_node, node_id)
# add to the big network
networks_dict['all'].add_node(node_id, group=group, physics=False, level=i)
networks_dict['all'].add_edge(prev_node, node_id)
prev_node = node_id
return networks_dict
def _manipulate_processed_network_df(df, interval_column, search_pattern_starts_with):
"""
This method helps to generate interactive widget in create_interactive_compare_df
:param search_pattern_starts_with:
:param df: the dataframe the user interact with
:param interval_column: the column of intervals
:return: A filtered and colored dataframe based on the option the user selected.
"""
mask = df[interval_column].astype(str).str.startswith(pat=search_pattern_starts_with)
filtered_df = df[mask].copy()
return filtered_df.fillna("-").style.applymap(
lambda x: "background: #ccebc5" if search_pattern_starts_with in x else "")
def create_interactive_compare_df(df, interval_column):
"""
This method returns a wdiget allowing users to interact with
the simple observations dataframe.
:param df: the dataframe the user interact with
:param interval_column: the column of intervals
:return: a widget that filters and colors a dataframe based on the users
search pattern.
"""
return interact(_manipulate_processed_network_df, df=fixed(df),
interval_column=fixed(interval_column), search_pattern_starts_with='Input search pattern')
def create_comparisons_networks_and_interactive_df(df, interval_column, interval_type, ema_column, patterns=[]):
"""
Generate a dictionary of networks and a simple dataframe allowing the users
search through the intervals.
:param df: the dataframe the user interact with
:param interval_column: the column of intervals
:param interval_type: put "time" or "melodic"
:param ema_column: column containing ema address
:param patterns: we could only choose to look at specific patterns (optional)
:return: a dictionary of networks created and a clean interactive df
"""
# process df
if patterns:
df = df[df[interval_column].isin(patterns)].copy()
networks_dict = create_interval_networks(df[interval_column], interval_type)
df = process_network_df(df, interval_column, ema_column)
return networks_dict, create_interactive_compare_df(df, interval_column)
#main heading of the resource
st.header("CRIM Project Meta Data Viewer")
st.write("These tools assemble metadata for about 5000 observations and 2500 relationships in Citations: The Renaissance Imitation Mass.")
st.write("Visit the [CRIM Project](https://crimproject.org) and its [Members Pages] (https://sites.google.com/haverford.edu/crim-project/home).")
st.markdown(
'''
- Use the __checkboxes at the left__ to view summaries of Observations by Type, Analyst, and Piece.
- For __Faceted Observation Search__ you can select any number of __pieces__ or __musical types__ (in either order), then view and download CSV files resulting tables.
- For __Faceted Relationship Search__ you can select any number of __pieces__ or __relationship types__ (in either order), then view and download CSV files resulting tables.
- Subtype tools display details as __charts__.
- Want to view a given __observation__ or __relationship__ with notation and metadata? Enter the given number as noted in the dialogue box.
''')
st.sidebar.write("Have you recently added Relationships to CRIM? Refresh to view them")
if st.sidebar.button("Refresh Data from CRIM Project"):
caching.clear_cache()
# st.cache speeds things up by holding data in cache
@st.cache(allow_output_mutation=True)
# get the data function
def get_data(link):
data = requests.get(link).json()
#df = pd.DataFrame(data)
df = pd.json_normalize(data)
return df
df = get_data('https://crimproject.org/data/observations')
# df = get_data('https://raw.githubusercontent.com/RichardFreedman/crim_data/main/test_data.json')
# df = requests.get('http://crimproject.org/data/observations/').json()
# df = get_data('https://raw.githubusercontent.com/CRIM-Project/CRIM-online/dev/crim/fixtures/migrated-crimdata/cleaned_observations.json')
df.rename(columns={'piece.piece_id':'piece_id',
'piece.full_title':'full_title',
'observer.name' : 'observer_name',
'details.entry intervals': 'entry_intervals',
'details.time intervals': 'time_intervals',
'details.voices': 'voices',
'details.voice': 'voice',
'details.periodic': 'periodic',
'details.regularity': 'regularity',
'details.sequential': 'sequential',
'details.inverted': 'inverted',
'details.retrograde': 'retrograde',
'details.invertible counterpoint': 'invertible_counterpoint',
'details.added entries': 'added_entries',
'details.ostinato': 'ostinato',
'details.type': 'type',
'details.dialogue': 'hr_dialogue',
'details.tone': 'cadence_tone',
'details.irregular cadence': 'irreg_cadence',
'details.features': 'features',
'details.dovetail cadence': 'dovetail',
'details.dovetail cadence voice': 'dovetail voice',
# 'details.dovetail voice name': 'dovetail_voice',
'details.dovetail position': 'dovetail_position',
'details.irregular roles': 'irregular_roles',
# 'details.cantizans': 'cantizans staff',
# 'details.tenorizans': 'tenorizans staff',
}, inplace=True)
# extract bar numbers from ema
df["measures"] = df['ema'].str.extract('(\d+-\d+)')
drop_list = ['url',
'ema',
'remarks',
'curated',
'created',
'updated',
'observer.url',
'piece.url',
'piece.mass',
'details.voice name',
'details.voice names',
'details.voice name reg',
'details.voice names reg',
'definition.url',
'definition.id',
'definition.observation_definition',
'details.cantizans name',
'details.tenorizans name',
'details.cantizans name reg',
'details.tenorizans name reg',
'details.dovetail voice name reg',
'details.altizans',
'details.bassizans',
'details.cantizans',
'details.tenorizans',
# 'details.irregular roles'
# 'details.dovetail cadence voice',
'details.dovetail voice name',
'voice',
'details',
'full_title',
]
df_clean = df.drop(columns=drop_list)
col_order = ['id',
'piece_id',
'full_title',
'musical_type',
'measures',
'observer_name',
'voices',
'time_intervals',
'entry_intervals',
'added_entries',
'regularity',
'periodic',
'inverted',
'retrograde',
'sequential',
'invertible_counterpoint',
'features',
'ostinato',
'type',
'hr_dialogue',
'cadence_tone',
'irregular_roles',
'dovetail',
'dovetail_position',
'irreg_cadence',
'dovetail voice',
]
df_clean = df_clean.reindex(columns=col_order)
# st.write(df_clean)
df_r = get_data('https://crimproject.org/data/relationships')
df_view = df_r
# # df_r = get_data('https://raw.githubusercontent.com/CRIM-Project/CRIM-online/dev/crim/fixtures/migrated-crimdata/cleaned_relationships.json')
convert_dict_r = {'id': int,
}
df = df.astype(convert_dict_r)
df_r.rename(columns={'observer.name':'observer_name',
'relationship_type': 'relationship_type',
'model_observation.id': 'model_observation',
'model_observation.piece.piece_id': 'model',
'model_observation.piece.full_title': 'model_title',
'derivative_observation.id': 'derivative_observation',
'derivative_observation.piece.piece_id': 'derivative',
'derivative_observation.piece.full_title': 'derivative_title',
'details.type': 'type',
'details.self': 'self',
'details.activity': 'activity',
'details.extent': 'extent',
'details.new counter subject': 'new_countersubject',
'details.sounding in different voices': "sounding_diff_voices",
'details.whole passage transposed': 'whole_passage_transposed',
'details.whole passage metrically shifted': 'whole_passage_shifted',
'details.melodically inverted': 'melodically_inverted',
'details.retrograde': 'retrograde',
'details.double or invertible counterpoint': 'invertible_counterpoint',
'details.old counter subject shifted metrically': 'old_cs_shifted',
'details.old counter subject transposed': 'old_cs_transposed',
'details.new combination': 'new_combination',
'details.metrically shifted': 'metrically_shifted',
'details.transposition': 'transposition',
'details.systematic diminution': 'diminution',
'details.systematic augmentation': 'augmentation',
}, inplace=True)
# df_r.rename(columns={'pk': 'id',
# 'fields.observer':'observer_name',
# 'fields.relationship_type': 'relationship_type',
# 'fields.model_observation': 'model_observation',
# 'fields.derivative_observation': 'derivative_observation',
# 'fields.details.type': 'type',
# 'fields.details.self': 'self',
# 'fields.details.activity': 'activity',
# 'fields.details.extent': 'extent',
# 'fields.details.new counter subject': 'new_countersubject',
# 'fields.details.sounding in different voices': "sounding_diff_voices",
# 'fields.details.whole passage transposed': 'whole_passage_transposed',
# 'fields.details.whole passage metrically shifted': 'whole_passage_shifted',
# 'fields.details.melodically inverted': 'melodically_inverted',
# 'fields.details.retrograde': 'retrograde',
# 'fields.details.double or invertible counterpoint': 'invertible_counterpoint',
# 'fields.details.old counter subject shifted metrically': 'old_cs_shifted',
# 'fields.details.old counter subject transposed': 'old_cs_transposed',
# 'fields.details.new combination': 'new_combination',
# 'fields.details.metrically shifted': 'metrically_shifted',