Python random.randint() Examples

The following are 30 code examples of random.randint(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module random , or try the search function .
Example #1
Source File: hiv.py    From indras_net with GNU General Public License v3.0 7 votes vote down vote up
def __init__(self, name, infected, infection_length, initiative,
                 coupling_tendency, condom_use, test_frequency, commitment,
                 coupled=False, coupled_length=0, known=False, partner=None):
        init_state = random.randint(0, 3)
        super().__init__(name, "wandering around", NSTATES, init_state)
        self.coupled = coupled
        self.couple_length = coupled_length
        self.partner = partner
        self.initiative = initiative
        self.infected = infected
        self.known = known
        self.infection_length = infection_length
        self.coupling_tendency = coupling_tendency
        self.condom_use = condom_use
        self.test_frequency = test_frequency
        self.commitment = commitment
        self.state = init_state
        self.update_ntype() 
Example #2
Source File: test_agent_pop.py    From indras_net with GNU General Public License v3.0 6 votes vote down vote up
def test_get_my_pop(self):
        report = True
        for var in self.dic_for_reference:
            for a in self.dic_for_reference[var][AGENTS]:
                self.agentpop.append(a)
        var = str(random.randint(0, 2))
        dummy_node = node.Node("dummy node")
        dummy_node.ntype = var
        self.agentpop.append(dummy_node)
        self.dic_for_reference[var][AGENTS].append(dummy_node)
        result = self.agentpop.get_my_pop(dummy_node)
        correct_pop = len(self.dic_for_reference[var][AGENTS])
        if result != correct_pop:
            report = False

        self.assertEqual(report, True) 
Example #3
Source File: test_agent_pop.py    From indras_net with GNU General Public License v3.0 6 votes vote down vote up
def test_get_pop_data(self):
        report = True
        check_list = []
        for var in self.dic_for_reference:
            random_pop_data = random.randint(1,10)
            check_list.append(random_pop_data)
            for a in self.dic_for_reference[var][AGENTS]:
                self.agentpop.append(a)
            self.agentpop.vars[var][POP_DATA] = random_pop_data
        index = 0
        for var in self.agentpop.vars:
            result = self.agentpop.get_pop_data(var)
            if result != check_list[index]:
                report = False
                break
            index += 1

        self.assertEqual(report, True) 
Example #4
Source File: test_basic.py    From indras_net with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, methodName, prop_file="models/basic_for_test.props"):
    
        super().__init__(methodName=methodName)
    
        pa = props.read_props(MODEL_NM, prop_file)
        # if result:
        #     pa.overwrite_props_from_dict(result.props)
        # else:
        #     print("Oh-oh, no props to read in!")
        #     exit(1)
    
        # Now we create a minimal environment for our agents to act within:
        self.env = bm.BasicEnv(model_nm=MODEL_NM, props=pa)
    
        # Now we loop creating multiple agents
        #  with numbered names based on the loop variable:
        for i in range(pa.props.get("num_agents").val):
            self.env.add_agent(bm.BasicAgent(name="agent" + str(i),
                                        goal="acting up!"))
        self.env.add_agent(bm.BasicAgent(name="agent for tracking",
                                         goal="acting up!"))

        # self.env.n_steps(random.randint(10, 20)) 
Example #5
Source File: anneal.py    From simulated-annealing-tsp with MIT License 6 votes vote down vote up
def anneal(self):
        """
        Execute simulated annealing algorithm.
        """
        # Initialize with the greedy solution.
        self.cur_solution, self.cur_fitness = self.initial_solution()

        print("Starting annealing.")
        while self.T >= self.stopping_temperature and self.iteration < self.stopping_iter:
            candidate = list(self.cur_solution)
            l = random.randint(2, self.N - 1)
            i = random.randint(0, self.N - l)
            candidate[i : (i + l)] = reversed(candidate[i : (i + l)])
            self.accept(candidate)
            self.T *= self.alpha
            self.iteration += 1

            self.fitness_list.append(self.cur_fitness)

        print("Best fitness obtained: ", self.best_fitness)
        improvement = 100 * (self.fitness_list[0] - self.best_fitness) / (self.fitness_list[0])
        print(f"Improvement over greedy heuristic: {improvement : .2f}%") 
