id
int64
0
25.6k
text
stringlengths
0
4.59k
19,000
def init_action(self)""the initial action act randomly initially could be overridden (but ' not sure why you would""self act random choice(self actionsself dist[self act+ return self act def select_action(selfreward)""select the action given the reward this implements "act randomlyand should be overridden""self total_score +reward self act random choice(self actionsself dist[self act+ return self act maslearn py -(continued class simpleqagent(gameagent)"""this agent just counts the number of times (it thinksit has won and does the actions it thinks is most likely to win ""def __init__(selfactionsalpha= q_init= explore= )""actions is the set of actions the agent can do alpha is the step size q_init is the initial -values explore is the probability of an exporatory (randomaction ""gameagent __init__(selfactionsself { :q_init for in self actionsself dist {act: for act in actionsunnormalized distibution self num_steps self alpha alpha self explore explore def select_action(selfreward)self total_score +reward self num_steps + self display( , "the reward for agent {self idwas {reward}"self [self act+self alpha*(reward-self [self act]if random random(self exploreself act random choice(self actionsact randomly elseself act utilities argmaxd(self qself dist[self act+ version june
19,001
multiagent systems self display( , "agent {self iddid {self act}"return self act maslearn py -(continued class stochasticqagent(gameagent)"""this agent maintains the -function for each state (or just the average reward as the future state is all the samechooses the best action using ""def __init__(selfactionsalpha= q_init= p_init= )""actions is the set of actions the agent can do alpha is the step size q_init is the initial -values p_init is the initial counts for ""gameagent __init__(selfactionsself { :q_init for in self actionsself dist { :p_init for in self actionsstart with random dist self alpha alpha self num_steps def select_action(selfreward)self total_score +reward self display( , "the reward for agent {self idwas {reward}"self [self act+self alpha*(reward-self [self act]a_best utilities argmaxall(self items()for in a_bestself dist[ + self display( , "distribution for agent {self idis {self dist}"self act select_from_dist(self distself display( , "agent {self iddid {self act}"return self act def normalize(dist)"""unnorm dict is {value:numberdictionarywhere the numbers are all non-negative returns dict where the numbers sum to one ""tot sum(dist values()return {var:val/tot for (var,valin dist items() def select_from_dist(dist)rand random random(for (act,probin normalize(distitems()rand -prob if rand return act the simulator takes game and simulates the gameversion june
19,002
maslearn py -(continued class simulategame(displayable)def __init__(selfgameagents)self game game self agents agents list of agents self action_history [self reward_history [self dist_history [self actions tuple(ag init_action(for ag in self agentsself num_steps def go(selfsteps)for in range(steps)self num_steps + self rewards self game play(self actionsself reward_history append(self rewardsself actions tuple(self agents[iselect_action(self rewards[ ]for in range(self game num_agents)self action_history append(self actionsself dist_history append([normalize(ag distfor ag in self agents]print("scores:"join( "agent {ag idaverage reward={ag total_score/self num_steps}for ag in self agents)#return self reward_historyself action_history def action_dist(self,which_actions=[ , ])""which actions is [ , returns the empirical disctribition of actions for agentswhere ai specifies the index of the actions for agent ""return [sum( for in sim action_history if [ ]==gm actions[ ][which_actions[ ]])/len(sim action_historyfor in range( )maslearn py -(continued def plot_dynamics(selfx_action= y_action= )#plt ion(make it interactive agents self agents x_act self game actions[ ][x_actiony_act self game actions[ ][y_actionplt xlabel( "probability {self game players[ ]{self agents[ actions[x_action]}"plt ylabel( "probability {self game players[ ]{self agents[ actions[y_action]}"plt plot([self dist_history[ ][ ][x_actfor in range(len(self dist_history))][self dist_history[ ][ ][y_actfor in version june
19,003
multiagent systems range(len(self dist_history))]color=' '#plt legend(plt savefig('soccerplot pdf'plt show(the following are some games from poole and mackworth [ maslearn py -(continued class shoppinggame(displayable)def __init__(self)self num_agents self actions [['shopping''football']]* self players ['football preferer goes to''shopping preferer goes to' def play(selfactions)return {('football''football')( , )('football''shopping')( , )('shopping''football')( , )('shopping''shopping')( , )}[actions class soccergame(displayable)def __init__(self)self num_agents self actions [['right''left']]* self players ['goalkeeper jumps''kicker kicks' def play(selfactions)return {('left''left')( )('left''right')( )('right''left')( )('right''right')( , }[actions class gameshow(displayable)def __init__(self)self num_agents self actions [['takes''gives']]* self players ['agent ''agent ' def play(selfactions)return {('takes''takes')( )('takes''gives')( )('gives''takes')( )('gives''gives')( , }[actions class uniquenegameexample(displayable)version june
19,004
def __init__(self)self num_agents self actions [[' '' '' '],[' '' '' ']self players ['agent does''agent does' def play(selfactions)return {(' '' ')( )(' '' ')( )(' '' ')( )(' '' ')( )(' '' ')( )(' '' ')( )(' '' ')( )(' '' ')( )(' '' ')( }[actions choose onegm shoppinggame(gm soccergame(gm gameshow(gm uniquenegameexample( choose one of the combinations of learnerssim=simulategame(gm,[stochasticqagent(gm actions[ ])stochasticqagent(gm actions[ ])])sim go( simsimulategame(gm,[simpleqagent(gm actions[ ])simpleqagent(gm actions[ ])])sim go( sim=simulategame(gm,[simpleqagent(gm actions[ ]),stochasticqagent(gm actions[ ])])sim go( sim=simulategame(gm,[stochasticqagent(gm actions[ ]),simpleqagent(gm actions[ ])])sim go( sim plot_dynamics( empirical proportion that agents did their action at index sim action_dist([ , ] (unnormalizedemprirical distribution for agent sim agents[ dist maslearn py -(continued solution to exercise (iof poole mackworth class stochasticqagent_i(gameagent)"""this agent maintains the -function for each state (or just the average reward as the future state is all the samechooses the best action using version june
19,005
multiagent systems ""def __init__(selfactionsalpha= q_init= p_init= beta= )""actions is the set of actions the agent can do alpha is the step size q_init is the initial -values p_init is the initial counts for beta is the discount for older probabilities ""gameagent __init__(selfactionsself { :q_init for in self actionsself dist { :p_init for in self actionsstart with random dist self alpha alpha self beta beta self num_steps def select_action(selfreward)self total_score +reward self display( , "the reward for agent {self idwas {reward}"self [self act+self alpha*(reward-self [self act]a_best utilities argmaxall(self items()for in self keys()self dist[ *( -self betafor in a_bestself dist[ + self display( , "distribution for agent {self idis {self dist}"self act select_from_dist(self distself display( , "agent {self iddid {self act}"return self act version june
19,006
relational learning collaborative filtering based on gradient descent algorithm of koreny bellr and volinskyc matrix factorization techniques for recommender systemsieee computer this assumes the form of the dataset from movielens (org/datasets/movielens/the rating are set of (useritemratingtimestamptuples relncollfilt py -latent property-based collaborative filtering import random import matplotlib pyplot as plt import urllib request from learnproblem import learner from display import displayable class cf_learner(learner)def __init__(selfrating_seta rating_set object rating_subset nonesubset of ratings to be used as training ratings test_subset nonesubset of ratings to be used as test ratings step_size gradient descent step size reglz the weight for the regularization terms num_properties number of hidden properties property_range properties are initialized to be between -property_range and property_range
19,007
relational learning )self rating_set rating_set self ratings rating_subset or rating_set training_ratings whichever is not empty if test_subset is noneself test_ratings self rating_set test_ratings elseself test_ratings test_subset self step_size step_size self reglz reglz self num_properties num_properties self num_ratings len(self ratingsself ave_rating (sum( for ( , , ,tin self ratings/self num_ratingsself users { for ( , , ,tin self ratingsself items { for ( , , ,tin self ratingsself user_bias { : for in self usersself item_bias { : for in self itemsself user_prop { :[random uniform(-property_range,property_rangefor in range(num_properties)for in self usersself item_prop { :[random uniform(-property_range,property_rangefor in range(num_properties)for in self itemsself zeros [ for in range(num_properties)self iter= def stats(self)self display( ,"ave sumsq error of mean for training="sum((self ave_rating-rating)** for (user,item,rating,timestampin self ratings)/len(self ratings)self display( ,"ave sumsq error of mean for test="sum((self ave_rating-rating)** for (user,item,rating,timestampin self test_ratings)/len(self test_ratings)self display( ,"error on training set"self evaluate(self ratings)self display( ,"error on test set"self evaluate(self test_ratings)learn carries out num iter steps of gradient descent relncollfilt py -(continued def prediction(self,user,item)"""returns prediction for this user on this item the use of get(is to handle users or items not in the training set ""return (self ave_rating self user_bias get(user, #self user_bias[userversion june
19,008
self item_bias get(item, #self item_bias[itemsum([self user_prop get(user,self zeros)[ ]*self item_prop get(item,self zeros)for in range(self num_properties)]) def learn(selfnum_iter )""do num_iter iterations of gradient descent ""for in range(num_iter)self iter + abs_error= sumsq_error= for (user,item,rating,timestampin random sample(self ratings,len(self ratings))error self prediction(user,itemrating abs_error +abs(errorsumsq_error +error error self user_bias[user-self step_size*error self item_bias[item-self step_size*error for in range(self num_properties)self user_prop[user][ -self step_size*error*self item_prop[item][pself item_prop[item][ -self step_size*error*self user_prop[user][pfor user in self usersself user_bias[user-self step_size*self reglzself user_bias[userfor in range(self num_properties)self user_prop[user][ -self step_size*self reglz*self user_prop[user][pfor item in self itemsself item_bias[item-self step_size*self reglz*self item_bias[itemfor in range(self num_properties)self item_prop[item][ -self step_size*self reglz*self item_prop[item][pself display( ,"iteration",self iter"(ave abs,avesumsqtraining =",self evaluate(self ratings)"test =",self evaluate(self test_ratings)evaluate evaluates current predictions on the rating setrelncollfilt py -(continued def evaluate(self,ratings)"""returns (avergage_absolute_erroraverage_sum_squares_errorfor ratings ""abs_error sumsq_error if not ratingsreturn ( , for (user,item,rating,timestampin ratingsversion june
19,009
relational learning error self prediction(user,itemrating abs_error +abs(errorsumsq_error +error error return abs_error/len(ratings)sumsq_error/len(ratingsalternative formulation an alternative formulation is to regularize after each update plotting relncollfilt py -(continued def plot_predictions(selfexamples="test")""examples is either "testor "trainingor the actual examples ""if examples ="test"examples self test_ratings elif examples ="training"examples self ratings plt ion(plt xlabel("prediction"plt ylabel("cumulative proportion"self actuals [[for in range( , )for (user,item,rating,timestampin examplesself actuals[ratingappend(self prediction(user,item)for rating in range( , )self actuals[ratingsort(numrat=len(self actuals[rating]yvals [ /numrat for in range(numrat)plt plot(self actuals[rating]yvalslabel="rating="+str(rating)plt legend(plt draw(this plots single property each (useritemratingis plotted where the -value is the value of the property for the userthe -value is the value of the property for the itemand the rating is plotted at this (xyposition that israting is plotted at the (xyposition ( (user) (item)relncollfilt py -(continued def plot_property(selfpproperty plot_all=falsetrue if all points should be plotted num_points= number of random points plotted if not all )"""plot some of the user-movie ratingsversion june
19,010
if plot_all is true num_points is the number of points selected at random plotted the plot has the users on the -axis sorted by their value on property and with the items on the -axis sorted by their value on property and the ratings plotted at the corresponding - position ""plt ion(plt xlabel("users"plt ylabel("items"user_vals [self user_prop[ ][pfor in self usersitem_vals [self item_prop[ ][pfor in self itemsplt axis([min(user_vals)- max(user_vals)+ min(item_vals)- max(item_vals)+ ]if plot_allfor ( , , ,tin self ratingsplt text(self user_prop[ ][ ]self item_prop[ ][ ]str( )elsefor in range(num_points)( , , ,trandom choice(self ratingsplt text(self user_prop[ ][ ]self item_prop[ ][ ]str( )plt show(creating rating sets rating set can be read from the internet or read from local file the default is to read the movielens dataset from the internet it would be more efficient to save the dataset as local fileand then set local file trueas then it will not need to download the dataset every time the program is run relncollfilt py -(continued class rating_set(displayable)def __init__(selfdate_split= local_file=falseurl="file_name=" data")self display( ,"reading "if local_filelines open(file_name,' 'elseversion june
19,011
relational learning lines (line decode('utf- 'for line in urllib request urlopen(url)all_ratings (tuple(int(efor in line strip(split('\ ')for line in linesself training_ratings [self training_stats { : : : : , : self test_ratings [self test_stats { : : : : , : for rate in all_ratingsif rate[ date_splitrate[ is timestamp self training_ratings append(rateself training_stats[rate[ ]+ elseself test_ratings append(rateself test_stats[rate[ ]+ self display( ,read:"len(self training_ratings),"training ratings and"len(self test_ratings),"test ratings"tr_users {user for (user,item,rating,timestampin self training_ratingstest_users {user for (user,item,rating,timestampin self test_ratingsself display( ,"users:",len(tr_users),"training,",len(test_users),"test,"len(tr_users test_users),"in common"tr_items {item for (user,item,rating,timestampin self training_ratingstest_items {item for (user,item,rating,timestampin self test_ratingsself display( ,"items:",len(tr_items),"training,",len(test_items),"test,"len(tr_items test_items),"in common"self display( ,"rating statistics for training set",self training_statsself display( ,"rating statistics for test set",self test_statssometimes it is useful to plot property for all (useritemratingtriples there are too many such triples in the data set the method create top subset creates much smaller dataset where this makes sense it picks the most rated itemsthen picks the users who have the most ratings on these items it is designed for depicting the meaning of propertiesand may not be useful for other purposes relncollfilt py -(continued def create_top_subset(selfnum_items num_users )"""returns subset of the ratings by picking the most rated itemsand then the users that have most ratings on theseand then all of the ratings that involve these users and items ""items {item for (user,item,rating,timestampin self training_ratings version june
19,012
item_counts { : for in itemsfor (user,item,rating,timestampin self training_ratingsitem_counts[item+ items_sorted sorted((item_counts[ ],ifor in itemstop_items items_sorted[-num_items:set_top_items set(item for (countitemin top_items users {user for (user,item,rating,timestampin self training_ratingsuser_counts { : for in usersfor (user,item,rating,timestampin self training_ratingsif item in set_top_itemsuser_counts[user+ users_sorted sorted((user_counts[ ],ufor in userstop_users users_sorted[-num_users:set_top_users set(user for (countuserin top_usersused_ratings (user,item,rating,timestampfor (user,item,rating,timestampin self training_ratings if user in set_top_users and item in set_top_itemsreturn used_ratings movielens rating_set(learner cf_learner(movielensnum_properties #learner learn( learner plot_predictions(examples "training"learner plot_predictions(examples "test"#learner plot_property( #movielens_subset movielens create_top_subset(num_items num_users #learner_s cf_learner(movielensrating_subset=movielens_subsettest_subset=[]num_properties= #learner_s learn( #learner_s plot_property( ,plot_all=trueversion june
19,013
version history version updated the csp code to have the same representation of variables as used by the probability code version major revisions to and introduced recursive conditioningsimplified much code new section on multiagent reinforcement learning version simplified value iteration for mdps version planning simplifiedand gives error if goal not part of state (by designfixed arc costs version added positions and string to constraints version rerepresented blocks world (section due to bug found by donato meoli
19,014
chent and guestrinc ( )xgboosta scalable tree boosting system in kdd ' proceedings of the nd acm sigkdd international conference on knowledge discovery and data miningpages - url cholletf ( )deeep learning with python manning duad and graffc ( )uci machine learning repository url archive ics uci edu/ml glorotx and bengioy ( )understanding the difficulty of training deep feedforward neural networks in tehy and titteringtonm (eds )proceedings of the thirteenth international conference on artificial intelligence and statisticsvolume of proceedings of machine learning researchpages pmlrchia laguna resortsardiniaitalyurl mlr press/ /glorot html lichmanm ( )uci machine learning repository url ics uci edu/ml pooled and mackwortha ( )artificial intelligencefoundations of computational agents cambridge university press nd editionurl https//artint info
19,015
bnfromdbn beliefnetwork boosted dataset boosting learner branch and bound cf learner cpdrename csp csp from strips clause con solver constraint dbn dbnvefilter dbnvariable df branch and bound dt learner data from file data from files data set data set augmented decisionnetwork decisionvariable displayable dropout layer em learner - pruning asearch asearch action agent argmax assignment assumable asynchronous value iteration augmented feature batched stochastic gradient descent bayesian network belief network blocks world boolean feature botton-up proof branch-and-bound search class action instance agent arc askable assumable
19,016
19,017
some of the key aspects of this book are it assumes knowledge of python and of concepts such as functionsclassesprotocolsabstract base classesdecoratorsiterablescollection types (such as list and tupleetc howeverthe book assumes very little knowledge or experience of the topics presented the book is divided into eight topic areascomputer graphicsgamestestingfile input/outputdatabase accessloggingconcurrency and parallelism and network programming each topic in the book has an introductory followed by that delve into that topic the book includes exercises at the end of most all code examples (and exercise solutionsare provided on line in github repository organisation each has brief introductionthe main body of the followed by list of online references that can be used for further reading following this there is typically an exercises section that lists one or more exercises that build on the skills you will have learnt in that sample solutions to the exercises are available in github repository that supports this book vii
19,018
preface what you need you can of course just read this bookhowever following the examples in this book will ensure that you get as much as possible out of the content for this you will need computer python is cross platform programming language and as such you can use python on windows pca linux box or an apple mac etc this means that you are not tied to particular type of operating systemyou can use whatever you have available however you will need to install some software on your computer at minimum you will need python the focus of this book is python so that is the version that is assumed for all examples and exercises as python is available for wide range of platforms from windowsto mac os and linuxyou will need to ensure that you download the version for your operating system python can be downloaded from the main python web site which can be found at you will also need some form of editor in which to write your programs there are numerous generic programming editors available for different operating systems with vim on linuxnotepad+on windows and sublime text on windows and macs being popular choices
19,019
ix howeverusing ide (integrated development environmenteditor such as pycharm can make writing and running your programs much easier howeverthis book doesn' assume any particular editoride or environment (other than python itselfpython versions currently there are two main versions of python called python and python python was launched in october and has beenand still isvery widely used python was launched in december and is major revision to the language that is not backward compatible the issues between the two versions can be highlighted by the simple print facilityin python this is written as print 'hello worldin python this is written as print ('hello world'it may not look like much of difference but the inclusion of the '()marks major change and means that any code written for one version of python will probably not run on the other version there are tools availablesuch as the to utilitythat will (partiallyautomate translation from python to python but in general you are still left with significant work to do this then raises the question which version to usealthough interest in python is steadily increasing there are many organisations that are still using python choosing which version to use is constant concern for many companies howeverthe python end of life plan was initially announced back in and although it has been postponed to out of concern that large body of existing code could not easily be forward-ported to python it is still living on borrowed time python is the future of the python language and it is this version that has introduced many of the new and improved language and library features (that have admittedly been back ported to python in many casesthis book is solely focussed on python useful python resources there are wide range of resources on the web for pythonwe will highlight few here that you should bookmark we will not keep referring to these to avoid repetition but you can refer back to this section whenever you need tofoundation
19,020
preface tutorialslibrary referencesset up and installation guides as well as python how-tos the python language--this is where you can find online documentation for the various class and functions that we will be using throughout this book manymany python modules with short examples and explanations of what the modules do python module is library of features that build on and expand the core python language for exampleif you are interested in building games using python then pygame is module specifically designed to make this easier focusses on single python topic each monthsuch as new library or module articlesprojectsvideos and upcoming events each section of the book will provide additional online references relevant to the topic being discussed conventions throughout this book you will find number of conventions used for text styles these text styles distinguish between different kinds of information code wordsvariable and python valuesused within the main body of the textare shown using courier font for examplethis program creates top level window (the wx frameand gives it title it also creates label ( wx statictext objectto be displayed within the frame in the above paragraph wx frame and wx statictext are classes available in python graphical user interface library block of python code is set out as shown here
19,021
xi note that keywords are shown in bold font in some cases something of particular interest may be highlighted with colourany command line or user input is shown in italics and coloured purplefor exampleor example code and sample solutions the examples used in this book (along with sample solutions for the exercises at the end of most are available in github repository github provides web interface to gitas well as server environment hosting git git is version control system typically used to manage source code files (such as those used to create systems in programming languages such as python but also javac# ++scala etc systems such as git are very useful for collaborative development as they allow multiple people to work on an implementation and to merge their work together they also provide useful historical view of the code (which also allows developers to roll back changes if modifications prove to be unsuitableif you already have git installed on your computer then you can clone (obtain copy ofthe repository locally using
19,022
preface if you do not have git then you can obtain zip file of the examples using you can of course install git yourself if you wish to do this see com/downloads versions of the git client for mac oswindows and linux/unix are available here howevermany ides such as pycharm come with git support and so offer another approach to obtaining git repository for more information on git see very good primer and is highly recommended acknowledgements would like to thank phoebe hunt for creating the pixel images used for the starshipmeteors game in chap
19,023
introduction introduction part computer graphics introduction to computer graphics introduction background the graphical computer era interactive and non interactive graphics pixels bit map versus vector graphics buffering python and computer graphics references online resources python turtle graphics introduction the turtle graphics library the turtle module basic turtle graphics drawing shapes filling shapes other graphics libraries graphics pyopengl online resources exercises xiii
19,024
contents computer generated art creating computer art computer art generator fractals in python the koch snowflake mandelbrot set online resources exercises introduction to matplotlib introduction matplotlib plot components matplotlib architecture backend layer the artist layer the scripting layer online resources graphing with matplotlib pyplot introduction the pyplot api line graphs coded format strings scatter graph when to use scatter graphs pie charts expanding segments when to use pie charts bar charts horizontal bar charts coloured bars stacked bar charts grouped bar charts figures and subplots graphs exercises graphical user interfaces introduction guis and wimps
19,025
xv windowing frameworks for python platform-independent gui libraries platform-specific gui libraries online resources the wxpython gui library the wxpython library wxpython modules windows as objects simple example the wx app class window classes widget/control classes dialogs arranging widgets within container drawing graphics online resources exercises simple gui application events in wxpython user interfaces event handling event definitions types of events binding an event to an event handler implementing event handling an interactive wxpython gui online resources exercises simple gui application gui interface to tic tac toe game pydraw wxpython example application introduction the pydraw application the structure of the application modelview and controller architecture pydraw mvc architecture additional classes object relationships the interactions between objects the pydrawapp the pydrawframe constructor
19,026
contents part ii changing the application mode adding graphic object the classes the pydrawconstants class the pydrawframe class the pydrawmenubar class the pydrawtoolbar class the pydrawcontroller class the drawingmodel class the drawingpanel class the drawingcontroller class the figure class the square class the circle class the line class the text class references exercises computer games introduction to games programming introduction games frameworks and libraries python games development using pygame online resources building games with pygame introduction the display surface events event types event information the event queue first pygame application further concepts more interactive pygame application alternative approach to processing input devices pygame modules online resources
19,027
xvii starshipmeteors pygame creating spaceship game the main game class the gameobject class displaying the starship moving the spaceship adding meteor class moving the meteors identifying collision identifying win increasing the number of meteors pausing the game displaying the game over message the starshipmeteors game online resources exercises part iii testing introduction to testing introduction types of testing what should be tested testing software systems unit testing integration testing system testing installation/upgrade testing smoke tests automating testing test driven development the tdd cycle test complexity refactoring design for testability testability rules of thumb online resources book resources pytest testing framework introduction what is pytest setting up pytest simple pytest example
19,028
contents working with pytest parameterised tests online resources exercises mocking for testing introduction why mock what is mocking common mocking framework concepts mocking frameworks for python the unittest mock library mock and magic mock classes the patchers mocking returned objects validating mocks have been called mock and magicmock usage naming your mocks mock classes attributes on mock classes mocking constants mocking properties raising exceptions with mocks applying patch to every test method using patch as context manager mock where you use it patch order issues how many mocks mocking considerations online resources exercises part iv file input/output introduction to filespaths and io introduction file attributes paths file input/output sequential access versus random access files and / in python online resources
19,029
xix reading and writing files introduction obtaining references to files reading files file contents iteration writing data to files using files and with statements the fileinput module renaming files deleting files random access files directories temporary files working with paths online resources exercise stream io introduction what is stream python streams iobase raw io/unbuffered io classes binary io/buffered io classes text stream classes stream properties closing streams returning to the open(function online resources exercise working with csv files introduction csv files the csv writer class the csv reader class the csv dictwriter class the csv dictreader class online resources exercises working with excel files introduction excel files
19,030
contents the openpyxl workbook class the openpyxl worksheet objects working with cells sample excel file creation application loading workbook from an excel file online resources exercises regular expressions in python introduction what are regular expressions regular expression patterns pattern metacharacters special sequences sets the python re module working with python regular expressions using raw strings simple example the match object the search(function the match(function the difference between matching and searching the findall(function the finditer(function the split(function the sub(function the compile(function online resources exercises part database access introduction to databases introduction what is databasedata relationships the database schema sql and databases data manipulation language transactions in databases further reading
19,031
xxi python db-api accessing database from python the db-api the connect function the connection object the cursor object mappings from database types to python types generating errors row descriptions transactions in pymysql online resources pymysql module the pymysql module working with the pymysql module importing the module connect to the database obtaining the cursor object using the cursor object obtaining information about the results fetching results close the connection complete pymysql query example inserting data to the database updating data in the database deleting data in the database creating tables online resources exercises part vi logging introduction to logging introduction why log what is the purpose of logging what should you log what not to log why not just use print online resources logging in python the logging module the logger
19,032
contents controlling the amount of information logged logger methods default logger module level loggers logger hierarchy formatters formatting log messages formatting log output online resources exercises advanced logging introduction handlers setting the root output handler programmatically setting the handler multiple handlers filters logger configuration performance considerations exercises part vii concurrency and parallelism introduction to concurrency and parallelism introduction concurrency parallelism distribution grid computing concurrency and synchronisation object orientation and concurrency threads processes some terminology online resources threading introduction threads thread states creating thread instantiating the thread class the thread class
19,033
xxiii the threading module functions passing arguments to thread extending the thread class daemon threads naming threads thread local data timers the global interpreter lock online resources exercise multiprocessing introduction the process class working with the process class alternative ways to start process using pool exchanging data between processes sharing state between processes process shared memory online resources exercises inter thread/process synchronisation introduction using barrier event signalling synchronising concurrent code python locks python conditions python semaphores the concurrent queue class online resources exercises futures introduction the need for future futures in python future creation simple example future running multiple futures waiting for all futures to complete processing results as completed
19,034
contents processing future results using callback online resources exercises concurrency with asyncio introduction asynchronous io async io event loop the async and await keywords using async and await async io tasks running multiple tasks collating results from multiple tasks handling task results as they are made available online resources exercises part viii reactive programming reactive programming introduction introduction what is reactive application the reactivex project the observer pattern hot and cold observables cold observables hot observables implications of hot and cold observables differences between event driven programming and reactive programming advantages of reactive programming disadvantages of reactive programming the rxpy reactive programming framework online resources reference rxpy observablesobservers and subjects introduction observables in rxpy observers in rxpy multiple subscribers/observers subjects in rxpy
19,035
xxv observer concurrency available schedulers online resources exercises rxpy operators introduction reactive programming operators piping operators creational operators transformational operators combinatorial operators filtering operators mathematical operators chaining operators online resources exercises part ix network programming introduction to sockets and web services introduction sockets web services addressing services localhost port numbers ipv versus ipv sockets and web services in python online resources sockets in python introduction socket to socket communication setting up connection an example client server application the system structure implementing the server application socket types and domains implementing the client application the socketserver module http server online resources exercises
19,036
contents web services in python introduction restful services restful api python web frameworks flask hello world in flask using json implementing flask web service simple service providing routing information running the service invoking the service the final solution online resources bookshop web service building flask bookshop service the design the domain model encoding books into json setting up the get services deleting book adding new book updating book what happens if we get it wrong bookshop services listing exercises
19,037
introduction introduction have heard many people over the years say that python is an easy language to lean and that python is also simple language to some extent both of these statements are truebut only to some extent while the core of the python language is easy to lean and relatively simple (in part thanks to its consistency)the sheer richness of the language constructs and flexibility available can be overwhelming in addition the python environmentits eco systemthe range of libraries availablethe often competing options available etc can make moving to the next level daunting once you have learned the core elements of the language such as how classes and inheritance workhow functions workwhat are protocols and abstract base classes etc where do you go nextthe aim of this book is to delve into those next steps the book is organised into eight different topics computer graphics the book covers computer graphics and computer generated art in python as well as graphical user interfaces and graphingcharting via matplotlib games programming this topic is covered using the pygame library testing and mocking testing is an important aspect of any software developmentthis book introduces testing in general and the pytest module in detail it also considers mocking within testing including what and when to mock file input/output the book covers text file reading and writing as well as reading and writing csv and excel files although not strictly related to file inputregulator expressions are included in this section as they can be used to process textual data held in files database access the book introduces databases and relational database in particular it then presents the python db-api database access standard and (cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science
19,038
introduction one implementation of this standardthe pymysql module used to access mysql database logging an often missed topic is that of logging the book therefore introduces logging the need for loggingwhat to log and what not to log as well as the python logging module concurrency and parallelism the book provides extensive coverage of concurrency topics including threadsprocesses and inter thread or process synchronisation it also presents futures and asyncio reactive programming this section of the book introduces reactive programming using the pyrx reactive programming library network programming the book concludes by introducing socket and web service communications in python each section is introduced by providing the background and key concepts of that topic subsequent then cover various aspects of the topic for examplethe first topic covered is on computer graphics this section has an introductory on computer graphics in general it then introduces the turtle graphics python library which can be used to generate graphical display the following considers the subject of computer generated art and uses the turtle graphics library to illustrate these ideas thus several examples are presented that might be considered art the concludes by presenting the well known koch snowflake and the mandelbrot fractal set this is followed by presenting the matplotlib library used for generating and charts and graphs (such as line chartbar chart or scatter graphthe section concludes with on graphical user interfaces (or guisusing the wxpython library this explores what we mean by gui and some of the alternatives available in python for creating gui subsequent topics follow similar pattern each programming or library oriented also includes numerous sample programs that can be downloaded from the guthub repository and executed these also include one or more end of exercises (with sample solutions also in the guthub repositorythe topics within the book can be read mostly independently of each other this allows the reader to dip into subject areas as and when required for examplethe file input/output section and the database access section can be read independently of each other (although in this case assessing both technologies may be useful in selecting an appropriate approach to adopt for the long term persistent storage of data in particular systemwithin each section there are usually dependenciesfor example it is necessary to understand the pygame library from the 'building games with pygameintroductory before exploring the worked case study presented by the on the starshipmeteors game similarly it is necessary to have read the threading and multiprocessing before reading the inter thread/process synchronisation
19,039
computer graphics
19,040
introduction to computer graphics introduction computer graphics are everywherethey are on your tvin cinema advertsthe core of many filmson your tablet or mobile phone and certainly on your pc or mac as well as on the dashboard of your caron your smart watch and in childrens electronic toys however what do we mean by the term computer graphicsthe term goes back to time when many (mostcomputers were purely textual in terms of their input and output and very few computers could generate graphical displays let alone handle input via such display howeverin terms of this book we take the term computer graphics to include the creation of graphical user interfaces (or guis)graphs and charts such as bar charts or line plots of datagraphics in computer games (such as space invaders or flight simulatoras well as the generation of and scenes or images we also use the term to include computer generated art the availability of computer graphics is very important for the huge acceptance of computer systems by non computer scientists over the last years it is in part thanks to the accessibility of computer systems via computer graphic interfaces that almost everybody now uses some form of computer system (whether that is pca tableta mobile phone or smart tva graphical user interface (guican capture the essence of an idea or situationoften avoiding the need for long passage of text or textual commands it is also because picture can paint thousand wordsas long as it is the right picture in many situations where the relationships between large amounts of information must be conveyedit is much easier for the user to assimilate this graphically than textually similarlyit is often easier to convey some meaning by manipulating some system entities on screenthan by combinations of text commands for examplea well chosen graph can make clear information that is hard to determine from table of the same data in turn an adventure style game can (cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science
19,041
introduction to computer graphics become engaging and immersive with computer graphics which is in marked contrast to the textual versions of the this highlights the advantages of visual presentation compared to purely textual one background every interactive software system has human computer interfacewhether it be single text line system or an advanced graphic display it is the vehicle used by developers for obtaining information from their user( )and in turnevery user has to face some form of computer interface in order to perform any desired computer operation historically computer systems did not have graphical user interface and rarely generated graphical view these systems from the and typically focussed on numerical or data processing tasks they were accessed via green or grey screens on text oriented terminal there was little or no opportunity for graphical output howeverduring this period various researchers at laboratories such as stanfordmitbell telephone labs and xerox were looking at the possibilities that graphic systems might offer to computers indeed even as far back as ivan sutherland showed that interactive computer graphics were feasible with his ph thesis on the sketchpad system the graphical computer era graphical computer displays and interactive graphical interfaces became common means of human-computer interaction during the such interfaces can save user from the need to learn complex commands they are less likely to intimidate computer naives and can provide large amount of information quickly in form which can be easily assimilated by the user the widespread use of high quality graphical interfaces (such as those provided by the apple macintosh and the early windows interfaceled many computer users to expect such interfaces to any software they use indeed these systems paved the way for the type of interface that is now omnipresent on pcsmacslinux boxestablets and smart phones etc this graphical user interface is based on the wimp paradigm (windowsiconsmenus and pointerswhich is now the prevalent type of graphical user interface in use today the main advantage of any window-based systemand particularly of wimp environmentis that it requires only small amount of user training there is no need to learn complex commandsas most operations are available either as iconsoperations on iconsuser actions (such as swipingor from menu optionsand are easy to use (an icon is small graphic object that is usually symbolic of an
19,042
operation or of larger entity such as an application program or filein generalwimp based systems are simple to learnintuitive to useeasy to retain and straightforward to work with these wimp systems are exemplified by the apple macintosh interface (see goldberg and robson as well as tesler)which was influenced by the pioneering work done at the palo alto research center on the xerox star machine it washoweverthe macintosh which brought such interfaces to the mass marketand first gained acceptance for them as tools for businesshome and industry this interface transformed the way in which humans expected to interact with their computersbecoming de facto standardwhich forced other manufacturers to provide similar interfaces on their own machinesfor example microsoft windows for the pc this type of interface can be augmented by providing direct manipulation graphics these are graphics which can be grabbed and manipulated by the userusing mouseto perform some operation or action icons are simple version of thisthe "openingof an icon causes either the associated application to execute or the associated window to be displayed interactive and non interactive graphics computer graphics can be broadly subdivided into two categoriesnon interactive computer graphics interactive computer graphics in non interactive computer graphics (aka passive computer graphicsan image is generated by computer typically on computer screenthis image can be viewed by the user (however they cannot interact with the imageexamples of non-interactive graphics presented later in this book include computer generated art in which an image is generated using the python turtle graphics library such an image can viewed by the user but not modified another example might be basic bar chart generated using matplotlib which presents some set of data interactive computer graphics by contrastinvolve the user interacting with the image displayed in the screen in some waythis might be to modify the data being displayed or to change they way in which the image is being rendered etc it is typified by interactive graphical user interfaces (guisin which user interacts with menusbuttonsinput fieldslidersscrollbars etc howeverother visual displays can also be interactive for examplea slider could be used with matplotlib chart this display could present the number of sales made on particular dateas the slider is moved so the data changes and the chart is modified to show different data sets another example is represented by all computer games which are inherently interactive and mostif not allupdate their visual display in response to some user inputs for example in the classic flight simulator gameas the user moves the joystick or mousethe simulated plane moves accordingly and the display presented to the user updates
19,043
introduction to computer graphics pixels key concept for all computer graphics systems is the pixel pixel was originally word formed from combining and shortening the words picture (or pixand element pixel is cell on the computer screen each cell represents dot on the screen the size of this dot or cell and the number of cells available will vary depending upon the typesize and resolution of the screen for exampleit was common for early windows pcs to have by resolution display (using vga graphics cardthis relates to the number of pixels in terms of the width and height this meant that there were pixels across the screen with rows of pixels down the screen by contrast todays tv displays have by pixels the size and number of pixels available affects the quality of the image as presented to user with lower resolution displays (with fewer individual pixelsthe image may appear blocky or poorly definedwhere as with higher resolution it may appear sharp and clear each pixel can be referenced by its location in the display grid by filling pixels on the screen with different colours various images/displays can be created for examplein the following picture single pixel has been filled at position by sequence of pixels can form linea circle or any number of different shapes howeversince the grid of pixels is based on individual pointsa diagonal line or circle may need to utilise multiple pixels which when zoomed may have jagged edges for examplethe following picture shows part of circle on which we have zoomed in
19,044
each pixel can have colour and transparency associated with it the range of colours available depends on the display system being used for examplemono chrome displays only allow black and whitewhere as grey scale display only allows various shades of grey to be displayed on modern systems it is usually possible to represent wide range of colours using the tradition rgb colour codes (where represents redg represents green and represents bluein this encoding solid red is represented by code such as [ where as solid green is represented by [ and solid blue by [ based on this idea various shades can be represented by combination of these codes such as orange which might be represented by [ this is illustrated below for set of rgb colours using different redgreen and blue valuesin addition it is possible to apply transparency to pixel this is used to indicate how solid the fill colour should be the above grid illustrates the effect of applying % and transparency to colours displayed using the python wxpython gui library in this library the transparency is referred to as the alpha opaque value it can have values in the range - where is completely transparent and is completely solid
19,045
introduction to computer graphics bit map versus vector graphics there are two ways of generating an image/display across the pixels on the screen one approach is known as bit mapped (or rastergraphics and the other is known as vector graphics in the bit mapped approach each pixel is mapped to the values to be displayed to create the image in the vector graphics approach geometric shapes are described (such as lines and pointsand these are then rendered onto display raster graphics are simpler but vector graphics provide much more flexibility and scalability buffering one issue for interactive graphical displays is the ability to change the display as smoothly and cleanly as possible if display is jerky or seems to jump from one image to anotherthen users will find it uncomfortable it is therefore common to drawn the next display on some in memory structureoften referred to as buffer this buffer can then be rendered on the display once the whole image has been created for example turtle graphics allows the user to define how many changes should be made to the display before it is rendered (or drawnon to the screen this can significantly speed up the performance of graphic application in some cases systems will use two buffersoften referred to as double buffering in this approach one buffer is being rendered or drawn onto the screen while the other buffer is being updated this can significantly improve the overall performance of the system as modern computers can perform calculations and generate data much faster than it can typically be drawn onto screen python and computer graphics in the remainder of this section of the book we will look at generating computer graphics using the python turtle graphics library we will also discuss using this library to create computer generated art following this we will explore the matplotlib library used to generate charts and data plots such as bar chartsscatter graphsline plots and heat maps etc we will then explore the use of python libraries to create guis using menusfieldstables etc
19,046
references the following are referenced in this sutherlandsketchpada man-machine graphical communication system (courtesy computer laboratoryuniversity of cambridge ucam-cl-tr- september )january smithc irbyr kimballb verplanke harslemdesigning the star user interface byte ( ) - ( online resources the following provide further reading materialsketchpad_a_man-machine_graphical_communication_system_jan pdf ivan sutherlands ph
19,047
python turtle graphics introduction python is very well supported in terms of graphics libraries one of the most widely used graphics libraries is the turtle graphics library introduced in this this is partly because it is straight forward to use and partly because it is provided by default with the python environment (and this you do not need to install any additional libraries to use itthe concludes by briefly considering number of other graphic libraries including pyopen gl the pyopengl library can be used to create sophisticated scenes the turtle graphics library the turtle module this provides library of features that allow what are known as vector graphics to be created vector graphics refers to the lines (or vectorsthat can be drawn on the screen the drawing area is often referred to as drawing plane or drawing board and has the idea of xy coordinates the turtle graphics library is intended just as basic drawing toolother libraries can be used for drawing two and three dimensional graphs (such as matplotlibbut those tend to focus on specific types of graphical displays the idea behind the turtle module (and its namederives from the logo programming language from the and that was designed to introduce programming to children it had an on screen turtle that could be controlled by commands such as forward (which would move the turtle forward)right (which would turn the turtle by certain number of degrees)left (which turns the turtle left by certain number of (cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science
19,048
python turtle graphics degreesetc this idea has continued into the current python turtle graphics library where commands such as turtle forward( moves the turtle (or cursor as it is nowforward pixels etc by combining together these apparently simple commandsit is possible to create intricate and quiet complex shapes basic turtle graphics although the turtle module is built into python it is necessary to import the module before you use itimport turtle there are in fact two ways of working with the turtle moduleone is to use the classes available with the library and the other is to use simpler set of functions that hide the classes and objects in this we will focus on the set of functions you can use to create drawings with the turtle graphics library the first thing we will do is to set up the window we will use for our drawingsthe turtlescreen class is the parent of all screen implementations used for whatever operating system you are running on if you are using the functions provided by the turtle modulethen the screen object is initialised as appropriate for your operating system this means that you can just focus on the following functions to configure the layout/display such as this screen can have titlea sizea starting location etc the key functions aresetup(widthheightstartxstartysets the size and position of the main window/screen the parameters arewidth--if an integera size in pixelsif floata fraction of the screendefault is of screen height--if an integerthe height in pixelsif floata fraction of the screendefault is of screen startx--if positivestarting position in pixels from the left edge of the screenif negative from the right edgeif nonecenter window horizontally starty--if positivestarting position in pixels from the top edge of the screenif negative from the bottom edgeif nonecenter window vertically title(titlestringsets the title of the screen/window exitonclick(shuts down the turtle graphics screen/window when the use clicks on the screen bye(shuts down the turtle graphics screen/window done(starts the main event loopthis must be the last statement in turtle graphics program
19,049
speed(speedthe drawing speed to usethe default is the higher the value the faster the drawing takes placevalues in the range - are accepted turtle tracer( nonethis can be used to batch updates to the turtle graphics screen it is very useful when drawing become large and complex by setting the number (nto large number (say then elements will be drawn in memory before the actual screen is updated in one gothis can significantly speed up the generation of for examplea fractal picture when called without argumentsreturns the currently stored value of turtle update(perform an update of the turtle screenthis should be called at the end of program when tracer(has been used as it will ensure that all elements have been drawn even if the tracer threshold has not yet been reached pencolor(colorused to set the colour used to draw lines on the screenthe color can be specified in numerous ways including using named colours set as 'red''blue''greenor using the rgb colour codes or by specifying the color using hexadecimal numbers for more information on the named colours and rgb colour codes to use see note all colour methods use american spellings for example this method is pencolor (not pencolourfillcolor(colorused to set the colour to use to fill in closed areas within drawn lines again note the spelling of colourthe following code snippet illustrates some of these functionsimport turtle set title for your canvas window turtle title('my turtle animation'set up the screen size (in pixelsset the starting point of the turtle ( turtle setup(width= height= startx= starty= sets the pen color to red turtle pencolor('red'add this so that the window will close when clicked on turtle exitonclick(we can now look at how to actually draw shape onto the screen the cursor on the screen has several propertiesthese include the current drawing colour of the pen that the cursor movesbut also its current position (in the xy coordinates of the screenand the direction it is currently facing we have
19,050
python turtle graphics already seen that you can control one of these properties using the pencolor(methodother methods are used to control the cursor (or turtleand are presented below the direction in which the cursor is pointing can be altered using several functions includingright(angleturn cursor right by angle units left(angleturn the cursor left by angle units setheading(to_angleset the orientation of the cursor to to_angle where is east is north is west and is south you can move the cursor (and if the pen is down this will draw lineusingforward(distancemove the cursor forward by the specified distance in the direction that the cursor is currently pointing if the pen is down then draw line backward(distancemove the cursor backward by distance in the opposite direction that in which the cursor is pointing and you can also explicitly position the cursorgoto(xymove the cursor to the xy location on the screen specifiedif the pen is down draw line you can also use steps and set position to do the same thing setx(xsets the cursor' coordinateleaves the coordinate unchanged sety(ysets the cursor' coordinateleaves the coordinate unchanged it is also possible to move the cursor without drawing by modifying whether the pen is up or downpenup(move the pen up--moving the cursor will no longer draw line pendown(move the pen down--moving the cursor will now draw line in the current pen colour the size of the pen can also be controlledpensize(widthset the line thickness to width the method width(is an alias for this method it is also possible to draw circle or dotcircle(radiusextentstepsdraws circle using the given radius the extent determines how much of the circle is drawnif the extent is not given then the whole circle is drawn steps indicates the number of steps to be used to drawn the circle (it can be used to draw regular polygonsdot(sizecolordraws filled circle with the diameter of size using the specified color
19,051
you can now use some of the above methods to draw shape on the screen for this first examplewe will keep it very simplewe will draw simple squaredraw square turtle forward( turtle right( turtle forward( turtle right( turtle forward( turtle right( turtle forward( turtle right( the above moves the cursor forward pixels then turns deg before repeating these steps three times the end result is that square of pixels is drawn on the screennote that the cursor is displayed during drawing (this can be turned off with turtle hideturtle(as the cursor was originally referred to as the turtledrawing shapes of course you do not need to just use fixed values for the shapes you drawyou can use variables or calculate positions based on expressions etc for examplethe following program creates sequences of squares rotated around central location to create an engaging image
19,052
python turtle graphics import turtle def setup()""provide the config for the screen ""turtle title('multiple squares animation'turtle setup( turtle hideturtle(def draw_square(size)""draw square in the current direction ""turtle forward(sizeturtle right( turtle forward(sizeturtle right( turtle forward(sizeturtle right( turtle forward(sizesetup(for in range( )draw_square( rotate the starting direction turtle right( add this so that the window will close when clicked on turtle exitonclick(in this program two functions have been definedone to setup the screen or window with title and size and to turn off the cursor display the second function takes size parameter and uses that to draw square the main part of the program then sets up the window and uses for loop to draw squares of pixels each by continuously rotating deg between each square note that as we do not need to reference the loop variable we are using the '_format which is considered an anonymous loop variable in python the image generated by this program is shown below
19,053
filling shapes it is also possible to fill in the area within drawn shape for exampleyou might wish to fill in one of the squares we have drawn as shown belowto do this we can use the begin_fill(and end_fill(functionsbegin_fill(indicates that shapes should be filled with the current fill colourthis function should be called just before drawing the shape to be filled end_fill(called after the shape to be filled has been finished this will cause the shape drawn since the last call to begin_fill(to be filled using the current fill colour filling(return the current fill state (true if fillingfalse if notthe following program uses this (and the earlier draw_square(functionto draw the above filled squareturtle title('filled square example'turtle setup( turtle hideturtle(turtle pencolor('red'turtle fillcolor('yellow'turtle begin_fill(draw_square( turtle end_fill(turtle done( other graphics libraries of course turtle graphics is not the only graphics option available for pythonhowever other graphics libraries do not come pre-packed with python and must be downloaded using tool such as anacondapip or pycharm
19,054
python turtle graphics pyqtgraph the pyqtgraph library is pure python library oriented towards mathematicsscientific and engineering graphic applications as well as gui applications for more information see pillow pillow is python imaging library (based on pil the python imaging librarythat provides image processing capabilities for use in python for more information on pillow see pyglet pyglet is another windowing and multimedia library for python see graphics although it is certainly possible for developer to create convincing images using turtle graphicsit is not the primary aim of the library this means that there is no direct support for creating images other than the basic cursor moving facilities and the programers skill howeverthere are graphics libraries available for python one such library is panda (while third is pi (the pyopengl library as this builds on the very widely used opengl library pyopengl pyopengl his an open source project that provides set of bindings (or wrappings aroundthe opengl library opengl is the open graphics library which is cross languagecross platform api for rendering and vector graphics opengl is used in wide range of applications from gamesto virtual realitythrough data and information visualisation systems to computer aided design (cadsystems pyopengl provides set of python functions that call out from python to the underlying opengl libraries this makes it very easy to create vector based images in python using the industry standard opengl library very simple examples of an image created using pyopengl is given below
19,055
online resources the following provide further reading materialintended for teaching the basic concepts behind programming using the turtle graphics library exercises the aim of this exercise is to create graphic display using python turtle graphics you should create simple program to draw an octagon on the turtle graphics screen modify your program so that there is an hexagon drawing function this function should take three parametersthe xand coordinates to start drawing the octagon and the size of each side of the octagon modify your program to draw the hexagon in multiple locations to create the following picture
19,056
computer generated art creating computer art computer art is defined as any art that uses computer howeverin the context of this book we mean it to be art that is generated by computer or more specifically computer program the following exampleillustrates how in very few lines of python codeusing the turtle graphics libraryyou can create images that might be considered to be computer art the following image is generated by recursive function that draws circle at given xy location of specified size this function recursively calls itself by modifying the parameters so that smaller and smaller circles are drawn at different locations until the size of the circles goes below pixels (cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science
19,057
computer generated art the program used to generate this picture is given below for referenceimport turtle width height def setup_window()set up the window turtle title('circles in my mind'turtle setup(widthheight turtle colormode( indicates rgb numbers will be in the range to turtle hideturtle(batch drawing to the screen for faster rendering turtle tracer( speed up drawing process turtle speed( turtle penup(def draw_circle(xyradiusred= green= blue= width= )""draw circle at specific xy location then draw four smaller circles recursively""colour (redgreenbluerecursively drawn smaller circles if radius calculate colours and line width for smaller circles if red red red green green blue blue width -
19,058
elsered green calculate the radius for the smaller circles new_radius int(radius drawn four circles draw_circle(int( new_radius)ynew_radiusredgreenbluewidthdraw_circle( new_radiusynew_radiusredgreenbluewidthdraw_circle(xint( new_radius)new_radiusredgreenbluewidthdraw_circle(xint( new_radius)new_radiusredgreenbluewidthdraw the original circle turtle goto(xyturtle color(colourturtle width(widthturtle pendown(turtle circle(radiusturtle penup(run the program print('starting'setup_window(draw_circle( - ensure that all the drawing is rendered turtle update(print('done'turtle done(there are few points to note about this program it uses recursion to draw the circles with smaller and smaller circles being drawn until the radius of the circles falls below certain threshold (the termination pointit also uses the turtle tracer(function to speed up drawing the picture as changes will be buffered before the screen is updated finallythe colours used for the circles are changed at each level of recessiona very simple approach is used so that the redgreen and blue codes are changed resulting in different colour circles also line width is used to reduce the size of the circle outline to add more interest to the image computer art generator as another example of how you can use turtle graphics to create computer artthe following program randomly generates rgb colours to use for the lines being drawn which gives the pictures more interest it also allows the user to input an
19,059
computer generated art angle to use when changing the direction in which the line is drawn as the drawing happens within loop even this simple change to the angle used to draw the lines can generate very different pictures lets play with some colours import turtle from random import randint def get_input_angle()""obtain input from user and convert to an int""message 'please provide an angle:value_as_string input(messagewhile not value_as_string isnumeric()print('the input must be an integer!'value_as_string input(messagereturn int(value_as_stringdef generate_random_colour()"""generates an , , values randomly in range to "" randint( randint( randint( return rgb print('set up screen'turtle title('colourful pattern'turtle setup( turtle hideturtle(turtle bgcolor('black'set the background colour of the screen turtle colormode( indicates rgb numbers will be in the range to turtle speed( angle get_input_angle(print('start the drawing'for in range( )turtle color(generate_random_colour()turtle forward(iturtle right(angleprint('done'turtle done(
19,060
some sample images generated from this program are given below the left most picture is generated by inputting an angle of degreesthe picture on the right uses an angle of degrees and the bottom picture an angle of degrees the following pictures below use angles of and degrees respectively what is interesting about these images is how different each iseven though they use exactly the same program this illustrates how algorithmic or computer generated art can be as subtle and flexible as any other art form it also illustrates that even with such process it is still up to the human to determine which image (if anyis the most aesthetically pleasing
19,061
computer generated art fractals in python within the arena of computer art fractals are very well known art form factrals are recurring patterns that are calculated either using an iterative approach (such as for loopor recursive approach (when function calls itself but with modified parametersone of the really interesting features of fractals is that they exhibit the same pattern (or nearly the same patternat successive levels of granularity that isif you magnified fractal image you would find that the same pattern is being repeated at successively smaller and smaller magnifications this is known as expanding symmetry or unfolding symmetryif this replication is exactly the same at every scalethen it is called affine self-similar fractals have their roots in the world of mathematics starting in the th centurywith the term fractal being coined in the th century by mathematical benoit mandelbrot in one often cited description that mandelbrot published to describe geometric fractals is rough or fragmented geometric shape that can be split into partseach of which is (at least approximatelya reduced-size copy of the whole for more information see mandelbrotbenoit ( the fractal geometry of nature macmillan isbn (- - since the later part of the th century fractals have been commonly used way of creating computer art one example of fractal often used in computer art is the koch snowflakewhile another is the mandelbrot set both of these are used in this as examples to illustrate how python and the turtle graphics library can be used to create fractal based art the koch snowflake the koch snowflake is fractal that begins with equilateral triangle and then replaces the middle third of every line segment with pair of line segments that form an equilateral bump this replacement can be performed to any depth generating finer and finer grained (smaller and smallertriangles until the overall shape resembles snow flake
19,062
the following program can be used to generate koch snowflake with different levels of recursion the larger the number of levels of recursion the more times each line segment is dissected import turtle set up constants angles [ - size_of_snowflake def get_input_depth()""obtain input from user and convert to an int""message 'please provide the depth ( or positive interger):value_as_string input(messagewhile not value_as_string isnumeric()print('the input must be an integer!'value_as_string input(messagereturn int(value_as_stringdef setup_screen(titlebackground='white'screen_size_x= screen_size_y= tracer_size= )print('set up screen'turtle title(titleturtle setup(screen_size_xscreen_size_yturtle hideturtle(turtle penup(turtle backward( batch drawing to the screen for faster rendering turtle tracer(tracer_sizeturtle bgcolor(backgroundset the background colour of the screen
19,063
computer generated art def draw_koch(sizedepth)if depth for angle in anglesdraw_koch(size depth turtle left(angleelseturtle forward(sizedepth get_input_depth(setup_screen('koch snowflake (depth str(depth')'background='black'screen_size_x= screen_size_y= set foreground colours turtle color('sky blue'ensure snowflake is centred turtle penup(turtle setposition(- , turtle left( turtle pendown(draw three sides of snowflake for in range( )draw_koch(size_of_snowflakedepthturtle right( ensure that all the drawing is rendered turtle update(print('done'turtle done(several different runs of the program are shown below with the depth set at and
19,064
running the simple draw_koch(function with different depths makes it easy to see the way in which each side of triangle can be dissected into further triangle like shape this can be repeated to multiple depths giving more detailed structured in which the same shape is repeated again and again mandelbrot set probably one of the most famous fractal images is based on the mandelbrot set the mandelbrot set is the set of complex numbers for which the function does not diverge when iterated from for which the sequence of functions (func( )func(func( )etc remains bounded by an absolute value the definition of the mandelbrot set and its name is down to the french mathematician adrien douadywho named it as tribute to the mathematician benoit mandelbrot mandelbrot set images may be created by sampling the complex numbers and testingfor each sample point cwhether the sequence func( )func(func( )etc ranges to infinity (in practice this means that test is made to see if it leaves some predetermined bounded neighbourhood of after predetermined number of iterationstreating the real and imaginary parts of as image coordinates on the complex planepixels may then be coloured according to how soon the sequence crosses an arbitrarily chosen thresholdwith special color (usually blackused for the values of for which the sequence has not crossed the threshold
19,065
computer generated art after the predetermined number of iterations (this is necessary to clearly distinguish the mandelbrot set image from the image of its complementthe following image was generated for the mandelbrot set using python and turtle graphics the program used to generate this image is given belowfor in range(image_size_y)zy (max_y min_y(image_size_y min_y for in range(image_size_x)zx (max_x min_x(image_size_y min_x zx zy for in range(max_iterations)if abs( break turtle color(( )turtle setposition( screen_offset_xy screen_offset_yturtle pendown(turtle dot( turtle penup(
19,066
online resources the following provide further reading materialsnowflake exercises the aim of this exercise is to create fractal tree fractal tree is tree in which the overall structure is replicated at finer and finer levels through the tree until set of leaf elements are reached to draw the fractal tree you will need todraw the trunk at the end of the trunksplit the trunk in two with the left trunk and the right trunk being deg left/right of the original trunk for aesthetic purposes the trunk may become thinner each time it is split the trunk may be drawn in particular colour such as brown continue this until maximum number of splits have occurred (or the trunk size reduces to particular minimumyou have now reached the leaves (you may draw the leaves in different colour greenan example of fractal tree is given below
19,067
introduction to matplotlib introduction matplotlib is python graphing and plotting library that can generate variety of different types of graph or chart in variety of different formats it can be used to generate line chartsscatter graphsheat mapsbar chartspie charts and plots it can even support animations and interactive displays an example of graph generated using matplotlib is given below this shows line chart used to plot simple sign wavematplotlib is very flexible and powerful graphing library it can support variety of different python graphics platforms and operating system windowing environments it can also generate output graphics in variety of different formats including pngjpegsvg and pdf etc (cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science
19,068
introduction to matplotlib matplotlib can be used on its own or in conjunction with other libraries to provide wide variety of facilities one library that is often used in conjunction with matplotlib is numpy which is library often used in data science applications that provides variety of functions and data structures (such as -dimensional arraysthat can be very useful when processing data for display within chart howevermatplotlib does not come prebuilt into the python environmentit is an optional module which must be added to your environment or ide in this we will introduce the matplotlib libraryits architecturethe components that comprise chart and the pyplot api the pyplot api is the simplest and most common way in which programmer interacts with matplotlib we will then explore variety of different types of chart and how they can be created using matplotlibfrom simple line chartsthrough scatter chartsto bar charts and pie charts we will finish by looking at simple chart matplotlib matplotlib is graph plotting library for python for simple graphs matplotlib is very easy to usefor example to create simple line graph for set of and coordinates you can use the matplotlib pyplot plot functionimport matplotlib pyplot as pyplot plot sequence of values pyplot plot([ ]display the chart in window pyplot show(this very simple program generates the following graph
19,069
in this examplethe plot(function takes sequence of values which will be treated as the axis valuesthe axis values are implied by the position of the values within the list thus as the list has six elements in it the axis has the range - in turn as the maximum value contained in the list is then the axis ranges from to plot components although they may seem simplethere are numerous elements that comprise matplotlib graph or plot these elements can all be manipulated and modified independently it is therefore useful to be familiar with the matplotlib terminology associated with these elementssuch as tickslegendslabels etc the elements that make up plot are illustrated belowthe diagram illustrates the following elementsaxes an axes is defined by the matplotlib axes axes class it is used to maintain most of the elements of figure namely the and axisthe ticksthe line plotsany text and any polygon shapes title this is the title of the whole figure ticks (major and minorthe ticks are represented by the class matplotlib axis tick tick is the mark on the axis indicating new
19,070
introduction to matplotlib value there can be major ticks which are larger and may be labeled there are also minor ticks which can be smaller (and may also be labelledtick labels (major and minorthis is label on tick axis the maplotlib axis axis class defines an axis object (such as an or axiswithin parent axes instance it can have formatters used to format the labels used for the major and minor ticks it is also possible to set the locations of the major and minor ticks axis labels (xy and in some cases zthese are labels used to describe the axis plot types such as line and scatter plots various types of plots and graphs are supported by matplotlib including line plotsscatter graphsbar charts and pie charts grid this is an optional grid displayed behind plotgraph or chart the grid can be displayed with variety of different line styles (such as solid or dashed lines)colours and line widths matplotlib architecture the matplotlib library has layered architecture that hides much of the complexity associated with different windowing systems and graphic outputs this architecture has three main layersthe scripting layerthe artist layer and the backend layer each layer has specific responsibilities and components for examplethe backend is responsible for reading and interacting with the graph or plot being generated in turn the artist layer is responsible for creating the graph objects that will be rendered by the backend layer finally the scripting layer is used by the developer to create the graphs this architecture is illustrated below
19,071
backend layer the matplotlib backend layer handles the generation of output to different target formats matplotlib itself can be used in many different ways to generate many different outputs matplotlib can be used interactivelyit can be embedded in an application (or graphical user interface)it may be used as part of batch application with plots being stored as pngsvgpdf or other images etc to support all of these use casesmatplotlib can target different outputsand each of these capabilities is called backendthe "frontendis the developer facing code the backend layer maintains all the different backends and the programmer can either use the default backend or select different backend as required the backend to be used can be set via the matplotlib use(function for exampleto set the backend to render postscript usematplotlib use('ps'this is illustrated belowimport matplotlib if 'matplotlib backendsnot in sys modulesmatplotlib use('ps'import matplotlib pyplot as pyplot it should be noted that if you use the matplotlib use(functionthis must be done before importing matplotlib pyplot calling matplotlib use (after matplotlib pyplot has been imported will have no effect note that the argument passed to the matplotlib use(function is case sensitive the default renderer is the 'aggwhich uses the anti-grain geometry +library to make raster (pixelimage of the figure this produces high quality raster graphics based images of the data plots the 'aggbackend was chosen as the default backend as it works on broad selection of linux systems as its supporting requirements are quite smallother backends may run on one particular systembut may not work on another system this occurs if particular system does not have all the dependencies loaded that the specified matplotlib backend relies on
19,072
introduction to matplotlib the backend layer can be divided into two categoriesuser interface backends (interactivethat support various python windowing systems such as wxwidgets (discussed in the next qttk etc hardcopy backends (non interactivethat support raster and vector graphic outputs the user interface and hardcopy backends are built upon common abstractions referred to as the backend base classes the artist layer the artist layer provides the majority of the functionality that you might consider to be what matplotlib actually doesthat is the generation of the plots and graphs that are rendereddisplayed to the user (or output in particular formatthe artist layer is concerned with things such as the linesshapesaxisand axestext etc that comprise plot the classes used by the artist layer can be classified into one of the following three groupsprimitivescontainers and collectionsprimitives are classes used to represent graphical objects that will be drawn on to figures canvas containers are objects that hold primitives for exampletypically figure would be instantiated and used to create one or more axes etc collections are used to efficiently handle large numbers of similar types of objects although it is useful to be aware of these classesin many cases you will not need to work with them directly as the pyplot api hides much of the detail howeverit is possible to work at the level of figuresaxesticks etc if required
19,073
the scripting layer the scripting layer is the developer facing interface that simplifies the task of working with the other layers note that from the programmers point of viewthe scripting layer is represented by the pyplot module under the covers pyplot uses module-level objects to track the state of the datahandle drawing the graphs etc when imported pyplot selects either the default backend for the system or the one that has been configuredfor example via the matplotlib use(function it then calls setup(function thatcreates figure manager factory functionwhich when called will create new figure manager appropriate for the selected backendprepares the drawing function that should be used with the selected backendidentifies the callable function that integrates with the backend mainloop functionprovides the module for the selected backend the pyplot interface simplifies interactions with the internal wrappers by providing methods such as plot()pie()bar()title()savefig()draw(and figure(etc most of the examples presented in the next will use the functions provided by the pyplot module to create the required chartsthereby hiding the lower level details
19,074
introduction to matplotlib online resources see the online documentation forexamples with complete listingsdocumentationgalleries and detailed user guide and faq
19,075
graphing with matplotlib pyplot introduction in this we will explore the matplotlib pyplot api this is the most common way in which developers generate different types of graphs or plots using matplotlib the pyplot api the purpose of the pyplot module and the api it presents is to simplify the generation and manipulation of matplotlib plots and charts as whole the matplotlib library tries to make simple things easy and complex things possible the primary way in which it achieves the first of these aims is through the pyplot api as this api has high level functions such as bar()plot()scatter(and pie(that make it easy to create bar chartsline plotsscatter graphs and pie charts one point to note about the functions provided by the pyplot api is that they can often take very many parametershowever most of these parameters will have default values that in many situations will give you reasonable default behaviourdefault visual representation you can therefore ignore most of the parameters available until such time as you actually need to do something differentat which point you should refer to the matplotlib documentation as this has extensive material as well as numerous examples it is of course necessary to import the pyplot moduleas it is module within the matplotlib ( matplotlib pyplotlibrary it is often given an alias within program to make it easier to reference common alias for this module are pyplot or plt typical import for the pyplot module is given belowimport matplotlib pyplot as pyplot (cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science
19,076
graphing with matplotlib pyplot the plyplot api can be used to construct the plotconfigure labels and axismanage color and line styleshandles events/allows plots to be interactivedisplay (showthe plot we will see examples of using the pyplot api in the following sections line graphs line graph or line plot is graph with the points on the graph (often referred to as markersconnected by lines to show how something changes in value as some set of values (typically the axischangesfor exampleover series to time intervals (also known as time seriestime series line charts are typically drawn in chronological ordersuch charts are known as run charts the following chart is an example of run chartit charts time across the bottom ( axisagainst speed (represented by the axis
19,077
the program used to generate this chart is given belowimport matplotlib pyplot as pyplot set up the data [ [ set the axes headings pyplot ylabel('speed'fontsize= pyplot xlabel('time'fontsize= set the title pyplot title("speed time"plot and display the graph using blue circles for markers ('bo'and solid line ('-'pyplot plot(xy'bo-'pyplot show(the first thing that this program does is to import the matplotlib pyplot module and give it an alias of pyplot (as this is shorter name it makes the code easier to readtwo lists of values are then created for the and coordinates of each marker or plot point the graph itself is then configured with labels being provided for the and axis (using the pyplot functions xlabel(and ylabel()the title of the graph is then set (again using pyplot functionafter this the and values are then plotted as line chart on the graph this is done using the pyplot plot(function this function can take wide range of parametersthe only compulsory parameters being the data used to define the plot points in the above example third parameter is providedthis is string 'bo-this is coded format string in that each element of the string is meaningful to the pyplot plot(function the elements of the string areb--this indicates the colour to use when drawing the linein this case the letter 'bindicates the colour blue (in the same way 'rwould indicate red and 'gwould indicate greeno--this indicates that each marker (each point being plottedshould be represented by cirlce the lines between the markers then create the line plot '-'--this indicates the line style to use single dash ('-'indicates solid linewhere as double dash ('-'indicates dashed line
19,078
graphing with matplotlib pyplot finally the program then uses the show(function to render the figure on the screenalternatively savefig(could have been used to save the figure to file coded format strings there are numerous options that can be provided via the format stringthe following tables summarises some of thesethe following colour abbreviations are supported by the format stringcharacter color ' ' ' ' ' ' ' 'wblue green red cyan magenta yellow black white different ways of representing the markers (points on the graphconnected by the lines are also supported includingcharacter description ',' ' '^'<'>' ' '*' '+' 'dpoint marker pixel marker circle marker triangle_down marker triangle_up marker triangle_left marker triangle_right marker square marker pentagon marker star marker hexagon marker plus marker marker diamond marker
19,079
finallythe format string supports different line stylescharacter description '-'-'':solid line style dashed line style dash-dot line style dotted line style some examples of formatting strings'rred line with default markers and line style ' -green solid line '-dashed line with the default colour and default markers 'yo:yellow dotted line with circle markers scatter graph scatter graph or scatter plot is type of plot where individual values are indicated using cartesian (or and ycoordinates to display values each value is indicated via mark (such as circle or triangleon the graph they can be used to represent values obtained for two different variablesone plotted on the axis and the other plotted on the axis an example of scatter chart with three sets of scatter values is given below
19,080
graphing with matplotlib pyplot in this graph each dot represents the amount of time people of different ages spend on three different activities the program that was used to generate the above graph is shown belowimport matplotlib pyplot as pyplot create data riding (( )( )swimming (( )( )sailing (( )( )plot the data pyplot scatter( =riding[ ] =riding[ ] ='red'marker=' 'label='riding'pyplot scatter( =swimming[ ] =swimming[ ] ='green'marker='^'label='swimming'pyplot scatter( =sailing[ ] =sailing[ ] ='blue'marker='*'label='sailing'configure graph pyplot xlabel('age'pyplot ylabel('hours'pyplot title('activities scatter graph'pyplot legend(display the chart pyplot show(in the above example the plot scatter(function is used to generate the scatter graph for the data defined by the ridingswimming and sailing tuples the colours of the markers have been specified using the named parameter this parameter can take string representing the name of colour or two dimensional array with single row in which each value in the row represents an rgb color code the marker indicates the marker style such as 'ofor circlea '^for triangle and '*for star shape the label is used in the chart legend for the marker other options available on the pyplot scatter(function includealpha indicates the alpha blending valuebetween (transparentand (opaque
19,081
linewidths which is used to indicate the line width of the marker edges edgecolors indicates the color to use for the marker edges if different from the fill colour used for the marker (indicates by the parameter ' 'when to use scatter graphs useful question to consider is when should scatter plot be usedin general scatter plats are used when it is necessary to show the relationship between two variables scatter plots are sometimes called correlation plots because they show how two variables are correlated in many cases trend can be discerned between the points plotted on scatter chart (although there may be outlying valuesto help visualise the trend it can be useful to draw trend line along with the scatter graph the trend line helps to make the relationship of the scatter plots to the general trend clearer the following chart represents set of values as scatter graph and draws the trend line of this scatter graph as can be seen some values are closer to the trendline than others the trend line has been created in this case using the numpy function polyfit(
19,082
graphing with matplotlib pyplot the polyfit(function performs least squares polynomial fit for the data it is given poly class is then created based on the array returned by polyfit(this class is one-dimensional polynomial class it is convenience classused to encapsulate "naturaloperations on polynomials the poly object is then used to generate set of values for use with the set of values for the function pyplot plot(import numpy as np import matplotlib pyplot as pyplot ( ( generate the scatter plot pyplot scatter(xygenerate the trend line np polyfit(xy np poly (zpyplot plot(xp( )' 'display the figure pyplot show( pie charts pie chart is type of graph in which circle is divided into sectors (or wedgesthat each represent proportion of the whole wedge of the circle represents category' contribution to the overall total as such the graph resembles pie that has been cut into different sized slices typicallythe different sectors of the pie chart are presented in different colours and are arranged clockwise around the chart in order of magnitude howeverif there is slice that does not contain unique category of data but summarises severalfor example "other typesor "other answers"then even if it is not the smallest categoryit is usual to display it last in order that it does not detract from the named categories of interest
19,083
the following chart illustrates pie chart used to represent programming language usage within particular organisation the pie chart is created using the pyplot pie(function import matplotlib pyplot as pyplot labels ('python''java''scala'' #'sizes [ pyplot pie(sizeslabels=labelsautopct='% %%'counterclock=falsestartangle= pyplot show(the pyplot pie(function takes several parametersmost of which are optional the only required parameter is the first one that provides the values to be used for the wedge or segment sizes the following optional parameters are used in the above example
19,084
graphing with matplotlib pyplot the labels parameter is an optional parameter that can take sequence of strings that are used to provide labels for each wedge the autopct parameter takes string (or functionto be used to format the numeric values used with each wedge the counterclockwise parameter by default wedges are plotted counter clockwise in pyplot and so to ensure that the layout is more like the traditional clockwise approach the counterclock parameter is set to false the startangle parameter the starting angle has also been moved deg using the startangle parameter so that the first segment starts at the top of the chart expanding segments it can be useful to emphasis particular segment of the pie chart by exploding itthat is separating it out from the rest of the pie chart this can be done using the explode parameter of the pie(function that takes sequence of values indicating how much segment should be exploded by the visual impact of the pie chart can also be enhanced in this case by adding shadow to the segments using the named shadow boolean parameter the effect of these are shown below
19,085
the program that generated this modified chart is given below for referenceimport matplotlib pyplot as pyplot labels ('python''java''scala'' #'sizes [ only "explodethe st slice ( 'python'explode ( pyplot pie(sizesexplode=explodelabels=labelsautopct='% %%'shadow=truecounterclock=falsestartangle= pyplot show(when to use pie charts it is useful to consider what data can be/should be presented using pie chart in general pie charts are useful for displaying data that can be classified into nominal or ordinal categories nominal data is categorised according to descriptive or qualitative information such as program languagestype of carcountry of birth etc ordinal data is similar but the categories can also be rankedfor example in survey people may be asked to say whether they classed something as very poorpoorfairgoodvery good pie charts can also be used to show percentage or proportional data and usually the percentage represented by each category is provided next to the corresponding slice of pie pie charts are also typically limited to presenting data for six or less categories when there are more categories it is difficult for the eye to distinguish between the relative sizes of the different sectors and so the chart becomes difficult to interpret
19,086
graphing with matplotlib pyplot bar charts bar chart is type of chart or graph that is used to present different discrete categories of data the data is usually presented vertically although in some cases horizontal bar charts may be used each category is represented by bar whose height (or lengthrepresents the data for that category because it is easy to interpret bar chartsand how each category relates to anotherthey are one of the most commonly used types of chart there are also several different common variations such as grouped bar charts and stacked bar charts the following is an example of typical bar chart five categories of programming languages are presented along the axis while the axis indicates percentage usage each bar then represents the usage percentage associated with each programming language the program used to generate the above figure is given below
19,087
import matplotlib pyplot as pyplot set up the data labels ('python''scala'' #''java''php'index ( provides locations on axis sizes [ set up the bar chart pyplot bar(indexsizestick_label=labelsconfigure the layout pyplot ylabel('usage'pyplot xlabel('programming languages'display the chart pyplot show(the chart is constructed such that the lengths of the different bars are proportional to the size of the category they represent the -axis represents the different categories and so has no scale in order to emphasise the fact that the categories are discretea gap is left between the bars on the -axis the -axis does have scale and this indicates the units of measurement horizontal bar charts bar charts are normally drawn so that the bars are vertical which means that the taller the barthe larger the category howeverit is also possible to draw bar charts so that the bars are horizontal which means that the longer the barthe larger the category this is particularly effective way of presenting large number of different categories when there is insufficient space to fit all the columns required for vertical bar chart across the page in matplotlib the pyplot barh(function can be used to generate horizontal bar chart
19,088
graphing with matplotlib pyplot in this case the only line of code to change from the previous example ispyplot barh(x_valuessizestick_label labelscoloured bars it is also common to colour different bars in the chart in different colours or using different shades this can help to distinguish one bar from another an example is given below
19,089
the colour to be used for each category can be provided via the color parameter to the bar((and barh()function this is sequence of the colours to apply for examplethe above coloured bar chart can be generated usingpyplot bar(x_valuessizestick_label=labelscolor=('red''green''blue''yellow''orange')stacked bar charts bar charts can also be stacked this can be way of showing total values (and what contributes to those total valuesacross several categories that isit is way of viewing overall totalsfor several different categories based on how different elements contribute to those totals different colours are used for the different sub-groups that contribute to the overall bar in such casesa legend or key is usually provided to indicate what sub-group each of the shadings/colours represent the legend can be placed in the plot area or may be located below the chart for examplein the following chart the total usage of particular programming language is composed of its use in games and web development as well as data science analytics from this figure we can see how much each use of programming language contributes to the overall usage of that language the program that generated this chart is given below
19,090
graphing with matplotlib pyplot import matplotlib pyplot as pyplot set up the data labels ('python''scala'' #''java''php'index ( web_usage [ data_science_usage [ games_usage [ set up the bar chart pyplot bar(indexweb_usagetick_label=labelslabel='web'pyplot bar(indexdata_science_usagetick_label=labelslabel='data science'bottom=web_usageweb_and_games_usage [web_usage[idata_science_usage[ifor in range( len(web_usage))pyplot bar(indexgames_usagetick_label=labelslabel='games'bottom=web_and_games_usageconfigure the layout pyplot ylabel('usage'pyplot xlabel('programming languages'pyplot legend(display the chart pyplot show(one thing to note from this example is that after the first set of values are added using the pyplot bar(functionit is necessary to specify the bottom locations for the next set of bars using the bottom parameter we can do this just using the values already used for web_usage for the second bar charthowever for the third bar chart we must add the values used for web_usage and data_science_usage together (in this case using for list comprehensiongrouped bar charts finallygrouped bar charts are way of showing information about different sub-groups of the main categories in such casesa legend or key is usually provided to indicate what sub-group each of the shadings/colours represent the legend can be placed in the plot area or may be located below the chart for particular category separate bar charts are drawn for each of the subgroups for examplein the following chart the results obtained for two sets of teams across
19,091
series of lab exercises are displayed thus each team has bar for lab lab lab etc space is left between each category to make it easier to compare the sub categories the following program generates the grouped bar chart for the lab exercises exampleimport matplotlib pyplot as pyplot bar_width set up grouped bar charts teama_results ( teamb_results ( set up the index for each bar index_teama ( index_teamb [ bar_width for in index_teamadetermine the mid point for the ticks ticks [ bar_width for in index_teamatick_labels ('lab ''lab ''lab ''lab ''lab 'plot the bar charts pyplot bar(index_teamateama_resultsbar_widthcolor=' 'label='team 'pyplot bar(index_teambteamb_resultsbar_widthcolor=' 'label='team 'set up the graph pyplot xlabel('labs'pyplot ylabel('scores'pyplot title('scores by lab'pyplot xticks(tickstick_labelspyplot legend(display the graph pyplot show(notice in the above program that it has been necessary to calculate the index for the second team as we want the bars presented next to each other thus the index for the teams includes the width of the bar for each index pointthus the first bar is at index position the second at index position etc finally the tick positions must therefore be between the two bars and thus is calculated by taking into account the bar widths
19,092
graphing with matplotlib pyplot this program generates the following grouped bar chart figures and subplots matplotlib figure is the object that contains all the graphical elements displayed on plot that is the axesthe legendthe title as well as the line plot or bar chart itself it thus represents the overall window or page and is the topout graphical component in many cases the figure is implicit as the developer interacts with the pyplot apihowever the figure can be accessed directly if required the matplotlib pyplot figure(function generates figure object this function returns matplotlib figure figure object it is then possible to interact directly with the figure object for example it is possible to add axes to the figureto add sub plots to graph etc working directly with the figure is necessary if you want to add multiple subplots to figure this can be useful if what is required is to be able to compare different views of the same data side by side each subplot has its own axes which can coexist within the figure one or more subplots can be added to figure using the figure add_ subplot(method this method adds an axes to the figure as one of set of one or more subplots subplot can be added using -digit integer (or three separate integersdescribing the position of the subplot the digits represent the number of rowscolumns and the index of the sub plot within the resulting matrix
19,093
thus (and all indicate that the subplot will take the st index within two by two grid of plots in turn ( indicates that the sub plot will be at index which will be row and column within the by grid of plots where as (or indicates that the plot should be added as at index or the fourth subplot within the grid (so position by etc for examplethe following figure illustrates four subplots presented within single figure each subplot is added via the figure add_subplot(method
19,094
graphing with matplotlib pyplot this figure is generated by the following programimport matplotlib pyplot as pyplot range( range( - set up the grid of subplots to be by grid_size=' initialize figure figure pyplot figure(add first subplot position grid_size ' print('adding first subplot to position'positionaxis figure add_subplot(positionaxis set(title='subplot( , , )'axis plot(tsadd second subplot position grid_size ' print('adding second subplot to position'positionaxis figure add_subplot(positionaxis set(title='subplot( , , )'axis plot(ts' -'add third subplot position grid_size ' print('adding third subplot to position'positionaxis figure add_subplot(positionaxis set(title='subplot( , , )'axis plot(ts' -'add fourth subplot position grid_size ' print('adding fourth subplot to position'positionaxis figure add_subplot(positionaxis set(title='subplot( , , )'axis plot(ts' -'display the chart pyplot show(
19,095
the console output from this program is given belowadding first subplot to position adding second subplot to position adding third subplot to position adding fourth subplot to position graphs three dimensional graph is used to plot the relationships between three sets of values (instead of the two used in the examples presented so far in this in three dimensional graph as well as the and axis there is also axis the following program creates simple graph using two sets of values generated using the numpy range function these are then converted into coordinate matrices using the numpy meshgrid(function the axis values are created using the numpy sin(function the graph surface is plotted using the plot_surface(function of the futures axes object this takes the xy and coordinates the function is also given colour map to use when rendering the surface (in this case the matplotlib cool to warm colour map is usedimport matplotlib pyplot as pyplot import matplotlib colour map from matplotlib import cm as colourmap required for psd projections from mpl_toolkits mplot import axes provide access to numpy functions import numpy as np make the data to be displayed x_values np arange(- y_values np arange(- generate coordinate matrices from coordinate vectors x_valuesy_values np meshgrid(x_valuesy_valuesgenerate values as sin of plus values z_values np sin(x_values y_values
19,096
graphing with matplotlib pyplot obtain the figure object figure pyplot figure(get the axes object for the graph axes figure gca(projection=' 'plot the surface surf axes plot_surface(x_valuesy_valuesz_valuescmap=colourmap coolwarmadd color bar which maps values to colors figure colorbar(surfadd labels to the graph pyplot title(" graph"axes set_ylabel(' values'fontsize= axes set_xlabel(' values'fontsize= axes set_zlabel(' values'fontsize= display the graph pyplot show(this program generates the following graph
19,097
one point to note about three dimensional graphs is that they are not universally accepted as being good way to present data one of the maxims of data visualisation is keep it simple/keep it clean many consider that three dimensional chart does not do this and that it can be difficult to see what is really being shown or that it can be hard to interpret the data appropriately for examplein the above chart what are the values associated with any of the peaksthis is difficult to determine as it is hard to see where the peaks are relative to the xy and axis many consider such charts to be eye candypretty to look at but not providing much information as such the use of chart should be minimised and only used when actually necessary exercises the following table provides information on cities in the uk and their populations (note that london has been omitted as its population is so much larger than that of any other city and this would distort the graphcity population bristol cardiff bath liverpool glasgow edinburgh leeds reading swansea manchester , , , , , , , , , , using this data create scatter plot for the city to population data bar chart for the city to population data
19,098
graphical user interfaces introduction graphical user interface can capture the essence of an idea or situationoften avoiding the need for long passage of text such interfaces can save user from the need to learn complex commands they are less likely to intimidate computer users and can provide large amount of information quickly in form which can be easily assimilated by the user the widespread use of high quality graphical interfaces has led many computer users to expect such interfaces to any software they use most programming languages either incorporate graphical user interface (guilibrary or have third party libraries available python is of course cross platform programming language and this brings in additional complexities as the underlying operating system may provide different windowing facilities depending upon whether the program is running on unixlinuxmac os or windows operating systems in this we will first introduce what we mean by gui and by wimp based uis in particular we will then consider the range of libraries available for python before selecting one to use this will then describe how to create rich client graphical displays (desktop applicationusing one of these gui libraries thus in this we consider how windowsbuttonstext fields and labels etc are createdadded to windowspositioned and organised (cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science
19,099
graphical user interfaces guis and wimps guis (graphical user interfacesand wimp (windowsiconsmice and pop-up menusstyle interfaces have been available within computer systems for many years but they are still one of the most significant developments to have occurred these interfaces were originally developed out of desire to address many of the perceived weaknesses of purely textual interfaces the textual interface to an operating system was typified by peremptory prompt in unix/linux systems for examplethe prompt is often merely single character such as %or $which can be intimidating this is true even for experienced computer users if they are not familiar with the unix/linux family of operating systems for examplea user wishing to copy file from one directory to another might have to type something likecp file pdf ~otheruser/projdir/srcdir/newfile pdf this long sequence needs to be entered with no mistakes in order to be accepted any error in this command will cause the system to generate an error message which might or might not be enlightening even where systems attempt to be more "user friendly'through features like command historiesmuch typing of arrow keys and filenames is typically needed the main issue on both input and output is one of bandwidth for examplein situations where the relationships between large amounts of information must be describedit is much easier to assimilate this if output is displayed graphically than if it is displayed as tables of figures on inputcombinations of mouse actions can be given meaning that could otherwise only be conveyed by several lines of text wimp stands for windows (or window managers)iconsmice and pop-up menus wimp interfaces allow the user to overcome at least some of the weaknesses of their textual counterparts--it is possible to provide pictorial image of the operating system which can be based on concept the user can relate tomenus can be used instead of textual commands and information in general can be displayed graphically the fundamental concepts presented via wimp interface were originally developed at xerox' palo alto research center and used on the xerox star machinebut gained much wider acceptance through first the apple macintosh and then ibm pc implementations of wimp interfaces most wimp style environments use desktop analogy (although this is less true of mobile devices such as phones and tablets)the whole screen represents working surface ( desktop)graphic windows that can overlap represent sheets of paper on that desktop