How to use heuristic method in fMBT

Best Python code snippet using fMBT_python

test_lm_cut.py

Source:test_lm_cut.py Github

copy

Full Screen

...245 for f in heuristic.goal_plateau} == {heuristic.explicit_goal, 'g'}246def test_lm_cut_unsolvable():247 task = _get_simple_task_unsolvable()248 heuristic = LmCutHeuristic(task)249 h_val = heuristic(make_root_node(task.initial_state))250 heuristic.compute_goal_plateau(heuristic.explicit_goal)251 assert h_val == float('inf')252def test_lm_cut_at_goal():253 task = _get_simple_task_at_goal()254 heuristic = LmCutHeuristic(task)255 h_val = heuristic(make_root_node(task.initial_state))256 heuristic.compute_goal_plateau(heuristic.explicit_goal)257 assert h_val == 0.258def test_lm_cut_mark_multiple_goal():259 task = _get_intermediate_task()260 heuristic = LmCutHeuristic(task)261 heuristic.compute_hmax(task.initial_state)262 # artificially alter operator costs to get a larger goal plateau263 heuristic.relaxed_ops['op4'].cost = 0.264 heuristic.compute_goal_plateau(heuristic.explicit_goal)265 assert ({f.name for f in heuristic.goal_plateau} in266 [{heuristic.explicit_goal, 'v4', 'g'},267 {heuristic.explicit_goal, 'v5', 'g'}])268def test_two_times_hmax_same_result():269 task = _get_intermediate_task()270 heuristic = LmCutHeuristic(task)271 heuristic.compute_hmax(task.initial_state)272 heuristic.compute_hmax(task.initial_state)273 # artificially alter operator costs to get a larger goal plateau274 heuristic.relaxed_ops['op4'].cost = 0.275 heuristic.compute_goal_plateau(heuristic.explicit_goal)276 assert ({f.name for f in heuristic.goal_plateau} in277 [{heuristic.explicit_goal, 'v4', 'g'},278 {heuristic.explicit_goal, 'v5', 'g'}])279def test_lm_cut_compute_single_cut():280 task1 = _get_intermediate_task_two_paths()281 heuristic = LmCutHeuristic(task1)282 heuristic.compute_hmax(task1.initial_state)283 heuristic.goal_plateau.clear()284 heuristic.compute_goal_plateau(heuristic.explicit_goal)285 cut = heuristic.find_cut(task1.initial_state)286 assert [op.name for op in cut] == ['op4']287def test_lm_cut_heuristic_value():288 task1 = _get_intermediate_task_two_paths()289 heuristic = LmCutHeuristic(task1)290 h_val = heuristic(make_root_node(task1.initial_state))291 assert h_val == 4.292def test_lm_cut_heuristic_value_two_initial_facts():293 task1 = _get_intermediate_task_two_initial_facts()294 heuristic = LmCutHeuristic(task1)295 h_val = heuristic(make_root_node(task1.initial_state))296 assert h_val == 4.297def test_lm_cut_heuristic_value_simple_task_always_true():298 task1 = _get_simple_task_always_true()299 heuristic = LmCutHeuristic(task1)300 h_val = heuristic(make_root_node(task1.initial_state))301 #print('Printing goal plateau')302 #for f in heuristic.goal_plateau:303 # print(repr(f))304 #print('Printing cut')305 #for op in cut:306 # print(repr(op))307 assert h_val == 1.308def test_lm_cut_blocksworld_initial_state():309 parser = Parser('')310 parser.domInput = blocks_dom311 parser.probInput = blocks_problem_1312 domain = parser.parse_domain(False)313 problem = parser.parse_problem(domain, False)314 task = grounding.ground(problem)315 heuristic = LmCutHeuristic(task)316 h_val = heuristic(make_root_node(task.initial_state))317 assert h_val == 6.318def test_lm_cut_blocksworld_complete_astar():319 # run through plan and validate heuristic value320 # the true_h_values are taken from fast downward with astar and lm cut321 # heuristic322 true_h_values = [6., 5., 4., 3., 2., 1., 0.]323 plan_length = 6324 yield py.test.mark.slow(gen_blocks_test_astar), LmCutHeuristic, \325 true_h_values, plan_length326def test_lm_cut_blocksworld_complete_enforced_hillclimbing():327 true_h_values = [6.0, 5.0, 5.0, 4.0, 5.0, 5.0, 6.0, 5.0, 4.0, 3.0, 2.0,328 1.0, 0.0]329 plan_length = 16330 # TODO: Result is currently undeterministic....

