distributed-kebab/kebab_worker/main.py

89 lines
2.2 KiB
Python
Raw Normal View History

2020-09-24 16:14:42 +02:00
import multiprocessing
2020-09-24 15:59:48 +02:00
import os
2020-09-24 16:14:42 +02:00
import requests
2020-09-24 15:59:48 +02:00
2020-09-24 16:14:42 +02:00
def worker(outqueue, id):
2020-09-24 16:17:12 +02:00
print(f"Worker {id} is preparing...")
2020-09-24 16:14:42 +02:00
import numpy as np
import networkx as nx
with open("/dkebab/GBA1000.txt") as f:
n = int(f.readline()) # pontok száma
m = int(f.readline()) # élek száma
A = [[0] * n for _ in range(n)] # táblázat, ahol az élek helyén 1 van, ammeg 0
for _ in range(m):
[u, v] = map(int, f.readline().split())
A[u][v] = 1
A[v][u] = 1
input_graph = nx.Graph(np.array(A))
def max_comp_size(G):
return max([len(c) for c in nx.connected_components(G)])
2020-09-24 16:17:12 +02:00
print(f"Worker {id} is working...")
2020-09-24 16:14:42 +02:00
while True:
del_list = []
G = input_graph.copy()
target = len(G.nodes) / 2
while max_comp_size(G) > target:
u = np.random.choice(G.nodes)
if u not in del_list:
del_list.append(u)
G.remove_node(u)
outqueue.put(del_list)
2020-09-24 16:16:29 +02:00
def worker_watchdog(outqueue, id):
while True:
try:
worker(outqueue, id)
2020-09-24 16:33:48 +02:00
except KeyboardInterrupt:
break
2020-09-24 16:16:29 +02:00
except:
print(f"Worker {id} died! Restarting...")
2020-09-24 16:33:48 +02:00
print(f"Worker {id} exited!")
def denumpy_result(numpy_type) -> list:
denumyed = []
for i in numpy_type:
denumyed = int(i)
return denumyed
2020-09-24 16:16:29 +02:00
2020-09-24 15:59:48 +02:00
def main():
2020-09-24 16:14:42 +02:00
target_url = os.environ['TARGET_URL']
multiprocessing.set_start_method('spawn')
outqueue = multiprocessing.Queue()
processes = []
for id in range(os.cpu_count()):
2020-09-24 16:16:29 +02:00
p = multiprocessing.Process(target=worker_watchdog, args=(outqueue, id))
2020-09-24 16:14:42 +02:00
p.start()
processes.append(p)
2020-09-24 16:21:28 +02:00
local_best = 1000
2020-09-24 16:14:42 +02:00
while True:
result = outqueue.get()
2020-09-24 16:21:28 +02:00
result_score = len(result)
if result_score < local_best:
print(f"New local best found: {local_best} -> {result_score}")
local_best = result_score
try:
2020-09-24 16:33:48 +02:00
r = requests.post(target_url, json=denumpy_result(result))
2020-09-24 16:21:28 +02:00
r.raise_for_status()
except (ConnectionError, requests.HTTPError) as e:
print(f"Error while posting result: {e}")
2020-09-24 15:59:48 +02:00
if __name__ == '__main__':
main()