How to use selection_order method in hypothesis

Best Python code snippet using hypothesis

tsp_env.py

Source:tsp_env.py Github

copy

Full Screen

1"""2Travelling Salesman Problem Environment3All x, y axis are normalized to [-1, 1].4L_p distance can be used.5Supports Erdos-Renyi, Barabasi-Albert, and regular graphs.6TODO: Support for other graph types.7"""8import random9from functools import partial10from typing import Any, Dict, List, Literal, Optional, Tuple11import networkx as nx12import numpy as np13class TspEnv:14 """15 Tsp Environment.16 Graph types:17 er: Erdos-Renyi18 ba: Barabasi-Albert19 regular: regular graph20 custom: custom graph21 Returns: state, reward, done, info22 "vertex_occupancy" : np.ndarray23 1 if vertex is visited, 0 otherwise24 "pos" : np.ndarray25 position of each vertex26 "current_idx" : int27 current index of the agent28 "start_idx" : int29 starting index of the agent, by default, 0.30 "edge_index" : np.ndarray31 edge index of the graph32 """33 GRAPH_SET = {34 "er": partial(nx.erdos_renyi_graph, p=0.5),35 "ba": partial(nx.barabasi_albert_graph, m=3),36 "regular": partial(nx.random_regular_graph, d=5),37 }38 def __init__(39 self,40 graph_type: Literal["er", "ba", "regular", "custom"],41 n_nodes: int = 10,42 lp: float = 2.0,43 custom_pos: Optional[List[List[float]]] = None,44 dim: int = 2,45 ):46 self.graph_type = graph_type47 self.n_nodes = n_nodes48 self.lp = lp49 self.dim = dim50 if graph_type == "custom":51 assert custom_pos is not None, "custom_pos must be provided"52 self.n_nodes = len(custom_pos)53 assert all(54 len(pos) == dim for pos in custom_pos55 ), "element of custom_pos must be of length dim"56 self.custom_pos = custom_pos57 self.start_idx: int = 058 self.current_idx: int = 059 def _get_state(self) -> Dict[str, np.ndarray]:60 return {61 "vertex_occupancy": self.vertex_occupancy,62 "edge_index": self.edge_index,63 "pos": self.pos,64 "start_idx": self.start_idx,65 "current_idx": self.current_idx,66 }67 def _reset_graph(self) -> None:68 if self.graph_type == "custom":69 # distance matrirx to nx graph70 self.graph = nx.Graph()71 for i in range(self.n_nodes):72 self.graph.add_node(i)73 for j in range(i + 1, self.n_nodes):74 self.graph.add_edge(i, j)75 self.pos = np.array(self.custom_pos)76 else:77 self.graph = self.GRAPH_SET[self.graph_type](n=self.n_nodes)78 pos = nx.spring_layout(self.graph, dim=self.dim)79 # put pos into nx graph80 self.pos = np.array([pos[i] for i in range(self.n_nodes)])81 # make it complete82 for i in range(self.n_nodes):83 for j in range(i + 1, self.n_nodes):84 self.graph.add_edge(i, j)85 # min-max normalize pos86 self.pos = (87 (self.pos - self.pos.min(axis=0))88 / (self.pos.max(axis=0) - self.pos.min(axis=0))89 ) * 2 - 190 for i in self.graph.nodes:91 self.graph.nodes[i]["pos"] = pos[i]92 def reset(93 self, seed: Optional[int] = None, new_graph: bool = False94 ) -> Dict[str, np.ndarray]:95 """96 Reset the environment.97 Args:98 seed: random seed99 new_graph: whether to generate a new graph.100 Returns:101 state: state of the environment102 """103 if seed is not None:104 np.random.seed(seed)105 random.seed(seed)106 if new_graph:107 self._reset_graph()108 self.start_idx = 0109 self.current_idx = 0110 self.vertex_occupancy = np.zeros(self.n_nodes)111 self.vertex_occupancy[self.start_idx] = 1112 self.length = 0113 self.selection_order = [self.start_idx]114 self.edge_index = np.array(self.graph.edges)115 return self._get_state()116 def step(117 self, action: int118 ) -> Tuple[Dict[str, np.ndarray], float, bool, Dict[str, Any]]:119 assert action in range(self.n_nodes), "invalid action, must be in [0, n_nodes)"120 if self.vertex_occupancy[action] > 0: # already visited121 return self._get_state(), -3, True, {"length": self.length}122 self.vertex_occupancy[action] = 1123 self.current_idx = action124 this_len = np.linalg.norm(125 self.graph.nodes[action]["pos"]126 - self.graph.nodes[self.selection_order[-1]]["pos"],127 ord=self.lp,128 )129 self.selection_order.append(action)130 done = False131 if len(self.selection_order) == self.n_nodes:132 this_len += np.linalg.norm(133 self.graph.nodes[self.selection_order[0]]["pos"]134 - self.graph.nodes[self.selection_order[-1]]["pos"],135 ord=self.lp,136 )137 # just for rendering.138 self.selection_order.append(self.selection_order[0])139 done = True140 self.length += this_len141 return (142 self._get_state(),143 (4 - this_len) / 10,144 done,145 {"length": self.length},146 )147 def render(self, save_path="./img_folder") -> None:148 """149 Save the scene graph to a file.150 Args:151 save_path: path to save the image.152 Returns:153 None154 """155 import os156 if not os.path.exists(save_path):157 os.makedirs(save_path)158 import matplotlib.pyplot as plt159 import matplotlib.lines as mlines160 import matplotlib.patches as mpatches161 fig, ax = plt.subplots()162 ax.set_aspect("equal")163 # set range of x and y164 x_min, x_max = self.pos[:, 0].min(), self.pos[:, 0].max()165 y_min, y_max = self.pos[:, 1].min(), self.pos[:, 1].max()166 ax.set_xlim(x_min, x_max)167 ax.set_ylim(y_min, y_max)168 for i in range(self.n_nodes):169 ax.add_patch(170 mpatches.Circle(171 self.pos[i],172 radius=0.05,173 color="black" if self.vertex_occupancy[i] == 0 else "grey",174 )175 )176 # plot current pos177 ax.add_patch(178 mpatches.Circle(179 self.pos[self.current_idx],180 radius=0.05,181 color="red",182 )183 )184 for i in range(len(self.selection_order) - 1):185 ax.add_line(186 mlines.Line2D(187 [188 self.pos[self.selection_order[i]][0],189 self.pos[self.selection_order[i + 1]][0],190 ],191 [192 self.pos[self.selection_order[i]][1],193 self.pos[self.selection_order[i + 1]][1],194 ],195 color="black",196 )197 )198 # put info on figure199 fig.suptitle(200 f"{self.graph_type} graph, {self.n_nodes} nodes, {self.lp}-norm, Total length: {self.length:.3f} \n \201 current_idx: {self.current_idx}, start_idx: {self.start_idx}",202 )203 plt.savefig(204 os.path.join(save_path, f"tsp_env_{len(self.selection_order) :03d}.png")205 )206 plt.close()207def heuristic(state, eps=0.1):208 """209 Select minimum distance vertex, greedily.210 Simple heuristic to debug / test the enviornment211 Args:212 state :213 "vertex_occupancy" : np.ndarray214 1 if vertex is visited, 0 otherwise215 "pos" : np.ndarray216 position of each vertex217 "current_idx" : int218 current index of the agent219 "start_idx" : int220 starting index of the agent, by default, 0.221 "edge_index" : np.ndarray222 edge index of the graph223 eps : float224 epsilon for greedy selection225 Returns:226 int : index of the vertex to visit227 """228 n_nodes = state["vertex_occupancy"].shape[0]229 # greedy selection230 current_idx = state["current_idx"]231 pos = state["pos"]232 dist = np.linalg.norm(pos - pos[current_idx], ord=2, axis=1)233 dist[state["vertex_occupancy"] == 1] = np.inf234 return np.argmin(dist)235def demo_heuristic():236 """237 Demo the heuristic runner.238 Save the process of the heuristic selection to a gif file.239 """240 env = TspEnv(n_nodes=20, dim=2, graph_type="ba")241 state = env.reset(1)242 env.render("./img_folder/_tmp")243 while True:244 action = heuristic(state)245 state, reward, done, info = env.step(action)246 print(f"action: {action}, reward: {reward}, done: {done}")247 env.render("./img_folder/_tmp")248 if done:249 break250 print(env.length)251 # convert tmp to gif252 import subprocess253 subprocess.call(254 ["convert", "-delay", "100", "./img_folder/_tmp/*.png", "./img_folder/_tmp.gif"]255 )256 # remove tmp folder257 import shutil258 shutil.rmtree("./img_folder/tmp")259if __name__ == "__main__":...