Example #6
Source File: asthama_search.py    From pepper-robot-programming with MIT License 6 votes vote down vote up
def _capture2dImage(self, cameraId):
        # Capture Image in RGB

        # WARNING : The same Name could be used only six time.
        strName = "capture2DImage_{}".format(random.randint(1,10000000000))

        clientRGB = self.video_service.subscribeCamera(strName, cameraId, AL_kVGA, 11, 10)
        imageRGB = self.video_service.getImageRemote(clientRGB)

        imageWidth   = imageRGB[0]
        imageHeight  = imageRGB[1]
        array        = imageRGB[6]
        image_string = str(bytearray(array))

        # Create a PIL Image from our pixel array.
        im = Image.frombytes("RGB", (imageWidth, imageHeight), image_string)

        # Save the image.
        image_name_2d = "images/img2d-" + str(self.imageNo2d) + ".png"
        im.save(image_name_2d, "PNG") # Stored in images folder in the pwd, if not present then create one
        self.imageNo2d += 1
        im.show()

        return 
Example #7
Source File: asthama_search.py    From pepper-robot-programming with MIT License 6 votes vote down vote up
def _capture3dImage(self):
        # Depth Image in RGB

        # WARNING : The same Name could be used only six time.
        strName = "capture3dImage_{}".format(random.randint(1,10000000000))


        clientRGB = self.video_service.subscribeCamera(strName, AL_kDepthCamera, AL_kQVGA, 11, 10)
        imageRGB = self.video_service.getImageRemote(clientRGB)

        imageWidth  = imageRGB[0]
        imageHeight = imageRGB[1]
        array       = imageRGB[6]
        image_string = str(bytearray(array))

        # Create a PIL Image from our pixel array.
        im = Image.frombytes("RGB", (imageWidth, imageHeight), image_string)
        # Save the image.
        image_name_3d = "images/img3d-" + str(self.imageNo3d) + ".png"
        im.save(image_name_3d, "PNG") # Stored in images folder in the pwd, if not present then create one
        self.imageNo3d += 1
        im.show()

        return 
Example #8
Source File: remote_voice.py    From pepper-robot-programming with MIT License 6 votes vote down vote up
def _capture2dImage(self, cameraId):
        # Capture Image in RGB

        # WARNING : The same Name could be used only six time.
        strName = "capture2DImage_{}".format(random.randint(1,10000000000))


        clientRGB = self.video.subscribeCamera(strName, cameraId, AL_kVGA, 11, 10)
        imageRGB = self.video.getImageRemote(clientRGB)

        imageWidth = imageRGB[0]
        imageHeight = imageRGB[1]
        array = imageRGB[6]
        image_string = str(bytearray(array))

        # Create a PIL Image from our pixel array.
        im = Image.frombytes("RGB", (imageWidth, imageHeight), image_string)

        # Save the image inside the images foler in pwd.
        image_name_2d = "images/img2d-" + str(self.imageNo2d) + ".png"
        im.save(image_name_2d, "PNG") # Stored in images folder in the pwd, if not present then create one
        self.imageNo2d += 1
        im.show()

        return 
Example #9
Source File: remote_voice.py    From pepper-robot-programming with MIT License 6 votes vote down vote up
def _capture3dImage(self):
        # Depth Image in RGB

        # WARNING : The same Name could be used only six time.
        strName = "capture3dImage_{}".format(random.randint(1,10000000000))

        clientRGB = self.video.subscribeCamera(strName, AL_kDepthCamera, AL_kQVGA, 11, 15)
        imageRGB = self.video.getImageRemote(clientRGB)

        imageWidth = imageRGB[0]
        imageHeight = imageRGB[1]
        array = imageRGB[6]
        image_string = str(bytearray(array))

        # Create a PIL Image from our pixel array.
        im = Image.frombytes("RGB", (imageWidth, imageHeight), image_string)

        # Save the image inside the images foler in pwd.
        image_name_3d = "images/img3d-" + str(self.imageNo3d) + ".png"
        im.save(image_name_3d, "PNG") # Stored in images folder in the pwd, if not present then create one
        self.imageNo3d += 1
        im.show()

        return 
