예제 #1
0
    def __init__(self, goal, w, h, num_poly, num_vertex, comparison_method,
                 savepoints, outdirectory, iterations, pop_size, nmax, mmax):
        super().__init__(goal, w, h, num_poly, num_vertex, comparison_method,
                         savepoints, outdirectory)
        self.iterations = iterations
        self.pop_size = pop_size
        self.nmax = nmax
        self.mmax = mmax
        self.evaluations = 0
        self.pop = p.Population(self.pop_size)
        self.best = None
        self.worst = None

        # define data header for hillclimber
        self.data.append([
            "Polygons", "Generation", "Evaluations", "bestMSE", "worstMSE",
            "medianMSE", "meanMSE"
        ])

        # fill population with random polygon drawings
        for i in range(self.pop_size):
            alex = c.Constellation(0, i, None, self.w, self.h)
            alex.initialize_genome(self.num_poly, self.num_vertex)
            alex.img_to_array()
            alex.calculate_fitness_mse(self.goalpx)
            self.pop.add_organism(alex)
예제 #2
0
    def run(self):
        for i in range(self.iterations):
            state = c.Constellation(0, 0, None, self.w, self.h)
            state.polygons = self.best.deepish_copy_state()
            state.id = i
            state.random_mutation(1)
            state.img_to_array()

            if self.comparison_method == "MSE":
                state.calculate_fitness_mse(self.goalpx)

            if state.fitness <= self.best.fitness:
                self.best = copy.deepcopy(state)

            # Store data per iteration
            if i in self.savepoints:
                self.best.save_img(self.outdirectory)
                self.best.save_polygons(self.outdirectory)
                self.save_data(
                    [int(self.num_poly), i,
                     round(self.best.fitness, 2)])

            # If checkpoint stepsize is given store checkpoints
            if self.stepsize > 0:
                # Store data per MSE improvement (for better movies etc.)
                if self.best.fitness <= self.check_point:
                    self.best.save_img(self.checks_out)
                    self.best.save_polygons(self.checks_out)
                    while self.best.fitness <= self.check_point:
                        self.check_point -= self.stepsize

        self.best.save_img(self.outdirectory)
        self.best.save_polygons(self.outdirectory)
        self.save_data([int(self.num_poly), i, round(self.best.fitness, 2)])
예제 #3
0
    def run(self):
        for i in range(1, self.iterations):
            state = c.Constellation(0, i, None, self.w, self.h)
            state.polygons = self.current.deepish_copy_state()
            state.random_mutation(1)
            state.img_to_array()

            state.calculate_fitness_mse(self.goalpx)

            dE = state.fitness - self.current.fitness
            T = self.cooling_geman(i)

            acceptance = self.acceptance_probability(dE, T)

            if random() < acceptance:
                self.current.genome = state.deepish_copy_state()
                self.current.fitness = state.fitness

            if self.current.fitness < self.best.fitness:
                self.best = copy.deepcopy(self.current)

            if i in self.savepoints:
                self.best.generation = i
                self.best.save_img(self.outdirectory)

            self.save_data(
                [self.num_poly, i, self.best.fitness, self.current.fitness])
예제 #4
0
    def generation(self, gen):
        counter = 0
        for organism in self.pop.organisms[:]:
            for i in range(organism.nr):
                state = c.Constellation(gen, counter, organism.name(), self.w,
                                        self.h)
                state.polygons = organism.deepish_copy_state()
                state.random_mutation(organism.d)
                state.img_to_array()
                state.calculate_fitness_mse(self.goalpx)

                self.pop.add_organism(state)
                counter += 1

        self.evaluations += counter
예제 #5
0
    def __init__(self, goal, w, h, num_poly, num_vertex, comparison_method,
                 savepoints, outdirectory, iterations):
        super().__init__(goal, w, h, num_poly, num_vertex, comparison_method,
                         savepoints, outdirectory)
        self.iterations = iterations

        # initializing organism
        self.best = c.Constellation(0, 0, None, self.w, self.h)
        self.best.initialize_genome(self.num_poly, num_vertex)
        self.best.img_to_array()
        self.best.calculate_fitness_mse(self.goalpx)

        self.current = copy.deepcopy(self.best)

        # define data header for SA
        self.data.append(["Polygons", "Iteration", "bestMSE", "currentMSE"])
