コード例 #1
0
    def __init__(self, operator, context):

        seed(operator.seed)

        if operator.create_empty and not operator.convert:

            create.empty(operator, context)

        if operator.uniform:

            if operator.amount > 1:

                operator.depth_locations = [
                    operator.depth * (index / (operator.amount - 1))
                    for index in range(operator.amount)
                ]

        for index in range(operator.amount):

            thickness = random_float(operator.thickness_min,
                                     operator.thickness_max)

            pipe = create.pipe(operator, context, index, thickness)

            self.pipe(operator, context, pipe, index, thickness)
コード例 #2
0
		def straight(self, operator, pipe, spline, thickness):

			spline.points[0].co.x = self.keep_inside(random_float(-operator.width * 0.5, operator.width * 0.5), thickness, operator.width * 0.5)

			spline.points.add(count=1)

			spline.points[-1].co.x = spline.points[-2].co.x
			spline.points[-1].co.y = operator.height
コード例 #3
0
		def depth(self, operator, context, pipe, depth, index, thickness):

			pipe.location.y += self.keep_inside(random_float(-depth, depth), thickness, depth)

			if operator.uniform:

				pipe.location.y = context.space_data.cursor_location.y

				if operator.amount > 1:

					pipe.location.y += operator.depth_locations[index] - operator.depth * 0.5
コード例 #4
0
        def depth(self, ot, context, pipe, depth, index, thickness):
            pipe.location.y += self.keep_inside(random_float(-depth, depth),
                                                thickness, depth)

            if ot.uniform:

                pipe.location.y = ot.location.y

                if ot.amount > 1:

                    pipe.location.y += ot.depth_locations[
                        index] - ot.depth * 0.5
コード例 #5
0
    def __init__(self, ot, context):
        seed(ot.seed)

        create.empty(ot, context)

        if ot.uniform:
            if ot.amount > 1:
                ot.depth_locations = [
                    ot.depth * (index / (ot.amount - 1))
                    for index in range(ot.amount)
                ]

        for index in range(ot.amount):
            thickness = random_float(ot.thickness_min, ot.thickness_max)
            if ot.thickness_min > ot.thickness_max:
                thickness = ot.thickness_max

            pipe = create.pipe(ot, context, index, thickness)

            self.pipe(ot, context, pipe, index, thickness)
コード例 #6
0
ファイル: utils.py プロジェクト: mkbreuer/ToolPlus
	def __init__(self, operator, context):

		seed(operator.seed)

		if operator.create_empty and not operator.convert:

			create.empty(operator, context)

		if operator.uniform:

			if operator.amount > 1:

				operator.depth_locations = [operator.depth * (index / (operator.amount - 1)) for index in range(operator.amount)]

		for index in range(operator.amount):

			thickness = random_float(operator.min, operator.max)

			pipe = create.pipe(operator, context, index, thickness)

			self.pipe(operator, context, pipe, index, thickness)
コード例 #7
0
ファイル: __init__.py プロジェクト: weisk/nichtparasoup
 def _random_weight(self) -> _CrawlerWeight:
     return random_float(0, sum(crawler.weight for crawler in self))
コード例 #8
0
            def get_corners(self, operator, context, pipe, spline, thickness):

                keep_inside = generate.pipe.keep_inside

                spline.points[-1].co.x = keep_inside(
                    random_float(-operator.width * 0.5, operator.width * 0.5),
                    thickness, operator.width * 0.5)

                last_x = spline.points[-1].co.x
                last_y = 0.0

                first_pass = True

                pipe_corners = [[last_x, last_y]]

                while last_y < operator.height:

                    if first_pass:

                        coord_y = keep_inside(
                            last_y + random_float(operator.length_y_min,
                                                  operator.length_y_max) * 0.5,
                            thickness, operator.height)

                        first_pass = False

                    else:

                        coord_y = keep_inside(
                            last_y + random_float(operator.length_y_min,
                                                  operator.length_y_max),
                            thickness, operator.height)

                    if coord_y + min(operator.length_y_min, operator.
                                     length_y_max) * 0.5 > operator.height:

                        pipe_corners.append([last_x, operator.height])

                        break

                    length_x_min = operator.length_x_min
                    length_x_max = operator.length_x_max

                    if last_x - length_x_min - thickness <= -operator.width * 0.5:

                        left = False

                    elif last_x + length_x_min + thickness >= operator.width * 0.5:

                        left = True

                    else:

                        left = choice([True, False])

                    thickness = -thickness if left else thickness
                    length_x_min = -length_x_min if left else length_x_min
                    length_x_max = -length_x_max if left else length_x_max

                    coord_x = keep_inside(
                        last_x + random_float(length_x_min, length_x_max),
                        thickness, operator.width * 0.5)

                    pipe_corners.append([last_x, coord_y, True, left])

                    last_x = coord_x
                    last_y = coord_y

                    pipe_corners.append([last_x, last_y, False, left])

                return pipe_corners