Full Screen

Full Screen

create_mode.py

Source:create_mode.py Github

copy

Full Screen

...11 players = player_list.split()12 return players13 14# Returns the order of selection from the list of players in snake draft order15def get_selection_order(players: List[str], rounds: int) -> List[str]:16 selection_order = []17 reverse = False18 for i in range(0,rounds):19 if reverse:20 for player in reversed(players):21 selection_order.append(player)22 reverse = False23 else:24 for player in players:25 selection_order.append(player)26 reverse = True27 28 return selection_order29 30def get_word(player: str) -> str:31 word = input(player + ' select a word: ')32 return word33def get_save_path() -> str:34 path = input('File to save game to [Default ' + DEFAULT_SAVE_PATH + ']')35 if path:36 return path37 else:38 return DEFAULT_SAVE_PATH39def get_words(players: List[str], rounds: int) -> Dict[str, List[str]]:40 words = {}41 for player in players:42 words[player] = []43 44 # The list of players names in order of word selection (snake draft)45 selection_order = get_selection_order(players, rounds)46 47 print('Select your words!')48 49 # Loop through and get all the words from input50 for player_selecting in selection_order:51 list_for_player = words[player_selecting]52 word = get_word(player_selecting)53 list_for_player.append(word)54 55 print('Selected words:')56 for player in words:57 print(player + ' ' + str(words[player]))58 59 return words...

Full Screen

Full Screen

track_selection_order.py

Source:track_selection_order.py Github

copy

Full Screen

1import bpy2class SelectionCallback:3 def __init__(self):4 self.selection_order = []5 6 @staticmethod7 def notify(*args):8 self = args[0]9 layer_objects = bpy.context.view_layer.objects10 if not layer_objects:11 return12 print("\n\n")13 print(layer_objects.active)14 if not layer_objects.active in self.selection_order:15 self.selection_order.append(layer_objects.active)16 if len(layer_objects.selected) > 1:17 selected = set(bpy.context.view_layer.objects.selected)18 selected.remove(bpy.context.view_layer.objects.active)19 for o in selected:20 if not o in self.selection_order:21 self.selection_order.append(o)22 removed = set(self.selection_order) - selected23 for r in removed:24 self.selection_order.remove(r)25 print(self.selection_order)26 else:27 self.selection_order = []28subscribe_to = bpy.types.LayerObjects, "active"29handle = SelectionCallback()30bpy.msgbus.subscribe_rna(31 key = subscribe_to,32 owner = handle,33 args = (handle,),34 notify = handle.notify,...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run hypothesis automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful