Commit 1589e512 authored by smsj's avatar smsj

remove testing code and organize the processing.py images

parent 2b36f111
import datetime
from random import shuffle, seed
################################################################################
# Global variables
################################################################################
# Get time
timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
# Set random seed value for both Python 'random' and Processing 'random'
rand_seed = 1138
print(rand_seed)
# Comment out seeds below to get new shape on every run
seed(rand_seed) # This only applys to the Python random functions
randomSeed(rand_seed) # This only applys to the Processing random functions
################################################################################
# Knobs to turn
################################################################################
filename = 'allegory'
record = True
animate = True
animate_mode = 'sinusoid'
# Canvas size
w = 1200 # width
h = 800 # height
steps = 1000
num_loops = 1
frame_rate = 20
inc = 0.01
scl = 20
cols = floor(w/scl)
rows = floor(h/scl)
step = TAU/steps
t1 = 0
# t2 = 1000
# t3 = 100000
c_points = [radians(x) for x in range(1, 360, 10)]
print(c_points)
def setup():
# Sets size of canvas in pixels (must be first line)
size(w, h) # (width, height)
# Sets resolution dynamically (affects resolution of saved image)
pixelDensity(displayDensity()) # 1 for low, 2 for high
# Sets color space to Hue Saturation Brightness with max values of HSB respectively
colorMode(HSB, 360, 255, 255, 255)
# Set the number of frames per second to display
frameRate(frame_rate)
# Stops draw() from running in an infinite loop (should be last line)
if not animate:
noLoop() # Comment to run draw() infinitely (or until 'count' hits limit)
background(0, 0, 0)
stroke(263,100,230)
noFill()
def draw():
global t1
global t2
global t3
t1 = t1 + 0.03;
# t2 = t2 + 2;
# t3 = t3 + 2;
if frameCount > (steps * num_loops):
#exit()
pass
beginShape()
r = w*0.03
# First 3 points of each blob line are explicitly set because
# they are needed at the end of the shape to close the loop
a = c_points[0]
n = map(noise(t1, a), 0, 1, 1, 2)
x0, y0 = circle_point(w/2, h/2, n*(r+frameCount), a)
curveVertex(x0, y0)
a = c_points[1]
n = map(noise(t1, a), 0, 1, 1, 2)
x1, y1 = circle_point(w/2, h/2, n*(r+frameCount), a)
curveVertex(x1, y1)
a = c_points[2]
n = map(noise(t1, a), 0, 1, 1, 2)
x2, y2 = circle_point(w/2, h/2, n*(r+frameCount), a)
curveVertex(x2, y2)
for i,a in enumerate(c_points):
# Limiting which points get vertices makes the "floor"
if i>3:
n = map(noise(t1, a), 0, 1, 1, 2)
x, y = circle_point(w/2, h/2, n*(r+frameCount), a)
curveVertex(x, y)
# The three first points are laid out again to smoothly close the loop
curveVertex(x0, y0)
curveVertex(x1, y1)
curveVertex(x2, y2)
endShape()
if record:
save_frame_timestamp(filename, timestamp)
def save_frame_timestamp(filename, timestamp='', output_dir='output'):
'''Saves each frame with a structured filename to allow for tracking all output'''
filename = filename.replace('\\', '')
filename = filename.replace('/', '')
output_filename = os.path.join(output_dir, '{}_{}_{}_####.png'.format(timestamp, filename, rand_seed))
saveFrame(output_filename)
print(output_filename)
def circle_point(cx, cy, r, a):
x = cx + r * cos(a)
y = cy + r * sin(a)
return x, y
'''
fractaL images - v 0.0.1 - 16th April 2019
To work with Processing.py easily you firt need to convert data to list.
To do so, we import the data and start the work setting it up.
This is a code to work with dataset, particularly with dataframe format.
The code is build in order to enable functionalities for the next steps. To know:
1 - Sensors integration: RPi and Arduino
2 - Easy to adapt to dictionaries" (like JSON files)
'''
size(500,500)
noStroke()
background('#004477')
dates = [ 'Jan 28', 'Feb 04']
scores = [
['Jan 28', 120000, 220],
['Feb 04', 80000, 260]
]
print(scores)
mode=Python
mode.id=jycessing.mode.PythonMode
from particle import Particle
import math
inc = 0.2
scl = 9 # ratio of cell size to canvas size
numrows = 999
numcols = 999
zoff = 0 # time dimension for noise
num_particles = 500
particles = []
flowfield = []
def setup():
global particles, num_particles, flowfield, numrows, numcols
size(600,600,P2D)
background(255,50)
numcols = int(math.ceil(width / scl)) + 1
numrows = int(math.ceil(height / scl)) + 1
print(numrows, numcols)
for y in range(numrows):
for x in range(numcols):
flowfield.append(None)
for i in range(num_particles):
particles.append(Particle())
def draw():
global zoff, particles, flowfield, numrows, numcols
# background(255)
stroke(255, 150)
strokeWeight(1.5)
yoff = 0
for y in range(numrows):
xoff = 0
for x in range(numcols):
# define flow vector at location
index = (x + y * numcols)
angle = noise(xoff, yoff, zoff) * TWO_PI * 3
v = PVector.fromAngle(angle)
v.setMag(.8)
flowfield[index] = v
# draw vector
# pushMatrix()
# translate(x * scl, y * scl)
# rotate(v.heading())
# line(0,0,scl,0)
# popMatrix()
xoff += inc
yoff += inc
zoff += 0.002
print(floor(frameRate))
for p in particles:
p.follow(flowfield, scl, numcols)
p.update()
p.show()
saveFrame("frames/flow_####.png")
class Particle(object):
def __init__(self):
# # OPTION 1
# self.pos = PVector(random(width),random(height))
# self.vel = PVector(0,0)
#OPTION 2
r = random(30)
a = random(TWO_PI)*4
self.pos = PVector(width/2 + r*cos(a), height/2 + r*sin(a))
self.vel = PVector.random2D().limit(4)
self.acc = PVector(0,0)
self.maxspeed = 4
self.prevpos = PVector.random2D()
def update(self):
self.prevpos = self.pos.copy()
self.vel.add(self.acc)
self.vel.limit(self.maxspeed)
self.pos.add(self.vel)
self.acc.mult(0)
self.edges()
def applyForce(self, force):
self.acc.add(force)
def show(self):
stroke(0, 5)
strokeWeight(.8)
line(self.prevpos.x, self.prevpos.y, self.pos.x, self.pos.y)
def updatePrevious(self):
self.prevpos = self.pos.copy()
def edges(self):
if self.pos.x > width:
self.pos.x = 0
self.updatePrevious()
if self.pos.x < 0:
self.pos.x = width
self.updatePrevious()
if self.pos.y > height:
self.pos.y = 0
self.updatePrevious()
if self.pos.y < 0:
self.pos.y = height
self.updatePrevious()
def follow(self, flowfield, scl, numcols):
x = floor(self.pos.x / scl)
y = floor(self.pos.y / scl)
idx = floor(x + y * numcols)
force = flowfield[idx]
self.applyForce(force)
add_library("minim")
x1=100
x2=25
y1=0
y2=25
def setup():
global sf
size(200, 200)
background(255) # white
minim=Minim(this)
sf=minim.loadFile("bounced.mp3")
def draw():
global x1,y1,x2,y2
fill(155)
rect(x1, y1, x2, y2)
def keyReleased():
global x1, y1, x2, y2
rect(x1, y1, x2, y2)
if (key == CODED):
if (keyCode == LEFT) and x1>=0:
x1=x1-10
print(x1)
background(255)
rect(x1, y1, x2, y2)
elif (keyCode == RIGHT) and x1<=170:
x1=x1+10
print(x1)
background(255)
rect(x1,y1,x2,y2)
elif (keyCode == UP) and y1>=0:
y1=y1-10
print(y1)
background(255)
rect(x1,y1,x2,y2)
elif (keyCode == DOWN) and y1<=170:
y1=y1+10
print(y1)
background(255)
rect(x1,y1,x2,y2)
else:
sf.play()
mode=Python
mode.id=jycessing.mode.PythonMode
add_library('sound')
mic = None
amp = None
def setup():
global mic, amp
size(440, 440)
background(0)# Create an audio input and start it
mic = AudioIn(this, 0)
mic.start()
# Create a new amplitude analyzer and patch into input
amp = Amplitude(this)
amp.input(mic)
def draw():
# Draw a background that fades to black
noStroke()
fill(26, 76, 102, 10)
rect(0, 0, width, height)
# The analyze() method returns values between 0 and 1,
# so map() is used to convert the values to larger numbers
diameter = map(amp.analyze(), 0, 1, 10, width)
# Draw the circle based on the volume
fill(255)
ellipse(width/2, height/2, diameter, diameter)
mode=Python
mode.id=jycessing.mode.PythonMode
add_library('sound')
blip = None
radius = 120
x = 0
speed = 1.0
direction = 1
def setup():
global blip, x
size(940, 940)
ellipseMode(RADIUS)
blip = SoundFile(this, "multilong2_sonified.mp3")
x = width/2 # Start in the center
def draw():
global x, direction
background(0)
x += speed * direction
if x > width-radius or x < radius:
direction = -direction # Flip direction
blip.play()
if direction == 1:
arc(x, 220, radius, radius, 0.52, 5.76) # Face right
else:
arc(x, 220, radius, radius, 3.67, 8.9) # Face left
mode=Python
mode.id=jycessing.mode.PythonMode
add_library('minim')
add_library('peasycam')
cylindrical, isPlaying, isMute = False, False, False
pts, radius, latheRadius, segments = 20, 1, 300, 128
vertices, vertices2 = [[PVector() for e in range(pts+1)] for e in range(2)]
def setup():
global song, fftLin, fftLog, cam
size(1200, 800, P3D)
frameRate(1000)
smooth(8)
cam = PeasyCam(this, 600)
cam.setMaximumDistance(600)
cam.rotateX(-PI/2.4)
perspective(60 * DEG_TO_RAD, width/float(height), 2, 6000)
minim = Minim(this)
song = minim.loadFile("multilong2_sonified.mp3")
fftLin, fftLog = [FFT(song.bufferSize(), song.sampleRate()) for e in range(2)]
fftLin.linAverages(30), fftLog.logAverages(22, 3)
def draw():
background(225, 250, 255)
lights()
ambientLight(255,153,39)
directionalLight(255,43,192, 1, 0, 0)
pointLight(255,215,60, width, height/2, 0)
rotateZ(frameCount*PI/560)
fill(255,82,139)
noStroke()
song.play() if isPlaying else song.pause()
song.mute() if isMute else song.unmute()
fftLin.forward(song.mix)
fftLog.forward(song.mix)
latheAngle = 0
for s in range(segments):
angle = 0
beginShape(QUAD_STRIP)
for i, v in enumerate(vertices2):
division = 1 if s%2 == 0 else 6
step = s*2 # select 1 freq every 2 freq (up to 256 out of 512)
c_step = (s*2)+((s%2)*2) # select 1 freq every 4 freq (up to 256 freq out of 512)
if cylindrical: sscale = map(fftLin.getBand(c_step)*((s+10)/10), 0, 35, .8, 35)
else: sscale = map(fftLin.getBand(step)*((s+10)/10), 0, 30, .8, 24)
sscale = constrain(sscale, 0, 50)
vertices[i].x = latheRadius + sin(radians(angle)) * radius * sscale
vertices[i].z = cos(radians(angle)) * radius * sscale
angle+=360.0/pts
vertex(v.x, v.y, v.z)
v.x = cos(radians(latheAngle)) * vertices[i].x
v.y = sin(radians(latheAngle)) * vertices[i].x
v.z = vertices[i].z
vertex(v.x, v.y, v.z)
latheAngle += (360.0+260)/(segments*6/division) if cylindrical else 360.0/segments
endShape()
cam.beginHUD()
text("'p' = PLAY/PAUSE", 20, 30)
text("'r' = REPLAY", 20, 50)
text("'m' = MUTE", 20, 70)
text("'c' = MODE", 20, 90)
cam.endHUD()
def keyPressed():
global isPlaying, cylindrical, isMute
if key == 'p': isPlaying = not isPlaying
if key == 'm': isMute = not isMute
if key == 'c': cylindrical = not cylindrical
if key == 'r': song.rewind()
"""
ES - Distribucion aleatoria uniforme sobre la superficie de una esfera.
EN - Uniform random distribution on the surface of a sphere.
"""
CUANTOS = 16000 # how many
LISTA = [] # list
RADIO = 200 # radius
rx = 0
ry = 0
def setup():
global RADIO, LISTA
size(1024, 768, P3D)
RADIO = height / 3.5
for _ in range(CUANTOS):
LISTA.append(Pelo())
noiseDetail(3)
def draw():
global rx, ry
background(255)
rxp = (mouseX - (width / 2)) * 0.005
ryp = (mouseY - (height / 2)) * 0.005
rx = rx * 0.9 + rxp * 0.1
ry = ry * 0.9 + ryp * 0.1
translate(width / 2, height / 2)
rotateY(rx)
rotateX(ry)
fill(0)
noStroke()
sphere(RADIO)
for pelo in LISTA:
pelo.dibujar()
class Pelo():
"""A hair"""
def __init__(self):
self.z = random(-RADIO, RADIO)
self.phi = random(TWO_PI)
self.largo = random(1.15, 1.2)
self.theta = asin(self.z / RADIO)
def dibujar(self):
"""Draw"""
off = (noise(millis() * 0.0005, sin(self.phi)) - 0.5) * 0.3
offb = (noise(millis() * 0.0007, sin(self.z) * 0.01) - 0.5) * 0.3
thetaff = self.theta + off
phff = self.phi + offb
x = RADIO * cos(self.theta) * cos(self.phi)
y = RADIO * cos(self.theta) * sin(self.phi)
z = RADIO * sin(self.theta)
xo = RADIO * cos(thetaff) * cos(phff)
yo = RADIO * cos(thetaff) * sin(phff)
zo = RADIO * sin(thetaff)
xb = xo * self.largo
yb = yo * self.largo
zb = zo * self.largo
strokeWeight(1)
beginShape(LINES)
stroke(0)
vertex(x, y, z)
stroke(200, 150)
vertex(xb, yb, zb)
endShape()
THE_SEED = None
n_particles = 5000
n_particle_sets = 8
particle_sets = []
# initial distribution of particles
sigmax = 210
sigmay = 180
def setup():
global THE_SEED, particle_sets
size(1000,750)
THE_SEED = floor(random(9999999))
randomSeed(THE_SEED)
noFill()
background(97,0,255)
# initialize the particle sets
for j in range(n_particle_sets):
ps = []
for i in range(n_particles):
ps.append(Particle(width/2 + sigmax*randomGaussian(),
height/2 + sigmay*randomGaussian(),
random(TWO_PI)))
particle_sets.append(ps)
def keyPressed():
if (keyCode == 80):
filename_png = "img/trace_{}.png".format(THE_SEED)
save(filename_png)
def draw():
stroke(10)
strokeWeight(0.7)
smooth()
global particle_sets
for index, ps in enumerate(particle_sets):
for p in ps:
p.update(index)
p.display(index)
class Particle(object):
def __init__(self, x, y, angle):
self.pos = PVector(x,y)
self.angle = angle # direction of travel, at construction is random
self.val = 0
self.altitude = 0
def update(self, index):
# update x and y coordinates according to phi (direction of travel)
speed = 1
self.pos.x += speed * cos(self.angle)
self.pos.y += speed * sin(self.angle)
# if particle has wandered off canvas, replace it in the middle somewhere
if (self.pos.x < 0 or self.pos.x > width or
self.pos.y < 0 or self.pos.y > height):
self.pos.x = width/2 + sigmax*randomGaussian()
self.pos.y = height/2 + sigmay*randomGaussian()
self.angle = random(TWO_PI)
# we want to be able to make the noise field symmetric, so we
# create n vector, which points to particle from center of canvas
## NOISE LANDSCAPE 1 (no perspective)
# nmagx = 1.8 # scales the ZOOM
# nmagy = 1.8
# nx = nmagx * map(self.pos.x, 0, width, -1, 1)
# ny = nmagy * map(self.pos.y, 0, height, -1, 1)
## NOISE LANDSCAPE 2 (some perspective)
# the height on the canvas scales the zoom level
# higher up is further away
nx = map(self.pos.y, 0, height + 100, 3, 0.5) * map(self.pos.x, 0, width, -1, 1)
ny = 2 * map(self.pos.y, 0, height + 100, 3, 0.5) * map(self.pos.y, 0, width, -1, 1)
nmag = 1
n = PVector(nx,ny)
noise_field_val = nmag * noise(n.x - 73, n.y + 825)
self.altitude = noise_field_val
# perlin noise is always between 0 and 1, with most values around 0.5
# scaled offset due to the particle set
sc = 0.045 # MANIPULATE TO CHANGE APPEARANCE
set_idx = index - float(n_particle_sets) / float(2)
noise_offset = sc * set_idx
# so each particle set is offset by a different amount, meaning that they'll
# each get displayed at different contours
nval = (noise_field_val + noise_offset) % 1
# adjust angle of travel based on nval
self.angle += 3 * map(nval, 0, 1, -1, 1)
self.val = nval
def display(self, index):
if self.val > 0.482 and self.val < 0.518:
pushMatrix()
# adjust y position based on particle's altitude
# self.altitude is always between 0 and 1
# want the height differences to be more apparent near bottom of the canvas
# but increase dyb too much and the particles will not go below the bottom of the canvas
dya = 60
dyb = 50
dy = dya - self.altitude * dyb * map(self.pos.y, 0, height + 100, 1, 4)
translate(self.pos.x, self.pos.y + dy)
#rotate(self.angle)
point(0,0)
popMatrix()
mode=Python
mode.id=jycessing.mode.PythonMode
num_lines = 100
points_per_line = 100
window_buffer = 0
# noise params
noise_mag = 200
xoff = random(10000)
yoff = random(10000)
zoff = random(10000)
dxoff = 0.06 # change in xoff between vertices\
dxoff_t = 0.01 # change in xoff over time (produces scrolling)
dyoff = 0.07 # change in yoff between lines
dzoff = 0.01
noiseDetail(2, .4)
def setup():
size(800,800)
noFill()
stroke(255)
strokeWeight(3)
#noLoop()
def draw():
background(0)
y_ = getY_()
x_ = getX_()
drawLines(x_,y_)
def getY_():
inc = ceil(float(height - 2 * window_buffer) / (num_lines + 1))