Example #1
0
def test_track(silent=True, precision="d", decimals=80):
    """
    Tests the path tracking on a small random system.
    Two random trinomials are generated and random constants
    are added to ensure there are no singular solutions
    so we can use this generated system as a start system.
    The target system has the same monomial structure as
    the start system, but with random real coefficients.
    Because all coefficients are random, the number of
    paths tracked equals the mixed volume of the system.
    """
    from phcpy.solver import random_trinomials, real_random_trinomials
    from phcpy.solver import solve, mixed_volume, newton_step

    pols = random_trinomials()
    real_pols = real_random_trinomials(pols)
    from random import uniform as u

    qone = pols[0][:-1] + ("%+.17f" % u(-1, +1)) + ";"
    qtwo = pols[1][:-1] + ("%+.17f" % u(-1, +1)) + ";"
    rone = real_pols[0][:-1] + ("%+.17f" % u(-1, +1)) + ";"
    rtwo = real_pols[1][:-1] + ("%+.17f" % u(-1, +1)) + ";"
    start = [qone, qtwo]
    target = [rone, rtwo]
    start_sols = solve(start, silent)
    sols = track(target, start, start_sols, precision, decimals)
    mixvol = mixed_volume(target)
    print "mixed volume of the target is", mixvol
    print "number of solutions found :", len(sols)
    newton_step(target, sols, precision, decimals)
Example #2
0
def solve_general():
    """
    Defines the pivot and generates random coordinates,
    uniformly distributed in [-1, +1], for the five points
    through which the coupler must pass.
    Calls the blackbox solver to solve the system.
    In each run, the number of computed solutions should be 36.
    """
    from random import uniform as u
    pt0 = Matrix(2, 1, lambda i,j: u(-1,+1))
    pt1 = Matrix(2, 1, lambda i,j: u(-1,+1))
    pt2 = Matrix(2, 1, lambda i,j: u(-1,+1))
    pt3 = Matrix(2, 1, lambda i,j: u(-1,+1))
    pt4 = Matrix(2, 1, lambda i,j: u(-1,+1))
    # the pivot is a
    piv = Matrix([[1], [0]])
    equ = polynomials(pt0,pt1,pt2,pt3,pt4,piv)
    print 'the polynomial system :'
    for pol in equ:
        print pol
    from phcpy.solver import solve
    sols = solve(equ)
    print 'the solutions :'
    for sol in sols:
        print sol
    print 'computed', len(sols), 'solutions'
Example #3
0
def test_quaddobl_store_load():
    """
    Tests the storing and loading of numerically computed tropisms,
    in quad double precision.
    """
    print "testing storing and loading numerical tropisms..."
    nbr = int(input("Give the number of tropisms : "))
    dim = int(input("Give the dimension : "))
    from random import randint

    wnd = [randint(10, 99) for _ in range(nbr)]
    from random import uniform as u

    dirs = []
    for _ in range(nbr):
        dirs.append([u(-1, +1) for _ in range(4 * dim)])
    errs = [u(0, 1) / 1000.0 for _ in range(4 * nbr)]
    print "random winding numbers :", wnd
    for k in range(len(dirs)):
        print "direction", k + 1, ":", dirs[k]
    print "random errors :", errs
    quaddobl_initialize(nbr, dim, wnd, dirs, errs)
    (retwnd, retdirs, reterrs) = quaddobl_retrieve(nbr, dim)
    retsize = quaddobl_size()
    retdim = quaddobl_dimension()
    print "retrieved number of tropisms :", retsize
    print "retrieved dimension of the tropisms :", retdim
    print "retrieved winding numbers :", retwnd
    print "retrieved directions :"
    for k in range(len(retdirs)):
        print "direction", k + 1, ":", retdirs[k]
    print "retrieved errors :", reterrs
    while True:
        idx = int(input("Give an index (0 to exit): "))
        if idx < 1:
            break
        (idxwnd, idxdir, idxerr) = retrieve_quaddobl_tropism(dim, idx)
        print "-> winding number for tropism", idx, ":", idxwnd
        print "-> tropism", idx, "has coordinates :", idxdir
        print "-> the error :", idxerr
        ranwnd = randint(10, 99)
        randir = [u(-1, 1) for _ in range(4 * dim)]
        ranerr = [u(0, 1) / 1000.0, u(0, 1) / 1000.0]
        print "store tropism %d with winding number %d" % (idx, ranwnd)
        print "with new coordinates :", randir
        print "and error", ranerr
        store_quaddobl_tropism(dim, idx, ranwnd, randir, ranerr)
    quaddobl_clear()
