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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
import marimo

__generated_with = "0.11.26"
app = marimo.App(width="medium")


@app.cell
def _():
    import marimo as mo
    import pandas as pd
    import math
    from svg import SVG, Circle, Text, G, Line, Ellipse, Rect, Title
    import numpy as np
    return Circle, Ellipse, G, Line, Rect, SVG, Text, Title, math, mo, np, pd


@app.cell
def _(pd):
    # ===== IMPORT DATASETS =====
    coffeeyield = pd.read_excel("data/Coffee_yield.xlsx")
    coffeestructureindex_management = pd.read_excel("data/Environmental_and_management_variables.xlsx")
    plant_species_richness = pd.read_excel("data/Plant_species_richness.xlsx")
    return coffeestructureindex_management, coffeeyield, plant_species_richness


@app.cell
def _(pd):
    # ===== PREPARE WOODY DATA =====

    #Load the excelfile
    woody_species_abundance = pd.read_excel("data/Woody_species_abundance.xlsx")
    woody_species_abundance

    #Creating dataframe of total abundance of woody species, per Site ID
    woody_totals = woody_species_abundance.iloc[:, 1:].sum().reset_index()

    #Rename the columns to meaningful names
    woody_totals.columns = ["Site ID", "Woody_total"]

    #Normalise the abundance values to 0-100 scale for comparability
    #Divide each value by max (0-1 scale) and multiply by 100 (0-100 scale)
    woody_totals["Woody_abundance"] = (woody_totals["Woody_total"] / woody_totals["Woody_total"].max()) * 100

    #Keep only the Site ID and normalised abundance columns
    w_abundance = woody_totals[["Site ID", "Woody_abundance"]]
    #w_abundance
    return w_abundance, woody_species_abundance, woody_totals


@app.cell
def _(pd):
    # ===== PREPARE BRYOPHYTE DATA =====

    #Load the txtfile
    bryophyte_species_abundance = pd.read_csv("data/Bryophyte_frequency.txt", sep="\t")

    #Creating dataframe of total abundance of bryo species, per Site ID
    bryo_totals = bryophyte_species_abundance.iloc[:, 1:].sum().reset_index()

    #Rename the columns to meaningful names
    bryo_totals.columns = ["Site ID", "Bryo_total"]

    #Normalise the abundance values to 0-100 scale for comparability
    #Divide each value by max (0-1 scale) and multiply by 100 (0-100 scale)
    bryo_totals["Bryo_abundance"] = (bryo_totals["Bryo_total"] / bryo_totals["Bryo_total"].max()) * 100

    #Keep only the Site ID and normalised abundance columns
    b_abundance = bryo_totals[["Site ID", "Bryo_abundance"]]
    #b_abundance
    return b_abundance, bryo_totals, bryophyte_species_abundance


@app.cell(hide_code=True)
def _():
    # # ===== VERIFY BRYOPHYTE DATA =====

    # # See the raw totals BEFORE normalization
    # print("Raw bryophyte totals (before normalization):")
    # print(bryo_totals[["Site ID", "Bryo_total"]])

    # # See which site has the max
    # print(f"\nMax bryo total: {bryo_totals['Bryo_total'].max()}")

    # # Check a specific site (e.g., Ge1)
    # ge1_row = bryo_totals[bryo_totals["Site ID"] == "Ge1"]
    # if not ge1_row.empty:
    #     ge1_raw = ge1_row["Bryo_total"].values[0]
    #     print(f"Ge1 raw total: {ge1_raw}")

    #     # Verify the normalization calculation manually
    #     ge1_normalized_manual = (ge1_raw / bryo_totals["Bryo_total"].max()) * 100
    #     ge1_normalized_actual = ge1_row["Bryo_abundance"].values[0]

    #     print(f"Ge1 normalized (manual calc): {ge1_normalized_manual:.2f}")
    #     print(f"Ge1 normalized (from data): {ge1_normalized_actual:.2f}")
    #     print(f"Match: {abs(ge1_normalized_manual - ge1_normalized_actual) < 0.01}")
    # else:
    #     print("Ge1 not found in data")

    # # Show distribution
    # print(f"\nBryo abundance range: {bryo_totals['Bryo_abundance'].min():.2f} to {bryo_totals['Bryo_abundance'].max():.2f}")

    # # Display final result
    # print("\nFinal bryophyte abundance (0-100 scale):")
    # print(b_abundance.head(10))
    return


