File size: 7,492 Bytes
f6050ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237

################################################################################
# command line args
configpath = nothing
num_workers = 1
num_threads = 1
num_blas_threads = 1
chunksize = 1

args = ARGS

if length(args) == 0
	@warn "No command line arguments provided. Using default configuration."
end

# go through command line arguments and assign them
for (i, arg) in enumerate(args)
	if arg == "--config"
		if i + 1 <= length(args)
			global configpath = args[i+1]
		else
			println("Error: --config requires a file path argument.")
			exit(1)
		end
	end

	if arg == "--num_workers"
		if i + 1 <= length(args)
			global num_workers = parse(Int64, args[i+1])
		else
			println("Error: --num_workers requires an integer argument")
			exit(1)
		end
	end

	if arg == "--num_threads"
		if i + 1 <= length(args)
			global num_threads = parse(Int64, args[i+1])
		else
			println("Error: --num_threads requires an integer argument")
			exit(1)
		end
	end

	if arg == "--num_blas_threads"
		if i + 1 <= length(args)
			global num_blas_threads = parse(Int64, args[i+1])
		else
			println("Error: --num_blas_threads requires an integer argument")
			exit(1)
		end
	end

	if arg == "--chunksize"
		if i + 1 <= length(args)
			global chunksize = parse(Int64, args[i+1])
		else
			println("Error: --chunksize requires an integer argument")
			exit(1)
		end
	end

	if arg == "--help" || arg == "-h"
		println("Usage: julia create_data.jl [--config <path_to_config_file>]")
		println("Options:")
		println("  --config <path_to_config_file>  Path to the configuration file.")
		println("  --num_workers <int> number of processes to run on.")
		println("  --num_threads <int> number of threads **per process**")
		println(
			"  --num_blas_threads <int> number of threads the blas library should use. Only needed if you use LinearAlgebra.jl algorithms. This is independent of --num_threads!",
		)
		println(
			"  --chunksize <int> number of csets to generate and write in one go. Setting this to something smaller than the total number of csets to be generated will result in the dataset being generated in chunks so that it doesn't have to be kept in memory all at once.",
		)
		println("  --help, -h                      Show this help message.")
		exit(0)
	end
end

################################################################################
# we need the distributed package to add multiprocessing
using Distributed: Distributed

# add processes
Distributed.addprocs(
	num_workers,
	exeflags = ["--threads=$(num_threads)", "-O3", "--project=$(dirname(@__DIR__))"],
	enable_threaded_blas = true,
)

################################################################################
# import things we need everywhere
Distributed.@everywhere import QuantumGrav as QG
Distributed.@everywhere import LinearAlgebra
Distributed.@everywhere import CausalSets
Distributed.@everywhere import Random
Distributed.@everywhere import YAML

# include further packages that might be needed here. Make sure to add the @everywhere part to have them available on all workers
# e.g. Distributed.@everywhere import StatsBase

# set BLAS threads in linear algebra so things like eigendecomposition run multithreaded
Distributed.@everywhere LinearAlgebra.BLAS.set_num_threads($num_blas_threads)

################################################################################
# functions for data production

# encode type of csets numerically in data
Distributed.@everywhere encode_csettype = Dict(
	"polynomial" => 1,
	"complex_topology" => 2,
	"destroyed" => 3,
	"merged" => 4,
	"grid" => 5,
	"layered" => 6,
	"random" => 7,
	"merged_ambiguous" => 8,
	"destroyed_ambiguous" => 9,
)