Example #4
0
def real_osculating_planes(mdim, pdim, qdeg):
    """
    Returns m*p + qdeg*(m+p) real m-planes osculating
    a rational normal curves.
    """
    from phcpy.phcpy2c3 import py2c_schubert_osculating_planes
    dim = mdim*pdim + qdeg*(mdim+pdim)
    from random import uniform as u
    pts = ""
    for k in range(dim):
        cff = '%.17lf' % u(-1, +1)
        pts = pts + ' ' + cff
    # print 'the points :', pts
    osc = py2c_schubert_osculating_planes(mdim, pdim, qdeg, len(pts), pts)
    # print 'the coefficients of the planes :'
    # print osc
    items = osc.split(' ')
    ind = 0
    planes = []
    for k in range(0, dim):
        plane = []
        for i in range(0, mdim+pdim):
            row = []
            for j in range(0, mdim):
                row.append(eval(items[ind]))
                ind = ind + 1
            plane.append(row)
        planes.append(plane)
    return planes
Example #5
0
def real_osculating_planes(mdim, pdim, qdeg):
    r"""
    Returns m*p + q*(m+p) real m-planes osculating
    a rational normal curves.
    The values for m, p, and q are provided respectively
    by *mdim*, *pdim*, and *qdeg*.
    """
    from phcpy.phcpy2c2 import py2c_schubert_osculating_planes

    dim = mdim * pdim + qdeg * (mdim + pdim)
    from random import uniform as u

    pts = ""
    for k in range(dim):
        cff = "%.17lf" % u(-1, +1)
        pts = pts + " " + cff
    # print 'the points :', pts
    osc = py2c_schubert_osculating_planes(mdim, pdim, qdeg, len(pts), pts)
    # print 'the coefficients of the planes :'
    # print osc
    items = osc.split(" ")
    ind = 0
    planes = []
    for k in range(0, dim):
        plane = []
        for i in range(0, mdim + pdim):
            row = []
            for j in range(0, mdim):
                row.append(eval(items[ind]))
                ind = ind + 1
            plane.append(row)
        planes.append(plane)
    return planes
Example #6
0
def test_quaddobl_store_load():
    """
    Tests the storing and loading of numerically computed tropisms,
    in quad double precision.
    """
    print('testing storing and loading numerical tropisms...')
    nbr = int(input('Give the number of tropisms : '))
    dim = int(input('Give the dimension : '))
    from random import randint
    wnd = [randint(10, 99) for _ in range(nbr)]
    from random import uniform as u
    dirs = []
    for _ in range(nbr):
        dirs.append([u(-1, +1) for _ in range(4*dim)])
    errs = [u(0,1)/1000.0 for _ in range(4*nbr)]
    print('random winding numbers :', wnd)
    for k in range(len(dirs)):
        print('direction', k+1, ':', dirs[k])
    print('random errors :', errs)
    quaddobl_initialize(nbr, dim, wnd, dirs, errs)
    (retwnd, retdirs, reterrs) = quaddobl_retrieve(nbr, dim)
    retsize = quaddobl_size()
    retdim = quaddobl_dimension()
    print('retrieved number of tropisms :', retsize)
    print('retrieved dimension of the tropisms :', retdim)
    print('retrieved winding numbers :', retwnd)
    print('retrieved directions :')
    for k in range(len(retdirs)):
        print('direction', k+1, ':', retdirs[k])
    print('retrieved errors :', reterrs)
    while True:
        idx = int(input('Give an index (0 to exit): '))
        if idx < 1:
            break
        (idxwnd, idxdir, idxerr) = retrieve_quaddobl_tropism(dim, idx)
        print('-> winding number for tropism', idx, ':', idxwnd)
        print('-> tropism', idx, 'has coordinates :', idxdir)
        print('-> the error :', idxerr)
        ranwnd = randint(10, 99)
        randir = [u(-1, 1) for _ in range(4*dim)]
        ranerr = [u(0, 1)/1000.0, u(0, 1)/1000.0]
        print('store tropism %d with winding number %d' % (idx,ranwnd))
        print('with new coordinates :', randir)
        print('and error', ranerr);
        store_quaddobl_tropism(dim, idx, ranwnd, randir, ranerr)
    quaddobl_clear()