コード例 #9
0
ファイル: mclass.py プロジェクト: gerg0/MouseCandy
	def run(self):
		super(Pav,self).run()
		
		import time
		from progressbar import progress
		from random import uniform as random_float

		#Reset since start stopwatch
		self.since_start.reset()
		
		#Log start
		self.log.append((0,0,"Start"))
		
		#Start doing the tasks
		current_task = 0
		for current_task in range(self.action_count):
			
			#Update progressbar
			progress(current_task*100/self.action_count)
			
			#Execute stimulus command
			self.stimulus()
			
			#Reset since stim stopwatch
			self.since_stim.reset()
			
			#Log the stimulus
			self.log.append((self.since_start.value(), 0, "Stimulus"))
			print "Stimulus at	"+ str(self.since_start)

			#Wait until the stim is over. Detect premature licks.
			self.stim_timer.reset()
			while self.stim_timer.is_running():
				time.sleep(0.001)
				
				if self.sensor.detected():
					self.log.append((self.since_start.value(), self.since_stim.value(), "Lick (premature)"))
					print "Lick at	" + str(self.since_start) +"	Since stim.	" +str(self.since_stim)+ " //Premature"
					
				
				
			#Give water
			self.water_valve.pulse()	
			
			#Log the water
			self.log.append((self.since_start.value(), self.since_stim.value(), "Water"))
			print "Water at	" + str(self.since_start) +"	Since stim.	" +str(self.since_stim)
			
			#Generate random wait time
			wait_time = random_float(self.wait_time_min,self.wait_time_max)
			
			#Log wait time
			self.wait_times.append(wait_time)
			print "Wait time	"+mtools.toString(wait_time)+" sec"
			
			#Set new time and reset the main timer
			self.main_timer.set(wait_time)
			self.main_timer.reset()
			
			#Wait until next stim. Log licks
			while self.main_timer.is_running():
				time.sleep(0.001)
				
				if self.sensor.detected():
					self.log.append((self.since_start.value(), self.since_stim.value(), "Lick"))
					print "Lick at	" + str(self.since_start) +"	Since stim.	" +str(self.since_stim)
				
		
		
		#Update progressbar
		progress(100)
		
		#Log end of project
		self.log.append((self.since_start.value(), self.since_stim.value(), "End"))
		
		#Calculate wait time statistics
		average_wait_time = mtools.avg(self.wait_times)
		wait_time_deviation = mtools.dev(self.wait_times)
		
		#Create specific logs
		licks_log = filter(lambda record: record[2]=="Lick" or record[2]=="Lick (premature)", self.log)
		reaction_times = map(lambda record: record[1], licks_log)
		
		#Calculate lick statistics
		average_reaction_time = mtools.avg(reaction_times)
		reaction_time_deviation = mtools.dev(reaction_times)
		
		
		#Create log files
		main_logfile = open("/MouseCandy/run/log.txt", "w")
		licks_logfile = open("/MouseCandy/run/licks.csv", "w")
		
		#Write logfile headers
		main_logfile.write(str(self)+"\n")
		main_logfile.write("Average wait time: " + mtools.toString(average_wait_time, padded=False) +" sec\n")
		main_logfile.write("Wait time deviation: " + mtools.toString(wait_time_deviation, padded=False) +" sec\n")
		main_logfile.write("Average reaction time: " + mtools.toString(average_reaction_time, padded=False) +" sec\n")
		main_logfile.write("Reaction time deviation: " + mtools.toString(reaction_time_deviation, padded=False) +" sec\n\n")
				
		licks_logfile.write("time[s],since_last_stim[s]\n")
		
		#Write records into log files
		for record in self.log:
			main_logfile.write(mtools.toString(record[0])+"	"+mtools.toString(record[1])+"	"+record[2]+"\n")
		
		for record in licks_log:
			licks_logfile.write(str(record[0])+","+str(record[1])+"\n")
		
		main_logfile.close()
		licks_logfile.close()
		
		#Create zipfiles
		import os
		zipname = mtools.CRC32_from_file("/MouseCandy/run/log.txt")
		os.system("zip -j /MouseCandy/logs/"+zipname+".zip /MouseCandy/run/log.txt /MouseCandy/run/licks.csv")
		os.remove("/MouseCandy/run/log.txt")
		os.remove("/MouseCandy/run/licks.csv")
		
		os.system("zipnote /MouseCandy/logs/"+zipname+".zip > /MouseCandy/logs/temp_notes.txt")
		
		notesfile = open("/MouseCandy/logs/temp_notes.txt", "a")
		tags = str(self).split("\n")
		tags = tags[0]
		notesfile.write(tags+"\n")
		notesfile.write(self.name)
		notesfile.close()
		
		os.system("zipnote -w /MouseCandy/logs/"+zipname+".zip < /MouseCandy/logs/temp_notes.txt")
		os.remove("/MouseCandy/logs/temp_notes.txt")
