diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..4de3c9b Binary files /dev/null and b/.DS_Store differ diff --git a/_modules/ergodicity/agents/agent_pool.html b/_modules/ergodicity/agents/agent_pool.html index cd9e033..c5eb599 100644 --- a/_modules/ergodicity/agents/agent_pool.html +++ b/_modules/ergodicity/agents/agent_pool.html @@ -114,7 +114,7 @@

Source code for ergodicity.agents.agent_pool

from scipy import stats
 
 
-[docs] +[docs] class AgentPool: """ AgentPool represents a collection of agents participating in a wealth dynamics simulation. @@ -175,7 +175,7 @@

Source code for ergodicity.agents.agent_pool

self.history = [self.wealth.copy()]
 
 
-[docs] +[docs] def simulate(self, dynamic_s=False): """ Run the wealth dynamics simulation for the specified time horizon. @@ -216,7 +216,7 @@

Source code for ergodicity.agents.agent_pool

# return self.history
 
 
-[docs] +[docs] def save_data(self, filename): """ Save the wealth history data to a file. @@ -230,7 +230,7 @@

Source code for ergodicity.agents.agent_pool

-[docs]
+[docs]
     def plot(self):
         """
         Visualize the wealth dynamics of all agents over time.
@@ -259,7 +259,7 @@ 

Source code for ergodicity.agents.agent_pool

-[docs]
+[docs]
     def mean_logarithmic_deviation(self):
         """
         Compute the Mean Logarithmic Deviation (MLD) for each time step.
@@ -274,7 +274,7 @@ 

Source code for ergodicity.agents.agent_pool

-[docs]
+[docs]
     def coefficient_of_variation(self):
         """
         Compute the Coefficient of Variation for each time step.
@@ -288,7 +288,7 @@ 

Source code for ergodicity.agents.agent_pool

-[docs]
+[docs]
     def palma_ratio(self):
         """
         Compute the Palma ratio for each time step.
@@ -309,7 +309,7 @@ 

Source code for ergodicity.agents.agent_pool

-[docs]
+[docs]
     def gini_coefficient(self):
         """
         Compute the Gini coefficient for each time step.
@@ -329,7 +329,7 @@ 

Source code for ergodicity.agents.agent_pool

-[docs]
+[docs]
     def plot_inequality_measures(self):
         """
         Plot all implemented inequality measures over time.
@@ -361,7 +361,7 @@ 

Source code for ergodicity.agents.agent_pool

-[docs]
+[docs]
     def save_and_plot_wealth_distribution(self, filename_prefix):
         """
         Save and plot the final wealth distribution in normal and log-log scales.
@@ -386,23 +386,29 @@ 

Source code for ergodicity.agents.agent_pool

ax1.set_ylabel('Frequency')
 
         # Log-log scale histogram
-        wealth_range = np.logspace(np.log10(min(final_wealth)), np.log10(max(final_wealth)), num=50)
-        hist, bins = np.histogram(final_wealth, bins=wealth_range)
+        final_wealth_nonzero = final_wealth[final_wealth > 0]
+        wealth_range = np.logspace(np.log10(min(final_wealth_nonzero)), np.log10(max(final_wealth_nonzero)), num=50)
+        hist, bins = np.histogram(final_wealth_nonzero, bins=wealth_range)
         center = (bins[:-1] + bins[1:]) / 2
 
-        ax2.loglog(center, hist, 'k.', markersize=10)
-        ax2.set_title('Wealth Distribution (Log-Log Scale)')
-        ax2.set_xlabel('Wealth (log scale)')
-        ax2.set_ylabel('Frequency (log scale)')
+        # Remove zero counts for log-log fit
+        nonzero = hist > 0
+        log_center = np.log10(center[nonzero])
+        log_hist = np.log10(hist[nonzero])
 
-        # Filter out zero values for log-log fit
-        nonzero_wealth = final_wealth[final_wealth > 0]
-        fit = stats.linregress(np.log10(nonzero_wealth), np.log10(np.arange(1, len(nonzero_wealth) + 1)[::-1]))
+        # Linear regression in log-log space
+        fit = stats.linregress(log_center, log_hist)
 