예제 #6
0
    def __init__(self, goal, w, h, num_poly, num_vertex, comparison_method,
                 savepoints, outdirectory, iterations, stepsize):
        # Initialize Algorithm class
        super().__init__(goal, w, h, num_poly, num_vertex, comparison_method,
                         savepoints, outdirectory, stepsize)
        self.iterations = iterations

        # initializing solution datastructure
        self.best = c.Constellation(0, 0, None, self.w, self.h)
        self.best.initialize_random_vertices(int(num_vertex / num_poly),
                                             num_vertex)
        self.best.img_to_array()
        self.best.calculate_fitness_mse(self.goalpx)
        self.check_point = self.best.fitness

        # define data header for hillclimber
        self.data.append(["Polygons", "Iteration", "MSE"])
예제 #7
0
def hint_constellation(cfg):
    # 1. Redis
    redis_ref = constellation.ImageReference("library", "redis", cfg.redis_tag)
    redis_mounts = [constellation.ConstellationMount("redis", "/data")]
    redis_args = ["--appendonly", "yes"]
    redis = constellation.ConstellationContainer("redis",
                                                 redis_ref,
                                                 mounts=redis_mounts,
                                                 args=redis_args,
                                                 configure=redis_configure)

    # 2. The db
    db_ref = constellation.ImageReference("mrcide", "hint-db", cfg.db_tag)
    db_mounts = [constellation.ConstellationMount("db", "/pgdata")]
    db = constellation.ConstellationContainer("db",
                                              db_ref,
                                              mounts=db_mounts,
                                              configure=db_configure)

    # 3. hintr
    hintr_ref = cfg.hintr_ref
    hintr_args = [
        "--workers=0", "--results-dir=/results", "--prerun-dir=/prerun"
    ]
    hintr_mounts = [
        constellation.ConstellationMount("uploads", "/uploads"),
        constellation.ConstellationMount("results", "/results"),
        constellation.ConstellationMount("prerun", "/prerun")
    ]
    hintr_env = {"REDIS_URL": "redis://{}:6379".format(redis.name)}
    if cfg.hintr_use_mock_model:
        hintr_env["USE_MOCK_MODEL"] = "true"
    hintr_ports = [8888] if cfg.hint_expose else None
    hintr = constellation.ConstellationContainer("hintr",
                                                 hintr_ref,
                                                 args=hintr_args,
                                                 mounts=hintr_mounts,
                                                 ports=hintr_ports,
                                                 environment=hintr_env)

    # 4. hint
    hint_ref = constellation.ImageReference("mrcide", "hint", cfg.hint_tag)
    hint_mounts = [
        constellation.ConstellationMount("uploads", "/uploads"),
        constellation.ConstellationMount("config", "/etc/hint")
    ]
    hint_ports = [8080] if cfg.hint_expose else None
    hint = constellation.ConstellationContainer("hint",
                                                hint_ref,
                                                mounts=hint_mounts,
                                                ports=hint_ports,
                                                configure=hint_configure)

    # 5. proxy
    proxy_ref = constellation.ImageReference("reside", "proxy-nginx", "latest")
    proxy_ports = [cfg.proxy_port_http, cfg.proxy_port_https]
    proxy_args = [
        "hint:8080", cfg.proxy_host,
        str(cfg.proxy_port_http),
        str(cfg.proxy_port_https)
    ]
    proxy = constellation.ConstellationContainer("proxy",
                                                 proxy_ref,
                                                 ports=proxy_ports,
                                                 args=proxy_args,
                                                 configure=proxy_configure)

    # 6. calibrate worker
    worker_ref = cfg.hintr_worker_ref
    calibrate_worker_args = ["--calibrate-only"]
    calibrate_worker = constellation.ConstellationService(
        "calibrate_worker",
        worker_ref,
        cfg.hintr_calibrate_workers,
        args=calibrate_worker_args,
        mounts=hintr_mounts,
        environment=hintr_env)

    # 7. hintr workers
    worker = constellation.ConstellationService("worker",
                                                worker_ref,
                                                cfg.hintr_workers,
                                                mounts=hintr_mounts,
                                                environment=hintr_env)

    containers = [db, redis, hintr, hint, proxy, calibrate_worker, worker]

    obj = constellation.Constellation("hint",
                                      cfg.prefix,
                                      containers,
                                      cfg.network,
                                      cfg.volumes,
                                      data=cfg,
                                      vault_config=cfg.vault)

    return obj