コード例 #10
0
ファイル: main.py プロジェクト: ianling/direct-democracy
def generate_unique_id(length=15):
    id = bytearray()
    for i in range(length):
        id.append(int(random_float(0,255)))
    return urlsafe_b64encode(id).decode("ASCII")
コード例 #11
0
def simulated_annealing(**kwargs):
    """
    Creates a random individual from which simulated annealing is used to generate a population.

    :param kwargs: Dictionary of expected parameters:
    - (int) 'node_count': Number of nodes used in the problem. Includes depot nodes and optional nodes.
    - (list<int>) 'depot_nodes': List of depot nodes used in the problem.
    - (list<int>) 'optional_nodes': List of optional nodes used in the problem.
    - (int) 'vehicle_count': Number of vehicles used in the problem.
    - (int) 'population_count': Number of individuals in the population.
    - (int) 'minimum_cpu_time': CPU time that is allotted for the initialization of an individual solution.
      The purpose of this is to stop the algorithm if that is unable to create a valid individual
      (or it takes too long).
    - (dict) 'validation_args': Dictionary of arguments that are used in individual validations. See
      validation functions for what is expected of them.
    - (dict) 'evaluation_args': Dictionary of arguments that are used in individual evaluations. See
      evaluation functions for what is expected of them.
    - (int) 'sa_iteration_count': Number of iterations that SA is allowed to go for.
    - (int) 'sa_initial_temperature': Initial temperature, acts as how easily a solution could be accepted.
    - (float) 'sa_p_coeff': Annealing coefficient.
    - (bool) 'maximize': Flag that determines whether the objective to maximize or minimize.

    :return: List of randomly generated individuals, representing the population. (list<VRP>)
    """

    population = []

    node_count = kwargs["node_count"]
    depot_nodes = kwargs["depot_nodes"]
    optional_nodes = kwargs["optional_nodes"]
    vehicle_count = kwargs["vehicle_count"]
    population_count = kwargs["population_count"]
    minimum_cpu_time = kwargs["minimum_cpu_time"]
    validation_args = kwargs["validation_args"]
    evaluation_args = kwargs["evaluation_args"]
    sa_iteration_count = kwargs["sa_iteration_count"]
    sa_initial_temperature = kwargs["sa_initial_temperature"]
    sa_p_coeff = kwargs["sa_p_coeff"]

    if "maximize" in kwargs:
        if kwargs["maximize"] is True:
            reverse_sort = True
            max_factor = 1
        else:
            reverse_sort = False
            max_factor = -1
    else:
        reverse_sort = False
        max_factor = -1

    population_timer = Timer()
    individual_timer = Timer(goal=minimum_cpu_time)

    def check_goal(timer):
        return timer.past_goal()

    population_timer.start()
    individual_timer.start()

    individual_args = {
        "node_count": node_count,
        "depot_nodes": depot_nodes,
        "optional_nodes": optional_nodes,
        "vehicle_count": vehicle_count,
        "failure_msg":
        "(Simulated Annealing - Random) Individual initialization is taking too long.",
        "individual_timer": individual_timer,
        "check_goal": check_goal,
        "validation_args": validation_args,
        "evaluation_args": evaluation_args
    }
    candidate_individual, individual_msg = random_valid_individual(
        **individual_args)
    if candidate_individual is None:
        return None, individual_msg
    individual_timer.reset()

    population.append(candidate_individual)
    guide_individual = deepcopy(candidate_individual)
    candidate_individual = deepcopy(candidate_individual)
    guide_individual.assign_id()
    candidate_individual.assign_id()

    for n in range(1, sa_iteration_count):
        # Once all of the iterations have been exhausted, the state of the population is checked.
        # If the population quota is not met, random individuals are created to make up for it.

        valid_individual = False
        while valid_individual is False:
            # Usually only one change is considered in SA. In this case, there is a possibility
            # that one change can invalidate the individual. For that reason, we'll keep changing it
            # until it is valid.
            VRP.mutation_operator[randint(0,
                                          len(VRP.mutation_operator) -
                                          1)](candidate_individual)
            for validator in VRP.validator:
                valid_individual, validation_msg = validator(
                    candidate_individual, **validation_args)
                if valid_individual is False:
                    break

            # If the solution is invalid, mutate it again.
            candidate_individual.valid = valid_individual

            # Should solution-finding via mutations take too long, it is halted here.
            if check_goal(individual_timer):
                return None, "(Simulated Annealing) Individual initialization is taking too long."

        # Once the solution is valid, evaluate it.
        candidate_individual.fitness = VRP.evaluator(candidate_individual,
                                                     **evaluation_args)

        # Calculate temperature for current iteration and generate a "pass requirement".
        temperature = sa_initial_temperature * (
            1 - (n - 1) / (sa_iteration_count - 1))**sa_p_coeff
        pass_requirement = random_float()

        # With the fitness values of both guide and candidate, SA probability can be calculated.
        try:
            sa_probability = exp(
                max_factor *
                (candidate_individual.fitness - guide_individual.fitness) /
                temperature)
        except OverflowError:
            sa_probability = float("inf")

        if sa_probability >= pass_requirement:
            # Mutation has been selected as the new guide.
            population.append(candidate_individual)

            # Delete old individuals if current population is too large.
            if len(population) > population_count:
                del population[0]

            guide_individual = deepcopy(candidate_individual)
            guide_individual.assign_id()
            candidate_individual = deepcopy(guide_individual)
            outcome_str = "Selected"
        else:
            # Mutation has been rejected. Revert to guide individual.
            candidate_individual = deepcopy(guide_individual)
            outcome_str = "Discarded"

        print("Iteration: {} |"
              " Fitness: {:> .5f} |"
              " Temperature: {:> .5f} |"
              " Selection Probability: {:> .5f} |"
              " Outcome: {}".format(n, candidate_individual.fitness,
                                    temperature, sa_probability, outcome_str))

        # Reset individual timer upon completing an iteration.
        individual_timer.reset()

    population_timer.stop()
    individual_timer.stop()

    msg = "(Simulated Annealing) Population initialization OK (Time taken: {} ms)\n" \
          "- Result Population Size: {}" \
        .format(population_timer.elapsed(), len(population))

    # If resulting population is too small, add missing individuals by
    # generating random individuals.
    if len(population) < population_count:
        missing_population_count = population_count - len(population)
        missing_population, msg0 = random(
            node_count=node_count,
            depot_nodes=depot_nodes,
            optional_nodes=optional_nodes,
            vehicle_count=vehicle_count,
            population_count=missing_population_count,
            minimum_cpu_time=minimum_cpu_time,
            validation_args=validation_args,
            evaluation_args=evaluation_args)
        population = population + missing_population

    population.sort(key=attrgetter("fitness"), reverse=reverse_sort)
    return population, msg
