예제 #1
0
def demo3d_hanoi(**kwargs):
    nr_disks = kwargs.get("nr_disks", 5)
    interactive = kwargs.get("interactive", 1)

    hanoi = Hanoi(nr_disks)
    tower_states = list([hanoi.towers])
    for _ in hanoi.moves():
        tower_states.append(hanoi.towers)

    vp = Plotter(axes=0, interactive=0, bg="w", size=(800, 600))
    vp.camera.SetPosition([18.5, -20.7, 7.93])
    vp.camera.SetFocalPoint([3.0, 0.0, 2.5])
    vp.camera.SetViewUp([-0.1, +0.17, 0.977])

    cols = makePalette("red", "blue", hanoi.nr_disks + 1, hsv=True)
    disks = {
        hanoi.nr_disks - i: Cylinder(pos=[0, 0, 0],
                                     r=0.2 * (hanoi.nr_disks - i + 1),
                                     c=cols[i])
        for i in range(hanoi.nr_disks)
    }
    for k in disks:
        vp += disks[k]
    vp += Box(pos=(3.0, 0, -.5), length=12.0, width=4.0, height=0.1)
    vp.show(zoom=1.2)

    printc("\n Press q to continue, Esc to exit. ", c="y", invert=1)
    pb = ProgressBar(0, len(tower_states), 1, c="b", ETA=False)
    for t in pb.range():
        pb.print()
        state = tower_states[t]
        for tower_nr in range(3):
            for i, disk in enumerate(state[tower_nr]):
                disks[disk].pos([3 * tower_nr, 0, i + 0.5])
        vp.show(resetcam=0, interactive=interactive, rate=10)
    vp.show(resetcam=0, interactive=1)
예제 #2
0
hanoi = Hanoi(nr_disks)

tower_states = list([hanoi.towers])
for _ in hanoi.moves():
    tower_states.append(hanoi.towers)

disks = {
    hanoi.nr_disks - i: Cylinder(r=0.2 * (hanoi.nr_disks - i + 1), c=i)
    for i in range(hanoi.nr_disks)
}

plt = Plotter(interactive=False, size=(800, 600), bg='wheat', bg2='lb')
plt += disks.values()
plt += Box(pos=(3, 0, -0.5), size=(12, 4, 0.1))
cam = dict(
    pos=(14.60, -20.56, 7.680),
    focalPoint=(3.067, 0.5583, 1.910),
    viewup=(-0.1043, 0.2088, 0.9724),
)
plt.show(camera=cam)

pb = ProgressBar(0, len(tower_states), 1, c="y")
for t in pb.range():
    pb.print()
    state = tower_states[t]
    for tower_nr in range(3):
        for i, disk in enumerate(state[tower_nr]):
            disks[disk].pos([3 * tower_nr, 0, i + 0.5])
    plt.render()
plt.interactive().close()
예제 #3
0
파일: gas.py 프로젝트: sariths/vtkPlotter
    mlist.append(mass)
    rlist.append(Ratom)

pos = np.array(poslist)
poscircle = pos
p = np.array(plist)
m = np.array(mlist)
m.shape = (Natoms, 1)
radius = np.array(rlist)
r = pos - pos[:, np.newaxis]  # all pairs of atom-to-atom vectors

ds = (p / m) * (dt / 2.0)
if "False" not in np.less_equal(mag(ds), radius).tolist():
    pos = pos + (p / mass) * (dt / 2.0)  # initial half-step

pb = ProgressBar(0, Nsteps, c=1)
for i in pb.range():

    # Update all positions
    ds = mag((p / m) * (dt / 2.0))
    if "False" not in np.less_equal(ds, radius).tolist():
        pos = pos + (p / m) * dt

    r = pos - pos[:, np.newaxis]  # all pairs of atom-to-atom vectors
    rmag = np.sqrt(np.sum(np.square(r), -1))  # atom-to-atom scalar distances
    hit = np.less_equal(rmag, radius + radius[:, None]) - np.identity(Natoms)
    hitlist = np.sort(np.nonzero(
        hit.flat)[0]).tolist()  # i,j encoded as i*Natoms+j

    # If any collisions took place:
    for ij in hitlist:
예제 #4
0
파일: brownian2D.py 프로젝트: zymale/vedo
           res=12).phong()
]
for s in range(1, Nsp):
    a = Sphere(pos=(Pos[s][0], Pos[s][1], 0), r=Radius[s], c="blue",
               res=6).phong()
    Spheres.append(a)
#    vp += a
vp += Spheres
vp += Grid(sx=screen_w, sy=screen_w)

# Auxiliary variables
Id = np.identity(Nsp)
Dij = (Radius + Radius[:, np.newaxis])**2  # Matrix Dij=(Ri+Rj)**2

# The main loop
pb = ProgressBar(0, 2000, c="r")
for i in pb.range():
    # Update all positions
    np.add(Pos, Vel * Dt, Pos)  # Fast version of Pos = Pos + Vel*Dt

    # Impose the bouncing at the walls
    if Pos[0, 0] <= -Lb0:
        Pos[0, 0] = -Lb0
        Vel[0, 0] = -Vel[0, 0]
    elif Pos[0, 0] >= Lb0:
        Pos[0, 0] = Lb0
        Vel[0, 0] = -Vel[0, 0]
    elif Pos[0, 1] <= -Lb1:
        Pos[0, 1] = -Lb1
        Vel[0, 1] = -Vel[0, 1]
    elif Pos[0, 1] >= Lb1:
예제 #5
0
        idx_new = N + it

        theta = acos(2. * np.random.uniform(0,1) - 1);
        phi = np.random.uniform(0,1) * 2.0 * pi;
        X[idx_new,0] = X[idx,0] + mean_dist / 4 * sin(theta) * cos(phi);
        X[idx_new,1] = X[idx,1] + mean_dist / 4 * sin(theta) * sin(phi);
        X[idx_new,2] = X[idx,2] + mean_dist / 4 * cos(theta);

    return N + marked_for_div_idx.size

# Initialise cells
ini_x = np.random.uniform(low=-1.0, high=1.0, size=n_max)
ini_y = np.random.uniform(low=-1.0, high=1.0, size=n_max)
ini_z = np.random.uniform(low=-1.0, high=1.0, size=n_max)

X = np.column_stack((ini_x, ini_y, ini_z))

########################################################
from vedo import ProgressBar, Spheres,show, interactive

pb = ProgressBar(0, T, c='red')
for t in pb.range():

    take_euler_step(X, N, dt, relu_force, r_max, r_eq)
    N = proliferation(X, N, prolif_rate, r_eq)

    cells = Spheres(X[:N,:], c='b', r=0.4)
    show(cells, interactive=0, viewup='z')
    pb.print("N= " + str(N))

interactive()
예제 #6
0
import numpy as np
from scipy.fftpack import fftn, fftshift
from vedo import Volume, ProgressBar, show, interactive


def f(x, y, z, t):
    r = np.sqrt(x * x + y * y + z * z + 2 * t * t) + 0.1
    return np.sin(9 * np.pi * r) / r


n = 64
qn = 50
vol = np.zeros((n, n, n))
n1 = int(n / 2)

pb = ProgressBar(0, qn, c="r")
for q in pb.range():
    pb.print()

    t = 2 * q / qn - 1
    for k in range(n1):
        z = 2 * k / n1 - 1
        for j in range(n1):
            y = 2 * j / n1 - 1
            for i in range(n1):
                x = 2 * i / n1 - 1
                vol[i, j, k] = f(x, y, z, t)
    volf = fftn(vol)
    volf = fftshift(abs(volf))
    volf = np.log(12 * volf / volf.max() + 1) / 2.5