Example #7
0
def real_random_trinomials(sys):
    """
    On input in sys are two random trinonials with complex coefficients,
    in the format what random_trinomials() returns.
    On return is a list of two real random trinomials with the same
    monomial structure but with random real coefficients in [-1,+1].
    """
    from random import uniform as u
    result = []
    for pol in sys:
        terms = pol.split(')')
        rpol = ''
        for i in range(1, len(terms)-1):
            rterm = terms[i].split('+')
            cff = '%+.17f' % u(-1, +1)
            rpol = rpol + cff + rterm[0]
        cff = '%+.17f' % u(-1, +1)
        rpol = rpol + cff + terms[len(terms)-1]
        result.append(rpol)
    return result
Example #8
0
File: B1.py Project: M0nd4/smag
def direct_Vol1_s(N,d):
    n_hits = 0
    for i in range(N):
        sum_x_sqr = 0
        for j in range(d):
            x_j = u(-1.0,1.0)
            sum_x_sqr += x_j**2
            if sum_x_sqr > 1.0:
                break;
        else:
            n_hits += 1
    return n_hits
Example #9
0
def random_complex_matrix(nbrows, nbcols):
    """
    Returns a random nbrows-by-nbcols matrix
    with randomly generated complex coefficients
    on the unit circle, as a list of rows.
    """
    from math import pi, sin, cos
    from random import uniform as u
    result = []
    for i in range(0, nbrows):
        angles = [u(0, 2 * pi) for _ in range(nbcols)]
        cols = [complex(cos(a), sin(a)) for a in angles]
        result.append(cols)
    return result
Example #10
0
def random_complex_matrix(nbrows, nbcols):
    """
    Returns a random nbrows-by-nbcols matrix
    with randomly generated complex coefficients
    on the unit circle, as a list of rows.
    """
    from math import pi, sin, cos
    from random import uniform as u
    result = []
    for i in range(0, nbrows):
        angles = [u(0, 2*pi) for _ in range(nbcols)]
        cols = [complex(cos(a), sin(a)) for a in angles]
        result.append(cols)
    return result
Example #11
0
def random_complex_matrix(nbrows, nbcols):
    """
    Returns a random nbrows-by-nbcols matrix
    with randomly generated complex coefficients
    on the unit circle, as a list of rows.
    """
    from math import pi, sin, cos
    from random import uniform as u
    result = []
    for i in range(0, nbrows):
        row = []
        for j in range(0, nbcols):
            angle = u(0, 2*pi)
            cff = complex(cos(angle), sin(angle))
            row.append(cff)
        result.append(row)
    return result
Example #12
0
def random_trinomials():
    """
    Returns a system of two trinomials equations for testing.
    A trinomial consists of three monomials in two variables.
    Exponents are uniform between 0 and 5 and coefficients are
    on the complex unit circle.
    """
    from random import randint as r
    exponents = [(r(0, 5), r(0, 5)) for i in range(0, 6)]
    monomials = map(lambda e: 'x^%d*y^%d' % e, exponents)
    from random import uniform as u
    from math import cos, sin, pi
    angles = [u(0, 2*pi) for i in range(0, 6)]
    cff = map(lambda a: '(' + str(cos(a)) + '%+.14f' % sin(a) + '*i)', angles)
    one = '+'.join(cff[i] + '*' + monomials[i] for i in range(0, 3)) + ';'
    two = '+'.join(cff[i] + '*' + monomials[i] for i in range(3, 6)) + ';'
    return [one, two]