コード例 #12
0
def random_valid_individual(**kwargs):
    """
    Creates a random individual, the solution of which has been both validated
    and evaluated.

    :param kwargs: Dictionary of expected parameters:
    - (int) 'node_count': Number of nodes used in the problem. Includes depot nodes and optional nodes.
    - (list<int>) 'depot_nodes': List of depot nodes used in the problem.
    - (list<int>) 'optional_nodes': List of optional nodes used in the problem.
    - (int) 'vehicle_count': Number of vehicles used in the problem.
    - (str) 'failure_msg': Text to represent if individual creation is taking too long.
    - (Timer) 'individual_timer': Timer based on specified minimum CPU time. Should be started before
      calling this function.
    - (function) 'check_goal': Convenience function that checks whether minimum CPU time has passed.
    - (dict) 'validation_args': Dictionary of arguments that are used in individual validations. See
      validation functions for what is expected of them.
    - (dict) 'evaluation_args': Dictionary of arguments that are used in individual evaluations. See
      evaluation functions for what is expected of them.

    :return: Randomly generated individual that has been validated and evaluated.
    """
    node_count = kwargs["node_count"]
    depot_nodes = kwargs["depot_nodes"]
    optional_nodes = kwargs["optional_nodes"]
    vehicle_count = kwargs["vehicle_count"]
    failure_msg = kwargs["failure_msg"]
    individual_timer = kwargs["individual_timer"]
    check_goal = kwargs["check_goal"]
    validation_args = kwargs["validation_args"]
    evaluation_args = kwargs["evaluation_args"]

    valid_individual = False
    candidate_individual = None
    while valid_individual is False:

        candidate_solution = random_solution(node_count=node_count,
                                             depot_nodes=depot_nodes,
                                             optional_nodes=optional_nodes,
                                             vehicle_count=vehicle_count)

        # Create an individual so that a solution can be assigned, validated and evaluated.
        candidate_individual = VRP(node_count, vehicle_count, depot_nodes,
                                   optional_nodes)
        candidate_individual.assign_solution(candidate_solution)

        # Mutate the individual with "vehicle diversification" 10% of the time.
        if random_float() <= 0.10:
            vehicle_diversification(candidate_individual)

        for validator in VRP.validator:
            valid_individual, validation_msg = validator(
                candidate_individual, **validation_args)
            # print("(Random Valid Individual) {}".format(validation_msg))
            if valid_individual is False:
                break

        # If the solution is invalid, the process is restarted.
        candidate_individual.valid = valid_individual

        # Should solution-finding take too long, it is halted here.
        if check_goal(individual_timer):
            return None, failure_msg

    # Once the solution is valid, it is evaluated.
    candidate_individual.fitness = VRP.evaluator(candidate_individual,
                                                 **evaluation_args)

    # The individual is now ready for use.
    return candidate_individual, "Individual Creation OK (Time taken: {} ms)".format(
        individual_timer.elapsed())
