score:0

Accepted answer

i tried to have a look at you jsfiddle, but d3 resource does not seem to load properly (console logs some mistakes about loading not-https resource). i created a plunker: http://plnkr.co/edit/unoiooafspraydqcynfi?p=preview

var num = 0;

var width = 660,
  height = 800;

var radius = 2;

d3.select("body").selectall("h1").data([{}]).enter()
  .insert("h1").html("some text here")
var svg = d3.select("#svgcontainer").append("svg")
  .attr("width", width)
  .attr("height", height)
  .append("g");
var g = svg.append("svg:g")
  .attr("transform", "translate(0, 0)");

function getpatterndata(num) {
  if (num == 1) {
    var pdata = cellular();
  } else {
    pdata = cellular2();
  }
  console.log("pdata", pdata);

  return pdata;
}

function makelines(datas) {

  var entries = d3.entries(datas);

  var thelines = [];
  var oneline = [];

  entries.foreach(function(d) {
    var line = d.value.split(" ");
    thelines.push(line);
  });
  console.log("thelines", thelines);
  return thelines;
}

function update(thelines, num) {

  // data join
  // join new data with old elements, if any.
console.log(thelines)
  // and update
  for (i = 0; i < thelines.length; i++) {
    //for (i = thelines.length; i >= 0;  i--) {

    var oneline = thelines.pop();
console.log(oneline);
    //append lines to container
    var circles = g
      .selectall(".dummy")
      .data(oneline) //will be oneline
      .enter()
      .append("circle")
      .classed('first-update',true);

    //console.log("inside update,oneline", oneline);


    var circleattributes = circles.attr("cx", function(d, idx) {
      var x= idx*10;
      console.log('x: ',x)
      return x;
    })
      .attr("cy", function(d, idx) {
        var y = (i + 1) * 10;
        console.log('y: ',y)

        return y;
      })
      .attr('r',2)
      .attr("transform", "translate(30," + (0) + ")")
      .transition().duration(2000)
      .attr("r", function(d, i) {
        if (+d == 1) {
          return 3;
        } else {
          return 2;
        }
      })
      .style("fill", function(d) {
        var returncolor;
        if (+d === 0) {
          returncolor = "lightblue";
        } else if (+d === 1) {
          returncolor = "red";
        } else if (+d === 0) {
          returncolor = "green";
        }
        return returncolor;
      })
      .transition(3000)
      .delay(2000)
      .attr("opacity", 0.01)
      .transition();
    //.remove();

  }

} //end function

function update2(thelines, num) {

  // data join
  // join new data with old elements, if any.

  // and update
  for (i = 0; i < thelines.length; i++) {
    //for (i = thelines.length; i >= 0;  i--) {

    var oneline = thelines.pop();

    //append lines to container
    //var samplesvg = d3.select('svg');
    var circles = g //.selectall("body")
      .selectall('.dummy')
      .data(oneline)
    //will be oneline
    .enter()
      .append("circle");
    console.log("inside update,oneline", oneline);


    var circleattributes = circles.attr("cx", function(d, idx) {
      return (idx * 10);
    })
      .attr("cy", function(d,idx){return i*10;})
      .attr("transform", "translate(30,0)")
      .transition().duration(2000)
      .attr("r", function(d, i) {
        if (+d == 1) {
          return 3;
        } else {
          return 2;
        }
      })
      .style("fill", function(d) {
        var returncolor;
        if (+d === 0) {
          returncolor = "lightblue";
        } else if (+d === 1) {
          returncolor = "red";
        } else if (+d === 0) {
          returncolor = "green";
        }
        return returncolor;
      });
  }
}

// the initial display.
var initialpattern = [];
var secpattern = [];
initialpattern = getpatterndata(2);

var thepatternrows = [];
thepatternrows = makelines(initialpattern);

console.log("thepatternrows", thepatternrows);
update(thepatternrows, 2);

//d3.select('div').attr("class",".inside").selectall("*").remove();

secpattern = getpatterndata(1);

thepatternrows = makelines(secpattern);

update2(thepatternrows, 1);



//#myc11a.js