Example #13
0
def random_trinomials():
    """
    Returns a system of two trinomials equations for testing.
    A trinomial consists of three monomials in two variables.
    Exponents are uniform between 0 and 5 and coefficients are
    on the complex unit circle.
    """
    from random import randint as r
    exponents = [(r(0, 5), r(0, 5)) for _ in range(0, 6)]
    makemonf = lambda e: 'x^%d*y^%d' % e
    monomials = [makemonf(e) for e in exponents]
    from random import uniform as u
    from math import cos, sin, pi
    angles = [u(0, 2 * pi) for _ in range(0, 6)]
    makecff = lambda a: '(' + str(cos(a)) + '%+.14f' % sin(a) + '*i)'
    cff = [makecff(a) for a in angles]
    one = '+'.join(cff[i] + '*' + monomials[i] for i in range(0, 3)) + ';'
    two = '+'.join(cff[i] + '*' + monomials[i] for i in range(3, 6)) + ';'
    return [one, two]
Example #14
0
def soc(data, h1, h2, h3):
    from sklearn import cluster
    import numpy as np
    from random import uniform as u
    from numpy.linalg import norm
    data = np.array(data)
    mi = data.min(axis=0)
    ma = data.max(axis=0)
    n = h1
    n1 = h2
    it = h3
    init = []
    velo = []
    kmeans = cluster.KMeans(n_clusters=n1)
    kmeans.fit(data)
    c = len(data[0])
    for i in range(n):
        for k in range(n1):
            tmp = []
            tmp1 = []
            for j in range(c):
                tmp.append(u(mi[j], ma[j]))
                tmp1.append(u(0, 1))
            init.append(tmp)
            velo.append(tmp1)
    for i in range(len(kmeans.cluster_centers_)):
        init[i - n1] = kmeans.cluster_centers_[i]
    init = np.array(init)
    velo = np.array(velo)
    mii = 0
    pbest = np.array([np.ndarray([n1, c]) for i in range(n)])
    pb = np.array([np.inf for i in range(n)])
    gbest = np.array([np.ndarray([n1, c])])
    gb = np.inf
    c1 = 2
    c2 = 1.5
    for k in range(it):
        for l in range(n):
            clus = {}
            for i in data:
                mic = 10**100
                for j in range(n1):
                    tmp = norm(i - init[l * n1 + j])
                    if (tmp < mic):
                        mii = j
                        mic = tmp
                clus.update({tuple(i): mii})
            sum = 0
            for m in set(clus.values()):
                tmp1 = [k for (k, v) in clus.items() if v == m]
                for x in tmp1:
                    sum += norm(np.array(x) - init[l * n1 + m]) / len(tmp1)
            if (set(range(n1)) - set(clus.values())):
                sum = sum * 10
            sum = sum / n1
            if (sum < pb[l]):
                pb[l] = sum
                pbest[l] = init[l * n1:(l + 1) * n1]
            if (sum < gb):
                gb = sum
                gbest[0] = init[l * n1:(l + 1) * n1]
            velo[l * n1:(l + 1) * n1] = velo[l * n1:(l + 1) * n1] + c1 * u(
                0, 1) * (pbest[l] - init[l * n1:(l + 1) * n1]) + c2 * u(
                    0, 1) * (gbest[0] - init[l * n1:(l + 1) * n1])
            init[l * n1:(l + 1) *
                 n1] = init[l * n1:(l + 1) * n1] + velo[l * n1:(l + 1) * n1]
    clus = {}
    for i in data:
        mic = 10**100
        for j in range(n1):
            tmp = norm(i - gbest[0][j])
            if (tmp < mic):
                mii = j
                mic = tmp
        clus.update({tuple(i): mii})
    return [clus, gbest]
Example #15
0
from random import random  # random是Python内置模块
from random import *  # 导人random模块中的所有对象
from random import uniform as u

print(random())  # 返回0~1之间的随机小数
print(randint(10, 20))  # 返回两个整数之间的随机整数
print(uniform(5, 10))  # 返回两个数之间的随机实数
print(u(5, 10))
Example #16
0
# Load 3 actors assigning each a different color, 
# by default use their file names as legend entries.
# No need to use any variables, as actors are stored internally in vp.actors:
vp = Plotter(title='3 shapes')
vp.load('data/250.vtk', c=(1,0.4,0), alpha=0.3)
vp.load('data/270.vtk', c=(1,0.6,0), alpha=0.3)
vp.load('data/290.vtk', c=(1,0.8,0), alpha=0.3)
print('Loaded vtkActors: ', len(vp.actors))
vp.show()


