Severian commited on
Commit
9dbdd98
ยท
verified ยท
1 Parent(s): b8daacb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +858 -109
app.py CHANGED
@@ -1020,8 +1020,145 @@ def create_diagnostic_plots(z, w):
1020
  )
1021
  return fig
1022
 
1023
- def create_dual_holography_plot(z1, phi1, z2, phi2, resolution, wavelength, title1="Primary", title2="Comparison"):
1024
- """Creates side-by-side holographic visualizations for comparison."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1025
  field_data1 = generate_holographic_field(z1, phi1, resolution)
1026
  field_data2 = generate_holographic_field(z2, phi2, resolution)
1027
 
@@ -1031,80 +1168,377 @@ def create_dual_holography_plot(z1, phi1, z2, phi2, resolution, wavelength, titl
1031
  grid_x1, grid_y1, grid_phi1 = field_data1
1032
  grid_x2, grid_y2, grid_phi2 = field_data2
1033
 
1034
- mag_phi1, phase_phi1 = np.abs(grid_phi1), np.angle(grid_phi1)
1035
- mag_phi2, phase_phi2 = np.abs(grid_phi2), np.angle(grid_phi2)
1036
-
1037
- # Wavelength to colorscale mapping
1038
- def wavelength_to_rgb(wl):
1039
- if 380 <= wl < 440: return f'rgb({int(-(wl - 440) / (440 - 380) * 255)}, 0, 255)'
1040
- elif 440 <= wl < 495: return f'rgb(0, {int((wl - 440) / (495 - 440) * 255)}, 255)'
1041
- elif 495 <= wl < 570: return f'rgb(0, 255, {int(-(wl - 570) / (570 - 495) * 255)})'
1042
- elif 570 <= wl < 590: return f'rgb({int((wl - 570) / (590 - 570) * 255)}, 255, 0)'
1043
- elif 590 <= wl < 620: return f'rgb(255, {int(-(wl - 620) / (620 - 590) * 255)}, 0)'
1044
- elif 620 <= wl <= 750: return 'rgb(255, 0, 0)'
1045
- return 'rgb(255,255,255)'
 
 
 
 
 
 
 
 
 
1046
 
1047
- mid_color = wavelength_to_rgb(wavelength)
1048
- custom_colorscale = [[0, 'rgb(20,0,40)'], [0.5, mid_color], [1, 'rgb(255,255,255)']]
1049
-
1050
  fig = make_subplots(
1051
  rows=1, cols=2,
1052
  specs=[[{'type': 'scene'}, {'type': 'scene'}]],
1053
- subplot_titles=[title1, title2]
 
1054
  )
1055
 
1056
- # Left plot (Primary)
1057
- fig.add_trace(go.Surface(
1058
- x=grid_x1, y=grid_y1, z=mag_phi1,
1059
- surfacecolor=phase_phi1,
1060
- colorscale=custom_colorscale,
1061
- cmin=-np.pi, cmax=np.pi,
1062
- showscale=False,
1063
- name=title1,
1064
- contours_z=dict(show=True, usecolormap=True, highlightcolor="limegreen", project_z=True)
1065
- ), row=1, col=1)
 
 
 
 
 
 
 
 
 
 
1066
 
1067
- # Right plot (Comparison)
1068
- fig.add_trace(go.Surface(
1069
- x=grid_x2, y=grid_y2, z=mag_phi2,
1070
- surfacecolor=phase_phi2,
1071
- colorscale=custom_colorscale,
1072
- cmin=-np.pi, cmax=np.pi,
1073
- showscale=False,
1074
- name=title2,
1075
- contours_z=dict(show=True, usecolormap=True, highlightcolor="limegreen", project_z=True)
1076
- ), row=1, col=2)
 
 
 
 
1077
 
1078
- # Add data points
1079
  if z1 is not None and phi1 is not None:
 
1080
  fig.add_trace(go.Scatter3d(
1081
  x=np.real(z1), y=np.imag(z1), z=np.abs(phi1) + 0.05,
1082
- mode='markers', marker=dict(size=3, color='black', symbol='x'),
1083
- name=f'{title1} Points', showlegend=False
 
 
 
 
1084
  ), row=1, col=1)
1085
 
1086
  if z2 is not None and phi2 is not None:
 
1087
  fig.add_trace(go.Scatter3d(
1088
  x=np.real(z2), y=np.imag(z2), z=np.abs(phi2) + 0.05,
1089
- mode='markers', marker=dict(size=3, color='black', symbol='x'),
1090
- name=f'{title2} Points', showlegend=False
 
 
 
 
1091
  ), row=1, col=2)
1092
 
 
1093
  fig.update_layout(
1094
- title="Side-by-Side Cross-Species Holographic Comparison",
 
 
 
 
1095
  scene=dict(
1096
  xaxis_title="Re(z)", yaxis_title="Im(z)", zaxis_title="|ฮฆ|",
1097
- camera=dict(eye=dict(x=1.5, y=1.5, z=1.5))
 
 
1098
  ),
1099
  scene2=dict(
1100
  xaxis_title="Re(z)", yaxis_title="Im(z)", zaxis_title="|ฮฆ|",
1101
- camera=dict(eye=dict(x=1.5, y=1.5, z=1.5))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1102
  ),
1103
  margin=dict(l=0, r=0, b=0, t=60),
1104
- height=600
1105
  )
1106
  return fig
1107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1108
  def create_dual_diagnostic_plots(z1, w1, z2, w2, title1="Primary", title2="Comparison"):
1109
  """Creates side-by-side diagnostic plots for cross-species comparison."""
1110
  fig = make_subplots(
@@ -1390,58 +1824,260 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="teal", secondary_hue="cyan")) a
1390
  outputs=manifold_outputs
1391
  )
1392
 
1393
- with gr.TabItem("Interactive Holography"):
 
 
 
 
 
 
 
 
 
 
 
1394
  with gr.Row():
1395
  with gr.Column(scale=1):
1396
- gr.Markdown("### Cross-Species Holography Controls")
1397
-
1398
- # Species selection and automatic pairing
1399
- species_dropdown = gr.Dropdown(
1400
- label="Select Species",
1401
- choices=["Dog", "Human"],
1402
- value="Dog"
1403
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1404
 
1405
- # Primary file selection (filtered by species)
1406
- dog_files = df_combined[df_combined["source"] == "Dog"]["filepath"].astype(str).tolist()
1407
- human_files = df_combined[df_combined["source"] == "Human"]["filepath"].astype(str).tolist()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1408
 
1409
- primary_dropdown = gr.Dropdown(
1410
- label="Primary Audio File",
1411
- choices=dog_files,
1412
- value=dog_files[0] if dog_files else None
1413
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1414
 
1415
- # Automatically found neighbor (from opposite species)
1416
- neighbor_dropdown = gr.Dropdown(
1417
- label="Auto-Found Cross-Species Neighbor",
1418
- choices=human_files,
1419
- value=human_files[0] if human_files else None,
1420
- interactive=True # Allow manual override
1421
- )
 
 
 
 
1422
 
1423
- holo_lens_dropdown = gr.Dropdown(label="CMT Lens", choices=["gamma", "zeta", "airy", "bessel"], value="gamma")
1424
- holo_resolution_slider = gr.Slider(label="Field Resolution", minimum=20, maximum=100, step=5, value=40)
1425
- holo_wavelength_slider = gr.Slider(label="Illumination Wavelength (nm)", minimum=380, maximum=750, step=5, value=550)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1426
 
1427
- # Information panels
1428
- primary_info_html = gr.HTML(label="Primary Audio Info")
1429
- neighbor_info_html = gr.HTML(label="Neighbor Audio Info")
 
 
 
 
 
 
 
 
 
 
 
 
1430
 
1431
- # Audio players
1432
- primary_audio_out = gr.Audio(label="Primary Audio")
1433
- neighbor_audio_out = gr.Audio(label="Neighbor Audio")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1434
 
1435
- with gr.Column(scale=2):
1436
- dual_holography_plot = gr.Plot(label="Side-by-Side Holographic Comparison")
1437
- dual_diagnostic_plot = gr.Plot(label="Cross-Species Diagnostic Comparison")
 
 
 
 
 
 
 
 
1438
 
1439
  def update_file_choices(species):
1440
  """Update the primary file dropdown based on selected species."""
1441
  species_files = df_combined[df_combined["source"] == species]["filepath"].astype(str).tolist()
1442
  return species_files
1443
 
1444
- def update_cross_species_view(species, primary_file, neighbor_file, lens, resolution, wavelength):
 
 
 
 
1445
  if not primary_file:
1446
  empty_fig = go.Figure(layout={"title": "Please select a primary file."})
1447
  return empty_fig, empty_fig, "", "", None, None
@@ -1488,25 +2124,44 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="teal", secondary_hue="cyan")) a
1488
  primary_fp = resolve_audio_path(primary_row)
1489
  neighbor_fp = resolve_audio_path(neighbor_row) if neighbor_row is not None else None
1490
 
1491
- # Create visualizations
1492
  if primary_cmt and neighbor_cmt:
1493
  primary_title = f"{species}: {primary_row.get('label', 'Unknown')}"
1494
  neighbor_title = f"{neighbor_row['source']}: {neighbor_row.get('label', 'Unknown')}"
1495
 
 
1496
  dual_holo_fig = create_dual_holography_plot(
1497
  primary_cmt["z"], primary_cmt["phi"],
1498
  neighbor_cmt["z"], neighbor_cmt["phi"],
1499
- resolution, wavelength, primary_title, neighbor_title
 
 
1500
  )
1501
 
 
1502
  dual_diag_fig = create_dual_diagnostic_plots(
1503
  primary_cmt["z"], primary_cmt["w"],
1504
  neighbor_cmt["z"], neighbor_cmt["w"],
1505
  primary_title, neighbor_title
1506
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
1507
  else:
1508
  dual_holo_fig = go.Figure(layout={"title": "Error processing audio files"})
1509
  dual_diag_fig = go.Figure(layout={"title": "Error processing audio files"})
 
 
1510
 
1511
  # Build info strings with CMT diagnostic values
1512
  primary_info = f"""