예제 #8
0
파일: mcgalaxy.py 프로젝트: mkai5/McGalaxy
	def handle_input(str_in):
		#pull list of valid constellations from constellation.py
		con_list = constellation.Constellation.constellations
		#by default, use only Alaska McDonald's
		limited = True
		#loop if given empty input
		if (str_in.isspace() or (str_in=="")):
			return True
		#check for exit condition
		elif ((str_in=="x") or (str_in=="exit")):
			return False
		#check for help condition
		elif ((str_in=="h") or (str_in=="help")):
			#print help message
			with pd.option_context('display.max_rows', None, 'display.max_columns', None):
					print("McGalaxy supports the following stars:")
					print (fitter.Fitter.import_stars()["Proper name"].to_string(index=False))
					print ("Any of these stars can be named by proper name, in any sequence")
					print ("McGalay also supports the following constellations:")
					print (con_list)
					print ("Make sure to only use whitespace to delimit your inputs!")
					print ("""Additionally, since the number of McDonald's locations is so large
as to be prohibitive for searching, McGalaxy automatically searches only within Alaska. To
expand your search to all McDonald's in the US and Canada, add the flag "-all" anywhere
within your input, but be warned! It'll take a long time on powerful hardware!""")
			return True
		#otherwise
		else:
			#split the string
			str_list = str_in.split()
			#access its length and store locally
			str_list_len = len(str_list)
			#import star data
			star_data = fitter.Fitter.import_stars()
			#initialize an empty series to hold input stars
			con_data = pd.Series([])
			#initialize index counter to check for two-word stars
			i=0

			#cycle through inputs
			for s in str_list:
				#unlimit is flag present
				if (s=="-all"):
					limited = False
				#if s in a known constellation, treat automatically use
				#	constellation data
				elif (s in con_list):
					#unlimit if flag present
					if ("-all" in str_list):
						limited=False
					#look up constellation data, construct constellation
					con_data = constellation.Constellation.constellation_lookup(s,star_data)
					star_list = con_data['Obj'].tolist()
					feeder_con = constellation.Constellation(star_list)
					#construct McDonald's list
					if (limited):
						feeder_mcds = mcds_con.McDs_con(fitter.Fitter.import_McDs().tolist()[:31])
					else:
						feeder_mcds = mcds_con.McDs_con(fitter.Fitter.import_McDs().tolist())
						#remove "-all" flag to make printing prettier
						str_list.remove("-all")
					#print information
					print("The McDonalds that most resemble {} are:".format(feeder_con.list_names()))
					#find best fit
					fitter.Fitter.find_best_fit(feeder_con,feeder_mcds).print_info()
					print('''Input "x" or "exit" to exit or continue exploring the McGalaxy!''')
					return True
				#otherwise, if star is input
				else:
					#append either the star matching the input string, or the
					#	input string and next input string (so two word stars
					# 	can be input)
					con_data = con_data.append(star_data.loc[
						(star_data["Proper name"] == s)])
					if ((i + 1) < str_list_len):
						con_data = con_data.append(star_data.loc[
							(star_data["Proper name"] == (s + " " 
								+ str_list[i+1]))])
				#increment index
				i=i+1

			#build star list
			star_list = con_data['Obj'].tolist()
			#check list has at least 3 entries
			if (len(star_list)<3):
				print("Please input 3 or more valid stars")
				return True
			#build constellation
			feeder_con = constellation.Constellation(star_list)
			#build McDonald's
			if (limited):
				feeder_mcds = mcds_con.McDs_con(fitter.Fitter.import_McDs().tolist()[:31])
			else:
				feeder_mcds = mcds_con.McDs_con(fitter.Fitter.import_McDs().tolist())
				str_list.remove("-all")
			print("The McDonalds that most resemble {} are:".format(feeder_con.list_names()))
			#check for best fit
			fitter.Fitter.find_best_fit(feeder_con,feeder_mcds).print_info()
			print('''Input "x" or "exit" to exit or continue exploring the McGalaxy!''')
			return True