HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
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.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
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.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
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.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<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>
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;
}
}
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 © Esri — 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
]
]
]
}
}
]
}
*/
Also see: Tab Triggers