Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <html ng-app="codepen">
  <head>
    <meta charset="utf-8">
    <title>Evolutionary Algorithm example in JS</title>

    <script
  src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>
    
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css"
   integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ=="
   crossorigin=""/>
    
    <script src="https://use.fontawesome.com/2e402fe4f3.js"></script>
    
    <link rel="stylesheet" href="https://unpkg.com/tachyons@4.8.1/css/tachyons.min.css"/>   
  
    <link href="https://fonts.googleapis.com/css?family=Rubik" rel="stylesheet">
    
    <script data-semver="1.5.9" src="http://code.angularjs.org/1.5.9/angular.js" data-require="angular.js@1.5.x">
    </script>
    
    <script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"
   integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log=="
   crossorigin=""></script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angularjs-slider/6.4.0/rzslider.min.js"></script>

    <link href="https://cdnjs.cloudflare.com/ajax/libs/angularjs-slider/6.4.0/rzslider.min.css"
            rel="stylesheet">
 
    
    
    <script src='https://npmcdn.com/@turf/turf/turf.min.js'></script>   
    


  </head>

  <body  ng-controller="MainCtrl as vm">
    <div class="col-xs-12 col-md-8">
      <div id="mapid"></div>
    </div>
    
     <div class="col-xs-12 col-md-4 info-panel center tc mv3">
        <div class="mv4 f3 tracked black">Evolutionary Algorithm example in JS</div>
        <div class="pb3">generation: {{vm.generationNumber}}</div>
        <div class="pb3">number of geometries: {{vm.numberOfGeometries}}</div>
        <div class="pb3">speed: {{vm.speed}}</div>
       
        <div class="pv3 ph2 dark-gray">This is an example of an evolutionary algorithm. The goal is to randomly generate a number of shapes, and "evolve" them at each generation, selecting the top most fit to reproduce, along with some random variance. Eventually, you should end up with some shape that roughly approximates the objective shape in the background (the black hexagon). This algorithm doesnt generate the most optimal shape, but tries to approximate it.</div>
       
        <div class="pb3 w4 center">
          
          
          <!--
          <div class="radio tl">
            <label><input type="radio"
               ng-model="vm.speed"
               name="radioSpeed"
               
               ng-value="1000"> Slow</label>
          </div>
          <div class="radio tl">
            <label><input type="radio"
               ng-model="vm.speed"
               name="radioSpeed"
               
               ng-value="500"> Medium</label>
          </div>
          <div class="radio tl">
            <label><input type="radio"
               ng-model="vm.speed"
               name="radioSpeed"
               
               ng-value="100"> Fast</label>
          </div>
          -->
          
         
          
       </div>
       <!--
        <button ng-click="vm.reset()" class="pv3 ph4 mt4 mb2 box-shadow-4 ttu tracked fw3 pointer bg-green ">New Values</button>
        -->
     </div>
     

  <!-- load the d3.js library -->
  <script src="http://d3js.org/d3.v3.min.js"></script>	
  
  </body>
</html>
              
            
!

CSS

              
                body {
    font-family: 'Rubik', sans-serif;
    
} 

#mapid { 
  background-color: black;
  height: 100vh;
  width: 65vw;
  left: 0vw;
  z-index: -9999;
}

.info-panel {
  z-index: 9999999999999;
  background-color: white;
  width: 35vw;
  height: 100vh;
  right: 0vw;
  position: absolute;
  bottom: 5px;
  
}

@media only screen and (max-width: 991px) {
  #mapid {
    width: 100vw;
    height: 70vh;
  }
  
  .info-panel {
    width: 100vw;
    height: 30vh;
  }
}
              
            
!

JS

              
                
var app = angular.module('codepen', []);
 