-        x_fit = np.logspace(np.log10(min(nonzero_wealth)), np.log10(max(nonzero_wealth)), 100)
+        # Compute the fitted power-law line
+        x_fit = np.logspace(np.log10(min(center[nonzero])), np.log10(max(center[nonzero])), 100)
         y_fit = 10 ** (fit.intercept + fit.slope * np.log10(x_fit))
 
-        ax2.plot(x_fit, y_fit, 'r-', label=f'Power Law Fit (α ≈ {-fit.slope:.2f})')
+        # Plotting
+        ax2.loglog(center, hist, 'k.', markersize=10)
+        # ax2.plot(x_fit, y_fit, 'r-', label=f'Power Law Fit (α ≈ {fit.slope:.2f})')
+        ax2.set_title('Wealth Distribution (Log-Log Scale)')
+        ax2.set_xlabel('Wealth (log scale)')
+        ax2.set_ylabel('Frequency (log scale)')
         ax2.legend()
 
         plt.tight_layout()
@@ -415,11 +421,16 @@ 

Source code for ergodicity.agents.agent_pool

import numpy as np
+import matplotlib.pyplot as plt
+import plotly.graph_objects as go
+
+
 
-[docs] +[docs] def plot_wealth_3d(process, w, time, simulation_timestep, timestep, s_range, n_range, save_html=False): """ - Plot a 3D graph of total wealth as a function of sharing rate s and number of agents n. + Plot a 3D graph of average wealth as a function of sharing rate s and number of agents n. :param process: The stochastic process to use (e.g., GeometricBrownianMotion instance) :type process: StochasticProcess @@ -441,24 +452,24 @@

Source code for ergodicity.agents.agent_pool

    :rtype: None
     """
     s_values, n_values = np.meshgrid(s_range, n_range)
-    total_wealth = np.zeros_like(s_values, dtype=float)
+    average_wealth = np.zeros_like(s_values, dtype=float)
 
     for i, n in enumerate(n_range):
         for j, s in enumerate(s_range):
             pool = AgentPool(process, n, w, s, time, simulation_timestep, timestep)
             pool.simulate(dynamic_s=False)
-            total_wealth[i, j] = np.sum(pool.wealth)
+            average_wealth[i, j] = np.mean(pool.wealth)
 
     # Create static 3D plot using Matplotlib
     fig = plt.figure(figsize=(12, 8))
     ax = fig.add_subplot(111, projection='3d')
 
-    surf = ax.plot_surface(s_values, n_values, total_wealth, cmap='viridis')
+    surf = ax.plot_surface(s_values, n_values, average_wealth, cmap='viridis')
 
     ax.set_xlabel('Sharing Rate (s)')
     ax.set_ylabel('Number of Agents (n)')
-    ax.set_zlabel('Total Wealth')
-    ax.set_title('Total Wealth as a Function of Sharing Rate and Number of Agents')
+    ax.set_zlabel('Average Wealth')
+    ax.set_title('Average Wealth as a Function of Sharing Rate and Number of Agents')
 
     fig.colorbar(surf, shrink=0.5, aspect=5)
 
@@ -466,17 +477,17 @@ 

Source code for ergodicity.agents.agent_pool

# Create and save interactive 3D plot using Plotly
     if save_html:
-        fig_plotly = go.Figure(data=[go.Surface(z=total_wealth, x=s_values, y=n_values)])
+        fig_plotly = go.Figure(data=[go.Surface(z=average_wealth, x=s_values, y=n_values)])
         fig_plotly.update_layout(
-            title='Total Wealth as a Function of Sharing Rate and Number of Agents',
+            title='Average Wealth as a Function of Sharing Rate and Number of Agents',
             scene=dict(
                 xaxis_title='Sharing Rate (s)',
                 yaxis_title='Number of Agents (n)',
-                zaxis_title='Total Wealth'
+                zaxis_title='Average Wealth'
             )
         )
 
-        html_filename = 'total_wealth_3d_plot.html'
+        html_filename = 'average_wealth_3d_plot.html'
         fig_plotly.write_html(html_filename)
         print(f"3D interactive graph saved as {html_filename}")