#########################################################################################
# Draw a spline through a set of points:
vp = Plotter(title='Example of splines through 8 random points')

pts = [ (u(0,2), u(0,2), u(0,2)+i) for i in range(8) ] # build python list of points
vp.points(pts, legend='random points')                 # create the vtkActor

for i in range(10):
    sp = spline(pts, smooth=i/10, degree=2, c=i, legend='smoothing '+str(i/10))
    vp.add(sp) # add the actor to the internal list of actors to be shown
vp.show(viewup='z', interactive=1)


#########################################################################################
# Draw a cloud of points each one with a different color
# which depends on the point position itself
vp = Plotter(title='color points')

rgb = [(u(0,255), u(0,255), u(0,255)) for i in range(5000)]
Example #17
0
from vtkplotter import printc, ProgressBar, Plotter

N = 10  # nr of particles along axis
s = 0.01  # random step size

scene = Plotter(verbose=0, axes=0)
scene.plane(pos=[.44, .44, -.1], texture='wood7')

for i in range(N):  # generate a grid of points
    for j in range(N):
        for k in range(N):
            p = [i / N, j / N, k / N]
            scene.point(p, c=p)  # color point by its own position

pb = ProgressBar(0, 80, c='red')
for t in pb.range():  # loop of 400 steps
    pb.print()

    for i in range(1, N * N * N):  # for each particle
        actor = scene.actors[i]
        r = [u(-s, s), u(-s, s), u(-s, s)]  # random step
        p = actor.pos()  # get point position
        q = p + r  # add the noise
        if q[2] < 0: q[2] *= -1  # if bounce on the floor
        actor.pos(q)  # set its new position
    scene.camera.Azimuth(.5)
    scene.camera.Roll(-.5)
    scene.render()

scene.show(resetcam=0)
while (i < 10):  # coz you might want to run it a thousand million times!
    S, I, R = x
    b, g = rates  # taking the same conditions, but these are for here!
    ctr = 0

    # Gillespie algo...

    while t < T:
        if I == 0:
            break

        dS = b * S * I / N
        dR = g * I
        W = dS + dR  # As a scale factor...

        step = u(0, 1)
        dt = -math.log(step) / W
        t += dt

        if u(0, 1) < dS / W:
            S = S - 1
            I = I + 1
        else:
            I = I - 1
            R = R + 1
        # Okay, so we are gonna average time! Makes mathematical sense...

        if i == 0:  # 1st run
            data.append(
                [t, S, I, R,
                 1])  # 1 means that one value is added ... needed below!
Example #19
0
#########################################################################################
# Load 3 actors assigning each a different (r,g,b) color,
# No need to use any variables here, as actors are stored internally in vp.actors:
vp = Plotter(title="Three limb shapes")
vp.load(datadir + "250.vtk").color([1, 0.4, 0
                                    ]).alpha(0.3)  # load and put it in Plotter
vp.load(datadir + "270.vtk").color([1, 0.6, 0]).alpha(0.3)
vp.load(datadir + "290.vtk").color([1, 0.8, 0]).alpha(0.3)
print("Loaded meshes: ", len(vp.actors))
vp.show()  # picks what is stored in the python list vp.actors

#########################################################################################
# Draw a spline through a set of points:
vp = Plotter(title="Example of splines through random points")

pts = [(u(0, 2), u(0, 2), u(0, 2) + i)
       for i in range(8)]  # build python list of points
vp += Points(pts, r=10)  # add the Points object to the internal list of actors
vp += DashedLine(pts)  # add a dashed line through the points

for i in range(10):
    sp = Spline(pts, smooth=i / 10, degree=2).color(i)
    sp.legend("smoothing " + str(i / 10.0))
    vp += sp  # add the object to Plotter
vp.show(viewup="z", axes=1, interactive=1)  # show internal list of actors