app.controller('MainCtrl', function( $interval, $window, $q ) {
  var vm = this;
  
  vm.isSmallDisplay = ($window.innerWidth < 991);
  
  var centerLatLng = [37.75, -122.45];
  
  //alert("isSmallDisplay???  "+vm.isSmallDisplay);
  
  var zoomLevel = vm.isSmallDisplay ? 11 : 12
  
  var mymap = L.map('mapid', { zoomControl: false }).setView(centerLatLng, zoomLevel);
  
  var allGeometries = [];   
  var addToAllGeometries = [];
  
  //var allGeometriesDifferences = [];
  //var allGeometriesDfferencesAreas = [];
  vm.generationNumber = 0; 
  vm.stepTimer = 200;
  vm.numberOfGeometries = 0;
  vm.speed = 400;
  vm.numberOfGenerations = 300;
  //var leafValues = [];  
  
  var hitReset = false;
  vm.reset = reset;
  
  var numberOfGeometries = 40;
  var randomRemovalPercentagePerGen = 30;
  var weakestPercentageRemovedPerGen = 40;
      
  var randomPointNumberMutationThreshold = 30;  
  var randomPointNumberNewMutationThreshold = 30;
  
  var evolutionTimer = "";
  
  //first value is the random value, the rest is the percent to the geometry in that index
  var reproductionGradient = [40, 35, 12, 6, 4, 3]
   
  function init() {
    
    //reset some values
    allGeometries = [];
    vm.generationNumber = 0;
    
    //disable dragging for the map
    mymap.dragging.disable();
    mymap.touchZoom.disable();
    mymap.doubleClickZoom.disable();
    mymap.scrollWheelZoom.disable();
    mymap.boxZoom.disable();
    mymap.keyboard.disable();
    
    //draw the satellite tile layer
    L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
        attribution: 'Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community',
        maxZoom: 18,
    }).addTo(mymap);
    
    //draw the geometryToCover
    L.geoJSON(geometryToCover, { style: affectedAreaStyling }).addTo(mymap);
    
    //draw centroid as dot
    //L.circle(vm.sourceSignalCoordinates,  sourceSignalStyling ).addTo(mymap);
    
    //initialize with basic geometries
    createInitialGeometries();
    
    //draw to 
    
    evolutionDriver();
    
  }
   
  function incrementGenerationNumber() {
    vm.generationNumber = vm.generationNumber+1;
  }
  
  function computeDifferences() {
    //console.log("computing differences");
    //loop through the number of geometries, and check the difference of each with the starting geometry
    //console.log(geometryToCover);
    for ( var i = 0; i < allGeometries.length; i++) {
      //console.log(allGeometries[i]);
      var difference = turf.difference(allGeometries[i], geometryToCover);
      if (difference === undefined) {
        allGeometries.splice(i, 1)
        return;
      }
      allGeometries[i].difference = difference;
      allGeometries[i].area = turf.area(difference);
    } 
  }  
    
  
  function createInitialGeometries() {
    //loop through the number of geometries, and create new ones
    for ( var i = 0; i < numberOfGeometries; i++) {
      allGeometries.push(createNewGeometry(true));
    }
  }
    
  //this function creates a single geometry, and returns it
  function createNewGeometry(isInit, numberToCreate) {
     //console.log("-------------");
    if (isInit) { 
      //create weird random geometry, and return it
      var newGeo = {};
      //generate new random number of points
      var numOfPoints = getRandomInt(4, 10);
      
      var newGeoPoints = [];
      var firstPoint = []; 
        
      for (var i = 0; i < numOfPoints; i++) {
        var tempXMod = getRandomInt(-1000, 1000);
        var tempStartingX = centerLatLng[0] * 10000;
        tempStartingX = tempStartingX + tempXMod;
        tempStartingX = tempStartingX / 10000;
        var tempYMod = getRandomInt(-1000, 1000);
        var tempStartingY = centerLatLng[1] * 10000;
        tempStartingY = tempStartingY + tempYMod;
        tempStartingY = tempStartingY / 10000;
        
        var newPolygonPoint = [tempStartingY, tempStartingX];
        if(i===0){
          firstPoint = angular.copy(newPolygonPoint);
        }
        newGeoPoints.push(newPolygonPoint);
      }
      
      newGeoPoints.push(firstPoint);
       
      var turfP = turf.polygon([
            newGeoPoints
        ], {
          "fill": returnRandomColorHex(),
          "fill-opacity": 1
        });
      
      var hull = turf.convex(turfP);
      return hull;
       
    } else {
      //numberToCreate
      
    }
    
  }
   
  function drawAllGeometriesToMap() {
    //clear map  
    $("svg").find("g").html(""); 
   
    //base shape
    L.geoJSON(geometryToCover, { style: affectedAreaStyling }).addTo(mymap);
    
    //draw all shapes now
    for (var i = 0; i < allGeometries.length; i++) {
      //console.log("drawing new geometry: "+i);
      //console.log(allGeometries[i]);
      L.geoJSON(allGeometries[i], { style: returnAreaStyling() }).addTo(mymap);
    }
    //console.log("completed drawing geometries");
    //console.log(geometryToCover);
    
  }
  
  function removeRandomGeometries() {
    //randomRemovalPercentagePerGen
    var randomToRemove = Math.floor((allGeometries.length * (randomRemovalPercentagePerGen / 100) ));
    //console.log("number of random to remove: " + randomToRemove);
    for (var i = 0; i < randomToRemove; i ++) {
      //remove one random geometry from array
      allGeometries.splice(getRandomInt(0, allGeometries.length-1), 1);
    }
  }
  
  function removeWeakest() {
    //weakestPercentageRemovedPerGen
    var numberToRemove = Math.floor((allGeometries.length * (weakestPercentageRemovedPerGen / 100) ));
    //console.log("number of weakest to remove: " + numberToRemove);
    for (var i = 0; i < numberToRemove; i ++) {
      //remove current weakest
      var indexToRemove = indexOfMaxArea(allGeometries);
      allGeometries.splice(indexToRemove, 1);
    }
  }
  
  function reset() {
    //hitReset = true;
    //init();
  }
  
  function runEvolution() { 
    return $q(function (accept, reject) {
      
      if (hitReset) {
        //$interval.cancel(evolutionTimer);
        //init();
        //hitReset = false;
        //accept();
      }
      
      
      if (vm.generationNumber >= vm.numberOfGenerations) {
        $interval.cancel(evolutionTimer);
        return; 
      }
      console.log("############################ \n\n run evolution\n\n ############################");
      //console.log(allGeometries);
       
      updateDiagnostics();
      //draw to map 
      drawAllGeometriesToMap();
      //compute differences of all geometries
      //console.log(allGeometries);
      computeDifferences();

      
      //console.log(allGeometriesDifferences);
      //console.log(allGeometriesDfferencesAreas);
      //kill off random geometries
      if (!vm.speedOverride) {
        //alert();
      }
      //console.log("starting to remove random");
      //console.log(allGeometries);
      removeRandomGeometries();    
      //console.log("removed random. now removing weakest");
      //console.log(allGeometries);
      //kill off weakest geometries
      removeWeakest();
      //console.log("removed weakest");
      //console.log(allGeometries);
      //create offspring
      createOffSpring(); 

      //add offspring to pool of geometries
      console.log(allGeometries);
      console.log(addToAllGeometries);
      //allGeometries.concat(addToAllGeometries);
      allGeometries = allGeometries.concat(addToAllGeometries);
      addToAllGeometries = [];
      console.log(allGeometries);

      incrementGenerationNumber();
      updateDiagnostics();
      accept();
      //runEvolution();
    });
  }
  
   
  function createOffSpring() {
    var numberOfOffspring = numberOfGeometries - allGeometries.length;
    
    var numberOfRandom = Math.floor(numberOfOffspring * (reproductionGradient[0] / 100));
    var numberOfNonRandom = numberOfOffspring - numberOfRandom;
    
    //loop through and create the random's offspring
    for (var j = 0; j < numberOfRandom; j++) {
      //get the geometry reproducing
      var reproducingGeometry = allGeometries[getRandomInt(0, allGeometries.length)];
      var newGeo = mutateGeometry(reproducingGeometry);
      if (!newGeo ) {
        return;
      }
      newGeo.isRandomGen = true;
      addToAllGeometries.push(newGeo);
      
    }
     
    var tempArrOfAllGeo = angular.copy(allGeometries);
    var reproductionGradientClone = angular.copy(reproductionGradient);
    reproductionGradientClone.splice(0,1);
    var loopPercentageSum = 0;
    var prodIndex = 0;
    var reproducerPercentSum = reproductionGradientClone[prodIndex];
    
    for (var i = 0; i < numberOfNonRandom; i++) {
      //console.log("\n\nreproducing non randoms\n\n");
      var loopPercentage = i / numberOfOffspring;
      loopPercentageSum = loopPercentageSum + loopPercentage;
      
      //each loop, check if i is into the next reproducer's percentage.
      //if so, remove the top from this array
      //console.log("loop percentage: " + loopPercentage + "   i: "+ i + "   numberOfNonRandom: " + numberOfNonRandom);
      var indexOfReproducing = indexOfMaxArea(tempArrOfAllGeo);
      console.log(loopPercentageSum, reproducerPercentSum);
      if (loopPercentageSum > reproducerPercentSum) {
        tempArrOfAllGeo.splice(indexOfReproducing, 1);
        prodIndex++;
        reproducerPercentSum = reproducerPercentSum + reproductionGradientClone[prodIndex];
      }
      //get the current highest value in the temporary array of all geometry
      
      var reproducingGeometry = allGeometries[indexOfReproducing];
      
      console.log("producing a new geometry from index: " + indexOfReproducing);
      
      var newGeo = mutateGeometry(reproducingGeometry);
      if (!newGeo) {
        return;
      }
      newGeo.isRandomGen = false;
      addToAllGeometries.push(newGeo);
      //console.log("completed");
     
    }
    
  }
  
    
  function mutateGeometry(geometry) {
    if (!geometry) return;
      //console.log("mutating geometry!!!! " + geometry);
      //console.log(geometry);
      var newGeo = {};
      var numOfPoints = geometry.geometry.coordinates[0].length;
      //if a super rare occurence, randomly gen number of points
      //else if its not rare, generate either the same, or one more or less
      if (getRandomInt(0,100) > randomPointNumberNewMutationThreshold) {
        numOfPoints = getRandomInt(4, 10);
      } else {
        var modifier = 0;
        if (getRandomInt(0,100) > randomPointNumberMutationThreshold) {
          modifier = 1;
        } else if (getRandomInt(0,100) > randomPointNumberMutationThreshold) {
          modifier = -1;
        }
        numOfPoints = numOfPoints + modifier;
      }
    
    
      var newGeoPoints = [];
      var firstPoint = []; 
        
      //console.log(numOfPoints); 
    
      for (var i = 0; i < numOfPoints; i++) {
        //console.log("starting loop");
        
        var tempXMod = getRandomInt(-10000000, 10000000);
        var tempYMod = getRandomInt(-10000000, 10000000);
        
        var tempStartingX = 0;   
        var tempStartingY = 0;
        //if it doesnt exist, generate from random
        //console.log(!!geometry.geometry.coordinates[0][i]); 
        if (!!!geometry.geometry.coordinates[0][i]) { 
          //console.log("no coordinates");
          tempStartingX = centerLatLng[0] * 1000000000; 
          tempStartingX = tempStartingX + (tempXMod*2);   
          tempStartingX = tempStartingX / 1000000000;
          tempStartingY = centerLatLng[1] * 1000000000;
          tempStartingY = tempStartingY + (tempYMod*2); 
          tempStartingY = tempStartingY / 1000000000;
        } else {
          //console.log("coordinates exist");
          //if it does exist, generate from existing
          tempStartingX = geometry.geometry.coordinates[0][i][1] * 1000000000;
          tempStartingX = tempStartingX + (tempXMod/2);
          tempStartingX = tempStartingX / 1000000000;
          tempStartingY = geometry.geometry.coordinates[0][i][0] * 1000000000;
          tempStartingY = tempStartingY + (tempYMod/2);
          tempStartingY = tempStartingY / 1000000000;
          //console.log("finishing getting x and y");
        } 
            
        var newPolygonPoint = [tempStartingY, tempStartingX];
        if(i===0){
          firstPoint = angular.copy(newPolygonPoint);
        }
        newGeoPoints.push(newPolygonPoint);
      }
      
      newGeoPoints.push(firstPoint);
     
      var turfP = turf.polygon([
            newGeoPoints
        ]);
      //console.log("generating hull");
      var hull = turf.convex(turfP);
      return hull;
  } 
  
  
  function evolutionDriver() {
    
    evolutionTimer = $interval(runEvolution, vm.speed);
    
  }
  
  function updateDiagnostics() {
    vm.numberOfGeometries = allGeometries.length;
  }
  
  
  init();
  
  
  
  
  
 
  
});
















//Helpers
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function returnRandomColorHex() {
  return '#'+(Math.random()*0xFFFFFF<<0).toString(16);
}

function indexOfMinArea(arr) {
    if (arr.length === 0) {
        return -1;
    }
    var min = arr[0].area;
    var minIndex = 0;
    for (var i = 1; i < arr.length; i++) {
        if (arr[i].area < min) {
            minIndex = i;
            min = arr[i].area;
        }
    }
    return minIndex;
}

function indexOfMaxArea(arr) {
  //console.log(arr);
    if (arr.length === 0) {
        return -1;
    }
    var max = arr[0].area;
    var maxIndex = 0;
    for (var i = 1; i < arr.length; i++) {
      //console.log(i + "    " + arr[i]);
        if (arr[i].area > max) {
            maxIndex = i;
            max = arr[i].area;
        }
    }
    return maxIndex;
}







//styling

   //affected area styling
    var affectedAreaStyling = {
      "color": "#000000",
      "weight": 3,
      "opacity": 1,
      "fillOpacity": .75
    };
    //affected area centroid dot styling
    var sourceSignalStyling = {
      "color": "#5bffad",
      "weight": 1,
      "opacity": 1,
      "fillOpacity": 1,
      "radius": 100
    };
    //generated area
    var generateAreaStyling = {
      //"color": returnRandomColorHex(),
      "weight": 3,
      //"opacity": .01,
      //"fillOpacity": .01
    };

    function returnAreaStyling(color) {
      if (!color) {
        color = returnRandomColorHex();
      }
      return {
          "color": color,
          "weight": 3,
          "opacity": .3,
          "fillOpacity": .1
        };
    }
  


var geometryToCover = turf.polygon([[
            [
              -122.40657806396484,
              37.80680022788906
            ],
            [
              -122.47489929199219,
              37.80734273233311
            ],
            [
              -122.50648498535156,
              37.78401144262929
            ],
            [
              -122.5033950805664,
              37.71152898951815
            ],
            [
              -122.41275787353516,
              37.70881291183666
            ],
            [
              -122.38288879394531,
              37.75171529845649
            ],
            [
              -122.40657806396484,
              37.80680022788906
            ]
]], {
  "fill": "#000",
  "fill-opacity": 0.9
});

/*
//default geojson
var geometryToCover = {
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              -122.40657806396484,
              37.80680022788906
            ],
            [
              -122.47489929199219,
              37.80734273233311
            ],
            [
              -122.50648498535156,
              37.78401144262929
            ],
            [
              -122.5033950805664,
              37.71152898951815
            ],
            [
              -122.41275787353516,
              37.70881291183666
            ],
            [
              -122.38288879394531,
              37.75171529845649
            ],
            [
              -122.40657806396484,
              37.80680022788906
            ]
          ]
        ]
      }
    }
  ]
}

*/ 
              
            
!
999px

Console