@@ -1537,7 +2192,99 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="teal", secondary_hue="cyan")) a
1537
  primary_audio = primary_fp if primary_fp and os.path.exists(primary_fp) else None
1538
  neighbor_audio = neighbor_fp if neighbor_row is not None and neighbor_fp and os.path.exists(neighbor_fp) else None
1539
 
1540
- return (dual_holo_fig, dual_diag_fig, primary_info, neighbor_info,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1541
  primary_audio, neighbor_audio)
1542
 
1543
  # Event handlers
@@ -1561,28 +2308,30 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="teal", secondary_hue="cyan")) a
1561
  outputs=[primary_dropdown, neighbor_dropdown]
1562
  )
1563
 
1564
- cross_species_inputs = [species_dropdown, primary_dropdown, neighbor_dropdown,
1565
- holo_lens_dropdown, holo_resolution_slider, holo_wavelength_slider]
1566
- cross_species_outputs = [dual_holography_plot, dual_diagnostic_plot,
1567
- primary_info_html, neighbor_info_html,
1568
- primary_audio_out, neighbor_audio_out]
1569
-
1570
- # Only bind change events, not load events to avoid overwhelming initialization
1571
- primary_dropdown.change(update_cross_species_view,
1572
- inputs=cross_species_inputs,
1573
- outputs=cross_species_outputs)
1574
- neighbor_dropdown.change(update_cross_species_view,
1575
- inputs=cross_species_inputs,
1576
- outputs=cross_species_outputs)
1577
- holo_lens_dropdown.change(update_cross_species_view,
1578
- inputs=cross_species_inputs,
1579
- outputs=cross_species_outputs)
1580
- holo_resolution_slider.change(update_cross_species_view,
1581
- inputs=cross_species_inputs,
1582
- outputs=cross_species_outputs)
1583
- holo_wavelength_slider.change(update_cross_species_view,
1584
- inputs=cross_species_inputs,
1585
- outputs=cross_species_outputs)
 
 
1586
 
1587
  if __name__ == "__main__":
1588
  demo.launch(share=True, debug=True)
 
1020
  )
1021
  return fig
1022
 