예제 #7
0
# (get these numbers by pressing Shift-C)
plt.camera.SetPosition([2.5, 2.5, 5.5])
plt.camera.SetFocalPoint([0.4, 0.4, 0.4])
plt.camera.SetParallelScale(1.8)
plt.camera.SetViewUp([-0.1, 1, -0.3])

# Let's start with creating 3 colonies of 1 cell each
# of types: red, green and blue, in different positions in space
# and with 3 different rates of division (tdiv in hours)
c1 = Colony([Cell([1, 0, 0], tdiv=8)], c="b")
c2 = Colony([Cell([0, 1, 0], tdiv=9)], c="g")
c3 = Colony([Cell([0, 0, 1], tdiv=10)], c="r")
colonies = [c1, c2, c3]

# time goes from 0 to 90 hours
pb = ProgressBar(0, 50, step=0.1, c=1)
for t in pb.range():
    msg = "[Nb,Ng,Nr,t] = "
    plt.actors = []  # clean up the list of actors

    for colony in colonies:

        newcells = []
        for cell in colony.cells:

            if cell.dieAt(t):
                continue
            if cell.divideAt(t):
                newc = cell.split()  # make daughter cell
                plt += Line(cell.pos, newc.pos, c="k", lw=3, alpha=0.5)
                newcells.append(newc)
예제 #8
0
    ynew = y + (yk1 + 2 * yk2 + 2 * yk3 + yk4) / 6
    vnew = v + (vk1 + 2 * vk2 + 2 * vk3 + vk4) / 6
    return ynew, vnew


def euler(y, v, t, dt):  # simple euler integrator
    vnew = v + accel(y, v, t) * dt
    ynew = y + vnew * dt + 1 / 2 * accel(y, vnew, t) * dt**2
    return ynew, vnew


positions_eu, positions_rk = [], []
y_eu, y_rk = np.array(y), np.array(y)
v_eu, v_rk = np.array(v), np.array(v)
t = 0
pb = ProgressBar(0, Nsteps, c="blue", ETA=0)
for i in pb.range():
    y_eu, v_eu = euler(y_eu, v_eu, t, dt)
    y_rk, v_rk = rk4(y_rk, v_rk, t, dt)
    t += dt
    positions_eu.append(y_eu)  # store result of integration
    positions_rk.append(y_rk)
    pb.print("Integrate: RK-4 and Euler")

####################################################
# Visualize the result
####################################################
vp = Plotter(interactive=0, axes=2)  # choose axes type nr.2
vp.ytitle = "u(x,t)"
vp.ztitle = ""  # will not draw z axis
예제 #9
0
pic.pickable(False).level(185).window(120)  # add some contrast to the original image
scale = [pic.shape[0]/2, pic.shape[1]/2, 1]

def GeoCircle(lat, lon, r, res=50):
    coords = []
    sinr, cosr = np.sin(r), np.cos(r)
    sinlat, coslat = np.sin(lat), np.cos(lat)
    for phi in np.linspace(0, 2*np.pi, num=res, endpoint=False):
        clat = np.arcsin(sinlat * cosr + coslat * sinr * np.cos(phi))
        clng = lon + np.arctan2(np.sin(phi) * sinr * coslat, cosr - sinlat * np.sin(clat))
        coords.append([clng/np.pi + 1, clat*2/np.pi + 1, 0])
    return Polygon(nsides=res).points(coords)  # warp polygon points to match geo projection


centers = []
pb = ProgressBar(0, len(data))
for i, d in data.iterrows():
    pb.print("Parsing USGS data..")
    M = d['mag']                                       # earthquake estimated magnitude
    E = np.sqrt(np.exp(5.24+1.44*M) * scale[0])/10000  # empirical formula for sqrt(energy_release(M))
    rgb = colorMap(E, name='Reds', vmin=0, vmax=7)     # map energy to color
    lat, lon = np.deg2rad(d['latitude']), np.deg2rad(d['longitude'])
    ce = GeoCircle(lat, lon, E/50).scale(scale).z(num/M).c(rgb).lw(0.1).useBounds(False)
    ce.time = i
    ce.info = '\n'.join(str(d).split('\n')[:-1])       # remove of the last line in string d
    #if M > 6.5: ce.alpha(0.8)                         # make the big ones slightly transparent
    if i < len(data)-num: ce.off()                     # switch off older ones: make circles invisible
    centers.append(ce)