コード例 #13
0
ファイル: utils.py プロジェクト: mkbreuer/ToolPlus
			def get_corners(self, operator, context, pipe, spline, thickness):

				keep_inside = generate.pipe.keep_inside

				spline.points[-1].co.x = keep_inside(random_float(-operator.width * 0.5, operator.width * 0.5), thickness, operator.width * 0.5)

				last_x = spline.points[-1].co.x
				last_y = 0.0

				first_pass = True

				pipe_corners = [[last_x, last_y]]

				while last_y + abs(operator.length_y_max - thickness) < operator.height - abs(operator.length_y_max - thickness):

					if last_x - thickness <= -operator.width * 0.5:

						left = False

					elif last_x + thickness >= operator.width * 0.5:

						left = True

					else:

						left = choice([True, False])

					if first_pass:

						left_first = choice([True, False])

						coord_y = random_float(thickness, operator.length_y_max)

						first_pass = False

					else:

						length_y_min = operator.length_y_min + abs(operator.length_y_min - thickness)
						length_y_max = operator.length_y_max + abs(operator.length_y_max - thickness)

						coord_y = keep_inside(last_y + random_float(length_y_min, length_y_max), thickness, operator.height)

					length_x_min = operator.length_x_min + abs(operator.length_x_min - thickness)
					length_x_max = operator.length_x_max + abs(operator.length_x_max - thickness)
					thickness = -thickness if left else thickness
					length_x_min = -length_x_min if left else length_x_min
					length_x_max = -length_x_max if left else length_x_max

					coord_x = keep_inside(last_x + random_float(length_x_min, length_x_max), thickness, operator.width * 0.5)

					pipe_corners.append([last_x, coord_y, True, left])

					last_x = coord_x
					last_y = coord_y

					pipe_corners.append([last_x, last_y, False, left])

				else:

					pipe_corners.append([last_x, operator.height])

				return pipe_corners
コード例 #14
0
    max_longitude = max(longitudes)

    print('Using latitude range: ', min_latitude, max_latitude)
    print('Using longitude range: ', min_longitude, max_longitude)

    # Base API URL
    base_url = 'https://maps.googleapis.com/maps/api/staticmap?'
    map_param = '&maptype=map'
    satellite_param = '&maptype=satellite'
    default_params = '&zoom=16&size=256x286&sensor=false&style=feature:all|element:labels|visibility:off'

    for i in range(500, 500 + num_images + 1):
        # Sleep every 0.5 seconds so we don't get throttled
        sleep(0.5)

        local_latitude = random_float(min_latitude, max_latitude)
        local_longitude = random_float(min_longitude, max_longitude)

        location_param = 'center=' + str(local_latitude) + ',' + str(
            local_longitude)

        # Map image
        fname = str(i) + '_map_' + location_param + '.png'
        url = base_url + location_param + default_params + map_param
        img = get_imagery(url)
        img.save(os.path.join('raw/', fname))

        # Satellite image
        fname = str(i) + '_satellite_' + location_param + '.png'
        url = base_url + location_param + default_params + satellite_param
        img = get_imagery(url)