#########################################################################################
# Increase the number of vertices and triangles of a Mesh with subdivide()
# show the before and after in two separate renderers defined by shape=(1,2)
vp = Plotter(shape=(1, 2), axes=0, title="L. v. Beethonven")
mesh1 = vp.load(datadir + "beethoven.ply")
Example #20
0
import numpy as np
# First, we must read in the probability vector.
f = open('bimodalNormalVector.csv', 'r')
p_vec = []
reader = csv.reader(f)
for row in reader:
    p_vec.append(float(row[0]))
p_vec.pop()
f = open('otherNormalVector.csv', 'r')
p_vec2 = []
reader = csv.reader(f)
for row in reader:
    p_vec2.append(float(row[0]))
p_vec2.pop()
p_vec = [p_vec, p_vec2]
rando = int(u(0, 70))  # This will be the initial depth of the mobile-agent.
# Create a new experiment with a randomly seeded depth for the agent and
# precision of 1m, max depth of 70m.
experiment = Experiment(rando, 70, p_vec, 10, True)

experiment.ensemble_evaluation_ns(20)
print("********************************************************************")
a = np.array(experiment.learned_best)
b = np.array(p_vec)
print("The location of the best depth is: " + str(np.where(a == a.max())))
print("the confidence of the learned best depth is: " +
      str(max(experiment.learned_best)))
print("The maximums of the environment vector are at indices: " +
      str(np.where(b == b.max())))
# print("the max of the actual probability vector is: " + str(max(p_vec)))
Example #21
0
'''
Example usage of align() method:
 generate two random sets of points as 2 actors 
 and align them using the Iterative Closest Point algorithm.
'''
from __future__ import division
from random import uniform as u
from vtkplotter import Plotter, align, Arrow, Text, Points

vp = Plotter(shape=[1, 2], verbose=0, axes=2, bg='w')

N1 = 15  # number of points of first set
N2 = 15  # number of points of second set
x = 1.  # add some randomness

pts1 = [(u(0, x), u(0, x), u(0, x) + i) for i in range(N1)]
pts2 = [(u(0, x) + 3, u(0, x) + i / 2 + 2, u(0, x) + i + 1) for i in range(N2)]

act1 = Points(pts1, r=8, c='b').legend('source')
act2 = Points(pts2, r=8, c='r').legend('target')

vp.show([act1, act2], at=0)

# find best alignment between the 2 sets of Points, e.i. find
# how to move act1 to best match act2
alpts1 = align(act1, act2).coordinates()
vp.add(Points(alpts1, r=8, c='b'))

for i in range(N1):  # draw arrows to see where points end up
    vp.add(Arrow(pts1[i], alpts1[i], c='k', s=0.007, alpha=.1))
Example #22
0
def gen_sample(id_, walk_length=20, nr_walks=20, draw=True):

    sample = "overhanging_side"
    choise = np.random.choice(6, p=[0.2, 0.2, 0.2, 0.15, 0.2, 0.05])
    print(choise)

    switch = {
        0: (lambda: gen_vertical_hole(diam=u(0.2, 1.5),
                                      critical_=0.7,
                                      thickness=u(1, 5),
                                      dimension=u(10, 25),
                                      edges_cylinder=r(12, 124),
                                      draw=draw), "vertical_hole"),
        1: (lambda: gen_horizontal_hole(diam=u(0.2, 1.5),
                                        critical=0.7,
                                        thickness=u(1, 5),
                                        dimension=u(10, 25),
                                        edges_cylinder=r(12, 124),
                                        draw=draw), "horizontal_hole"),
        2: (lambda: gen_overhanging_side(angle=r(10, 70),
                                         length=10,
                                         critical_bound=(30, 45),
                                         thickness=u(2, 4),
                                         draw=draw), "overhanging_side"),
        3: (lambda: gen_fine_wall_single(thickness=u(0.2, 1.5),
                                         critical_=0.5,
                                         dimension=u(5, 10),
                                         ext=u(1, 3),
                                         out=True,
                                         draw=draw), "fine_wall_single_out"),
        4: (lambda: gen_fine_wall_single(thickness=u(0.2, 1.),
                                         critical_=0.5,
                                         dimension=u(5, 10),
                                         ext=u(1, 3),
                                         out=False,
                                         draw=draw), "fine_wall_single_in"),
        5: (lambda: gen_fine_walls(thickness=u(0.2, 1.5),
                                   critical_=0.5,
                                   dimension=u(3, 10),
                                   ext=u(0.5, 4),
                                   nr_boxes=r(2, 12),
                                   translate_factor=u(2, 6),
                                   draw=draw), "fine_walls")
    }

    func, sample = switch.get(choise)

    mesh, critical = func()
    G, face_feature = get_dual(mesh)

    #if all faces are critical something went wrong and we discard this sample
    #for training at least one should be critical to be more sample efficient
    if np.all(critical) or np.all(np.logical_not(critical)):
        print('discard sample')
        return None

    df = []

    for start in range(len(critical)):
        label = critical[start]
        for _ in range(nr_walks):
            walk, feature = randow_walk(start, G, walk_length, face_feature)
            row = np.concatenate((np.array([label]), feature))
            df.append(row.reshape((1, -1)))

    df = pd.DataFrame(np.concatenate(df, axis=0))

    df.to_csv(savedir + f'features/{id_}.tsv',
              header=False,
              sep='\t',
              index=False)

    o3d.io.write_triangle_mesh(savedir + f'stl/{id_}.stl', mesh)

    return sample
