def main(): from modules.boids import B from sand import Sand from fn import Fn fn = Fn(prefix='./res/', postfix='.png') sand = Sand(SIZE) sand.set_bg(BACK) sand.set_rgba(FRONT) b = B(INIT_NUM, SIZE, STP) for itt in range(1000000): b.step(separation=SEPARATION, cohesion=COHESION, alignment=ALIGNMENT) xy = b.xy for i, nearby in enumerate(b.get_nearby()): if not nearby: continue start = zeros((len(nearby), 2)) start[:, 0] = xy[i, 0] start[:, 1] = xy[i, 1] stop = xy[nearby, :] g = GRAINS * ones(len(nearby), 'int') sand.paint_strokes(start, stop, g) if not itt % DRAW_ITT: name = fn.name() print(itt, name) sand.write_to_png(name)
def main(): import sys, traceback from fn import Fn from sand import Sand sand = Sand(SIZE) sand.set_bg_from_rgb_array(img) sand.set_rgba(FRONT) fn = Fn(prefix='./res/', postfix='.png') si = spline_iterator() while True: try: itt, xy = next(si) # sand.distort_dots_swap(xy) sand.distort_dots_wind(xy) if not itt%5000: print(itt) sand.write_to_png(fn.name()) except Exception: sand.write_to_png(fn.name()) traceback.print_exc(file=sys.stdout) return
def main(): parser = argparse.ArgumentParser() parser.add_argument('--4-int-colour-list', nargs='+', type=int) import sys, traceback from fn import Fn from sand import Sand rgba_list = parser.parse_args()._get_args() sand = Sand(SIZE) sand.set_bg(BG) sand.set_rgba(rgba_list) fn = Fn(prefix='./res/', postfix='.png') si = spline_iterator() while True: try: itt, xy = next(si) sand.paint_dots(xy) if not itt % (5000 * GRID_Y): print(itt) sand.write_to_png(fn.name(), GAMMA) except Exception as e: print(e) sand.write_to_png(fn.name(), GAMMA) traceback.print_exc(file=sys.stdout)
def main(): from dunes import Dunes from sand import Sand from fn import Fn from time import time from modules.helpers import get_initial_rnd initial = get_initial_rnd(SIZE, n=4) bw = zeros(initial.shape,'float') dunes = Dunes(initial, DELTA, PROB) sand = Sand(SIZE) sand.set_rgba(FRONT) fn = Fn(prefix='./res/', postfix='.png') try: while True: t0 = time() itt = dunes.steps(LEAP) print(itt, time()-t0) dunes.get_normalized_sand_limit(bw, 10) # bw *= 0.8 # sand.set_bg_from_bw_array(bw) # dunes.get_shadow(shadow) # rgb = dstack((bw,bw,shadow)) # sand.set_bg_from_rgb_array(rgb) sand.set_bg_from_bw_array(bw) name = fn.name() sand.write_to_png(name) except KeyboardInterrupt: pass
def main(): import sys, traceback from fn import Fn from sand import Sand from modules.helpers import get_colors sand = Sand(SIZE) sand.set_bg(BG) sand.set_rgba(FRONT) colors = get_colors('../colors/dark_cyan_white_black2.gif') nc = len(colors) fn = Fn(prefix='./res/', postfix='.png') si = spline_iterator() while True: try: itt, w, xy = next(si) rgba = colors[w%nc] + [0.0005] sand.set_rgba(rgba) sand.paint_dots(xy) if not itt%(40000): print(itt) sand.write_to_png(fn.name(), GAMMA) except Exception as e: print(e) sand.write_to_png(fn.name(), GAMMA) traceback.print_exc(file=sys.stdout)
def main(): import sys, traceback from fn import Fn from sand import Sand from modules.helpers import get_colors sand = Sand(SIZE) sand.set_bg(BG) sand.set_rgba(FRONT) colors = get_colors('../colors/dark_cyan_white_black2.gif') nc = len(colors) fn = Fn(prefix='./res/', postfix='.png') si = spline_iterator() while True: try: itt, w, xy = next(si) rgba = colors[w % nc] + [0.0005] sand.set_rgba(rgba) sand.paint_dots(xy) if not itt % (40000): print(itt) sand.write_to_png(fn.name(), GAMMA) except Exception as e: print(e) sand.write_to_png(fn.name(), GAMMA) traceback.print_exc(file=sys.stdout)
def main(): from modules.fracture import Fracture from numpy.random import random from numpy import linspace from iutils.random import darts_rect from time import time from numpy.random import seed from sand import Sand from fn import Fn fn = Fn(prefix='./res/') sand = Sand(SIZE) sand.set_bg(BACK) sand.set_rgba(FRONT) seed(1) start = time() initial_sources = darts_rect( SOURCES, 0.5, 0.5, 1.0-2.0*EDGE, 1.0-2.0*EDGE, FRAC_STP ) F = Fracture( FRAC_DOT, FRAC_DST, FRAC_STP, initial_sources=initial_sources, zone_leap=ZONE_LEAP, nmax=NMAX ) for _ in range(INIT_FRACS): F.blow(1, EDGE+random((1, 2))*(1.0-2.0*EDGE)) while True: res = F.step() F.frac_front(factor=SPAWN_FACTOR, angle=SPAWN_ANGLE, dbg=DBG) if not F.itt % ITT or not res: print('itt', F.itt, 'num', F.num, 'fnum', F.fnum, 'anum', F.anum, 'time', time()-start) if not res: print('done') break show(sand, F) name = fn.name()+'.png' print(name) sand.write_to_png(name)
def __init__(self, ): from fn import Fn from os import sep self.fn = Fn() self.repo = self.fn.repo self._store = self.fn.top_level + sep + '.genlog' self.__ensure_store() self.size = 1024
def main(): from sand import Sand from fn import Fn sand = Sand(SIZE) sand.set_rgba(FRONT) fn = Fn(prefix='./res/', postfix='.png') make_creatures(sand) name = fn.name() sand.write_to_png(name, GAMMA)
def main(): sand = Sand(SIZE) sand.set_bg(BG) sand.set_rgba(FRONT) fn = Fn(prefix='./res/', postfix='.png') for index, spline in enumerate(spline_iterator()): sand.paint_dots(spline) if not index % SIZE: print('Iteration {}'.format(index)) sand.write_to_png(fn.name(), GAMMA)
def main(): from sand import Sand from fn import Fn sand = Sand(SIZE) sand.set_bg(BACK) sand.set_rgba(FRONT) fn = Fn(prefix='./res/', postfix='.png') write(sand) # sand.set_bg(bw) name = fn.name() sand.write_to_png(name, GAMMA)
def main(): from sand import Sand from fn import Fn from iutils.ioOBJ import export_2d as export sand = Sand(SIZE) sand.set_rgba(FRONT) fn = Fn(prefix='./res/') vertices, lines = make_creatures(sand) name = fn.name() sand.write_to_png(name + '.png', GAMMA) export('scribbles', name + '.2obj', verts=vertices, lines=lines)
def get_show(dm): np_coord = zeros((NMAX, 6), 'float') # from modules.colors import cyan from fn import Fn fn = Fn(prefix='./res/') def show(render): render.clear_canvas() num = dm.np_get_triangles_coordinates(np_coord) render_triangle = render.triangle # render_circle = render.circle for f, vv in enumerate(np_coord[:num, :]): render.set_front(FRONT) render_triangle(*vv, fill=False) # rad = ONE*3 # render.set_front(cyan) # render_circle(vv[0], vv[1], rad, fill=True) # render_circle(vv[2], vv[3], rad, fill=True) # render_circle(vv[4], vv[5], rad, fill=True) name = fn.name() + '.png' render.write_to_png(name) return show
def main(): from modules.fracture import Fracture from iutils.render import Animate from numpy.random import random from iutils.random import darts_rect from time import time from fn import Fn fn = Fn(prefix='./res/') start = time() initial_sources = darts_rect(SOURCES, 0.5, 0.5, 1.0 - 2.0 * EDGE, 1.0 - 2.0 * EDGE, FRAC_STP) F = Fracture(FRAC_DOT, FRAC_DST, FRAC_STP, initial_sources=initial_sources, zone_leap=ZONE_LEAP, nmax=NMAX) for _ in range(20): F.blow(1, EDGE + random((1, 2)) * (1.0 - 2.0 * EDGE)) def wrap(render): print('itt', F.itt, 'num', F.num, 'fnum', F.fnum, 'anum', F.anum, 'time', time() - start) res = F.step() n = F.frac_front(factor=SPAWN_FACTOR, angle=SPAWN_ANGLE, dbg=DBG) if n > 0: print('new fracs: {:d}'.format(n)) if not F.itt % DRAW_ITT: show(render, F) return res render = Animate(SIZE, BACK, FRONT, wrap) render.set_line_width(LINEWIDTH) render.start() name = fn.name() render.write_to_png(name + '.png') export(name + '.2obj', F)
def main(): from iutils.render import Animate from differentialLine import DifferentialLine from modules.helpers import get_exporter # from modules.show import show_closed # from modules.show import show_detail from modules.show import show DF = DifferentialLine(NMAX, FARL*2, NEARL, FARL, PROCS) angles = sorted(random(INIT_NUM)*TWOPI) DF.init_circle_segment(MID,MID,INIT_RAD, angles) from fn import Fn fn = Fn(prefix='./res/') exporter = get_exporter( NMAX, { 'nearl': NEARL, 'farl': FARL, 'stp': STP, 'size': SIZE, 'procs': PROCS } ) def wrap(render): global i # animation stops when res is False res = steps(DF) ## if fn is a path each image will be saved to that path ## render outline num = DF.np_get_edges_coordinates(np_edges) if not i % 100: show(render,np_edges[:num,:], None, r=1.3*ONE) # render.write_to_png(fn.name()) exporter( DF, fn.name()+'.2obj' ) ## render solid # num = DF.get_sorted_vert_coordinates(np_verts) #show_closed(render,np_verts[:num,:],fn) i += 1 return res render = Animate(SIZE, BACK, FRONT, wrap) render.start()
def get_wrap(dl, colors, limit, prob, render_steps=10, export_steps=10): from fn import Fn from time import time # from iutils.ioOBJ import export_2d as export t0 = time() fn = Fn(prefix='./res/') def wrap(render): dl.step() dl.spawn_curl(limit=limit, prob=prob) # dl.spawn_normal(limit=limit, prob=prob) if dl.itt % render_steps == 0: print('itt', dl.itt, 'num', dl.num, 'time', time() - t0) num = dl.num render.clear_canvas() render.set_line_width(2 * dl.one) xy = dl.xy[:num, :] links = dl.links[:num, :] # line = dl.get_line() render.ctx.set_source_rgba(*colors['front']) ## dots # for x,y in xy: # render.circle(x, y, dl.one, fill=True) ## edges for i in range(num): b = links[i, 1] render.line(xy[i, 0], xy[i, 1], xy[b, 0], xy[b, 1]) ## connected edges # remapped = xy[line,:] # render.ctx.move_to(remapped[0,0], remapped[0,1]) # for x in remapped[:,:]: # render.ctx.line_to(x[0], x[1]) # render.ctx.fill() if dl.itt % export_steps == 0: name = fn.name() render.write_to_png(name + '.png') # export('differential-line-cuda', name+'.2obj', xy, lines=[line]) return True return wrap
def main(): from iutils.render import Animate from modules.fracture import Fractures # from dddUtils.ioOBJ import export_2d as export from fn import Fn fn = Fn(prefix='./res/', postfix='.2obj') F = Fractures(INIT_NUM, INIT_RAD, SOURCE_DST, FRAC_DOT, FRAC_DST, FRAC_STP, FRAC_SPD, FRAC_DIMINISH, FRAC_SPAWN_DIMINISH, domain='rect') print(F.sources.shape) # uniform square distribution from numpy.random import random for _ in range(5): F.blow(2, random(size=2)) # uniform circular distribution # for _ in xrange(5): # F.blow(3, random_uniform_circle(INIT_RAD, num=1)) def wrap(render): if not F.i % 20: show(render, F) # vertices, paths = F.get_vertices_and_paths() # export('fractures', fn.name(), vertices, lines=paths) render.write_to_png(fn.name() + '.png') F.print_stats() res = F.step(dbg=False) n = F.spawn_front(factor=SPAWN_FACTOR, angle=SPAWN_ANGLE) print('spawned: {:d}'.format(n)) # fn = './asdf_{:04d}.png'.format(F.i) # render.write_to_png(fn) # if not res: # vertices, paths = F.get_vertices_and_paths() # export('fractures', fn.name(), vertices, lines=paths) return res render = Animate(SIZE, BACK, FRONT, wrap) render.start()
def main(): from modules.sand import Sand from render.render import Animate from fn import Fn fn = Fn(prefix='./res/', postfix='.png') sand = Sand( SIZE, INUM, NOISE_STP, fn ) ## radial lines # n = 50 # for i, snum in enumerate(linspace(5,100,n).astype('int')): # a = ones(snum, 'float') * i/n*TWOPI # r = sorted(random(size=(snum, 1))*RAD) # xy = 0.5+column_stack((cos(a), sin(a)))*r # sand.init(xy) ## horizontal lines # n = 50 # for i, snum in enumerate(linspace(5,100,n).astype('int')): # x = linspace(EDGE, 1.0-EDGE, snum) # y = ones(snum)*(EDGE + (i/(n-1.0))*2*RAD) # xy = column_stack((x,y)) # sand.init(xy) ## messy spheres # n = 50 # for i, snum in enumerate(linspace(5,100,n).astype('int')): # a = sorted(random(snum)*TWOPI) # r = ones((snum, 1))*(EDGE + (i/(n-1.0))*(RAD-EDGE)) # xy = 0.5+column_stack((cos(a), sin(a)))*r # sand.init(xy) ## tidy spheres n = 50 for i, snum in enumerate(linspace(20,80,n).astype('int')): a = linspace(0,TWOPI, snum) r = ones((snum, 1))*(EDGE + (i/(n-1.0))*(RAD-EDGE)) xy = 0.5+column_stack((cos(a), sin(a)))*r sand.init(xy) render = Animate(SIZE, BACK, FRONT, sand.wrap) render.set_line_width(sand.one) render.transparent_pix() render.set_front(FRONT) render.start()
def __init__( self, ): from fn import Fn from os import sep self.fn = Fn() self.repo = self.fn.repo self._store = self.fn.top_level + sep + '.genlog' self.__ensure_store() self.size = 1024
def main(): fn = Fn() for _ in range(20): print(fn.name()) sleep(0.01) print() fn = Fn() print(fn.name()) print() fn = Fn(prefix='/some/path/', postfix='.txt', git_sha_size=10) print(fn.name()) # note: you can't override the prefix print(fn.name(postfix='')) print(fn.name(postfix='.png')) print(fn.name(milli=False)) print(fn.name(milli=True)) print()
def main(): import sys, traceback from fn import Fn from sand import Sand sand = Sand(SIZE) sand.set_bg(BG) sand.set_rgba(FRONT) fn = Fn(prefix='./res/', postfix='.png') si = spline_iterator() while True: try: itt, xy = next(si) sand.paint_dots(xy) if not itt % (500 * GRID_Y): print(itt) sand.write_to_png("./res/currenrt.png", GAMMA) except Exception as e: print(e) sand.write_to_png(fn.name(), GAMMA) traceback.print_exc(file=sys.stdout)
def __init__(self, con='localhost:6379', chan='erosion', resolution=1000, gsamples=100000, show=False, path='./', verbose=False): self.con = str(con) host, port = _parse_con(self.con) self.host = host self.port = port self.chan = str(chan) self.imsize = int(resolution) self.gsamples = int(gsamples) self.verbose = verbose self.show = show self.red = None self.count = 0 self.desert = None self.fn = Fn(prefix=path, postfix='.png')
def main(): import sys, traceback from fn import Fn from sand import Sand sand = Sand(SIZE) sand.set_bg(BG) sand.set_rgba(FRONT) fn = Fn(prefix='./res/', postfix='.png') si = spline_iterator() while True: try: itt, xy = next(si) sand.paint_dots(xy) if not itt%(500*GRID_Y): print(itt) sand.write_to_png(fn.name(), GAMMA) except Exception as e: print(e) sand.write_to_png(fn.name(), GAMMA) traceback.print_exc(file=sys.stdout)
def get_wrap(dl, colors, render_steps=10, export_steps=10): from fn import Fn # from dddUtils.ioOBJ import export_2d as export fn = Fn(prefix='./res/') def wrap(render): dl.step() dl.spawn(ratio=0.1, age=1000) if not dl.itt % export_steps: print(('itt', dl.itt, 'num', dl.num)) num = dl.num render.clear_canvas() vertices, edges = dl.link_export() render.ctx.set_source_rgba(*colors['purple']) for a, b in edges: render.line( vertices[a, 0], vertices[a, 1], vertices[b, 0], vertices[b, 1] ) render.ctx.set_source_rgba(*colors['front']) for i in range(num): render.circle( vertices[i, 0], vertices[i, 1], dl.node_rad*0.6, fill=True ) if not dl.itt % export_steps: name = fn.name() render.write_to_png(name+'.png') # export('lattice', name+'.2obj', vertices, edges=edges) write_svg(name, vertices, edges) return True return wrap
def main(): import sys, traceback from fn import Fn from sand import Sand from modules.helpers import get_colors sand = Sand(SIZE) sand.set_bg(BG) sand.set_rgba(FRONT) colors = get_colors('colors/dark_cyan_white_black.gif') nc = len(colors) fn = Fn(prefix='./res/', postfix='.png') si = spline_iterator() while True: try: itt, w, xy = next(si) rgba = colors[w%nc] + [0.005] sand.set_rgba(rgba) sand.paint_dots(xy) if not itt%(50): print("ci:"+str(itt)) if not itt%(5000): if os.path.isfile("./res/dump1.png"): print("printing to dump2:"+str(itt)) sand.write_to_png("./res/dump2.png", GAMMA) os.remove("./res/dump1.png") else: print("printing to dump1:"+str(itt)) sand.write_to_png("./res/dump1.png", GAMMA) if os.path.isfile("./res/dump2.png"): os.remove("./res/dump2.png") except Exception as e: print(e) sand.write_to_png("./res/current.png", GAMMA) traceback.print_exc(file=sys.stdout)
def main(): from differentialMesh3d import DifferentialMesh3d from modules.ioOBJ import load_move_scale as load_obj from modules.random import random_unit_vec from modules.geometry import get_show_geometry from modules.utils import get_seed_selector from modules.utils import print_stats from modules.utils import get_exporter from fn import Fn fn = Fn(prefix='./res/', postfix='.obj') DM = DifferentialMesh3d( nmax=NMAX, zonewidth=ZONEWIDTH, nearl=NEARL, farl=FARL, procs=PROCS ) data = load_obj( OBJ, s=SCALE, mx=[0.5] * 3 ) info = DM.initiate_faces(list(data['vertices']), list(data['faces'])) if info['min_edge'] < NEARL: print('all edges are too short. try scaling up initial size.') return seed_selector = get_seed_selector(DM, SEEDTYPE, SEEDRATIO) noise = random_unit_vec(DM.get_vnum(), STP*100.) DM.position_noise(noise, scale_intensity=-1) DM.optimize_edges(SPLIT_LIMIT, FLIP_LIMIT, FLIP_CURVATURE) for he in range(DM.get_henum()): DM.set_edge_intensity(he, 1.0) show_geometry = get_show_geometry(DM, NMAX) def geometry_generator(): seeds = seed_selector() i = 0 k = 0 box = array((-1, -1, -1, 1, 1), 'float') while True: i += 1 for _ in range(SPEEDUP): k += 1 DM.optimize_position( REJECT, ATTRACT, DIMINISH, SMOOTH, scale_intensity=1 ) DM.optimize_edges(SPLIT_LIMIT, FLIP_LIMIT, FLIP_CURVATURE) if len(seeds) > 0: DM.set_vertices_intensity(seeds, 1.0) if k%SEED_FREQ == 0: seeds = seed_selector() print_stats(k, DM, meta='alive v: {:d}'.format(len(seeds))) box = show_geometry() yield box from view3d import View3d v3d = View3d( size=SCREEN_SIZE, initial_scale=INITIAL_SCALE, autorotate=AUTOROTATE, save_img=SAVE_IMG ) v3d.start(geometry_generator) export = get_exporter(DM, fn, NMAX) export()
class ErosionWorker(): def __init__(self, con='localhost:6379', chan='erosion', resolution=1000, gsamples=100000, show=False, path='./', verbose=False): self.con = str(con) host, port = _parse_con(self.con) self.host = host self.port = port self.chan = str(chan) self.imsize = int(resolution) self.gsamples = int(gsamples) self.verbose = verbose self.show = show self.red = None self.count = 0 self.desert = None self.fn = Fn(prefix=path, postfix='.png') def __enter__(self): print('>> running erosion worker.') print('>> listening at: {:s}/{:s}.'.format(self.con, self.chan)) print('>> resolution: ({:d} {:d}).'.format(self.imsize, self.imsize)) print('>> gsamples: ', self.gsamples) print('>> show: ', self.show) self.red = Redis(self.host, self.port) self.desert = Desert(self.imsize, show=self.show, gsamples=self.gsamples, verbose=self.verbose).init() return self def __exit__(self, _type, val, tb): self.save() print('>> exited. total: {:d}'.format(self.count)) del self.red del self.desert def save(self): self.desert.save(self.fn.name()) if self.show and self.desert._gupdated: self.desert.show() def clear_chan(self): l = self.red.llen(self.chan) print('>> cleared: {:d}'.format(l)) self.red.delete(self.chan) def _show_test(self, j): print('** rec test: {:s}'.format(j['_data']['time'])) def _erosion_cmd(self, _type, j): if _type == '_test': self._show_test(j) elif _type == '_init': self.desert.init( fg=Rgba.from_json(j['_data']['fg']), bg=Rgba.from_json(j['_data']['bg']), ) elif _type == '_save': self.save() else: print('## warn: erosion. unknown cmd: {:s}'.format(_type)) def listen(self): while True: try: _, v = self.red.blpop(self.chan) self.count += 1 j = loads(v.decode('utf8')) _type = j['_type'] if _type.startswith('_'): self._erosion_cmd(_type, j) continue try: p = type_router(j) self.desert.gdraw([p]) if self.show and self.desert._gupdated: self.desert.show() except Exception as e: print('## err: erosion:\n{:s}'.format(str(j))) except KeyboardInterrupt: return
def main(): from fn import Fn fn = Fn() for i in range(20): print(fn.name()) sleep(0.1) print() fn = Fn(append_inc=True) print(fn.name()) print(fn.current) # overwritten when you call fn.name() print(fn.name()) print(fn.current) print() fn = Fn(inc_size=3, append_inc=True) for i in range(20): print(fn.name()) sleep(0.1) print() # you can't override the prefix fn = Fn(delimit='.', prefix='/some/path/', postfix='.txt', git_sha_size=10) print(fn.name()) print(fn.name(postfix='')) print(fn.name(postfix='.png')) print()
def main(): from time import time from itertools import count from render.render import Render from modules.helpers import print_stats from modules.show import show # from modules.show import show_closed from differentialLine import DifferentialLine from modules.helpers import get_exporter from numpy.random import random from fn import Fn DF = DifferentialLine(NMAX, FARL*2, NEARL, FARL, PROCS) fn = Fn(prefix='./res/') exporter = get_exporter( NMAX, { 'nearl': NEARL, 'farl': FARL, 'stp': STP, 'size': SIZE, 'procs': PROCS } ) render = Render(SIZE, BACK, FRONT) render.ctx.set_source_rgba(*FRONT) render.ctx.set_line_width(LINEWIDTH) angles = sorted(random(INIT_NUM)*TWOPI) DF.init_circle_segment(MID,MID,INIT_RAD, angles) t_start = time() for i in count(): DF.optimize_position(STP) # spawn_curl(DF,NEARL) spawn(DF, NEARL, 0.03) if i % STAT_ITT == 0: print_stats(i,time()-t_start,DF) if i % EXPORT_ITT == 0: name = fn.name() num = DF.np_get_edges_coordinates(np_edges) show(render,np_edges[:num,:],name+'.png') exporter( DF, name+'.2obj' )
class Genlog(object): def __init__(self, ): from fn import Fn from os import sep self.fn = Fn() self.repo = self.fn.repo self._store = self.fn.top_level + sep + '.genlog' self.__ensure_store() self.size = 1024 def __enter__(self): return self def __exit__(self, type, value, traceback): return False def __ensure_store(self): from os import stat from os import mkdir try: stat(self._store) except Exception: mkdir(self._store) def __copy_file(self, recent): from shutil import copyfile from os import sep for t in recent: if t.endswith('.png'): target = t.split(sep)[-1] full_target = self._store + sep + target copyfile(t, full_target) return full_target return False def __thumbnail(self, recent): try: from PIL import Image except Exception: import Image thumb = self.__copy_file(recent) if thumb: n = self.size img = Image.open(thumb) img.thumbnail((n, n)) img.save(thumb) return thumb def __get_author(self): from os import getenv email = getenv('GENLOG_USER_EMAIL', '') if len(email) > 0: return email return None def __commit_all(self, thumb, m): from os import sep from git import Actor info_file = thumb.split(sep)[-1] self.repo.git.add('-A') self.repo.git.add(thumb, '-f') email = self.__get_author() a = None if email: a = Actor('genlog', email) if m: s = m else: s = ':genlog:' s += '\n\n:thumb:{:s}'.format(info_file) self.repo.index.commit(s, committer=a, author=a) def log(self, d, m): if not d: d = '.' recent = self.fn.recent(d) if not recent: return None thumb = self.__thumbnail(recent) self.__commit_all(thumb, m)
def main(): from fn import Fn fn = Fn(prefix='./res/').name() + '.png' copy_file('./res/sample.png', fn)
class Genlog(object): def __init__( self, ): from fn import Fn from os import sep self.fn = Fn() self.repo = self.fn.repo self._store = self.fn.top_level + sep + '.genlog' self.__ensure_store() self.size = 1024 def __enter__(self): return self def __exit__(self ,type, value, traceback): return False def __ensure_store(self): from os import stat from os import mkdir try: stat(self._store) except Exception: mkdir(self._store) def __copy_file(self, recent): from shutil import copyfile from os import sep for t in recent: if t.endswith('.png'): target = t.split(sep)[-1] full_target = self._store+sep+target copyfile(t, full_target) return full_target return False def __thumbnail(self, recent): try: from PIL import Image except Exception: import Image thumb = self.__copy_file(recent) if thumb: n = self.size img = Image.open(thumb) img.thumbnail((n, n)) img.save(thumb) return thumb def __get_author(self): from os import getenv email = getenv('GENLOG_USER_EMAIL', '') if len(email)>0: return email return None def __commit_all(self, thumb, m): from os import sep from git import Actor info_file = thumb.split(sep)[-1] self.repo.git.add('-A') self.repo.git.add(thumb, '-f') email = self.__get_author() a = None if email: a = Actor('genlog', email) if m: s = m else: s = ':genlog:' s += '\n\n:thumb:{:s}'.format(info_file) self.repo.index.commit(s, committer=a, author=a) def log(self, d, m): if not d: d = '.' recent = self.fn.recent(d) if not recent: return None thumb = self.__thumbnail(recent) self.__commit_all(thumb, m)
def main(): from iutils.render import Animate from differentialLine import DifferentialLine from fn import Fn from modules.show import sandstroke from modules.show import dots DF = DifferentialLine(NMAX, FARL * 2, NEARL, FARL, PROCS) ## arc # angles = sorted(random(INIT_NUM)*pi*1.5) # xys = [] # for a in angles: # x = 0.5 + cos(a)*0.06 # y = 0.5 + sin(a)*0.06 # xys.append((x,y)) # DF.init_line_segment(xys, lock_edges=1) ## vertical line #xx = sorted(0.45+0.1*random(INIT_NUM)) #yy = MID+0.005*(0.5-random(INIT_NUM)) #xys = [] #for x,y in zip(xx,yy): #xys.append((x,y)) #DF.init_line_segment(xys, lock_edges=1) # diagonal line # yy = sorted(0.3+0.4*random(INIT_NUM)) # xx = 0.3+linspace(0,0.4,num=INIT_NUM) # xys = [] # for x,y in zip(xx,yy): # xys.append((x,y)) # DF.init_line_segment(xys, lock_edges=1) angles = sorted(random(INIT_NUM) * TWOPI) DF.init_circle_segment(MID, MID, FARL * 0.2, angles) fn = Fn(prefix='./res/', postfix='.png') def wrap(render): global np_coords global np_vert_coords global grains ## if fn is a path each image will be saved to that path if not render.steps % 3: f = fn.name() else: f = None grains += (-1)**floor(2 * random()) print(grains) if grains < 0: grains = 0 res = steps(DF) render.set_front(FRONT) coord_num = DF.np_get_edges_coordinates(np_coords) sandstroke(render, np_coords[:coord_num, :], grains, f) if not random() < 0.1: vert_num = DF.np_get_vert_coordinates(np_vert_coords) dots(render, np_vert_coords[:vert_num, :], None) return res render = Animate(SIZE, BACK, FRONT, wrap) render.start()
def main(): from fn import Fn from modules.differentialLattice import DifferentialLattice from modules.helpers import get_colors from modules.helpers import spawn_circle from numpy import array from numpy import cumsum from numpy import sqrt from numpy import linspace from numpy import sort from numpy import ones from numpy.random import random from numpy.random import seed from sand import Sand from numpy import pi from numpy import sin from numpy import cos TWOPI = pi*2.0 fn = Fn(prefix='./res/') size = 512 one = 1.0/size threads = 512 zone_leap = 512 grains = 20 init_num = 20 stp = one*0.03 spring_stp = 5 reject_stp = 0.1 cohesion_stp = 1.0 max_capacity = 30 node_rad = 4*one spring_reject_rad = node_rad*1.9 spring_attract_rad = node_rad*2.0 outer_influence_rad = 10.0*node_rad link_ignore_rad = 0.5*outer_influence_rad colors = get_colors('../colors/black_t.gif') # colors = get_colors('../colors/ir.jpg') nc = len(colors) sand = Sand(size) sand.set_bg(BACK) sand.set_rgba(FRONT) DL = DifferentialLattice( size, stp, spring_stp, reject_stp, cohesion_stp, max_capacity, node_rad, spring_reject_rad, spring_attract_rad, outer_influence_rad, link_ignore_rad, threads=threads, zone_leap=zone_leap, nmax=50000000 ) spawn_circle(DL, init_num, xy=array([[0.5, 0.5]]), dst=node_rad*0.8, rad=0.01) itt = 0 while True: itt += 1 DL.step() DL.spawn(ratio=0.1, age=1000) if not itt%20: print(('itt', DL.itt, 'num', DL.num)) vertices, edges = DL.link_export() # sand.set_rgba(FRONT) # sand.paint_strokes( # vertices[edges[:,0],:].astype('double'), # vertices[edges[:,1],:].astype('double'), # grains # ) # sand.paint_circles( # vertices.astype('double'), # random(len(vertices))*one*4.0, # grains # ) # for k,(a,b) in enumerate(edges): # w = a*nc+b # rgba = colors[w%nc]+[0.001] # sand.set_rgba(rgba) # sand.paint_strokes( # vertices[a:a+1,:].astype('double'), # vertices[b:b+1,:].astype('double'), # grains # ) n = 20 for k, (x, y) in enumerate(vertices): rgba = colors[k%nc]+[0.0005] sand.set_rgba(rgba) o = ones((n, 2), 'float') o[:,0] *= x o[:,1] *= y r = (1.0-2.0*random(n))*4*one sand.paint_filled_circles( o, r, grains ) if not itt%5: # vertices, edges = DL.link_export() # n = 1000 # sand.set_bg(BACK) # seed(1) # for k, (x, y) in enumerate(vertices): # rgba = colors[k%nc]+[0.005] # sand.set_rgba(rgba) # o = ones((n, 2), 'float') # o[:,0] *= x # o[:,1] *= y # r = random()*one*3+cumsum(random(n)*random()*10)*one*0.002 # # r = sqrt(linspace(2.0, 10.0, n))*one # # r = ones(n, 'float')*one* # sand.paint_circles( # o, # r, # grains # ) name = fn.name() + '.png' print(name) sand.write_to_png(name, 2)
#!/usr/bin/env python import numpy as np from fn import Fn from src.draw import Canvas from src.rnd import rnd_crc small_conf = { "width": 4000, "height": 4000, "bg": (0, 0, 0), "fg": (255, 255, 255, 0.25), "fname": Fn().name(), } def acc_vec(_pos, _mass): d2 = _pos @ (-2 * _pos.T) diag = -0.5 * np.einsum('ii->i', d2) d2 = d2 + diag + diag[:, None] np.einsum('ii->i', d2)[...] = 1 return np.nansum( (_pos[:, None, :] - _pos) * (_mass[:, None] * d2**-1.5)[..., None], axis=0) with Canvas(**small_conf) as c: # Initial particle conditions n = 3000 pos = np.random.uniform(0, 4000, (n, 2))
def main(): from modules.path import Path from modules.helpers import get_limit_indices from modules.export import Exporter from render import Render from fn import Fn fn = Fn(prefix='./res/') exporter = Exporter() render = Render(SIZE, BACK, FRONT) render.set_line_width(LINE_WIDTH) #the = 0.5*PI*ones(NMAX) xy = column_stack((ones(NMAX)*START_X,linspace(START_Y,STOP_Y,NMAX))) draw_start,draw_stop = get_limit_indices(xy,top=START_Y,bottom=STOP_Y) # last_xy = xy[draw_start:draw_stop,:] # draw_circles = render.circles for i in count(): ## gradient-like distribution of lines pix = sqrt(1+i)*ONE ## linear distribution of lines #pix = PIX_BETWEEN*ONE path = Path(xy,pix) path.trace(-PIHALF) path.noise() path.interpolate(int(pix/ONE)*2) xy = path.xy_interpolated ## remove nodes above and below canvas canvas_start,canvas_stop = get_limit_indices(xy,top=0.,bottom=1.) xy = xy[canvas_start:canvas_stop,:] ## render nodes above STOP_Y and below START_Y draw_start,draw_stop = get_limit_indices(xy,top=START_Y,bottom=STOP_Y) #draw_circles(xy[draw_start:draw_stop,:],\ #ones(draw_stop-draw_start)*ONE) render.path(xy[draw_start:draw_stop,:]) exporter.add(xy[draw_start:draw_stop,:]) xmax = xy[:,0].max() if (xmax>STOP_X): break print 'num',i,'points', len(path.xy_circles),'x', xmax name = fn.name() render.transparent_pix() render.write_to_png(name+'.png') exporter.export(name+'.2obj')
def main(): from time import time from itertools import count from iutils.render import Render from modules.helpers import print_stats from modules.show import show # from modules.show import show_closed from differentialLine import DifferentialLine from modules.helpers import get_exporter from numpy.random import random from fn import Fn DF = DifferentialLine(NMAX, FARL*2, NEARL, FARL, PROCS) fn = Fn(prefix='./res/') exporter = get_exporter( NMAX, { 'nearl': NEARL, 'farl': FARL, 'stp': STP, 'size': SIZE, 'procs': PROCS } ) render = Render(SIZE, BACK, FRONT) render.ctx.set_source_rgba(*FRONT) render.ctx.set_line_width(LINEWIDTH) angles = sorted(random(INIT_NUM)*TWOPI) DF.init_circle_segment(MID,MID,INIT_RAD, angles) t_start = time() for i in count(): DF.optimize_position(STP) # spawn_curl(DF,NEARL) spawn(DF, NEARL, 0.03) if i % STAT_ITT == 0: print_stats(i,time()-t_start,DF) if i % EXPORT_ITT == 0: name = fn.name() num = DF.np_get_edges_coordinates(np_edges) show(render,np_edges[:num,:],name+'.png') exporter( DF, name+'.2obj' )