Coverage for .tox/p311/lib/python3.10/site-packages/scicom/randomletters/model.py: 0%

34 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2024-04-16 09:50 +0200

1import mesa 

2import numpy as np 

3import networkx as nx 

4 

5from .agents import LetterAgent, LetterNode 

6 

7 

8class LetterSpace(mesa.Model): 

9 """ 

10 Letter sending model class. Handles agent creation, placement and scheduling. 

11 

12 Each agent has a personal topic vector representing 

13 the shares the agent has of topics 1 to 3 with values 

14 between 0 and 1. 

15 Each agent has two different ranges, moveRange for deciding 

16 to move to another agents position, and letterRange to find 

17 potential correspondence partners. In addition a threshold 

18 value determines the necessary similarity between topic vectors 

19 to send a letter or not. 

20 

21 Received and send letters are kept track of with two additional 

22 internal variables. 

23 """ 

24 

25 def __init__( 

26 self, 

27 population=100, 

28 width=360, 

29 height=180, 

30 moveRange=20, 

31 letterRange=30, 

32 threshold=0.5, 

33 updateTopic=0.1, 

34 minSep=5 

35 ): 

36 """Create a new Letter model.""" 

37 self.population = population 

38 self.letterLedger = list() 

39 self.schedule = mesa.time.RandomActivation(self) 

40 self.G = nx.DiGraph() 

41 self.G.add_nodes_from([x for x in range(self.population)]) 

42 self.space = mesa.space.ContinuousSpace(width, height, True) 

43 self.grid = mesa.space.NetworkGrid(self.G) 

44 self.factors = dict(minSep=minSep, updateTopic=updateTopic, threshold=threshold, moveRange=moveRange, letterRange=letterRange) 

45 self.make_agents() 

46 self.running = True 

47 

48 def make_agents(self): 

49 """ 

50 Create self.population agents, with random positions and starting headings. 

51 """ 

52 for i, node in enumerate(self.G.nodes()): 

53 x = self.random.random() * self.space.x_max 

54 y = self.random.random() * self.space.y_max 

55 pos = np.array((x, y)) 

56 topicVec = np.array([np.random.random() for x in range(3)]) # Agent has random shares of topics 1 - 3 between 0 and 1. 

57 letter = LetterAgent( 

58 i, 

59 self, 

60 pos, 

61 topicVec, 

62 **self.factors 

63 ) 

64 nx.set_node_attributes(self.G, {i: {'numLettersSend': 0, 'numLettersReceived': 0}}) 

65 letterNode = LetterNode( 

66 i, 

67 self, 

68 topicVec, 

69 ) 

70 self.space.place_agent(letter, pos) 

71 self.grid.place_agent(letterNode, node) 

72 self.schedule.add(letter) 

73 

74 def step(self): 

75 self.schedule.step() 

76 nx.spring_layout(self.G) 

77 

78 def run(self, n): 

79 """Run the model for n steps.""" 

80 for _ in range(n): 

81 self.step()