id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
18,700 | data reshape(num_points labels reshape(num_points visualize and plot the input data set using the following commandsplt figure(plt scatter(datalabelsplt xlabel('dimension 'plt ylabel('dimension 'plt title('data-points'nowbuild the neural network having two hidden layers with neurolab with ten neurons in the first hidden layersix in the second hidden layer and one in the output layer neural_net nl net newff([[min_valmax_val]][ ]now use the gradient training algorithmneural_net trainf nl train train_gd now train the network with goal of learning on the data generated aboveerror neural_net train(datalabelsepochs= show= goal= nowrun the neural networks on the training data-pointsoutput neural_net sim(datay_pred output reshape(num_points |
18,701 | now plot and visualization taskplt figure(plt plot(errorplt xlabel('number of epochs'plt ylabel('error'plt title('training error progress'now we will be plotting the actual versus predicted outputx_dense np linspace(min_valmax_valnum_points y_dense_pred=neural_net sim(x_dense reshape(x_dense size, )reshape(x_dense si zeplt figure(plt plot(x_densey_dense_pred'-'xy'xy_pred' 'plt title('actual vs predicted'plt show(as result of the above commandsyou can observe the graphs as shown below |
18,702 | |
18,703 | ai with python reinforcement learning in this you will learn in detail about the concepts reinforcement learning in ai with python basics of reinforcement learning this type of learning is used to reinforce or strengthen the network based on critic information that isa network being trained under reinforcement learningreceives some feedback from the environment howeverthe feedback is evaluative and not instructive as in the case of supervised learning based on this feedbackthe network performs the adjustments of the weights to obtain better critic information in future this learning process is similar to supervised learning but we might have very less information the following figure gives the block diagram of reinforcement learningx (inputneural network (actual outputerror signal error signal generator (reinforcement signalbuilding blocksenvironment and agent environment and agent are main building blocks of reinforcement learning in ai this section discusses them in detailagent an agent is anything that can perceive its environment through sensors and acts upon that environment through effectors human agent has sensory organs such as eyesearsnosetongue and skin parallel to the sensorsand other organs such as handslegsmouthfor effectors robotic agent replaces cameras and infrared range finders for the sensorsand various motors and actuators for effectors software agent has encoded bit strings as its programs and actions |
18,704 | agent terminology the following terms are more frequently used in reinforcement learning in aiperformance measure of agentit is the criteriawhich determines how successful an agent is behavior of agentit is the action that agent performs after any given sequence of percepts perceptit is agent' perceptual inputs at given instance percept sequenceit is the history of all that an agent has perceived till date agent functionit is map from the precept sequence to an action environment some programs operate in an entirely artificial environment confined to keyboard inputdatabasecomputer file systems and character output on screen in contrastsome software agentssuch as software robots or softbotsexist in rich and unlimited softbot domains the simulator has very detailedand complex environment the software agent needs to choose from long array of actions in real time for examplea softbot designed to scan the online preferences of the customer and display interesting items to the customer works in the real as well as an artificial environment properties of environment the environment has multifold properties as discussed belowdiscrete/continuousif there are limited number of distinctclearly definedstates of the environmentthe environment is discrete otherwise it is continuous for examplechess is discrete environment and driving is continuous environment observable/partially observableif it is possible to determine the complete state of the environment at each time point from the perceptsit is observableotherwise it is only partially observable static/dynamicif the environment does not change while an agent is actingthen it is staticotherwise it is dynamic single agent/multiple agentsthe environment may contain other agents which may be of the same or different kind as that of the agent accessible/inaccessibleif the agent' sensory apparatus can have access to the complete state of the environmentthen the environment is accessible to that agentotherwise it is inaccessible deterministic/non-deterministicif the next state of the environment is completely determined by the current state and the actions of the agentthen the environment is deterministicotherwise it is non-deterministic episodic/non-episodicin an episodic environmenteach episode consists of the agent perceiving and then acting the quality of its action depends just on the episode itself subsequent episodes do not depend on the actions in the previous |
18,705 | episodes episodic environments are much simpler because the agent does not need to think ahead constructing an environment with python for building reinforcement learning agentwe will be using the openai gym package which can be installed with the help of the following commandpip install gym there are various environments in openai gym which can be used for various purposes few of them are cartpole- hopper- and mspacman- they require different engines the detail documentation of openai gym can be found on the following code shows an example of python code for cartpole- environmentimport gym env gym make('cartpole- 'env reset(for in range( )env render(env step(env action_space sample() |
18,706 | you can construct other environments in similar way constructing learning agent with python for building reinforcement learning agentwe will be using the openai gym package as shownimport gym env gym make('cartpole- 'for in range( )observation env reset(for in range( )env render(print(observationaction env action_space sample(observationrewarddoneinfo env step(actionif doneprint("episode finished after {timestepsformat( + )break observe that the cartpole can balance itself |
18,707 | ai with python genetic algorithms this discusses genetic algorithms of ai in detail what are genetic algorithmsgenetic algorithms (gasare search based algorithms based on the concepts of natural selection and genetics gas are subset of much larger branch of computation known as evolutionary computation gas were developed by john holland and his students and colleagues at the university of michiganmost notably david goldberg it has since been tried on various optimization problems with high degree of success in gaswe have pool of possible solutions to the given problem these solutions then undergo recombination and mutation (like in natural genetics)produces new childrenand the process is repeated for various generations each individual (or candidate solutionis assigned fitness value (based on its objective function valueand the fitter individuals are given higher chance to mate and yield fitter individuals this is in line with the darwinian theory of survival of the fittest thusit keeps evolving better individuals or solutions over generationstill it reaches stopping criterion genetic algorithms are sufficiently randomized in naturebut they perform much better than random local search (where we just try random solutionskeeping track of the best so far)as they exploit historical information as well how to use ga for optimization problemsoptimization is an action of making designsituationresource and systemas effective as possible the following block diagram shows the optimization processinput function output stages of ga mechanism for optimization process the following is sequence of steps of ga mechanism when used for optimization of problems step generate the initial population randomly step select the initial solution with best fitness values step recombine the selected solutions using mutation and crossover operators step insert an offspring into the population |
18,708 | step nowif the stop condition is metreturn the solution with their best fitness value else go to step installing necessary packages for solving the problem by using genetic algorithms in pythonwe are going to use powerful package for ga called deap it is library of novel evolutionary computation framework for rapid prototyping and testing of ideas we can install this package with the help of the following command on command promptpip install deap if you are using anaconda environmentthen following command can be used to install deapconda install - conda-forge deap implementing solutions using genetic algorithms this section explains you the implementation of solutions using genetic algorithms generating bit patterns the following example shows you how to generate bit string that would contain onesbased on the one max problem import the necessary packages as shownimport random from deap import basecreatortools define the evaluation function it is the first step to create genetic algorithm def eval_func(individual)target_sum return len(individualabs(sum(individualtarget_sum)nowcreate the toolbox with the right parametersdef create_toolbox(num_bits)creator create("fitnessmax"base fitnessweights=( ,)creator create("individual"listfitness=creator fitnessmaxinitialize the toolboxtoolbox base toolbox(toolbox register("attr_bool"random randint |
18,709 | toolbox register("individual"tools initrepeatcreator individualtoolbox attr_boolnum_bitstoolbox register("population"tools initrepeatlisttoolbox individualregister the evaluation operatortoolbox register("evaluate"eval_funcnowregister the crossover operatortoolbox register("mate"tools cxtwopointregister mutation operatortoolbox register("mutate"tools mutflipbitindpb= define the operator for breedingtoolbox register("select"tools seltournamenttournsize= return toolbox if __name__ ="__main__"num_bits toolbox create_toolbox(num_bitsrandom seed( population toolbox population( = probab_crossingprobab_mutating num_generations print('\nevolution process starts'evaluate the entire populationfitnesses list(map(toolbox evaluatepopulation)for indfit in zip(populationfitnesses)ind fitness values fit print('\nevaluated'len(population)'individuals'create and iterate through generationsfor in range(num_generations)print("\ngeneration" |
18,710 | selecting the next generation individualsoffspring toolbox select(populationlen(population)nowclone the selected individualsoffspring list(map(toolbox cloneoffspring)apply crossover and mutation on the offspringfor child child in zip(offspring[:: ]offspring[ :: ])if random random(probab_crossingtoolbox mate(child child delete the fitness value of childdel child fitness values del child fitness values nowapply mutationfor mutant in offspringif random random(probab_mutatingtoolbox mutate(mutantdel mutant fitness values evaluate the individuals with an invalid fitnessinvalid_ind [ind for ind in offspring if not ind fitness validfitnesses map(toolbox evaluateinvalid_indfor indfit in zip(invalid_indfitnesses)ind fitness values fit print('evaluated'len(invalid_ind)'individuals'nowreplace population with next generation individualpopulation[:offspring print the statistics for the current generationsfits [ind fitness values[ for ind in populationlength len(populationmean sum(fitslength |
18,711 | sum sum( * for in fitsstd abs(sum length mean** )** print('min ='min(fits)'max ='max(fits)print('average ='round(mean )'standard deviation ='round(std )print("\nevolution ends"print the final outputbest_ind tools selbest(population )[ print('\nbest individual:\ 'best_indprint('\nnumber of ones:'sum(best_ind)following would be the outputevolution process starts evaluated individuals generation evaluated individuals min max average standard deviation generation evaluated individuals min max average standard deviation generation evaluated individuals min max average standard deviation generation evaluated individuals min max average standard deviation evolution ends best individual[ number of ones |
18,712 | symbol regression problem it is one of the best known problems in genetic programming all symbolic regression problems use an arbitrary data distributionand try to fit the most accurate data with symbolic formula usuallya measure like the rmse (root mean square erroris used to measure an individual' fitness it is classic regressor problem and here we are using the equation we need to follow all the steps as followed in the above examplebut the main part would be to create the primitive sets because they are the building blocks for the individuals so the evaluation can start here we will be using the classic set of primitives the following python code explains this in detailimport operator import math import random import numpy as np from deap import algorithmsbasecreatortoolsgp def division_operator(numeratordenominator)if denominator = return return numerator denominator def eval_func(individualpoints)func toolbox compile(expr=individualmse ((func( ( ** ** ))** for in pointsreturn math fsum(mselen(points)def create_toolbox()pset gp primitiveset("main" pset addprimitive(operator add pset addprimitive(operator sub pset addprimitive(operator mul pset addprimitive(division_operator pset addprimitive(operator neg pset addprimitive(math cos pset addprimitive(math sin pset addephemeralconstant("rand "lambdarandom randint(- , )pset renamearguments(arg =' 'creator create("fitnessmin"base fitnessweights=(- ,)creator create("individual",gp primitivetree,fitness=creator fitnessmintoolbox base toolbox(toolbox register("expr"gp genhalfandhalfpset=psetmin_= max_= |
18,713 | toolbox register("individual"tools inititeratecreator individualtoolbox exprtoolbox register("population",tools initrepeat,listtoolbox individualtoolbox register("compile"gp compilepset=psettoolbox register("evaluate"eval_funcpoints=[ / for in range( , )]toolbox register("select"tools seltournamenttournsize= toolbox register("mate"gp cxonepointtoolbox register("expr_mut"gp genfullmin_= max_= toolbox register("mutate"gp mutuniformexpr=toolbox expr_mutpset=psettoolbox decorate("mate"gp staticlimit(key=operator attrgetter("height")max_value= )toolbox decorate("mutate"gp staticlimit(key=operator attrgetter("height")max_value= )return toolbox if __name__ ="__main__"random seed( toolbox create_toolbox(population toolbox population( = hall_of_fame tools halloffame( stats_fit tools statistics(lambda xx fitness valuesstats_size tools statistics(lenmstats tools multistatistics(fitness=stats_fitsize=stats_sizemstats register("avg"np meanmstats register("std"np stdmstats register("min"np minmstats register("max"np maxprobab_crossover probab_mutate number_gen populationlog algorithms easimple(populationtoolboxprobab_crossoverprobab_mutatenumber_genstats=mstatshalloffame=hall_of_fameverbose=truenote that all the basic steps are same as used while generating bit patterns this program will give us the output as minmaxstd (standard deviationafter number of generations |
18,714 | ai with python computer vision computer vision is concerned with modeling and replicating human vision using computer software and hardware in this you will learn in detail about this computer vision computer vision is discipline that studies how to reconstructinterrupt and understand scene from its imagesin terms of the properties of the structure present in the scene computer vision hierarchy computer vision is divided into three basic categories as followinglow-level visionit includes process image for feature extraction intermediate-level visionit includes object recognition and scene interpretation high-level visionit includes conceptual description of scene like activityintention and behavior computer vision vs image processing image processing studies image to image transformation the input and output of image processing are both images computer vision is the construction of explicitmeaningful descriptions of physical objects from their image the output of computer vision is description or an interpretation of structures in scene applications computer vision finds applications in the following fieldsrobotics localization-determine robot location automatically navigation obstacles avoidance assembly (peg-in-holeweldingpaintingmanipulation ( puma robot manipulatorhuman robot interaction (hri)intelligent robotics to interact with and serve people |
18,715 | medicine classification and detection ( lesion or cells classification and tumor detection / segmentation human organ reconstruction (mri or ultrasoundvision-guided robotics surgery security biometrics (irisfinger printface recognitionsurveillance-detecting certain suspicious activities or behaviors transportation autonomous vehicle safetye driver vigilance monitoring industrial automation application industrial inspection (defect detectionassembly barcode and package label reading object sorting document understanding ( ocrinstalling useful packages for computer vision with pythonyou can use popular library called opencv (open source computer visionit is library of programming functions mainly aimed at the real-time computer vision it is written in +and its primary interface is in +you can install this package with the help of the following commandpip install opencv_python- -cp -cp -winx whl here represents the version of python installed on your machine as well as the win or bit you are having if you are using the anaconda environmentthen use the following command to install opencvconda install - conda-forge opencv |
18,716 | readingwriting and displaying an image most of the cv applications need to get the images as input and produce the images as output in this sectionyou will learn how to read and write image file with the help of functions provided by opencv opencv functions for readingshowingwriting an image file opencv provides the following functions for this purposeimread(functionthis is the function for reading an imread(supports various image formats like pngjpegimage opencv jpgtiffetc imshow(functionthis is the function for showing an image in window the window automatically fits to the image size opencv imshow(supports various image formats like pngjpegjpgtiffetc imwrite(functionthis is the function for writing imwrite(supports various image formats like pngan image opencv jpegjpgtiffetc example this example shows the python code for reading an image in one formatshowing it in window and writing the same image in other format consider the steps shown belowimport the opencv package as shownimport cv nowfor reading particular imageuse the imread(functionimage cv imread('image_flower jpg'for showing the imageuse the imshow(function the name of the window in which you can see the image would be image_flower cv imshow('image_flower',imagecv destroyallwindows( |
18,717 | nowwe can write the same image into the other formatsay png by using the imwrite(functioncv imwrite('image_flower png',imagethe output true means that the image has been successfully written as png file also in the same folder true notethe function destroyallwindows(simply destroys all the windows we created color space conversion in opencvthe images are not stored by using the conventional rgb colorrather they are stored in the reverse order in the bgr order hence the default color code while reading an image is bgr the cvtcolor(color conversion function in for converting the image from one color code to other example consider this example to convert image from bgr to grayscale import the opencv package as shownimport cv nowfor reading particular imageuse the imread(functionimage cv imread('image_flower jpg'nowif we see this image using imshow(functionthen we can see that this image is in bgr |
18,718 | cv imshow('bgr_penguins',imagenowuse cvtcolor(function to convert this image to grayscale image cv cvtcolor(image,cv color_bgr graycv imshow('gray_penguins',image |
18,719 | edge detection humansafter seeing rough sketchcan easily recognize many object types and their poses that is why edges play an important role in the life of humans as well as in the applications of computer vision opencv provides very simple and useful function called canny()for detecting the edges example the following example shows clear identification of the edges import opencv package as shownimport cv import numpy as np nowfor reading particular imageuse the imread(function image cv imread('penguins jpg'nowuse the canny (function for detecting the edges of the already read image cv imwrite('edges_penguins jpg',cv canny(image, , )nowfor showing the image with edgesuse the imshow(function cv imshow('edges'cv imread(''edges_penguins jpg')this python program will create an image named edges_penguins jpg with edge detection |
18,720 | face detection face detection is one of the fascinating applications of computer vision which makes it more realistic as well as futuristic opencv has built-in facility to perform face detection we are going to use the haar cascade classifier for face detection haar cascade data we need data to use the haar cascade classifier you can find this data in our opencv package after installing opencvyou can see the folder name haarcascades there would be xml files for different application nowcopy all of them for different use and paste then in new folder under the current project example the following is the python code using haar cascade to detect the face of amitabh bachan shown in the following imageimport the opencv package as shownimport cv import numpy as np nowuse the haarcascadeclassifier for detecting faceface_detection cv cascadeclassifier(' :/programdata/cascadeclassifier/haarcascade_frontalface _default xml'nowfor reading particular imageuse the imread(functionimg cv imread('ab jpg'nowconvert it into grayscale because it would accept gray imagesgray cv cvtcolor(imgcv color_bgr gray |
18,721 | nowusing face_detection detectmultiscaleperform actual face detection faces face_detection detectmultiscale(gray nowdraw rectangle around the whole facefor ( , , ,hin facesimg cv rectangle(img,( , ),( +wy+ ),( , , ), cv imwrite('face_ab jpg',imgthis python program will create an image named face_ab jpg with face detection as showneye detection eye detection is another fascinating application of computer vision which makes it more realistic as well as futuristic opencv has built-in facility to perform eye detection we are going to use the haar cascade classifier for eye detection example the following example gives the python code using haar cascade to detect the face of amitabh bachan given in the following image |
18,722 | import opencv package as shownimport cv import numpy as np nowuse the haarcascadeclassifier for detecting faceeye_cascade cv cascadeclassifier(' :/programdata/cascadeclassifier/haarcascade_eye xml'nowfor reading particular imageuse the imread(functionimg cv imread('ab_eye jpg'nowconvert it into grayscale because it would accept grey imagesgray cv cvtcolor(imgcv color_bgr graynow with the help of eye_cascade detectmultiscaleperform actual face detectioneyes eye_cascade detectmultiscale(gray nowdraw rectangle around the whole facefor (ex,ey,ew,ehin eyesimg cv rectangle(img,(ex,ey),(ex+ewey+eh),( , , ), cv imwrite('eye_ab jpg',imgthis python program will create an image named eye_ab jpg with eye detection as shown |
18,723 | artificial neural network (annit is an efficient computing systemwhose central theme is borrowed from the analogy of biological neural networks neural networks are one type of model for machine learning in the mid- and early smuch important architectural advancements were made in neural networks in this you will learn more about deep learningan approach of ai deep learning emerged from decade' explosive computational growth as serious contender in the field thusdeep learning is particular kind of machine learning whose algorithms are inspired by the structure and function of human brain machine learning / deep learning deep learning is the most powerful machine learning technique these days it is so powerful because they learn the best way to represent the problem while learning how to solve the problem comparison of deep learning and machine learning is given belowdata dependency the first point of difference is based upon the performance of dl and ml when the scale of data increases when the data is largedeep learning algorithms perform very well machine dependency deep learning algorithms need high-end machines to work perfectly on the other handmachine learning algorithms can work on low-end machines too feature extraction deep learning algorithms can extract high level features and try to learn from the same too on the other handan expert is required to identify most of the features extracted by machine learning time of execution execution time depends upon the numerous parameters used in an algorithm deep learning has more parameters than machine learning algorithms hencethe execution time of dl algorithmsspecially the training timeis much more than ml algorithms but the testing time of dl algorithms is less than ml algorithms approach to problem solving deep learning solves the problem end-to-end while machine learning uses the traditional way of solving the problem by breaking down it into parts convolutional neural network (cnnconvolutional neural networks are the same as ordinary neural networks because they are also made up of neurons that have learnable weights and biases ordinary neural networks |
18,724 | ignore the structure of input data and all the data is converted into - array before feeding it into the network this process suits the regular datahowever if the data contains imagesthe process may be cumbersome cnn solves this problem easily it takes the structure of the images into account when they process themwhich allows them to extract the properties specific to images in this waythe main goal of cnns is to go from the raw image data in the input layer to the correct class in the output layer the only difference between an ordinary nns and cnns is in the treatment of input data and in the type of layers architecture overview of cnns architecturallythe ordinary neural networks receive an input and transform it through series of hidden layer every layer is connected to the other layer with the help of neurons the main disadvantage of ordinary neural networks is that they do not scale well to full images the architecture of cnns have neurons arranged in dimensions called widthheight and depth each neuron in the current layer is connected to small patch of the output from the previous layer it is similar to overlaying filter on the input image it uses filters to be sure about getting all the details these filters are feature extractors which extract features like edgescornersetc layers used to construct cnns following layers are used to construct cnnsinput layerit takes the raw image data as it is convolutional layerthis layer is the core building block of cnns that does most of the computations this layer computes the convolutions between the neurons and the various patches in the input rectified linear unit layerit applies an activation function to the output of the previous layer it adds non-linearity to the network so that it can generalize well to any type of function pooling layerpooling helps us to keep only the important parts as we progress in the network pooling layer operates independently on every depth slice of the input and resizes it spatially it uses the max function fully connected layer/output layerthis layer computes the output scores in the last layer the resulting output is of the size where is the number training dataset classes installing useful python packages you can use keraswhich is an high level neural networks apiwritten in python and capable of running on top of tensorflowcntk or theno it is compatible with python you can learn more about it from use the following commands to install keras |
18,725 | contents tabular factors graphical models example belief networks inference methods recursive conditioning variable elimination stochastic simulation sampling from discrete distribution sampling methods for belief network inference rejection sampling likelihood weighting particle filtering examples gibbs sampling plotting behaviour of stochastic simulators hidden markov models exact filtering for hmms localization particle filtering for hmms generating examples dynamic belief networks representing dynamic belief networks unrolling dbns dbn filtering causal models planning with uncertainty decision networks example decision networks recursive conditioning for decision networks variable elimination for decision networks markov decision processes value iteration showing grid mdps asynchronous value iteration learning with uncertainty -means em reinforcement learning representing agents and environments simulating an environment from an mdp simple game evaluation and plotting version june |
18,726 | learning testing -learning -leaning with experience replay model-based reinforcement learner reinforcement learning with features representing features feature-based rl learner experience replay multiagent systems minimax creating two-player game minimax and - pruning multiagent learning relational learning collaborative filtering alternative formulation plotting creating rating sets version history bibliography index version june |
18,727 | python for artificial intelligence why pythonwe use python because python programs can be close to pseudo-code it is designed for humans to read python is reasonably efficient efficiency is usually not problem for small examples if your python code is not efficient enougha general procedure to improve it is to find out what is taking most the timeand implement just that part more efficiently in some lower-level language most of these lowerlevel languages interoperate with python nicely this will result in much less programming and more efficient code (because you will have more time to optimizethan writing everything in low-level language you will not have to do that for the code here if you are using it for course projects getting python you need python (org/that runs with python this code is not compatible with python ( with python download and istall the latest python release from this should also install pip you can install matplotlib using pip install matplotlib in terminal shell (not in pythonthat should "just workif nottry using pip instead of pip the command python or python should then start the interactive python shell you can quit python with control- or with quit( |
18,728 | python for artificial intelligence to upgrade matplotlib to the latest version (which you should do if you install new version of pythondopip install --upgrade matplotlib we recommend using the enhanced interactive python ipython (ipython org/to install ipython after you have installed python dopip install ipython running python we assume that everything is done with an interactive python shell you can either do this with an idesuch as idle that comes with standard python distributionsor just running ipython (or perhaps just ipythonfrom shell here we describe the most simple version that uses no ide if you download the zip fileand cd to the "aipythonfolder where the py files areyou should be able to do the followingwith user input following the first ipython command is in the operating system shell (note that the - is important to enter interactive mode)with user input in boldipython - searchgeneric py python ( : mar : : type 'copyright''creditsor 'licensefor more information ipython -an enhanced interactive python type '?for help testing problem paths have been expanded and paths remain in the frontier path founda -- -- -- -- passed unit test in [ ]searcher astarsearcher(searchproblem acyclic_delivery_problem#ain [ ]searcher search(find first path paths have been expanded and paths remain in the frontier out[ ] -- -- -- -- in [ ]searcher search(find next path paths have been expanded and paths remain in the frontier out[ ] -- -- -- -- -- -- in [ ]searcher search(find next path paths have been expanded and paths remain in the frontier out[ ] -- -- -- -- -- -- -- -- in [ ]searcher search(find next path no (moresolutions total of paths expanded version june |
18,729 | in [ ]you can then interact at the last prompt there are many textbooks for python the best source of information about python is the rest of this is about what is special about the code for ai tools we will only use the standard python library and matplotlib all of the exercises can be done (and should be donewithout using other librariesthe aim is for you to spend your time thinking about how to solve the problem rather than searching for pre-existing solutions pitfalls it is important to know when side effects occur often ai programs consider what would happen or what may have happened in many such caseswe don' want side effects when an agent acts in the worldside effects are appropriate in pythonyou need to be careful to understand side effects for examplethe inexpensive function to add an element to listnamely appendchanges the list in functional language like haskell or lispadding new element to listwithout changing the original listis cheap operation for example if is list containing elementsadding an extra element to the list in python (using appendis fastbut it has the side effect of changing the list to construct new list that contains the elements of plus new elementwithout changing the value of xentails copying the listor using different representation for lists in the searching codewe will use different representation for lists for this reason features of python liststuplessetsdictionaries and comprehensions we make extensive uses of liststuplessets and dictionaries (dictssee one of the nice features of python is the use of list comprehensions (and also tupleset and dictionary comprehensions(fe for in iter if condenumerates the values fe for each in iter for which cond is true the "if condpart is optionalbut the "forand "inare not optional here has to be variableiter is an iteratorwhich can generate stream of datasuch as lista seta range object (to enumerate integers between rangesor file cond version june |
18,730 | python for artificial intelligence is an expression that evaluates to either true or false for each eand fe is an expression that will be evaluated for each value of for which cond returns true the result can go in list or used in another iterationor can be called directly using next the procedure next takes an iterator returns the next element (advancing the iteratorand raises stopiteration exception if there is no next element the following shows simple examplewhere user input is prepended with [ * for in range( if % == [ ( * for in range( if % == next( next( next( list( [ next(atraceback (most recent call last)file ""line in stopiteration notice how list(acontinued on the enumerationand got to the end of it comprehensions can also be used for dictionaries the following code creates an index for list aa [" "," ","bar"," "," ","aaaaa"ind { [ ]: for in range(len( ))ind {' ' ' ' 'bar' ' ' 'aaaaa' ind[' ' which means that 'bis the rd element of the list the assignment of ind could have also be written asind {val: for ( ,valin enumerate( )where enumerate returns an iterator of (indexvaluepairs functions as first-class objects python can create lists and other data structures that contain functions there is an issue that tricks many newcomers to python for local variable in functionthe function uses the last value of the variable when the function is version june |
18,731 | callednot the value of the variable when the function was defined (this is called "late binding"this means if you want to use the value variable has when the function is createdyou need to save the current value of that variable whereas python uses "late bindingby defaultthe alternative that newcomers often expect is "early binding"where function uses the value variable had when the function was definedcan be easily implemented consider the following programs designed to create list of functionswhere the ith function in the list is meant to add to its argument: pythondemo py -some tricky examples fun_list [for in range( )def fun ( )return + fun_list append(fun fun_list [for in range( )def fun ( ,iv= )return +iv fun_list append(fun fun_list [lambda ee+ for in range( ) fun_list [lambda ,iv=ie+iv for in range( ) = try to predictand then test to see the outputof the output of the following callsremembering that the function uses the latest value of any variable that is not bound in the function callpythondemo py -(continued in shell do #ipython - pythondemo py try these (copy text after the comment symbol and paste in the python prompt)print([ ( for in fun_list ]print([ ( for in fun_list ]print([ ( for in fun_list ]print([ ( for in fun_list ]in the first for-loopthe function fun uses iwhose value is the last value it was assigned in the second loopthe function fun uses iv there is separate iv variable for each functionand its value is the value of when the function was defined thus fun uses late bindingand fun uses early binding fun list numbered lines are python code available in the code-directoryaipython the name of the file is given in the gray text above the listing the numbers correspond to the line numbers in that file version june |
18,732 | python for artificial intelligence and fun list are equivalent to the first two (except fun list uses different variableone of the advantages of using the embedded definitions (as in fun and fun aboveover the lambda is that is it possible to add __doc__ stringwhich is the standard for documenting functions in pythonto the embedded definitions generators and coroutines python has generators which can be used for form of coroutines the yield command returns value that is obtained with next it is typically used to enumerate the values for for loop or in generators (the yield command can also be used for coroutinesbut we only us it for genertors in aipython version of the built-in rangewith or arguments (and positive stepscan be implemented aspythondemo py -(continued def myrange(startstopstep= )"""enumerates the values from start in steps of size step that are less than stop ""assert step> "only positive steps implemented in myrangei start while <stopyield +step print("list(myrange( , , )):",list(myrange( , , ))note that the built-in range is unconventional in how it handles single argumentas the single argument acts as the second argument of the function note also that the built-in range also allows for indexing ( range( )[ returns )which the above implementation does not however myrange also works for floatswhich the built-in range does not exercise implement version of myrange that acts like the built-in version when there is single argument (hintmake the second argument have default value that can be recognized in the function yield can be used to generate the same sequence of values as in the example of section pythondemo py -(continued def ga( )"""generates square of even nonnegative integers less than ""for in range( )if % == yield * ga( version june |
18,733 | the sequence of next( )and list(agives exactly the same results as the comprehension in section it is straightforward to write version of the built-in enumerate let' call it myenumeratepythondemo py -(continued def myenumerate(enum)for in range(len(enum))yield ,enum[iexercise write version of enumerate where the only iteration is "for val in enumhintkeep track of the index useful libraries timing code in order to compare algorithmswe often want to compute how long program takesthis is called the runtime of the program the most straightforward way to compute runtime is to use time perf counter()as inimport time start_time time perf_counter(compute_for_a_while(end_time time perf_counter(print("time:"end_time start_time"seconds"note that time perf_counter(measures clock timeso this should be done without user interaction between the calls on the consoleyou should dostart_time time perf_counter()compute_for_a_while()end_time time perf_counter(if this time is very small (say less than second)it is probably very inaccurateand it may be better to run your code many times to get more accurate count for this you can use timeit (timeit htmlto use timeit to time the call to foo bar(aaauseimport timeit time timeit timeit("foo bar(aaa)"setup="from __main__ import foo,aaa"number= the setup is needed so that python can find the meaning of the names in the string that is called this returns the number of seconds to execute foo bar(aaa times the variable number should be set so that the runtime is at least seconds you should not trust single measurement as that can be confounded by interference from other processes timeit repeat can be used for running timit few (say times usually the minimum time is the one to reportbut you should be explicit and explain what you are reporting version june |
18,734 | python for artificial intelligence plottingmatplotlib the standard plotting for python is matplotlib (will use the most basic plotting using the pyplot interface here is simple example that uses everything we will use pythondemo py -(continued import matplotlib pyplot as plt def myplot(minv,maxv,step,fun ,fun )plt ion(make it interactive plt xlabel("the axis"plt ylabel("the axis"plt xscale('linear'makes 'logor 'linearscale xvalues range(minv,maxv,stepplt plot(xvalues,[fun (xfor in xvalues]label="the first fun"plt plot(xvalues,[fun (xfor in xvalues]linestyle='--',color=' 'label=fun __doc__use the doc string of the function plt legend(loc="upper right"display the legend def slin( )""" = + ""return * + def sqfun( )""" =( - )^""return ( - )* try the followingfrom pythondemo import myplotslinsqfun import matplotlib pyplot as plt myplot( , , ,slin,sqfunplt legend(loc="best"import math plt plot([ + *math cos(th/ for th in range( )][ + *math sin(th/ for th in range( )]plt text( , ,"ellipse?"plt xscale('log'at the end of the code are some commented-out commands you should try in interactive mode cut from the file and paste into python (and remember to remove the comments symbol and leading space utilities display in this distributionto keep things simple and to only use standard pythonwe use text-oriented tracing of the code graphical depiction of the code could version june |
18,735 | override the definition of display (but we leave it as projectthe method self display is used to trace the program any call self display(levelto print where the level is less than or equal to the value for max display level will be printed the to print can be anything that is accepted by the built-in print (including any keyword argumentsthe definition of display isdisplay py - simple way to trace the intermediate steps of algorithms class displayable(object)"""class that uses 'displaythe amount of detail is controlled by max_display_level ""max_display_level can be overridden in subclasses def display(self,level,*args,**nargs)"""print the arguments if level is less than or equal to the current max_display_level level is an integer the other arguments are whatever arguments print can take ""if level <self max_display_levelprint(*args**nargs##if error you are using python not python note that args gets tuple of the positional argumentsand nargs gets dictionary of the keyword argumentsthis will not work in python and will give an error any class that wants to use display can be made subclass of displayable to change the maximum display level to say for class doclassname max display level which will make calls to display in that class print when the value of level is less than-or-equal to the default display level is it can also be changed for individual objects (the object value overrides the class valuethe value of max display level by convention is display nothing display solutions (nothing that happens repeatedly also display the values as they change (little detail through loop also display more details and above even more detail version june |
18,736 | python for artificial intelligence in order to implement more sophisticated visualizations of the algorithmwe add visualize "decoratorto the methods to be visualized the following code ignores the decoratordisplay py -(continued def visualize(func)""" decorator for algorithms that do interactive visualization ignored here ""return func argmax python has built-in max function that takes generator (or list or setand returns the maximum value the argmax method returns the index of an element that has the maximum value if there are multiple elements with the maximum valueone if the indexes to that value is returned at random argmaxe assumes an enumerationa generator of (elementvaluepairsas for example is generated by the built-in enumerate(listfor lists or dict items(for dicts utilities py -aipython useful utilities import random import math def argmaxall(gen)"""gen is generator of (element,valuepairswhere value is real argmaxall returns list of all of the elements with maximal value ""maxv -math inf negative infinity maxvals [list of maximal elements for ( ,vin genif >maxvmaxvals,maxv [ ] elif ==maxvmaxvals append(ereturn maxvals def argmaxe(gen)"""gen is generator of (element,valuepairswhere value is real argmaxe returns an element with maximal value if there are multiple elements with the max valueone is returned at random ""return random choice(argmaxall(gen) def argmax(lst)"""returns maximum index in list""return argmaxe(enumerate(lst)tryversion june |
18,737 | argmax([ , , , , , , ] def argmaxd(dct)"""returns the arx max of dictionary dct""return argmaxe(dct items()tryarxmaxd({ : , : , : }exercise change argmax to have an optional argument that specifies whether you want the "first""lastor "randomindex of the maximum value returned if you want the first or the lastyou don' need to keep list of the maximum elements probability for many of the simulationswe want to make variable true with some probability flip(preturns true with probability pand otherwise returns false utilities py -(continued def flip(prob)"""return true with probability prob""return random random(prob dictionary union this is now in python so will be replaced the function dict union( returns the union of dictionaries and if the values for the keys conflictthe values in are used this is similar to dict( )but that only works when the keys of are strings utilities py -(continued def dict_union( , )"""returns dictionary that contains the keys of and the value for each key that is in is the value from otherwise it is the value from this does not have side effects "" dict( copy update( return testing code it is important to test code early and test it often we include simple form of unit test the value of the current module is in __name__ and if the module is run at the top-levelit' value is "__main__see librarymain html version june |
18,738 | python for artificial intelligence the following code tests argmax and dict_unionbut only when if utilities is loaded in the top-level if it is loaded in module the test code is not run in your code you should do more substantial testing than we do herein particular testing the boundary cases utilities py -(continued def test()"""test part of utilities""assert argmax(enumerate([ , , , , , ])in [ , assert dict_union({ : : : },{ : : }={ : : : : print("passed unit test in utilities" if __name__ ="__main__"test(version june |
18,739 | agents and control this implements the controllers described in in this version the higher-levels call the lower-levels more sophisticated version may have them run concurrently (either as coroutines or in parallelthe higher-levels calling the lower-level works in simulated environments when there is single agentand where the lower-level are written to make sure they return (and don' go on forever)and the higher level doesn' take too long (as the lower-levels will wait until called again representing agents and environments an agent observes the worldand carries out actions in the environmentit also has an internal state that it updates the environment takes in actions of the agentsupdates it internal state and returns the percepts in this implementationthe state of the agent and the state of the environment are represented using standard python variableswhich are updated as the state changes the percepts and the actions are represented as variablevalue dictionaries an agent implements the go(nmethodwhere is an integer this means that the agent should run for time steps in the following code raise notimplementederror(is way to specify an abstract method that needs to be overidden in any implemented agent or environment agents py -agent and controllers import random class agent(object)def __init__(self,env) |
18,740 | agents and control """set up the agent""self env=env def go(self, )"""acts for time steps""raise notimplementederror("go"abstract method the environment implements do(actionmethod where action is variablevalue dictionary this returns perceptwhich is also variable-value dictionary the use of dictionaries allows for structured actions and percepts note that environment is subclass of displayable so that it can use the display method described in section agents py -(continued from display import displayable class environment(displayable)def initial_percepts(self)"""returns the initial percepts for the agent""raise notimplementederror("initial_percepts"abstract method def do(self,action)"""does the action in the environment returns the next percept ""raise notimplementederror("do"abstract method paper buying agent and environment to run the demoin folder "aipython"load "agents py"using ipython - agents pyand copy and paste the commented-out commands at the bottom of that file this requires python with matplotlib this is an implementation of the paper buying example the environment the environment state is given in terms of the time and the amount of paper in stock it also remembers the in-stock history and the price history the percepts are the price and the amount of paper in stock the action of the agent is the number to buy here we assume that the prices are obtained from the prices list plus random integer in range [ max price addonplus linear "inflationthe agent cannot access the price modelit just observes the prices and the amount in stock agents py -(continued class tp_env(environment)version june |
18,741 | prices [ max_price_addon maximum of random value added to get price def __init__(self)"""paper buying agent""self time= self stock= self stock_history [memory of the stock history self price_history [memory of the price history def initial_percepts(self)"""return initial percepts""self stock_history append(self stockprice self prices[ ]+random randrange(self max_price_addonself price_history append(pricereturn {'price'price'instock'self stock def do(selfaction)"""does action (buyand returns percepts (price and instock)""used pick_from_dist({ : : : : : : }bought action['buy'self stock self stock+bought-used self stock_history append(self stockself time + price (self prices[self time%len(self prices)repeating pattern +random randrange(self max_price_addonplus randomness +self time// plus inflation self price_history append(pricereturn {'price'price'instock'self stockthe pick from dist method takes in item probability dictionaryand returns one of the items in proportion to its probability agents py -(continued def pick_from_dist(item_prob_dist)""returns value from distribution item_prob_dist is an item:probability dictionarywhere the probabilities sum to returns an item chosen in proportion to its probability ""ranreal random random(for (it,probin item_prob_dist items()if ranreal probversion june |
18,742 | agents and control return it elseranreal -prob raise runtimeerror(str(item_prob_dist)+is not probability distribution"the agent the agent does not have access to the price model but can only observe the current price and the amount in stock it has to decide how much to buy the belief state of the agent is an estimate of the average price of the paperand the total amount of money the agent has spent agents py -(continued class tp_agent(agent)def __init__(selfenv)self env env self spent percepts env initial_percepts(self ave self last_price percepts['price'self instock percepts['instock' def go(selfn)"""go for time steps ""for in range( )if self last_price *self ave and self instock tobuy elif self instock tobuy elsetobuy self spent +tobuy*self last_price percepts env do({'buy'tobuy}self last_price percepts['price'self ave self ave+(self last_price-self ave)* self instock percepts['instock'set up an environment and an agent uncomment the last lines to run the agent for stepsand determine the average amount spent agents py -(continued env tp_env(ag tp_agent(env#ag go( #ag spent/env time #average spent per time period version june |
18,743 | plotting the following plots the price and number in stock historyagents py -(continued import matplotlib pyplot as plt class plot_prices(object)"""set up the plot for history of price and number in stock""def __init__(selfag,env)self ag ag self env env plt ion(plt xlabel("time"plt ylabel("number in stock price " def plot_run(self)"""plot history of price and instock""num len(env stock_historyplt plot(range(num),env stock_history,label="in stock"plt plot(range(num),env price_history,label="price"#plt legend(loc="upper left"plt draw( pl plot_prices(ag,envag go( )pl plot_run( hierarchical controller to run the hierarchical controllerin folder "aipython"load "agenttop py"using ipython - agenttop pyand copy and paste the commands near the bottom of that file this requires python with matplotlib in this implementationeach layerincluding the top layerimplements the environment classbecause each layer is seen as an environment from the layer above we arbitrarily divide the environment and the bodyso that the environment just defines the wallsand the body includes everything to do with the agent note that the named locations are part of the (top-level of theagentnot part of the environmentalthough they could have been environment the environment defines the walls agentenv py -agent environment version june |
18,744 | agents and control import math from agents import environment class rob_env(environment)def __init__(self,walls {})"""walls is set of line segments where each line segment is of the form (( , ),( , )""self walls walls body the body defines everything about the agent body agentenv py -(continued import math from agents import environment import matplotlib pyplot as plt import time class rob_body(environment)def __init__(selfenvinit_pos=( , , ))""env is the current environment init_pos is triple of ( -positiony-positiondirectiondirection is in degrees is to right is straight-upetc ""self env env self rob_xself rob_yself rob_dir init_pos self turning_angle degrees that left makes self whisker_length length of the whisker self whisker_angle angle of whisker relative to robot self crashed false the following control how it is plotted self plotting true whether the trace is being plotted self sleep_time time between actions (for real-time plottingthe following are data structures maintainedself history [(self rob_xself rob_y)history of ( ,ypositions self wall_history [history of hitting the wall def percepts(self)return {'rob_x_pos':self rob_x'rob_y_pos':self rob_y'rob_dir':self rob_dir'whisker':self whisker('crashed':self crashedinitial_percepts percepts use percept function for initial percepts too def do(self,action)""action is {'steer':directionversion june |
18,745 | direction is 'left''rightor 'straight""if self crashedreturn self percepts(direction action['steer'compass_deriv {'left': ,'straight': ,'right':- }[direction]*self turning_angle self rob_dir (self rob_dir compass_deriv + )% make in range [ , rob_x_new self rob_x math cos(self rob_dir*math pi/ rob_y_new self rob_y math sin(self rob_dir*math pi/ path ((self rob_x,self rob_y),(rob_x_new,rob_y_new)if any(line_segments_intersect(path,wallfor wall in self env walls)self crashed true if self plottingplt plot([self rob_x],[self rob_y]," *",markersize= plt draw(self rob_xself rob_y rob_x_newrob_y_new self history append((self rob_xself rob_y)if self plotting and not self crashedplt plot([self rob_x],[self rob_y],"go"plt draw(plt pause(self sleep_timereturn self percepts(this detects if the whisker and the wall intersect it' value is returned as percept agentenv py -(continued def whisker(self)"""returns true whenever the whisker sensor intersects with wall ""whisk_ang_world (self rob_dir-self whisker_angle)*math pi/ angle in radians in world coordinates wx self rob_x self whisker_length math cos(whisk_ang_worldwy self rob_y self whisker_length math sin(whisk_ang_worldwhisker_line ((self rob_x,self rob_y),(wx,wy)hit any(line_segments_intersect(whisker_line,wallfor wall in self env wallsif hitself wall_history append((self rob_xself rob_y)if self plottingplt plot([self rob_x],[self rob_y],"ro"plt draw(return hit def line_segments_intersect(linea,lineb)"""returns true if the line segmentslinea and lineb intersect line segment is represented as pair of points point is represented as ( ,ypair version june |
18,746 | agents and control ""(( , ),( , )linea (( , ),( , )lineb dadb - ax - eaeb - ay - denom db*ea-eb*da if denom== line segments are parallel return false cb (da*( - )-ea*( - ))/denom position along line if cb return false ca (db*( - )-eb*( - ))/denom position along line return <=ca<= test casesassert line_segments_intersect((( , ),( , )),(( , ),( , ))assert not line_segments_intersect((( , ),( , )),(( , ),( , ))assert line_segments_intersect((( , ),( , )),(( , ),( , ))middle layer the middle layer acts like both controller (for the environment layerand an environment for the upper layer it has to tell the environment how to steer thus it calls env do(*it also is told the position to go to and the timeout thus it also has to implement do(*agentmiddle py -middle layer from agents import environment import math class rob_middle_layer(environment)def __init__(self,env)self env=env self percepts env initial_percepts(self straight_angle angle that is close enough to straight ahead self close_threshold distance that is close enough to arrived self close_threshold_squared self close_threshold** just compute it once def initial_percepts(self)return { def do(selfaction)"""action is {'go_to':target_pos,'timeout':timeouttarget_pos is ( ,ypair timeout is the number of steps to try returns {'arrived':truewhen arrived is true or {'arrived':falseif it reached the timeout version june |
18,747 | ""if 'timeoutin actionremaining action['timeout'elseremaining - will never reach target_pos action['go_to'arrived self close_enough(target_poswhile not arrived and remaining ! self percepts self env do({"steer":self steer(target_pos)}remaining - arrived self close_enough(target_posreturn {'arrived':arrivedthis determines how to steer depending on whether the goal is to the right or the left of where the robot is facing agentmiddle py -(continued def steer(self,target_pos)if self percepts['whisker']self display( ,'whisker on'self perceptsreturn "leftelsegx,gy target_pos rx,ry self percepts['rob_x_pos'],self percepts['rob_y_pos'goal_dir math acos((gx-rx)/math sqrt((gx-rx)*(gx-rx+(gy-ry)*(gy-ry)))* /math pi if ry>gygoal_dir -goal_dir goal_from_rob (goal_dir self percepts['rob_dir']+ )% - assert - goal_from_rob < if goal_from_rob self straight_anglereturn "leftelif goal_from_rob -self straight_anglereturn "rightelsereturn "straight def close_enough(self,target_pos)gx,gy target_pos rx,ry self percepts['rob_x_pos'],self percepts['rob_y_pos'return (gx-rx)** (gy-ry)** <self close_threshold_squared top layer the top layer treats the middle layer as its environment note that the top layer is an environment for us to tell it what to visit agenttop py -top layer from agentmiddle import rob_middle_layer version june |
18,748 | agents and control from agents import environment class rob_top_layer(environment)def __init__(selfmiddletimeout= locations {'mail':(- , )' ':( , )' ':( , ),'storage':( , ))"""middle is the middle layer timeout is the number of steps the middle layer goes before giving up locations is loc:pos dictionary where loc is named locationand pos is an ( ,yposition ""self middle middle self timeout timeout number of steps before the middle layer should give up self locations locations def do(self,plan)"""carry out actions actions is of the form {'visit':list_of_locationsit visits the locations in turn ""to_do plan['visit'for loc in to_doposition self locations[locarrived self middle do({'go_to':position'timeout':self timeout}self display( ,"arrived at",loc,arrivedplotting the following is used to plot the locationsthe walls and (eventuallythe movement of the robot it can either plot the movement if the robot as it is going (with the default env plotting true)or not plot it as it is going (setting env plotting falsein this case the trace can be plotted using pl plot run()agenttop py -(continued import matplotlib pyplot as plt class plot_env(object)def __init__(selfbody,top)"""sets up the plot ""self body body plt ion(plt clf(plt axes(set_aspect('equal'for wall in body env walls(( , ),( , )wall version june |
18,749 | plt plot([ , ],[ , ],"- ",linewidth= for loc in top locations( ,ytop locations[locplt plot([ ],[ ]," <"plt text( + , + ,locprint the label above and to the right plt plot([body rob_x],[body rob_y],"go"plt draw( def plot_run(self)"""plots the history after the agent has finished this is typically only used if body plotting==false ""xs,ys zip(*self body historyplt plot(xs,ys,"go"wxs,wys zip(*self body wall_historyplt plot(wxs,wys,"ro"#plt draw(the following code plots the agent as it acts in the worldagenttop py -(continued from agentenv import rob_bodyrob_env env rob_env({(( , ),( , ))(( ,- ),( , ))}body rob_body(envmiddle rob_middle_layer(bodytop rob_top_layer(middle trypl=plot_env(body,toptop do({'visit':[' ','storage',' ',' ']}you can directly control the middle layermiddle do({'go_to':( ,- )'timeout': }can you make it crashexercise the following code implements robot trap write controller that can escape the "trapand get to the goal see textbook for hints agenttop py -(continued robot trap for which the current controller cannot escapetrap_env rob_env({(( ,- ),( , ))(( , ),( , ))(( ,- ),( , ))(( , ),( , ))(( ,- ),( , ))(( ,- ),( ,- ))(( , ),( , ))(( , ),( , ))(( , ),( , ))}trap_body rob_body(trap_env,init_pos=(- , , )trap_middle rob_middle_layer(trap_bodytrap_top rob_top_layer(trap_middle,locations={'goal':( , )} robot trap exerciseversion june |
18,750 | agents and control pl=plot_env(trap_body,trap_toptrap_top do({'visit':['goal']}version june |
18,751 | searching for solutions representing search problems search problem consists ofa start node neighbors function that given nodereturns an enumeration of the arcs from the node specification of goal in terms of boolean function that takes node and returns true if the node is goal (optionalheuristic function thatgiven nodereturns non-negative real number the heuristic function defaults to zero as far as the searcher is concerned node can be anything if multiple-path pruning is useda node must be hashable in the simple examplesit is stringbut in more complicated examples (in later it can be tuplea frozen setor python object in the following code raise notimplementederror(is way to specify that this is an abstract method that needs to be overridden to define an actual search problem searchproblem py -representations of search problems class search_problem(object)""" search problem consists ofa start node neighbors function that gives the neighbors of node specification of goal (optionalheuristic function |
18,752 | searching for solutions the methods must be overridden to define search problem "" def start_node(self)"""returns start node""raise notimplementederror("start_node"abstract method def is_goal(self,node)"""is true if node is goal""raise notimplementederror("is_goal"abstract method def neighbors(self,node)"""returns list of the arcs for the neighbors of node""raise notimplementederror("neighbors"abstract method def heuristic(self, )"""gives the heuristic value of node returns if not overridden ""return the neighbors is list of arcs (directedarc consists of from node node and to node node the arc is the pair but can also contain non-negative cost (which defaults to and can be labeled with an action searchproblem py -(continued class arc(object)"""an arc has from_node and to_node node and (non-negativecost""def __init__(selffrom_nodeto_nodecost= action=none)assert cost > ("cost cannot be negative for"str(from_node)+"->"+str(to_node)+"cost"+str(cost)self from_node from_node self to_node to_node self action action self cost=cost def __repr__(self)"""string representation of an arc""if self actionreturn str(self from_node)+--"+str(self action)+"--"+str(self to_nodeelsereturn str(self from_node)+--"+str(self to_nodeexplicit representation of search graph the first representation of search problem is from an explicit graph (as opposed to one that is generated as neededan explicit graph consists of version june |
18,753 | list or set of nodes list or set of arcs start node list or set of goal nodes (optionallya dictionary that maps node to heuristic value for that node to define search problemwe need to define the start nodethe goal predicatethe neighbors function and the heuristic function searchproblem py -(continued class search_problem_from_explicit_graph(search_problem)""" search problem consists ofa list or set of nodes list or set of arcs start node list or set of goal nodes dictionary that maps each node into its heuristic value dictionary that maps each node into its ( ,yposition "" def __init__(selfnodesarcsstart=nonegoals=set()hmap={}positions={})self neighs {self nodes nodes for node in nodesself neighs[node]=[self arcs arcs for arc in arcsself neighs[arc from_nodeappend(arcself start start self goals goals self hmap hmap self positions positions def start_node(self)"""returns start node""return self start def is_goal(self,node)"""is true if node is goal""return node in self goals def neighbors(self,node)"""returns the neighbors of node""return self neighs[node version june |
18,754 | searching for solutions def heuristic(self,node)"""gives the heuristic value of node returns if not overridden in the hmap ""if node in self hmapreturn self hmap[nodeelsereturn def __repr__(self)"""returns string representation of the search problem""res="for arc in self arcsres +str(arc)+return res the following is used for the depth-first search implementation below searchproblem py -(continued def neighbor_nodes(self,node)"""returns an iterator over the neighbors of node""return (path to_node for path in self neighs[node]paths searcher will return path from the start node to goal node python list is not suitable representation for pathas many search algorithms consider multiple paths at onceand these paths should share initial parts of the path if we wanted to do this with python listswe would need to keep copying the listwhich can be expensive if the list is long an alternative representation is used here in terms of recursive data structure that can share subparts path is eithera node (representing path of length or pathinitial and an arcwhere the from node of the arc is the node at the end of initial these cases are distinguished in the following code by having arc none if the path has length in which case initial is the node of the path python yield is used for enumerations only searchproblem py -(continued class path(object)""" path is either node or path followed by an arc"" def __init__(self,initial,arc=none)"""initial is either node (in which case arc is noneor path (in which case arc is an object of type arc)""self initial initial version june |
18,755 | self arc=arc if arc is noneself cost= elseself cost initial cost+arc cost def end(self)"""returns the node at the end of the path""if self arc is nonereturn self initial elsereturn self arc to_node def nodes(self)"""enumerates the nodes for the path this starts at the end and enumerates nodes in the path backwards ""current self while current arc is not noneyield current arc to_node current current initial yield current initial def initial_nodes(self)"""enumerates the nodes for the path before the end node this starts at the end and enumerates nodes in the path backwards ""if self arc is not noneyield from self initial nodes( def __repr__(self)"""returns string representation of path""if self arc is nonereturn str(self initialelif self arc actionreturn (str(self initial)+"\ --"+str(self arc action+"--"+str(self arc to_node)elsereturn str(self initial)+--"+str(self arc to_nodeexample search problems the first search problem is one with nodes where the least-cost path is one with many arcs see figure note that this example is used for the unit testsso the test (in searchgenericwill need to be changed if this is changed searchproblem py -(continued problem search_problem_from_explicit_graph{' ',' ',' ',' ',' '}[arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )version june |
18,756 | searching for solutions figure problem figure problem arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )]start ' 'goals {' '}positions={' '( )' '( )' '( , )' '( , )' '( , )}the second search problem is one with nodes where many paths do not lead to the goal see figure searchproblem py -(continued problem search_problem_from_explicit_graph{' ',' ',' ',' ',' ',' ',' ',' '}[arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )]start ' 'goals {' '}positions={' '( )' '( )' '( , )' '( , )' '( , )' '( , )' '( , )' '( , )}the third search problem is disconnected graph (contains no arcs)where the start node is goal node this is boundary case to make sure that weird cases work version june |
18,757 | searchproblem py -(continued problem search_problem_from_explicit_graph{' ',' ',' ',' ',' ',' ',' ',' '}[]start ' 'goals {' ',' '}the acyclic delivery problem is the delivery problem described in example and shown in figure of the textbook searchproblem py -(continued acyclic_delivery_problem search_problem_from_explicit_graph{'mail','ts',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '' ',' ',' ',' ','storage'}[arc('ts','mail', )arc(' ','ts', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ','storage', )]start ' 'goals {' '}hmap 'mail 'ts ' ' ' ' ' ' ' ' ' ' ' ' ' version june |
18,758 | searching for solutions ' 'storage the cyclic delivery problem is the delivery problem described in example and shown in figure of the textbook this is the same as acyclic delivery problembut almost every arc also has its inverse searchproblem py -(continued cyclic_delivery_problem search_problem_from_explicit_graph{'mail','ts',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '' ',' ',' ',' ','storage'}arc('ts','mail', )arc('mail','ts', )arc(' ','ts', )arc('ts',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ',' ', )arc(' ','storage', )arc('storage',' ', )]start ' 'goals {' '}hmap 'mail 'ts ' ' ' ' ' ' ' ' ' ' ' ' ' ' version june |
18,759 | 'storage generic searcher and variants to run the search demosin folder "aipython"load "searchgeneric pyusing ipython - searchgeneric pyand copy and paste the example queries at the bottom of that file this requires python searcher searcher for problem can be asked repeatedly for the next path to solve problemwe can construct searcher object for the problem and then repeatedly ask for the next path using search if there are no more pathsnone is returned searchgeneric py -generic searcherincluding depth-first and from display import displayablevisualize class searcher(displayable)"""returns searcher for problem paths can be found by repeatedly calling search(this does depth-first search unless overridden ""def __init__(selfproblem)"""creates searcher from problem ""self problem problem self initialize_frontier(self num_expanded self add_to_frontier(path(problem start_node())super(__init__( def initialize_frontier(self)self frontier [ def empty_frontier(self)return self frontier =[ def add_to_frontier(self,path)self frontier append(path @visualize def search(self)"""returns (nextpath from the problem' start node to goal node version june |
18,760 | searching for solutions returns none if no path exists ""while not self empty_frontier()path self frontier pop(self display( "expanding:",path,"(cost:",path cost,")"self num_expanded + if self problem is_goal(path end())solution found self display( self num_expanded"paths have been expanded and"len(self frontier)"paths remain in the frontier"self solution path store the solution found return path elseneighs self problem neighbors(path end()self display( ,"neighbors are"neighsfor arc in reversed(list(neighs))self add_to_frontier(path(path,arc)self display( ,"frontier:",self frontierself display( ,"no (moresolutions total of"self num_expanded,"paths expanded "note that this reverses the neigbours so that it implements depth-first search in an intutive manner (expanding the first neighbor first)and list is needed if the neighboure are generated reversing the neighbours might not be required for other methods the calls to reversed and list can be removedand the algothihm still implements depth-fist search exercise when it returns paththe algorithm can be used to find another path by calling search(again howeverit does not find other paths that go through one goal node to another explain whyand change the code so that it can find such paths when search(is called again frontier as priority queue in many of the search algorithmssuch as aand other best-first searchersthe frontier is implemented as priority queue here we use the python' built-in priority queue implementationsheapq following the lead of the python documentation /library/heapq htmla frontier is list of triples the first element of each triple is the value to be minimized the second element is unique index which specifies the order when the first elements are the sameand the third element is the path that is on the queue the use of the unique index ensures that the priority queue implementation does not compare pathswhether one path is less than another is not defined it also lets us control what sort of search ( depth-first or breadth-firstoccurs when the value to be minimized does not give unique next path version june |
18,761 | the variable frontier index is the total number of elements of the frontier that have been created as well as being used as unique indexit is useful for statisticsparticularly in conjunction with the current size of the frontier searchgeneric py -(continued import heapq part of the python standard library from searchproblem import path class frontierpq(object)""" frontier consists of priority queue (heap)frontierpqof (valueindexpathtripleswhere value is the value we want to minimize ( path cost hindex is unique index for each element path is the path on the queue note that the priority queue always returns the smallest element "" def __init__(self)"""constructs the frontierinitially an empty priority queue ""self frontier_index the number of items ever added to the frontier self frontierpq [the frontier priority queue def empty(self)"""is true if the priority queue is empty""return self frontierpq =[ def add(selfpathvalue)"""add path to the priority queue value is the value to be minimized""self frontier_index + get new unique index heapq heappush(self frontierpq,(value-self frontier_indexpath) def pop(self)"""returns and removes the path of the frontier with minimum value ""( , ,pathheapq heappop(self frontierpqreturn path the following methods are used for finding and printing information about the frontier searchgeneric py -(continued def count(self,val)"""returns the number of elements of the frontier with value=val""return sum( for in self frontierpq if [ ]==val def __repr__(self)"""string representation of the frontier""return str([( , ,str( )for ( , ,pin self frontierpq]version june |
18,762 | searching for solutions def __len__(self)"""length of the frontier""return len(self frontierpq def __iter__(self)"""iterate through the paths in the frontier""for ( , ,pathin self frontierpqyield path asearch for an asearch the frontier is implemented using the frontierpq class searchgeneric py -(continued class astarsearcher(searcher)"""returns searcher for problem paths can be found by repeatedly calling search("" def __init__(selfproblem)super(__init__(problem def initialize_frontier(self)self frontier frontierpq( def empty_frontier(self)return self frontier empty( def add_to_frontier(self,path)"""add path to the frontier with the appropriate cost""value path cost+self problem heuristic(path end()self frontier add(pathvaluecode should always be tested the following provides simple unit testusing problem as the the default problem searchgeneric py -(continued import searchproblem as searchproblem def test(searchclassproblem=searchproblem problem solutions=[[' ',' ',' ',' ',' '])"""unit test for aipython searching algorithms searchclass is class that takes problemm and implements search(problem is search problem solutions is list of optimal solutions ""print("testing problem :"schr searchclass(problempath schr search(version june |
18,763 | print("path found:",path assert path is not none"no path is found in problem assert list(path nodes()in solutions"shortest path not found in problem print("passed unit test" if __name__ ="__main__"#test(searchertest(astarsearcher example queriessearcher searcher(searchproblem acyclic_delivery_problemdfs searcher search(find first path searcher search(find next path searcher astarsearcher(searchproblem acyclic_delivery_problemasearcher search(find first path searcher search(find next path searcher searcher(searchproblem cyclic_delivery_problemdfs searcher search(find first path with dfs what do you expect to happensearcher astarsearcher(searchproblem cyclic_delivery_problemasearcher search(find first path exercise change the code so that it implements (ibest-first search and (iilowest-cost-first search for each of these methods compare it to ain terms of the number of paths expandedand the path found exercise in the add method in frontierpq what does the "-in front of frontier index dowhen there are multiple paths with the same -valuewhich search method does this act likewhat happens if the "-is removedwhen there are multiple paths with the same valuewhich search method does this act likedoes it work better with or without the "-"what evidence did you base your conclusion onexercise the searcher acts like python iteratorin that it returns one value (here pathand then returns other values (pathson demandbut does not implement the iterator interface change the code so it implements the iterator interface what does this enable us to domultiple path pruning to run the multiple-path pruning demoin folder "aipython"load "searchmpp pyusing ipython - searchmpp pyand copy and paste the example queries at the bottom of that file the following implements awith multiple-path pruning it overrides search(in searcher searchmpp py -searcher with multiple-path pruning from searchgeneric import astarsearchervisualize from searchproblem import path version june |
18,764 | searching for solutions class searchermpp(astarsearcher)"""returns searcher for problem paths can be found by repeatedly calling search(""def __init__(selfproblem)super(__init__(problemself explored set( @visualize def search(self)"""returns next path from an element of problem' start nodes to goal node returns none if no path exists ""while not self empty_frontier()path self frontier pop(if path end(not in self exploredself display( "expanding:",path,"(cost:",path cost,")"self explored add(path end()self num_expanded + if self problem is_goal(path end())self display( self num_expanded"paths have been expanded and"len(self frontier)"paths remain in the frontier"self solution path store the solution found return path elseneighs self problem neighbors(path end()self display( ,"neighbors are"neighsfor arc in neighsself add_to_frontier(path(path,arc)self display( ,"frontier:",self frontierself display( ,"no (moresolutions total of"self num_expanded,"paths expanded " from searchgeneric import test if __name__ ="__main__"test(searchermpp import searchproblem searchermppcdp searchermpp(searchproblem cyclic_delivery_problemprint(searchermppcdp search()find first path exercise implement searcher that implements cycle pruning instead of multiple-path pruning you need to decide whether to check for cycles when paths are added to the frontier or when they are removed (hinteither method can be implemented by only changing one or two lines in searchermpp hintthere is cyle if path end(in path initial_nodes(compare no pruningmultiple path version june |
18,765 | pruning and cycle pruning for the cyclic delivery problem which works better in terms of number of paths expandedcomputational time or space branch-and-bound search to run the demoin folder "aipython"load "searchbranchandbound py"and copy and paste the example queries at the bottom of that file depth-first search methods do not need an priority queuebut can use list as stack in this implementation of branch-and-bound searchwe call search to find an optimal solution with cost less than bound this uses depthfirst search to find path to goal that extends path with cost less than the bound once path to goal has been foundthat path is remembered as the best paththe bound is reducedand the search continues searchbranchandbound py -branch and bound search from searchproblem import path from searchgeneric import searcher from display import displayablevisualize class df_branch_and_bound(searcher)"""returns branch and bound searcher for problem an optimal path with cost less than bound can be found by calling search(""def __init__(selfproblembound=float("inf"))"""creates searcher than can be used with search(to find an optimal path bound gives the initial bound by default this is infinite meaning there is no initial pruning due to depth bound ""super(__init__(problemself best_path none self bound bound @visualize def search(self)"""returns an optimal solution to problem with cost less than bound returns none if there is no solution with cost less than bound ""self frontier [path(self problem start_node())self num_expanded while self frontierpath self frontier pop(if path cost+self problem heuristic(path end()self boundif path end(not in path initial_nodes()for cycle pruning version june |
18,766 | searching for solutions self display( ,"expanding:",path,"cost:",path costself num_expanded + if self problem is_goal(path end())self best_path path self bound path cost self display( ,"new best path:",path,cost:",path costelseneighs self problem neighbors(path end()self display( ,"neighbors are"neighsfor arc in reversed(list(neighs))self add_to_frontier(path(patharc)self display( ,"number of paths expanded:",self num_expanded"(optimalif self best_path else "(no""solution found)"self solution self best_path return self best_path note that this code used reversed in order to expand the neighbors of node in the left-to-right order one might expect it does this because pop(removes the rightmost element of the list the call to list is there because reversed only works on lists and tuplesbut the neighbours can be generated here is unit test and some queriessearchbranchandbound py -(continued from searchgeneric import test if __name__ ="__main__"test(df_branch_and_bound example queriesimport searchproblem searcherb df_branch_and_bound(searchproblem acyclic_delivery_problemprint(searcherb search()find optimal path searcherb df_branch_and_bound(searchproblem cyclic_delivery_problembound= print(searcherb search()find optimal path exercise implement branch-and-bound search uses recursion hintyou don' need an explicit frontierbut can do recursive call for the children exercise after the branch-and-bound search found solutionsam ran search againand noticed different count sam hypothesized that this count was related to the number of nodes that an asearch would use (either expand or be added to the frontieror maybesam thoughtthe count for number of nodes when the bound is slightly above the optimal path case is related to how awould work is there relationship between these countsare there different things that it could count so they are relatedtry to find the most specific statement that is trueand explain why it is true to test the hypothesissam wrote the following codebut isn' sure it is helpfulsearchtest py -code that may be useful to compare aand branch-and-bound version june |
18,767 | from searchgeneric import searcherastarsearcher from searchbranchandbound import df_branch_and_bound from searchmpp import searchermpp df_branch_and_bound max_display_level searcher max_display_level def run(problem,name)print("\ \ *******",name print("\na*:"asearcher astarsearcher(problemprint("path found:",asearcher search(),cost=",asearcher solution costprint("there are",asearcher frontier count(asearcher solution cost)"elements remaining on the queue with -value=",asearcher solution cost print("\nawith mpp:")msearcher searchermpp(problemprint("path found:",msearcher search(),cost=",msearcher solution costprint("there are",msearcher frontier count(msearcher solution cost)"elements remaining on the queue with -value=",msearcher solution cost bound asearcher solution cost+ print("\nbranch and bound (with too-good initial bound of"bound,")"tbb df_branch_and_bound(problem,boundcheating!!!print("path found:",tbb search(),cost=",tbb solution costprint("rerunning & "print("path found:",tbb search() bbound asearcher solution cost* + print("\nbranch and bound (with not-very-good initial bound of"bbound")"tbb df_branch_and_bound(problem,bboundcheating!!!print("path found:",tbb search(),cost=",tbb solution costprint("rerunning & "print("path found:",tbb search() print("\ndepth-first search(use ^ if it goes on forever)"tsearcher searcher(problemprint("path found:",tsearcher search(),cost=",tsearcher solution cost import searchproblem from searchtest import run if __name__ ="__main__"run(searchproblem problem ,"problem "run(searchproblem acyclic_delivery_problem,"acyclic delivery"run(searchproblem cyclic_delivery_problem,"cyclic delivery"version june |
18,768 | searching for solutions also test some graphs with cyclesand some with multiple least-cost paths version june |
18,769 | reasoning with constraints constraint satisfaction problems variables variable consists of namea domain and an optional ( ,yposition (for displayingthe domain of variable is list or tupleas the ordering will matter in the representation of constraints cspproblem py -representations of constraint satisfaction problem import random import matplotlib pyplot as plt class variable(object)""" random variable name (stringname of the variable domain (lista list of the values for the variable variables are ordered according to their name "" def __init__(selfnamedomainposition=none)"""variable name string domain list of printable values position of form ( , ""self name name string self domain domain list of values self position position if position else (random random()random random()self size len(domain |
18,770 | reasoning with constraints def __str__(self)return self name def __repr__(self)return self name "variable({self name})constraints constraint consists ofa tuple (or listof variables is called the scope condition is boolean function that takes the same number of arguments as there are variables in the scope the condition must have __name__ property that gives printable name of the functionbuilt-in functions and functions that are defined using def have such propertyfor other functions you may need to define this property an optional name an optional (xyposition cspproblem py -(continued class constraint(object)""" constraint consists of scopea tuple of variables conditiona boolean function that can applied to tuple of values for variables in scope stringa string for printing the constraints all of the strings must be unique for the variables ""def __init__(selfscopeconditionstring=noneposition=none)self scope scope self condition condition if string is noneself string self condition __name__ str(self scopeelseself string string self position position def __repr__(self)return self string an assignment is variable:value dictionary if con is constraintcon holds(assignmentreturns true or false depending on whether the condition is true or false for that assignment the assignment assignment must assigns value to every variable in the scope of the constraint con (and could also assign values other variables)con holds gives an error if version june |
18,771 | not all variables in the scope of con are assigned in the assignment it ignores variables in assignment that are not in the scope of the constraint in pythonthe notation is used for unpacking tuple for examplef(*( )is the same as ( so if has value ( )then (*tis the same as ( cspproblem py -(continued def can_evaluate(selfassignment)""assignment is variable:value dictionary returns true if the constraint can be evaluated given assignment ""return all( in assignment for in self scope def holds(self,assignment)"""returns the value of constraint con evaluated in assignment preconditionall variables are assigned in assignmentie self can_evaluate(assignmentis true ""return self condition(*tuple(assignment[vfor in self scope)csps constraint satisfaction problem (csprequiresvariablesa list or set of variables constraintsa set or list of constraints other properties are inferred from thesevariables is the set of variables var to const is mapping from variables to set of constraintssuch that var to const[varis the set of constraints with var in the scope cspproblem py -(continued class csp(object)""" csp consists of title ( stringvariablesa set of variables constraintsa list of constraints var_to_consta variable to set of constraints dictionary ""def __init__(selftitlevariablesconstraints)"""title is string variables is set of variables constraints is list of constraints version june |
18,772 | reasoning with constraints ""self title title self variables variables self constraints constraints self var_to_const {var:set(for var in self variablesfor con in constraintsfor var in con scopeself var_to_const[varadd(con def __str__(self)"""string representation of csp""return str(self title def __repr__(self)"""more detailed string representation of csp""return "csp({self title}{self variables}{([str(cfor in self constraints])})csp consistent(assignmentreturns true if the assignment is consistent with each of the constraints in csp ( all of the constraints that can be evaluated evaluate to truenote that this is local consistency with each constraintit does not imply the csp is consistent or has solution cspproblem py -(continued def consistent(self,assignment)"""assignment is variable:value dictionary returns true if all of the constraints that can be evaluated evaluate to true given assignment ""return all(con holds(assignmentfor con in self constraints if con can_evaluate(assignment)the show method uses matplotlib to show the graphical structure of constraint network cspproblem py -(continued def show(self)plt ion(interactive ax plt figure(gca(ax set_axis_off(plt title(self titlevar_bbox dict(boxstyle="round ,pad= ,rounding_size= "con_bbox dict(boxstyle="square,pad= ",color="green"for var in self variablesif var position is nonevar position (random random()random random()for con in self constraintsif con position is nonecon position tuple(sum(var position[ifor var in con scope)/len(con scopeversion june |
18,773 | for in range( )bbox dict(boxstyle="square,pad= ",color="green"for var in con scopeax annotate(con stringvar positionxytext=con positionarrowprops={'arrowstyle':'-'},bbox=con_bboxha='center'for var in self variablesx, var position plt text( , ,var name,bbox=var_bbox,ha='center'examples in the following code ne when given numberreturns function that is true when its argument is not that number for exampleif ne ( )then ( is true and ( is false that isne ( )(yis true when allowing function of multiple arguments to use its arguments one at time is called curryingafter the logician haskell curry functions used as conditions in constraints require names (so they can be printedcspexamples py -example csps from cspproblem import variablecspconstraint from operator import lt,ne,eq,gt def ne_(val)"""not equal value""nev lambda xx !val alternative definition nev partial(neq,valanother alternative definition def nev( )return val ! nev __name__ str(val)+"!=name of the function return nev similarly is ( )(yis true when cspexamples py -(continued def is_(val)"""is value""isv lambda xx =val alternative definition isv partial(eq,valanother alternative definition def isv( )return val = isv __name__ str(val)+"==return isv the cspcsp has variables xy and zeach with domain { the constraints are and cspexamples py -(continued variable(' '{ , , } variable(' '{ , , }version june |
18,774 | reasoning with constraints csp ! < < figure csp show( variable(' '{ , , }csp csp("csp "{ , , }constraint([ , ],lt)constraint([ , ],lt)]the cspcsp has variables ab and ceach with domain { the constraints are bb and this is slightly more interesting than csp as it has more solutions this example is used in the unit testsand so if it is changedthe unit tests need to be changed cspexamples py -(continued variable(' '{ , , , }position=( , ) variable(' '{ , , , }position=( , ) variable(' '{ , , , }position=( , ) constraint([ , ]lt" "position=( , ) constraint([ ]ne_( )" ! "position=( , ) constraint([ , ]lt" "position=( , )csp csp("csp "{abc}[ ]the next cspcsp is example of the textbookthe domain consistent network (after applying the unary constraintsis shown in figure ?note that we use the same variables as the previous example and add two more cspexamples py -(continued variable(' '{ , , , }position=( , ) variable(' '{ , , , }position=( , )csp csp("csp "{ , , , , }constraint([ ]ne_( )" ! "position=( , ))constraint([ ]ne_( )" ! "position=( , ))version june |
18,775 | csp ! = ! ! > ! > < > > ! figure csp show( constraint([ , ]ne" ! ")constraint([ , ]ne" ! ")constraint([ , ]lt" ")constraint([ , ]eq" ")constraint([ , ]gt" ")constraint([ , ]gt" ")constraint([ , ]gt" ")constraint([ , ]gt" ")constraint([ , ]ne" ! ")]the following example is another scheduling problem (but with multiple answersthis is the same scheduling in the original aispace org consistency app cspexamples py -(continued csp csp("csp "{ , , , , }[constraint([ , ]ne" ! ")constraint([ , ]lt" ")constraint([ , ]lambda , ( - )% = " - is odd") - is odd constraint([ , ]lt" ")constraint([ , ]lt" ")constraint([ , ]ne" ! ")constraint([ , ]ne" ! ")]version june |
18,776 | reasoning with constraints csp ! < - is odd < < ! ! figure csp show(the following example is another abstract scheduling problem what are the solutionscspexamples py -(continued def adjacent( , )"""true when and are adjacent numbers""return abs( - = csp csp("csp "{ , , , , }[constraint([ , ]adjacent"adjacent( , )")constraint([ , ]adjacent"adjacent( , )")constraint([ , ]adjacent"adjacent( , )")constraint([ , ]adjacent"adjacent( , )")constraint([ , ]ne" ! ")constraint([ , ]ne" ! ")constraint([ , ]ne" ! ")]the following examples represent the crossword shown in figure in the first representationthe variables represent words the constraint imposed by the crossword is that where two words intersectthe letter at the intersection must be the same the method meet_at is used to test whether two words intersect with the same letter for examplethe constraint meet_at( , version june |
18,777 | csp adjacent( ,bb ! ! adjacent( ,cadjacent( ,dadjacent( ,ec ! figure csp show( wordsantbigbuscarhasbookbuysholdlaneyeargingersearchsymbolsyntax figure crossword crossword puzzle to be solved version june |
18,778 | reasoning with constraints crossword one_across meet_at( , )[one_acrossone_downmeet_at( , )[one_acrosstwo_downtwo_down one_down meet_at( , )[three_acrossone_downmeet_at( , )[three_acrosstwo_downmeet_at( , )[four_acrosstwo_downthree_across four_across figure crossword show(means that the third letter (at position of the first argument is the same as the first letter of the second argument this is shown in figure cspexamples py -(continued def meet_at( , )"""returns function of two words that is true when the words intersect at postions the positions are relative to the wordsstarting at position meet_at( , )( , is true if the same letter is at position of word and at position of word ""def meets( , )return [ = [ meets __name__ "meet_at("+str( )+','+str( )+')return meets one_across variable('one_across'{'ant''big''bus''car''has'}position=( , )one_down variable('one_down'{'book''buys''hold''lane''year'}position=( , )two_down variable('two_down'{'ginger''search''symbol''syntax'}position=( , )three_across variable('three_across'{'book''buys''hold''land''year'}position=( , )four_across variable('four_across',{'ant''big''bus''car''has'}position=( , )version june |
18,779 | crossword is_word[ is_word[ is_word[ is_word[ is_word[ figure crossword show( crossword csp("crossword "{one_acrossone_downtwo_downthree_acrossfour_across}[constraint([one_across,one_down]meet_at( , ))constraint([one_across,two_down]meet_at( , ))constraint([three_across,two_down]meet_at( , ))constraint([three_across,one_down]meet_at( , ))constraint([four_across,two_down]meet_at( , ))]in an alternative representation of crossword (the "dualrepresentation)the variables represent lettersand the constraints are that adjacent sequences of letters form words this is shown in figure cspexamples py -(continued words {'ant''big''bus''car''has','book''buys''hold''lane''year''ginger''search''symbol''syntax' def is_word(*letterswords=words)"""is true if the letters concatenated form word in words""return "join(lettersin words letters {" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "version june |
18,780 | reasoning with constraints " " pij is the variable representing the letter from the left and down (starting from variable(' 'lettersposition=( , ) variable(' 'lettersposition=( , ) variable(' 'lettersposition=( , ) variable(' 'lettersposition=( , ) variable(' 'lettersposition=( , ) variable(' 'lettersposition=( , ) variable(' 'lettersposition=( , ) variable(' 'lettersposition=( , ) variable(' 'lettersposition=( , ) variable(' 'lettersposition=( , ) variable(' 'lettersposition=( , ) variable(' 'lettersposition=( , ) variable(' 'lettersposition=( , ) variable(' 'lettersposition=( , ) variable(' 'lettersposition=( , ) crossword csp("crossword "{ first row second row third row #fourth row fifth row sixth row }[constraint([ ]is_wordposition=( , ))# -across constraint([ ]is_wordposition=( , )) -down constraint([ ]is_wordposition=( , )) -across constraint([ ]is_wordposition=( , )) -down constraint([ ]is_wordposition=( , ) -across ]exercise how many assignments of value to each variable are there for each of the representations of the above crossworddo you think an exhaustive enumeration will work for either onethe queens problem is puzzle on chess boardwhere the idea is to place queen on each column so the queens cannot take each otherthere are no two queens on the same rowcolumn or diagonal the -queens problem is generalization where the size of the board is an nand queens have to be placed version june |
18,781 | here is representation of the -queens problemwhere the variables are the columns and the values are the rows in which the queen is placed the original queens problem on standard ( chess board is n_queens( cspexamples py -(continued def queens(ri,rj)"""ri and rj are different rowsreturn the condition that the queens cannot take each other""def no_take(ci,cj)"""is true if queen at (ri,cicannot take queen at (rj,cj)""return ci !cj and abs(ri-ci!abs(rj-cjreturn no_take def n_queens( )"""returns csp for -queens""columns list(range( )variables [variable( " { }",columnsfor in range( )return csp(" -queens"variables[constraint([variables[ ]variables[ ]]queens( , )for in range(nfor in range(nif ! ] try the csp n_queens( in one of the solvers what is the smallest for which there is solutionexercise how many constraints does this representation of the -queens problem producecan it be done with fewer constraintseither explain why it can' be done with fewer constraintsor give solution using fewer constraints unit tests the following defines unit test for csp solversby default using example csp cspexamples py -(continued def test_csp(csp_solvercsp=csp solutions=[{ }{ }])"""csp_solver is solver that takes csp and returns solution csp is constraint satisfaction problem solutions is the list of all solutions to csp this tests whether the solution returned by csp_solver is solution ""print("testing csp with",csp_solver __doc__sol csp_solver(cspprint("solution found:",sol assert sol in solutions"solution not correct for "+str(cspprint("passed unit test"exercise modify test so that instead of taking in list of solutionsit checks whether the returned solution actually is solution version june |
18,782 | reasoning with constraints exercise propose test that is appropriate for csps with no solutions assume that the test designer knows there are no solutions consider what csp solver should return if there are no solutions to the csp exercise write unit test that checks whether all solutions ( for the search algorithms that can return multiple solutionsare correctand whether all solutions can be found simple depth-first solver the first solver searches through the space of partial assignments this takes in csp problem and an optional variable orderingwhich is list of the variables in the csp it returns generator of the solutions (see python documentation on yield for enumerationscspdfs py -solving csp using depth-first search from cspexamples import csp ,csp ,test_cspcrossword crossword def dfs_solver(constraintscontextvar_order)"""generator for all solutions to csp context is an assignment of values to some of the variables var_order is list of the variables in csp that are not in context ""to_eval { for in constraints if can_evaluate(context)if all( holds(contextfor in to_eval)if var_order =[]yield context elserem_cons [ for in constraints if not in to_evalvar var_order[ for val in var domainyield from dfs_solver(rem_conscontext|{var:val}var_order[ :] def dfs_solve_all(cspvar_order=none)"""depth-first csp solver to return list of all solutions to csp ""if var_order =noneuse an arbitrary variable order var_order list(csp variablesreturn listdfs_solver(csp constraints{}var_order) def dfs_solve (cspvar_order=none)"""depth-first csp solver to find single solution or none if there are no solutions ""if var_order =noneuse an arbitrary variable order var_order list(csp variablesgen dfs_solver(csp constraints{}var_ordertrypython generators raise an exception if there are no more elements version june |
18,783 | return next(genexcept stopiterationreturn none if __name__ ="__main__"test_csp(dfs_solve #trydfs_solve_all(csp dfs_solve_all(csp dfs_solve_all(crossword dfs_solve_all(crossword dwarningmay take *verylong timeexercise instead of testing all constraints at every nodechange it so each constraint is only tested when all of it variables are assigned given an elimination orderingit is possible to determine when each constraint needs to be tested implement this hintcreate parallel list of sets of constraintswhere at each position in the listthe constraints at position can be evaluated when the variable at position has been assigned exercise estimate how long dfs_solve_all(crossword dwill take on your computer to do thisreduce the number of variables that need to be assignedso that the simplifies problem can be solved in reasonable time (between second and secondsthis can be done by reducing the number of variables in var_orderas the program only splits on these how much more time will it take if the number of variables is increased by (try it!then extrapolate to all of the variables see section for how to time your code would making the code times faster or using computer times faster help converting csps to search problems to run the demoin folder "aipython"load "cspsearch py"and copy and paste the example queries at the bottom of that file the next solver constructs search space that can be solved using the search methods of the previous this takes in csp problem and an optional variable orderingwhich is list of the variables in the csp in this search spacea node is variable value dictionary which does not violate any constraints (so that dictionaries that violate any conmtratints are not addedan arc corresponds to an assignment of value to the next variable this assumes static orderingthe next variable chosen to split does not depend on the context if no variable ordering is giventhis makes no attempt to choose good ordering version june |
18,784 | reasoning with constraints cspsearch py -representations of search problem from csp from cspproblem import cspconstraint from searchproblem import arcsearch_problem from utilities import dict_union class search_from_csp(search_problem)""" search problem directly from the csp node is variable:value dictionary""def __init__(selfcspvariable_order=none)self csp=csp if variable_orderassert set(variable_order=set(csp variablesassert len(variable_order=len(csp variablesself variables variable_order elseself variables list(csp variables def is_goal(selfnode)"""returns whether the current node is goal for the search ""return len(node)==len(self csp variables def start_node(self)"""returns the start node for the search ""return {the neighbors(nodemethod uses the fact that the length of the nodewhich is the number of variables already assignedis the index of the next variable to split on note that we do no need to check whether there are no more variables to split onas the nodes are all consistentby constructionand so when there are no more variables we have solutionand so don' need the neighbours cspsearch py -(continued def neighbors(selfnode)"""returns list of the neighboring nodes of node ""var self variables[len(node)the next variable res [for val in var domainnew_env dict_union(node,{var:val}#dictionary union if self csp consistent(new_env)res append(arc(node,new_env)return res the unit tests relies on solver the following procedure creates solver using search that can be tested cspsearch py -(continued from cspexamples import csp ,csp ,test_cspcrossword crossword version june |
18,785 | from searchgeneric import searcher def solver_from_searcher(csp)"""depth-first search solver""path searcher(search_from_csp(csp)search(if path is not nonereturn path end(elsereturn none if __name__ ="__main__"test_csp(solver_from_searcher #test solving csps with searchsearcher searcher(search_from_csp(csp )#print(searcher search()get next solution searcher searcher(search_from_csp(csp )#print(searcher search()get next solution searcher searcher(search_from_csp(crossword )#print(searcher search()get next solution searcher searcher(search_from_csp(crossword )#print(searcher search()get next solution (warningslowexercise what would happen if we constructed the new assignment by assigning node[varval (with side effectsinstead of using dictionary uniongive an example of where this could give wrong answer how could the algorithm be changed to work with side effects(hintthink about what information needs to be in nodeexercise change neighbors so that it returns an iterator of values rather than list (hintuse yield consistency algorithms to run the demoin folder "aipython"load "cspconsistency py"and copy and paste the commented-out example queries at the bottom of that file con solver is used to simplify csp using arc consistency cspconsistency py -arc consistency and domain splitting for solving csp from display import displayable class con_solver(displayable)"""solves csp with arc consistency and domain splitting ""def __init__(selfcsp**kwargs)""" csp solver that uses arc consistency csp is the csp to be solved version june |
18,786 | reasoning with constraints kwargs is the keyword arguments for displayable superclass ""self csp csp super(__init__(**kwargsor displayable __init__(self,**kwargsthe following implementation of arc consistency maintains the set to do of (variableconstraintpairs that are to be checked it takes in domain dictionary and returns new domain dictionary it needs to be careful to avoid side effects (by copying the domains dictionary and the to do setcspconsistency py -(continued def make_arc_consistent(selforig_domains=noneto_do=none)"""makes this csp arc-consistent using generalized arc consistency orig_domains is the original domains to_do is set of (variable,constraintpairs returns the reduced domains (an arc-consistent variable:domain dictionary""if orig_domains is noneorig_domains {var:var domain for var in self csp variablesif to_do is noneto_do {(varconstfor const in self csp constraints for var in const scopeelseto_do to_do copy(use copy of to_do domains orig_domains copy(self display( ,"performing ac with domains"domainswhile to_dovarconst self select_arc(to_doself display( "processing arc ("var","const")"other_vars [ov for ov in const scope if ov !varnew_domain {val for val in domains[varif self any_holds(domainsconst{varval}other_vars)if new_domain !domains[var]self display( "arc("var","const"is inconsistent"self display( "domain pruned""dom("var"="new_domaindue to "constdomains[varnew_domain add_to_do self new_to_do(varconstto_do to_do |add_to_do set union self display( adding"add_to_do if add_to_do else "nothing""to to_do "self display( "arc("var","const"now consistent"self display( "ac done reduced domains"domainsreturn domains def new_to_do(selfvarconst)"""returns new elements to be added to to_do after assigning version june |
18,787 | variable var in constraint const ""return {(nvarnconstfor nconst in self csp var_to_const[varif nconst !const for nvar in nconst scope if nvar !varthe following selects an arc any element of to do can be selected the selected element needs to be removed from to do the default implementation just selects which ever element pop method for sets returns user interface could allow the user to select an arc alternatively more sophisticated selection could be employed (or just stack or queuecspconsistency py -(continued def select_arc(selfto_do)"""selects the arc to be taken from to_do to_do is set of arcswhere an arc is (variable,constraintpair the element selected must be removed from to_do ""return to_do pop(the value of new_domain is the subset of the domain of var that is consistent with the assignment to the other variables it might be easier to understand the following codewhich treats unary (with no other variables in the constraintand binary (with one other variables in the constraintconstraints as special cases (this can replace the assignment to new_domain in the above code)if len(other_vars)== unary constraint new_domain {val for val in domains[varif const holds({var:val})elif len(other_vars)== binary constraint other other_vars[ new_domain {val for val in domains[varif any(const holds({varval,other:other_val}for other_val in domains[other])elsegeneral case new_domain {val for val in domains[varif self any_holds(domainsconst{varval}other_vars)any holds is recursive function that tries to finds an assignment of values to the other variables (other varsthat satisfies constraint const given the assignment in env the integer variable ind specifies which index to other vars needs to be checked next as soon as one assignment returns truethe algorithm returns true note that it has side effects with respect to envit changes the values of the variables in other vars it should only be called when the side effects have no ill effects cspconsistency py -(continuedversion june |
18,788 | reasoning with constraints def any_holds(selfdomainsconstenvother_varsind= )"""returns true if constraint const holds for an assignment that extends env with the variables in other_vars[ind:env is dictionary warningthis has side effects and changes the elements of env ""if ind =len(other_vars)return const holds(envelsevar other_vars[indfor val in domains[var]env dict_union(env,{var:val}no side effectsenv[varval if self any_holds(domainsconstenvother_varsind )return true return false direct implementation of domain splitting the following is direct implementation of domain splitting with arc consistency that uses recursion it finds one solution if one exists or returns false if there are no solutions cspconsistency py -(continued def solve_one(selfdomains=noneto_do=none)"""return solution to the current csp or false if there are no solutions to_do is the list of arcs to check ""new_domains self make_arc_consistent(domainsto_doif any(len(new_domains[var]= for var in new_domains)return false elif all(len(new_domains[var]= for var in new_domains)self display( "solution:"{varselectnew_domains[var]for var in new_domains}return {varselect(new_domains[var]for var in new_domainselsevar self select_var( for in self csp variables if len(new_domains[ ] if vardom dom partition_domain(new_domains[var]self display( splitting"var"into"dom "and"dom new_doms copy_with_assign(new_domainsvardom new_doms copy_with_assign(new_domainsvardom to_do self new_to_do(varnoneself display( adding"to_do if to_do else "nothing""to to_do "return self solve_one(new_doms to_door self solve_one(new_doms to_doversion june |
18,789 | def select_var(selfiter_vars)"""return the next variable to split""return select(iter_vars def partition_domain(dom)"""partitions domain dom into two ""split len(dom/ dom set(list(dom)[:split]dom dom dom return dom dom the domains are implemented as dictionary that maps each variables to its domain assigning value in python has side effects which we want to avoid copy with assign takes copy of the domains dictionaryperhaps allowing for new domain for variable it creates copy of the csp with an (optionalassignment of new domain to variable only the domains are copied cspconsistency py -(continued def copy_with_assign(domainsvar=nonenew_domain={truefalse})"""create copy of the domains with an assignment var=new_domain if var==none then it is just copy ""newdoms domains copy(if var is not nonenewdoms[varnew_domain return newdoms cspconsistency py -(continued def select(iterable)"""select an element of iterable returns none if there is no such element this implementation just picks the first element for many of the useswhich element is selected does not affect correctnessbut may affect efficiency ""for in iterablereturn returns first element found exercise implement of solve all that is like solve one but returns the set of all solutions exercise implement solve enum that enumerates the solutions it should use python' yield (and perhaps yield fromunit testversion june |
18,790 | reasoning with constraints cspconsistency py -(continued from cspexamples import test_csp def ac_solver(csp)"arc consistency (solve_one)return con_solver(cspsolve_one( if __name__ ="__main__"test_csp(ac_solverdomain splitting as an interface to graph searching an alternative implementation is to implement domain splitting in terms of the search abstraction of node is domains dictionary cspconsistency py -(continued from searchproblem import arcsearch_problem class search_with_ac_from_csp(search_problem,displayable)""" search problem with arc consistency and domain splitting node is csp ""def __init__(selfcsp)self cons con_solver(csp#copy of the csp self domains self cons make_arc_consistent( def is_goal(selfnode)"""node is goal if all domains have element""return all(len(node[var])== for var in node def start_node(self)return self domains def neighbors(self,node)"""returns the neighboring nodes of node ""neighs [var select( for in node if len(node[ ])> if vardom dom partition_domain(node[var]self display( ,"splitting"var"into"dom "and"dom to_do self cons new_to_do(var,nonefor dom in [dom ,dom ]newdoms copy_with_assign(node,var,domcons_doms self cons make_arc_consistent(newdoms,to_doif all(len(cons_doms[ ])> for in cons_doms)all domains are non-empty neighs append(arc(node,cons_doms)elseversion june |
18,791 | self display( ,",var,"in",dom,"has no solution"return neighs exercise when splitting domainthis code splits the domain into halfapproximately in half (without any effort to make sensible choicedoes it work better to split one element from domainunit testcspconsistency py -(continued from cspexamples import test_csp from searchgeneric import searcher def ac_search_solver(csp)"""arc consistency (search interface)""sol searcher(search_with_ac_from_csp(csp)search(if solreturn { :select(dfor ( ,din sol end(items() if __name__ ="__main__"test_csp(ac_search_solvertestingcspconsistency py -(continued from cspexamples import csp csp csp csp crossword crossword #test solving csps with arc consistency and domain splitting#con_solver max_display_level display details of ac ( turns off#con_solver(csp solve_one(#searcher searcher(search_with_ac_from_csp(csp )#print(searcher search()#searcher max_display_level display search trace ( turns off#searcher searcher(search_with_ac_from_csp(csp )#print(searcher search()#searcher searcher(search_with_ac_from_csp(crossword )#print(searcher search()#searcher searcher(search_with_ac_from_csp(crossword )#print(searcher search() solving csps using stochastic local search to run the demoin folder "aipython"load "cspsls py"and copy and paste the commented-out example queries at the bottom of that file this assumes python some of the queries require matplotlib this implements both the two-stage choicethe any-conflict algorithm and random choice of variable (and probabilistic mix of the threeversion june |
18,792 | reasoning with constraints given cspthe stochastic local searcher (slsearchercreates the data structuresvariables to select is the set of all of the variables with domain-size greater than one for variable not in this setwe cannot pick another value from that variable var to constraints maps from variable into the set of constraints it is involved in note that the inverse mapping from constraints into variables is part of the definition of constraint cspsls py -stochastic local search for solving csps from cspproblem import cspconstraint from searchproblem import arcsearch_problem from display import displayable import random import heapq class slsearcher(displayable)""" search problem directly from the csp node is variable:value dictionary""def __init__(selfcsp)self csp csp self variables_to_select {var for var in self csp variables if len(var domain create assignment and conflicts set self current_assignment none this will trigger random restart self number_of_steps #number of steps after the initialization restart creates new total assignmentand constructs the set of conflicts (the constraints that are false in this assignmentcspsls py -(continued def restart(self)"""creates new total assignment and the conflict set ""self current_assignment {var:random_choice(var domainfor var in self csp variablesself display( ,"initial assignment",self current_assignmentself conflicts set(for con in self csp constraintsif not con holds(self current_assignment)self conflicts add(conself display( ,"number of conflicts",len(self conflicts)self variable_pq none the search method is the top-level searching algorithm it can either be used to start the search or to continue searching if there is no current assignmentversion june |
18,793 | it must create one note thatwhen counting stepsa restart is counted as one step this method selects one of two implementations the argument pob best is the probability of selecting best variable (one involving the most conflictswhen the value of prob best is positivethe algorithm needs to maintain priority queue of variables and the number of conflicts (using search with var pqif the probability of selecting best variable is zeroit does not need to maintain this priority queue (as implemented in search with any conflictthe argument prob anycon is the probability that the any-conflict strategy is used (which selects variable at random that is in conflict)assuming that it is not picking best variable note that for the probability parametersany value less that zero acts like probability zero and any value greater than acts like probability this means that when prob anycon best variable is chosen with probability prob bestotherwise variable in any conflict is chosen variable is chosen at random with probability prob anycon prob best as long as that is positive this returns the number of steps needed to find solutionor none if no solution is found if there is solutionit is in self current assignment cspsls py -(continued def search(self,max_stepsprob_best= prob_anycon= )""returns the number of steps or none if these is no solution if there is solutionit can be found in self current_assignment max_steps is the maximum number of steps it will try before giving up prob_best is the probability that best variable (one in most conflictis selected prob_anycon is the probability that variable in any conflict is selected (otherwise variable is chosen at random""if self current_assignment is noneself restart(self number_of_steps + if not self conflictsself display( ,"solution found:"self current_assignment"after restart"return self number_of_steps if prob_best we need to maintain variable priority queue return self search_with_var_pq(max_stepsprob_bestprob_anyconelsereturn self search_with_any_conflict(max_stepsprob_anyconexercise this does an initial random assignment but does not do any random restarts implement searcher that takes in the maximum number of walk version june |
18,794 | reasoning with constraints steps (corresponding to existing max stepsand the maximum number of restartsand returns the total number of steps for the first solution found (as in searchthe solution found can be extracted from the variable self current assignmentany-conflict if the probability of picking best variable is zerothe implementation need to keeps track of which variables are in conflicts cspsls py -(continued def search_with_any_conflict(selfmax_stepsprob_anycon= )"""searches with the any_conflict heuristic this relies on just maintaining the set of conflictsit does not maintain priority queue ""self variable_pq none we are not maintaining the priority queue this ensures it is regenerated if we call search_with_var_pq for in range(max_steps)self number_of_steps += if random random(prob_anyconcon random_choice(self conflictspick random conflict var random_choice(con scopepick variable in conflict elsevar random_choice(self variables_to_selectif len(var domain val random_choice([val for val in var domain if val is not self current_assignment[var]]self display( ,self number_of_steps,"assigning",var,"=",valself current_assignment[var]=val for varcon in self csp var_to_const[var]if varcon holds(self current_assignment)if varcon in self conflictsself conflicts remove(varconelseif varcon not in self conflictsself conflicts add(varconself display( ,number of conflicts",len(self conflicts)if not self conflictsself display( ,"solution found:"self current_assignment"in"self number_of_steps,"steps"return self number_of_steps self display( ,"no solution in",self number_of_steps,"steps"len(self conflicts),"conflicts remain"return none exercise this makes no attempt to find the best alternative value for variable modify the code so that after selecting variable it selects value the reduces version june |
18,795 | the number of conflicts by the most have parameter that specifies the probability that the best value is chosen two-stage choice this is the top-level searching algorithm that maintains priority queue of variables ordered by (the negative ofthe number of conflictsso that the variable with the most conflicts is selected first if there is no current priority queue of variablesone is created the main complexity here is to maintain the priority queue this uses the dictionary var differential which specifies how much the values of variables should change this is used with the updatable queue (page to find variable with the most conflicts cspsls py -(continued def search_with_var_pq(self,max_stepsprob_best= prob_anycon= )"""search with priority queue of variables this is used to select variable with the most conflicts ""if not self variable_pqself create_pq(pick_best_or_con prob_best prob_anycon for in range(max_steps)self number_of_steps += randnum random random(#pick variable if randnum prob_bestpick best variable var,oldval self variable_pq top(elif randnum pick_best_or_conpick variable in conflict con random_choice(self conflictsvar random_choice(con scopeelse#pick any variable that can be selected var random_choice(self variables_to_selectif len(var domain var has other values #pick value val random_choice([val for val in var domain if val is not self current_assignment[var]]self display( ,"assigning",var,val#update the priority queue var_differential {self current_assignment[var]=val for varcon in self csp var_to_const[var]self display( ,"checking",varconif varcon holds(self current_assignment)if varcon in self conflicts#was inconsnow consis self display( ,"became consistent",varconself conflicts remove(varconfor in varcon scopev is in one fewer conflicts version june |
18,796 | reasoning with constraints var_differential[vvar_differential get( , )- elseif varcon not in self conflictswas consisnot now self display( ,"became inconsistent",varconself conflicts add(varconfor in varcon scopev is in one more conflicts var_differential[vvar_differential get( , )+ self variable_pq update_each_priority(var_differentialself display( ,"number of conflicts",len(self conflicts)if not self conflictsno conflictsso solution found self display( ,"solution found:"self current_assignment,"in"self number_of_steps,"steps"return self number_of_steps self display( ,"no solution in",self number_of_steps,"steps"len(self conflicts),"conflicts remain"return none create pq creates an updatable priority queue of the variablesordered by the number of conflicts they participate in the priority queue only includes variables in conflicts and the value of variable is the negative of the number of conflicts the variable is in this ensures that the priority queuewhich picks the minimum valuepicks variable with the most conflicts cspsls py -(continued def create_pq(self)"""create the variable to number-of-conflicts priority queue this is needed to select the variable in the most conflicts the value of variable in the priority queue is the negative of the number of conflicts the variable appears in ""self variable_pq updatable_priority_queue(var_to_number_conflicts {for con in self conflictsfor var in con scopevar_to_number_conflicts[varvar_to_number_conflicts get(var, )+ for var,num in var_to_number_conflicts items()if num> self variable_pq add(var,-numcspsls py -(continued def random_choice(st)"""selects random element from set st it will be more efficient to convert to tuple or list only once ""return random choice(tuple(st)version june |
18,797 | exercise this makes no attempt to find the best alternative value for variable modify the code so that after selecting variable it selects value the reduces the number of conflicts by the most have parameter that specifies the probability that the best value is chosen exercise these implementations always select value for the variable selected that is different from its current value (if that is possiblechange the code so that it does not have this restriction (so it can leave the value the samewould you expect this code to be fasterdoes it work worse (or better)updatable priority queues an updatable priority queue is priority queuewhere key-value pairs can be storedand the pair with the smallest key can be found and removed quicklyand where the values can be updated this implementation follows the idea of unmodified howeverthis might be expensive if changes are more common than popping (as might happen if the probability of choosing the best is close to zeroin this implementationthe equal values are sorted randomly this is achieved by having the elements of the heap being [valrandelttripleswhere the second element is random number note that python requires this to be listnot tupleas the tuple cannot be modified cspsls py -(continued class updatable_priority_queue(object)""" priority queue where the values can be updated elements with the same value are ordered randomly this code is based on the ideas described in it could probably be done more efficiently by shuffling the modified element in the heap ""def __init__(self)self pq [priority queue of [val,rand,elttriples self elt_map {map from elt to [val,rand,elttriple in pq self removed "*removed* string that won' be legal element self max_size= def add(self,elt,val)"""adds elt to the priority queue with priority=val ""assert val < ,val assert elt not in self elt_mapelt new_triple [valrandom random(),eltheapq heappush(self pqnew_tripleself elt_map[eltnew_triple version june |
18,798 | reasoning with constraints def remove(self,elt)"""remove the element from the priority queue""if elt in self elt_mapself elt_map[elt][ self removed del self elt_map[elt def update_each_priority(self,update_dict)"""update values in the priority queue by subtracting the values in update_dict from the priority of those elements in priority queue ""for elt,incr in update_dict items()if incr ! newval self elt_map get(elt,[ ])[ incr assert newval < str(elt)+":"+str(newval+incr)+"-"+str(incrself remove(eltif newval ! self add(elt,newval def pop(self)"""removes and returns the (elt,valuepair with minimal value if the priority queue is emptyindexerror is raised ""self max_size max(self max_sizelen(self pq)keep statistics triple heapq heappop(self pqwhile triple[ =self removedtriple heapq heappop(self pqdel self elt_map[triple[ ]return triple[ ]triple[ eltvalue def top(self)"""returns the (elt,valuepair with minimal valuewithout removing it if the priority queue is emptyindexerror is raised ""self max_size max(self max_sizelen(self pq)keep statistics triple self pq[ while triple[ =self removedheapq heappop(self pqtriple self pq[ return triple[ ]triple[ eltvalue def empty(self)"""returns true iff the priority queue is empty""return all(triple[ =self removed for triple in self pqversion june |
18,799 | plotting runtime distributions runtime distribution uses matplotlib to plot runtime distributions here the runtime is misnomer as we are only plotting the number of stepsnot the time computing the runtime is non-trivial as many of the runs have very short runtime to compute the time accurately would require running the same codewith the same random seedmultiple times to get good estimate of the runtime this is left as an exercise cspsls py -(continued import matplotlib pyplot as plt class runtime_distribution(object)def __init__(selfcspxscale='log')"""sets up plotting for csp xscale is either 'linearor 'log""self csp csp plt ion(plt xlabel("number of steps"plt ylabel("cumulative number of runs"plt xscale(xscalemakes 'logor 'linearscale def plot_runs(self,num_runs= ,max_steps= prob_best= prob_anycon= )"""plots num_runs of sls for the given settings ""stats [slsearcher max_display_leveltemp_mdl slsearcher max_display_level no display for in range(num_runs)searcher slsearcher(self cspnum_steps searcher search(max_stepsprob_bestprob_anyconif num_stepsstats append(num_stepsstats sort(if prob_best > label " (best)= elsep_ac min(prob_anycon -prob_bestlabel " (best)= fp(ac)= (prob_bestp_acplt plot(stats,range(len(stats)),label=labelplt legend(loc="upper left"#plt draw(slsearcher max_display_leveltemp_mdl #restore display testing cspsls py -(continuedversion june |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.