Interactive Posts with Marimo
DarkPost supports interactive Python content through Marimo integration, allowing you to create dynamic, executable content that enhances reader engagement. This guide covers everything from basic code snippets to complex interactive visualizations.
π Why Include Python Code?
Benefits for Readers
- Reproducible research: Others can run and verify your results
- Interactive learning: Readers can modify parameters and see immediate results
- Practical application: Demonstrate real-world implementation of methods
- Educational value: Step-by-step code explanations
Benefits for Authors
- Credibility: Show your work transparently
- Collaboration: Enable others to build upon your methods
- Documentation: Code serves as detailed methodology notes
- Impact: Interactive content gets more engagement
π οΈ Setting Up Python Integration
Marimo Integration
DarkPost uses Marimo for interactive Python content. Marimo cells allow readers to: - Modify input parameters - See real-time updates - Explore different scenarios - Download results
Basic Syntax
Use the {marimo} tag in your code blocks:
```python {marimo}
import marimo as mo
import numpy as np
# Create an interactive slider
redshift_max = mo.ui.slider(0.1, 2.0, 0.1, label="Maximum redshift")
redshift_max
```
π Common Use Cases
1. Parameter Exploration
Create interactive widgets for exploring parameter spaces:
```python {marimo}
import marimo as mo
import numpy as np
import matplotlib.pyplot as plt
# Interactive cosmological parameters
h = mo.ui.slider(0.6, 0.8, 0.01, value=0.7, label="Hβ (Γ100 km/s/Mpc)")
omega_m = mo.ui.slider(0.1, 0.5, 0.01, value=0.3, label="Ξ©β")
omega_lambda = mo.ui.slider(0.5, 0.9, 0.01, value=0.7, label="Ξ©β")
mo.hstack([h, omega_m, omega_lambda])
```
```python {marimo}
# Calculate and plot Hubble parameter
z = np.linspace(0, 2, 100)
H_z = h.value * 100 * np.sqrt(omega_m.value * (1+z)**3 + omega_lambda.value)
plt.figure(figsize=(8, 6))
plt.plot(z, H_z, 'b-', linewidth=2, label=f'Hβ={h.value*100:.0f}, Ξ©β={omega_m.value:.2f}')
plt.xlabel('Redshift z')
plt.ylabel('H(z) [km/s/Mpc]')
plt.title('Hubble Parameter Evolution')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
```
2. Data Visualization
Interactive plots that respond to user input:
```python {marimo}
import marimo as mo
import numpy as np
import matplotlib.pyplot as plt
# Data selection widget
survey = mo.ui.dropdown(
["DESI", "Planck", "SN1a", "Combined"],
label="Select dataset"
)
parameter = mo.ui.dropdown(
["wβ", "wβ", "Hβ", "Ξ©β"],
label="Parameter"
)
mo.hstack([survey, parameter])
```
```python {marimo}
# Generate mock constraints based on selection
np.random.seed(42)
constraints = {
"DESI": {"wβ": (-1.05, 0.08), "wβ": (0.2, 0.3), "Hβ": (68.5, 1.2), "Ξ©β": (0.31, 0.02)},
"Planck": {"wβ": (-1.00, 0.15), "wβ": (0.0, 0.5), "Hβ": (67.4, 0.5), "Ξ©β": (0.315, 0.008)},
"SN1a": {"wβ": (-0.98, 0.12), "wβ": (-0.1, 0.4), "Hβ": (73.2, 1.3), "Ξ©β": (0.30, 0.05)},
}
if survey.value in constraints:
mean, std = constraints[survey.value][parameter.value]
x = np.linspace(mean - 3*std, mean + 3*std, 1000)
y = np.exp(-0.5 * ((x - mean) / std)**2) / (std * np.sqrt(2 * np.pi))
plt.figure(figsize=(8, 5))
plt.fill_between(x, y, alpha=0.6, label=f'{survey.value} constraint')
plt.axvline(mean, color='red', linestyle='--', label=f'Best fit: {mean:.3f}')
plt.xlabel(parameter.value)
plt.ylabel('Probability density')
plt.title(f'{parameter.value} constraints from {survey.value}')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
mo.md(f"**{survey.value} result**: {parameter.value} = {mean:.3f} Β± {std:.3f}")
```
3. Scientific Calculations
Step-by-step calculations with explanatory text:
```python {marimo}
import marimo as mo
import numpy as np
# Input parameters
mo.md("""
## Chi-square Analysis
Let's calculate the goodness of fit for different cosmological models.
""")
observed_h0 = mo.ui.number(70, 60, 80, label="Observed Hβ")
observed_error = mo.ui.number(2, 0.5, 5, label="Uncertainty Ο")
mo.hstack([observed_h0, observed_error])
```
```python {marimo}
# Theoretical predictions from different models
models = {
"ΞCDM": 67.4,
"wCDM": 68.1,
"Early Dark Energy": 71.2
}
mo.md("### Model Comparison")
results = []
for model, predicted_h0 in models.items():
chi2 = ((observed_h0.value - predicted_h0) / observed_error.value)**2
results.append({
"Model": model,
"Predicted Hβ": f"{predicted_h0:.1f}",
"ΟΒ²": f"{chi2:.2f}",
"ΞΟΒ²": f"{chi2 - min([((observed_h0.value - h) / observed_error.value)**2 for h in models.values()]):.2f}"
})
mo.ui.table(results)
```
π§ Advanced Features
Custom Functions and Classes
Define reusable code components:
```python {marimo}
import marimo as mo
import numpy as np
class CosmologyCalculator:
def __init__(self, h0, omega_m, omega_lambda):
self.h0 = h0
self.omega_m = omega_m
self.omega_lambda = omega_lambda
def luminosity_distance(self, z):
"""Calculate luminosity distance in Mpc"""
c = 299792.458 # km/s
# Simplified calculation for demonstration
return c * z / self.h0 * (1 + z/2)
def distance_modulus(self, z):
"""Calculate distance modulus"""
dl = self.luminosity_distance(z)
return 5 * np.log10(dl) + 25
# Create calculator instance
calc = CosmologyCalculator(70, 0.3, 0.7)
mo.md("CosmologyCalculator class defined successfully!")
```
```python {marimo}
# Use the calculator
redshift_input = mo.ui.slider(0.01, 2.0, 0.01, value=0.5, label="Redshift")
redshift_input
```
```python {marimo}
z = redshift_input.value
dl = calc.luminosity_distance(z)
mu = calc.distance_modulus(z)
mo.md(f"""
**Results for z = {z:.2f}:**
- Luminosity distance: {dl:.1f} Mpc
- Distance modulus: {mu:.2f} mag
""")
```
Data Import and Processing
Show how to work with real datasets:
```python {marimo}
import marimo as mo
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Simulate loading data (in practice, you'd load from files)
mo.md("### Simulated Supernova Data")
np.random.seed(42)
n_sn = 50
z_data = np.random.exponential(0.3, n_sn)
z_data = z_data[z_data < 1.5] # Limit redshift range
# Simulate distance modulus with scatter
true_mu = 5 * np.log10(3000 * z_data / 70) + 25 + 2.5 * z_data
observed_mu = true_mu + np.random.normal(0, 0.2, len(z_data))
# Create DataFrame
sn_data = pd.DataFrame({
'redshift': z_data,
'distance_modulus': observed_mu,
'error': np.random.uniform(0.1, 0.3, len(z_data))
})
mo.ui.table(sn_data.head(10))
```
```python {marimo}
# Interactive analysis
h0_fit = mo.ui.slider(60, 80, 1, value=70, label="Hβ for model comparison")
h0_fit
```
```python {marimo}
# Plot data and model
z_model = np.linspace(0.01, 1.5, 100)
mu_model = 5 * np.log10(3000 * z_model / h0_fit.value) + 25 + 2.5 * z_model
plt.figure(figsize=(10, 6))
plt.errorbar(sn_data['redshift'], sn_data['distance_modulus'],
yerr=sn_data['error'], fmt='o', alpha=0.7, label='Simulated SN Data')
plt.plot(z_model, mu_model, 'r-', linewidth=2, label=f'Model (Hβ={h0_fit.value})')
plt.xlabel('Redshift')
plt.ylabel('Distance Modulus')
plt.title('Hubble Diagram')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
# Calculate chi-square
chi2 = np.sum(((sn_data['distance_modulus'] -
(5 * np.log10(3000 * sn_data['redshift'] / h0_fit.value) + 25 + 2.5 * sn_data['redshift'])) /
sn_data['error'])**2)
mo.md(f"**ΟΒ² = {chi2:.1f}** for {len(sn_data)} data points (reduced ΟΒ² = {chi2/(len(sn_data)-1):.2f})")
```
π Best Practices
Code Organization
- Start simple: Begin with basic examples, build complexity gradually
- Use descriptive variable names:
hubble_constantinstead ofh - Add comments: Explain physics and methodology
- Break into logical cells: Each cell should have a clear purpose
User Experience
- Provide context: Explain what each widget controls
- Set reasonable defaults: Choose physically meaningful initial values
- Add error handling: Account for edge cases
- Include units: Always specify physical units
Performance Considerations
- Limit computation time: Keep calculations under a few seconds
- Cache expensive operations: Store results when possible
- Use vectorized operations: Prefer NumPy over Python loops
- Progressive complexity: Start with simple cases
π¨ Common Pitfalls
Import Issues
# β Don't do this
from some_custom_package import *
# β
Do this instead
import numpy as np
import matplotlib.pyplot as plt
# Standard scientific packages are available
Widget Responsiveness
# β Avoid heavy computations in widget definitions
expensive_widget = mo.ui.slider(min=compute_expensive_min(), ...)
# β
Pre-compute or use reasonable defaults
min_val = 0.1 # Known reasonable minimum
expensive_widget = mo.ui.slider(min=min_val, ...)
Error Handling
```python {marimo}
import marimo as mo
import numpy as np
def safe_calculation(x):
try:
if x <= 0:
return mo.md("β οΈ **Warning**: Input must be positive")
result = np.sqrt(x)
return mo.md(f"β{x} = {result:.3f}")
except Exception as e:
return mo.md(f"β **Error**: {str(e)}")
input_val = mo.ui.number(1, label="Enter a positive number")
mo.vstack([input_val, safe_calculation(input_val.value)])
```
π Code Templates
Basic Interactive Plot
```python {marimo}
import marimo as mo
import numpy as np
import matplotlib.pyplot as plt
# Parameter widgets
param1 = mo.ui.slider(min_val, max_val, step, value=default, label="Parameter 1")
param2 = mo.ui.slider(min_val, max_val, step, value=default, label="Parameter 2")
mo.hstack([param1, param2])
```
```python {marimo}
# Calculation and plotting
x = np.linspace(x_min, x_max, num_points)
y = your_function(x, param1.value, param2.value)
plt.figure(figsize=(8, 6))
plt.plot(x, y, label='Your Function')
plt.xlabel('X Label')
plt.ylabel('Y Label')
plt.title('Your Title')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
```
Data Analysis Template
```python {marimo}
import marimo as mo
import pandas as pd
import numpy as np
# Load or simulate data
data = your_data_loading_function()
# Analysis parameters
analysis_param = mo.ui.dropdown(options, label="Analysis type")
filter_param = mo.ui.slider(min_val, max_val, step, label="Filter threshold")
mo.hstack([analysis_param, filter_param])
```
```python {marimo}
# Process data based on parameters
filtered_data = data[data['column'] > filter_param.value]
result = perform_analysis(filtered_data, analysis_param.value)
# Display results
mo.ui.table(result) if isinstance(result, pd.DataFrame) else mo.md(f"Result: {result}")
```
π Testing Your Code
Before publishing:
- Test all widgets: Ensure they respond correctly
- Check edge cases: Test minimum/maximum values
- Verify calculations: Double-check mathematical formulas
- Test on different devices: Ensure mobile compatibility
- Review performance: Confirm reasonable execution times
π― Examples in Action
Check out these example posts to see Python integration in practice:
- Template Post - Basic Marimo integration
- Look for posts tagged with Python Applications
π Ready to Code?
Start with simple widgets and gradually add complexity. Remember:
- Physics first: Focus on the science, let code support it
- User experience: Make interactions intuitive
- Documentation: Explain both the physics and the code
- Testing: Verify everything works as expected
Your interactive content will help readers understand complex concepts through hands-on exploration!