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
| import numpy as np import matplotlib.pyplot as plt from scipy.optimize import minimize, differential_evolution import networkx as nx from matplotlib.patches import Circle import seaborn as sns
plt.style.use('seaborn-v0_8') sns.set_palette("husl")
class VascularNetwork: """ A class to model and optimize vascular networks based on Murray's Law and energy minimization principles. """ def __init__(self, alpha=1.0, beta=1.0, murray_exponent=3.0): """ Initialize the vascular network optimizer. Parameters: - alpha: weight for metabolic cost (proportional to vessel volume) - beta: weight for pumping cost (inversely related to resistance) - murray_exponent: exponent in Murray's law (typically 3.0) """ self.alpha = alpha self.beta = beta self.n = murray_exponent self.vessels = [] def add_vessel(self, start_point, end_point, radius, flow_rate=1.0): """Add a vessel segment to the network.""" length = np.linalg.norm(np.array(end_point) - np.array(start_point)) vessel = { 'start': start_point, 'end': end_point, 'radius': radius, 'length': length, 'flow_rate': flow_rate } self.vessels.append(vessel) def metabolic_cost(self, vessel): """Calculate metabolic cost proportional to vessel volume.""" return self.alpha * vessel['radius']**2 * vessel['length'] def pumping_cost(self, vessel): """Calculate pumping cost based on Poiseuille's law.""" return self.beta * vessel['flow_rate'] * vessel['length'] / vessel['radius']**4 def total_energy_cost(self): """Calculate total energy cost of the network.""" total_cost = 0 for vessel in self.vessels: total_cost += self.metabolic_cost(vessel) + self.pumping_cost(vessel) return total_cost def murray_law_violation(self, parent_radius, daughter_radii): """Calculate violation of Murray's law.""" expected = sum(r**self.n for r in daughter_radii) actual = parent_radius**self.n return abs(actual - expected) / actual
def optimize_bifurcation(parent_radius, total_flow, alpha=1.0, beta=1.0, n=3.0): """ Optimize a single bifurcation according to Murray's law and energy minimization. Parameters: - parent_radius: radius of parent vessel - total_flow: total flow rate - alpha, beta: energy cost weights - n: Murray's exponent Returns: - Optimal daughter vessel radii and flow distribution """ def objective(x): """Objective function to minimize total energy cost.""" r1, r2, flow_ratio = x if r1 <= 0 or r2 <= 0 or flow_ratio <= 0 or flow_ratio >= 1: return 1e10 flow1 = flow_ratio * total_flow flow2 = (1 - flow_ratio) * total_flow metabolic_cost = alpha * (r1**2 + r2**2) pumping_cost = beta * (flow1/r1**4 + flow2/r2**4) murray_violation = abs(parent_radius**n - (r1**n + r2**n)) penalty = 1000 * murray_violation return metabolic_cost + pumping_cost + penalty r_guess = parent_radius / (2**(1/n)) x0 = [r_guess, r_guess, 0.5] bounds = [(0.01, parent_radius*0.99), (0.01, parent_radius*0.99), (0.01, 0.99)] result = minimize(objective, x0, bounds=bounds, method='L-BFGS-B') return result.x
def create_fractal_network(generations=4, base_radius=1.0, base_flow=1.0): """ Create a fractal vascular network using recursive bifurcations. """ network = VascularNetwork() def recursive_branch(start_point, direction, radius, flow, generation, length=1.0): if generation <= 0: return end_point = (start_point[0] + direction[0] * length, start_point[1] + direction[1] * length) network.add_vessel(start_point, end_point, radius, flow) if generation > 1: r1, r2, flow_ratio = optimize_bifurcation(radius, flow) angle1 = np.pi/6 angle2 = -np.pi/6 cos1, sin1 = np.cos(angle1), np.sin(angle1) cos2, sin2 = np.cos(angle2), np.sin(angle2) dir1 = (direction[0]*cos1 - direction[1]*sin1, direction[0]*sin1 + direction[1]*cos1) dir2 = (direction[0]*cos2 - direction[1]*sin2, direction[0]*sin2 + direction[1]*cos2) recursive_branch(end_point, dir1, r1, flow*flow_ratio, generation-1, length*0.8) recursive_branch(end_point, dir2, r2, flow*(1-flow_ratio), generation-1, length*0.8) recursive_branch((0, 0), (0, 1), base_radius, base_flow, generations) return network
def analyze_murray_law(): """Analyze Murray's law for different scenarios.""" parent_radii = np.linspace(0.5, 2.0, 20) results = [] for parent_r in parent_radii: r1, r2, flow_ratio = optimize_bifurcation(parent_r, 1.0) murray_left = parent_r**3 murray_right = r1**3 + r2**3 compliance = murray_right / murray_left results.append({ 'parent_radius': parent_r, 'daughter1_radius': r1, 'daughter2_radius': r2, 'flow_ratio': flow_ratio, 'murray_compliance': compliance, 'radius_ratio': r1/parent_r, 'total_daughter_volume': np.pi * (r1**2 + r2**2), 'parent_volume': np.pi * parent_r**2 }) return results
def plot_network_visualization(network): """Create a comprehensive visualization of the vascular network.""" fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 12)) fig.suptitle('Vascular Network Analysis', fontsize=16, fontweight='bold') ax1.set_title('Network Structure', fontweight='bold') for vessel in network.vessels: x_coords = [vessel['start'][0], vessel['end'][0]] y_coords = [vessel['start'][1], vessel['end'][1]] linewidth = vessel['radius'] * 5 ax1.plot(x_coords, y_coords, 'b-', linewidth=linewidth, alpha=0.7) mid_x = (vessel['start'][0] + vessel['end'][0]) / 2 mid_y = (vessel['start'][1] + vessel['end'][1]) / 2 dx = vessel['end'][0] - vessel['start'][0] dy = vessel['end'][1] - vessel['start'][1] length = np.sqrt(dx**2 + dy**2) ax1.arrow(mid_x, mid_y, dx/length*0.1, dy/length*0.1, head_width=0.05, head_length=0.05, fc='red', ec='red') ax1.set_xlabel('X Position') ax1.set_ylabel('Y Position') ax1.grid(True, alpha=0.3) ax1.set_aspect('equal') ax2.set_title('Vessel Radius Distribution', fontweight='bold') radii = [vessel['radius'] for vessel in network.vessels] ax2.hist(radii, bins=20, alpha=0.7, color='skyblue', edgecolor='black') ax2.set_xlabel('Vessel Radius') ax2.set_ylabel('Frequency') ax2.grid(True, alpha=0.3) ax3.set_title('Energy Cost Components', fontweight='bold') metabolic_costs = [network.metabolic_cost(vessel) for vessel in network.vessels] pumping_costs = [network.pumping_cost(vessel) for vessel in network.vessels] vessel_indices = range(len(network.vessels)) width = 0.35 ax3.bar([i - width/2 for i in vessel_indices], metabolic_costs, width, label='Metabolic Cost', alpha=0.7) ax3.bar([i + width/2 for i in vessel_indices], pumping_costs, width, label='Pumping Cost', alpha=0.7) ax3.set_xlabel('Vessel Index') ax3.set_ylabel('Energy Cost') ax3.legend() ax3.grid(True, alpha=0.3) ax4.set_title("Murray's Law Compliance Analysis", fontweight='bold') compliance_data = [] for i, vessel in enumerate(network.vessels[:-2]): parent_r = vessel['radius'] if i + 2 < len(network.vessels): r1 = network.vessels[i+1]['radius'] r2 = network.vessels[i+2]['radius'] murray_expected = parent_r**3 murray_actual = r1**3 + r2**3 compliance = murray_actual / murray_expected if murray_expected > 0 else 0 compliance_data.append(compliance) if compliance_data: ax4.plot(compliance_data, 'o-', linewidth=2, markersize=8) ax4.axhline(y=1.0, color='red', linestyle='--', label="Perfect Murray's Law Compliance") ax4.set_xlabel('Bifurcation Index') ax4.set_ylabel('Compliance Ratio') ax4.legend() ax4.grid(True, alpha=0.3) plt.tight_layout() plt.show()
def plot_murray_law_analysis(): """Plot comprehensive Murray's law analysis.""" results = analyze_murray_law() fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 12)) fig.suptitle("Murray's Law Optimization Analysis", fontsize=16, fontweight='bold') parent_radii = [r['parent_radius'] for r in results] ax1.set_title('Optimal Daughter Vessel Radii', fontweight='bold') daughter1_radii = [r['daughter1_radius'] for r in results] daughter2_radii = [r['daughter2_radius'] for r in results] ax1.plot(parent_radii, daughter1_radii, 'o-', label='Daughter 1', linewidth=2) ax1.plot(parent_radii, daughter2_radii, 's-', label='Daughter 2', linewidth=2) ax1.plot(parent_radii, [p/2**(1/3) for p in parent_radii], '--', label='Murray Prediction', alpha=0.7) ax1.set_xlabel('Parent Vessel Radius') ax1.set_ylabel('Daughter Vessel Radius') ax1.legend() ax1.grid(True, alpha=0.3) ax2.set_title("Murray's Law Compliance", fontweight='bold') compliance = [r['murray_compliance'] for r in results] ax2.plot(parent_radii, compliance, 'o-', color='green', linewidth=2, markersize=8) ax2.axhline(y=1.0, color='red', linestyle='--', label='Perfect Compliance', alpha=0.7) ax2.set_xlabel('Parent Vessel Radius') ax2.set_ylabel('Compliance Ratio') ax2.legend() ax2.grid(True, alpha=0.3) ax3.set_title('Optimal Flow Distribution', fontweight='bold') flow_ratios = [r['flow_ratio'] for r in results] ax3.plot(parent_radii, flow_ratios, 'o-', color='purple', linewidth=2) ax3.axhline(y=0.5, color='orange', linestyle='--', label='Equal Flow Split', alpha=0.7) ax3.set_xlabel('Parent Vessel Radius') ax3.set_ylabel('Flow Ratio (Daughter 1)') ax3.legend() ax3.grid(True, alpha=0.3) ax4.set_title('Volume Efficiency Analysis', fontweight='bold') parent_volumes = [r['parent_volume'] for r in results] daughter_volumes = [r['total_daughter_volume'] for r in results] efficiency = [d/p for d, p in zip(daughter_volumes, parent_volumes)] ax4.plot(parent_radii, efficiency, 'o-', color='brown', linewidth=2) ax4.set_xlabel('Parent Vessel Radius') ax4.set_ylabel('Volume Efficiency Ratio') ax4.grid(True, alpha=0.3) plt.tight_layout() plt.show() return results
if __name__ == "__main__": print("=== Vascular Network Optimization Analysis ===\n") print("1. Creating fractal vascular network...") network = create_fractal_network(generations=4, base_radius=1.0) print(f" Network created with {len(network.vessels)} vessel segments") print(f" Total energy cost: {network.total_energy_cost():.4f}") print("\n2. Visualizing network structure and properties...") plot_network_visualization(network) print("\n3. Analyzing Murray's law compliance...") murray_results = plot_murray_law_analysis() print("\n4. Summary Statistics:") print(f" Average Murray's law compliance: {np.mean([r['murray_compliance'] for r in murray_results]):.4f}") print(f" Standard deviation of compliance: {np.std([r['murray_compliance'] for r in murray_results]):.4f}") avg_radius_ratio = np.mean([r['radius_ratio'] for r in murray_results]) theoretical_ratio = 1 / (2**(1/3)) print(f" Average daughter/parent radius ratio: {avg_radius_ratio:.4f}") print(f" Theoretical Murray's ratio: {theoretical_ratio:.4f}") print(f" Ratio accuracy: {(1 - abs(avg_radius_ratio - theoretical_ratio)/theoretical_ratio)*100:.2f}%") print("\n=== Analysis Complete ===")
|