Distributed.@everywhere function make_cset_data(worker_factory)::Dict{String, Any}

	# reference the globally build thing
	config = worker_factory.conf
	rng = worker_factory.rng
	n = rand(rng, worker_factory.npoint_distribution)

	@debug "    Generating cset data with $n atoms"
	cset_type = config["cset_type"]
	cset = nothing
	counter = 0
	while isnothing(cset) && counter < 20
		try
			cset, _ = worker_factory(cset_type, n, rng)
		catch e
			@warn "cset generator threw an exception: $(e)"
			cset = nothing
		end
		counter += 1
	end

	if isnothing(cset)
		throw(ErrorException("Couldn't create a working cset"))
	end

	@debug "    computing adjacency matrix"
	adj = QG.make_adj(cset, type = Matrix, eltype = UInt8)

	@debug "    make link matrix as transitive reduction of adjacency"
	linkmat = deepcopy(adj)
	QG.transitive_reduction!(linkmat)

	@debug "    compute degrees"

	# recently learned: because laplacian evs are equivalent to degrees for DAGs,
	# we can compute the degrees directly hence we go from O(N^3) to O(N^1)
    # not needed always, b/c we are mostly operating on link matrices
	# in_degrees_adj = sum(adj, dims = 1)[1, :]
	# out_degrees_adj = sum(adj, dims = 2)[:, 1]

	in_degrees_link = sum(linkmat, dims = 1)[1, :]
	out_degrees_link = sum(linkmat, dims = 2)[:, 1]

	@debug "    compute number of zero degrees"

    # not needed always, b/c we are mostly operating on link matrices
	# num_zero_degree_in = count(x -> abs(x) < 1e-9, in_degrees_adj)
	# num_zero_degree_out = count(x -> abs(x) < 1e-9, out_degrees_adj)

	num_zero_degree_in_link = count(x -> abs(x) < 1e-9, in_degrees_link)
	num_zero_degree_out_link = count(x -> abs(x) < 1e-9, out_degrees_link)

	@debug "    compute max path lengths"
	topoorder = 1:size(adj, 1)
	maxpaths_forward = zeros(Int, size(adj, 1))
	@sync Threads.@threads for i in topoorder
		max_path = QG.max_pathlen(linkmat, topoorder, i)
		maxpaths_forward[i] = max_path
	end

	topoorder = 1:size(adj, 2)
	maxpaths_backward = zeros(Int, size(adj, 2))
	@sync Threads.@threads for i in topoorder
		max_path = QG.max_pathlen(linkmat', topoorder, i)
		maxpaths_backward[i] = max_path
	end

	@debug "    compute causal set specific data"
	relation_numbers = CausalSets.count_relations(cset)

	chain_numbers = CausalSets.count_chains(cset, n)

	relation_dimension = CausalSets.estimate_relation_dimension(cset)

	spectrum = CausalSets.cardinality_abundances(cset)

	return Dict(
		"adj" => adj,
		"linkmat" => linkmat,
		"in_degrees_link" => in_degrees_link,
		"out_degrees_link" => out_degrees_link,
		"num_zero_degree_in_link" => num_zero_degree_in_link,
		"num_zero_degree_out_link" => num_zero_degree_out_link,
		"max_pathlen_forward_link" => maxpaths_forward,
		"max_pathlen_backward_link" => maxpaths_backward,
		"relation_numbers" => relation_numbers,
		"chain_numbers" => chain_numbers,
		"relation_dimension" => relation_dimension,
		"spectrum" => spectrum,
		"n" => n,
		"cset_type" => encode_csettype[cset_type],
		"manifold_like" => cset_type in
						   ["polynomial", "complex_topology", "merged_ambiguous", "destroyed_ambiguous"],
	)
end



################################################################################
# run the main dataproduction part
csettypes = [

]
try
	normalized = abspath(expanduser(configpath))
	loaded_config = YAML.load_file(normalized)
	YAML.write_file(joinpath(dirname(normalized), "temp_config.yaml"), loaded_config)
	@info "Causal set type to be generated: $(loaded_config["cset_type"]) with configpath $configpath"
	global configpath = joinpath(dirname(normalized), "temp_config.yaml")
	QG.produce_data(chunksize, configpath, make_cset_data)
catch e
	@error "An error occurred: $(e). Data production cancelled"
finally
	# don´t forget to remove workers processes after being done
	Distributed.rmprocs(Distributed.workers()...)
end