Example #10
Source File: remote_terminal.py    From pepper-robot-programming with MIT License 6 votes vote down vote up
def _capture3dImage(self):
        # Depth Image in RGB

        # WARNING : The same Name could be used only six time.
        strName = "capture3dImage_{}".format(random.randint(1,10000000000))

        clientRGB = self.video.subscribeCamera(strName, AL_kDepthCamera, AL_kQVGA, 11, 15)
        imageRGB = self.video.getImageRemote(clientRGB)

        imageWidth = imageRGB[0]
        imageHeight = imageRGB[1]
        array = imageRGB[6]
        image_string = str(bytearray(array))

        # Create a PIL Image from our pixel array.
        im = Image.frombytes("RGB", (imageWidth, imageHeight), image_string)

        # Save the image inside the images foler in pwd.
        image_name_3d = "images/img3d-" + str(self.imageNo3d) + ".png"
        im.save(image_name_3d, "PNG") # Stored in images folder in the pwd, if not present then create one
        self.imageNo3d += 1
        im.show()

        return 
Example #11
Source File: __init__.py    From EDeN with MIT License 6 votes vote down vote up
def random_optimize(GA, GB, n_iter=20):
    best_c = None
    best_order = None
    best_depth = None
    best_quality = -1
    for it in range(n_iter):
        c = random.randint(1, 7)
        order = random.randint(1, 10)
        depth = random.randint(1, 20)
        pairings = match(GA, GB, complexity=c, order=order, max_depth=depth)
        quality = compute_quality(GA, GB, pairings)
        if quality > best_quality:
            best_quality = quality
            best_c = c
            best_order = order
            best_depth = depth
    logging.debug('[random search] quality:%.2f c:%d o:%d d:%d' % (best_quality, best_c, best_order, best_depth))
    return best_quality, best_c, best_order, best_depth 
Example #12
Source File: snake.py    From unicorn-hat-hd with MIT License 5 votes vote down vote up
def reset(self):
        c_x, c_y = self.canvas.get_shape()
        c_y -= 3

        self.position = (random.randint(0, c_x - 1), random.randint(0, c_y - 1))

        self.score = random.randint(0, len(self.colours) - 1)

        self.eaten = False 
Example #13
Source File: GXSecure.py    From Gurux.DLMS.Python with GNU General Public License v2.0 5 votes vote down vote up
def generateChallenge(cls):
        #  Random challenge is 8 to 64 bytes.
        #  Texas Instruments accepts only 16 byte long challenge.
        #  For this reason challenge size is 16 bytes at the moment.
        len_ = 16
        result = [None] * len_
        pos = 0
        while pos != len_:
            result[pos] = random.randint(0, 255)
            pos += 1
        return result 
Example #14
Source File: space.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def rand_x(self, low=0, high=None):
        """
        Return a random x-value between 0 and this space's width,
        if no constraints are passed.
        With constraints, narrow to that range.
        """
        high = self.width if high is None else high
        return randint(low, high) 
Example #15
Source File: space.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def rand_y(self, low=0, high=None):
        """
        Return a random y-value between 0 and this space's height
        if no constraints are passed.
        With constraints, narrow to that range.
        """
        high = self.height if high is None else high
        return randint(low, high) 
Example #16
Source File: obst.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def get_rand_vector_mag(dist):
    vector_mag = random.randint(1, dist)
    return vector_mag 
Example #17
Source File: zombie.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, name, goal, repro_age, life_force, max_detect=10,
    rand_age=False, speed=3):
        
        init_state = random.randint(0, 3)

        super().__init__(name, goal, repro_age, life_force, init_state,
                         max_detect=max_detect, rand_age=rand_age, speed=speed)
        self.other = Human
        self.ntype = "Zombie"

    # Chooses which human to eat 
