Coverage for .tox/p311/lib/python3.10/site-packages/scicom/knowledgespread/server.py: 0%
69 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-26 17:47 +0200
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-26 17:47 +0200
1import altair as alt
2import mesa
3import networkx as nx
4import nx_altair as nxa
5import pandas as pd
6import solara
7from matplotlib import colors
8from mesa.visualization.modules import ChartVisualization
10from scicom.knowledgespread.model import KnowledgeSpread
11from scicom.knowledgespread.SimpleContinuousModule import SimpleCanvas
12from scicom.knowledgespread.utils import ageFunction
14model_params = {
15 "num_scientists": mesa.visualization.Slider(
16 "Initial number of scientists",
17 100, 10, 200, 10,
18 ),
19 "num_timesteps": mesa.visualization.Slider(
20 "How long is the number of agents growing?",
21 20, 5, 100, 5,
22 ),
23 "oppositionPercent": mesa.visualization.Slider(
24 "Percentage of opposing agents",
25 0.05, 0, 0.5, 0.05,
26 ),
27 "epiInit": mesa.visualization.Choice(
28 "Choose initial conditions for epistemic space",
29 value=("complex"),
30 choices=["complex", "central", "polarized"],
31 ),
32 "timeInit": mesa.visualization.Choice(
33 "Choose initial conditions for population growth.",
34 value=("saturate"),
35 choices=["saturate", "linear", "exponential"],
36 ),
37 "epiRange": mesa.visualization.Slider(
38 "Basic range of visibility in epistemic space",
39 0.005, 0.001, 0.03, 0.001,
40 ),
41}
44def agent_draw_altair(agent):
45 shapeDict = {True: "triangle-up", False: "circle"}
46 colortuple = set(agent.topicledger[-1])
47 color = colors.to_hex(colortuple)
48 #color = "#" + "".join(format(int(round(val * 255)), "02x") for val in colortuple)
49 if agent.age > 0:
50 size = ageFunction(agent, agent.a, agent.b, agent.c, 10)
51 else:
52 size = 0.001
53 probDict = {
54 #"Shape": shapeDict[agent.opposition],
55 "opposition": agent.opposition,
56 #"r": ageFunction(agent),
57 "size": size,
58 #"Filled": "true",
59 "Color": color,
60 "color": color,
61 }
62 return probDict
65def chart_draw_altair_agents(model):
66 data = model.datacollector.get_model_vars_dataframe().reset_index()
67 chart = (
68 alt.Chart(data)
69 .mark_bar(color="orange")
70 .encode(
71 x=alt.X("index", title="Step"),
72 y=alt.Y(
73 "Active Agents",
74 title="Active agents",
75 ),
76 )
77 )
78 return solara.FigureAltair(chart)
81def chart_draw_altair_communities(model):
82 data = model.datacollector.get_model_vars_dataframe().reset_index()
83 data.insert(0, "compLen", data["Graph structure"].apply(lambda x: len(x)))
84 chart = (
85 alt.Chart(data)
86 .mark_bar(color="orange")
87 .encode(
88 x=alt.X("index", title="Step"),
89 y=alt.Y(
90 "compLen",
91 title="Communities in social network",
92 ),
93 )
94 )
95 return solara.FigureAltair(chart)
98def epiSpace_draw_altair(model, agent_portrayal):
99 isOpposed = (False, True)
100 shape_range = ("circle", "triangle-up")
101 all_agent_data = []
102 if not model.schedule.agents:
103 return solara.Markdown("## Finished run")
104 else:
105 for agent in model.schedule.agents:
106 cur_agent = agent_draw_altair(agent)
107 cur_agent["x"] = agent.pos[0]
108 cur_agent["y"] = agent.pos[1]
109 all_agent_data.append(cur_agent)
110 df = pd.DataFrame(all_agent_data)
111 colors = list(set(a["color"] for a in all_agent_data))
112 chart_color = alt.Color("color").legend(None).scale(domain=colors, range=colors)
113 chart = (
114 alt.Chart(df)
115 .mark_point(filled=True)
116 .encode(
117 x=alt.X("x", axis=None), # no x-axis label
118 y=alt.Y("y", axis=None), # no y-axis label
119 size=alt.Size("size", title="current activity"), # relabel size for legend
120 color=chart_color,
121 shape=alt.Shape( # use shape to indicate choice
122 "opposition", scale=alt.Scale(domain=isOpposed, range=shape_range),
123 ),
124 )
125 .configure_view(strokeOpacity=0) # hide grid/chart lines
126 )
127 return solara.FigureAltair(chart)
130def socialNetwork_draw_altair(model):
131 currentTime = model.schedule.time
132 H = model.socialNetwork
133 Graph = nx.Graph(((u, v, e) for u, v, e in H.edges(data=True) if e["time"] <= currentTime))
134 pos = nx.kamada_kawai_layout(Graph)
135 between = nx.betweenness_centrality(Graph)
136 nx.set_node_attributes(Graph, between, "between")
137 communities = list(nx.community.label_propagation_communities(Graph))
138 for f in Graph.nodes():
139 for i, c in enumerate(communities):
140 if f in c:
141 Graph.nodes()[f].update(
142 {
143 "community": str(i),
144 "name": f,
145 },
146 )
147 chart = nxa.draw_networkx(
148 G=Graph,
149 pos=pos,
150 node_color="between",
151 edge_color="time",
152 cmap="viridis",
153 )
154 chart.configure_view(strokeOpacity=0) # hide grid/chart lines
155 return solara.FigureAltair(chart)
158def agent_draw(agent):
159 colortuple = set(agent.topicledger[-1])
160 color = "#" + "".join(format(int(round(val * 255)), "02x") for val in colortuple)
161 probDict = {
162 "Shape": "circle",
163 "r": ageFunction(agent),
164 "Filled": "true",
165 "Color": color,
166 }
167 return probDict
170chart = ChartVisualization.ChartModule(
171 [
172 {"Label": "Active Agents", "Color": "#000000"},
173 {"Label": "Graph components", "Color": "black"},
174 ],
175 data_collector_name="datacollector",
176)
179epistemic_canvas = SimpleCanvas(agent_draw, 720, 720)
182server = mesa.visualization.ModularServer(
183 KnowledgeSpread,
184 [epistemic_canvas, chart],
185 "Knowledge spread",
186 model_params,
187)