@app.cell
def _(pd):
    # ===== PREPARE HERB DATA =====

    #Load the txtfile
    herb_species_abundance = pd.read_csv("data/Herbaceous_vegetation_Abundance.txt", sep="\t")

    #Set Site ID as index and then sum species columns for total abundance
    herb_totals = herb_species_abundance.set_index(herb_species_abundance.columns[0]).iloc[:, :].sum(axis=1).reset_index()

    #Rename the columns to meaningful names
    herb_totals.columns = ["Site ID", "Herb_total"]

    #Normalise the abundance values to 0-100 scale for comparability
    #Divide each value by max (0-1 scale) and multiply by 100 (0-100 scale)
    herb_totals["Herb_abundance"] = (herb_totals["Herb_total"] / herb_totals["Herb_total"].max()) * 100
    herb_totals

    #Keep only the Site ID and normalised abundance columns
    h_abundance = herb_totals[["Site ID", "Herb_abundance"]]
    #h_abundance
    return h_abundance, herb_species_abundance, herb_totals


@app.cell
def _(

    b_abundance,

    coffeestructureindex_management,

    coffeeyield,

    h_abundance,

    plant_species_richness,

    w_abundance,

):
    merged = coffeeyield \
        .merge(coffeestructureindex_management, on="Site ID") \
        .merge(plant_species_richness, on="Site ID") \
        .merge(w_abundance, on="Site ID")\
        .merge(b_abundance, on="Site ID")\
        .merge(h_abundance, on="Site ID")
    merged
    return (merged,)


@app.cell
def _(filtered_flowers, filtered_for_plot, pd):
    # # ===== PREPARE CLUSTER DATA FOR HISTOGRAMS =====
    # # Load cluster distribution data
    # Coffee_structure_index_variables = pd.read_excel("Coffee_structure_index_variables.xlsx")
    # cluster_data = Coffee_structure_index_variables.copy()
    # cluster_data

    # # Group by Site ID and count clusters
    # cluster_counts = cluster_data.groupby(['Site ID', 'Fitted cluster']).size().unstack(fill_value=0)

    # # Ensure all clusters exist (1, 2, 3)
    # for cluster in [1, 2, 3]:
    #     if cluster not in cluster_counts.columns:
    #         cluster_counts[cluster] = 0

    # # Get only sites in filtered_flowers
    # cluster_counts = cluster_counts.loc[cluster_counts.index.isin(filtered_flowers['Site ID'])]

    # # Sort by ordinal_pos to match graph order
    # cluster_counts = cluster_counts.join(
    #     filtered_for_plot[['Site ID', 'ordinal_pos']].set_index('Site ID'),
    #     how='left'
    # )
    # cluster_counts = cluster_counts.sort_values('ordinal_pos')
    # cluster_counts

    # ===== PREPARE CLUSTER DATA FOR HISTOGRAMS =====
    cluster_data = pd.read_excel("data/Coffee_structure_index_variables.xlsx")

    # Simple: group by Site ID and cluster, count rows
    cluster_counts = cluster_data.groupby(['Site ID', 'Fitted cluster']).size().unstack(fill_value=0)

    # Make sure we have columns 1, 2, 3 (add if missing)
    for col in [1, 2, 3]:
        if col not in cluster_counts.columns:
            cluster_counts[col] = 0

    # Keep only sites we're showing
    cluster_counts = cluster_counts[cluster_counts.index.isin(filtered_flowers['Site ID'])]

    # Sort to match graph order
    site_order = filtered_for_plot[filtered_for_plot['Site ID'].isin(cluster_counts.index)].set_index('Site ID')
    cluster_counts = cluster_counts.loc[site_order.index]

    # FIX: Rename integer columns to strings
    cluster_counts.columns = cluster_counts.columns.astype(str)

    cluster_counts
    return cluster_counts, cluster_data, col, site_order