Example #18
Source File: zombie.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, name, goal, repro_age, life_force, max_detect=5,
                 rand_age=False, speed=1):

        init_state = random.randint(0, 3)
        super().__init__(name, goal, repro_age, life_force, init_state,
                         max_detect=max_detect, rand_age=rand_age, speed=speed)
        self.other = Zombie
        self.ntype = "Human"
        self.reproTime = repro_age
        self.lifeTime = life_force

    # Human who has been bit becomes a zombie 
Example #19
Source File: wolfsheep.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, name, goal, repro_age, life_force, init_state, max_detect=1,
                 rand_age=False, speed=1):
        super().__init__(name, goal, NSTATES, init_state, max_detect=max_detect)
        if not rand_age:
            self.age = 0
        else:
            self.age = random.randint(0, repro_age - 2)
        self.alive = True
        self.other = None
        self.repro_age = repro_age
        self.life_force = life_force
        self.init_life_force = life_force
        self.speed = speed
        self.state = init_state 
Example #20
Source File: wolfsheep.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, name, goal, repro_age, life_force, max_detect=10,
                    rand_age=False, speed=2):
        init_state = random.randint(0,3)
        super().__init__(name, goal, repro_age, life_force, init_state,
                         max_detect=max_detect, rand_age=rand_age, speed=speed)
        self.other = Sheep
        self.ntype = WOLF_NTYPE 
Example #21
Source File: wolfsheep.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, name, goal, repro_age, life_force, max_detect=5,
                 rand_age=False, speed=1):
        init_state = random.randint(0,3)
        super().__init__(name, goal, repro_age, life_force, init_state,
                         max_detect=max_detect, rand_age=rand_age, speed=speed)
        self.other = Wolf
        self.ntype = SHEEP_NTYPE 
Example #22
Source File: test_agent_pop.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def test_element_at(self):
        report = True
        lst_for_reference = []
        for var in self.dic_for_reference:
            lst_for_reference += self.dic_for_reference[var][AGENTS]
        for var in self.dic_for_reference:
            for a in self.dic_for_reference[var][AGENTS]:
                self.agentpop.append(a)
        index = random.randint(0,len(self.agentpop)-1)
        if self.agentpop.element_at(index) != lst_for_reference[index]:
            report = False

        self.assertEqual(report, True) 
Example #23
Source File: test_agent_pop.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def test_get_agents_of_var(self):
        report = True
        for var in self.dic_for_reference:
            for a in self.dic_for_reference[var][AGENTS]:
                self.agentpop.append(a)
        var = str(random.randint(0,2))
        result_lst = self.agentpop.get_agents_of_var(var)
        if self.dic_for_reference[var][AGENTS] != result_lst:
            report = False

        self.assertEqual(report, True) 
Example #24
Source File: test_agent_pop.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def test_get_pop(self):
        report = True
        for var in self.dic_for_reference:
            for a in self.dic_for_reference[var][AGENTS]:
                self.agentpop.append(a)
        var = str(random.randint(0, 2))
        result = self.agentpop.get_pop(var)
        if result != len(self.dic_for_reference[var][AGENTS]):
            report = False

        self.assertEqual(report, True) 
Example #25
Source File: test_basic.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def test_n_step(self):
        announce('test_n_step')
        report = True
        period_before_run = self.env.period
        random_steps = random.randint(3,30)
        self.env.n_steps(random_steps)
        period_after_run = self.env.period
        if (period_before_run + random_steps) != period_after_run:
            report = False
        self.assertEqual(report, True) 
