Best Python code snippet using slash
sample_trajectory.py
Source:sample_trajectory.py  
1import random2def get_scene_4_fam_wall(valid_fam_configs, selected_target):3    pos_x = 2 if selected_target == "1" else 04    easy_fam = valid_fam_configs[5        (valid_fam_configs["obstacle_height"].isin([1, 2])) &6        (valid_fam_configs["obstacle_width"].isin([0])) &7        (valid_fam_configs["obstacle_pos_z"] == valid_fam_configs["obj_pos_z"]) &8        (valid_fam_configs["obstacle_pos_z"] == valid_fam_configs["agent_z"]) &9        (valid_fam_configs["obj_pos_x"] == pos_x) &10        (valid_fam_configs["cost"] < 9) &11        (valid_fam_configs["path_type"].isin(["Jump"]))12        ]13    easy_fam = easy_fam.iloc[random.choice(range(easy_fam.shape[0]))]14    med_fam_1 = valid_fam_configs[15        (valid_fam_configs["obj_pos_x"] == pos_x) &16        (valid_fam_configs["obj_pos_z"] == easy_fam["obj_pos_z"]) &17        (valid_fam_configs["agent_z"] == easy_fam["agent_z"])18        ]19    med_heights = [easy_fam["obstacle_height"] + 2]20    if easy_fam["obstacle_height"] + 3 < 5:21        med_heights.append(easy_fam["obstacle_height"] + 3)22    med_fam_1 = med_fam_1[23        (med_fam_1["obstacle_height"].isin(med_heights)) &24        (med_fam_1["obstacle_width"].isin([0])) &25        (med_fam_1["cost"] > easy_fam["cost"]) &26        (med_fam_1["path_type"].isin(["Jump"]))27        ]28    med_fam_1 = med_fam_1.iloc[random.choice(range(med_fam_1.shape[0]))]29    med_fam_2 = valid_fam_configs[30        (valid_fam_configs["agent_x"] == pos_x) &31        (valid_fam_configs["obj_pos_z"] == easy_fam["obj_pos_z"]) &32        (valid_fam_configs["agent_z"] == easy_fam["agent_z"])33        ]34    med_heights = [easy_fam["obstacle_height"] + 2]35    if easy_fam["obstacle_height"] + 3 < 5:36        med_heights.append(easy_fam["obstacle_height"] + 3)37    med_fam_2 = med_fam_2[38        (med_fam_2["obstacle_height"].isin(med_heights)) &39        (med_fam_2["obstacle_width"].isin([0])) &40        (med_fam_2["cost"] > easy_fam["cost"]) &41        (med_fam_2["path_type"].isin(["Jump"]))42        ]43    med_fam_2 = med_fam_2.iloc[random.choice(range(med_fam_2.shape[0]))]44    hard_heights = [med_fam_2["obstacle_height"] + 2]45    if med_fam_2["obstacle_height"] + 3 < 7:46        hard_heights.append(med_fam_2["obstacle_height"] + 3)47    hard_fam = valid_fam_configs[48        (valid_fam_configs["obj_pos_z"] == easy_fam["obj_pos_z"]) &49        (valid_fam_configs["agent_x"] == pos_x) &50        (valid_fam_configs["agent_z"] == easy_fam["agent_z"])51        ]52    hard_fam = hard_fam.iloc[random.choice(range(hard_fam.shape[0]))]53    return hard_fam, med_fam_2, med_fam_1, easy_fam54def get_scene_4_cost_reward_trade_offs_test_v1(test_type, valid_test_configs, selected_target, not_selected, switch_test_targets,55                                               target_1_pos_to_target_2_pos):56    valid_test_configs = valid_test_configs[valid_test_configs["scene_type"].isin(["barrier_scenes_3_4",57                                                                                   "barrier_scenes"])]58    59    if switch_test_targets:60        selected_target, not_selected = not_selected, selected_target61    if test_type == "Type-4.1":62        test_a_valid_configs = valid_test_configs[63            (valid_test_configs["target"] == f"Target-{selected_target}") &64            (valid_test_configs[f"obstacle_height_{selected_target}"] == 0) &65            (valid_test_configs[f"target-{selected_target}-distance"] > 1)66            ]67        test_a = test_a_valid_configs.iloc[random.choice(range(test_a_valid_configs.shape[0]))]68        test_b = valid_test_configs[69            (valid_test_configs["target"] == f"Target-{not_selected}") &70            (valid_test_configs[f"obj_{not_selected}_pos_z"] == test_a[f"obj_{selected_target}_pos_z"]) &71            (valid_test_configs[f"obj_{not_selected}_pos_x"] ==72             target_1_pos_to_target_2_pos[f"target_{selected_target}"][test_a[f"obj_{selected_target}_pos_x"]]) &73            (valid_test_configs[f"obstacle_height_{not_selected}"] == 0) &74            (valid_test_configs["agent_pos_z"] == test_a["agent_pos_z"]) &75            (valid_test_configs["path_type"].isin(["Straight-Target"]))76            ].iloc[0]77        return [test_a, test_b]78    if test_type == "Type-4.2":79        pos_x = 0 if not_selected == "2" else 680        test_b_valid_configs = valid_test_configs[81            (valid_test_configs["target"] == f"Target-{not_selected}") &82            (valid_test_configs[f"obstacle_height_{not_selected}"].isin([5, 6])) &83            (valid_test_configs[f"obstacle_width_{not_selected}"].isin([0, 1])) &84            (valid_test_configs[f"obstacle_depth_{not_selected}"].isin([3, 4])) &85            (valid_test_configs["path_type"].isin(['Around-barrier-bottom']))86            ]87        test_b = test_b_valid_configs.iloc[random.choice(range(test_b_valid_configs.shape[0]))]88        test_a = valid_test_configs[89            (valid_test_configs["target"] == f"Target-{selected_target}") &90            (valid_test_configs[f"obj_{selected_target}_pos_x"] == pos_x) &91            (valid_test_configs[f"obj_{selected_target}_pos_z"] == test_b[f"obj_{not_selected}_pos_z"]) &92            (valid_test_configs[f"obstacle_height_{selected_target}"].isin([0])) &93            (valid_test_configs["agent_pos_z"] == test_b["agent_pos_z"]) &94            (valid_test_configs["cost"] < test_b["cost"])95            ].iloc[0]96        return [test_a, test_b]97def get_scene_4_cost_reward_trade_offs_test_v2(test_type, valid_test_configs, selected_target, not_selected, switch_test_target,98                                               target_1_pos_to_target_2_pos, object_type_test):99    if switch_test_target:100        selected_target, not_selected = not_selected, selected_target101    pos_x = 0 if selected_target == "1" else 6102    if test_type == "Type-4.1":103        if object_type_test[0] == "pit-with-bridge" or object_type_test[1] == "pit-with-bridge":104            if object_type_test[0] == "pit-with-bridge":105                test_a = valid_test_configs[106                    (valid_test_configs["target"] == f"Target-{selected_target}") &107                    (valid_test_configs["scene_type"] == "pit_scenes_3_4") &108                    (valid_test_configs[f"obj_{selected_target}_pos_z"].isin([1, 2])) &109                    (valid_test_configs[f"obj_{selected_target}_pos_z"] == valid_test_configs["agent_pos_z"]) &110                    (valid_test_configs[f"obstacle_{selected_target}_pos_z"] == valid_test_configs["agent_pos_z"]) &111                    (valid_test_configs["path_type"] == "Cross-Bridge")112                ]113                test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]114            else:115                test_a = valid_test_configs[116                    (valid_test_configs["target"] == f"Target-{selected_target}") &117                    (valid_test_configs["scene_type"] == "pit_scenes_3_4") &118                    (valid_test_configs["path_type"] == "Straight-Target")119                    ]120                test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]121            if object_type_test[1] == "pit-with-bridge":122                test_b = valid_test_configs[123                    (valid_test_configs["target"] == f"Target-{not_selected}") &124                    (valid_test_configs["scene_type"] == "pit_scenes_3_4") &125                    (valid_test_configs["path_type"] == "Cross-Bridge")126                ]127                if object_type_test[0] == "pit-with-bridge":128                    test_b = test_b[129                        (test_b[f"obstacle_{not_selected}_pos_z"] == test_a[f"obstacle_{selected_target}_pos_z"] ) &130                        (test_b[f"obstacle_width_{not_selected}"] == test_a[f"obstacle_width_{selected_target}"] ) &131                        (test_b["agent_pos_z"] == test_a["agent_pos_z"]) &132                        (test_b[f"obj_{not_selected}_pos_z"] == test_a[f"obj_{selected_target}_pos_z"])133                    ]134                test_b = test_b.iloc[random.choice(range(test_b.shape[0]))]135            else:136                test_b = valid_test_configs[137                    (valid_test_configs["target"] == f"Target-{not_selected}") &138                    (valid_test_configs["scene_type"] == "pit_scenes_3_4") &139                    (valid_test_configs["path_type"] == "Straight-Target") &140                    (valid_test_configs["agent_pos_z"] == test_a["agent_pos_z"]) &141                    (valid_test_configs[f"obj_{not_selected}_pos_z"] == test_a[f"obj_{selected_target}_pos_z"])142                    ]143                test_b = test_b.iloc[random.choice(range(test_b.shape[0]))]144            return [test_a, test_b]145        elif object_type_test[0] == "barrier_with_door" or object_type_test[1] == "barrier_with_door":146            if object_type_test[0] == "barrier_with_door":147                test_a = valid_test_configs[148                    (valid_test_configs["target"] == f"Target-{selected_target}") &149                    (valid_test_configs["path_type"] == "barrier-door") &150                    (valid_test_configs[f"obstacle_{selected_target}_pos_z"] == 1) &151                    (valid_test_configs[f"obj_{selected_target}_pos_z"] == 1) &152                    (valid_test_configs[f"agent_pos_z"] == 1) &153                    (valid_test_configs[f"obstacle_height_{selected_target}"].isin([5, 6]))154                    ]155                test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]156            else:157                test_a = valid_test_configs[158                    (valid_test_configs["target"] == f"Target-{selected_target}") &159                    (valid_test_configs["path_type"] == "Straight-Target") &160                    (valid_test_configs[f"obstacle_height_{selected_target}"].isin([0])) &161                    (valid_test_configs[f"obj_{selected_target}_pos_x"] == pos_x)162                    ]163                test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]164            if object_type_test[1] == "barrier_with_door":165                test_b = valid_test_configs[166                    (valid_test_configs["target"] == f"Target-{not_selected}") &167                    (valid_test_configs["path_type"] == "barrier-door") &168                    (valid_test_configs[f"obstacle_{not_selected}_pos_z"] == 1) &169                    (valid_test_configs[f"obstacle_height_{not_selected}"].isin([5, 6])) &170                    (valid_test_configs[f"agent_pos_z"] == 1) &171                    (valid_test_configs[f"obj_{not_selected}_pos_z"] == 1)172                    ]173                test_b = test_b.iloc[random.choice(range(test_b.shape[0]))]174            else:175                pos_x_b = 6 if selected_target == "1" else 0176                test_b = valid_test_configs[177                    (valid_test_configs["target"] == f"Target-{not_selected}") &178                    (valid_test_configs["path_type"] == "Straight-Target") &179                    (valid_test_configs[f"obstacle_height_{not_selected}"].isin([0])) &180                    (valid_test_configs[f"obj_{not_selected}_pos_z"] == test_a[f"obj_{selected_target}_pos_z"]) &181                    (valid_test_configs[f"agent_pos_z"] == test_a[f"agent_pos_z"]) &182                    (valid_test_configs[f"obj_{not_selected}_pos_x"] == pos_x_b)183                    ]184                test_b = test_b.iloc[random.choice(range(test_b.shape[0]))]185            return [test_a, test_b]186    if test_type == "Type-4.2":187        if object_type_test[1] == "platform":188            test_b = valid_test_configs[189                (valid_test_configs["path_type"] == "Platform-jump") &190                (valid_test_configs["agent_pos_z"] == 1) &191                (valid_test_configs["target"] == f"Target-{not_selected}")192            ]193            test_b = test_b.iloc[random.choice(range(test_b.shape[0]))]194        elif object_type_test[1] == "ramp":195            test_b = valid_test_configs[196                (valid_test_configs["path_type"] == "Go-up-ramp") &197                (valid_test_configs["agent_pos_z"] == 1) &198                (valid_test_configs["target"] == f"Target-{not_selected}")199                ]200            test_b = test_b.iloc[random.choice(range(test_b.shape[0]))]201        # elif object_type_test[1] == "pit":202        else:203            test_b = valid_test_configs[204                (valid_test_configs["path_type"] == "Pit_Jump") &205                (valid_test_configs["target"] == f"Target-{not_selected}")206                ]207            if object_type_test[0] == "pit-with-bridge":208                test_b = test_b[209                    (test_b["agent_pos_z"] == test_b[f"obj_{not_selected}_pos_z"]) &210                    (test_b["agent_pos_z"] == test_b[f"obstacle_{not_selected}_pos_z"])211                ]212            test_b = test_b.iloc[random.choice(range(test_b.shape[0]))]213        if object_type_test[1] in ["pit", "pit-with-bridge"] and object_type_test[0] == "pit-with-bridge":214            test_a = valid_test_configs[215                (valid_test_configs["target"] == f"Target-{selected_target}") &216                (valid_test_configs["path_type"] == "Cross-Bridge") &217                (valid_test_configs["agent_pos_z"] == test_b["agent_pos_z"]) &218                (valid_test_configs[f"obstacle_width_{selected_target}"] == test_b[f"obstacle_width_{not_selected}"]) &219                (valid_test_configs[f"obj_{selected_target}_pos_z"] == test_b[f"obj_{not_selected}_pos_z"]) &220                (valid_test_configs[f"obstacle_{selected_target}_pos_z"] == test_b[f"obj_{not_selected}_pos_z"])221                ]222            test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]223        elif object_type_test[1] in ["pit", "pit-with-bridge"] and object_type_test[0] == "none":224            test_a = valid_test_configs[225                (valid_test_configs["target"] == f"Target-{selected_target}") &226                (valid_test_configs["scene_type"] == "pit_scenes_3_4") &227                (valid_test_configs["path_type"] == "Straight-Target") &228                (valid_test_configs["agent_pos_z"] == test_b["agent_pos_z"]) &229                (valid_test_configs[f"obj_{selected_target}_pos_z"] == test_b[f"obj_{not_selected}_pos_z"])230                ]231            test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]232        elif object_type_test[0] == "none":233            pox = 0 if selected_target == "1" else 6234            test_a = valid_test_configs[235                (valid_test_configs["target"] == f"Target-{selected_target}") &236                (valid_test_configs["scene_type"] == "barrier_scenes_3_4") &237                (valid_test_configs["path_type"] == "Straight-Target") &238                (valid_test_configs["agent_pos_z"] == 1) &239                # 1 Because both ramp and platform have fixed z values which is 1240                (valid_test_configs[f"obj_{selected_target}_pos_z"] == 1) &241                (valid_test_configs[f"obj_{selected_target}_pos_x"] == pox)242                ]243            test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]244        elif object_type_test[0] == "barrier_with_door":245            test_a = valid_test_configs[246                (valid_test_configs["target"] == f"Target-{selected_target}") &247                (valid_test_configs["path_type"] == "barrier-door") &248                (valid_test_configs[f"obstacle_height_{selected_target}"].isin([5, 6])) &249                (valid_test_configs["agent_pos_z"] == 1) &250                (valid_test_configs[f"obstacle_{selected_target}_pos_z"] == 1) &251                (valid_test_configs[f"obj_{selected_target}_pos_z"] == 1)252                ]253            test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]254        return [test_a, test_b]255def get_scene_4_fam_pit(valid_fam_configs, selected_target):256    pos_x = 2 if selected_target == "1" else 0257    easy_fam = valid_fam_configs[258        (valid_fam_configs["scene_type"] == "pit_scenes") &259        (valid_fam_configs["obj_pos_x"] == pos_x) &260        ( (valid_fam_configs["path_type"] == "Straight-Target") |261          ( (valid_fam_configs["obstacle_width"] == 0) & (valid_fam_configs["path_type"] == "Pit_Jump")) )262        ]263    easy_fam = easy_fam.iloc[random.choice(range(easy_fam.shape[0]))]264    med_fam_1 = valid_fam_configs[265        (valid_fam_configs["obj_pos_x"] == pos_x) &266        (valid_fam_configs["obj_pos_z"] == easy_fam["obj_pos_z"]) &267        (valid_fam_configs["agent_z"] == easy_fam["agent_z"]) &268        (valid_fam_configs["scene_type"] == "pit_scenes") &269        (valid_fam_configs["obstacle_width"] == 2) &270        (valid_fam_configs["path_type"] == "Pit_Jump")271        ]272    med_fam_1 = med_fam_1.iloc[random.choice(range(med_fam_1.shape[0]))]273    med_fam_2 = valid_fam_configs[274        (valid_fam_configs["agent_x"] == pos_x) &275        (valid_fam_configs["obj_pos_z"] == easy_fam["obj_pos_z"]) &276        (valid_fam_configs["agent_z"] == easy_fam["agent_z"]) &277        (valid_fam_configs["scene_type"] == "pit_scenes") &278        (valid_fam_configs["obstacle_width"] == 2) &279        (valid_fam_configs["path_type"] == "Pit_Jump")280        ]281    med_fam_2 = med_fam_2.iloc[random.choice(range(med_fam_2.shape[0]))]282    hard_fam = valid_fam_configs[283        (valid_fam_configs["obj_pos_z"] == easy_fam["obj_pos_z"]) &284        (valid_fam_configs["agent_x"] == pos_x) &285        (valid_fam_configs["agent_z"] == easy_fam["agent_z"]) &286        (valid_fam_configs["scene_type"] == "pit_scenes") &287        (valid_fam_configs["obstacle_width"] > 3) &288        (valid_fam_configs["path_type"] == "Pit_Jump")289        ]290    hard_fam = hard_fam.iloc[random.choice(range(hard_fam.shape[0]))]291    return hard_fam, med_fam_2, med_fam_1, easy_fam292def get_scene_4_fam_platform(valid_fam_configs, selected_target):293    pos_x = 2 if selected_target == "1" else 0294    easy_fam = valid_fam_configs[295        (valid_fam_configs["obj_pos_x"] == pos_x) &296         ((valid_fam_configs["scene_type"] == "platform_scenes") &297          (valid_fam_configs["obstacle_height"] == 0) &298          (valid_fam_configs["path_type"] == "Platform-jump"))299        ]300    easy_fam = easy_fam.iloc[random.choice(range(easy_fam.shape[0]))]301    med_fam_1 = valid_fam_configs[302        (valid_fam_configs["obj_pos_x"] == pos_x) &303        (valid_fam_configs["agent_z"] == easy_fam["agent_z"]) &304        (valid_fam_configs["scene_type"] == "platform_scenes") &305        (valid_fam_configs["obstacle_height"] == 1) &306        (valid_fam_configs["path_type"] == "Platform-jump")307        ]308    med_fam_1 = med_fam_1.iloc[random.choice(range(med_fam_1.shape[0]))]309    med_fam_2 = valid_fam_configs[310        (valid_fam_configs["agent_x"] == pos_x) &311        (valid_fam_configs["agent_z"] == easy_fam["agent_z"]) &312        (valid_fam_configs["scene_type"] == "platform_scenes") &313        (valid_fam_configs["obstacle_height"] == 1) &314        (valid_fam_configs["path_type"] == "Platform-jump")315        ]316    med_fam_2 = med_fam_2.iloc[random.choice(range(med_fam_2.shape[0]))]317    hard_fam = valid_fam_configs[318        (valid_fam_configs["agent_x"] == pos_x) &319        (valid_fam_configs["agent_z"] == easy_fam["agent_z"]) &320        (valid_fam_configs["scene_type"] == "platform_scenes") &321        (valid_fam_configs["obstacle_height"] > 1) &322        (valid_fam_configs["path_type"] == "Platform-jump")323        ]324    hard_fam = hard_fam.iloc[random.choice(range(hard_fam.shape[0]))]325    return hard_fam, med_fam_2, med_fam_1, easy_fam326def get_scene_4_fam_ramp(valid_fam_configs, selected_target):327    pos_x = 2 if selected_target == "1" else 0328    ramp_pos_x = 1 if selected_target == "1" else 0329    easy_fam = valid_fam_configs[330        (valid_fam_configs["obj_pos_x"] == ramp_pos_x) &331         ((valid_fam_configs["scene_type"] == "ramp_scenes") &332          (valid_fam_configs["obstacle_height"] == 0) &333          (valid_fam_configs["path_type"] == "Go-up-ramp"))334        ]335    easy_fam = easy_fam.iloc[random.choice(range(easy_fam.shape[0]))]336    med_fam_1 = valid_fam_configs[337        (valid_fam_configs["obj_pos_x"] == ramp_pos_x) &338        (valid_fam_configs["agent_z"] == easy_fam["agent_z"]) &339        (valid_fam_configs["scene_type"] == "ramp_scenes") &340        (valid_fam_configs["obstacle_height"] == 1) &341        (valid_fam_configs["path_type"] == "Go-up-ramp")342        ]343    med_fam_1 = med_fam_1.iloc[random.choice(range(med_fam_1.shape[0]))]344    med_fam_2 = valid_fam_configs[345        (valid_fam_configs["agent_x"] == pos_x) &346        (valid_fam_configs["agent_z"] == easy_fam["agent_z"]) &347        (valid_fam_configs["scene_type"] == "ramp_scenes") &348        (valid_fam_configs["obstacle_height"] == 1) &349        (valid_fam_configs["path_type"] == "Go-up-ramp")350        ]351    med_fam_2 = med_fam_2.iloc[random.choice(range(med_fam_2.shape[0]))]352    hard_fam = valid_fam_configs[353        (valid_fam_configs["agent_x"] == pos_x) &354        (valid_fam_configs["agent_z"] == easy_fam["agent_z"]) &355        (valid_fam_configs["scene_type"] == "ramp_scenes") &356        (valid_fam_configs["obstacle_height"] > 1) &357        (valid_fam_configs["path_type"] == "Go-up-ramp")358        ]359    hard_fam = hard_fam.iloc[random.choice(range(hard_fam.shape[0]))]360    return hard_fam, med_fam_2, med_fam_1, easy_fam361def get_scene_3_test_(test_type, valid_test_configs, selected_target, target_1_pos_to_target_2_pos,362                      object_type_test):363    pos_x = 0 if selected_target == "1" else 6364    not_selected = 1 if selected_target == 2 else 2365    if test_type in ["Type-1.1", ""]:366        if object_type_test[0] == "pit-with-bridge" or object_type_test[1] == "pit-with-bridge":367            if object_type_test[0] == "pit-with-bridge":368                test_a = valid_test_configs[369                    (valid_test_configs["target"] == f"Target-{selected_target}") &370                    (valid_test_configs["scene_type"] == "pit_scenes_3_4") &371                    (valid_test_configs["path_type"] == "Cross-Bridge")372                ]373                test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]374            else:375                test_a = valid_test_configs[376                    (valid_test_configs["target"] == f"Target-{selected_target}") &377                    (valid_test_configs["scene_type"] == "pit_scenes_3_4") &378                    (valid_test_configs["path_type"] == "Straight-Target")379                    ]380                test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]381            if object_type_test[1] == "pit-with-bridge":382                test_b = valid_test_configs[383                    (valid_test_configs["target"] == f"Target-{not_selected}") &384                    (valid_test_configs["scene_type"] == "pit_scenes_3_4") &385                    (valid_test_configs["path_type"] == "Cross-Bridge") &386                    (valid_test_configs[f"obj_{not_selected}_pos_z"] == test_a[f"obj_{selected_target}_pos_z"])387                ]388                if object_type_test[0] == "pit-with-bridge":389                    test_b = test_b[390                        test_b[f"obstacle_{not_selected}_pos_z"] == test_a[f"obstacle_{selected_target}_pos_z"]391                    ]392                test_b = test_b.iloc[random.choice(range(test_b.shape[0]))]393            else:394                test_b = valid_test_configs[395                    (valid_test_configs["target"] == f"Target-{not_selected}") &396                    (valid_test_configs["scene_type"] == "pit_scenes_3_4") &397                    (valid_test_configs["path_type"] == "Straight-Target") &398                    (valid_test_configs[f"obj_{not_selected}_pos_z"] == test_a[f"obj_{selected_target}_pos_z"])399                    ]400                test_b = test_b.iloc[random.choice(range(test_b.shape[0]))]401            return [test_a, test_b]402        elif object_type_test[0] == "barrier_with_door" or object_type_test[1] == "barrier_with_door":403            if object_type_test[0] == "barrier_with_door":404                test_a = valid_test_configs[405                    (valid_test_configs["target"] == f"Target-{selected_target}") &406                    (valid_test_configs["path_type"] == "barrier-door") &407                    (valid_test_configs[f"obstacle_{selected_target}_pos_z"] == valid_test_configs["agent_pos_z"]) &408                    (valid_test_configs[f"obstacle_height_{selected_target}"].isin([5, 6]))409                    ]410                test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]411            else:412                test_a = valid_test_configs[413                    (valid_test_configs["target"] == f"Target-{selected_target}") &414                    (valid_test_configs["path_type"] == "Straight-Target") &415                    (valid_test_configs[f"obstacle_height_{selected_target}"].isin([0])) &416                    (valid_test_configs[f"obj_{selected_target}_pos_x"] == pos_x)417                    ]418                test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]419            if object_type_test[1] == "barrier_with_door":420                test_b = valid_test_configs[421                    (valid_test_configs["target"] == f"Target-{not_selected}") &422                    (valid_test_configs["path_type"] == "barrier-door") &423                    (valid_test_configs[f"obstacle_{not_selected}_pos_z"] == valid_test_configs["agent_pos_z"]) &424                    (valid_test_configs[f"obstacle_height_{not_selected}"].isin([5, 6])) &425                    (valid_test_configs[f"obj_{not_selected}_pos_z"] == test_a[f"obj_{selected_target}_pos_z"])426                    ]427                test_b = test_b.iloc[random.choice(range(test_b.shape[0]))]428            else:429                test_b = valid_test_configs[430                    (valid_test_configs["target"] == f"Target-{not_selected}") &431                    (valid_test_configs["path_type"] == "Straight-Target") &432                    (valid_test_configs[f"obstacle_height_{not_selected}"].isin([0])) &433                    (valid_test_configs[f"obj_{not_selected}_pos_z"] == test_a[f"obj_{selected_target}_pos_z"]) &434                    (valid_test_configs[f"obj_{not_selected}_pos_x"] ==435                     target_1_pos_to_target_2_pos[f"target_{selected_target}"][test_a[f"obj_{selected_target}_pos_x"]])436                    ]437                test_b = test_b.iloc[random.choice(range(test_b.shape[0]))]438            return [test_a, test_b]439    if test_type == "Type-2":440        if object_type_test[1] == "platform":441            test_b = valid_test_configs[442                (valid_test_configs["path_type"] == "Platform-jump") &443                (valid_test_configs["target"] == f"Target-{not_selected}")444            ]445            test_b = test_b.iloc[random.choice(range(test_b.shape[0]))]446        elif object_type_test[1] == "ramp":447            test_b = valid_test_configs[448                (valid_test_configs["path_type"] == "Go-up-ramp") &449                (valid_test_configs["target"] == f"Target-{not_selected}")450                ]451            test_b = test_b.iloc[random.choice(range(test_b.shape[0]))]452        # elif object_type_test[1] == "pit":453        else:454            test_b = valid_test_configs[455                (valid_test_configs["path_type"] == "Pit_Jump") &456                (valid_test_configs["target"] == f"Target-{not_selected}")457                ]458            if object_type_test[0] == "pit-with-bridge":459                test_b = test_b[460                    (test_b["agent_pos_z"] == test_b[f"obj_{not_selected}_pos_z"])461                ]462            test_b = test_b.iloc[random.choice(range(test_b.shape[0]))]463        if object_type_test[1] in ["pit", "pit-with-bridge"] and object_type_test[0] == "pit-with-bridge":464            test_a = valid_test_configs[465                (valid_test_configs["target"] == f"Target-{selected_target}") &466                (valid_test_configs["path_type"] == "Cross-Bridge") &467                (valid_test_configs["agent_pos_z"] == test_b["agent_pos_z"]) &468                (valid_test_configs[f"obj_{selected_target}_pos_z"] == test_b[f"obj_{not_selected}_pos_z"]) &469                (valid_test_configs[f"obstacle_{selected_target}_pos_z"] == test_b[f"obj_{not_selected}_pos_z"])470                ]471            test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]472        elif object_type_test[1] in ["pit", "pit-with-bridge"] and object_type_test[0] == "none":473            test_a = valid_test_configs[474                (valid_test_configs["target"] == f"Target-{selected_target}") &475                (valid_test_configs["scene_type"] == "pit_scenes_3_4") &476                (valid_test_configs["path_type"] == "Straight-Target") &477                (valid_test_configs[f"obj_{selected_target}_pos_z"] == test_b[f"obj_{not_selected}_pos_z"])478                ]479            test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]480        elif object_type_test[0] == "none":481            pox = 0 if selected_target == "1" else 6482            test_a = valid_test_configs[483                (valid_test_configs["target"] == f"Target-{selected_target}") &484                (valid_test_configs["scene_type"] == "barrier_scenes_3_4") &485                (valid_test_configs["path_type"] == "Straight-Target") &486                # 1 Because both ramp and platform have fixed z values which is 1487                (valid_test_configs[f"obj_{selected_target}_pos_z"] == 1) &488                (valid_test_configs[f"obj_{selected_target}_pos_x"] == pox)489                ]490            test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]491        elif object_type_test[0] == "barrier_with_door":492            test_a = valid_test_configs[493                (valid_test_configs["target"] == f"Target-{selected_target}") &494                (valid_test_configs["path_type"] == "barrier-door") &495                (valid_test_configs[f"obstacle_height_{selected_target}"].isin([5, 6])) &496                (valid_test_configs["agent_pos_z"] == test_b["agent_pos_z"]) &497                (valid_test_configs[f"obstacle_{selected_target}_pos_z"] == test_b ["agent_pos_z"]) &498                (valid_test_configs[f"obj_{selected_target}_pos_z"] == test_b["agent_pos_z"])499                ]500            test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]501        return [test_a, test_b]502def scene_1_goal_preference_v1(scenario_sub_type, selected_target, switch_goals, valid_configs, target_1_pos_to_target_2_pos, history,503                               valid_configs_jumps):504    while True:505        type_ = random.choice(["jump", "go-around"])506        not_selected = "2" if selected_target == "1" else "1"507        if scenario_sub_type in ["Type-1.1", "Type-1.1.0__1.2",  "Type-1.2.0__1.2"]:508            valid_configs_for_subtype = valid_configs[(valid_configs[f"obstacle_height_{selected_target}"] == 0)509            ]510            valid_configs_for_subtype_target = valid_configs_for_subtype[511                (valid_configs_for_subtype["target"] == f"Target-{selected_target}") &512                (valid_configs_for_subtype[f"target-{selected_target}-distance"] > 1.5)513                ]514            fam = valid_configs_for_subtype_target.iloc[515                random.choice(range(valid_configs_for_subtype_target.shape[0]))]516            # Switch the goals positions517            if scenario_sub_type == "Type-1.1":518                target_2_test = valid_configs_for_subtype[519                    (valid_configs_for_subtype[f"obj_{not_selected}_pos_x"] ==520                     target_1_pos_to_target_2_pos[f"target_{selected_target}"][fam[f"obj_{selected_target}_pos_x"]]) &521                    (valid_configs_for_subtype[f"obj_{not_selected}_pos_z"] == fam[f"obj_{selected_target}_pos_z"]) &522                    (valid_configs_for_subtype[f"obstacle_height_{not_selected}"] == 0) &523                    (valid_configs_for_subtype["agent_pos_z"] == fam["agent_pos_z"]) &524                    (valid_configs_for_subtype["target"] == f"Target-{not_selected}")525                    ].iloc[0]526                if switch_goals:527                    return [fam], [target_2_test, fam], history, switch_goals528                else:529                    return [fam], [fam, target_2_test], history, switch_goals530            if switch_goals:531                selected_target, not_selected = not_selected, selected_target532            if scenario_sub_type == "Type-1.1.0__1.2":533                try:534                    valid_configs_for_testing = valid_configs[535                        (valid_configs[f"target-{selected_target}-distance"] < 2) &536                        (valid_configs[f"obstacle_height_{selected_target}"] == 0) &537                        (valid_configs["path_type"] == "Straight-Target") &538                        (valid_configs["agent_pos_z"] == fam["agent_pos_z"])539                        ]540                    test_a = valid_configs_for_testing[541                        (valid_configs_for_testing["target"] == f"Target-{selected_target}")542                    ]543                    test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]544                    test_b = valid_configs[545                        (valid_configs[f"target-{not_selected}-distance"] > 3) &546                        (valid_configs["target"] == f"Target-{not_selected}") &547                        (valid_configs["path_type"] == "Straight-Target") &548                        (valid_configs["agent_pos_z"] == fam["agent_pos_z"])549                        ].iloc[0]550                    return [fam], [test_a, test_b], history, switch_goals551                except:552                    continue553            elif scenario_sub_type == "Type-1.2.0__1.2":554                pos_x = 0 if selected_target == "1" else 6555                valid_configs_for_testing = valid_configs[556                    (valid_configs[f"obstacle_height_{selected_target}"] == 0) &557                    (valid_configs[f"obj_{selected_target}_pos_x"] == pos_x) &558                    (valid_configs["path_type"] == "Straight-Target") &559                    (valid_configs["agent_pos_z"] == fam["agent_pos_z"])560                    ]561                test_a = valid_configs_for_testing[562                    (valid_configs_for_testing["target"] == f"Target-{selected_target}")563                ]564                test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]565                test_b = valid_configs[566                    (valid_configs["target"] == f"Target-{not_selected}") &567                    (valid_configs[f"obstacle_height_{not_selected}"] != 0) &568                    (valid_configs[f"obstacle_depth_{not_selected}"].isin(569                        [3, 4, 5])) &570                    (valid_configs["agent_pos_z"] == fam["agent_pos_z"]) &571                    (valid_configs[f"obj_{not_selected}_pos_z"] == test_a[f"obj_{selected_target}_pos_z"])572                    ].iloc[0]573                return [fam], [test_a, test_b], history, switch_goals574        elif scenario_sub_type in ["Type-1.3", "Type-2.1.0__1.4", "Type-2.2.0__1.4"]:575            if type_ == "jump":576                valid_configs_fam, valid_config_test = valid_configs_jumps, valid_configs577            else:578                valid_configs_fam, valid_config_test = valid_configs, valid_configs_jumps579            valid_configs_for_subtype = valid_configs_fam[580                (valid_configs_fam[f"obstacle_height_{selected_target}"] != 0) &581                (valid_configs_fam[f"obstacle_depth_{selected_target}"].isin([3, 4, 5]))582                ]583            valid_configs_for_subtype_target = valid_configs_for_subtype[584                valid_configs_for_subtype["target"] == f"Target-{selected_target}"]585            fam = valid_configs_for_subtype_target.iloc[random.choice(range(valid_configs_for_subtype_target.shape[0]))]586            if switch_goals:587                selected_target, not_selected = not_selected, selected_target588            if scenario_sub_type == "Type-1.3":589                pos_x = 0 if not_selected == "1" else 6590                valid_configs_for_testing = valid_config_test[591                    (valid_config_test[f"obstacle_height_{selected_target}"] != 0) &592                    (valid_config_test[f"obstacle_depth_{selected_target}"].isin(593                        [3, 4, 5])) &594                    (valid_config_test["agent_pos_z"] == fam["agent_pos_z"])595                    ]596                test_a = valid_configs_for_testing[597                    (valid_configs_for_testing["target"] == f"Target-{selected_target}")598                ]599                test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]600                test_b = valid_config_test[601                    (valid_config_test[f"obstacle_height_{not_selected}"] == test_a[f"obstacle_height_{selected_target}"]) &602                    (valid_config_test[f"obstacle_width_{not_selected}"] == test_a[f"obstacle_width_{selected_target}"]) &603                    (valid_config_test[f"obstacle_depth_{not_selected}"] == test_a[f"obstacle_depth_{selected_target}"]) &604                    (valid_config_test[f"obj_{not_selected}_pos_z"] == test_a[f"obj_{selected_target}_pos_z"]) &605                    (valid_config_test["target"] == f"Target-{not_selected}") &606                    (valid_config_test["agent_pos_z"] == fam["agent_pos_z"]) &607                    (valid_config_test[f"obj_{not_selected}_pos_z"] == test_a[f"obj_{selected_target}_pos_z"])608                    ].iloc[0]609                return [fam], [test_a, test_b], history, switch_goals610            elif scenario_sub_type == "Type-2.1.0__1.4":611                try:612                    valid_configs_for_testing = valid_configs[613                        (valid_configs[f"target-{selected_target}-distance"] < 2) &614                        (valid_configs["obstacle_height_1"] == 0) &615                        (valid_configs["obstacle_height_2"] == 0) &616                        (valid_configs["path_type"] == "Straight-Target") &617                        (valid_configs["agent_pos_z"] == fam["agent_pos_z"])618                        ]619                    test_a = valid_configs_for_testing[620                        (valid_configs_for_testing["target"] == f"Target-{selected_target}")621                    ]622                    test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]623                    test_b = valid_configs[624                        (valid_configs[f"target-{not_selected}-distance"] > 3) &625                        (valid_configs["target"] == f"Target-{not_selected}") &626                        (valid_configs["agent_pos_z"] == fam["agent_pos_z"]) &627                        (valid_configs["path_type"] == "Straight-Target") &628                        (valid_configs[f"obj_{not_selected}_pos_z"] == test_a[f"obj_{selected_target}_pos_z"])629                        ].iloc[0]630                    return [fam], [test_a, test_b], history, switch_goals631                except:632                    continue633            elif scenario_sub_type == "Type-2.2.0__1.4":634                pos_x = 0 if selected_target == "1" else 6635                valid_configs_for_testing = valid_configs[636                    (valid_configs[f"obstacle_height_{selected_target}"] == 0) &637                    (valid_configs[f"obj_{selected_target}_pos_x"] == pos_x) &638                    (valid_configs["path_type"] == "Straight-Target") &639                    (valid_configs["agent_pos_z"] == fam["agent_pos_z"])640                    ]641                test_a = valid_configs_for_testing[642                    (valid_configs_for_testing["target"] == f"Target-{selected_target}")643                ]644                test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]645                test_b = valid_config_test[646                    (valid_config_test["target"] == f"Target-{not_selected}") &647                    (valid_config_test[f"obstacle_height_{not_selected}"] != 0) &648                    (valid_config_test[f"obstacle_depth_{not_selected}"].isin(649                        [3, 4, 5])) &650                    (valid_config_test["agent_pos_z"] == fam["agent_pos_z"]) &651                    (valid_config_test[f"obj_{not_selected}_pos_z"] == test_a[f"obj_{selected_target}_pos_z"])652                    ].iloc[0]653                return [fam], [test_a, test_b], history, switch_goals654            else:  # scenario_sub_type == "Type-2.2.1"655                pos_x = 0 if not_selected == "1" else 6656                valid_configs_for_testing = valid_config_test[657                    (valid_config_test[f"obstacle_height_{selected_target}"] != 0) &658                    (valid_config_test[f"obstacle_depth_{selected_target}"].isin(659                        [3, 4, 5])) &660                    (valid_config_test["agent_pos_z"] == fam["agent_pos_z"])661                    ]662                test_a = valid_configs_for_testing[663                    (valid_configs_for_testing["target"] == f"Target-{selected_target}")664                ]665                test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]666                test_b = valid_configs[667                    (valid_configs["target"] == f"Target-{not_selected}") &668                    (valid_configs[f"obstacle_height_{not_selected}"] == 0) &669                    (valid_configs["path_type"] == "Straight-Target") &670                    (valid_configs[f"obj_{not_selected}_pos_x"] == pos_x) &671                    (valid_configs["agent_pos_z"] == fam["agent_pos_z"]) &672                    (valid_configs[f"obj_{not_selected}_pos_z"] == test_a[f"obj_{selected_target}_pos_z"])673                    ].iloc[0]674                return [fam], [test_a, test_b], history, switch_goals675def scene_1_goal_preference_v2(scenario_sub_type, selected_target, object_type_fam, object_type_test, valid_test_configs, history, switch_goals):676    """677            type 1.1.0, type 1.2.0 v1 and v2 -> type 1.2678       type 1.0 -> type 1.1679       type 2.0 -> type 1.3680       type 2.1.0, type 2.2.0 v1 and v2 -> type 1.4681        "Fam": ["ramp", "platform", "pit"],682               "Type-1.1": ["barrier", "ramp", "platform", "pit"],683               "Type-1.2.0__1.2": ["barrier", "ramp", "platform", "pit"],684               "Type-1.1.0__1.2": ["barrier"],685               "Type-1.3": ["barrier", "ramp", "platform", "pit"],686               "Type-2.2.0__1.4": ["barrier", "ramp", "platform", "pit"],687               "Type-2.1.0__1.4": ["barrier"],688       """689    not_selected = "2" if selected_target == "1" else "1"690    if scenario_sub_type in ["Type-1.1", "Type-1.2.0__1.2", "Type-1.3", "Type-2.2.0__1.4"]:691        fam_target = selected_target692        if object_type_fam[0] == "platform":693            fam = valid_test_configs[694                (valid_test_configs["path_type"] == "Platform-jump") &695                (valid_test_configs[f"obstacle_height_{not_selected}"] < 2) &696                (valid_test_configs["target"] == f"Target-{selected_target}")697                ]698            if object_type_fam[1] == "barrier_with_door":699                fam = fam[700                    fam["agent_pos_z"] == 1701                ]702            fam = fam.iloc[random.choice(range(fam.shape[0]))]703        elif object_type_fam[0] == "ramp":704            fam = valid_test_configs[705                (valid_test_configs["path_type"] == "Go-up-ramp") &706                (valid_test_configs["target"] == f"Target-{selected_target}")707                ]708            if object_type_fam[1] == "barrier_with_door":709                fam = fam[710                    fam["agent_pos_z"] == 1711                ]712            fam = fam.iloc[random.choice(range(fam.shape[0]))]713        elif object_type_fam[0] == "pit":714            fam = valid_test_configs[715                (valid_test_configs["path_type"] == "Pit_Jump") &716                (valid_test_configs["target"] == f"Target-{selected_target}")717                ]718            if object_type_fam[1] == "pit-with-bridge":719                fam = fam[720                    fam[f"agent_pos_z"] == fam[f"obj_{selected_target}_pos_z"]721                ]722            fam = fam.iloc[random.choice(range(fam.shape[0]))]723        if scenario_sub_type in ["Type-1.1", "Type-1.3"]:724            if object_type_fam[0] == "platform":725                test_a = valid_test_configs[726                    (valid_test_configs["path_type"] == "Platform-jump") &727                    (valid_test_configs[f"obstacle_height_{not_selected}"] == fam[f"obstacle_height_{fam_target}"]) &728                    (valid_test_configs[f"agent_pos_z"] == fam[f"agent_pos_z"]) &729                    (valid_test_configs["target"] == f"Target-{not_selected}")730                    ]731                test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]732            elif object_type_fam[0] == "ramp":733                test_a = valid_test_configs[734                    (valid_test_configs["path_type"] == "Go-up-ramp") &735                    (valid_test_configs[f"obstacle_height_{not_selected}"] == fam[f"obstacle_height_{fam_target}"]) &736                    (valid_test_configs[f"agent_pos_z"] == fam[f"agent_pos_z"]) &737                    (valid_test_configs["target"] == f"Target-{not_selected}")738                    ]739                test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]740            elif object_type_fam[0] == "pit":741                test_a = valid_test_configs[742                    (valid_test_configs["path_type"] == "Pit_Jump") &743                    (valid_test_configs[f"obstacle_width_{not_selected}"] == fam[f"obstacle_width_{fam_target}"]) &744                    (valid_test_configs[f"obj_{not_selected}_pos_z"] == fam[f"obj_{fam_target}_pos_z"]) &745                    (valid_test_configs[f"agent_pos_z"] == fam[f"agent_pos_z"]) &746                    (valid_test_configs["target"] == f"Target-{not_selected}")747                    ]748                test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]749            if scenario_sub_type == "Type-1.1":750                if switch_goals:751                    return [fam], [test_a, fam], history, switch_goals752                else:753                    return [fam], [fam, test_a], history, switch_goals754            elif scenario_sub_type == "Type-1.3":755                if switch_goals:756                    return [fam], [test_a, fam], history, switch_goals757                else:758                    return [fam], [fam, test_a], history, switch_goals759    # Testing760    if scenario_sub_type in ["Type-1.2.0__1.2", "Type-2.2.0__1.4"]:761        if switch_goals:762            selected_target, not_selected = not_selected, selected_target763        if object_type_test[1] == "platform":764            test_b = valid_test_configs[765                (valid_test_configs["path_type"] == "Platform-jump") &766                (valid_test_configs["agent_pos_z"] == 1) &767                (valid_test_configs[f"obstacle_height_{not_selected}"] < 2) &768                (valid_test_configs["target"] == f"Target-{not_selected}")769            ]770            test_b = test_b.iloc[random.choice(range(test_b.shape[0]))]771        elif object_type_test[1] == "ramp":772            test_b = valid_test_configs[773                (valid_test_configs["path_type"] == "Go-up-ramp") &774                (valid_test_configs["agent_pos_z"] == 1) &775                (valid_test_configs["target"] == f"Target-{not_selected}")776                ]777            test_b = test_b.iloc[random.choice(range(test_b.shape[0]))]778        # elif object_type_test[1] == "pit":779        else:780            test_b = valid_test_configs[781                (valid_test_configs["path_type"] == "Pit_Jump") &782                (valid_test_configs["target"] == f"Target-{not_selected}")783                ]784            if object_type_test[0] == "pit-with-bridge":785                test_b = test_b[786                    (test_b["agent_pos_z"] == test_b[f"obj_{not_selected}_pos_z"])787                ]788            test_b = test_b.iloc[random.choice(range(test_b.shape[0]))]789        if object_type_test[1] in ["pit", "pit-with-bridge"] and object_type_test[0] == "pit-with-bridge":790            test_a = valid_test_configs[791                (valid_test_configs["target"] == f"Target-{selected_target}") &792                (valid_test_configs["path_type"] == "Cross-Bridge") &793                (valid_test_configs["agent_pos_z"] == test_b["agent_pos_z"]) &794                (valid_test_configs[f"obstacle_width_{selected_target}"] == test_b[f"obstacle_width_{not_selected}"]) &795                (valid_test_configs[f"obj_{selected_target}_pos_z"] == test_b[f"obj_{not_selected}_pos_z"]) &796                (valid_test_configs[f"obstacle_{selected_target}_pos_z"] == test_b[f"obj_{not_selected}_pos_z"])797                ]798            test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]799        elif object_type_test[1] in ["pit", "pit-with-bridge"] and object_type_test[0] == "none":800            test_a = valid_test_configs[801                (valid_test_configs["target"] == f"Target-{selected_target}") &802                (valid_test_configs["scene_type"] == "pit_scenes_3_4") &803                (valid_test_configs["path_type"] == "Straight-Target") &804                (valid_test_configs[f"obj_{selected_target}_pos_z"] == test_b[f"obj_{not_selected}_pos_z"]) &805                (valid_test_configs["agent_pos_z"] == test_b["agent_pos_z"])806                ]807            test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]808        elif object_type_test[0] == "none":809            pox = 0 if selected_target == "1" else 6810            test_a = valid_test_configs[811                (valid_test_configs["target"] == f"Target-{selected_target}") &812                (valid_test_configs["scene_type"] == "barrier_scenes_3_4") &813                (valid_test_configs["path_type"] == "Straight-Target") &814                # 1 Because both ramp and platform have fixed z values which is 1815                (valid_test_configs[f"obj_{selected_target}_pos_z"] == 1) &816                (valid_test_configs[f"obj_{selected_target}_pos_x"] == pox) &817                (valid_test_configs["agent_pos_z"] == 1)818                ]819            test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]820        elif object_type_test[0] == "barrier_with_door":821            test_a = valid_test_configs[822                (valid_test_configs["target"] == f"Target-{selected_target}") &823                (valid_test_configs["path_type"] == "barrier-door") &824                (valid_test_configs[f"obstacle_height_{selected_target}"].isin([5, 6])) &825                (valid_test_configs[f"obstacle_{selected_target}_pos_z"] == 1) &826                (valid_test_configs[f"obj_{selected_target}_pos_z"] == 1) &827                (valid_test_configs["agent_pos_z"] == 1)828                ]829            test_a = test_a.iloc[random.choice(range(test_a.shape[0]))]...test_events.py
Source:test_events.py  
1#emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-2#ex: set sts=4 ts=4 sw=4 et:3### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##4#5#   See the COPYING file distributed along with the PTSA package for the6#   copyright and license terms.7#8### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##9import numpy as np10from numpy.testing import TestCase, assert_array_equal,\11     assert_array_almost_equal12from ptsa.data import ArrayWrapper,BaseWrapper13from ptsa.data.events import Events14class Setup():15    def __init__(self):16        self.test1xyz = np.array([(1.0, 2, 'bla1'), (3.0, 4, 'bla2')],17                                 dtype=[('x', float), ('y', int),18                                        ('z', '|S4')])19        self.test1yz = np.array([(2, 'bla1'), (4, 'bla2')],20                                dtype=[('y', int), ('z', '|S4')])21        self.test1xz = np.array([(1.0, 'bla1'), (3.0, 'bla2')],22                                dtype=[('x', float), ('z', '|S4')])23        self.test1xy = np.array([(1.0, 2), (3.0, 4)],24                                dtype=[('x', float), ('y', int)])25        self.test1x = np.array([(1.0,), (3.0,)],26                               dtype=[('x', float)])27        self.test1y = np.array([(2,), (4,)],28                               dtype=[('y', int)])29        self.test1z = np.array([('bla1',), ('bla2',)],30                               dtype=[('z', '|S4')])31        dw = BaseWrapper()32        self.test2sox = np.array([[(dw, 2, 42.),33                                   (dw, 4, 33.)],34                                  [(dw, 5, 22.),35                                   (dw, 6, 11.)]],36                                 dtype=[('esrc', BaseWrapper),37                                        ('eoffset', int),38                                        ('x', float)])39        self.test2so = np.array([[(dw, 2),40                                  (dw, 4)],41                                 [(dw, 5),42                                  (dw, 6)]],43                                dtype=[('esrc', BaseWrapper),44                                       ('eoffset', int)])45        self.test2sx = np.array([[(dw, 42.),46                                  (dw, 33.)],47                                 [(dw, 22.),48                                  (dw, 11.)]],49                                dtype=[('esrc', BaseWrapper),50                                       ('x', float)])51        self.test2sox1 = np.array([[(1.5, 2, dw),52                                    (1.5, 4, dw)],53                                   [(1.5, 5, dw),54                                    (1.5, 6, dw)]],55                                  dtype=[('esrc', float),56                                         ('eoffset', int),57                                         ('x', BaseWrapper)])58        self.test2sox2 = np.array([[(dw, dw, 42),59                                    (dw, dw, 33)],60                                   [(dw, dw, 22),61                                    (dw, dw, 11)]],62                                  dtype=[('esrc', BaseWrapper),63                                         ('eoffset', BaseWrapper),64                                         ('x', int)])65        self.test2sox3 = np.array([[(3, 2, dw),66                                    (3, 4, dw)],67                                   [(3, 5, dw),68                                    (3, 6, dw)]],69                                  dtype=[('esrc', int),70                                         ('eoffset', int),71                                         ('x', BaseWrapper)])72        self.test2soxy = np.array([[(dw, 2, 42., 1),73                                    (dw, 4, 33., 2)],74                                   [(dw, 5, 22., 3),75                                    (dw, 6, 11., 4)]],76                                  dtype=[('esrc', BaseWrapper),77                                         ('eoffset', int),78                                         ('x', float),('y',int)])79        self.test2soxyz = np.array([[(dw, 2, 42., 1, 'z1'),80                                     (dw, 4, 33., 2, 'z2')],81                                    [(dw, 5, 22., 3, 'z3'),82                                     (dw, 6, 11., 4, 'z4')]],83                                   dtype=[('esrc', BaseWrapper),84                                          ('eoffset', int),85                                          ('x', float),('y',int),('z','|S2')])86        self.test2soy = np.array([[(dw, 2, 1),87                                     (dw, 4, 2)],88                                    [(dw, 5, 3),89                                     (dw, 6, 4)]],90                                 dtype=[('esrc', BaseWrapper),91                                        ('eoffset', int),92                                        ('y',int)])93        self.test2soz = np.array([[(dw, 2, 'z1'),94                                   (dw, 4, 'z2')],95                                  [(dw, 5, 'z3'),96                                   (dw, 6, 'z4')]],97                                 dtype=[('esrc', BaseWrapper),98                                        ('eoffset', int),99                                        ('z','|S2')])100        self.test2soyz = np.array([[(dw, 2, 1, 'z1'),101                                    (dw, 4, 2, 'z2')],102                                   [(dw, 5, 3, 'z3'),103                                    (dw, 6, 4, 'z4')]],104                                  dtype=[('esrc', BaseWrapper),105                                         ('eoffset', int),106                                         ('y', int),('z', '|S2')])107        self.test2soxz = np.array([[(dw, 2, 42., 'z1'),108                                    (dw, 4, 33., 'z2')],109                                   [(dw, 5, 22., 'z3'),110                                    (dw, 6, 11., 'z4')]],111                                  dtype=[('esrc', BaseWrapper),112                                         ('eoffset', int),113                                         ('x', float),('z', '|S2')])114class test_Events(TestCase):115    def setUp(self):116        self.dat = np.random.rand(10,1000)117        self.aw = ArrayWrapper(self.dat,200)118        self.eoffsets = [80,140,270]119    def test_new(self):120        tst = Setup()121        test = tst.test1xyz.view(Events)122        test = tst.test1xy.view(Events)123        test = tst.test1xz.view(Events)124        test = tst.test1yz.view(Events)125        test = tst.test1x.view(Events)126        test = tst.test1y.view(Events)127        test = tst.test1z.view(Events)128        test = tst.test2sox.view(Events)129        test = tst.test2so.view(Events)130        test = tst.test2sx.view(Events)131        test = tst.test2sox1.view(Events)132        test = tst.test2sox2.view(Events)133        test = tst.test2sox3.view(Events)134        test = tst.test2soxy.view(Events)135        test = tst.test2soxyz.view(Events)136        test = tst.test2soxz.view(Events)137        test = tst.test2soyz.view(Events)138        test = tst.test2soy.view(Events)139        test = tst.test2soz.view(Events)140    def test_remove_fields(self):141        tst = Setup()142        test_a = tst.test1xyz.view(Events).remove_fields('z')143        test_b = tst.test1xy.view(Events)144        assert_array_equal(test_a,test_b)145        test_a = tst.test1xyz.view(Events).remove_fields('y')146        test_b = tst.test1xz.view(Events)147        assert_array_equal(test_a,test_b)148        test_a = tst.test1xyz.view(Events).remove_fields('x')149        test_b = tst.test1yz.view(Events)150        assert_array_equal(test_a,test_b)151        test_a = tst.test1xyz.view(Events).remove_fields(152            'y').remove_fields('z')153        test_b = tst.test1x.view(Events)154        assert_array_equal(test_a,test_b)155        test_a = tst.test1xyz.view(Events).remove_fields('y','z')156        test_b = tst.test1x.view(Events)157        assert_array_equal(test_a,test_b)158        test_a = tst.test1xyz.view(Events).remove_fields('z','y')159        test_b = tst.test1x.view(Events)160        assert_array_equal(test_a,test_b)161        test_a = tst.test1xyz.view(Events).remove_fields(162            'z').remove_fields('y')163        test_b = tst.test1x.view(Events)164        assert_array_equal(test_a,test_b)165        test_a = tst.test1xyz.view(Events).remove_fields(166            'y').remove_fields('x')167        test_b = tst.test1z.view(Events)168        assert_array_equal(test_a,test_b)169        test_a = tst.test1xyz.view(Events).remove_fields('y','x')170        test_b = tst.test1z.view(Events)171        assert_array_equal(test_a,test_b)172        test_a = tst.test1xyz.view(Events).remove_fields('x','y')173        test_b = tst.test1z.view(Events)174        assert_array_equal(test_a,test_b)175        test_a = tst.test1xyz.view(Events).remove_fields(176            'x').remove_fields('y')177        test_b = tst.test1z.view(Events)178        assert_array_equal(test_a,test_b)179        test_a = tst.test1xyz.view(Events).remove_fields(180            'x').remove_fields('z')181        test_b = tst.test1y.view(Events)182        assert_array_equal(test_a,test_b)183        test_a = tst.test1xyz.view(Events).remove_fields('x','z')184        test_b = tst.test1y.view(Events)185        assert_array_equal(test_a,test_b)186        test_a = tst.test1xyz.view(Events).remove_fields('z','x')187        test_b = tst.test1y.view(Events)188        assert_array_equal(test_a,test_b)189        test_a = tst.test1xyz.view(Events).remove_fields(190            'z').remove_fields('x')191        test_b = tst.test1y.view(Events)192        assert_array_equal(test_a,test_b)193        test_a = tst.test1xy.view(Events).remove_fields('y')194        test_b = tst.test1x.view(Events)195        assert_array_equal(test_a,test_b)196        test_a = tst.test1xy.view(Events).remove_fields('x')197        test_b = tst.test1y.view(Events)198        assert_array_equal(test_a,test_b)199        test_a = tst.test1xz.view(Events).remove_fields('z')200        test_b = tst.test1x.view(Events)201        assert_array_equal(test_a,test_b)202        test_a = tst.test1xz.view(Events).remove_fields('x')203        test_b = tst.test1z.view(Events)204        assert_array_equal(test_a,test_b)205        test_a = tst.test1yz.view(Events).remove_fields('z')206        test_b = tst.test1y.view(Events)207        assert_array_equal(test_a,test_b)208        test_a = tst.test1yz.view(Events).remove_fields('y')209        test_b = tst.test1z.view(Events)210        assert_array_equal(test_a,test_b)211        test_a = tst.test2soxyz.view(Events).remove_fields('z')212        test_b = tst.test2soxy.view(Events)213        assert_array_equal(test_a,test_b)214        test_a = tst.test2soxyz.view(Events).remove_fields('y')215        test_b = tst.test2soxz.view(Events)216        assert_array_equal(test_a,test_b)217        test_a = tst.test2soxyz.view(Events).remove_fields('x')218        test_b = tst.test2soyz.view(Events)219        assert_array_equal(test_a,test_b)220        test_a = tst.test2soxyz.view(Events).remove_fields('y','z')221        test_b = tst.test2sox.view(Events)222        assert_array_equal(test_a,test_b)223        test_a = tst.test2soxyz.view(Events).remove_fields('z','y')224        test_b = tst.test2sox.view(Events)225        assert_array_equal(test_a,test_b)226        test_a = tst.test2soxyz.view(Events).remove_fields(227            'z').remove_fields('y')228        test_b = tst.test2sox.view(Events)229        assert_array_equal(test_a,test_b)230        test_a = tst.test2soxyz.view(Events).remove_fields(231            'y').remove_fields('z')232        test_b = tst.test2sox.view(Events)233        assert_array_equal(test_a,test_b)234        test_a = tst.test2soxyz.view(Events).remove_fields('x','y','z')235        test_b = tst.test2so.view(Events)236        assert_array_equal(test_a,test_b)237        test_a = tst.test2soxyz.view(Events).remove_fields('x','z','y')238        test_b = tst.test2so.view(Events)239        assert_array_equal(test_a,test_b)240        test_a = tst.test2soxyz.view(Events).remove_fields('y','x','z')241        test_b = tst.test2so.view(Events)242        assert_array_equal(test_a,test_b)243        test_a = tst.test2soxyz.view(Events).remove_fields('y','z','x')244        test_b = tst.test2so.view(Events)245        assert_array_equal(test_a,test_b)246        test_a = tst.test2soxyz.view(Events).remove_fields('z','y','x')247        test_b = tst.test2so.view(Events)248        assert_array_equal(test_a,test_b)249        test_a = tst.test2soxyz.view(Events).remove_fields('z','x','y')250        test_b = tst.test2so.view(Events)251        assert_array_equal(test_a,test_b)252        test_a = tst.test2soxyz.view(Events).remove_fields(253            'x').remove_fields('y').remove_fields('z')254        test_b = tst.test2so.view(Events)255        assert_array_equal(test_a,test_b)256        test_a = tst.test2soxyz.view(Events).remove_fields(257            'x').remove_fields('z').remove_fields('y')258        test_b = tst.test2so.view(Events)259        assert_array_equal(test_a,test_b)260        test_a = tst.test2soxyz.view(Events).remove_fields(261            'y').remove_fields('x').remove_fields('z')262        test_b = tst.test2so.view(Events)263        assert_array_equal(test_a,test_b)264        test_a = tst.test2soxyz.view(Events).remove_fields(265            'y').remove_fields('z').remove_fields('x')266        test_b = tst.test2so.view(Events)267        assert_array_equal(test_a,test_b)268        test_a = tst.test2soxyz.view(Events).remove_fields(269            'z').remove_fields('x').remove_fields('y')270        test_b = tst.test2so.view(Events)271        assert_array_equal(test_a,test_b)272        test_a = tst.test2soxyz.view(Events).remove_fields(273            'z').remove_fields('y').remove_fields('x')274        test_b = tst.test2so.view(Events)275        assert_array_equal(test_a,test_b)276    def test_add_fields(self):277        tst = Setup()278        x = np.array([1.0,3.0])279        y = np.array([2,4])280        z = np.array(['bla1','bla2'])281        test_a = tst.test1xyz.view(Events)282        self.assertRaises(ValueError,tst.test1xyz.view(Events).add_fields,x=x)283        self.assertRaises(ValueError,tst.test1xyz.view(Events).add_fields,y=int)284        test_b = tst.test1xy.view(Events).add_fields(z=z)285        assert_array_equal(test_a,test_b)286        test_a = test_a.add_fields(a=int)287        test_b = test_b.add_fields(a=int)288        self.assertTrue(test_a.shape==test_b.shape)289        assert_array_equal(np.sort(test_a.dtype.names),290                           np.sort(test_b.dtype.names))291        for f,v in test_a.dtype.fields.iteritems():292            if f!='a':293                assert_array_equal(test_a[f],test_b[f])294            self.assertTrue(test_a.dtype[f]==test_b.dtype[f])295        test_a = tst.test1xyz.view(Events)296        test_b = tst.test1x.view(Events).add_fields(y=y).add_fields(z=z)297        assert_array_equal(test_a,test_b)298        test_a = tst.test1xyz.view(Events)299        test_b = tst.test1x.view(Events).add_fields(y=y,z=z)300        assert_array_equal(np.sort(test_a.dtype.names),301                           np.sort(test_b.dtype.names))302        for f,v in test_a.dtype.fields.iteritems():303            assert_array_equal(test_a[f],test_b[f])304            self.assertTrue(test_a.dtype[f]==test_b.dtype[f])305        for field in test_a.dtype.names:306            assert_array_equal(test_a[field],test_b[field])307        test_a = tst.test1xy.view(Events)308        test_b = tst.test1x.view(Events).add_fields(y=y)309        assert_array_equal(test_a,test_b)310        test_a = tst.test1xz.view(Events)311        test_b = tst.test1x.view(Events).add_fields(z=z)312        assert_array_equal(test_a,test_b)313        test_a = tst.test1yz.view(Events)314        test_b = tst.test1y.view(Events).add_fields(z=z)315        assert_array_equal(test_a,test_b)316        x = np.array([[42.,33.],[22.,11.]])317        y = np.array([[1,2],[3,4]])318        z = np.array([['z1','z2'],['z3','z4']])319        test_a = tst.test2soxyz.view(Events)320        test_b = tst.test2soxy.view(Events).add_fields(z=z)321        assert_array_equal(test_a,test_b)322        test_a = tst.test2soxyz.view(Events)323        test_b = tst.test2sox.view(Events).add_fields(y=y,z=z)324        assert_array_equal(np.sort(test_a.dtype.names),325                           np.sort(test_b.dtype.names))326        for f,v in test_a.dtype.fields.iteritems():327            assert_array_equal(test_a[f],test_b[f])328            self.assertTrue(test_a.dtype[f]==test_b.dtype[f])329        for field in test_a.dtype.names:330            assert_array_equal(test_a[field],test_b[field])331        test_a = tst.test2soxyz.view(Events)332        test_b = tst.test2sox.view(Events).add_fields(y=y).add_fields(z=z)333        assert_array_equal(test_a,test_b)334        test_a = tst.test2soxyz.view(Events)335        test_b = tst.test2so.view(Events).add_fields(x=x).add_fields(336            y=y).add_fields(z=z)337        assert_array_equal(test_a,test_b)338        test_a = tst.test2soxyz.view(Events)339        test_b = tst.test2so.view(Events).add_fields(x=x,y=y,z=z)340        assert_array_equal(np.sort(test_a.dtype.names),341                           np.sort(test_b.dtype.names))342        for f,v in test_a.dtype.fields.iteritems():343            assert_array_equal(test_a[f],test_b[f])344            self.assertTrue(test_a.dtype[f]==test_b.dtype[f])345        346    def test_get_data(self):347        # get data directly from the wrapper348        ed = self.aw.get_event_data(3,self.eoffsets,.5,-.1,.25)349        # create same array by hand:350        ed2 = np.array([self.dat[3,60:161],self.dat[3,120:221],351                        self.dat[3,250:351]])352        assert_array_equal(ed,ed2)353        # get data from a events354        # make some events355        events = np.rec.fromarrays(([self.aw]*len(self.eoffsets),self.eoffsets),356                                   names='esrc,eoffset').view(Events)357        ed3 = events.get_data(3,.5,-.1,.25)358        assert_array_almost_equal(ed[:],ed3[:],decimal=6)359        # get data directly from the wrapper360        ed = self.aw.get_event_data(3,self.eoffsets,.5,.1,.25)361        # create same array by hand:362        ed2 = np.array([self.dat[3,100:201],self.dat[3,160:261],363                        self.dat[3,290:391]])364        assert_array_equal(ed,ed2)365        # get data from a events366        # make some events367        events = np.rec.fromarrays(([self.aw]*len(self.eoffsets),self.eoffsets),368                                   names='esrc,eoffset').view(Events)369        ed3 = events.get_data(3,.5,.1,.25)...benchmark.py
Source:benchmark.py  
1# -*- coding: utf-8 -*-2"""3Created on Sat Jun 16 20:24:56 20124@author: soeren5"""6import optparse7#import numpy as np8import time9import collections10import copy11import cProfile12import sys, os13from jinja2 import Template14sys.path.append(os.getcwd())15sys.path.append("%s/.."%(os.getcwd()))16import grass.lib.gis as libgis17import grass.lib.raster as libraster18import grass.script as core19import pygrass20import ctypes21def test__RasterNumpy_value_access__if():22    test_a = pygrass.RasterNumpy(name="test_a", mtype="CELL", mode="r+")23    test_a.open()24    test_c = pygrass.RasterNumpy(name="test_c", mtype="CELL", mode="w+", overwrite=True)25    test_c.open()26    for row in xrange(test_a.rows):27        for col in xrange(test_a.cols):28            test_c[row, col] = test_a[row, col] > 5029    test_a.close()30    test_c.close()31def test__RasterNumpy_value_access__add():32    test_a = pygrass.RasterNumpy(name="test_a", mode="r+")33    test_a.open()34    test_b = pygrass.RasterNumpy(name="test_b", mode="r+")35    test_b.open()36    test_c = pygrass.RasterNumpy(name="test_c", mtype="DCELL", mode="w+", overwrite=True)37    test_c.open()38    for row in xrange(test_a.rows):39        for col in xrange(test_a.cols):40            test_c[row, col] = test_a[row, col] + test_b[row, col]41    test_a.close()42    test_b.close()43    test_c.close()44def test__RasterNumpy_row_access__if():45    test_a = pygrass.RasterNumpy(name="test_a", mtype="CELL", mode="r+")46    test_a.open()47    test_c = pygrass.RasterNumpy(name="test_c", mtype="CELL", mode="w+", overwrite=True)48    test_c.open()49    for row in xrange(test_a.rows):50        test_c[row] = test_a[row] > 5051    test_a.close()52    test_c.close()53def test__RasterNumpy_row_access__add():54    test_a = pygrass.RasterNumpy(name="test_a", mode="r+")55    test_a.open()56    test_b = pygrass.RasterNumpy(name="test_b", mode="r+")57    test_b.open()58    test_c = pygrass.RasterNumpy(name="test_c", mtype="DCELL", mode="w+", overwrite=True)59    test_c.open()60    for row in xrange(test_a.rows):61        test_c[row] = test_a[row] + test_b[row]62    test_a.close()63    test_b.close()64    test_c.close()65def test__RasterNumpy_map_access__if():66    test_a = pygrass.RasterNumpy(name="test_a", mtype="CELL", mode="r+")67    test_a.open()68    test_c = pygrass.RasterNumpy(name="test_c", mtype="CELL", mode="w+", overwrite=True)69    test_c.open()70    test_c = test_a > 5071    test_a.close()72    test_c.close()73def test__RasterNumpy_map_access__add():74    test_a = pygrass.RasterNumpy(name="test_a", mode="r+")75    test_a.open()76    test_b = pygrass.RasterNumpy(name="test_b", mode="r+")77    test_b.open()78    test_c = pygrass.RasterNumpy(name="test_c", mtype="DCELL", mode="w+", overwrite=True)79    test_c.open()80    test_c = test_a + test_b81    test_a.close()82    test_b.close()83    test_c.close()84def test__RasterSegment_value_access__if():85    test_a = pygrass.RasterSegment(name="test_a")86    test_a.open(mode="r")87    test_c = pygrass.RasterSegment(name="test_c")88    test_c.open(mode="w", mtype="CELL", overwrite=True)89    buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)90    for row in xrange(test_a.rows):91        test_a.get_row(row, buff_a)92        for col in xrange(test_a.cols):93            test_c.put(row, col, buff_a[col] > 50)94    test_a.close()95    test_c.close()96def test__RasterSegment_value_access__add():97    test_a = pygrass.RasterSegment(name="test_a")98    test_a.open(mode="r")99    test_b = pygrass.RasterSegment(name="test_b")100    test_b.open(mode="r")101    test_c = pygrass.RasterSegment(name="test_c")102    test_c.open(mode="w", mtype="DCELL", overwrite=True)103    buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)104    buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)105    for row in xrange(test_a.rows):106        test_a.get_row(row, buff_a)107        test_b.get_row(row,buff_b)108        for col in xrange(test_a.cols):109            test_c.put(row, col, buff_a[col] + buff_b[col])110    test_a.close()111    test_b.close()112    test_c.close()113def test__RasterSegment_row_access__if():114    test_a = pygrass.RasterSegment(name="test_a")115    test_a.open(mode="r")116    test_c = pygrass.RasterSegment(name="test_c")117    test_c.open(mode="w", mtype="CELL", overwrite=True)118    buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)119    for row in xrange(test_a.rows):120        test_a.get_row(row, buff_a)121        test_c.put_row(row, buff_a > 50)122    test_a.close()123    test_c.close()124def test__RasterSegment_row_access__add():125    test_a = pygrass.RasterSegment(name="test_a")126    test_a.open(mode="r")127    test_b = pygrass.RasterSegment(name="test_b")128    test_b.open(mode="r")129    test_c = pygrass.RasterSegment(name="test_c")130    test_c.open(mode="w", mtype="DCELL", overwrite=True)131    buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)132    buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)133    for row in xrange(test_a.rows):134        test_a.get_row(row, buff_a)135        test_b.get_row(row,buff_b)136        test_c.put_row(row, buff_a + buff_b)137    test_a.close()138    test_b.close()139    test_c.close()140def test__RasterRow_value_access__add():141    test_a = pygrass.RasterRow(name="test_a")142    test_a.open(mode="r")143    test_b = pygrass.RasterRow(name="test_b")144    test_b.open(mode="r")145    test_c = pygrass.RasterRow(name="test_c")146    test_c.open(mode="w", mtype="FCELL", overwrite=True)147    buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)148    buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)149    buff_c = pygrass.Buffer(test_b.cols, test_b.mtype)150    for row in xrange(test_a.rows):151        test_a.get_row(row, buff_a)152        test_b.get_row(row,buff_b)153        for col in xrange(test_a.cols):154            buff_c[col] = buff_a[col] + buff_b[col]155        test_c.put_row(buff_c)156    test_a.close()157    test_b.close()158    test_c.close()159def test__RasterRow_value_access__if():160    test_a = pygrass.RasterRow(name="test_a")161    test_a.open(mode="r")162    test_c = pygrass.RasterRow(name="test_c")163    test_c.open(mode="w", mtype="CELL", overwrite=True)164    buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)165    buff_c = pygrass.Buffer(test_a.cols, test_a.mtype)166    for row in xrange(test_a.rows):167        test_a.get_row(row, buff_a)168        for col in xrange(test_a.cols):169            buff_c[col] = buff_a[col] > 50170        test_c.put_row(buff_c)171    test_a.close()172    test_c.close()173def test__RasterRowIO_row_access__add():174    test_a = pygrass.RasterRowIO(name="test_a")175    test_a.open(mode="r")176    test_b = pygrass.RasterRowIO(name="test_b")177    test_b.open(mode="r")178    test_c = pygrass.RasterRowIO(name="test_c")179    test_c.open(mode="w", mtype="FCELL", overwrite=True)180    buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)181    buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)182    for row in xrange(test_a.rows):183        test_a.get_row(row, buff_a)184        test_b.get_row(row,buff_b)185        test_c.put_row(buff_a + buff_b)186    test_a.close()187    test_b.close()188    test_c.close()189def test__RasterRowIO_row_access__if():190    test_a = pygrass.RasterRowIO(name="test_a")191    test_a.open(mode="r")192    test_c = pygrass.RasterRowIO(name="test_c")193    test_c.open(mode="w", mtype="CELL", overwrite=True)194    buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)195    for row in xrange(test_a.rows):196        test_a.get_row(row, buff_a)197        test_c.put_row(buff_a > 50)198    test_a.close()199    test_c.close()200def test__RasterRow_row_access__add():201    test_a = pygrass.RasterRow(name="test_a")202    test_a.open(mode="r")203    test_b = pygrass.RasterRow(name="test_b")204    test_b.open(mode="r")205    test_c = pygrass.RasterRow(name="test_c")206    test_c.open(mode="w", mtype="FCELL", overwrite=True)207    buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)208    buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)209    for row in xrange(test_a.rows):210        test_a.get_row(row, buff_a)211        test_b.get_row(row,buff_b)212        test_c.put_row(buff_a + buff_b)213    test_a.close()214    test_b.close()215    test_c.close()216def test__RasterRow_row_access__if():217    test_a = pygrass.RasterRow(name="test_a")218    test_a.open(mode="r")219    test_c = pygrass.RasterRow(name="test_c")220    test_c.open(mode="w", mtype="CELL", overwrite=True)221    buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)222    for row in xrange(test_a.rows):223        test_a.get_row(row, buff_a)224        test_c.put_row(buff_a > 50)225    test_a.close()226    test_c.close()227def test__mapcalc__add():228    core.mapcalc("test_c = test_a + test_b", quite=True, overwrite=True)229def test__mapcalc__if():230    core.mapcalc("test_c = if(test_a > 50, 1, 0)", quite=True, overwrite=True)231def mytimer(func, runs=1):232    times = []233    t = 0.0234    for _ in xrange(runs):235        start = time.time()236        func()237        end = time.time()238        times.append(end - start)239        t = t + end - start240    return t/runs, times241def run_benchmark(resolution_list, runs, testdict, profile):242    regions = []243    for resolution in resolution_list:244        core.use_temp_region()245        core.run_command('g.region', e=50, w=-50, n=50, s=-50, res=resolution, flags='p')246        # Adjust the computational region for this process247        region = libgis.Cell_head()248        libraster.Rast_get_window(ctypes.byref(region))249        region.e = 50250        region.w = -50251        region.n = 50252        region.s = -50253        region.ew_res = resolution254        region.ns_res = resolution255        libgis.G_adjust_Cell_head(ctypes.byref(region), 0, 0)256        libraster.Rast_set_window(ctypes.byref(region))257        libgis.G_set_window(ctypes.byref(region))258        # Create two raster maps with random numbers259        core.mapcalc("test_a = rand(0, 100)", quite=True, overwrite=True)260        core.mapcalc("test_b = rand(0.0, 1.0)", quite=True, overwrite=True)261        result = collections.OrderedDict()262        result['res'] = resolution263        result['cols'] = region.cols264        result['rows'] = region.rows265        result['cells'] = region.rows * region.cols266        result['results'] = copy.deepcopy(testdict)267        for execmode, operation in result['results'].iteritems():268            print(execmode)269            for oper, operdict in operation.iteritems():270                operdict['time'], operdict['times'] = mytimer(operdict['func'],runs)271                if profile:272                    filename = '{}_{}_{}'.format(execmode, oper, profile)273                    cProfile.runctx(operdict['func'].__name__ + '()',274                                    globals(), locals(), filename = filename)275                print('    {0}: {1: 40.6f}s'.format(oper, operdict['time']))276                del(operdict['func'])277        regions.append(result)278        core.del_temp_region()279    return regions280def get_testlist(loc):281    testlist = [test for test in loc.keys() if 'test' in test[:5]]282    testlist.sort()283    return testlist284def get_testdict(testlist):285    testdict = collections.OrderedDict()286    for testfunc in testlist:287        #import pdb; pdb.set_trace()288        dummy, execmode, operation = testfunc.split('__')289        if execmode in testdict.keys():290            testdict[execmode][operation] = collections.OrderedDict()291            testdict[execmode][operation]['func'] = loc[testfunc]292        else:293            testdict[execmode] = collections.OrderedDict()294            testdict[execmode][operation] = collections.OrderedDict()295            testdict[execmode][operation]['func'] = loc[testfunc]296    return testdict297def print_test(testdict):298    for execmode, operation in testdict.iteritems():299        print execmode300        for oper, operdict in operation.iteritems():301            print '    ', oper302            for key, value in operdict.iteritems():303                print '        ', key304TXT = u"""305{% for region in regions %}306{{ '#'*60 }}307### Benchmark cols = {{ region.cols }} rows = {{ region.rows}} cells = {{ region.cells }}308{{ '#'*60 }}309    # equation: c = a + b310    {% for execmode, operation in region.results.iteritems() %}311        {{ "%-30s - %5s % 12.6fs"|format(execmode, 'add', operation.add.time) }}312    {%- endfor %}313    # equation: c = if a > 50 then 1 else 0314    {% for execmode, operation in region.results.iteritems() %}315        {{ "%-30s - %5s % 12.6fs"|format(execmode, 'if', operation.if.time) }}316    {%- endfor %}317{%- endfor %}318"""319CSV = """Class; Mode; Operation;320"""321RST = """322"""323#>>> txt = Template(TxT)324#>>> txt.render(name='John Doe')325def get_txt(results):326    txt = Template(TXT)327    return txt.render(regions = results)328#classes for required options329strREQUIRED = 'required'330class OptionWithDefault(optparse.Option):331    ATTRS = optparse.Option.ATTRS + [strREQUIRED]332    def __init__(self, *opts, **attrs):333        if attrs.get(strREQUIRED, False):334            attrs['help'] = '(Required) ' + attrs.get('help', "")335        optparse.Option.__init__(self, *opts, **attrs)336class OptionParser(optparse.OptionParser):337    def __init__(self, **kwargs):338        kwargs['option_class'] = OptionWithDefault339        optparse.OptionParser.__init__(self, **kwargs)340    def check_values(self, values, args):341        for option in self.option_list:342            if hasattr(option, strREQUIRED) and option.required:343                if not getattr(values, option.dest):344                    self.error("option %s is required".format(str(option)))345        return optparse.OptionParser.check_values(self, values, args)346def main(testdict):347    """Main function"""348    #usage349    usage = "usage: %prog [options] raster_map"350    parser = OptionParser(usage=usage)351    # ntime352    parser.add_option("-n", "--ntimes", dest="ntime",default=5, type="int",353                      help="Number of run for each test.")354    # res355    parser.add_option("-r", "--resolution", action="store", type="string",356                      dest="res", default = '1,0.25',357                      help="Resolution list separete by comma.")358    # fmt359    parser.add_option("-f", "--fmt", action="store", type="string",360                      dest="fmt", default = 'txt',361                      help="Choose the output format: 'txt', 'csv', 'rst'.")362    # output363    parser.add_option("-o", "--output", action="store", type="string",364                      dest="output", help="The output filename.")365    # store366    parser.add_option("-s", "--store", action="store", type="string",367                      dest="store", help="The filename of pickle obj.")368    # profile369    parser.add_option("-p", "--profile", action="store", type="string",370                      dest="profile", help="The filename of the profile results.")371    #return options and argument372    options, args = parser.parse_args()373    res = [float(r) for r in options.res.split(',')]374    #res = [1, 0.25, 0.1, 0.05]375    results = run_benchmark(res, options.ntime, testdict, options.profile)376    if options.store:377        import pickle378        output = open(options.store, 'wb')379        pickle.dump(results, output)380        output.close()381    #import pdb; pdb.set_trace()382    print get_txt(results)383#add options384if __name__ == "__main__":385    #import pdb; pdb.set_trace()386    loc = locals()387    testlist = get_testlist(loc)388    testdict = get_testdict(testlist)389    #print_test(testdict)390    #import pdb; pdb.set_trace()...snap_test_api.py
Source:snap_test_api.py  
1# -*- coding: utf-8 -*-2# snapshottest: v1 - https://goo.gl/zC4yUc3from __future__ import unicode_literals4from snapshottest import Snapshot5snapshots = Snapshot()6snapshots['test_report_skeleton 1'] = {7    'child_branches': {8        'test_a.py': {9            'child_branches': {10                'TestSuite': {11                    'child_branches': {12                    },13                    'child_leaves': {14                        'test_alpha': {15                            'longrepr': None,16                            'nodeid': 'test_a.py::TestSuite::test_alpha',17                            'short_id': 'test_alpha',18                            'status': 'init'19                        },20                        'test_beta': {21                            'longrepr': None,22                            'nodeid': 'test_a.py::TestSuite::test_beta',23                            'short_id': 'test_beta',24                            'status': 'init'25                        }26                    },27                    'environment_state': 'inactive',28                    'nodeid': 'test_a.py::TestSuite',29                    'short_id': 'TestSuite',30                    'status': 'init'31                }32            },33            'child_leaves': {34                'test_one': {35                    'longrepr': None,36                    'nodeid': 'test_a.py::test_one',37                    'short_id': 'test_one',38                    'status': 'init'39                },40                'test_two': {41                    'longrepr': None,42                    'nodeid': 'test_a.py::test_two',43                    'short_id': 'test_two',44                    'status': 'init'45                }46            },47            'environment_state': 'inactive',48            'nodeid': 'test_a.py',49            'short_id': 'test_a.py',50            'status': 'init'51        },52        'test_b.py': {53            'child_branches': {54            },55            'child_leaves': {56                'test_http_service': {57                    'longrepr': None,58                    'nodeid': 'test_b.py::test_http_service',59                    'short_id': 'test_http_service',60                    'status': 'init'61                },62                'test_one': {63                    'longrepr': None,64                    'nodeid': 'test_b.py::test_one',65                    'short_id': 'test_one',66                    'status': 'init'67                },68                'test_two': {69                    'longrepr': None,70                    'nodeid': 'test_b.py::test_two',71                    'short_id': 'test_two',72                    'status': 'init'73                }74            },75            'environment_state': 'inactive',76            'nodeid': 'test_b.py',77            'short_id': 'test_b.py',78            'status': 'init'79        }80    },81    'child_leaves': {82    },83    'environment_state': 'stopped',84    'nodeid': '',85    'short_id': 'pytest_examples',86    'status': 'init'87}88snapshots['test_run_test 1'] = [89    {90        'args': [91            {92                'child_branches': {93                    'test_a.py': {94                        'child_branches': {95                            'TestSuite': {96                                'child_branches': {97                                },98                                'child_leaves': {99                                    'test_alpha': {100                                        'longrepr': None,101                                        'nodeid': 'test_a.py::TestSuite::test_alpha',102                                        'short_id': 'test_alpha',103                                        'status': 'init'104                                    },105                                    'test_beta': {106                                        'longrepr': None,107                                        'nodeid': 'test_a.py::TestSuite::test_beta',108                                        'short_id': 'test_beta',109                                        'status': 'init'110                                    }111                                },112                                'environment_state': 'inactive',113                                'nodeid': 'test_a.py::TestSuite',114                                'short_id': 'TestSuite',115                                'status': 'init'116                            }117                        },118                        'child_leaves': {119                            'test_one': {120                                'longrepr': None,121                                'nodeid': 'test_a.py::test_one',122                                'short_id': 'test_one',123                                'status': 'running'124                            },125                            'test_two': {126                                'longrepr': None,127                                'nodeid': 'test_a.py::test_two',128                                'short_id': 'test_two',129                                'status': 'init'130                            }131                        },132                        'environment_state': 'inactive',133                        'nodeid': 'test_a.py',134                        'short_id': 'test_a.py',135                        'status': 'running'136                    },137                    'test_b.py': {138                        'child_branches': {139                        },140                        'child_leaves': {141                            'test_http_service': {142                                'longrepr': None,143                                'nodeid': 'test_b.py::test_http_service',144                                'short_id': 'test_http_service',145                                'status': 'init'146                            },147                            'test_one': {148                                'longrepr': None,149                                'nodeid': 'test_b.py::test_one',150                                'short_id': 'test_one',151                                'status': 'init'152                            },153                            'test_two': {154                                'longrepr': None,155                                'nodeid': 'test_b.py::test_two',156                                'short_id': 'test_two',157                                'status': 'init'158                            }159                        },160                        'environment_state': 'inactive',161                        'nodeid': 'test_b.py',162                        'short_id': 'test_b.py',163                        'status': 'init'164                    }165                },166                'child_leaves': {167                },168                'environment_state': 'stopped',169                'nodeid': '',170                'short_id': 'pytest_examples',171                'status': 'running'172            }173        ],174        'name': 'update',175        'namespace': '/'176    },177    {178        'args': [179            {180                'child_branches': {181                    'test_a.py': {182                        'child_branches': {183                            'TestSuite': {184                                'child_branches': {185                                },186                                'child_leaves': {187                                    'test_alpha': {188                                        'longrepr': None,189                                        'nodeid': 'test_a.py::TestSuite::test_alpha',190                                        'short_id': 'test_alpha',191                                        'status': 'init'192                                    },193                                    'test_beta': {194                                        'longrepr': None,195                                        'nodeid': 'test_a.py::TestSuite::test_beta',196                                        'short_id': 'test_beta',197                                        'status': 'init'198                                    }199                                },200                                'environment_state': 'inactive',201                                'nodeid': 'test_a.py::TestSuite',202                                'short_id': 'TestSuite',203                                'status': 'init'204                            }205                        },206                        'child_leaves': {207                            'test_one': {208                                'longrepr': None,209                                'nodeid': 'test_a.py::test_one',210                                'short_id': 'test_one',211                                'status': 'running'212                            },213                            'test_two': {214                                'longrepr': None,215                                'nodeid': 'test_a.py::test_two',216                                'short_id': 'test_two',217                                'status': 'init'218                            }219                        },220                        'environment_state': 'inactive',221                        'nodeid': 'test_a.py',222                        'short_id': 'test_a.py',223                        'status': 'running'224                    },225                    'test_b.py': {226                        'child_branches': {227                        },228                        'child_leaves': {229                            'test_http_service': {230                                'longrepr': None,231                                'nodeid': 'test_b.py::test_http_service',232                                'short_id': 'test_http_service',233                                'status': 'init'234                            },235                            'test_one': {236                                'longrepr': None,237                                'nodeid': 'test_b.py::test_one',238                                'short_id': 'test_one',239                                'status': 'init'240                            },241                            'test_two': {242                                'longrepr': None,243                                'nodeid': 'test_b.py::test_two',244                                'short_id': 'test_two',245                                'status': 'init'246                            }247                        },248                        'environment_state': 'inactive',249                        'nodeid': 'test_b.py',250                        'short_id': 'test_b.py',251                        'status': 'init'252                    }253                },254                'child_leaves': {255                },256                'environment_state': 'stopped',257                'nodeid': '',258                'short_id': 'pytest_examples',259                'status': 'running'260            }261        ],262        'name': 'update',263        'namespace': '/'264    },265    {266        'args': [267            {268                'child_branches': {269                    'test_a.py': {270                        'child_branches': {271                            'TestSuite': {272                                'child_branches': {273                                },274                                'child_leaves': {275                                    'test_alpha': {276                                        'longrepr': None,277                                        'nodeid': 'test_a.py::TestSuite::test_alpha',278                                        'short_id': 'test_alpha',279                                        'status': 'init'280                                    },281                                    'test_beta': {282                                        'longrepr': None,283                                        'nodeid': 'test_a.py::TestSuite::test_beta',284                                        'short_id': 'test_beta',285                                        'status': 'init'286                                    }287                                },288                                'environment_state': 'inactive',289                                'nodeid': 'test_a.py::TestSuite',290                                'short_id': 'TestSuite',291                                'status': 'init'292                            }293                        },294                        'child_leaves': {295                            'test_one': {296                                'longrepr': None,297                                'nodeid': 'test_a.py::test_one',298                                'short_id': 'test_one',299                                'status': 'passed'300                            },301                            'test_two': {302                                'longrepr': None,303                                'nodeid': 'test_a.py::test_two',304                                'short_id': 'test_two',305                                'status': 'init'306                            }307                        },308                        'environment_state': 'inactive',309                        'nodeid': 'test_a.py',310                        'short_id': 'test_a.py',311                        'status': 'passed'312                    },313                    'test_b.py': {314                        'child_branches': {315                        },316                        'child_leaves': {317                            'test_http_service': {318                                'longrepr': None,319                                'nodeid': 'test_b.py::test_http_service',320                                'short_id': 'test_http_service',321                                'status': 'init'322                            },323                            'test_one': {324                                'longrepr': None,325                                'nodeid': 'test_b.py::test_one',326                                'short_id': 'test_one',327                                'status': 'init'328                            },329                            'test_two': {330                                'longrepr': None,331                                'nodeid': 'test_b.py::test_two',332                                'short_id': 'test_two',333                                'status': 'init'334                            }335                        },336                        'environment_state': 'inactive',337                        'nodeid': 'test_b.py',338                        'short_id': 'test_b.py',339                        'status': 'init'340                    }341                },342                'child_leaves': {343                },344                'environment_state': 'stopped',345                'nodeid': '',346                'short_id': 'pytest_examples',347                'status': 'passed'348            }349        ],350        'name': 'update',351        'namespace': '/'352    }...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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