diff --git a/_modules/ergodicity/agents/agents.html b/_modules/ergodicity/agents/agents.html index 3c0e76c..d951386 100644 --- a/_modules/ergodicity/agents/agents.html +++ b/_modules/ergodicity/agents/agents.html @@ -149,7 +149,7 @@

Source code for ergodicity.agents.agents

 
 
 
-[docs] +[docs] def general_utility_function(x, alpha, beta, gamma, delta, epsilon): """ Calculates the utility for a given x and set of parameters. @@ -177,7 +177,7 @@

Source code for ergodicity.agents.agents

 
 
 
-[docs] +[docs] @dataclass class Agent_utility: """ @@ -205,7 +205,7 @@

Source code for ergodicity.agents.agents

     total_accumulated_wealth: float = 1.0  # New field to track total wealth
 
 
-[docs] +[docs] @staticmethod def expected_utility(process_dict: Dict[str, Any], params: np.ndarray, t: float = None) -> Union[ Callable[[float], float], float]: @@ -291,7 +291,7 @@

Source code for ergodicity.agents.agents

 
 
 
-[docs] +[docs] @staticmethod def numerical_expected_utility(process: Union[Dict[str, Any], object], params: np.ndarray, stochastic_process_class: Type, t: float = None, num_instances: int = 1000) -> Union[ @@ -338,7 +338,7 @@

Source code for ergodicity.agents.agents

 
 
 
-[docs] +[docs] @staticmethod def compare_numerical_and_symbolic_expected_utility(process_dict: Dict[str, Any], params: np.ndarray, stochastic_process_class: Type, t: float = None): @@ -382,7 +382,7 @@

Source code for ergodicity.agents.agents

     # compare_numerical_and_symbolic_expected_utility(process, params, 1.0, GeometricBrownianMotion)
 
 
-[docs] +[docs] @staticmethod def general_utility_function(x, alpha, beta, gamma, delta, epsilon): """ @@ -399,7 +399,7 @@

Source code for ergodicity.agents.agents

 
 
 
-[docs] +[docs] @staticmethod def general_utility_function_np(x, alpha, beta, gamma, delta, epsilon): """ @@ -427,7 +427,7 @@

Source code for ergodicity.agents.agents

 
 
 
-[docs] +[docs] @staticmethod def visualize_utility_function_evolution(history, output_video_path, output_csv_path): """ @@ -494,7 +494,7 @@

Source code for ergodicity.agents.agents

 
 
 
-[docs] +[docs] @staticmethod def initialize_agents(n: int, param_means: np.ndarray, param_stds: np.ndarray) -> List['Agent_utility']: """ @@ -512,7 +512,7 @@

Source code for ergodicity.agents.agents

 
 
 
-[docs] +[docs] @staticmethod def mutate_params(params: np.ndarray, mutation_rate: float) -> np.ndarray: """ @@ -530,7 +530,7 @@

Source code for ergodicity.agents.agents

 
 
 
-[docs] +[docs] @staticmethod def evolutionary_algorithm(n_agents: int, n_steps: int, save_interval: int, processes: List[Union[dict, object]], @@ -699,7 +699,7 @@

Source code for ergodicity.agents.agents

 
 
 
-[docs] +[docs] @staticmethod def evolutionary_algorithm_with_exchange(n_agents: int, n_steps: int, save_interval: int, processes: List[Union[dict, object]], @@ -867,7 +867,7 @@

Source code for ergodicity.agents.agents

 
 
 
-[docs] +[docs] @staticmethod def evolutionary_algorithm_with_multiple_processes( n_agents: int, n_steps: int, save_interval: int, @@ -1035,7 +1035,7 @@

Source code for ergodicity.agents.agents

 
 
 
-[docs] +[docs] def visualize_agent_evolution(history: List[Dict], top_n: int = 5): """ Visualize the evolution of top agents and their utility functions. @@ -1119,7 +1119,7 @@

Source code for ergodicity.agents.agents

 
 
 
-[docs] +[docs] def recursive_flatten(data: Any) -> List[float]: """ Recursively flatten any nested structure into a 1D list of floats. @@ -1140,7 +1140,7 @@

Source code for ergodicity.agents.agents