@app.cell
def _(filter_selector, merged, pd):
    # ===== PREPARE DATA FOR VISUALISATION. =====

    # ===== CREATING TWO VARIABLES FOR SELECTOR: one for plotting whole graph, one for filtering flowers only =====

    #Determine which sites to display (all variables for axis/background)
    filtered_for_plot = merged.copy()
    filtered_for_plot = filtered_for_plot.sort_values("Coffee structure index").reset_index(drop=True)
    filtered_for_plot["ordinal_pos"] = range(1, len(filtered_for_plot) + 1)

    # Define min/max yield for ALL sites (needed for axes)
    filtered_for_plot["min_yield"] = filtered_for_plot[["CC_Yield_2017", "CC_Yield_2018", "CC_Yield_2019"]].min(axis=1, skipna=True)
    filtered_for_plot["max_yield"] = filtered_for_plot[["CC_Yield_2017", "CC_Yield_2018", "CC_Yield_2019"]].max(axis=1, skipna=True)

    #Determine which flowers are shown (changes based on filter)
    if filter_selector.value == "All sites":
        filtered_flowers = filtered_for_plot.copy()
        show_labels = False
    else:  # "Top 10 + Bottom 10 yield"
        t10 = merged.nlargest(10, "Mean_CC_Yield")
        b10 = merged.nsmallest(10, "Mean_CC_Yield")
        filtered_flowers = pd.concat([t10, b10]).sort_values("Coffee structure index").reset_index(drop=True)
        show_labels = True

    # Add ordinal_pos, min_yield, max_yield from filtered_for_plot + add if to avoid duplicates (every time code runs)
    if "ordinal_pos" not in filtered_flowers.columns:
        filtered_flowers = filtered_flowers.merge(
        filtered_for_plot[["Site ID", "ordinal_pos", "min_yield", "max_yield"]], 
        on="Site ID", 
        how="left"
        )

    # ===== PREPERATION OF RICHNESS VARIABLE: CALCULATE MIN/MAX RICHNESS FOR NORMALIZATION =====
    herb_richness_min = filtered_flowers["Veg_Spps"].min()
    herb_richness_max = filtered_flowers["Veg_Spps"].max()
    bryo_richness_min = filtered_flowers["Bryo_Spps"].min()
    bryo_richness_max = filtered_flowers["Bryo_Spps"].max()
    woody_richness_min = filtered_flowers["Woody_Spps"].min()
    woody_richness_max = filtered_flowers["Woody_Spps"].max()

    # Function to normalize richness and convert to opacity in petals
    def get_opacity_from_richness(value, min_val, max_val):
        if max_val == min_val:  # Handle case where all values are the same
            normalized = 0.5
        else:
            normalized = (value - min_val) / (max_val - min_val)
        return 0.2 + (normalized * 0.8)  # Maps to 0.2-1.0 opacity range


    # ===== EXTRACT VARIABLES for plotting ======
    structureindex = filtered_for_plot["Coffee structure index"]
    mean_coffee_yield = filtered_for_plot["Mean_CC_Yield"]
    site_id = filtered_for_plot["Site ID"]
    herb_abundance = filtered_for_plot["Herb_abundance"]
    bryo_abundance = filtered_for_plot["Bryo_abundance"]
    woody_abundance = filtered_for_plot["Woody_abundance"]
    ordinal_pos = filtered_for_plot["ordinal_pos"]

    #Extract variables for flowers (filtered)
    flower_sites = filtered_flowers["Site ID"].tolist()

    print(f"All sites to display: {len(filtered_for_plot)}")
    print(f"Flowers to show: {len(filtered_flowers)}")
    return (
        b10,
        bryo_abundance,
        bryo_richness_max,
        bryo_richness_min,
        filtered_flowers,
        filtered_for_plot,
        flower_sites,
        get_opacity_from_richness,
        herb_abundance,
        herb_richness_max,
        herb_richness_min,
        mean_coffee_yield,
        ordinal_pos,
        show_labels,
        site_id,
        structureindex,
        t10,
        woody_abundance,
        woody_richness_max,
        woody_richness_min,
    )


@app.cell
def _():
    # filtered_for_plot
    # filtered_flowers
    return


