STARTING WITH PYTHON3 – The very beginning – part 6

Journal: uffmm.org,
ISSN 2567-6458, July 20  2019 – May 12, 2020
Email: info@uffmm.org
Author: Gerd Doeben-Henisch
Email:
gerd@doeben-henisch.de

CONTEXT

This is the next step in the python3 programming project. The overall context is still the python Co-Learning project.

SUBJECT

Meanwhile I am beginning to combine elements of the python language with some applied ideas (in the last section the idea of cognitive entropy illustrated with the equalization of strings). In this section I address the idea of a simple 2-dimensional virtual world, how to represent it with python. In later sections I will use this virtual worlds for some ideas of internal representations and some kinds of learning in an artificial actor.

Remark: for a general help-information you can find a lot of helpful text directly on the python.org site: https://www.python.org/doc/.

SZENARIO

Motivation

Because we want to introduce step-wise artificial actors which can learn, show some intelligence, and can work in teams, we need a minimal virtual world to start (this virtual world is a placeholder for the real world later if applied to the real world (RW) by sensors and actors). Although there is a big difference between the real world and a virtual world a virtual world is nevertheless very helpful for introducing basic concepts. And, indeed, finally if you are applying to real world data you will not be able to do this without mathematical models which represent virtual structures. You will need lots of mappings between real and virtual and vice versa. Thus from a theoretical point of view any kind of virtual model will do, the question is only how ‘easily’ and how ‘good’ it fits.

Assumptions Virtual World (VW)

1. A 2-dimensional world as a grid together with a world clock CLCK. The clock produces periodic events which can be used to organize a timely order.

2. There is an x and y axis with the root (0,0) in the upper left corner

3. A coordinate (x,y) represents a position.

4. A position can be occupied by (i) nothing or (ii) by an object. Objects can be obstacles, energy objects (= Food), by a virtual executive actor, or even more.

5. Only one object per position is allowed.

6. It is assumed that there are four directions (headings): ‘North (N)’ as -Y, ‘East (E)’ as +X, ‘South (S)’ as +Y, and ‘West (W)’ as -X.

7. Possible movements are always only in one of the main directions from one cell to the adjacent cell. Movements will be blocked by obstacle objects or actor objects.

8. A sequence of movements realizes in the grid a path from one position to the next.

9. The size of the assumed grids is always finite. In a strict finite world the border of the grid blocks a movement. In a finite-infinite world the borders of the grid are connected in a way that the positions in the south lead to the position in the north and the positions in the east lead to the positions in the west, and vice versa. Therefor can a path in an finite-infinite world become infinite.

10. A grid G with its objects O will be configured at the beginning of an experiment. Without the artificial actors all objects are in a static world assumed to be permanent. In a dynamic world there can be a world function f_w inducing changes depending from the world clock.

11. During an experiment possible changes in the world can happen through a world function f_w, if such a function has been defined. The other possible source for changes are artificial actors, which can act and which can ‘die’.