Example #23
0
'''
Example usage of align() method:
 generate 3 random sets of points
 and align them using vtkProcrustesAlignmentFilter.
'''
from __future__ import division, print_function
from random import uniform as u

from vtkplotter import Plotter, procrustes, Text, Points

vp = Plotter(shape=[1, 2], verbose=0, axes=2, sharecam=0, bg='w')

N = 15  # number of points
x = 1.  # add some randomness

pts1 = [(u(0, x), u(0, x), u(0, x)+i) for i in range(N)]
pts2 = [(u(0, x)+3, u(0, x)+i/2+2, u(0, x)+i+1) for i in range(N)]
pts3 = [(u(0, x)+4, u(0, x)+i/4-3, u(0, x)+i-2) for i in range(N)]

act1 = Points(pts1, c='r').legend('set1')
act2 = Points(pts2, c='g').legend('set2')
act3 = Points(pts3, c='b').legend('set3')

vp.show([act1, act2, act3], at=0)

# find best alignment among the n sets of Points,
# return an Assembly formed by the aligned sets
aligned = procrustes([act1, act2, act3])

# print(aligned.info['transform'])
Example #24
0
# L-12 MCS 260 : Monte Carlo for pi
"""
We count the number of samples (x, y)
that lie in the unit disk.
"""
from random import uniform as u

print('Monte Carlo simulation for Pi')
NBR = int(input('Give number of runs : '))
INDISK = 0
for i in range(NBR):
    (X, Y) = (u(-1, 1), u(-1, 1))
    if X**2 + Y**2 <= 1:
        INDISK = INDISK + 1
print('After %d runs : %f' % (NBR, 4 * INDISK / NBR))
# Load 3 actors assigning each a different color, 
# by default use their file names as legend entries.
# No need to use any variables, as actors are stored internally in vp.actors:
vp = plotter.vtkPlotter(title='3 shapes')
vp.load('data/250.vtk', c=(1,0.4,0), alpha=.3)
vp.load('data/270.vtk', c=(1,0.6,0), alpha=.3)
vp.load('data/290.vtk', c=(1,0.8,0), alpha=.3)
print ('Loaded vtkActors: ', len(vp.actors))
vp.show()


#########################################################################################
# Draw a spline that goes through a set of points, show the points (nodes=True):
vp = plotter.vtkPlotter(title='Example of splines through 8 random points')

pts = [ (u(0,2), u(0,2), u(0,2)+i) for i in range(8) ]

vp.points(pts, legend='random points')

for i in range(10):
    vp.spline(pts, smooth=i/10, degree=2, c=i, legend='spline #'+str(i))
vp.show()