1023
+ def create_enhanced_holography_plot(z, phi, resolution, wavelength, field_depth=5, interference_strength=1.0, colormap="Wavelength", title="Holographic Field"):
1024
+ """Creates an enhanced holographic visualization with advanced mathematical features."""
1025
+ field_data = generate_holographic_field(z, phi, resolution)
1026
+ if field_data is None:
1027
+ return go.Figure(layout={"title": "Insufficient data for enhanced holography"})
1028
+
1029
+ grid_x, grid_y, grid_phi = field_data
1030
+ mag_phi = np.abs(grid_phi) * interference_strength
1031
+ phase_phi = np.angle(grid_phi)
1032
+
1033
+ # Enhanced wavelength to colorscale mapping with more sophisticated colors
1034
+ def wavelength_to_rgb_enhanced(wl):
1035
+ if 380 <= wl < 420: return f'rgb({int(255 * (420-wl)/40)}, 0, 255)' # Violet
1036
+ elif 420 <= wl < 440: return f'rgb(0, 0, 255)' # Blue
1037
+ elif 440 <= wl < 490: return f'rgb(0, {int(255 * (wl-440)/50)}, 255)' # Cyan
1038
+ elif 490 <= wl < 510: return f'rgb(0, 255, {int(255 * (510-wl)/20)})' # Green
1039
+ elif 510 <= wl < 580: return f'rgb({int(255 * (wl-510)/70)}, 255, 0)' # Yellow
1040
+ elif 580 <= wl < 645: return f'rgb(255, {int(255 * (645-wl)/65)}, 0)' # Orange
1041
+ elif 645 <= wl <= 750: return f'rgb(255, 0, 0)' # Red
1042
+ return 'rgb(255,255,255)'
1043
+
1044
+ # Choose colorscale based on mode
1045
+ if colormap == "Wavelength":
1046
+ mid_color = wavelength_to_rgb_enhanced(wavelength)
1047
+ custom_colorscale = [[0, 'rgb(10,0,20)'], [0.3, 'rgb(30,20,60)'], [0.5, mid_color],
1048
+ [0.7, 'rgb(255,200,150)'], [1, 'rgb(255,255,255)']]
1049
+ elif colormap == "Phase":
1050
+ custom_colorscale = 'hsv'
1051
+ elif colormap == "Magnitude":
1052
+ custom_colorscale = 'hot'
1053
+ elif colormap == "Interference":
1054
+ custom_colorscale = [[0, 'rgb(0,0,100)'], [0.25, 'rgb(0,100,200)'], [0.5, 'rgb(255,255,0)'],
1055
+ [0.75, 'rgb(255,100,0)'], [1, 'rgb(255,0,0)']]
1056
+ else: # Custom
1057
+ custom_colorscale = 'viridis'
1058
+
1059
+ fig = go.Figure()
1060
+
1061
+ # Multi-layer holographic surface with depth
1062
+ for depth_layer in range(field_depth):
1063
+ layer_alpha = 1.0 - (depth_layer * 0.15) # Fade deeper layers
1064
+ layer_offset = depth_layer * 0.1
1065
+
1066
+ fig.add_trace(go.Surface(
1067
+ x=grid_x, y=grid_y, z=mag_phi + layer_offset,
1068
+ surfacecolor=phase_phi if colormap == "Phase" else mag_phi,
1069
+ colorscale=custom_colorscale,
1070
+ opacity=layer_alpha,
1071
+ showscale=(depth_layer == 0), # Only show colorbar for top layer
1072
+ colorbar=dict(title='Holographic Field Intensity', x=1.02),
1073
+ name=f'Field Layer {depth_layer+1}',
1074
+ contours_z=dict(
1075
+ show=True,
1076
+ usecolormap=True,
1077
+ highlightcolor="rgba(255,255,255,0.8)",
1078
+ project_z=True,
1079
+ highlightwidth=2
1080
+ )
1081
+ ))
1082
+
1083
+ # Enhanced data points with size based on magnitude
1084
+ point_sizes = np.abs(phi) * 5 + 2 # Dynamic sizing
1085
+ fig.add_trace(go.Scatter3d(
1086
+ x=np.real(z), y=np.imag(z), z=np.abs(phi) + 0.1,
1087
+ mode='markers',
1088
+ marker=dict(
1089
+ size=point_sizes,
1090
+ color=np.angle(phi),
1091
+ colorscale='rainbow',
1092
+ symbol='diamond',
1093
+ opacity=0.9,
1094
+ line=dict(width=1, color='white')
1095
+ ),
1096
+ name='Signal Constellation',
1097
+ hovertemplate='<b>Signal Point</b><br>Re(z): %{x:.3f}<br>Im(z): %{y:.3f}<br>|ฯ†|: %{z:.3f}<extra></extra>'
1098
+ ))
1099
+
1100
+ # Enhanced vector flow field with adaptive density
1101
+ if resolution >= 40: # Only show for sufficient resolution
1102
+ grad_y, grad_x = np.gradient(mag_phi)
1103
+ sample_rate = max(1, resolution // 20) # Adaptive sampling
1104
+
1105
+ fig.add_trace(go.Cone(
1106
+ x=grid_x[::sample_rate, ::sample_rate].flatten(),
1107
+ y=grid_y[::sample_rate, ::sample_rate].flatten(),
1108
+ z=mag_phi[::sample_rate, ::sample_rate].flatten(),
1109
+ u=-grad_x[::sample_rate, ::sample_rate].flatten(),
1110
+ v=-grad_y[::sample_rate, ::sample_rate].flatten(),
1111
+ w=np.full_like(mag_phi[::sample_rate, ::sample_rate].flatten(), -0.05),
1112
+ sizemode="absolute",
1113
+ sizeref=0.08 * interference_strength,
1114
+ anchor="tip",
1115
+ colorscale='greys',
1116
+ showscale=False,
1117
+ opacity=0.6,
1118
+ name='Field Gradient'
1119
+ ))
1120
+
1121
+ fig.update_layout(
1122
+ title={
1123
+ 'text': f"๐ŸŒŸ {title}<br><sub>Enhanced Holographic Field Reconstruction (ฮป={wavelength}nm)</sub>",
1124
+ 'x': 0.5,
1125
+ 'xanchor': 'center'
1126
+ },
1127
+ scene=dict(
1128
+ xaxis_title="Re(z) - Complex Embedding",
1129
+ yaxis_title="Im(z) - Phase Encoding",
1130
+ zaxis_title="|ฮฆ| - Holographic Intensity",
1131
+ camera=dict(eye=dict(x=1.8, y=1.8, z=1.5)),
1132
+ aspectmode='cube',
1133
+ bgcolor='rgba(5,5,15,1)'
1134
+ ),
1135
+ margin=dict(l=0, r=0, b=0, t=80),
1136
+ paper_bgcolor='rgba(10,10,25,1)',
1137
+ plot_bgcolor='rgba(5,5,15,1)'
1138
+ )
1139
+ return fig
1140
+
1141
+ def create_dual_holography_plot(z1, phi1, z2, phi2, resolution, wavelength, field_depth=5,
1142
+ interference_strength=1.0, view_mode="Side-by-Side", colormap="Wavelength",
1143
+ title1="Primary", title2="Comparison"):
1144
+ """Creates enhanced side-by-side holographic visualizations with multiple view modes."""
1145
+
1146
+ if view_mode == "Side-by-Side":
1147
+ return create_side_by_side_holography(z1, phi1, z2, phi2, resolution, wavelength,
1148
+ field_depth, interference_strength, colormap, title1, title2)
1149
+ elif view_mode == "Overlay":
1150
+ return create_overlay_holography(z1, phi1, z2, phi2, resolution, wavelength,
1151
+ field_depth, interference_strength, colormap, title1, title2)
1152
+ elif view_mode == "Difference":
1153
+ return create_difference_holography(z1, phi1, z2, phi2, resolution, wavelength,
1154
+ field_depth, interference_strength, colormap, title1, title2)
1155
+ else: # Animation
1156
+ return create_animated_holography(z1, phi1, z2, phi2, resolution, wavelength,
1157
+ field_depth, interference_strength, colormap, title1, title2)
1158
+
1159
+ def create_side_by_side_holography(z1, phi1, z2, phi2, resolution, wavelength, field_depth,
1160
+ interference_strength, colormap, title1, title2):
1161
+ """Enhanced side-by-side comparison with mathematical precision."""
1162
  field_data1 = generate_holographic_field(z1, phi1, resolution)
1163
  field_data2 = generate_holographic_field(z2, phi2, resolution)
1164
 
 
1168
  grid_x1, grid_y1, grid_phi1 = field_data1
1169
  grid_x2, grid_y2, grid_phi2 = field_data2
1170
 
1171
+ # Enhanced color mapping
1172
+ def get_enhanced_colorscale(colormap, wavelength):
1173
+ if colormap == "Wavelength":
1174
+ # Sophisticated wavelength-based colors
1175
+ if 380 <= wavelength < 450:
1176
+ return [[0, 'rgb(20,0,60)'], [0.5, 'rgb(120,0,255)'], [1, 'rgb(200,150,255)']]
1177
+ elif 450 <= wavelength < 550:
1178
+ return [[0, 'rgb(0,20,60)'], [0.5, 'rgb(0,120,255)'], [1, 'rgb(150,200,255)']]
1179
+ elif 550 <= wavelength < 650:
1180
+ return [[0, 'rgb(0,60,20)'], [0.5, 'rgb(120,255,0)'], [1, 'rgb(200,255,150)']]
1181
+ else:
1182
+ return [[0, 'rgb(60,20,0)'], [0.5, 'rgb(255,120,0)'], [1, 'rgb(255,200,150)']]
1183
+ elif colormap == "Phase":
1184
+ return 'hsv'
1185
+ elif colormap == "Magnitude":
1186
+ return 'hot'
1187
+ elif colormap == "Interference":
1188
+ return [[0, 'rgb(0,0,100)'], [0.3, 'rgb(0,150,255)'], [0.6, 'rgb(255,255,0)'], [1, 'rgb(255,0,0)']]
1189
+ return 'viridis'
1190
+
1191
+ custom_colorscale = get_enhanced_colorscale(colormap, wavelength)
1192
 
 
 
 
1193
  fig = make_subplots(
1194
  rows=1, cols=2,
1195
  specs=[[{'type': 'scene'}, {'type': 'scene'}]],
1196
+ subplot_titles=[f"๐ŸŽต {title1}", f"๐Ÿ”— {title2}"],
1197
+ horizontal_spacing=0.05
1198
  )
1199
 
1200
+ # Enhanced processing for both fields
1201
+ mag_phi1 = np.abs(grid_phi1) * interference_strength
1202
+ mag_phi2 = np.abs(grid_phi2) * interference_strength
1203
+ phase_phi1 = np.angle(grid_phi1)
1204
+ phase_phi2 = np.angle(grid_phi2)
1205
+
1206
+ # Left plot (Primary) with multiple layers
1207
+ for layer in range(min(field_depth, 3)): # Limit for performance
1208
+ layer_alpha = 1.0 - (layer * 0.2)
1209
+ layer_offset = layer * 0.05
1210
+
1211
+ fig.add_trace(go.Surface(
1212
+ x=grid_x1, y=grid_y1, z=mag_phi1 + layer_offset,
1213
+ surfacecolor=phase_phi1 if colormap == "Phase" else mag_phi1,
1214
+ colorscale=custom_colorscale,
1215
+ opacity=layer_alpha,
1216
+ showscale=False,
1217
+ name=f'{title1} Layer {layer+1}',
1218
+ contours_z=dict(show=True, usecolormap=True, project_z=True)
1219
+ ), row=1, col=1)
1220
 
1221
+ # Right plot (Comparison)
1222
+ for layer in range(min(field_depth, 3)):
1223
+ layer_alpha = 1.0 - (layer * 0.2)
1224
+ layer_offset = layer * 0.05
1225
+
1226
+ fig.add_trace(go.Surface(
1227
+ x=grid_x2, y=grid_y2, z=mag_phi2 + layer_offset,
1228
+ surfacecolor=phase_phi2 if colormap == "Phase" else mag_phi2,
1229
+ colorscale=custom_colorscale,
1230
+ opacity=layer_alpha,
1231
+ showscale=False,
1232
+ name=f'{title2} Layer {layer+1}',
1233
+ contours_z=dict(show=True, usecolormap=True, project_z=True)
1234
+ ), row=1, col=2)
1235
 
1236
+ # Enhanced data points for both sides
1237
  if z1 is not None and phi1 is not None:
1238
+ point_sizes1 = np.abs(phi1) * 3 + 1
1239
  fig.add_trace(go.Scatter3d(
1240
  x=np.real(z1), y=np.imag(z1), z=np.abs(phi1) + 0.05,
1241
+ mode='markers',
1242
+ marker=dict(size=point_sizes1, color=np.angle(phi1), colorscale='rainbow',
1243
+ symbol='diamond', opacity=0.8, line=dict(width=1, color='white')),
1244
+ name=f'{title1} Constellation',
1245
+ showlegend=False,
1246
+ hovertemplate=f'<b>{title1}</b><br>Re(z): %{{x:.3f}}<br>Im(z): %{{y:.3f}}<br>|ฯ†|: %{{z:.3f}}<extra></extra>'
1247
  ), row=1, col=1)
1248
 
1249
  if z2 is not None and phi2 is not None:
1250
+ point_sizes2 = np.abs(phi2) * 3 + 1
1251
  fig.add_trace(go.Scatter3d(
1252
  x=np.real(z2), y=np.imag(z2), z=np.abs(phi2) + 0.05,
1253
+ mode='markers',
1254
+ marker=dict(size=point_sizes2, color=np.angle(phi2), colorscale='rainbow',
1255
+ symbol='diamond', opacity=0.8, line=dict(width=1, color='white')),
1256
+ name=f'{title2} Constellation',
1257
+ showlegend=False,
1258
+ hovertemplate=f'<b>{title2}</b><br>Re(z): %{{x:.3f}}<br>Im(z): %{{y:.3f}}<br>|ฯ†|: %{{z:.3f}}<extra></extra>'
1259
  ), row=1, col=2)
1260
 
1261
+ # Mathematical precision layout
1262
  fig.update_layout(
1263
+ title={
1264
+ 'text': "๐ŸŒŸ Cross-Species Holographic Field Comparison<br><sub>Mathematical precision visualization of interspecies communication geometry</sub>",
1265
+ 'x': 0.5,
1266
+ 'xanchor': 'center'
1267
+ },
1268
  scene=dict(
1269
  xaxis_title="Re(z)", yaxis_title="Im(z)", zaxis_title="|ฮฆ|",
1270
+ camera=dict(eye=dict(x=1.5, y=1.5, z=1.5)),
1271
+ bgcolor='rgba(5,5,15,1)',
1272
+ aspectmode='cube'
1273
  ),
1274
  scene2=dict(
1275
  xaxis_title="Re(z)", yaxis_title="Im(z)", zaxis_title="|ฮฆ|",
1276
+ camera=dict(eye=dict(x=1.5, y=1.5, z=1.5)),
1277
+ bgcolor='rgba(5,5,15,1)',
1278
+ aspectmode='cube'
1279
+ ),
1280
+ margin=dict(l=0, r=0, b=0, t=80),
1281
+ paper_bgcolor='rgba(10,10,25,1)',
1282
+ plot_bgcolor='rgba(5,5,15,1)'
1283
+ )
1284
+ return fig
1285
+
1286
+ def create_overlay_holography(z1, phi1, z2, phi2, resolution, wavelength, field_depth,
1287
+ interference_strength, colormap, title1, title2):
1288
+ """Create overlaid holographic fields showing interference patterns."""
1289
+ field_data1 = generate_holographic_field(z1, phi1, resolution)
1290
+ field_data2 = generate_holographic_field(z2, phi2, resolution)
1291
+
1292
+ if field_data1 is None or field_data2 is None:
1293
+ return go.Figure(layout={"title": "Insufficient data for overlay holography"})
1294
+
1295
+ # Combine the fields for interference analysis
1296
+ grid_x1, grid_y1, grid_phi1 = field_data1
1297
+ grid_x2, grid_y2, grid_phi2 = field_data2
1298
+
1299
+ # Create interference pattern
1300
+ combined_field = grid_phi1 + grid_phi2 * 0.7 # Weighted combination
1301
+ interference_magnitude = np.abs(combined_field) * interference_strength
1302
+ interference_phase = np.angle(combined_field)
1303
+
1304
+ fig = go.Figure()
1305
+
1306
+ # Main interference surface
1307
+ fig.add_trace(go.Surface(
1308
+ x=grid_x1, y=grid_y1, z=interference_magnitude,
1309
+ surfacecolor=interference_phase,
1310
+ colorscale='rainbow',
1311
+ name='Interference Pattern',
1312
+ colorbar=dict(title='Phase Interference'),
1313
+ contours_z=dict(show=True, usecolormap=True, project_z=True)
1314
+ ))
1315
+
1316
+ # Add both signal constellations with different symbols
1317
+ if z1 is not None and phi1 is not None:
1318
+ fig.add_trace(go.Scatter3d(
1319
+ x=np.real(z1), y=np.imag(z1), z=np.abs(phi1) + 0.1,
1320
+ mode='markers',
1321
+ marker=dict(size=6, color='red', symbol='circle', opacity=0.8),
1322
+ name=title1
1323
+ ))
1324
+
1325
+ if z2 is not None and phi2 is not None:
1326
+ fig.add_trace(go.Scatter3d(
1327
+ x=np.real(z2), y=np.imag(z2), z=np.abs(phi2) + 0.1,
1328
+ mode='markers',
1329
+ marker=dict(size=6, color='blue', symbol='square', opacity=0.8),
1330
+ name=title2
1331
+ ))
1332
+
1333
+ fig.update_layout(
1334
+ title=f"๐ŸŒŠ Holographic Interference: {title1} โšก {title2}",
1335
+ scene=dict(
1336
+ xaxis_title="Re(z)", yaxis_title="Im(z)", zaxis_title="Interference |ฮฆ|",
1337
+ bgcolor='rgba(5,5,15,1)'
1338
  ),
1339
  margin=dict(l=0, r=0, b=0, t=60),
1340
+ paper_bgcolor='rgba(10,10,25,1)'
1341
  )
1342
  return fig
1343
 
1344
+ def create_difference_holography(z1, phi1, z2, phi2, resolution, wavelength, field_depth,
1345
+ interference_strength, colormap, title1, title2):
1346
+ """Show the mathematical difference between holographic fields."""
1347
+ field_data1 = generate_holographic_field(z1, phi1, resolution)
1348
+ field_data2 = generate_holographic_field(z2, phi2, resolution)
1349
+
1350
+ if field_data1 is None or field_data2 is None:
1351
+ return go.Figure(layout={"title": "Insufficient data for difference analysis"})
1352
+
1353
+ grid_x1, grid_y1, grid_phi1 = field_data1
1354
+ grid_x2, grid_y2, grid_phi2 = field_data2
1355
+
1356
+ # Calculate difference field
1357
+ difference_field = grid_phi1 - grid_phi2
1358
+ diff_magnitude = np.abs(difference_field)
1359
+ diff_phase = np.angle(difference_field)
1360
+
1361
+ fig = go.Figure()
1362
+
1363
+ # Difference surface
1364
+ fig.add_trace(go.Surface(
1365
+ x=grid_x1, y=grid_y1, z=diff_magnitude,
1366
+ surfacecolor=diff_phase,
1367
+ colorscale='RdBu',
1368
+ name='Field Difference',
1369
+ colorbar=dict(title='Difference Magnitude'),
1370
+ contours_z=dict(show=True, usecolormap=True, project_z=True)
1371
+ ))
1372
+
1373
+ fig.update_layout(
1374
+ title=f"๐Ÿ” Holographic Difference Analysis: {title1} - {title2}",
1375
+ scene=dict(
1376
+ xaxis_title="Re(z)", yaxis_title="Im(z)", zaxis_title="Difference |ฮฆ|",
1377
+ bgcolor='rgba(15,5,5,1)'
1378
+ ),
1379
+ margin=dict(l=0, r=0, b=0, t=60),
1380
+ paper_bgcolor='rgba(25,10,10,1)'
1381
+ )
1382
+ return fig
1383
+
1384
+ def create_animated_holography(z1, phi1, z2, phi2, resolution, wavelength, field_depth,
1385
+ interference_strength, colormap, title1, title2):
1386
+ """Create animated transition between holographic fields."""
1387
+ # For now, return the overlay version with animation notation
1388
+ # Full animation would require Plotly animation frames
1389
+ fig = create_overlay_holography(z1, phi1, z2, phi2, resolution, wavelength,
1390
+ field_depth, interference_strength, colormap, title1, title2)
1391
+
1392
+ fig.update_layout(
1393
+ title=f"๐ŸŽฌ Animated Holographic Transition: {title1} โ†” {title2}<br><sub>Interactive transition between communication states</sub>"
1394
+ )
1395
+ return fig
1396
+
1397
+ def create_enhanced_entropy_plot(phi1, phi2, title1="Primary", title2="Comparison"):
1398
+ """Creates enhanced information entropy geometry analysis."""
1399
+ if phi1 is None or phi2 is None or len(phi1) < 2 or len(phi2) < 2:
1400
+ return go.Figure(layout={"title": "Insufficient data for entropy analysis"})
1401
+
1402
+ # Calculate comprehensive entropy metrics
1403
+ def calculate_entropy_metrics(phi):
1404
+ magnitudes = np.abs(phi)
1405
+ phases = np.angle(phi)
1406
+
1407
+ # Shannon entropy
1408
+ mag_hist, _ = np.histogram(magnitudes, bins=20, density=True)
1409
+ phase_hist, _ = np.histogram(phases, bins=20, density=True)
1410
+ mag_entropy = shannon_entropy(mag_hist + 1e-12) # Avoid log(0)
1411
+ phase_entropy = shannon_entropy(phase_hist + 1e-12)
1412
+
1413
+ # Geometric entropy
1414
+ geometric_entropy = np.std(magnitudes) * np.std(phases)
1415
+
1416
+ # Complexity measures
1417
+ magnitude_complexity = np.var(magnitudes) / (np.mean(magnitudes) + 1e-12)
1418
+ phase_complexity = np.var(phases) / (np.pi**2 / 3) # Normalized by max variance
1419
+
1420
+ return {
1421
+ 'mag_entropy': mag_entropy,
1422
+ 'phase_entropy': phase_entropy,
1423
+ 'geometric_entropy': geometric_entropy,
1424
+ 'magnitude_complexity': magnitude_complexity,
1425
+ 'phase_complexity': phase_complexity,
1426
+ 'total_entropy': mag_entropy + phase_entropy
1427
+ }
1428
+
1429
+ metrics1 = calculate_entropy_metrics(phi1)
1430
+ metrics2 = calculate_entropy_metrics(phi2)
1431
+
1432
+ fig = make_subplots(
1433
+ rows=2, cols=3,
1434
+ subplot_titles=[
1435
+ f'{title1}: Magnitude Distribution', f'{title2}: Magnitude Distribution', 'Entropy Comparison',
1436
+ f'{title1}: Phase Distribution', f'{title2}: Phase Distribution', 'Complexity Analysis'
1437
+ ],
1438
+ specs=[[{'type': 'xy'}, {'type': 'xy'}, {'type': 'xy'}],
1439
+ [{'type': 'xy'}, {'type': 'xy'}, {'type': 'xy'}]]
1440
+ )
1441
+
1442
+ # Magnitude distributions
1443
+ fig.add_trace(go.Histogram(x=np.abs(phi1), nbinsx=30, name=f'{title1} Magnitude',
1444
+ marker_color='rgba(255,100,100,0.7)'), row=1, col=1)
1445
+ fig.add_trace(go.Histogram(x=np.abs(phi2), nbinsx=30, name=f'{title2} Magnitude',
1446
+ marker_color='rgba(100,100,255,0.7)'), row=1, col=2)
1447
+
1448
+ # Phase distributions
1449
+ fig.add_trace(go.Histogram(x=np.angle(phi1), nbinsx=30, name=f'{title1} Phase',
1450
+ marker_color='rgba(255,150,100,0.7)'), row=2, col=1)
1451
+ fig.add_trace(go.Histogram(x=np.angle(phi2), nbinsx=30, name=f'{title2} Phase',
1452
+ marker_color='rgba(100,150,255,0.7)'), row=2, col=2)
1453
+
1454
+ # Entropy comparison
1455
+ entropy_categories = ['Magnitude', 'Phase', 'Geometric', 'Total']
1456
+ entropy_values1 = [metrics1['mag_entropy'], metrics1['phase_entropy'],
1457
+ metrics1['geometric_entropy'], metrics1['total_entropy']]
1458
+ entropy_values2 = [metrics2['mag_entropy'], metrics2['phase_entropy'],
1459
+ metrics2['geometric_entropy'], metrics2['total_entropy']]
1460
+
1461
+ fig.add_trace(go.Bar(x=entropy_categories, y=entropy_values1, name=title1,
1462
+ marker_color='rgba(255,100,100,0.8)'), row=1, col=3)
1463
+ fig.add_trace(go.Bar(x=entropy_categories, y=entropy_values2, name=title2,
1464
+ marker_color='rgba(100,100,255,0.8)'), row=1, col=3)
1465
+
1466
+ # Complexity analysis
1467
+ complexity_categories = ['Magnitude Complexity', 'Phase Complexity']
1468
+ complexity_values1 = [metrics1['magnitude_complexity'], metrics1['phase_complexity']]
1469
+ complexity_values2 = [metrics2['magnitude_complexity'], metrics2['phase_complexity']]
1470
+
1471
+ fig.add_trace(go.Bar(x=complexity_categories, y=complexity_values1, name=f'{title1} Complexity',
1472
+ marker_color='rgba(255,200,100,0.8)', showlegend=False), row=2, col=3)
1473
+ fig.add_trace(go.Bar(x=complexity_categories, y=complexity_values2, name=f'{title2} Complexity',
1474
+ marker_color='rgba(100,200,255,0.8)', showlegend=False), row=2, col=3)
1475
+
1476
+ fig.update_layout(
1477
+ title="๐Ÿ“Š Enhanced Information Entropy Geometry Analysis",
1478
+ height=600,
1479
+ showlegend=True,
1480
+ paper_bgcolor='rgba(10,10,25,1)',
1481
+ plot_bgcolor='rgba(5,5,15,1)'
1482
+ )
1483
+
1484
+ return fig
1485
+
1486
+ def create_enhanced_phase_analysis(phi1, phi2, z1, z2, title1="Primary", title2="Comparison"):
1487
+ """Creates comprehensive phase space analysis."""
1488
+ if phi1 is None or phi2 is None:
1489
+ return go.Figure(layout={"title": "Insufficient data for phase analysis"})
1490
+
1491
+ fig = make_subplots(
1492
+ rows=2, cols=2,
1493
+ subplot_titles=[
1494
+ 'Complex Plane Trajectories', 'Phase Evolution',
1495
+ 'Magnitude vs Phase', 'Cross-Correlation Analysis'
1496
+ ],
1497
+ specs=[[{'type': 'xy'}, {'type': 'xy'}],
1498
+ [{'type': 'xy'}, {'type': 'xy'}]]
1499
+ )
1500
+
1501
+ # Complex plane trajectories
1502
+ fig.add_trace(go.Scatter(x=np.real(phi1), y=np.imag(phi1), mode='lines+markers',
1503
+ name=f'{title1} Trajectory', line=dict(color='red', width=2),
1504
+ marker=dict(size=4)), row=1, col=1)
1505
+ fig.add_trace(go.Scatter(x=np.real(phi2), y=np.imag(phi2), mode='lines+markers',
1506
+ name=f'{title2} Trajectory', line=dict(color='blue', width=2),
1507
+ marker=dict(size=4)), row=1, col=1)
1508
+
1509
+ # Phase evolution
1510
+ phases1 = np.angle(phi1)
1511
+ phases2 = np.angle(phi2)
1512
+ t1 = np.arange(len(phases1))
1513
+ t2 = np.arange(len(phases2))
1514
+
1515
+ fig.add_trace(go.Scatter(x=t1, y=phases1, mode='lines', name=f'{title1} Phase',
1516
+ line=dict(color='red', width=2)), row=1, col=2)
1517
+ fig.add_trace(go.Scatter(x=t2, y=phases2, mode='lines', name=f'{title2} Phase',
1518
+ line=dict(color='blue', width=2)), row=1, col=2)
1519
+
1520
+ # Magnitude vs Phase scatter
1521
+ fig.add_trace(go.Scatter(x=np.abs(phi1), y=phases1, mode='markers',
1522
+ name=f'{title1} Mag-Phase', marker=dict(color='red', size=6, opacity=0.7)), row=2, col=1)
1523
+ fig.add_trace(go.Scatter(x=np.abs(phi2), y=phases2, mode='markers',
1524
+ name=f'{title2} Mag-Phase', marker=dict(color='blue', size=6, opacity=0.7)), row=2, col=1)
1525
+
1526
+ # Cross-correlation analysis
1527
+ if len(phi1) == len(phi2):
1528
+ correlation = np.correlate(np.abs(phi1), np.abs(phi2), mode='full')
1529
+ lags = np.arange(-len(phi2)+1, len(phi1))
1530
+ fig.add_trace(go.Scatter(x=lags, y=correlation, mode='lines',
1531
+ name='Cross-Correlation', line=dict(color='green', width=2)), row=2, col=2)
1532
+
1533
+ fig.update_layout(
1534
+ title="๐ŸŒ€ Enhanced Phase Space Analysis",
1535
+ height=600,
1536
+ paper_bgcolor='rgba(10,10,25,1)',
1537
+ plot_bgcolor='rgba(5,5,15,1)'
1538
+ )
1539
+
1540
+ return fig
1541
+
1542
  def create_dual_diagnostic_plots(z1, w1, z2, w2, title1="Primary", title2="Comparison"):
1543
  """Creates side-by-side diagnostic plots for cross-species comparison."""
1544
  fig = make_subplots(
 
1824
  outputs=manifold_outputs
1825
  )
1826
 
1827
+ with gr.TabItem("๐Ÿ”ฌ Interactive Holography Laboratory"):
1828
+ gr.Markdown("""
1829
+ # ๐ŸŒŸ **CMT Holographic Information Geometry Engine**
1830
+ *Transform audio signals into mathematical holographic fields revealing hidden geometric structures*
1831
+
1832
+ Based on the **Holographic Information Geometry** framework - each vocalization becomes a complex holographic field showing:
1833
+ - **Geometric Embedding**: 1D signals mapped to complex plane constellations
1834
+ - **Mathematical Illumination**: Lens functions (ฮ“, ฮถ, Ai, Jโ‚€) probe latent structures
1835
+ - **Holographic Superposition**: Phase/magnitude interference creates information geometry
1836
+ - **Field Reconstruction**: Continuous holographic visualization of discrete transformations
1837
+ """)
1838
+
1839
  with gr.Row():
1840
  with gr.Column(scale=1):
1841
+ # Advanced Species Selection with Smart Pairing
1842
+ with gr.Accordion("๐ŸŽฏ **Cross-Species Communication Mapping**", open=True):
1843
+ gr.Markdown("*Automatically finds geometric neighbors across species for grammar analysis*")
1844
+
1845
+ species_dropdown = gr.Dropdown(
1846
+ label="๐Ÿงฌ Primary Species",
1847
+ choices=["Dog", "Human"],
1848
+ value="Dog",
1849
+ info="Select primary species for holographic analysis"
1850
+ )
1851
+
1852
+ # Primary file selection with enhanced info
1853
+ dog_files = df_combined[df_combined["source"] == "Dog"]["filepath"].astype(str).tolist()
1854
+ human_files = df_combined[df_combined["source"] == "Human"]["filepath"].astype(str).tolist()
1855
+
1856
+ primary_dropdown = gr.Dropdown(
1857
+ label="๐ŸŽต Primary Vocalization",
1858
+ choices=dog_files,
1859
+ value=dog_files[0] if dog_files else None,
1860
+ info="Select the primary audio for holographic transformation"
1861
+ )
1862
+
1863
+ neighbor_dropdown = gr.Dropdown(
1864
+ label="๐Ÿ”— Cross-Species Geometric Neighbor",
1865
+ choices=human_files,
1866
+ value=human_files[0] if human_files else None,
1867
+ interactive=True,
1868
+ info="Auto-detected or manually select geometric neighbor"
1869
+ )
1870
+
1871
+ # Similarity metrics display
1872
+ similarity_info = gr.HTML(
1873
+ label="๐Ÿงฎ Geometric Similarity Analysis",
1874
+ value="<i>Select vocalizations to see geometric similarity metrics</i>"
1875
+ )
1876
 
1877
+ # Mathematical Lens Configuration
1878
+ with gr.Accordion("๐Ÿ”ฌ **Mathematical Lens Configuration**", open=True):
1879
+ gr.Markdown("*Configure the mathematical illumination functions*")
1880
+
1881
+ holo_lens_dropdown = gr.Dropdown(
1882
+ label="๐Ÿ“ Mathematical Lens Function",
1883
+ choices=["gamma", "zeta", "airy", "bessel"],
1884
+ value="gamma",
1885
+ info="ฮ“(z): Recursion | ฮถ(z): Primes | Ai(z): Oscillation | Jโ‚€(z): Waves"
1886
+ )
1887
+
1888
+ # Advanced holographic parameters
1889
+ with gr.Row():
1890
+ holo_resolution_slider = gr.Slider(
1891
+ label="๐ŸŽ›๏ธ Field Resolution",
1892
+ minimum=20, maximum=150, step=5, value=60,
1893
+ info="Higher = more detail, slower processing"
1894
+ )
1895
+
1896
+ field_depth_slider = gr.Slider(
1897
+ label="๐Ÿ“ Field Depth",
1898
+ minimum=1, maximum=10, step=1, value=5,
1899
+ info="Z-axis interpolation layers"
1900
+ )
1901
+
1902
+ with gr.Row():
1903
+ holo_wavelength_slider = gr.Slider(
1904
+ label="๐ŸŒˆ Illumination Wavelength (nm)",
1905
+ minimum=380, maximum=750, step=5, value=550,
1906
+ info="380nm=Violet, 550nm=Green, 750nm=Red"
1907
+ )
1908
+
1909
+ interference_strength = gr.Slider(
1910
+ label="โšก Interference Strength",
1911
+ minimum=0.1, maximum=2.0, step=0.1, value=1.0,
1912
+ info="Holographic interference amplitude"
1913
+ )
1914
+
1915
+ # Advanced encoding parameters
1916
+ with gr.Accordion("โš™๏ธ **Advanced Encoding Parameters**", open=False):
1917
+ encoding_mode = gr.Dropdown(
1918
+ label="๐Ÿ”„ Encoding Mode",
1919
+ choices=["Standard", "Multi-View", "Frequency-Locked", "Phase-Coherent"],
1920
+ value="Multi-View",
1921
+ info="Different geometric embedding strategies"
1922
+ )
1923
+
1924
+ with gr.Row():
1925
+ phase_modulation = gr.Slider(
1926
+ label="๐ŸŒ€ Phase Modulation",
1927
+ minimum=0.0, maximum=2.0, step=0.1, value=1.0,
1928
+ info="Controls structured phase encoding intensity"
1929
+ )
1930
+
1931
+ magnitude_scaling = gr.Slider(
1932
+ label="๐Ÿ“Š Magnitude Scaling",
1933
+ minimum=0.1, maximum=3.0, step=0.1, value=1.0,
1934
+ info="Amplifies signal magnitude in complex plane"
1935
+ )
1936
 
1937
+ # Real-time Analysis Controls
1938
+ with gr.Accordion("โšก **Real-Time Analysis Engine**", open=False):
1939
+ gr.Markdown("*Live mathematical analysis and pattern detection*")
1940
+
1941
+ with gr.Row():
1942
+ auto_detect_patterns = gr.Checkbox(
1943
+ label="๐Ÿ” Auto-Detect Patterns",
1944
+ value=True,
1945
+ info="Automatically identify geometric structures"
1946
+ )
1947
+
1948
+ live_updates = gr.Checkbox(
1949
+ label="๐Ÿ“ก Live Updates",
1950
+ value=False,
1951
+ info="Real-time holographic field updates"
1952
+ )
1953
+
1954
+ analysis_depth = gr.Slider(
1955
+ label="๐Ÿงฌ Analysis Depth",
1956
+ minimum=1, maximum=5, step=1, value=3,
1957
+ info="1=Basic | 3=Standard | 5=Deep Mathematical Analysis"
1958
+ )
1959
+
1960
+ # Pattern detection sensitivity
1961
+ pattern_sensitivity = gr.Slider(
1962
+ label="๐ŸŽฏ Pattern Sensitivity",
1963
+ minimum=0.1, maximum=1.0, step=0.05, value=0.5,
1964
+ info="Threshold for detecting geometric patterns"
1965
+ )
1966
 
1967
+ # Information Analysis Panels
1968
+ with gr.Accordion("๐Ÿ“Š **Vocalization Analysis**", open=True):
1969
+ primary_info_html = gr.HTML(
1970
+ label="๐ŸŽต Primary Vocalization Analysis",
1971
+ value="<i>Select a primary vocalization to see detailed CMT analysis</i>"
1972
+ )
1973
+
1974
+ neighbor_info_html = gr.HTML(
1975
+ label="๐Ÿ”— Neighbor Vocalization Analysis",
1976
+ value="<i>Cross-species neighbor will be automatically detected</i>"
1977
+ )
1978
 
1979
+ # Audio Players with Enhanced Controls
1980
+ with gr.Accordion("๐Ÿ”Š **Audio Playback & Analysis**", open=False):
1981
+ with gr.Row():
1982
+ primary_audio_out = gr.Audio(
1983
+ label="๐ŸŽต Primary Audio",
1984
+ show_download_button=True
1985
+ )
1986
+
1987
+ neighbor_audio_out = gr.Audio(
1988
+ label="๐Ÿ”— Neighbor Audio",
1989
+ show_download_button=True
1990
+ )
1991
+
1992
+ # Audio analysis metrics
1993
+ audio_metrics_html = gr.HTML(
1994
+ label="๐Ÿ“ˆ Audio Signal Metrics",
1995
+ value="<i>Play audio files to see signal analysis</i>"
1996
+ )
1997
+
1998
+ # Main Visualization Panel
1999
+ with gr.Column(scale=3):
2000
+ # Enhanced Holographic Visualization
2001
+ with gr.Accordion("๐ŸŒŒ **Holographic Field Visualization**", open=True):
2002
+ dual_holography_plot = gr.Plot(
2003
+ label="๐Ÿ”ฌ Side-by-Side Holographic Field Reconstruction"
2004
+ )
2005
+
2006
+ # Advanced visualization controls
2007
+ with gr.Row():
2008
+ view_mode = gr.Dropdown(
2009
+ label="๐Ÿ‘๏ธ Visualization Mode",
2010
+ choices=["Side-by-Side", "Overlay", "Difference", "Animation"],
2011
+ value="Side-by-Side",
2012
+ info="Different ways to compare holographic fields"
2013
+ )
2014
+
2015
+ colormap_selection = gr.Dropdown(
2016
+ label="๐ŸŽจ Color Mapping",
2017
+ choices=["Wavelength", "Phase", "Magnitude", "Interference", "Custom"],
2018
+ value="Wavelength",
2019
+ info="Color encoding for holographic visualization"
2020
+ )
2021
 
2022
+ # Diagnostic and Analysis Plots
2023
+ with gr.Accordion("๐Ÿ” **Mathematical Diagnostics**", open=True):
2024
+ dual_diagnostic_plot = gr.Plot(
2025
+ label="๐Ÿ“Š Cross-Species Mathematical Diagnostics"
2026
+ )
2027
+
2028
+ # Additional analysis plots
2029
+ with gr.Row():
2030
+ entropy_plot = gr.Plot(
2031
+ label="๐Ÿ“ˆ Information Entropy Geometry"
2032
+ )
2033
+
2034
+ phase_plot = gr.Plot(
2035
+ label="๐ŸŒ€ Phase Space Analysis"
2036
+ )
2037
 
2038
+ # Mathematical Insights Panel
2039
+ with gr.Accordion("๐Ÿงฎ **Mathematical Insights & Metrics**", open=True):
2040
+ with gr.Row():
2041
+ with gr.Column():
2042
+ mathematical_metrics = gr.HTML(
2043
+ label="๐Ÿ“ Geometric Properties",
2044
+ value="<i>Mathematical analysis will appear here</i>"
2045
+ )
2046
+
2047
+ with gr.Column():
2048
+ pattern_analysis = gr.HTML(
2049
+ label="๐Ÿ” Pattern Recognition",
2050
+ value="<i>Detected patterns and structures</i>"
2051
+ )
2052
+
2053
+ with gr.Column():
2054
+ cross_species_insights = gr.HTML(
2055
+ label="๐ŸŒ‰ Cross-Species Insights",
2056
+ value="<i>Grammar mapping and communication bridges</i>"
2057
+ )
2058
 
2059
+ # Export and Analysis Tools
2060
+ with gr.Accordion("๐Ÿ’พ **Export & Advanced Analysis**", open=False):
2061
+ with gr.Row():
2062
+ export_hologram = gr.Button("๐Ÿ’พ Export Holographic Data", variant="secondary")
2063
+ export_analysis = gr.Button("๐Ÿ“Š Export Mathematical Analysis", variant="secondary")
2064
+ generate_report = gr.Button("๐Ÿ“ Generate Full Report", variant="primary")
2065
+
2066
+ export_status = gr.HTML(
2067
+ label="๐Ÿ“‹ Export Status",
2068
+ value="<i>Ready to export holographic analysis data</i>"
2069
+ )
2070
 
2071
  def update_file_choices(species):
2072
  """Update the primary file dropdown based on selected species."""
2073
  species_files = df_combined[df_combined["source"] == species]["filepath"].astype(str).tolist()
2074
  return species_files
2075
 
2076
+ def update_enhanced_cross_species_view(species, primary_file, neighbor_file, lens, resolution,
2077
+ field_depth, wavelength, interference_strength, encoding_mode,
2078
+ phase_modulation, magnitude_scaling, auto_detect_patterns,
2079
+ live_updates, analysis_depth, pattern_sensitivity,
2080
+ view_mode, colormap_selection):
2081
  if not primary_file:
2082
  empty_fig = go.Figure(layout={"title": "Please select a primary file."})
2083
  return empty_fig, empty_fig, "", "", None, None
 
2124
  primary_fp = resolve_audio_path(primary_row)
2125
  neighbor_fp = resolve_audio_path(neighbor_row) if neighbor_row is not None else None
2126
 
2127
+ # Create enhanced visualizations with new parameters
2128
  if primary_cmt and neighbor_cmt:
2129
  primary_title = f"{species}: {primary_row.get('label', 'Unknown')}"
2130
  neighbor_title = f"{neighbor_row['source']}: {neighbor_row.get('label', 'Unknown')}"
2131
 
2132
+ # Enhanced holographic visualization with multiple view modes
2133
  dual_holo_fig = create_dual_holography_plot(
2134
  primary_cmt["z"], primary_cmt["phi"],
2135
  neighbor_cmt["z"], neighbor_cmt["phi"],
2136
+ resolution, wavelength, field_depth,
2137
+ interference_strength, view_mode, colormap_selection,
2138
+ primary_title, neighbor_title
2139
  )
2140
 
2141
+ # Enhanced diagnostic plots
2142
  dual_diag_fig = create_dual_diagnostic_plots(
2143
  primary_cmt["z"], primary_cmt["w"],
2144
  neighbor_cmt["z"], neighbor_cmt["w"],
2145
  primary_title, neighbor_title
2146
  )
2147
+
2148
+ # New enhanced analysis plots
2149
+ entropy_fig = create_enhanced_entropy_plot(
2150
+ primary_cmt["phi"], neighbor_cmt["phi"],
2151
+ primary_title, neighbor_title
2152
+ )
2153
+
2154
+ phase_fig = create_enhanced_phase_analysis(
2155
+ primary_cmt["phi"], neighbor_cmt["phi"],
2156
+ primary_cmt["z"], neighbor_cmt["z"],
2157
+ primary_title, neighbor_title
2158
+ )
2159
+
2160
  else:
2161
  dual_holo_fig = go.Figure(layout={"title": "Error processing audio files"})
2162
  dual_diag_fig = go.Figure(layout={"title": "Error processing audio files"})
2163
+ entropy_fig = go.Figure(layout={"title": "Error processing audio files"})
2164
+ phase_fig = go.Figure(layout={"title": "Error processing audio files"})
2165
 
2166
  # Build info strings with CMT diagnostic values
2167
  primary_info = f"""
 
2192
  primary_audio = primary_fp if primary_fp and os.path.exists(primary_fp) else None
2193
  neighbor_audio = neighbor_fp if neighbor_row is not None and neighbor_fp and os.path.exists(neighbor_fp) else None
2194
 
2195
+ # Calculate mathematical insights and similarity metrics
2196
+ if primary_cmt and neighbor_cmt:
2197
+ # Geometric similarity calculation
2198
+ primary_centroid = np.mean(primary_cmt["phi"])
2199
+ neighbor_centroid = np.mean(neighbor_cmt["phi"])
2200
+ geometric_distance = np.abs(primary_centroid - neighbor_centroid)
2201
+
2202
+ # Pattern coherence analysis
2203
+ primary_coherence = np.std(np.abs(primary_cmt["phi"])) / (np.mean(np.abs(primary_cmt["phi"])) + 1e-12)
2204
+ neighbor_coherence = np.std(np.abs(neighbor_cmt["phi"])) / (np.mean(np.abs(neighbor_cmt["phi"])) + 1e-12)
2205
+ coherence_similarity = 1.0 / (1.0 + abs(primary_coherence - neighbor_coherence))
2206
+
2207
+ # Cross-species communication bridge analysis
2208
+ phase_correlation = np.corrcoef(np.angle(primary_cmt["phi"]), np.angle(neighbor_cmt["phi"]))[0,1]
2209
+ if np.isnan(phase_correlation):
2210
+ phase_correlation = 0.0
2211
+
2212
+ bridge_strength = (coherence_similarity + abs(phase_correlation)) / 2.0
2213
+
2214
+ # Enhanced similarity info
2215
+ similarity_details = f"""
2216
+ <h4>๐Ÿงฎ <b>Geometric Similarity Metrics</b></h4>
2217
+ <div style="background: rgba(20,20,40,0.8); padding: 10px; border-radius: 8px; margin: 5px 0;">
2218
+ <p><b>๐ŸŽฏ Geometric Distance:</b> {geometric_distance:.4f}</p>
2219
+ <p><b>๐Ÿ“Š Coherence Similarity:</b> {coherence_similarity:.4f}</p>
2220
+ <p><b>๐ŸŒŠ Phase Correlation:</b> {phase_correlation:.4f}</p>
2221
+ <p><b>๐ŸŒ‰ Communication Bridge:</b> {bridge_strength:.4f}</p>
2222
+ <p><b>๐Ÿ“ˆ Pattern Match:</b> {(1.0 - geometric_distance) * 100:.1f}%</p>
2223
+ </div>
2224
+ """
2225
+
2226
+ # Mathematical insights
2227
+ math_insights = f"""
2228
+ <h4>๐Ÿ“ <b>Mathematical Properties</b></h4>
2229
+ <div style="background: rgba(40,20,20,0.8); padding: 10px; border-radius: 8px; margin: 5px 0;">
2230
+ <p><b>๐ŸŽต {primary_title}:</b></p>
2231
+ <p>โ€ข Field Complexity: {primary_cmt['alpha']:.4f}</p>
2232
+ <p>โ€ข SRL Resonance: {primary_cmt['srl']:.4f}</p>
2233
+ <p>โ€ข Coherence Index: {primary_coherence:.4f}</p>
2234
+ <br>
2235
+ <p><b>๐Ÿ”— {neighbor_title}:</b></p>
2236
+ <p>โ€ข Field Complexity: {neighbor_cmt['alpha']:.4f}</p>
2237
+ <p>โ€ข SRL Resonance: {neighbor_cmt['srl']:.4f}</p>
2238
+ <p>โ€ข Coherence Index: {neighbor_coherence:.4f}</p>
2239
+ </div>
2240
+ """
2241
+
2242
+ # Cross-species insights based on mathematical analysis
2243
+ if bridge_strength > 0.7:
2244
+ bridge_quality = "๐ŸŸข <b>Strong Communication Bridge</b>"
2245
+ bridge_description = "High geometric similarity suggests potential shared communication patterns."
2246
+ elif bridge_strength > 0.4:
2247
+ bridge_quality = "๐ŸŸก <b>Moderate Communication Bridge</b>"
2248
+ bridge_description = "Some shared mathematical structures detected."
2249
+ else:
2250
+ bridge_quality = "๐Ÿ”ด <b>Weak Communication Bridge</b>"
2251
+ bridge_description = "Limited mathematical correspondence between vocalizations."
2252
+
2253
+ cross_species_analysis = f"""
2254
+ <h4>๐ŸŒ‰ <b>Cross-Species Grammar Mapping</b></h4>
2255
+ <div style="background: rgba(20,40,20,0.8); padding: 10px; border-radius: 8px; margin: 5px 0;">
2256
+ <p>{bridge_quality}</p>
2257
+ <p>{bridge_description}</p>
2258
+ <br>
2259
+ <p><b>๐Ÿ” Pattern Analysis:</b></p>
2260
+ <p>โ€ข Encoding Mode: {encoding_mode}</p>
2261
+ <p>โ€ข Analysis Depth: Level {analysis_depth}</p>
2262
+ <p>โ€ข Detection Sensitivity: {pattern_sensitivity:.2f}</p>
2263
+ {"<p>โ€ข ๐Ÿ”ด <b>Patterns Detected!</b></p>" if auto_detect_patterns and bridge_strength > pattern_sensitivity else ""}
2264
+ </div>
2265
+ """
2266
+
2267
+ # Audio metrics
2268
+ audio_analysis = f"""
2269
+ <h4>๐Ÿ“ˆ <b>Signal Analysis</b></h4>
2270
+ <div style="background: rgba(40,40,20,0.8); padding: 10px; border-radius: 8px; margin: 5px 0;">
2271
+ <p><b>๐ŸŽต Primary Signal:</b> {len(primary_cmt['phi'])} samples</p>
2272
+ <p><b>๐Ÿ”— Neighbor Signal:</b> {len(neighbor_cmt['phi'])} samples</p>
2273
+ <p><b>๐Ÿ“ Lens Function:</b> {lens.upper()} (Mathematical Illumination)</p>
2274
+ <p><b>๐ŸŒˆ Wavelength:</b> {wavelength}nm</p>
2275
+ <p><b>โšก Interference:</b> {interference_strength:.1f}x</p>
2276
+ <p><b>๐Ÿ“ Field Depth:</b> {field_depth} layers</p>
2277
+ </div>
2278
+ """
2279
+ else:
2280
+ similarity_details = "<i>Select vocalizations to see similarity analysis</i>"
2281
+ math_insights = "<i>Mathematical analysis will appear here</i>"
2282
+ cross_species_analysis = "<i>Cross-species insights will appear here</i>"
2283
+ audio_analysis = "<i>Audio signal analysis will appear here</i>"
2284
+
2285
+ return (dual_holo_fig, dual_diag_fig, entropy_fig, phase_fig,
2286
+ primary_info, neighbor_info, similarity_details,
2287
+ math_insights, cross_species_analysis, audio_analysis,
2288
  primary_audio, neighbor_audio)
2289
 
2290
  # Event handlers
 
2308
  outputs=[primary_dropdown, neighbor_dropdown]
2309
  )
2310
 
2311
+ # Enhanced input/output configuration with all new parameters
2312
+ enhanced_inputs = [
2313
+ species_dropdown, primary_dropdown, neighbor_dropdown,
2314
+ holo_lens_dropdown, holo_resolution_slider, field_depth_slider,
2315
+ holo_wavelength_slider, interference_strength, encoding_mode,
2316
+ phase_modulation, magnitude_scaling, auto_detect_patterns,
2317
+ live_updates, analysis_depth, pattern_sensitivity,
2318
+ view_mode, colormap_selection
2319
+ ]
2320
+
2321
+ enhanced_outputs = [
2322
+ dual_holography_plot, dual_diagnostic_plot, entropy_plot, phase_plot,
2323
+ primary_info_html, neighbor_info_html, similarity_info,
2324
+ mathematical_metrics, pattern_analysis, cross_species_insights,
2325
+ audio_metrics_html, primary_audio_out, neighbor_audio_out
2326
+ ]
2327
+
2328
+ # Bind all enhanced controls to the new update function
2329
+ for component in enhanced_inputs[2:]: # Skip species and primary (handled separately)
2330
+ component.change(
2331
+ update_enhanced_cross_species_view,
2332
+ inputs=enhanced_inputs,
2333
+ outputs=enhanced_outputs
2334
+ )
2335
 
2336
  if __name__ == "__main__":
2337
  demo.launch(share=True, debug=True)