@app.cell
def _():
    #svg frame
    svg_width=2350
    svg_height=1300
    return svg_height, svg_width


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

        <!-- CSS for layout of svg-->

        <style>

            svg.abc {

                border: 1px solid;

                background: #fafafa;

                border-radius: 4px;

                box-shadow: 0 1px 3px rgba(0,0,0,0.1);

                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;

            }

            .axis-label {

             font-size: 11px;

                fill: #333;

        }

            .axis-title {

                font-size: 13px;

                fill: #222;

                font-weight: 500;

            }

            .main-title {

            font-size: 20px;

            fill: black;

            font-weight: 600;

            }



            .subtitle {

                font-size: 11px;

                fill: #6b7280;

                font-weight: 400;

            }



            circle.nq1 {

                fill: #2563eb;

                stroke: #1e40af;

                stroke-width: 0.5px;

                opacity: 0.6;

            }



            ellipse {

                stroke: none;

            }



            line {

                stroke-linecap: round;

                stroke-linejoin: round;

            }

        </style>

        """
    )
    return


@app.cell
def _(mo):
    flower_size = mo.ui.slider(start=1, stop=2, step=0.25, value=1, label="Flower size")
    flower_size
    return (flower_size,)


@app.cell
def _(mo):
    filter_selector = mo.ui.dropdown(
         options=["All sites", "Top 10 yield & Bottom 10 yield"],
         label="Show sites"
     )
    filter_selector
    return (filter_selector,)


@app.cell
def _(

    Circle,

    Ellipse,

    Line,

    Rect,

    SVG,

    Text,

    bryo_richness_max,

    bryo_richness_min,

    cluster_counts,

    filter_selector,

    filtered_flowers,

    filtered_for_plot,

    flower_size,

    get_opacity_from_richness,

    herb_richness_max,

    herb_richness_min,

    math,

    mo,

    ordinal_pos,

    structureindex,

    svg_height,

    svg_width,

    woody_richness_max,

    woody_richness_min,

):
    #creating variable 'elements'
    _elements = []

    #Scaling of x-axis and y-axis
    margin = 90
    top_margin = 20 #add extra space at top for title
    usable_width = svg_width - 6 * margin + 30
    usable_height = svg_height - 2 * margin -top_margin

    x_min = 1
    x_max = 3

    y_min = 0
    y_max = 5500

    num_sites = len(filtered_for_plot)


    #===== LOOP FOR DRAWING ELEMENTS =====
    #adding elements to svg - loop for circles, flower petals and dashed lines of min-max yield
    #but instead of looping through all sites, we will loop through filtered_flowers (for selection 60 vs 20 site ids)
    for structure_, yield_, site_, herb_, bryo_, woody_, herb_richness, bryo_richness, woody_richness, min_y, max_y, ord_pos in zip(
        filtered_flowers["Coffee structure index"],
        filtered_flowers["Mean_CC_Yield"],
        filtered_flowers["Site ID"],
        filtered_flowers["Herb_abundance"],
        filtered_flowers["Bryo_abundance"],
        filtered_flowers["Woody_abundance"],
        filtered_flowers["Veg_Spps"],  # Herb richness
        filtered_flowers["Bryo_Spps"],  # Bryo richness
        filtered_flowers["Woody_Spps"],  # Woody richness
        filtered_flowers["min_yield"],
        filtered_flowers["max_yield"],
        #we need to get ordinal_pos from filtered_for_plot, not filtered_flowers
        filtered_flowers["Site ID"].map(filtered_for_plot.set_index("Site ID")["ordinal_pos"])
        ):

        #create position for site ids to draw circles, flowers etc.
        cx = margin + (ord_pos/num_sites)*usable_width
        cy = top_margin + margin + (y_max - yield_) / (y_max - y_min) * usable_height
        cy_min  = top_margin + margin + (y_max - min_y)  / (y_max - y_min) * usable_height
        cy_max  = top_margin + margin + (y_max - max_y)  / (y_max - y_min) * usable_height

        #draw site ID name
        _elements.append(
            Text(x=cx, y= cy-10,  
                 text=str(site_), 
                 class_="axis-label", font_size=8)
        )

        #draw number of structure index per site ID at x-axis
        _elements.append(
        Text(x=cx-10-10, y=svg_height - margin +25, 
             text=f"{structure_:.2f}", 
             class_="axis-label", font_size=8,
            transform=f"rotate(-45, {cx-10}, {svg_height - margin +15})")
    )

        #draw circles per site ID
        _elements.append(
            Circle(
                cx=cx,
                cy=cy,
                r=3,
                class_="nq1"
            )
        )


        #DRAW MIN-MAX YIELD for three years - draw dashed line from min to max yield
        _elements.append(
            Line(
                x1=cx, y1=cy_min,
                x2=cx, y2=cy_max,
                stroke="gray",
                stroke_dasharray="3,3"
            )
        )
        # - draw small square at max yield
        _elements.append(
            Rect(x=cx-3, y=cy_max-3, width=6, height=6, fill="gray")
        )

        # - draw small square at min yield
        _elements.append(
            Rect(x=cx-3, y=cy_min-3, width=6, height=6, fill="gray")
        )


        # each petal shows LENGTH = abundance, OPACITY = richness
        #create three petals categories
        petals = [
            (90,  herb_,   "orange", herb_richness, herb_richness_min, herb_richness_max),
            (210, bryo_,  "blue",   bryo_richness, bryo_richness_min, bryo_richness_max),
            (330, woody_, "green",  woody_richness, woody_richness_min, woody_richness_max),
        ]

        #draw ellipses based on petals data: correct direction, length corresponding abundance, opacity corresponding richness, and colour per group
        for angle, abundance, color, richness, min_richness, max_richness in petals:
            rad = math.radians(angle)
            petal_length = abundance / 100 * 16 * flower_size.value  # scale to fit in the plot, ABUNDANCE
            opacity = get_opacity_from_richness(richness, min_richness, max_richness)  # OPACITY = richness
            ex = cx + math.sin(rad) * petal_length
            ey = cy - math.cos(rad) * petal_length
            _elements.append(
                Ellipse(
                    cx=ex,
                    cy=ey,
                    rx=3*flower_size.value,
                    ry=petal_length,
                    fill=color,
                    opacity=opacity,
                    transform=f"rotate({angle}, {ex}, {ey})"
                )
            )


    # ===== AXES ======
    #creating variable 'axes'
    _axes = []

    # X-axis: draw the line of the x-axis and label it
    _axes.append(
        Line(
            x1=margin,
            y1=svg_height - margin,
            x2=usable_width + margin,
            y2=svg_height - margin,
            stroke="black"
        )
    )
    _axes.append(
        Text(
            x= usable_width + 100,
            y=svg_height - margin + 22,
            text="Sites ordered by structure index (1-3)",
            class_="axis-title"
        )
    )

    #Add ordinal positions on X-axis
    for i in range(0, num_sites + 1, 1):  
        x = margin + (i / num_sites) * usable_width
        _axes.append(
            Line(x1=x, y1=svg_height - margin, x2= x, y2=svg_height - margin - 5, stroke="black")
        )

    # ===== HISTOGRAMS PER SITE =====
    histogram_y = svg_height - 5 
    bar_width = 5
    bar_spacing = 2  # Space between the 3 bars
    bar_max_height = 40

    _axes.append(
        Text(
            x=margin,
            y=histogram_y - 40,
            text="Cluster Distribution per Site (16 shrubs each)",
            class_="axis-title"
        )
    )

    # Colors for clusters
    cluster_colors = {
        '1': "#2d46dc",  # Purple
        '2': "#91d76e",  # Green
        '3': "#be2d32"   # Red
    }

    # Draw histogram for each site in filtered_flowers
    for site_id_ in filtered_flowers['Site ID'].values:
        # Get ordinal position from filtered_for_plot
        ord_pos_val = filtered_for_plot[filtered_for_plot['Site ID'] == site_id_]['ordinal_pos'].values[0]
        site_x = margin + (ord_pos_val / num_sites) * usable_width

        # Get cluster counts for this site
        if site_id_ in cluster_counts.index:
            counts = cluster_counts.loc[site_id_, ['1', '2', '3']]

            # Draw 3 bars side-by-side
            for cluster_idx, cluster in enumerate(['1', '2', '3']):
                count = counts[cluster]
                bar_height = (count / 16) * bar_max_height

                # Calculate x position for each bar (3 bars side-by-side)
                bar_x = site_x - (bar_width + bar_spacing) + cluster_idx * (bar_width + bar_spacing)

                if bar_height > 0:
                    _axes.append(
                        Rect(
                            x=bar_x-2.5,
                            y=histogram_y - bar_height,
                            width=bar_width,
                            height=bar_height,
                            fill=cluster_colors[cluster]
                        )
                    )

    # Y-axis: draw the line and label it
    _axes.append(
        Line(
            x1=margin,
            y1=top_margin + margin -15,
            x2=margin,
            y2=svg_height - margin,
            stroke="black",
            )
    )

    _axes.append(
        Text(
            x= margin,
            y= top_margin + margin -23,
            text="Mean coffee yield (kg/ha)",
            class_="axis-title"
        )
    )

    #Add manual arrow at top of y-axis
    arrow_tip_x = margin
    arrow_tip_y = top_margin + margin - 15
    _axes.append(Line(x1=arrow_tip_x, y1=arrow_tip_y, x2=arrow_tip_x - 5, y2=arrow_tip_y + 10, stroke="black"))
    _axes.append(Line(x1=arrow_tip_x, y1=arrow_tip_y, x2=arrow_tip_x + 5, y2=arrow_tip_y + 10, stroke="black"))

    #Add positions on Y-axis
    for val in [0, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500]:

        y = top_margin + margin + (y_max - val) / (y_max - y_min) * usable_height

        _axes.append(
            Line(
                x1=margin - 5,
                y1=y,
                x2=margin,
                y2=y,
                stroke="black"
            )
        )

        _axes.append(
            Text(
                x=margin -50,
                y=y + 5,
                text=str(val),
                class_="axis-label"
            )
        )

        #Add dashed reference lines for Y-axis positions
        # Make lines longer for 0 and 2000
        if val in [500, 1000, 1500, 2000]:
            x2_end = svg_width - 50  # Longer
        else:
            x2_end = usable_width + margin  # Normal length

        _axes.append(
            Line(
                x1=margin,
                y1=y,
                x2=x2_end, 
                y2=y,
                stroke="lightgray",
                stroke_dasharray="3,3",
                opacity=0.7
            )
        )


    # ===== TITLE ======
    _axes.append(
        Text(
            x=svg_width / 2,
            y= 50,  # top_margin / 2 + 10,
            text="Exploring Coffee Yield Patterns: Structure Index, Plant Abundance, and Plant Richness",
            class_="main-title",
            text_anchor="middle"
        )
    )
    # Add subtitle
    _axes.append(
        Text(
            x=svg_width / 2,
            y= 75, #top_margin / 2 + 32,
            text="Each flower represents a site; flower petals show abundance and richness of co-occuring plant species. Min-max lines indicate yield variation across 2017-2019.",
            class_="subtitle",
            text_anchor="middle"
        )
    )


    # ===== LEGENDS =====

    # ===== RIGHT SIDE =====

    legend_x = usable_width + 120
    legend_y = top_margin + margin

    # ===== PART A: PLANT SPECIES LEGENDS =====

    # ===== 1) PLANT SPECIES TYPE =====
    _axes.append(
        Text(
            x=legend_x,
            y=legend_y,
            text="Plant Species Type",
            class_="axis-title"
        )
    )

    legend_colors = [
        ("orange", "Herbaceous plant species"),
        ("blue", "Bryophyte plant species"),
        ("green", "Woody plant species"),
    ]

    for i, (color, label) in enumerate(legend_colors):
        y_pos = legend_y + 20 + i * 18
        _axes.append(
            Ellipse(cx=legend_x, cy=y_pos, rx=5, ry=5, fill=color, opacity=0.6)
        )
        _axes.append(
            Text(x=legend_x + 15, y=y_pos + 4, text=label, class_="axis-label")
        )

    # ===== 2) PETAL LENGTH = ABUNDANCE =====
    legend_y_abundance = legend_y + 110

    _axes.append(
        Text(
            x=legend_x,
            y=legend_y_abundance,
            text="Petal Length = Plant Abundance",
            class_="axis-title"
        )
    )

    _axes.append(
        Text(
            x=legend_x,
            y=legend_y_abundance + 16,
            text="(% of plant community)",
            class_="axis-label",
            font_size=8
        )
    )

    # 5 petals showing abundance gradient with actual percentage values
    abundance_values = [0, 25, 50, 75, 100]
    petal_lengths = [2, 6, 10, 14, 18]
    spacing = 50

    for i, (abundance, petal_len) in enumerate(zip(abundance_values, petal_lengths)):
        ex = legend_x + 5 + i * spacing
        ey = legend_y_abundance + 40
        _axes.append(
            Ellipse(
                cx=ex,
                cy=ey,
                rx=1.5,
                ry=petal_len,
                fill="gray",
                opacity=0.3,
                transform=f"rotate(90, {ex}, {ey})"
            )
        )

        # Add value labels below
        _axes.append(
            Text(x=ex - 5, y=legend_y_abundance + 62, text=f"{abundance}%", 
                 class_="axis-label", font_size=7)
        )

    # ===== 3) PETAL OPACITY = SPECIES RICHNESS =====
    legend_y_richness = legend_y_abundance + 110

    _axes.append(
        Text(
            x=legend_x,
            y=legend_y_richness,
            text="Petal Opacity = Species Richness",
            class_="axis-title"
        )
    )

    _axes.append(
        Text(
            x=legend_x,
            y=legend_y_richness + 16,
            text="(normalized 0.2-1.0 scale)",
            class_="axis-label",
            font_size=8
        )
    )

    # 5 circles showing richness gradient with actual species counts
    richness_values = [
        (herb_richness_min, f"{int(herb_richness_min)} sp."),
        ((herb_richness_min + herb_richness_max) * 0.25, f"{int((herb_richness_min + herb_richness_max) * 0.25)} sp."),
        ((herb_richness_min + herb_richness_max) * 0.5, f"{int((herb_richness_min + herb_richness_max) * 0.5)} sp."),
        ((herb_richness_min + herb_richness_max) * 0.75, f"{int((herb_richness_min + herb_richness_max) * 0.75)} sp."),
        (herb_richness_max, f"{int(herb_richness_max)} sp."),
    ]

    opacities_richness = [0.2, 0.4, 0.6, 0.8, 1.0]

    for i, (opacity, (richness_val, richness_label)) in enumerate(zip(opacities_richness, richness_values)):
        ex = legend_x + 5 + i * spacing
        ey = legend_y_richness + 40
        _axes.append(
            Ellipse(cx=ex, cy=ey, rx=5, ry=5, fill="gray", opacity=opacity)
        )

        # Add value labels below
        _axes.append(
            Text(x=ex - 8, y=legend_y_richness + 62, text=richness_label, 
                 class_="axis-label", font_size=7)
        )


    # Frame around three Plant Species legends (Type, Abundance, Richness)
    frame_padding = 12
    _axes.append(
        Rect(
            x=legend_x - frame_padding,
            y=legend_y - frame_padding,
            width=320,
            height=legend_y_richness + 100 - (legend_y - frame_padding),
            fill="none",
            stroke="#cccccc",
            stroke_width=1.5,
            opacity=0.9
        )
    )

    # ===== STRUCTURE INDEX DENSITY LEGEND =====
    density_legend_y = legend_y_richness + 145

    #add title
    _axes.append(
        Text(
            x=legend_x,
            y=density_legend_y - 15,
            text="Structure Index Density",
            class_="axis-title"
        )
    )

    # Create a vertical gradient scale showing gap size progression
    gap_values = ["gap ≈ 0", "gap < 0.03", "gap < 0.06", "gap < 0.10", "gap ≥ 0.10"]
    opacity_values = [0.35, 0.32, 0.25, 0.18, 0.10]

    # Top label - High density
    _axes.append(
        Text(x=legend_x + 30, y=density_legend_y, text="High density (compressed)", 
             class_="axis-label", font_size=9)
    )

    # Draw rectangles vertically
    for i, (gap, opacity) in enumerate(zip(gap_values, opacity_values)):
        y_pos = density_legend_y + 10 + i * 22

        _axes.append(
            Rect(x=legend_x, y=y_pos, width=20, height=18, fill="gray", opacity=opacity)
        )

        _axes.append(
            Text(x=legend_x + 28, y=y_pos + 13, text=gap, 
                 class_="axis-label", font_size=9)
        )

    # Bottom label - Low density
    _axes.append(
        Text(x=legend_x + 30, y=density_legend_y + 10 + 5 * 22 + 15, 
             text="Low density (spread)", class_="axis-label", font_size=9)
    )

    # Frame around Structure Index Density legend
    _axes.append(
        Rect(
            x=legend_x - frame_padding,
            y= 430, #density_legend_y - frame_padding,
            width=320,
            height=5 * 22 + 60 +15,
            fill="none",
            stroke="#cccccc",
            stroke_width=1.5,
            opacity=0.9
        )
    )


    # ===== CLUSTER LEGEND =====
    cluster_legend_x = usable_width + 350
    cluster_legend_y = histogram_y - 63

    _axes.append(
        Text(
            x=cluster_legend_x -143,
            y=cluster_legend_y +43,
            text="Cluster Distribution",
            class_="axis-title"
        )
    )

    cluster_dataa = [
        ("#2d46dc", "Cluster 1"),
        ("#91d76e", "Cluster 2"),
        ("#be2d32", "Cluster 3"),
    ]

    for i, (color, label) in enumerate(cluster_dataa):
        y_pos = cluster_legend_y + 16 + i * 16
        _axes.append(
            Rect(x=cluster_legend_x, y=y_pos, width=10, height=10, fill=color)
        )
        _axes.append(
            Text(x=cluster_legend_x + 18, y=y_pos + 10, text=label, class_="axis-label")
        )



    # ===== AGGREGATE FLOWERS (Bottom right area) =====

    #create two groups
    top_half = filtered_flowers.nlargest(len(filtered_flowers)//2, "Mean_CC_Yield")
    bottom_half = filtered_flowers.nsmallest(len(filtered_flowers)//2, "Mean_CC_Yield")

    # ABUNDANCE (for petal length)
    g1_herb   = bottom_half["Herb_abundance"].mean()
    g1_bryo  = bottom_half["Bryo_abundance"].mean()
    g1_woody = bottom_half["Woody_abundance"].mean()

    g2_herb   = top_half["Herb_abundance"].mean()
    g2_bryo  = top_half["Bryo_abundance"].mean()
    g2_woody = top_half["Woody_abundance"].mean()

    # RICHNESS (for petal opacity)
    g1_herb_richness = bottom_half["Veg_Spps"].mean()
    g1_bryo_richness = bottom_half["Bryo_Spps"].mean()
    g1_woody_richness = bottom_half["Woody_Spps"].mean()

    g2_herb_richness = top_half["Veg_Spps"].mean()
    g2_bryo_richness = top_half["Bryo_Spps"].mean()
    g2_woody_richness = top_half["Woody_Spps"].mean()

    #y positions fixed to mean yield of each group
    flower_x = usable_width + 200
    flower_y1 = top_margin + margin + (y_max - bottom_half["Mean_CC_Yield"].mean()) / (y_max - y_min) * usable_height #+800
    flower_y2 = top_margin +  margin + (y_max - top_half["Mean_CC_Yield"].mean()) / (y_max - y_min) * usable_height # + 900

    #define draw_flower mentioning position, direction, abundance for two groups, colour etc
    def draw_flower(cx, cy, herb, bryo, woody, herb_rich, bryo_rich, woody_rich, scale=1):
        petals = [
            (90,  herb,   "orange", herb_rich, herb_richness_min, herb_richness_max),
            (210, bryo,   "blue",   bryo_rich, bryo_richness_min, bryo_richness_max),
            (330, woody,  "green",  woody_rich, woody_richness_min, woody_richness_max),
        ]
        flower_elements = []
        for angle, abundance, color, richness, min_richness, max_richness in petals:
            rad = math.radians(angle)
            petal_length = abundance / 100 * 14 * scale
            opacity = get_opacity_from_richness(richness, min_richness, max_richness)
            ex = cx + math.sin(rad) * petal_length
            ey = cy - math.cos(rad) * petal_length
            flower_elements.append(
                Ellipse(
                    cx=ex,
                    cy=ey,
                    rx=3 * scale,
                    ry=petal_length,
                    fill=color,
                    opacity=opacity,
                    transform=f"rotate({angle}, {ex}, {ey})"
                )
            )
        return flower_elements

    # draw both aggregate flowers using definition
    _elements += draw_flower(flower_x, flower_y1, g1_herb, g1_bryo, g1_woody, g1_herb_richness, g1_bryo_richness, g1_woody_richness, scale=3)
    _elements += draw_flower(flower_x, flower_y2, g2_herb, g2_bryo, g2_woody, g2_herb_richness, g2_bryo_richness, g2_woody_richness, scale=3)

    #add labels
    _axes.append(
        Text(
            x=legend_x#flower_x-60
            , y=density_legend_y +235,
            text="Aggregate flowers of two groups comparing low/high yield",
            class_="axis-title"#,
            #font_size=6
        )
    )
    _axes.append(Text(
        x=legend_x #flower_x-60
        , y=flower_y1 - 60,
        text="Sites with low yield (Lower half of 60 sites/Bottom 10)", class_="axis-label"#, font_size=7
    ))
    _axes.append(Text(
        x=legend_x,
        #flower_x-60, 
        y=flower_y2 -60,
        text="Sites with top yield (Upper half of 60 sites/Top 10)", class_="axis-label"#, font_size=7
    ))

    # ===== DENSITY VISUALISATION BACKGROUND =====
    #add values of structure index in a list to calculate gaps
    struct_values = structureindex.values

    for idx in range(len(struct_values) - 1):
        gap = struct_values[idx + 1] - struct_values[idx]

        #size of gap determines opacity
        if gap == 0.0000:
            opacity = 0.35
        elif gap < 0.03:
            opacity = 0.32
        elif gap < 0.06:
            opacity = 0.25
        elif gap < 0.10:
            opacity = 0.18
        else:
            opacity = 0.10

        #define positions for drawing rectangle (in between sites)
        x_curr = margin + (ordinal_pos[idx] / num_sites) * usable_width
        x_next = margin + (ordinal_pos[idx + 1] / num_sites) * usable_width

        #draw rectangles between each site/structure index value, that span across the whole y-axis, using opacity variable to change according to gap size
        _axes.append(
            Rect(x=x_curr, y=margin+ top_margin, width=x_next - x_curr, 
                 height=usable_height, fill="gray", opacity=opacity)
        )

    # ===== CREATING SVG FRAME =====
    _svg = SVG(width=svg_width, height=svg_height, class_="abc",
              elements=_elements+_axes)
    svg_str = _svg.as_str()

    mo.vstack([
        mo.Html(svg_str),
        mo.hstack([
            filter_selector,
            flower_size
            ])
    ])
    return (
        abundance,
        abundance_values,
        angle,
        arrow_tip_x,
        arrow_tip_y,
        bar_height,
        bar_max_height,
        bar_spacing,
        bar_width,
        bar_x,
        bottom_half,
        bryo_,
        bryo_richness,
        cluster,
        cluster_colors,
        cluster_dataa,
        cluster_idx,
        cluster_legend_x,
        cluster_legend_y,
        color,
        count,
        counts,
        cx,
        cy,
        cy_max,
        cy_min,
        density_legend_y,
        draw_flower,
        ex,
        ey,
        flower_x,
        flower_y1,
        flower_y2,
        frame_padding,
        g1_bryo,
        g1_bryo_richness,
        g1_herb,
        g1_herb_richness,
        g1_woody,
        g1_woody_richness,
        g2_bryo,
        g2_bryo_richness,
        g2_herb,
        g2_herb_richness,
        g2_woody,
        g2_woody_richness,
        gap,
        gap_values,
        herb_,
        herb_richness,
        histogram_y,
        i,
        idx,
        label,
        legend_colors,
        legend_x,
        legend_y,
        legend_y_abundance,
        legend_y_richness,
        margin,
        max_richness,
        max_y,
        min_richness,
        min_y,
        num_sites,
        opacities_richness,
        opacity,
        opacity_values,
        ord_pos,
        ord_pos_val,
        petal_len,
        petal_length,
        petal_lengths,
        petals,
        rad,
        richness,
        richness_label,
        richness_val,
        richness_values,
        site_,
        site_id_,
        site_x,
        spacing,
        struct_values,
        structure_,
        svg_str,
        top_half,
        top_margin,
        usable_height,
        usable_width,
        val,
        woody_,
        woody_richness,
        x,
        x2_end,
        x_curr,
        x_max,
        x_min,
        x_next,
        y,
        y_max,
        y_min,
        y_pos,
        yield_,
    )


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