MilesCranmer commited on
Commit
47712b5
1 Parent(s): d1327f1

Function to combine redundant constants for plus, multiply

Browse files
Files changed (1) hide show
  1. eureqa.jl +33 -0
eureqa.jl CHANGED
@@ -433,6 +433,38 @@ function deleteRandomOp(tree::Node)::Node
433
  return tree
434
  end
435
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
436
 
437
  # Simplify tree
438
  function simplifyTree(tree::Node)::Node
@@ -484,6 +516,7 @@ function iterate(
484
  tree = deleteRandomOp(tree)
485
  elseif mutationChoice < cweights[6]
486
  tree = simplifyTree(tree) # Sometimes we simplify tree
 
487
  return tree
488
  elseif mutationChoice < cweights[7]
489
  tree = genRandomTree(5) # Sometimes we simplify tree
 
433
  return tree
434
  end
435
 
436
+ # Simplify tree
437
+ function combineOperators(tree::Node)::Node
438
+ # (const (+*) const) already accounted for
439
+ # ((const + var) + const) => (const + var)
440
+ # ((const * var) * const) => (const * var)
441
+ # (anything commutative!)
442
+ if tree.degree == 2 && (tree.op == plus || tree.op == mult)
443
+ op = tree.op
444
+ if tree.l.constant || tree.r.constant
445
+ # Put the constant in r
446
+ if tree.l.constant
447
+ tmp = tree.r
448
+ tree.r = tree.l
449
+ tree.l = tmp
450
+ end
451
+ topconstant = tree.r.val
452
+ # Simplify down first
453
+ tree.l = combineOperators(tree.l)
454
+ below = tree.l
455
+ if below.degree == 2 && below.op == op
456
+ if below.l.constant
457
+ tree = below
458
+ tree.l.val = op(tree.l.val, topconstant)
459
+ elseif below.r.constant
460
+ tree = below
461
+ tree.r.val = op(tree.r.val, topconstant)
462
+ end
463
+ end
464
+ end
465
+ end
466
+ return tree
467
+ end
468
 
469
  # Simplify tree
470
  function simplifyTree(tree::Node)::Node
 
516
  tree = deleteRandomOp(tree)
517
  elseif mutationChoice < cweights[6]
518
  tree = simplifyTree(tree) # Sometimes we simplify tree
519
+ tree = combineOperators(tree) # See if repeated constants at outer levels
520
  return tree
521
  elseif mutationChoice < cweights[7]
522
  tree = genRandomTree(5) # Sometimes we simplify tree