Coverage for src/scicom/knowledgespread/server.py: 0%

70 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2024-04-15 13:26 +0200

1import mesa 

2import solara 

3import altair as alt 

4import pandas as pd 

5import nx_altair as nxa 

6import networkx as nx 

7import matplotlib.colors as colors 

8 

9from scicom.knowledgespread.SimpleContinuousModule import SimpleCanvas 

10from mesa.visualization.modules import ChartVisualization 

11 

12 

13from scicom.knowledgespread.agents import ScientistAgent 

14from scicom.knowledgespread.model import KnowledgeSpread 

15from scicom.knowledgespread.utils import ageFunction 

16 

17model_params = { 

18 "num_scientists": mesa.visualization.Slider( 

19 "Initial number of scientists", 

20 100, 10, 200, 10, 

21 ), 

22 "num_timesteps": mesa.visualization.Slider( 

23 "How long is the number of agents growing?", 

24 20, 5, 100, 5, 

25 ), 

26 "oppositionPercent": mesa.visualization.Slider( 

27 "Percentage of opposing agents", 

28 0.05, 0, 0.5, 0.05, 

29 ), 

30 "epiInit": mesa.visualization.Choice( 

31 'Choose initial conditions for epistemic space', 

32 value=('complex'), 

33 choices=['complex', "central", "polarized"] 

34 ), 

35 "timeInit": mesa.visualization.Choice( 

36 'Choose initial conditions for population growth.', 

37 value=('saturate'), 

38 choices=['saturate', "linear", "exponential"] 

39 ), 

40 "epiRange": mesa.visualization.Slider( 

41 "Basic range of visibility in epistemic space", 

42 0.005, 0.001, 0.03, 0.001, 

43 ) 

44} 

45 

46 

47def agent_draw_altair(agent): 

48 shapeDict = {True: "triangle-up", False: "circle"} 

49 colortuple = set(agent.topicledger[-1]) 

50 color = colors.to_hex(colortuple) 

51 #color = "#" + "".join(format(int(round(val * 255)), "02x") for val in colortuple) 

52 if agent.age > 0: 

53 size = ageFunction(agent, agent.a, agent.b, agent.c, 10) 

54 else: 

55 size = 0.001 

56 probDict = { 

57 #"Shape": shapeDict[agent.opposition], 

58 "opposition": agent.opposition, 

59 #"r": ageFunction(agent), 

60 "size": size, 

61 #"Filled": "true", 

62 "Color": color, 

63 "color": color 

64 } 

65 return probDict 

66 

67 

68def chart_draw_altair_agents(model): 

69 data = model.datacollector.get_model_vars_dataframe().reset_index() 

70 chart = ( 

71 alt.Chart(data) 

72 .mark_bar(color="orange") 

73 .encode( 

74 x=alt.X("index", title="Step"), 

75 y=alt.Y( 

76 "Active Agents", 

77 title="Active agents" 

78 ), 

79 ) 

80 ) 

81 return solara.FigureAltair(chart) 

82 

83 

84def chart_draw_altair_communities(model): 

85 data = model.datacollector.get_model_vars_dataframe().reset_index() 

86 data.insert(0, "compLen", data["Graph structure"].apply(lambda x: len(x))) 

87 chart = ( 

88 alt.Chart(data) 

89 .mark_bar(color="orange") 

90 .encode( 

91 x=alt.X("index", title="Step"), 

92 y=alt.Y( 

93 "compLen", 

94 title="Communities in social network" 

95 ), 

96 ) 

97 ) 

98 return solara.FigureAltair(chart) 

99 

100 

101def epiSpace_draw_altair(model, agent_portrayal): 

102 isOpposed = (False, True) 

103 shape_range = ("circle", "triangle-up") 

104 all_agent_data = [] 

105 if not model.schedule.agents: 

106 return solara.Markdown("## Finished run") 

107 else: 

108 for agent in model.schedule.agents: 

109 cur_agent = agent_draw_altair(agent) 

110 cur_agent["x"] = agent.pos[0] 

111 cur_agent["y"] = agent.pos[1] 

112 all_agent_data.append(cur_agent) 

113 df = pd.DataFrame(all_agent_data) 

114 colors = list(set(a["color"] for a in all_agent_data)) 

115 chart_color = alt.Color("color").legend(None).scale(domain=colors, range=colors) 

116 chart = ( 

117 alt.Chart(df) 

118 .mark_point(filled=True) 

119 .encode( 

120 x=alt.X("x", axis=None), # no x-axis label 

121 y=alt.Y("y", axis=None), # no y-axis label 

122 size=alt.Size("size", title="current activity"), # relabel size for legend 

123 color=chart_color, 

124 shape=alt.Shape( # use shape to indicate choice 

125 "opposition", scale=alt.Scale(domain=isOpposed, range=shape_range) 

126 ), 

127 ) 

128 .configure_view(strokeOpacity=0) # hide grid/chart lines 

129 ) 

130 return solara.FigureAltair(chart) 

131 

132 

133def socialNetwork_draw_altair(model): 

134 currentTime = model.schedule.time 

135 H = model.socialNetwork 

136 Graph = nx.Graph(((u, v, e) for u, v, e in H.edges(data=True) if e['time'] <= currentTime)) 

137 pos = nx.kamada_kawai_layout(Graph) 

138 between = nx.betweenness_centrality(Graph) 

139 nx.set_node_attributes(Graph, between, 'between') 

140 communities = list(nx.community.label_propagation_communities(Graph)) 

141 for f in Graph.nodes(): 

142 for i, c in enumerate(communities): 

143 if f in c: 

144 Graph.nodes()[f].update( 

145 { 

146 "community": str(i), 

147 "name": f 

148 } 

149 ) 

150 chart = nxa.draw_networkx( 

151 G=Graph, 

152 pos=pos, 

153 node_color="between", 

154 edge_color='time', 

155 cmap='viridis' 

156 ) 

157 chart.configure_view(strokeOpacity=0) # hide grid/chart lines 

158 return solara.FigureAltair(chart) 

159 

160 

161def agent_draw(agent): 

162 colortuple = set(agent.topicledger[-1]) 

163 color = "#" + "".join(format(int(round(val * 255)), "02x") for val in colortuple) 

164 probDict = { 

165 "Shape": "circle", 

166 "r": ageFunction(agent), 

167 "Filled": "true", 

168 "Color": color 

169 } 

170 return probDict 

171 

172 

173chart = ChartVisualization.ChartModule( 

174 [ 

175 {"Label": "Active Agents", "Color": "#000000"}, 

176 {"Label": "Graph components", "Color": "black"} 

177 ], 

178 data_collector_name='datacollector', 

179) 

180 

181 

182epistemic_canvas = SimpleCanvas(agent_draw, 720, 720) 

183 

184 

185server = mesa.visualization.ModularServer( 

186 KnowledgeSpread, 

187 [epistemic_canvas, chart], 

188 "Knowledge spread", 

189 model_params, 

190)