Browse Source

Almost working commit

Yann Weber 6 years ago
parent
commit
4e74e8909c
6 changed files with 71 additions and 16 deletions
  1. 14
    2
      gte/__main__.py
  2. 3
    3
      gte/turmit.py
  3. 9
    2
      gte/world.py
  4. 15
    3
      libs/cturmit.c
  5. 26
    6
      libs/turmit.c
  6. 4
    0
      libs/turmit.h

+ 14
- 2
gte/__main__.py View File

@@ -16,12 +16,16 @@ logger = logging.getLogger()
16 16
 logger.debug('Logger started')
17 17
 
18 18
 from . import turmit, rpnlib
19
-from .turmit import Turmit
19
+#from .turmit import Turmit
20
+from cturmit import CTurmit as Turmit
20 21
 from .world import World, LivingTurmit, eval_prog
21 22
 from .mutator import mutate
22 23
 
23 24
 parser = argparse.ArgumentParser(description='Genetic Turmit Evolver')
24 25
 
26
+parser.add_argument('-L', '--list-op', action="store_const", default=False,
27
+                    const=True, help="List operations and exit")
28
+
25 29
 subparsers = parser.add_subparsers(help='sub-commands help')
26 30
 
27 31
 parser_evolve = subparsers.add_parser('evolve', help='evolving help')
@@ -112,7 +116,15 @@ parser_gen.add_argument('--threads', '-t', type=int, metavar='N',
112 116
 
113 117
 args = parser.parse_args()
114 118
 
115
-if 'pool_size' in args:
119
+if args.list_op:
120
+    from . import rpnlib
121
+    print("Operations list & aliases :")
122
+    for i, opname in enumerate(rpnlib._op_list):
123
+        alias = rpnlib._op_alias[opname] if opname in rpnlib._op_alias else ""
124
+        print("\t%02X: %8s\t%s" % (i, opname, alias))
125
+    exit(0)
126
+
127
+elif 'pool_size' in args:
116 128
     # Evolver
117 129
     if args.prog is None:
118 130
         prog = rpnlib.RpnExpr.random(args.prog_size)

+ 3
- 3
gte/turmit.py View File

@@ -424,11 +424,11 @@ class Turmit(object):
424 424
             Condition type is encoded on an int : 
425 425
             - 0b0000 : je
426 426
             - 0b0001 : jne
427
-            - 0b0010 : jle
428
-            - 0b0011 : jl
427
+            - 0b0010 : jl
428
+            - 0b0011 : jle
429 429
             - 0b0100 : jg
430 430
             - 0b0101 : jge
431
-            - 0b0110 : jne
431
+            - 0b0110 : jmp
432 432
             - 0b0111 : jmp
433 433
 
434 434
             @param a int : operand

+ 9
- 2
gte/world.py View File

@@ -12,7 +12,8 @@ import time
12 12
 import numpy as np
13 13
 from random import randint
14 14
 
15
-from .turmit import Turmit
15
+#from .turmit import Turmit
16
+from cturmit import CTurmit as Turmit
16 17
 
17 18
 logger = logging.getLogger()
18 19
 
@@ -169,6 +170,8 @@ class LivingTurmit(Turmit):
169 170
     ''' @brief Represent a Turmit with coordinates in a world '''
170 171
 
171 172
     def __init__(self, world, color = None, x=None, y=None, diag=True, **kwargs):
173
+        if 'prog' in kwargs:
174
+            kwargs['prog'] = str(kwargs['prog']).lower()
172 175
         super().__init__(**kwargs)
173 176
         
174 177
         if not isinstance(world, World):
@@ -228,6 +231,7 @@ class LivingTurmit(Turmit):
228 231
             r = g = b = self._world[self._y][self._x]
229 232
         else:
230 233
             r,g,b = self._world[self._y][self._x]
234
+        r = int(r); g=int(g); b=int(b)
231 235
         tdir = super().__call__(x=self._x, y=self._y, r=r, g=g, b=b)
232 236
         self.move(tdir)
233 237
 
@@ -253,7 +257,10 @@ class LivingTurmit(Turmit):
253 257
         ''' @brief Process a determinit score : determinist_expr / total expr
254 258
             @return float in [0.0..1.0]
255 259
         '''
256
-        return (self._determin_score + 1) / self._steps
260
+        try:
261
+            return (self._determin_score + 1) / self._steps
262
+        except AttributeError:
263
+            return 1
257 264
 
258 265
     def dirvar(self):
259 266
         ''' @brief Process @ref _dirvar to return a direction variation

+ 15
- 3
libs/cturmit.c View File

@@ -102,11 +102,11 @@ but %ld found", sz);
102 102
 	PyMapping_DelItemString(kwds, "prog");
103 103
 	if(expr)
104 104
 	{
105
-		if(!PyUnicode_Check(expr))
105
+		if(!PyUnicode_Check(expr) && !(expr = PyObject_Str(expr)))
106 106
 		{
107 107
 			PyErr_Restore(errtype, errvalue, errbck);
108 108
 			PyErr_SetString(PyExc_TypeError,
109
-				"prog expected to be a string");
109
+				"prog expected to be a string !");
110 110
 			return -1;
111 111
 		}
112 112
 		expr = PyUnicode_AsASCIIString(expr);
@@ -155,8 +155,11 @@ but %ld found", sz);
155 155
 		TURMIT_AUTOCOMP);
156 156
 	if(self->turmit->err)
157 157
 	{
158
+		snprintf(err_msg, 128,
159
+			"Unable to compile '%s' err : %s", arg_expr,
160
+			self->turmit->err_str);
158 161
 		PyErr_SetString(PyExc_ValueError,
159
-			"Unable to compile given prog");
162
+			err_msg);
160 163
 		return -1;
161 164
 	}
162 165
 	return 0;
@@ -208,6 +211,15 @@ PyObject* CTurmit_call(PyObject *func, PyObject *args, PyObject *kwds)
208 211
 			Py_RETURN_NONE;
209 212
 		}
210 213
 		exec_args[i] = PyLong_AsUnsignedLongLong(arg);
214
+		if(PyErr_Occurred())
215
+		{
216
+			PyErr_Restore(errtype, errvalue, errbck);
217
+			snprintf(err_msg, 64, "An integer is required for %s",
218
+				argsname[i]);
219
+			PyErr_SetString(PyExc_TypeError,
220
+				err_msg);
221
+			Py_RETURN_NONE;
222
+		}
211 223
 	}
212 224
 
213 225
 	res = turmit_exec(self->turmit, exec_args);

+ 26
- 6
libs/turmit.c View File

@@ -156,6 +156,7 @@ turmit_t *turmit_init(turmit_t *turmit, ssize_t stack_sz, ssize_t int_max,
156 156
 	turmit->stack_cur = turmit->stack_sz - 1;
157 157
 	turmit->stack = malloc(sizeof(turmit_int) * turmit->stack_sz);
158 158
 	turmit->err = 0;
159
+	turmit->err_str = NULL;
159 160
 
160 161
 	if(!turmit->stack)
161 162
 	{
@@ -173,6 +174,7 @@ turmit_t *turmit_init(turmit_t *turmit, ssize_t stack_sz, ssize_t int_max,
173 174
 
174 175
 void turmit_clean(turmit_t *turmit)
175 176
 {
177
+	if(turmit->err_str) { free(turmit->err_str); }
176 178
 	if(turmit->expr) { free(turmit->expr); }
177 179
 	if(turmit->op_expr) { free(turmit->op_expr); }
178 180
 
@@ -247,7 +249,7 @@ int turmit_compile(turmit_t *turmit)
247 249
 				perror("Unable to allocate memory");
248 250
 				goto turmit_compile_err;
249 251
 			}
250
-			bzero(&(pret[opcur - 1]),
252
+			bzero(pret + opcur - 1,
251 253
 				64 * sizeof(turmit_op_t));
252 254
 			turmit->op_expr = pret;
253 255
 		}
@@ -279,7 +281,7 @@ int turmit_compile(turmit_t *turmit)
279 281
 			cur+= 2;
280 282
 			iret = strtol(cur, &endptr, 16);
281 283
 			err = errno;
282
-			if(err)
284
+			if(err || endptr == cur)
283 285
 			{
284 286
 				fprintf(stderr, "Invalid constant %s : %s\n",
285 287
 					cur-2, strerror(err));
@@ -313,10 +315,19 @@ int turmit_compile(turmit_t *turmit)
313 315
 		isym = tsym;
314 316
 		while(isym->str != NULL)
315 317
 		{
316
-			if((strncasecmp(isym->str, cur, strlen(isym->str)) == 0) ||
317
-				(isym->alias && strncmp(cur, isym->alias,3) == 0))
318
+			endptr = cur;
319
+			if(strncasecmp(isym->str, cur, strlen(isym->str)) == 0)
320
+			{
321
+				endptr = cur+strlen(isym->str);
322
+			}
323
+			else if(isym->alias && strncmp(cur, isym->alias,
324
+					strlen(isym->alias)) == 0)
318 325
 			{
319
-				cur += strlen(isym->str);
326
+				endptr = cur+strlen(isym->alias);
327
+			}
328
+			if(cur != endptr)
329
+			{
330
+				cur = endptr;
320 331
 				turmit->op_expr[opcur].op.op = isym->op_fun;
321 332
 				turmit->op_expr[opcur].value = TURMIT_SYM_OP;
322 333
 				opcur++;
@@ -330,7 +341,16 @@ int turmit_compile(turmit_t *turmit)
330 341
 		}
331 342
 		//unrecognized symbol :'(
332 343
 		turmit->err = 1;
333
-		cur++;
344
+		if(turmit->err_str) { free(turmit->err_str); }
345
+		turmit->err_str = malloc(sizeof(char) * 256);
346
+		if(!turmit->err_str)
347
+		{
348
+			perror("Unable to allocate memory for error string");
349
+			return -1;
350
+		}
351
+		snprintf(turmit->err_str, 256,
352
+			"Error compiling prog starting at : '%s'", cur);
353
+		goto turmit_compile_err;
334 354
 	}
335 355
 	if(!opcur)
336 356
 	{	//empty expression

+ 4
- 0
libs/turmit.h View File

@@ -97,7 +97,11 @@ struct turmit_s
97 97
 	turmit_int *stack;
98 98
 	ssize_t stack_cur;
99 99
 
100
+	/**@brief 0 if no error
101
+	 * @note only for compilation error for the moment
102
+	 */
100 103
 	char err;
104
+	char *err_str;
101 105
 };
102 106
 
103 107
 inline static turmit_int __SPOP(turmit_t *t) {

Loading…
Cancel
Save