#########################################################################################
# Draw the PCA ellipsoid that contains 50% of a cloud of points,
# check if points are inside the actor surface:
vp = plotter.vtkPlotter(title='Example of PCA analysys')
pts = [(gauss(0,1), gauss(0,2), gauss(0,3)) for i in range(1000)]
a = vp.pca(pts, pvalue=0.5, pcaAxes=1, legend='PCA ellipsoid')
def path_obfuscated(b):
	global a;r=round;d=(lambda x,y:(lambda x:((lambda x:3 if r(x/2)%2==0 else 0)(x),(lambda x:0)(x),(lambda x:0)(x),(lambda x:0)(x)))(y)if x==0 else((lambda x:((lambda x:1)(x),(lambda x:-2 if r(x/4)%2==0 else 2)(x),(lambda x:0)(x),(lambda x:0)(x)))(y)if x==1 else((lambda x:((lambda x:1)(x),(lambda x:s(x/2)*1)(x),(lambda x:c(x/2)*1)(x),(lambda x:0)(x)))(y)if x==2 else((lambda x:((lambda x:1)(x),(lambda x:0)(x),(lambda x:0)(x),(lambda x:u(-1,1) if r(x/2%2,2)<=0.05 else a)(x)))(y)if x==3 else None))))(b,t());a=(d[3]if d is not None else 0);return d
Example #27
0
#########################################################################################
# Load 3 actors assigning each a different (r,g,b) color,
# No need to use any variables here, as actors are stored internally in vp.actors:
vp = Plotter(title="Three limb shapes")
vp.load(datadir+"250.vtk", c=(1, 0.4, 0), alpha=0.3)
vp.load(datadir+"270.vtk", c=(1, 0.6, 0), alpha=0.3)
vp.load(datadir+"290.vtk", c=(1, 0.8, 0), alpha=0.3)
print("Loaded meshes: ", len(vp.actors))
vp.show()


#########################################################################################
# Draw a spline through a set of points:
vp = Plotter(title="Example of splines through random points")

pts = [(u(0,2), u(0,2), u(0,2) + i) for i in range(8)]  # build python list of points
vp += Points(pts, r=10) # add the Points(vtkActor) object to the internal list of actors

for i in range(10):
    sp = Spline(pts, smooth=i/10, degree=2).color(i)
    sp.legend("smoothing " + str(i/10.0))
    vp += sp                                # add the object to Plotter
vp.show(viewup="z", axes=1, interactive=1)  # show internal list of actors


#########################################################################################
# Increase the number of vertices of a Mesh using subdivide()
# show it both before and after the cure in two separate renderers defined by shape=(1,2)
vp = Plotter(shape=(1,2), axes=0, title="L. v. Beethonven")
mesh1 = vp.load(datadir+"beethoven.ply")
pts1 = Points(mesh1, r=4, c="g").legend("#points = " + str(mesh1.N()))
Example #28
0
"""
Kochanek–Bartels spline
"""
from vtkplotter import Text, Points, KSpline, show
from random import uniform as u

pts = [(u(0, 2), u(0, 2), u(0, 2) + i) for i in range(8)]

Points(pts, r=10)
Text(__doc__)

for i in range(10):
    g = (i / 10 - 0.5) * 2  # from -1 to 1
    KSpline(pts, continuity=g, tension=0, bias=0, closed=False).color(i)

# plot all object sofar created:
show(..., viewup="z", axes=1)
Example #29
0
#########################################################################################
# Load 3 actors assigning each a different color,
# by default use their file names as legend entries.
# No need to use any variables, as actors are stored internally in vp.actors:
vp = Plotter(title='3 shapes')
vp.load('data/250.vtk', c=(1, 0.4, 0), alpha=.3)
vp.load('data/270.vtk', c=(1, 0.6, 0), alpha=.3)
vp.load('data/290.vtk', c=(1, 0.8, 0), alpha=.3)
print('Loaded vtkActors: ', len(vp.actors))
vp.show()

#########################################################################################
# Draw a spline through a set of points:
vp = Plotter(title='Example of splines through 8 random points')

pts = [(u(0, 2), u(0, 2), u(0, 2) + i)
       for i in range(8)]  # build python list of points
vp.points(pts, legend='random points')  # create the vtkActor

for i in range(10):
    vp.spline(pts,
              smooth=i / 10,
              degree=2,
              c=i,
              legend='smoothing ' + str(i / 10))
vp.show()

#########################################################################################
# Draw a cloud of points each one with a different color
# which depends on the point position itself
vp = Plotter(title='color points')
Example #30
0
def gen(z, e, c):
    return [(z[0] + u(-e, e), z[1] + u(-e, e)) for i in range(c)]