//randomized, and returns a big list of strings separated by a space
function cellular2() {
  // this is the same as the other pattern input except it randomizes
  // the neighbors.
  // my attempt to translate from python to d3.js javascript
  //def ca():
  //   ''' celluar automata with python - k. hong'''
  //   # 64 boolean - true(1) : '*'
  //   #            - false(0): '-'
  //   # rule - the status of current cell vaue is true
  //   # if only one of the two neighbors at the previous step is true('*')
  //   # otherwise, the current cell status is false('-')

  //  # list representing the current status of 64 cells
  var ca = [];
  for (i = 0; i < 64; i++) {

    var arval = math.round(math.random());
    ca.push(arval);
  }

  //# new cellular values

  //   dic = { 0:"-", 1: "*" }


  //# initial draw - step 0
  //print  ''.join( [dic[e] for e in ca_new])
  //console.log('initial ca',ca);

  var ca_next_string = '';
  var castring = ca.valueof();
  //console.log("initial castring",castring);
  var castring2 = ca.join(" ");
  //console.log("initial castring2",castring2);


  var ca_lol0 = [];
  ca_lol0.push(castring2);
  //ca_lol0.push("\n");

  var ca_new = ca;


  castring = ''
  castring2 = ''
  // additional 31 steps
  // loop through 0 to 63 and store the current cell status in ca_new list
  var ca_next = [];
  var step = 1;
  while (step < 32) {
    ca_new = [];
    // loop through 0 to 63 and store the current cell status in ca_new list
    for (var i = 0; i < 64; i++) {
      // inside cells - check the neighbor cell state
      if (i > 0 && i < 63) {
        if (ca[i - 1] == ca[i + 1]) {
          ca_new.push(0);
        } else {
          ca_new.push(1);
        }
      }

      // left-most cell : check the second cell
      else if (i == 0) {
        if (ca[1] == 1) {
          ca_new.push(1);
        } else {
          ca_new.push(0);
        }
      }

      // right-most cell : check the second to the last cell
      else if (i == 63) {
        if (ca[62] == 1) {
          ca_new.push(1);
        } else {
          ca_new.push(0);
        }
      }


      castring0 = ca_new.join(" ");
      castring20 = ca_new.concat("\n");
    } //end of for

    //draw current cell state
    //this one contains 0,1

    ca_lol0.push(castring20.join(' '))
    //ca_lol0.push(castring20)
    //ca_lol0.push('\n')

    //update cell list
    ca = ca_new;
    ca_next = [];
    step = step + 1;
  } //end of while

  //           console.log("final list of strings",ca_lol0);
  console.log("pattern of randomized neighbors");
  // return castring20;
  return ca_lol0;

}

//myc11.js
//returns a big list of strings separated by a space
function cellular() {
  // my attempt to translate from python to d3.js javascript
  //def ca():
  //   ''' celluar automata with python - k. hong'''
  //   # 64 boolean - true(1) : '*'
  //   #            - false(0): '-'
  //   # rule - the status of current cell vaue is true
  //   # if only one of the two neighbors at the previous step is true('*')
  //   # otherwise, the current cell status is false('-')

  //  # list representing the current status of 64 cells
  var ca = [
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  ];

  //# new cellular values

  //   dic = { 0:"-", 1: "*" }


  //# initial draw - step 0
  //print  ''.join( [dic[e] for e in ca_new])
  //console.log('initial ca',ca);

  var ca_next_string = '';
  var castring = ca.valueof();
  //console.log("initial castring",castring);
  var castring2 = ca.join(" ");
  //console.log("initial castring2",castring2);


  var ca_lol0 = [];
  ca_lol0.push(castring2);
  //ca_lol0.push("\n");

  var ca_new = ca;


  castring = ''
  castring2 = ''
  // additional 31 steps
  // loop through 0 to 63 and store the current cell status in ca_new list
  var ca_next = [];
  var step = 1;
  while (step < 32) {
    ca_new = [];
    // loop through 0 to 63 and store the current cell status in ca_new list
    for (var i = 0; i < 64; i++) {
      // inside cells - check the neighbor cell state
      if (i > 0 && i < 63) {
        if (ca[i - 1] == ca[i + 1]) {
          ca_new.push(0);
        } else {
          ca_new.push(1);
        }
      }

      // left-most cell : check the second cell
      else if (i == 0) {
        if (ca[1] == 1) {
          ca_new.push(1);
        } else {
          ca_new.push(0);
        }
      }

      // right-most cell : check the second to the last cell
      else if (i == 63) {
        if (ca[62] == 1) {
          ca_new.push(1);
        } else {
          ca_new.push(0);
        }
      }


      castring0 = ca_new.join(" ");
      castring20 = ca_new.concat("\n");
    } //end of for

    //draw current cell state
    //this one contains 0,1

    ca_lol0.push(castring20.join(' '))
    //ca_lol0.push(castring20)
    //ca_lol0.push('\n')

    //update cell list
    ca = ca_new;
    ca_next = [];
    step = step + 1;
  } //end of while

  //           console.log("final list of strings",ca_lol0);
  console.log("pattern of static assigned neighbors");
  // return castring20;
  return ca_lol0;

}

the first thing i noticed is that you create an svg at each iteration of your update loop. this step is not required, as you are creating your svg at the top, and a group to store your circles (or so i guess).

as for the update pattern,here is how it works (for what i understood):

  • you have to select the types of element you want to update ( in code above: selectall('.dummy') )
  • you set the data you want to bind to ( .data(oneline) )
  • you do your operations (appending circles, setting their attributes, etc.)
  • you exit and you remove

now in the code above, i used a .dummy selector before binding to data to avoid selecting existing objects. the proper way would be to use .selectall('circle'), but in that case, you would only get one line of circles, as existing circles would be reselected every time. this is linked to the fact that you loop on the lines yourself. i would try to bind to the original collection directly, and try to use callback functions properly to compute cx and cy. would i do it myself, i would even create an array of object with a property x and y that would let me build my circles easily (but that's a personnal data design choice).

also, be careful for the use of the variable i in your loops and as an indexer in your callback functions for computing cx and cy, this could lead to conflicts.

i hope this is clear(er) and it helps; otherwise i will try to elaborate more on required points.


Related Query