Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

generate_data.py 7.3 KB

You have to be logged in to leave a comment. Sign In
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
  1. import argparse
  2. import os
  3. import numpy as np
  4. from utils.data_utils import check_extension, save_dataset
  5. def generate_tsp_data(dataset_size, tsp_size):
  6. return np.random.uniform(size=(dataset_size, tsp_size, 2)).tolist()
  7. def generate_vrp_data(dataset_size, vrp_size):
  8. CAPACITIES = {
  9. 10: 20.,
  10. 20: 30.,
  11. 50: 40.,
  12. 100: 50.
  13. }
  14. return list(zip(
  15. np.random.uniform(size=(dataset_size, 2)).tolist(), # Depot location
  16. np.random.uniform(size=(dataset_size, vrp_size, 2)).tolist(), # Node locations
  17. np.random.randint(1, 10, size=(dataset_size, vrp_size)).tolist(), # Demand, uniform integer 1 ... 9
  18. np.full(dataset_size, CAPACITIES[vrp_size]).tolist() # Capacity, same for whole dataset
  19. ))
  20. def generate_op_data(dataset_size, op_size, prize_type='const'):
  21. depot = np.random.uniform(size=(dataset_size, 2))
  22. loc = np.random.uniform(size=(dataset_size, op_size, 2))
  23. # Methods taken from Fischetti et al. 1998
  24. if prize_type == 'const':
  25. prize = np.ones((dataset_size, op_size))
  26. elif prize_type == 'unif':
  27. prize = (1 + np.random.randint(0, 100, size=(dataset_size, op_size))) / 100.
  28. else: # Based on distance to depot
  29. assert prize_type == 'dist'
  30. prize_ = np.linalg.norm(depot[:, None, :] - loc, axis=-1)
  31. prize = (1 + (prize_ / prize_.max(axis=-1, keepdims=True) * 99).astype(int)) / 100.
  32. # Max length is approximately half of optimal TSP tour, such that half (a bit more) of the nodes can be visited
  33. # which is maximally difficult as this has the largest number of possibilities
  34. MAX_LENGTHS = {
  35. 20: 2.,
  36. 50: 3.,
  37. 100: 4.
  38. }
  39. return list(zip(
  40. depot.tolist(),
  41. loc.tolist(),
  42. prize.tolist(),
  43. np.full(dataset_size, MAX_LENGTHS[op_size]).tolist() # Capacity, same for whole dataset
  44. ))
  45. def generate_pctsp_data(dataset_size, pctsp_size, penalty_factor=3):
  46. depot = np.random.uniform(size=(dataset_size, 2))
  47. loc = np.random.uniform(size=(dataset_size, pctsp_size, 2))
  48. # For the penalty to make sense it should be not too large (in which case all nodes will be visited) nor too small
  49. # so we want the objective term to be approximately equal to the length of the tour, which we estimate with half
  50. # of the nodes by half of the tour length (which is very rough but similar to op)
  51. # This means that the sum of penalties for all nodes will be approximately equal to the tour length (on average)
  52. # The expected total (uniform) penalty of half of the nodes (since approx half will be visited by the constraint)
  53. # is (n / 2) / 2 = n / 4 so divide by this means multiply by 4 / n,
  54. # However instead of 4 we use penalty_factor (3 works well) so we can make them larger or smaller
  55. MAX_LENGTHS = {
  56. 20: 2.,
  57. 50: 3.,
  58. 100: 4.
  59. }
  60. penalty_max = MAX_LENGTHS[pctsp_size] * (penalty_factor) / float(pctsp_size)
  61. penalty = np.random.uniform(size=(dataset_size, pctsp_size)) * penalty_max
  62. # Take uniform prizes
  63. # Now expectation is 0.5 so expected total prize is n / 2, we want to force to visit approximately half of the nodes
  64. # so the constraint will be that total prize >= (n / 2) / 2 = n / 4
  65. # equivalently, we divide all prizes by n / 4 and the total prize should be >= 1
  66. deterministic_prize = np.random.uniform(size=(dataset_size, pctsp_size)) * 4 / float(pctsp_size)
  67. # In the deterministic setting, the stochastic_prize is not used and the deterministic prize is known
  68. # In the stochastic setting, the deterministic prize is the expected prize and is known up front but the
  69. # stochastic prize is only revealed once the node is visited
  70. # Stochastic prize is between (0, 2 * expected_prize) such that E(stochastic prize) = E(deterministic_prize)
  71. stochastic_prize = np.random.uniform(size=(dataset_size, pctsp_size)) * deterministic_prize * 2
  72. return list(zip(
  73. depot.tolist(),
  74. loc.tolist(),
  75. penalty.tolist(),
  76. deterministic_prize.tolist(),
  77. stochastic_prize.tolist()
  78. ))
  79. if __name__ == "__main__":
  80. parser = argparse.ArgumentParser()
  81. parser.add_argument("--filename", help="Filename of the dataset to create (ignores datadir)")
  82. parser.add_argument("--data_dir", default='data', help="Create datasets in data_dir/problem (default 'data')")
  83. parser.add_argument("--name", type=str, required=True, help="Name to identify dataset")
  84. parser.add_argument("--problem", type=str, default='all',
  85. help="Problem, 'tsp', 'vrp', 'pctsp' or 'op_const', 'op_unif' or 'op_dist'"
  86. " or 'all' to generate all")
  87. parser.add_argument('--data_distribution', type=str, default='all',
  88. help="Distributions to generate for problem, default 'all'.")
  89. parser.add_argument("--dataset_size", type=int, default=10000, help="Size of the dataset")
  90. parser.add_argument('--graph_sizes', type=int, nargs='+', default=[20, 50, 100],
  91. help="Sizes of problem instances (default 20, 50, 100)")
  92. parser.add_argument("-f", action='store_true', help="Set true to overwrite")
  93. parser.add_argument('--seed', type=int, default=1234, help="Random seed")
  94. opts = parser.parse_args()
  95. assert opts.filename is None or (len(opts.problems) == 1 and len(opts.graph_sizes) == 1), \
  96. "Can only specify filename when generating a single dataset"
  97. distributions_per_problem = {
  98. 'tsp': [None],
  99. 'vrp': [None],
  100. 'pctsp': [None],
  101. 'op': ['const', 'unif', 'dist']
  102. }
  103. if opts.problem == 'all':
  104. problems = distributions_per_problem
  105. else:
  106. problems = {
  107. opts.problem:
  108. distributions_per_problem[opts.problem]
  109. if opts.data_distribution == 'all'
  110. else [opts.data_distribution]
  111. }
  112. for problem, distributions in problems.items():
  113. for distribution in distributions or [None]:
  114. for graph_size in opts.graph_sizes:
  115. datadir = os.path.join(opts.data_dir, problem)
  116. os.makedirs(datadir, exist_ok=True)
  117. if opts.filename is None:
  118. filename = os.path.join(datadir, "{}{}{}_{}_seed{}.pkl".format(
  119. problem,
  120. "_{}".format(distribution) if distribution is not None else "",
  121. graph_size, opts.name, opts.seed))
  122. else:
  123. filename = check_extension(opts.filename)
  124. assert opts.f or not os.path.isfile(check_extension(filename)), \
  125. "File already exists! Try running with -f option to overwrite."
  126. np.random.seed(opts.seed)
  127. if problem == 'tsp':
  128. dataset = generate_tsp_data(opts.dataset_size, graph_size)
  129. elif problem == 'vrp':
  130. dataset = generate_vrp_data(
  131. opts.dataset_size, graph_size)
  132. elif problem == 'pctsp':
  133. dataset = generate_pctsp_data(opts.dataset_size, graph_size)
  134. elif problem == "op":
  135. dataset = generate_op_data(opts.dataset_size, graph_size, prize_type=distribution)
  136. else:
  137. assert False, "Unknown problem: {}".format(problem)
  138. print(dataset[0])
  139. save_dataset(dataset, filename)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...