Full Screen

Full Screen

pyperplan.py

Source:pyperplan.py Github

copy

Full Screen

1#! /usr/bin/env python32#3# This file is part of pyperplan.4#5# This program is free software: you can redistribute it and/or modify6# it under the terms of the GNU General Public License as published by7# the Free Software Foundation, either version 3 of the License, or8# (at your option) any later version.9#10# This program is distributed in the hope that it will be useful,11# but WITHOUT ANY WARRANTY; without even the implied warranty of12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the13# GNU General Public License for more details.14#15# You should have received a copy of the GNU General Public License16# along with this program. If not, see <http://www.gnu.org/licenses/>17#18# TODO: Give searches and heuristics commandline options and reenable preferred19# operators.20import sys21import os22import re23import logging24import subprocess25import time26try:27 import argparse28except ImportError:29 from external import argparse30from pddl.parser import Parser31import grounding32import search33import heuristics34import tools35from search.model_reconciliation import mce, mme36SEARCHES = {37 'astar': search.astar_search,38 'wastar': search.weighted_astar_search,39 'gbf': search.greedy_best_first_search,40 'bfs': search.breadth_first_search,41 'ehs': search.enforced_hillclimbing_search,42 'ids': search.iterative_deepening_search,43 'sat': search.sat_solve,44}45NUMBER = re.compile(r'\d+')46MRP = {47 'MME': mme.mme_search,48 'MCE': mce.mce_search49}50def get_heuristics():51 """52 Scan all python modules in the "heuristics" directory for classes ending53 with "Heuristic".54 """55 heuristics = []56 src_dir = os.path.dirname(os.path.abspath(__file__))57 heuristics_dir = os.path.abspath(os.path.join(src_dir, 'heuristics'))58 for filename in os.listdir(heuristics_dir):59 if not filename.endswith('.py'):60 continue61 module = tools.import_python_file(os.path.join(heuristics_dir, filename))62 heuristics.extend([getattr(module, cls) for cls in dir(module)63 if cls.endswith('Heuristic') and cls != 'Heuristic' and64 not cls.startswith('_')])65 return heuristics66def _get_heuristic_name(cls):67 name = cls.__name__68 assert name.endswith('Heuristic')69 return name[:-9].lower()70HEURISTICS = {_get_heuristic_name(heur): heur for heur in get_heuristics()}71def validator_available():72 return tools.command_available(['validate', '-h'])73def find_domain(problem):74 """75 This function tries to guess a domain file from a given problem file.76 It first uses a file called "domain.pddl" in the same directory as77 the problem file. If the problem file's name contains digits, the first78 group of digits is interpreted as a number and the directory is searched79 for a file that contains both, the word "domain" and the number.80 This is conforming to some domains where there is a special domain file81 for each problem, e.g. the airport domain.82 @param problem The pathname to a problem file83 @return A valid name of a domain84 """85 dir, name = os.path.split(problem)86 number_match = NUMBER.search(name)87 number = number_match.group(0)88 domain = os.path.join(dir, 'domain.pddl')89 for file in os.listdir(dir):90 if 'domain' in file and number in file:91 domain = os.path.join(dir, file)92 break93 if not os.path.isfile(domain):94 logging.error('Domain file "{0}" can not be found'.format(domain))95 sys.exit(1)96 logging.info('Found domain {0}'.format(domain))97 return domain98def _parse(domain_file, problem_file):99 # Parsing100 parser = Parser(domain_file, problem_file)101 logging.info('Parsing Domain {0}'.format(domain_file))102 domain = parser.parse_domain()103 logging.info('Parsing Problem {0}'.format(problem_file))104 problem = parser.parse_problem(domain)105 logging.debug(domain)106 logging.info('{0} Predicates parsed'.format(len(domain.predicates)))107 logging.info('{0} Actions parsed'.format(len(domain.actions)))108 logging.info('{0} Objects parsed'.format(len(problem.objects)))109 logging.info('{0} Constants parsed'.format(len(domain.constants)))110 return problem111def _ground(problem):112 logging.info('Grounding start: {0}'.format(problem.name))113 task = grounding.ground(problem)114 logging.info('Grounding end: {0}'.format(problem.name))115 logging.info('{0} Variables created'.format(len(task.facts)))116 logging.info('{0} Operators created'.format(len(task.operators)))117 return task118def _search(task, search, heuristic, use_preferred_ops=False):119 logging.info('Search start: {0}'.format(task.name))120 if heuristic:121 if use_preferred_ops:122 solution = search(task, heuristic, use_preferred_ops)123 else:124 solution = search(task, heuristic)125 else:126 solution = search(task)127 logging.info('Search end: {0}'.format(task.name))128 return solution129def _write_solution(solution, filename):130 assert solution is not None131 with open(filename, 'w') as file:132 for op in solution:133 print(op.name, file=file)134def search_plan(domain_file, problem_file, search, heuristic_class,135 use_preferred_ops=False):136 """137 Parses the given input files to a specific planner task and then tries to138 find a solution using the specified search algorithm and heuristics.139 @param domain_file The path to a domain file140 @param problem_file The path to a problem file in the domain given by141 domain_file142 @param search A callable that performs a search on the task's143 search space144 @param heuristic_class A class implementing the heuristic_base.Heuristic145 interface146 @return A list of actions that solve the problem147 """148 problem = _parse(domain_file, problem_file)149 task = _ground(problem)150 heuristic = None151 if not heuristic_class is None:152 heuristic = heuristic_class(task)153 print(task)154 print(task.get_meta_task(task))155 search_start_time = time.clock()156 if use_preferred_ops and isinstance(heuristic, heuristics.hFFHeuristic):157 solution = _search(task, search, heuristic, use_preferred_ops=True)158 else:159 solution = _search(task, search, heuristic)160 logging.info('Wall-clock search time: {0:.2}'.format(time.clock() -161 search_start_time))162 print(type(solution[0]))163 return solution164def search_explanation(domain1_file, problem1_file, domain2_file, problem2_file, search, heuristic_class, model_reconcilition):165 problem1 = _parse(domain1_file, problem1_file)166 robot_task = _ground(problem1)167 problem2 = _parse(domain2_file, problem2_file)168 human_task = _ground(problem2)169 heuristic = None170 if not heuristic_class is None:171 heuristic = heuristic_class(robot_task)172 if use_preferred_ops and isinstance(heuristic, heuristics.hFFHeuristic):173 p_r = _search(robot_task, search, heuristic, use_preferred_ops=True)174 else:175 p_r = _search(robot_task, search, heuristic)176 explanation = model_reconcilition(search, heuristic, p_r, robot_task, human_task)177 return explanation178def validate_solution(domain_file, problem_file, solution_file):179 if not validator_available():180 logging.info('validate could not be found on the PATH so the plan can '181 'not be validated.')182 return183 cmd = ['validate', domain_file, problem_file, solution_file]184 exitcode = subprocess.call(cmd, stdout=subprocess.PIPE)185 if exitcode == 0:186 logging.info('Plan correct')187 else:188 logging.warning('Plan NOT correct')189 return exitcode == 0190if __name__ == '__main__':191 # Commandline parsing192 log_levels = ['debug', 'info', 'warning', 'error']193 # get pretty print names for the search algorithms:194 # use the function/class name and strip off '_search'195 def get_callable_names(callables, omit_string):196 names = [c.__name__ for c in callables]197 names = [n.replace(omit_string, '').replace('_', ' ') for n in names]198 return ', '.join(names)199 search_names = get_callable_names(SEARCHES.values(), '_search')200 argparser = argparse.ArgumentParser(201 formatter_class=argparse.ArgumentDefaultsHelpFormatter)202 argparser.add_argument(dest='domain', nargs='?')203 argparser.add_argument(dest='problem')204 argparser.add_argument('-l', '--loglevel', choices=log_levels,205 default='info')206 argparser.add_argument('-H', '--heuristic', choices=HEURISTICS.keys(),207 help='Select a heuristic', default='hff')208 argparser.add_argument('-s', '--search', choices=SEARCHES.keys(),209 help='Select a search algorithm from {0}'.format(search_names),210 default='bfs')211 argparser.add_argument('-e', '--explanations', choices=["MME", "MCE"])212 argparser.add_argument('-d2', '--domain2')213 argparser.add_argument('-p2', '--problem2')214 args = argparser.parse_args()215 logging.basicConfig(level=getattr(logging, args.loglevel.upper()),216 format='%(asctime)s %(levelname)-8s %(message)s',217 stream=sys.stdout)218 hffpo_searches = ['gbf', 'wastar', 'ehs']219 if args.heuristic == 'hffpo' and args.search not in hffpo_searches:220 print('ERROR: hffpo can currently only be used with %s\n' %221 hffpo_searches, file=sys.stderr)222 argparser.print_help()223 exit(2)224 args.problem = os.path.abspath(args.problem)225 if args.domain is None:226 args.domain = find_domain(args.problem)227 else:228 args.domain = os.path.abspath(args.domain)229 search = SEARCHES[args.search]230 heuristic = HEURISTICS[args.heuristic]231 if args.search in ['bfs', 'ids', 'sat']:232 heuristic = None233 logging.info('using search: %s' % search.__name__)234 logging.info('using heuristic: %s' % (heuristic.__name__ if heuristic235 else None))236 use_preferred_ops = (args.heuristic == 'hffpo')237 if args.explanations is None:238 solution = search_plan(args.domain, args.problem, search, heuristic,239 use_preferred_ops=use_preferred_ops)240 if solution is None:241 logging.warning('No solution could be found')242 else:243 solution_file = args.problem + '.soln'244 logging.info('Plan length: %s' % len(solution))245 _write_solution(solution, solution_file)246 validate_solution(args.domain, args.problem, solution_file)247 else:248 if args.domain2 is None or args.problem2 is None:249 print("Error: arguments 'domain2' and 'problem2' required when requesting explanations")250 exit(2)251 else:252 model_reconciliation = MRP[args.explanations]253 solution, explanation = search_explanation(args.domain, args.problem, args.domain2, args.problem2, search, heuristic, model_reconciliation)254 print("Solution :", solution)...

Full Screen

Full Screen

heuristic_test_instances.py

Source:heuristic_test_instances.py Github

copy

Full Screen

...61"""62def _gen_h_values(initial_state, plan, heuristic):63 node = searchspace.SearchNode(initial_state, None, None, None)64 for op in plan:65 h_val = heuristic(node)66 yield h_val67 node = searchspace.SearchNode(op.apply(node.state), None, None, None)68 h_val = heuristic(node)69 yield h_val70def gen_heuristic_test(dom, prob, search_class, heuristic_class, h_values_plan,71 plan_length=None):72 parser = Parser('')73 parser.domInput = dom74 parser.probInput = prob75 domain = parser.parse_domain(False)76 problem = parser.parse_problem(domain, False)77 task = grounding.ground(problem)78 heuristic = heuristic_class(task)79 plan = search_class(task, heuristic)80 if plan_length:81 assert len(plan) == plan_length82 # run through plan and validate heuristic value...

Full Screen

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run fMBT automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful