Midterm Progress – Julia Set

Concept:

While researching randomly generated methods to implement in my code, I came across the Julia Set. A Julia Set is a set of complex numbers that do not converge to any limit when a given mapping is repeatedly applied to them. The primary purpose of this code is to provide an engaging way to explore the fascinating world of fractals and complex dynamics through visual art. It allows for a deeper appreciation of mathematical concepts by transforming them into a dynamic visual experience. This kind of interactive art can be used for educational purposes, artistic expression, or simply as a fun visual experiment (although it is extremely difficult).

Understanding Julia and Mandelbrot Sets

Code Highlight:
class JuliaSet {
  constructor(cRe, cIm) {
    this.cRe = cRe; // Real part of the Julia constant
    this.cIm = cIm; // Imaginary part of the Julia constant
  }

  // Create particles based on the Julia set
  createParticles() {
    for (let i = 0; i < numParticles; i++) {
      // Random position for each particle
      let x = random(width);
      let y = random(height);
      let zx = map(x, 0, width, -2, 2);
      let zy = map(y, 0, height, -2, 2);
      let iter = 0;

      // Check if the point is in the Julia set
      while (zx * zx + zy * zy < 4 && iter < maxIterations) {
        let tmp = zx * zx - zy * zy + this.cRe;
        zy = 2 * zx * zy + this.cIm;
        zx = tmp;
        iter++;
      }

      // Create particles based on whether they are in the Julia set
      let brightness = iter < maxIterations ? 50 : map(iter, 0, maxIterations, 0, 255);
      particles.push(new Particle(x, y, brightness));
    }
  }
}

 

Key Components
  1. Particle System: An array called particles stores instances of Particle, representing individual points that are displayed on the canvas..
  2. Mapping Mouse Movement: The cRe and cIm variables are calculated using the map() function, which transforms the mouse’s x and y positions to a range suitable for generating the Julia set (between -1.5 and 1.5).
  3. Julia Set Creation: A JuliaSet object is created with the mapped constants, and its createParticles() method generates particles based on whether points fall within the Julia set.
  4. Each point on the canvas is tested using an iterative algorithm to see if it remains bounded (within a circle of radius 2) when applying the Julia set’s equation. If it does not escape, it belongs to the set.
  5. Particle Behavior: Each Particle is updated every frame using Perlin noise (noise()) to create smooth, organic movements. The angle of movement is determined by the noise value, leading to a natural, swirling motion.
  6. Particles are checked to see if they are within the canvas boundaries; if they exit, they are randomly repositioned.
  7. Brightness Calculation: The brightness of each particle is determined based on the number of iterations it took to escape the set. If the point escapes before reaching the maximum number of iterations, it is assigned a low brightness. Otherwise, its brightness is scaled based on how quickly it escaped.
Sketch:

Edit:   https://editor.p5js.org/mariamalkhoori/sketches/M0NHDl7zU
Next Steps:

I want to expand the Julia set to take on a fuller shape across my canvas. So far, this is not what I had in mind at all, but working with such a new concept has been challenging, so I will pause here for now.

  • Work on the generative aspect further.
  • Refine the particle system, as I still feel it doesn’t meet the design I envision.

Advanced Mathematical Exploration:

  • Different Constants: Allow users to explore different Julia constants (e.g., c values) by letting them input values directly or select from a preset list.
  • Mandelbrot Set Comparison: Implement a feature to compare the Julia set with its corresponding Mandelbrot set, illustrating their relationship.

 

References

https://thecodingtrain.com/challenges/22-julia-set

https://paulbourke.net/fractals/juliaset/

https://fractalsaco.weebly.com/julia-set.html

Assignemnt 4

Concept

In this project, I aimed to create a mesmerizing visual display that responds dynamically to sound input using the p5.js library. The core concept revolves around simulating particles that mimic harmonic motion while being influenced by real-time audio levels detected through the microphone. This interplay of sound and visuals creates an engaging experience, reminiscent of a light show or a digital aurora, where each particle dances in response to the surrounding environment.

Highlights I’m Proud Of
class Particle {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.angle = random(TWO_PI);
    this.length = random(10, 20); // Length of the trails
    this.timeOffset = random(TWO_PI); 
  }

  update(vol) {
   
    let harmonicX = cos(this.angle) * 200 * sin(frameCount * 0.02 + this.timeOffset); // Horizontal oscillation
    let harmonicY = sin(this.angle * 2) * 200 * cos(frameCount * 0.03 + this.timeOffset); // Vertical oscillation

    // Update positions based on combined harmonic motion
    this.x += harmonicX * vol * 0.5; 
    this.y += harmonicY * vol * 0.5; 

  
    this.x += cos(this.angle) * vol * 100; 
    this.y += sin(this.angle) * vol * 100; 

  
    this.x = constrain(this.x, 0, width);
    this.y = constrain(this.y, 0, height);
    
    this.angle += 0.05; // Smooth rotation
  }

 

Embedded sketch

https://editor.p5js.org/mariamalkhoori/full/_9bo6lBl_

Edit Sketch:
https://editor.p5js.org/mariamalkhoori/sketches/_9bo6lBl_
Reflection and Ideas for Future Work
  • Expanded Color Palette: Experiment with a broader range of colors or gradients, perhaps responding to different frequencies or sound levels for a richer visual output.
  • More Complex Patterns: Investigate additional mathematical functions to define the particle movements, creating even more intricate and visually stunning animations.

 

Refrences

Simple Harmonic Motion #11 for Light at Blenheim Palace (2014)

Sound from my favourite band :3 — https://music.youtube.com/watch?v=CaMcDzvwL30&si=ZyQE7yoDhOCHxzFR

Assignment 3- Mixing Water and Salt

Concept

Pure water is one of the simplest chemical compounds to understand, and the concept of mixing solubles with water is something most people learn early on in third grade. However, translating this fundamental idea into a digital simulation presented a significant challenge. Representing molecules and their interactions through code required a deeper understanding of both chemistry and programming. Initially, my goal was to model how water and salt molecules interact with each other using forces of attraction. This involved not only visualizing the individual molecules but also accurately simulating their dynamic interactions. The process of creating this simulation highlighted the complexity behind seemingly simple concepts and provided valuable insights into the behavior of molecules in a digital environment.

 

I tried to implement the particles movements in this seperate code using attractors to mimic an atom: https://editor.p5js.org/mariamalkhoori/sketches/VmTpfxlVA

Water Atoms Stock Illustrations – 1,606 Water Atoms Stock Illustrations, Vectors & Clipart - Dreamstime

Highlight I’m proud of

 

function draw() {
  background(img);
  
  // Draw the glass of water
  fill(177, 177, 199, 225);
  quad(131, 126, 318, 126, 290, 344, 158, 344);
  
  fill(85, 179, 236, 100);
  quad(137, 177, 312, 177, 290, 344, 158, 344);
  
  // Update and display water molecules
  for (let molecule of waterMolecules) {
    molecule.update();
    molecule.display();
  }

  // Update and display salt molecules if showSalt is true
  if (showSalt) {
    for (let molecule of saltMolecules) {
      molecule.update();
      molecule.display();
    }
  }

  // Check if attraction pairs exist and apply attraction during MIX
  if (isMixing) {
    for (let pair of attractPairs) {
      let waterMolecule = pair.water;
      let saltMolecule = pair.salt;

      // Calculate the distance between the water molecule and the salt molecule
      let target = createVector(saltMolecule.x, saltMolecule.y);
      let currentPos = createVector(waterMolecule.x, waterMolecule.y);
      let distance = p5.Vector.dist(currentPos, target);

      // If the water molecule is close enough, snap to the salt molecule and stop moving
      if (distance > 15) { // Adjust the threshold to be equal to their combined radii
        let attractionForce = p5.Vector.sub(target, currentPos);
        attractionForce.setMag(0.5); // Set attraction force strength

        // Apply the attraction force to move the water molecule towards the salt molecule
        waterMolecule.x += attractionForce.x;
        waterMolecule.y += attractionForce.y;
      } else {
        // Snap the water molecule to the salt molecule's position
        waterMolecule.x = saltMolecule.x;
        waterMolecule.y = saltMolecule.y;
        waterMolecule.isAttached = true; // Mark as attached to stop future movement
      }
    }
  }

 

Embedded sketch

https://editor.p5js.org/mariamalkhoori/sketches/Oy3gJilH_

Reflection and ideas for future work or improvements

The project provided a valuable exploration of simulating molecular interactions and highlighted the complexities of translating theoretical chemistry into a visual format. It revealed the challenge of balancing scientific accuracy with effective coding techniques and emphasized the importance of a solid understanding of molecular behavior. Future improvements could include enhancing simulation accuracy, adding interactive user features, incorporating advanced visualization techniques, expanding to more complex scenarios, and developing educational tools to support learning.

Future Work:

  • Accuracy Improvement: Enhance precision of molecular interactions.
  • User Interaction:Add features for user input and parameter adjustments.
References:

//https://www.youtube.com/watch?v=OAcXnzRNiCY&ab_channel=TheCodingTrain

Assignment 2- Spiral Repulsion

Concept

For this assignment, I was primarily inspired by the galaxy—a seemingly simple yet profoundly intricate phenomenon in our vast universe. The swirling motion of stars and cosmic dust, the vibrant colors, and the immense scale all evoke a sense of mystery and wonder. Galaxies are both elegant and complex, embodying the balance between chaos and order. This duality inspired me to explore patterns and shapes that reflect the beauty and unpredictability of the cosmos. Through this project, I aimed to capture the essence of the galaxy’s mesmerizing movement and its delicate balance of simplicity and complexity.

In my code, I implemented two key features. The first was the required assessment of movement and acceleration. By pressing the up and down arrow keys, the speed of the particles could be controlled, allowing for a dynamic interaction with the animation. The second feature involved particle interaction through hovering. As the cursor hovers over the particles, they would disperse, creating a sense of disruption and fluid motion in response to user input.

Dark Matter May Not Exist: These Physicists Favor of a New Theory of Gravity

Highlight I’m proud of

Here I was able to create a special class for the particles.

class Particle {
  constructor(vx, vy) {
    this.vx = vx;
    this.vy = vy;
    this.num = 255;
    this.a = 255;
    this.loc = createVector(width / 2, height / 2);  // Start from the center
    this.vel = createVector(0, 0);  
    this.acc = createVector(1, 1);
  }

  update() {
    // Apply acceleration using the acceleration factor
    this.vel.add(this.acc.mult(accelerationFactor));  
    this.loc.add(this.vel);

    // Reset acceleration and limit the velocity for smoother control
    this.acc.mult(0);
    this.vel.limit(0.5);  
  }

  repulse() {
    // Calculate the distance between the particle and the mouse
    let mouse = createVector(mouseX, mouseY);
    let dir = p5.Vector.sub(this.loc, mouse);  
    let distance = dir.mag();  

    if (distance < repulsionRadius) {  // If the particle is within the repulsion radius
      dir.normalize();  // Normalize the direction to get just the direction vector
      let force = map(distance, 0, repulsionRadius, 5, 0);  // Stronger repulsion the closer the particle is
      dir.mult(force);  // Multiply the direction vector by the repulsion force
      this.vel.add(dir);  // Apply the repulsion force to the particle's velocity
    }
  }

  isOutside() {
    // Check if the particle goes outside the canvas
    return (this.loc.x < 0 || this.loc.x > width || this.loc.y < 0 || this.loc.y > height);
  }

  display() {
    // Update acceleration based on the particle's properties and a trigonometric function for spirals
    this.acc = createVector(
      sin(radians(this.vx + this.num / 2)) / 2,
      cos(radians(this.vy - this.num / 2)) / 2
    );

    // Draw the particle with a fade effect
    fill(255, this.a);
    var r = map(this.a, 255, 0, 1, 10);  // Particle size changes as it fades
    ellipse(this.loc.x, this.loc.y, r);

    this.num += map(this.a, 255, 0, 1, 0);  // Update num for smooth spiral motion
    this.a -= 0.1;  // Gradually reduce alpha for a fade-out effect
  }
}

Embedded sketch

Sketch:
 https://editor.p5js.org/mariamalkhoori/sketches/_t5yMvlGp
Reflection and ideas for future work or improvements
  • User Interaction: Add interaction features such as particles reacting to clicks or drag-and-drop functionality.
  • Different Particle Types: Introduce various particle types with distinct behaviors, such as different shapes or sizes.
  • Customizable Motion Patterns: Allow particles to follow different patterns or trajectories, like zig-zags or chaotic paths.
Refrences:
  • https://editor.p5js.org/RonanChang/sketches/S1NQJgbx4
  • https://decodingnature.nyuadim.com/2024/08/28/week-1-fireflies-by-dachi/

 

Assignment 1 – Chromatic Trails of Chance

Concept

For my first assignment, I decided to keep it simple while adhering to the given requirements. From the first list, I chose to implement the Lévy flight walk along with the concept of changing color based on the ellipse’s position on the screen. This type of random walk features steps distributed according to a power-law, resulting in occasional long jumps interspersed with shorter steps.

Highlight I’m proud of
function draw() {
  // Update position based on Levy Flight
  angle = random(TWO_PI); // Random angle
  stepSize = pow(random(), -1.5) * 5; // Levy Flight step size with power-law distribution
  x += cos(angle) * stepSize;
  y += sin(angle) * stepSize;
  
  // Ensure the position is within bounds
  x = constrain(x, 0, width);
  y = constrain(y, 0, height);
  
  // Store current position for trailing effect
  trail.push([x, y]);
  
  // Limit the number of points in the trail for performance
  if (trail.length > 100) {
    trail.shift(); // Remove oldest point
  }

From the code above I allowed for my canvas to leave a trail of where the previous pattern came across. Then slowly it would remove the oldest trail by limiting the number of points.

Embedded sketch

Reflection and ideas for future work or improvements

It would be nice to add more user input by allowing users to control aspects of the Levy Flight, such as step size or angle, using mouse or keyboard inputs. Maybe also experiment with different types of random walks or combine multiple patterns for complex behaviors.

Week 1 – Reading Reflection

In the first chapter of The Computational Beauty of Nature, Gary Flake draws on examples from different fields of science and nature to offer a new way of thinking. I believe he succeeds in simplifying complex concepts like computing and coding. Looking at something as complicated as computer science can be quite intimidating; however, a solution is offered by trying to view how things may work using different methods. This approach to learning can make complex coding a simpler task.

Flake’s approach to reductionism and holism allows for a more thorough learning experience. One example I can provide is when a person tries to get their driver’s license—it is required to gain a basic understanding of some car parts before driving. The parts they would focus on include batteries, engines, alternators, as well as external products used for cars. This allows the driver to recognize the kind of device they will be dealing with and understand the use of each part, especially since specific parts may differ across car brands. The holistic approach comes into play when driving the car itself, as managing the car and ensuring that all parts work together cooperatively is crucial.

Getting my driver’s license was a traumatic experience, especially with the overwhelming amount of information I had to learn. But if it means I get to be the best driver among my siblings, then it is worth it.