Remark: The basic idea of this kind of a virtual world I have got from a paper from S.W.Wilson from 1994 entitled ZCS: a zeroth level classifier system published in the Journal Evolutionary Computation vol. 2 number 1 pages 1-18. I have used this concept the first time in a lecture in 2012 (URL: https://www.doeben-henisch.de/fh/gbblt/node95.html). Although this concept looks at a first glance very simple, perhaps too simple, it is very powerful and allows very far reaching experiments (perhaps I can show some aspects from this in upcoming posts :-)).

ACTOR STORY
1. There is a human executive actor as a user who uses a program as an assisting actor by an interface with inputs and outputs.

2. The program tries to construct a 2D-virtual world in the format of a grid. The program needs the size of the grid as (m,n) = (number of columns, number of rows), which is here assumed by default as equal m=n. After the input the program will show the grid on screen.

3. Then the program will ask for the percentage of obstacles ‘O’ and energy objects (= food) ‘F’ in the world. Randomly the grid will be filled according to these values.

4. Then a finite number of virtual actors will be randomly inserted too. In the first version only one.

POSSIBLE EXTENSIONS

In upcoming versions the following options should be added:

1. Allow multiple objects with free selectable strings for encoding.

2. Allow multiple actors.

4. Transfer the whole world specification into an object specification. This allows the usage of different worlds in one program.

IMPLEMENTATION

vw1b.py

And with separation of support functions in an import module:

vw1c.py

gridHelper.py(The import module)

EXERCISES

m=int(input(‘Number of columns (= equal to rows!) of 2D-grid ?’))

The input() command generates as output a string object. If one wants to use as output numbers for follow-up computations one has to convert the string object into an integer object, which can be done with the int() operator.

mx=nmlist(n)

Is the call of the nmlist() function which has been defined before the main source code (see. above)(in another version all these supporting functions will again be stored as an extra import module:

printMX(mx,n)

This self-defined function assumes the existence of a matrix object mx with n=m many columns and rows. One row in the matrix can be addressed with the first index of mx like mx[i]. The ‘i’ gives the number of the row from ‘above’ starting with zero. Thus if the matrix has n-many rows then we have [0,…,n-1] as index numbers. The rows correspond to the y-axis.

mx = [[‘_’ for y in range(n)] for x in range(n)]

This expression is an example of a general programming pattern in python called list comprehension (see for example chapters 14 and 22 of the mentioned book of Mark Lutz in part 1 of this series). List comprehension has the basic idea to apply an arbitrary python expression onto an iteration like y in range(n). In the case of a numeric value n=5 the series goes from 0 to 4. Thus y takes the values from 0 to 4. In the above case we have two iterations, one for y (representing the rows) and one vor x (representing the columns). Thus this construct generates (y,x) pairs of numbers which represent virtual positions and each position is associated with a string value ‘_’. And because these instructions are enclosed in []-brackets will the result be a set of lists embedded in a list. And as you can see, it works 🙂 But I must confess that from the general idea of list comprehension to this special application is no direct way. I got this idea from the stack overflow web site (https://stackoverflow.com/questions) which offers lots of discussions around this topic.

for i in range(no):

x=rnd.randrange(n)

y=rnd.randrange(n)

mx[x][y]=obj

A simple for-loop to generate random pairs of (x,y) coordinates to place the different objects into the 2D-grid realized as a matrix object mx.

Demo

PS C:\Users\gdh\code> python vw1.py

Number of columns (= equal to rows!) of 2D-grid ?5

[‘_’, ‘_’, ‘_’, ‘_’, ‘_’]

[‘_’, ‘_’, ‘_’, ‘_’, ‘_’]

[‘_’, ‘_’, ‘_’, ‘_’, ‘_’]

[‘_’, ‘_’, ‘_’, ‘_’, ‘_’]

[‘_’, ‘_’, ‘_’, ‘_’, ‘_’]

Percentage (as integer) of obstacles in the 2D-grid?45

Number of objects :

11

Position :

3 2

Position :

2 3

Position :

3 2

Position :

3 2

Position :

0 1

Position :

2 2

Position :

0 1

Position :

4 3

Position :

0 2

Position :

3 1

Position :

1 4

New Matrix :

[‘_’, ‘O’, ‘O’, ‘_’, ‘_’]

[‘_’, ‘_’, ‘_’, ‘_’, ‘O’]

[‘_’, ‘_’, ‘O’, ‘O’, ‘_’]

[‘_’, ‘O’, ‘O’, ‘_’, ‘_’]

[‘_’, ‘_’, ‘_’, ‘O’, ‘_’]

Percentage (as integer) of Energy Objects (= Food) in the 2D-grid ?15

Number of objects :

3

Position :

3 4

Position :

0 4

Position :

4 1

New Matrix :

[‘_’, ‘O’, ‘O’, ‘_’, ‘F’]

[‘_’, ‘_’, ‘_’, ‘_’, ‘O’]

[‘_’, ‘_’, ‘O’, ‘O’, ‘_’]

[‘_’, ‘O’, ‘O’, ‘_’, ‘F’]

[‘_’, ‘F’, ‘_’, ‘O’, ‘_’]

Default random placement of one virtual actor

Position :

2 2

New Matrix :

[‘_’, ‘O’, ‘O’, ‘_’, ‘F’]

[‘_’, ‘_’, ‘_’, ‘_’, ‘O’]

[‘_’, ‘_’, ‘A’, ‘O’, ‘_’]

[‘_’, ‘O’, ‘O’, ‘_’, ‘F’]

[‘_’, ‘F’, ‘_’, ‘O’, ‘_’]

STARTING WITH PYTHON3 – The very beginning – part 4

Journal: uffmm.org,
ISSN 2567-6458, July 15, 2019 – May 9, 2020
Email: info@uffmm.org
Author: Gerd Doeben-Henisch
Email:
gerd@doeben-henisch.de

Change: July 16, 2019 (Some re-arrangement of the content :-))

CONTEXT

This is the next step in the python3 programming project. The overall context is still the python Co-Learning project.

SUBJECT

After a first clearing of the environment for python programming we have started with the structure of the python programming language, and in this section will deal with the object type string(s).

Remark: the following information about strings you can get directly from the python manuals, which you can find associated with the entry for python 3.7.3 if you press the Windows-Button, look to the list of Apps (= programs), and identify the entry for python 3.7.3. If you open the python entry by clicking you see the sub-entry python 3.7.3 Manuals. If you click on this sub-entry the python documentation will open. In this documentation you can find nearly everything you will need. For Beginners you even find a nice tutorial.

TOPIC: VALUES (OBJECTS) AS STRINGS

PROBLEM(s)

(1) When I see a single word (a string of symbols) I do not know which type this is in python. (2) If I have a statement with many words I would like to get from this a partition into all the single words for further processing.

VISION OF A SOLUTION

There is a simple software actor which can receive as input either single words or multiple words and which can respond by giving either the type of the received word or the list of the received multiple words.

ACTOR STORY (AS)

We assume a human user as executing actor (eA) and a piece of running software as an assisting actor (aA). For these both we assume the following sequence of states:

1. The user will start the program by calling python and the name of the program.
2. The program offers the user two options: single word or multiple words.
3. The user has to select one of these options.
4. After the selection the user can enter accordingly either one  or multiple words.
5. The program will respond either with the recognized type in python or with a list of words.
6. Finally asks the program the user whether he/she will continue or stop.
7. Depending from the answer of the user the program will continue or stop.

IMPLEMENTATION

# File stringDemo1.py
# Author: G.Doeben-Henisch
# First date: July 15, 2019

##################
# Function definition sword()

def sword(w1):
w=str(w1)
if w.islower():
print(‘Is lower\n’)
elif w.isalpha() :
print(‘Is alpha\n’)
elif w.isdecimal():
print(‘Is decimal\n’)
elif w.isascii():
print(‘Is ascii\n’)
else : print(‘Is not lower, alpha, decimal, ascii\n’)

##########################
# Main Programm

###############
# Start main loop

loop=’Y’
while loop==’Y’:

###################

opt=input(‘Single word =1 or multiple words =2\n’)

if opt==’1′:
w1=input(‘Input a single word\n’)
sword(w1) # Call for new function defined above

elif opt==’2′:
w1=input(‘Input multiple words\n’)
w2=w1.split() # Call for built-in method of class str
print(w2)

loop=input(‘To stop enter N or Y otherwise\n’) # Check whether loop shall be repeated

DEMO

Here it is assumed that the code of the python program is stored in the folder ‘code’ in my home director.

I am starting the windows power shell (PS) by clicking on the icon. Then I enter the command ‘cd code’ to enter the folder code. Then I call the python interpreter together with the demo programm ‘stringDemo1.py’:

PS C:\Users\gerd_2\code> python stringDemo1.py
Single word =1 or multiple words =2

Then I select first option ‘Single word’ with entering 1:

1
Input a single word
Is alpha

To stop enter N

After entering 1 the program asks me to enter a single word.

I am entering the fantasy word ‘Abrakadabra’.

Then the program responds with the classification ‘Is alpha’, what is correct. If I want to stop I have to enter ‘N’ otherwise it contiues.

I want o try another word, therefore I am entering ‘Y’:

Y
Single word =1 or multiple words =2

I select again ‘1’ and the new menue appears:

1
Input a single word
29282726
Is decimal

To stop enter N

I entered a sequence of digits which has been classified as ‘decimal’.

I want to contiue with ‘Y’ and entering ‘2’:

Y
Single word =1 or multiple words =2
2
Input multiple words
Hans kommt meistens zu spät
[‘Hans’, ‘kommt’, ‘meistens’, ‘zu’, ‘spät’]
To stop enter N

I have entered a German sentence with 5 words. The response of the system is to identify every single word and generate a list of the individual words.

Thus, so far, the test works fine.

Before the main program a new function ‘sword()’ has been defined:

def sword(w1):

The python keyword ‘def‘ indicates that here the definition of a function  takes place, ‘sword‘ is the name of this new function, and ‘w1‘ is the input argument for this function. ‘w1’ as such is the name of a variable pointing to some memory place and the value of this variable at this place will depend from the context.

w=str(w1)

The input variable w1 is taken by the operator str and str translates the input value into a python object of type ‘string’. Thus the further operations with the object string can assume that it is a string and therefore one can apply alle the operations to the object which can be applied to strings.

if w.islower():

One of these string-specific operations is islower(). Attached to the string object ‘w’ by a dot-operator ‘.’ the operation ‘islower() will check, whether the string object ‘w’ contains lower case symbols. If yes then the following ‘print()’ operation will send this message to the output, otherwise the program continues with the next ‘elif‘ statement.

The ‘if‘ (and following the if the ‘elif‘) keyword states a condition (whether ‘w’ is of type ‘lower case symbols’). The statement closes with the ‘:’ sign. This statement can be ‘true’ or not. If it is true then the part after the ‘:’ sign will be executed (the ‘print()’ action), if false then the next condition ‘elif … :’ will be checked.

If no condition would be true then the ‘else: …’ statement would be executed.

The main program is organized as a loop which can iterate as long as the user does not stop it. This entails that the user can enter as many words or multi-words as he/ she wants.

loop=’Y’
while loop==’Y’:

In the first line the variable ‘loop’ receives as a value the string ‘Y’ (short for ‘yes’). In the next line starts the loop with the python key-word ‘while’ forming a condition statement ‘while … :’. This is similar to the condition statements above with ‘if …. :’ and ‘elif … :’.

The condition depends on the expression ‘loop == ‘Y” which means that  as long as the variable loop is logically equal == to the value ‘Y’ the loop condition  is ‘true’ and the part after the ‘:’ sign will be executed. Thus if one wants to break this loop one has to change the value of the variable ‘loop’ before the while-statement ‘while … :’ will be checked again. This check is done in the last line of the while-execution part with the input command:

loop=input(‘To stop enter N\n’)

Before the while-condition will be checked again there is this input() operator asking the user to enter a ‘N’ if he/ she wantds to stop. If the user  enters a  ‘N’  in the input line the result of his input will be stored in the variable called ‘loop’ and therefore the variable will have the value ‘==’N” which is different from ‘==’Y”. But what would happen if the user enters something different from ‘N’ and ‘Y’, because ‘Y’ is expected for repetition?

Because the user does not know that he/she has to enter ‘Y’ to continue the program will highly probably stop even if the user does not want to stop. To avoid this unwanted case one should change the code for the while-condition as follows:

while loop!=’N’:

This states that the loop will be true as long as the value of the loop variable is different != from the value ‘N’ which will explicitly asked from the user at the end of the loop.

The main part of the while-loop distinguishes two cases: single word or multiple words. This is realized by a new input() operation:

opt=input(‘Single word =1 or multiple words =2\n’)

The user can enter a ‘1’ or a ‘2’, which will be stored in the variable ‘opt’. Then a construction with an if or an elif will test which one of these both happens. Depending from the option 1 or 2 ther program asks the user again with an input() operation for the specific input (one word or multiple words).

sword(w1)

In the case of the one word input in the variable ‘w1’ w1 contains as value a string input which will be delivered as input argument to the new function ‘sword()’ (explanation see above). In case of input 2 the

w2=w1.split()

‘split()’ operation will be applied to the object ‘w1’ by the dot operator ‘.’. This operation will take every word separated by a ‘blank’ and generates a list ‘[ … ]’ with the individual words as elements.

A next possible continuation you can find HERE.

Example python3: pop0 – simple population program

eJournal: uffmm.org,
ISSN 2567-6458, 2-3.April 2019
Email: info@uffmm.org
Author: Gerd Doeben-Henisch
Email: gerd@doeben-henisch.de

CONTEXT

This is a possible 2nd step in the overall topic ‘Co-Learning python3′. After downloading WinPython and activating the integrated editor ‘spyder’ (see here),  one can edit a first simple program dealing with population dynamics in a most simple way (see the source code below under the title ‘EXAMPLE: pop0.py’.

BASIC PROGRAMMING ELEMENTS

SOURCE FILE

The source code is stored under the name ‘pop0.py’. It is a ‘stand alone’ program not making use of any kind of a library except the built in functions of python3. The external libraries can be included by the ‘import command’.

FUNCTION DEFINITION

If one wants to use the built-in functions in some new way one can do this by telling the computer the keyword ‘def‘ which states that the following text defines a new function.

A function has always a name, some input arguments between rounded brackets followed by a colon marking the beginning of the function-body.  After the colon follows a list of built-in commands or some already defined functions. With defined functions one can make life much easier. Instead of repeating all the commands of the function-body again and again one can limit the writing to the call of the function name with its input arguments.

In the example file we have the following function definition:

def pop0(p,br,dr):
p=p+(p*br)-(p*dr)
return p

The name is pop0, the input arguments are (p,br,dr), the used built-in functions are +, -, *, return as well as the =-sign, and the new composition is p=p+(p*br)-(p*dr). This new composition combines known function names with new variable names to compute a certain mathematical mapping. The result of this simple mapping is stored in the variable ‘p’ and it is delivered to the outside of the function pop0 by the return-statement.

NECESSARY INPUT VALUES

To run the program one has to call the defined new function. But because the called function will need some values for the input variables one has first to enable the user to interact with the program by some input commands.

The input commands are informing the user which kind of information is asked for and the answers of the users will be stored in the variables p, br, and dr. The input values can also be ‘casted‘ into different value types like int — for integer — and float — for floating point –.

Here is the protocol of a possible input:

Number of citizens in the start year? 1000

Birthrate %? 0.82

Deathrate in %? 0.92

CALLING A DEFINED FUNCTION

After these preparations one can call the defined new function with the statement pnew = pop0(p,br,dr). Because the input variables have values received from the user the new function can start it’s mapping and can compute the follow up value for the population.

SHOW RESULTS

To show the user this new value explicitly on the screen  one has to use the print function, the counterpart to the input function:  print(‘New population number:\n’,int(pnew)). The print function prints the new value for the population number on the screen.  If you look closer to the print function you can detect some inherent structure: print() is the main structure with the function name ‘print’ and the brackets () as the placeholder for possible input arguments. In the used example the input arguments have two ‘parts’: (‘…’,v). The ‘…’-part allows some text which will be shown to the user, in our case New population number: followed by a line break caused by the symbols \n. The v-part allows the names of variables which have some values which can be printed. In the used example we have the expression int(pnew). pnew is the name of a variable with a value delivered by the pop0() function enabled by the return p function of the pop0() function. (Attention: the ‘return’ function works without ()-brackets to receive input arguments! The variable ‘p’ is an input argument) The value delivered by ‘return p’ is a floating point value. But because we have only ‘whole citizens’ we cast the non-integer parts of the float value away by making the variable ‘pnew’ an argument of another function int(). The int() function translates a floating point value into an integer value. This is the reason that we do not see ‘999.0’ but ‘999’:

New population number:
999

REMARK: Global and Local Variables

This simple example tells already something about the difference between global and local values. If one enters the variable names ‘p’ and ‘pnew’ in the python console of the spyder editor then one can see the following:

p
Out[5]: 1000

pnew
Out[6]: 999.0

After the function call to pop0() the original value of ‘p’ is unchanged, and the new value ‘pnew’ is different. That means the new value of ‘p internal in the function’ and the ‘old value of p external to the function’ are separated. The name of a variable has therefore to be distinguished with regard to the actual context: The same name  in different contexts (inside a function definition or outside) does represents different memory spaces.   The variable names inside a function definition are called local variables and the variable names external to a function definition are called global variables.

A continuation of this post you can find here.

SOURCE CODE: EXAMPLE: pop0.py

pop0.py as pop0.pdf