def sliderfunc(widget, event):
예제 #10
0
               sin(state[2]) * cosa + M2 * L2 * state[3] * state[3] * sina -
               (M1 + M2) * G * sin(state[0])) / den1
    dydx[2] = state[3]
    den2 = (L2 / L1) * den1
    dydx[3] = (-M2 * L2 * state[3] * state[3] * sina * cosa +
               (M1 + M2) * G * sin(state[0]) * cosa -
               (M1 + M2) * L1 * state[1] * state[1] * sina -
               (M1 + M2) * G * sin(state[2])) / den2
    return dydx


t = np.arange(0.0, 10.0, dt)
state = np.radians([th1, w1, th2, w2])
y = integrate.odeint(derivs, state, t)

P1 = np.dstack([L1 * sin(y[:, 0]), -L1 * cos(y[:, 0])]).squeeze()
P2 = P1 + np.dstack([L2 * sin(y[:, 2]), -L2 * cos(y[:, 2])]).squeeze()

ax = Axes(xrange=(-2, 2), yrange=(-2, 1), htitle=__doc__)
pb = ProgressBar(0, len(t), c="b")
for i in pb.range():
    j = max(i - 5, 0)
    k = max(i - 10, 0)
    l1 = Line([[0, 0], P1[i], P2[i]]).lw(7).c("blue2")
    l2 = Line([[0, 0], P1[j], P2[j]]).lw(6).c("blue2", 0.3)
    l3 = Line([[0, 0], P1[k], P2[k]]).lw(5).c("blue2", 0.1)
    pt = Points([P1[i], P2[i], P1[j], P2[j], P1[k], P2[k]],
                r=8).c("blue2", 0.2)
    show(l1, l2, l3, pt, ax, interactive=False, size=(900, 700), zoom=1.4)
    pb.print()
예제 #11
0
import numpy as np
from Forces.forces import relu_force
from Solvers.solvers import take_euler_step

# Params
N = 200
T = 100
r_max = 1.0
r_eq = 0.8
dt = 0.1

# Initialise cells
ini_x = np.random.uniform(low=-1.0, high=1.0, size=N)
ini_y = np.random.uniform(low=-1.0, high=1.0, size=N)
ini_z = np.random.uniform(low=-1.0, high=1.0, size=N)

X = np.column_stack((ini_x, ini_y, ini_z))

from vedo import ProgressBar, Spheres, interactive

pb = ProgressBar(0, T, c='red')
for t in pb.range():

    take_euler_step(X, N, dt, relu_force, r_max, r_eq)

    Spheres(X, c='b', r=0.3).show(axes=1, interactive=0)
    pb.print()

interactive()
예제 #12
0
ini_theta = np.zeros(N)
ini_phi = np.ones(N)

X = np.column_stack((ini_x, ini_y, ini_z, ini_theta, ini_phi))

# List to store time series output
coords_t = []
pol_t = []

# Save state at t=0
out_X = np.copy(X)
pol = arr_pol_to_float3(out_X[:, 3:5])
coords_t.append(out_X[:, :3])
pol_t.append(pol)

pb = ProgressBar(0, T, c='red')
for t in pb.range():
    take_euler_step(X, N, dt, apical_constriction_force, r_max, r_eq,
                    preferential_angle)
    pb.print("Integrating")

    if t % output_int == 0:
        out_X = np.copy(X)
        pol = arr_pol_to_float3(out_X[:, 3:5])
        coords_t.append(out_X[:, :3])
        pol_t.append(pol)

###############################################################################
# View as an interactive time sequence with a slider
max_time = len(coords_t)
vp = Plotter(interactive=False)