Example #26
Source File: test_basic.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def test_save_session(self):
        announce('test_save_session')
        report = True
        rand_sess_id = random.randint(1, 10)
        try:
            base_dir = self.env.props["base_dir"]
        except:
            base_dir = ""
        self.env.save_session(rand_sess_id)

        path = base_dir + "json/" + self.env.model_nm + str(rand_sess_id) + ".json"
        with open(path, "r") as f:
            json_input = f.readline()
            json_input_dic = json.loads(json_input)
        if json_input_dic["period"] != self.env.period:
            report = False
        if json_input_dic["model_nm"] != self.env.model_nm:
            report = False
        if json_input_dic["preact"] != self.env.preact:
            report = False
        if json_input_dic["postact"] != self.env.postact:
            report = False
        if json_input_dic["props"] != self.env.props.to_json():
            report = False
        #Here is why test_save_session fail before.
        #The env will generate a new prop_arg 2 type proparg when restoring
        #session(check env.from_json function), but 
        # we were using old prop_arg in this test file.
        if json_input_dic["user"] != self.env.user.to_json():
            report = False
        agents = []
        for agent in self.env.agents:
            agents.append(agent.to_json())
        if json_input_dic["agents"] != agents:
            report = False

        f.close()
        os.remove(path)

        self.assertEqual(report, True) 
Example #27
Source File: test_hiv.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def test_n_step(self):
        announce('test_n_step')
        report = True
        period_before_run = self.env.period
        random_steps = random.randint(3, 30)
        self.env.n_steps(random_steps)
        period_after_run = self.env.period
        if (period_before_run + random_steps) != period_after_run:
            report = False
        self.assertEqual(report, True) 
Example #28
Source File: test_hiv.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def test_population_report(self):
        announce('test_population_report')
        self.env.n_steps(random.randint(10, 20))
        report = True
        self.env.pop_report(self.env.model_nm + ".csv")
        f = open(self.env.model_nm + ".csv", "r")
        head = f.readline()
        head = head.strip("\n")
        head_list = head.split(",")
        dic_for_reference = self.env.agents.get_pop_hist()
        for i in head_list:
            if i not in dic_for_reference:
                report = False
                break
        if report:
            dic_for_check = {}
            for i in head_list:
                dic_for_check[i] = []
            for line in f:
                line = line.strip("\n")
                line_list = line.split(",")
                if len(line_list) == len(head_list):
                    for i in range(len(line_list)):
                        dic_for_check[head_list[i]].append(int(line_list[i]))
                else:
                    report = False
                    break

        if report:
            if len(dic_for_check) != len(dic_for_reference):
                report = False
            if report is True:
                for key in dic_for_check:
                    if dic_for_check[key] != dic_for_reference[key]["data"]:
                        report = False
                        break
        f.close()
        os.remove(self.env.model_nm + ".csv")
        self.assertEqual(report, True) 
Example #29
Source File: test_hiv.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def test_restore_session(self):
        announce('test_restore_session')
        report = True
        rand_sess_id = random.randint(1, 10)
        try:
            base_dir = self.env.props["base_dir"]
        except:
            base_dir = ""
        self.env.save_session(rand_sess_id)
        self.env.n_steps(random.randint(1, 10))
        self.env.restore_session(rand_sess_id)

        path = (base_dir + "json/" + self.env.model_nm +
                str(rand_sess_id) + ".json")
        with open(path, "r") as f:
            json_input = f.readline()
        json_input_dic = json.loads(json_input)
        if json_input_dic["period"] != self.env.period:
            report = False
        if json_input_dic["model_nm"] != self.env.model_nm:
            report = False
        if json_input_dic["preact"] != self.env.preact:
            report = False
        if json_input_dic["postact"] != self.env.postact:
            report = False
        if json_input_dic["props"] != self.env.props.to_json():
            report = False
        if json_input_dic["user"] != self.env.user.to_json():
            report = False
        agents = []
        for agent in self.env.agents:
            agents.append(agent.to_json())

        os.remove(path)
        f.close()

        self.assertEqual(report, True) 
Example #30
Source File: test_fmarket.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def test_n_step(self):
        announce('test_n_step')
        report = True
        period_before_run = self.env.period
        random_steps = random.randint(3,30)
        self.env.n_steps(random_steps)
        period_after_run = self.env.period
        if (period_before_run + random_steps) != period_after_run:
            report = False
        self.assertEqual(report, True)