source: lmdz_wrf/trunk/tools/geometry_tools.py @ 2546

Last change on this file since 2546 was 2546, checked in by lfita, 6 years ago

Adding in `cut_ypolygon', 'keep' value

File size: 63.6 KB
Line 
1# Python tools to manage netCDF files.
2# L. Fita, CIMA. Mrch 2019
3# More information at: http://www.xn--llusfb-5va.cat/python/PyNCplot
4#
5# pyNCplot and its component geometry_tools.py comes with ABSOLUTELY NO WARRANTY.
6# This work is licendes under a Creative Commons
7#   Attribution-ShareAlike 4.0 International License (http://creativecommons.org/licenses/by-sa/4.0)
8#
9## Script for geometry calculations and operations as well as definition of different
10###    standard objects and shapes
11
12import numpy as np
13import matplotlib as mpl
14from mpl_toolkits.mplot3d import Axes3D
15import matplotlib.pyplot as plt
16import os
17import generic_tools as gen
18import numpy.ma as ma
19import module_ForSci as sci
20
21errormsg = 'ERROR -- error -- ERROR -- error'
22infmsg = 'INFORMATION -- information -- INFORMATION -- information'
23
24####### Contents:
25# cut_ypolygon: Function to cut a polygon from a given value of the y-axis
26# deg_deci: Function to pass from degrees [deg, minute, sec] to decimal angles [rad]
27# dist_points: Function to provide the distance between two points
28# join_circ_sec: Function to join aa series of points by circular segments
29# join_circ_sec_rand: Function to join aa series of points by circular segments with
30#   random perturbations
31# max_coords_poly: Function to provide the extremes of the coordinates of a polygon
32# mirror_polygon: Function to reflex a polygon for a given axis
33# position_sphere: Function to tranform fom a point in lon, lat deg coordinates to
34#   cartesian coordinates over an sphere
35# read_join_poly: Function to read an ASCII file with the combination of polygons
36# rotate_2D: Function to rotate a vector by a certain angle in the plain
37# rotate_polygon_2D: Function to rotate 2D plain the vertices of a polygon
38# rotate_line2D: Function to rotate a line given by 2 pairs of x,y coordinates by a
39#   certain angle in the plain
40# rotate_lines2D: Function to rotate multiple lines given by mulitple pars of x,y
41#   coordinates by a certain angle in the plain
42# spheric_line: Function to transform a series of locations in lon, lat coordinates
43#   to x,y,z over an 3D spaceFunction to provide coordinates of a line  on a 3D space
44# write_join_poly: Function to write an ASCII file with the combination of polygons
45
46## Shapes/objects
47# buoy1: Function to draw a buoy as superposition of prism and section of ball
48# circ_sec: Function union of point A and B by a section of a circle
49# ellipse_polar: Function to determine an ellipse from its center and polar coordinates
50# p_angle_triangle: Function to draw a triangle by an initial point and two
51#   consecutive angles and the first length of face. The third angle and 2 and 3rd
52#   face will be computed accordingly the provided values
53# p_doubleArrow: Function to provide an arrow with double lines
54# p_circle: Function to get a polygon of a circle
55# p_reg_polygon: Function to provide a regular polygon of Nv vertices
56# p_reg_star: Function to provide a regular star of Nv vertices
57# p_sinusiode: Function to get coordinates of a sinusoidal curve
58# p_square: Function to get a polygon square
59# p_spiral: Function to provide a polygon of an Archimedean spiral
60# p_triangle: Function to provide the polygon of a triangle from its 3 vertices
61# band_lighthouse: Function to plot a lighthouse with spiral bands
62# surface_sphere: Function to provide an sphere as matrix of x,y,z coordinates
63# z_boat: Function to define an schematic boat from the z-plane
64# zsailing_boat: Function to define an schematic sailing boat from the z-plane with sails
65# zisland1: Function to draw an island from z-axis as the union of a series of points by
66#   circular segments
67
68## Plotting
69# paint_filled: Function to draw an object filling given sections
70# plot_sphere: Function to plot an sphere and determine which standard lines will be
71#   also drawn
72# [north/east/south/west_buoy1: Function to draw a [North/East/South/West] danger buoy using buoy1
73
74def deg_deci(angle):
75    """ Function to pass from degrees [deg, minute, sec] to decimal angles [rad]
76      angle: list of [deg, minute, sec] to pass
77    >>> deg_deci([41., 58., 34.])
78    0.732621346072
79    """
80    fname = 'deg_deci'
81
82    deg = np.abs(angle[0]) + np.abs(angle[1])/60. + np.abs(angle[2])/3600.
83
84    if angle[0] < 0.: deg = -deg*np.pi/180.
85    else: deg = deg*np.pi/180.
86
87    return deg
88
89def position_sphere(radii, alpha, beta):
90    """ Function to tranform fom a point in lon, lat deg coordinates to cartesian 
91          coordinates over an sphere
92      radii: radii of the sphere
93      alpha: longitude of the point
94      beta: latitude of the point
95    >>> position_sphere(10., 30., 45.)
96    (0.81031678432964027, -5.1903473778327376, 8.5090352453411846
97    """
98    fname = 'position_sphere'
99
100    xpt = radii*np.cos(beta)*np.cos(alpha)
101    ypt = radii*np.cos(beta)*np.sin(alpha)
102    zpt = radii*np.sin(beta)
103
104    return xpt, ypt, zpt
105
106def spheric_line(radii,lon,lat):
107    """ Function to transform a series of locations in lon, lat coordinates to x,y,z
108          over an 3D space
109      radii: radius of the sphere
110      lon: array of angles along longitudes
111      lat: array of angles along latitudes
112    """
113    fname = 'spheric_line'
114
115    Lint = lon.shape[0]
116    coords = np.zeros((Lint,3), dtype=np.float)
117
118    for iv in range(Lint):
119        coords[iv,:] = position_sphere(radii, lon[iv], lat[iv])
120
121    return coords
122
123def rotate_2D(vector, angle):
124    """ Function to rotate a vector by a certain angle in the plain
125      vector= vector to rotate [y, x]
126      angle= angle to rotate [rad]
127    >>> rotate_2D(np.array([1.,0.]), np.pi/4.)
128    [ 0.70710678 -0.70710678]
129    """
130    fname = 'rotate_2D'
131
132    rotmat = np.zeros((2,2), dtype=np.float)
133
134    rotmat[0,0] = np.cos(angle)
135    rotmat[0,1] = -np.sin(angle)
136    rotmat[1,0] = np.sin(angle)
137    rotmat[1,1] = np.cos(angle)
138
139    rotvector = np.zeros((2), dtype=np.float)
140
141    vecv = np.zeros((2), dtype=np.float)
142
143    # Unifying vector
144    modvec = vector[0]**2+vector[1]**2
145    if modvec != 0: 
146        vecv[0] = vector[1]/modvec
147        vecv[1] = vector[0]/modvec
148
149        rotvec = np.matmul(rotmat, vecv)
150        rotvec = np.where(np.abs(rotvec) < 1.e-7, 0., rotvec)
151
152        rotvector[0] = rotvec[1]*modvec
153        rotvector[1] = rotvec[0]*modvec
154
155    return rotvector
156
157def rotate_polygon_2D(vectors, angle):
158    """ Function to rotate 2D plain the vertices of a polygon
159      line= matrix of vectors to rotate
160      angle= angle to rotate [rad]
161    >>> square = np.zeros((4,2), dtype=np.float)
162    >>> square[0,:] = [-0.5,-0.5]
163    >>> square[1,:] = [0.5,-0.5]
164    >>> square[2,:] = [0.5,0.5]
165    >>> square[3,:] = [-0.5,0.5]
166    >>> rotate_polygon_2D(square, np.pi/4.)
167    [[-0.70710678  0.        ]
168     [ 0.         -0.70710678]
169     [ 0.70710678  0.        ]
170     [ 0.          0.70710678]]
171    """
172    fname = 'rotate_polygon_2D'
173
174    rotvecs = np.zeros(vectors.shape, dtype=np.float)
175
176    Nvecs = vectors.shape[0]
177    for iv in range(Nvecs):
178        rotvecs[iv,:] = rotate_2D(vectors[iv,:], angle)
179
180    return rotvecs
181
182def rotate_line2D(line, angle):
183    """ Function to rotate a line given by 2 pairs of x,y coordinates by a certain
184          angle in the plain
185      line= line to rotate as couple of points [[y0,x0], [y1,x1]]
186      angle= angle to rotate [rad]
187    >>> rotate_line2D(np.array([[0.,0.], [1.,0.]]), np.pi/4.)
188    [[ 0.          0.        ]
189     [0.70710678  -0.70710678]]
190    """
191    fname = 'rotate_2D'
192
193    rotline = np.zeros((2,2), dtype=np.float)
194    rotline[0,:] = rotate_2D(line[0,:], angle)
195    rotline[1,:] = rotate_2D(line[1,:], angle)
196
197    return rotline
198
199def rotate_lines2D(lines, angle):
200    """ Function to rotate multiple lines given by mulitple pars of x,y coordinates 
201          by a certain angle in the plain
202      line= matrix of N couples of points [N, [y0,x0], [y1,x1]]
203      angle= angle to rotate [rad]
204    >>> square = np.zeros((4,2,2), dtype=np.float)
205    >>> square[0,0,:] = [-0.5,-0.5]
206    >>> square[0,1,:] = [0.5,-0.5]
207    >>> square[1,0,:] = [0.5,-0.5]
208    >>> square[1,1,:] = [0.5,0.5]
209    >>> square[2,0,:] = [0.5,0.5]
210    >>> square[2,1,:] = [-0.5,0.5]
211    >>> square[3,0,:] = [-0.5,0.5]
212    >>> square[3,1,:] = [-0.5,-0.5]
213    >>> rotate_lines2D(square, np.pi/4.)
214    [[[-0.70710678  0.        ]
215      [ 0.         -0.70710678]]
216
217     [[ 0.         -0.70710678]
218      [ 0.70710678  0.        ]]
219
220     [[ 0.70710678  0.        ]
221      [ 0.          0.70710678]]
222
223     [[ 0.          0.70710678]
224      [-0.70710678  0.        ]]]
225    """
226    fname = 'rotate_lines2D'
227
228    rotlines = np.zeros(lines.shape, dtype=np.float)
229
230    Nlines = lines.shape[0]
231    for il in range(Nlines):
232        line = np.zeros((2,2), dtype=np.float)
233        line[0,:] = lines[il,0,:]
234        line[1,:] = lines[il,1,:]
235
236        rotlines[il,:,:] = rotate_line2D(line, angle)
237
238    return rotlines
239
240def dist_points(ptA, ptB):
241    """ Function to provide the distance between two points
242      ptA: coordinates of the point A [yA, xA]
243      ptB: coordinates of the point B [yB, xB]
244    >>> dist_points([1.,1.], [-1.,-1.])
245    2.82842712475
246    """
247    fname = 'dist_points'
248
249    dist = np.sqrt( (ptA[0]-ptB[0])**2 + (ptA[1]-ptB[1])**2)
250
251    return dist
252
253def max_coords_poly(polygon):
254    """ Function to provide the extremes of the coordinates of a polygon
255      polygon: coordinates [Nvertexs, 2] of a polygon
256    >>> square = np.zeros((4,2), dtype=np.float)
257    >>> square[0,:] = [-0.5,-0.5]
258    >>> square[1,:] = [0.5,-0.5]
259    >>> square[2,:] = [0.5,0.5]
260    >>> square[3,:] = [-0.5,0.5]
261    >>> max_coords_poly(square)
262    [-0.5, 0.5], [-0.5, 0.5], [0.5, 0.5], 0.5
263    """
264    fname = 'max_coords_poly'
265
266    # x-coordinate min/max
267    nx = np.min(polygon[:,1])
268    xx = np.max(polygon[:,1])
269
270    # y-coordinate min/max
271    ny = np.min(polygon[:,0])
272    xy = np.max(polygon[:,0])
273
274    # x/y-coordinate maximum of absolute values
275    axx = np.max(np.abs(polygon[:,1]))
276    ayx = np.max(np.abs(polygon[:,0]))
277
278    # absolute maximum
279    xyx = np.max([axx, ayx])
280
281    return [nx, xx], [ny, xy], [ayx, axx], xyx
282
283def mirror_polygon(polygon,axis):
284    """ Function to reflex a polygon for a given axis
285      polygon: polygon to mirror
286      axis: axis at which mirror is located ('x' or 'y')
287    """
288    fname = 'mirror_polygon'
289
290    reflex = np.zeros(polygon.shape, dtype=np.float)
291
292    N = polygon.shape[0]
293    if axis == 'x':
294        for iv in range(N):
295            reflex[iv,:] = [-polygon[iv,0], polygon[iv,1]]
296    elif axis == 'y':
297        for iv in range(N):
298            reflex[iv,:] = [polygon[iv,0], -polygon[iv,1]]
299
300    return reflex
301
302def join_circ_sec(points, radfrac=3., N=200):
303    """ Function to join aa series of points by circular segments
304      points: main points of the island (clockwise ordered, to be joined by circular
305        segments of radii as the radfrac factor of the distance between
306        consecutive points)
307      radfrac: multiplicative factor of the distance between consecutive points to
308        draw the circular segment (3., default)
309      N: number of points (200, default)
310    """
311    fname = 'join_circ_sec'
312
313    jcirc_sec = np.ones((N,2), dtype=np.float)
314
315    # main points
316    lpoints = list(points)
317    Npts = len(lpoints)
318    Np = int(N/(Npts+1))
319    for ip in range(Npts-1):
320        p1 = lpoints[ip]
321        p2 = lpoints[ip+1]
322        dps = dist_points(p1, p2)
323        jcirc_sec[Np*ip:Np*(ip+1),:] = circ_sec(p1, p2, dps*radfrac, 'short', Np)
324
325    Np2 = N - (Npts-1)*Np
326    p1 = lpoints[Npts-1]
327    p2 = lpoints[0]
328    dps = dist_points(p1, p2)
329    jcirc_sec[(Npts-1)*Np:N,:] = circ_sec(p1, p2, dps*3., 'short', Np2)
330
331    return jcirc_sec
332
333def join_circ_sec_rand(points, radfrac=3., Lrand=0.1, arc='short', pos='left', N=200):
334    """ Function to join aa series of points by circular segments with random
335        perturbations
336      points: main points of the island (clockwise ordered, to be joined by circular
337        segments of radii as the radfrac factor of the distance between
338        consecutive points)
339      radfrac: multiplicative factor of the distance between consecutive points to
340        draw the circular segment (3., default)
341      Lrand: maximum length of the random perturbation to be added perpendicularly to
342        the direction of the union line between points (0.1, default)
343      arc: type of arc ('short', default)
344      pos: position of arc ('left', default)
345      N: number of points (200, default)
346    """
347    import random
348    fname = 'join_circ_sec_rand'
349
350    jcirc_sec = np.ones((N,2), dtype=np.float)
351
352    # main points
353    lpoints = list(points)
354    Npts = len(lpoints)
355    Np = int(N/(Npts+1))
356    for ip in range(Npts-1):
357        p1 = lpoints[ip]
358        p2 = lpoints[ip+1]
359        dps = dist_points(p1, p2)
360        angle = np.arctan2(p2[0]-p1[0], p2[1]-p1[1]) + np.pi/2.
361        jcirc_sec[Np*ip:Np*(ip+1),:] = circ_sec(p1, p2, dps*radfrac, arc, pos, Np)
362        drand = Lrand*np.array([np.sin(angle), np.cos(angle)])
363        for iip in range(Np*ip,Np*(ip+1)):
364            jcirc_sec[iip,:] = jcirc_sec[iip,:] + drand*random.uniform(-1.,1.)
365
366    Np2 = N - (Npts-1)*Np
367    p1 = lpoints[Npts-1]
368    p2 = lpoints[0]
369    dps = dist_points(p1, p2)
370    angle = np.arctan2(p2[0]-p1[0], p2[1]-p1[1]) + np.pi/2.
371    jcirc_sec[(Npts-1)*Np:N,:] = circ_sec(p1, p2, dps*3., arc, pos, Np2)
372    drand = Lrand*np.array([np.sin(angle), np.cos(angle)])
373    for iip in range(Np*(Npts-1),N):
374        jcirc_sec[iip,:] = jcirc_sec[iip,:] + drand*random.uniform(-1.,1.)
375
376    return jcirc_sec
377
378def write_join_poly(polys, flname='join_polygons.dat'):
379    """ Function to write an ASCII file with the combination of polygons
380      polys: dictionary with the names of the different polygons
381      flname: name of the ASCII file
382    """
383    fname = 'write_join_poly'
384
385    of = open(flname, 'w')
386
387    for polyn in polys.keys():
388        vertices = polys[polyn]
389        Npts = vertices.shape[0]
390        for ip in range(Npts):
391            of.write(polyn+' '+str(vertices[ip,1]) + ' ' + str(vertices[ip,0]) + '\n')
392
393    of.close()
394
395    return
396
397def read_join_poly(flname='join_polygons.dat'):
398    """ Function to read an ASCII file with the combination of polygons
399      flname: name of the ASCII file
400    """
401    fname = 'read_join_poly'
402
403    of = open(flname, 'r')
404
405    polys = {}
406    polyn = ''
407    poly = []
408    for line in of:
409        if len(line) > 1: 
410            linevals = line.replace('\n','').split(' ')
411            if polyn != linevals[0]:
412                if len(poly) > 1:
413                    polys[polyn] = np.array(poly)
414                polyn = linevals[0]
415                poly = []
416                poly.append([np.float(linevals[2]), np.float(linevals[1])])
417            else:
418                poly.append([np.float(linevals[2]), np.float(linevals[1])])
419
420    of.close()
421    polys[polyn] = np.array(poly)
422
423    return polys
424
425def cut_ypolygon(polygon, yval, keep='bottom', Nadd=20):
426    """ Function to cut a polygon from a given value of the y-axis
427      polygon: polygon to cut
428      yval: value to use to cut the polygon
429      keep: part to keep from the height ('bottom', default)
430         'bottom': below the height
431         'above': above the height
432      Nadd: additional points to add to draw the line (20, default)
433    """
434    fname = 'cut_ypolygon'
435
436    N = polygon.shape[0]
437    availkeeps = ['bottom', 'above']
438
439    if not gen.searchInlist(availkeeps, keep):
440        print errormsg
441        print '  ' + fname + ": wring keep '" + keep + "' value !!"
442        print '    available ones:', availkeeps
443        quit(-1)
444
445    ipt = None
446    ept = None
447
448    if type(polygon) == type(gen.mamat):
449        # Assuming clockwise polygons
450        for ip in range(N):
451            if not polygon.mask[ip,0]:
452                eep = ip + 1
453                if eep == N: eep = 0
454     
455                if polygon[ip,0] <= yval and polygon[eep,0] >= yval:
456                    icut = ip
457                    dx = polygon[eep,1] - polygon[ip,1]
458                    dy = polygon[eep,0] - polygon[ip,0]
459                    dd = yval - polygon[ip,0]
460                    ipt = [yval, polygon[ip,1]+dx*dd/dy]
461
462                if polygon[ip,0] >= yval and polygon[eep,0] <= yval:
463                    ecut = ip
464                    dx = polygon[eep,1] - polygon[ip,1]
465                    dy = polygon[eep,0] - polygon[ip,0]
466                    dd = yval - polygon[eep,0]
467                    ept = [yval, polygon[eep,1]+dx*dd/dy]
468    else:
469        # Assuming clockwise polygons
470        for ip in range(N):
471            eep = ip + 1
472            if eep == N: eep = 0
473     
474            if polygon[ip,0] <= yval and polygon[eep,0] >= yval:
475                icut = ip
476                dx = polygon[eep,1] - polygon[ip,1]
477                dy = polygon[eep,0] - polygon[ip,0]
478                dd = yval - polygon[ip,0]
479                ipt = [yval, polygon[ip,1]+dx*dd/dy]
480
481            if polygon[ip,0] >= yval and polygon[eep,0] <= yval:
482                ecut = ip
483                dx = polygon[eep,1] - polygon[ip,1]
484                dy = polygon[eep,0] - polygon[ip,0]
485                dd = yval - polygon[ip,0]
486                ept = [yval, polygon[ip,1]+dx*dd/dy]
487
488    if ipt is None or ept is None:
489        print errormsg
490        print '  ' + fname + ': no cutting for polygon at y=', yval, '!!'
491        irmv = 0
492        rmpolygon = []
493        if keep == 'bottom':
494            for ip in range(N):
495                if polygon[ip,0] > yval:
496                    rmpolygon.append([gen.fillValueF, gen.fillValueF])
497                else:
498                    rmpolygon.append(polygon[ip,:])
499        else:
500            for ip in range(N):
501                if polygon[ip,0] < yval:
502                    rmpolygon.append([gen.fillValueF, gen.fillValueF])
503                else:
504                    rmpolygon.append(polygon[ip,:])
505
506        Npts = len(rmpolygon)
507        cutpolygon = np.array(rmpolygon)
508    else:
509        if keep == 'bottom':
510            Npts = icut + (N-ecut) + Nadd
511
512            cutpolygon = np.zeros((Npts,2), dtype=np.float)
513            if type(polygon) == type(gen.mamat):
514                cutpolygon[0:icut+1,:] = polygon[0:icut+1,:].filled(gen.fillValueF)
515            else:
516                cutpolygon[0:icut+1,:] = polygon[0:icut+1,:]
517            iip = icut+1
518        else:
519            Npts = ecut - icut + Nadd-1
520
521            cutpolygon = np.zeros((Npts,2), dtype=np.float)
522            if type(polygon) == type(gen.mamat):
523                cutpolygon[0:ecut-icut-1,:] = polygon[icut+1:ecut,:].filled(gen.fillValueF)
524            else:
525                cutpolygon[0:ecut-icut-1,:] = polygon[icut+1:ecut,:]
526            iip = ecut-icut-1
527
528        # cutting line
529        cutline = np.zeros((Nadd,2), dtype=np.float)
530        dx = (ept[1] - ipt[1])/(Nadd-2)
531        dy = (ept[0] - ipt[0])/(Nadd-2)
532        cutline[0,:] = ipt
533        for ip in range(1,Nadd-1):
534            cutline[ip,:] = ipt + np.array([dy*ip,dx*ip])
535        cutline[Nadd-1,:] = ept
536        cutpolygon[iip:iip+Nadd,:] = cutline
537        if keep == 'bottom':
538            cutpolygon[iip+Nadd:Npts,:] = polygon[ecut+1:N,:]
539
540    cutpolygon = ma.masked_equal(cutpolygon, gen.fillValueF)
541
542    return Npts, cutpolygon
543
544####### ###### ##### #### ### ## #
545# Shapes/objects
546
547def surface_sphere(radii,Npts):
548    """ Function to provide an sphere as matrix of x,y,z coordinates
549      radii: radii of the sphere
550      Npts: number of points to discretisize longitues (half for latitudes)
551    """
552    fname = 'surface_sphere'
553
554    sphereup = np.zeros((3,Npts/2,Npts), dtype=np.float)
555    spheredown = np.zeros((3,Npts/2,Npts), dtype=np.float)
556    for ia in range(Npts):
557        alpha = ia*2*np.pi/(Npts-1)
558        for ib in range(Npts/2):
559            beta = ib*np.pi/(2.*(Npts/2-1))
560            sphereup[:,ib,ia] = position_sphere(radii, alpha, beta)
561        for ib in range(Npts/2):
562            beta = -ib*np.pi/(2.*(Npts/2-1))
563            spheredown[:,ib,ia] = position_sphere(radii, alpha, beta)
564
565    return sphereup, spheredown
566
567def ellipse_polar(c, a, b, Nang=100):
568    """ Function to determine an ellipse from its center and polar coordinates
569        FROM: https://en.wikipedia.org/wiki/Ellipse
570      c= coordinates of the center
571      a= distance major axis
572      b= distance minor axis
573      Nang= number of angles to use
574    """
575    fname = 'ellipse_polar'
576
577    if np.mod(Nang,2) == 0: Nang=Nang+1
578 
579    dtheta = 2*np.pi/(Nang-1)
580
581    ellipse = np.zeros((Nang,2), dtype=np.float)
582    for ia in range(Nang):
583        theta = dtheta*ia
584        rad = a*b/np.sqrt( (b*np.cos(theta))**2 + (a*np.sin(theta))**2 )
585        x = rad*np.cos(theta)
586        y = rad*np.sin(theta)
587        ellipse[ia,:] = [y+c[0],x+c[1]]
588
589    return ellipse
590
591def hyperbola_polar(a, b, Nang=100):
592    """ Fcuntion to determine an hyperbola in polar coordinates
593        FROM: https://en.wikipedia.org/wiki/Hyperbola#Polar_coordinates
594          x^2/a^2 - y^2/b^2 = 1
595      a= x-parameter
596      y= y-parameter
597      Nang= number of angles to use
598      DOES NOT WORK!!!!
599    """
600    fname = 'hyperbola_polar'
601
602    dtheta = 2.*np.pi/(Nang-1)
603
604    # Positive branch
605    hyperbola_p = np.zeros((Nang,2), dtype=np.float)
606    for ia in range(Nang):
607        theta = dtheta*ia
608        x = a*np.cosh(theta)
609        y = b*np.sinh(theta)
610        hyperbola_p[ia,:] = [y,x]
611
612    # Negative branch
613    hyperbola_n = np.zeros((Nang,2), dtype=np.float)
614    for ia in range(Nang):
615        theta = dtheta*ia
616        x = -a*np.cosh(theta)
617        y = b*np.sinh(theta)
618        hyperbola_n[ia,:] = [y,x]
619
620    return hyperbola_p, hyperbola_n
621
622def circ_sec(ptA, ptB, radii, arc='short', pos='left', Nang=100):
623    """ Function union of point A and B by a section of a circle
624      ptA= coordinates od the point A [yA, xA]
625      ptB= coordinates od the point B [yB, xB]
626      radii= radi of the circle to use to unite the points
627      arc= which arc to be used ('short', default)
628        'short': shortest angle between points
629        'long': largest angle between points
630      pos= orientation of the arc following clockwise union of points ('left', default)
631        'left': to the left of union
632        'right': to the right of union
633      Nang= amount of angles to use
634    """
635    fname = 'circ_sec'
636    availarc = ['short', 'long']
637    availpos = ['left', 'right']
638
639    distAB = dist_points(ptA,ptB)
640
641    if distAB > radii:
642        print errormsg
643        print '  ' + fname + ': radii=', radii, " too small for the distance " +     \
644          "between points !!"
645        print '    distance between points:', distAB
646        quit(-1)
647
648    # Coordinate increments
649    dAB = np.abs(ptA-ptB)
650
651    # angle of the circular section joining points
652    alpha = 2.*np.arcsin((distAB/2.)/radii)
653
654    # center along coincident bisection of the union
655    xcc = -radii
656    ycc = 0.
657
658    # Getting the arc of the circle at the x-axis
659    if arc == 'short':
660        dalpha = alpha/(Nang-1)
661    elif arc == 'long':
662        dalpha = (2.*np.pi - alpha)/(Nang-1)
663    else:
664        print errormsg
665        print '  ' + fname + ": arc '" + arc + "' not ready !!" 
666        print '    available ones:', availarc
667        quit(-1)
668    if pos == 'left': sign=-1.
669    elif pos == 'right': sign=1.
670    else:
671        print errormsg
672        print '  ' + fname + ": position '" + pos + "' not ready !!" 
673        print '     available ones:', availpos
674        quit(-1)
675
676    circ_sec = np.zeros((Nang,2), dtype=np.float)
677    for ia in range(Nang):
678        alpha = sign*dalpha*ia
679        x = radii*np.cos(alpha)
680        y = radii*np.sin(alpha)
681
682        circ_sec[ia,:] = [y+ycc,x+xcc]
683
684    # Angle of the points
685    theta = np.arctan2(ptB[0]-ptA[0],ptB[1]-ptA[1])
686
687    # rotating angle of the circ
688    if pos == 'left': 
689        rotangle = theta + np.pi/2. - alpha/2.
690    elif pos == 'right':
691        rotangle = theta + 3.*np.pi/2. - alpha/2.
692    else:
693        print errormsg
694        print '  ' + fname + ": position '" + pos + "' not ready !!" 
695        print '     available ones:', availpos
696        quit(-1)
697
698    #print 'alpha:', alpha*180./np.pi, 'theta:', theta*180./np.pi, 'rotangle:', rotangle*180./np.pi
699 
700    # rotating the arc along the x-axis
701    rotcirc_sec = rotate_polygon_2D(circ_sec, rotangle)
702
703    # Moving arc to the ptA
704    circ_sec = rotcirc_sec + ptA
705
706    return circ_sec
707
708def p_square(face, N=5):
709    """ Function to get a polygon square
710      face: length of the face of the square
711      N: number of points of the polygon
712    """
713    fname = 'p_square'
714
715    square = np.zeros((N,2), dtype=np.float)
716
717    f2 = face/2.
718    N4 = N/4
719    df = face/(N4)
720    # SW-NW
721    for ip in range(N4):
722        square[ip,:] = [-f2+ip*df,-f2]
723    # NW-NE
724    for ip in range(N4):
725        square[ip+N4,:] = [f2,-f2+ip*df]
726    # NE-SE
727    for ip in range(N4):
728        square[ip+2*N4,:] = [f2-ip*df,f2]
729    N42 = N-3*N4-1
730    df = face/(N42)
731    # SE-SW
732    for ip in range(N42):
733        square[ip+3*N4,:] = [-f2,f2-ip*df]
734    square[N-1,:] = [-f2,-f2]
735
736    return square
737
738def p_circle(radii, N=50):
739    """ Function to get a polygon of a circle
740      radii: length of the radii of the circle
741      N: number of points of the polygon
742    """
743    fname = 'p_circle'
744
745    circle = np.zeros((N,2), dtype=np.float)
746
747    dangle = 2.*np.pi/(N-1)
748
749    for ia in range(N):
750        circle[ia,:] = [radii*np.sin(ia*dangle), radii*np.cos(ia*dangle)]
751
752    circle[N-1,:] = [0., radii]
753
754    return circle
755
756def p_triangle(p1, p2, p3, N=4):
757    """ Function to provide the polygon of a triangle from its 3 vertices
758      p1: vertex 1 [y,x]
759      p2: vertex 2 [y,x]
760      p3: vertex 3 [y,x]
761      N: number of vertices of the triangle
762    """
763    fname = 'p_triangle'
764
765    triangle = np.zeros((N,2), dtype=np.float)
766
767    N3 = N / 3
768    # 1-2
769    dx = (p2[1]-p1[1])/N3
770    dy = (p2[0]-p1[0])/N3
771    for ip in range(N3):
772        triangle[ip,:] = [p1[0]+ip*dy,p1[1]+ip*dx]
773    # 2-3
774    dx = (p3[1]-p2[1])/N3
775    dy = (p3[0]-p2[0])/N3
776    for ip in range(N3):
777        triangle[ip+N3,:] = [p2[0]+ip*dy,p2[1]+ip*dx]
778    # 3-1
779    N32 = N - 2*N/3
780    dx = (p1[1]-p3[1])/N32
781    dy = (p1[0]-p3[0])/N32
782    for ip in range(N32):
783        triangle[ip+2*N3,:] = [p3[0]+ip*dy,p3[1]+ip*dx]
784
785    triangle[N-1,:] = p1
786
787    return triangle
788
789def p_spiral(loops, eradii, N=1000):
790    """ Function to provide a polygon of an Archimedean spiral
791        FROM: https://en.wikipedia.org/wiki/Spiral
792      loops: number of loops of the spiral
793      eradii: length of the radii of the final spiral
794      N: number of points of the polygon
795    """
796    fname = 'p_spiral'
797
798    spiral = np.zeros((N,2), dtype=np.float)
799
800    dangle = 2.*np.pi*loops/(N-1)
801    dr = eradii*1./(N-1)
802
803    for ia in range(N):
804        radii = dr*ia
805        spiral[ia,:] = [radii*np.sin(ia*dangle), radii*np.cos(ia*dangle)]
806
807    return spiral
808
809def p_reg_polygon(Nv, lf, N=50):
810    """ Function to provide a regular polygon of Nv vertices
811      Nv: number of vertices
812      lf: length of the face
813      N: number of points
814    """
815    fname = 'p_reg_polygon'
816
817    reg_polygon = np.zeros((N,2), dtype=np.float)
818
819    # Number of points per vertex
820    Np = N/Nv
821    # Angle incremental between vertices
822    da = 2.*np.pi/Nv
823    # Radii of the circle according to lf
824    radii = lf*Nv/(2*np.pi)
825
826    iip = 0
827    for iv in range(Nv-1):
828        # Characteristics between vertices iv and iv+1
829        av1 = da*iv
830        v1 = [radii*np.sin(av1), radii*np.cos(av1)]
831        av2 = da*(iv+1)
832        v2 = [radii*np.sin(av2), radii*np.cos(av2)]
833        dx = (v2[1]-v1[1])/Np
834        dy = (v2[0]-v1[0])/Np
835        for ip in range(Np):
836            reg_polygon[ip+iv*Np,:] = [v1[0]+dy*ip,v1[1]+dx*ip]
837
838    # Characteristics between vertices Nv and 1
839
840    # Number of points per vertex
841    Np2 = N - Np*(Nv-1)
842
843    av1 = da*Nv
844    v1 = [radii*np.sin(av1), radii*np.cos(av1)]
845    av2 = 0.
846    v2 = [radii*np.sin(av2), radii*np.cos(av2)]
847    dx = (v2[1]-v1[1])/Np2
848    dy = (v2[0]-v1[0])/Np2
849    for ip in range(Np2):
850        reg_polygon[ip+(Nv-1)*Np,:] = [v1[0]+dy*ip,v1[1]+dx*ip]
851
852    return reg_polygon
853
854def p_reg_star(Nv, lf, freq, vs=0, N=50):
855    """ Function to provide a regular star of Nv vertices
856      Nv: number of vertices
857      lf: length of the face of the regular polygon
858      freq: frequency of union of vertices ('0', for just centered to zero arms)
859      vs: vertex from which start (0 being first [0,lf])
860      N: number of points
861    """
862    fname = 'p_reg_star'
863
864    reg_star = np.zeros((N,2), dtype=np.float)
865
866    # Number of arms of the star
867    if freq != 0 and np.mod(Nv,freq) == 0: 
868        Na = Nv/freq + 1
869    else:
870        Na = Nv
871
872    # Number of points per arm
873    Np = N/Na
874    # Angle incremental between vertices
875    da = 2.*np.pi/Nv
876    # Radii of the circle according to lf
877    radii = lf*Nv/(2*np.pi)
878
879    iip = 0
880    av1 = vs*da
881    for iv in range(Na-1):
882        # Characteristics between vertices iv and iv+1
883        v1 = [radii*np.sin(av1), radii*np.cos(av1)]
884        if freq != 0:
885            av2 = av1 + da*freq
886            v2 = [radii*np.sin(av2), radii*np.cos(av2)]
887        else:
888            v2 = [0., 0.]
889            av2 = av1 + da
890        dx = (v2[1]-v1[1])/(Np-1)
891        dy = (v2[0]-v1[0])/(Np-1)
892        for ip in range(Np):
893            reg_star[ip+iv*Np,:] = [v1[0]+dy*ip,v1[1]+dx*ip]
894        if av2 > 2.*np.pi: av1 = av2 - 2.*np.pi
895        else: av1 = av2 + 0.
896
897    iv = Na-1
898    # Characteristics between vertices Na and 1
899    Np2 = N-Np*iv
900    v1 = [radii*np.sin(av1), radii*np.cos(av1)]
901    if freq != 0:
902        av2 = vs*da
903        v2 = [radii*np.sin(av2), radii*np.cos(av2)]
904    else:
905        v2 = [0., 0.]
906    dx = (v2[1]-v1[1])/(Np2-1)
907    dy = (v2[0]-v1[0])/(Np2-1)
908    for ip in range(Np2):
909        reg_star[ip+iv*Np,:] = [v1[0]+dy*ip,v1[1]+dx*ip]
910
911    return reg_star
912
913def p_sinusiode(length=10., amp=5., lamb=3., ival=0., func='sin', N=100):
914    """ Function to get coordinates of a sinusoidal curve
915      length: length of the line (default 10.)
916      amp: amplitude of the peaks (default 5.)
917      lamb: wave longitude (defalult 3.)
918      ival: initial angle (default 0. in degree)
919      func: function to use: (default sinus)
920        'sin': sinus
921        'cos': cosinus
922      N: number of points (default 100)
923    """
924    fname = 'p_sinusiode'
925    availfunc = ['sin', 'cos']
926
927    dx = length/(N-1)
928    ia = ival*np.pi/180.
929    da = 2*np.pi*dx/lamb
930
931    sinusoide = np.zeros((N,2), dtype=np.float)
932    if func == 'sin':
933        for ix in range(N):
934            sinusoide[ix,:] = [amp*np.sin(ia+da*ix),dx*ix]
935    elif func == 'cos':
936        for ix in range(N):
937            sinusoide[ix,:] = [amp*np.cos(ia+da*ix),dx*ix]
938    else:
939        print errormsg
940        print '  ' + fname + ": function '" + func + "' not ready !!"
941        print '    available ones:', availfunc
942        quit(-1)
943
944    sinusoidesecs = ['sinusoide']
945    sinusoidedic = {'sinusoide': [sinusoide, '-', '#000000', 1.]}
946
947    return sinusoide, sinusoidesecs, sinusoidedic
948
949def p_doubleArrow(length=5., angle=45., width=1., alength=0.10, N=50):
950    """ Function to provide an arrow with double lines
951      length: length of the arrow (5. default)
952      angle: angle of the head of the arrow (45., default)
953      width: separation between the two lines (2., default)
954      alength: length of the head (as percentage in excess of width, 0.1 default)
955      N: number of points (50, default)
956    """
957    function = 'p_doubleArrow'
958
959    doubleArrow = np.zeros((50,2), dtype=np.float)
960    N4 = int((N-3)/4)
961
962    doublearrowdic = {}
963    ddy = width*np.tan(angle*np.pi/180.)/2.
964    # Arms
965    dx = (length-ddy)/(N4-1)
966    for ix in range(N4):
967        doubleArrow[ix,:] = [dx*ix,-width/2.]
968    doublearrowdic['leftarm'] = [doubleArrow[0:N4,:], '-', '#000000', 2.]
969    doubleArrow[N4,:] = [gen.fillValueF,gen.fillValueF]
970    for ix in range(N4):
971        doubleArrow[N4+1+ix,:] = [dx*ix,width/2.]
972    doublearrowdic['rightarm'] = [doubleArrow[N4+1:2*N4+1,:], '-', '#000000', 2.]
973    doubleArrow[2*N4+1,:] = [gen.fillValueF,gen.fillValueF]
974
975    # Head
976    N42 = int((N-2 - 2*N4)/2)
977    dx = width*(1.+alength)*np.cos(angle*np.pi/180.)/(N42-1)
978    dy = width*(1.+alength)*np.sin(angle*np.pi/180.)/(N42-1)
979    for ix in range(N42):
980        doubleArrow[2*N4+2+ix,:] = [length-dy*ix,-dx*ix]
981    doublearrowdic['lefthead'] = [doubleArrow[2*N4:2*N4+N42,:], '-', '#000000', 2.]
982    doubleArrow[2*N4+2+N42,:] = [gen.fillValueF,gen.fillValueF]
983
984    N43 = N-3 - 2*N4 - N42 + 1
985    dx = width*(1.+alength)*np.cos(angle*np.pi/180.)/(N43-1)
986    dy = width*(1.+alength)*np.sin(angle*np.pi/180.)/(N43-1)
987    for ix in range(N43):
988        doubleArrow[2*N4+N42+2+ix,:] = [length-dy*ix,dx*ix]
989    doublearrowdic['rightthead'] = [doubleArrow[2*N4+N42+2:51,:], '-', '#000000', 2.]
990
991    doubleArrow = ma.masked_equal(doubleArrow, gen.fillValueF)
992    doublearrowsecs = ['leftarm', 'rightarm', 'lefthead', 'righthead']
993
994    return doubleArrow, doublearrowsecs, doublearrowdic
995
996def p_angle_triangle(pi=np.array([0.,0.]), angle1=60., length1=1., angle2=60., N=100):
997    """ Function to draw a triangle by an initial point and two consecutive angles
998        and the first length of face. The third angle and 2 and 3rd face will be
999        computed accordingly the provided values:
1000           length1 / sin(angle1) = length2 / sin(angle2) = length3 / sin(angle3)
1001           angle1 + angle2 + angle3 = 180.
1002      pi: initial point ([0., 0.], default)
1003      angle1: first angle from pi clockwise (60., default)
1004      length1: length of face from pi by angle1 (1., default)
1005      angle2: second angle from second point (60., default)
1006      length2: length of face from p2 by angle2 (1., default)
1007      N: number of points (100, default)
1008    """
1009    fname = 'p_angle_triangle'
1010
1011    angle3 = 180. - angle1 - angle2
1012    length2 = np.sin(angle2*np.pi/180.)*length1/np.sin(angle1*np.pi/180.)
1013    length3 = np.sin(angle3*np.pi/180.)*length1/np.sin(angle1*np.pi/180.)
1014
1015    triangle = np.zeros((N,2), dtype=np.float)
1016
1017    N3 = int(N/3)
1018    # first face
1019    ix = pi[1]
1020    iy = pi[0]
1021    dx = length1*np.cos(angle1*np.pi/180.)/(N3-1)
1022    dy = length1*np.sin(angle1*np.pi/180.)/(N3-1)
1023    for ip in range(N3):
1024        triangle[ip,:] = [iy+dy*ip, ix+dx*ip]
1025
1026    # second face
1027    ia = -90. - (90.-angle1)
1028    ix = triangle[N3-1,1]
1029    iy = triangle[N3-1,0]
1030    dx = length2*np.cos((ia+angle2)*np.pi/180.)/(N3-1)
1031    dy = length2*np.sin((ia+angle2)*np.pi/180.)/(N3-1)
1032    for ip in range(N3):
1033        triangle[N3+ip,:] = [iy+dy*ip, ix+dx*ip]
1034
1035    # third face
1036    N32 = N - 2*N3
1037    ia = -180. - (90.-angle2)
1038    ix = triangle[2*N3-1,1]
1039    iy = triangle[2*N3-1,0]
1040    angle3 = np.arctan2(pi[0]-iy, pi[1]-ix)
1041    dx = (pi[1]-ix)/(N32-1)
1042    dy = (pi[0]-iy)/(N32-1)
1043    for ip in range(N32):
1044        triangle[2*N3+ip,:] = [iy+dy*ip, ix+dx*ip]
1045
1046    return triangle
1047
1048# Combined objects
1049##
1050
1051# FROM: http://www.photographers1.com/Sailing/NauticalTerms&Nomenclature.html
1052def zboat(length=10., beam=1., lbeam=0.4, sternbp=0.5):
1053    """ Function to define an schematic boat from the z-plane
1054      length: length of the boat (without stern, default 10)
1055      beam: beam of the boat (default 1)
1056      lbeam: length at beam (as percentage of length, default 0.4)
1057      sternbp: beam at stern (as percentage of beam, default 0.5)
1058    """
1059    fname = 'zboat'
1060
1061    bow = np.array([length, 0.])
1062    maxportside = np.array([length*lbeam, -beam])
1063    maxstarboardside = np.array([length*lbeam, beam])
1064    portside = np.array([0., -beam*sternbp])
1065    starboardside = np.array([0., beam*sternbp])
1066
1067    # forward section
1068    fportside = circ_sec(maxportside, bow, length*2)
1069    fstarboardside = circ_sec(bow, maxstarboardside, length*2)
1070    # aft section
1071    aportside = circ_sec(portside, maxportside, length*2)
1072    astarboardside = circ_sec(maxstarboardside, starboardside, length*2)
1073    # stern
1074    stern = circ_sec(starboardside, portside, length*2)
1075
1076    dpts = stern.shape[0]
1077    boat = np.zeros((dpts*5,2), dtype=np.float)
1078
1079    boat[0:dpts,:] = aportside
1080    boat[dpts:2*dpts,:] = fportside
1081    boat[2*dpts:3*dpts,:] = fstarboardside
1082    boat[3*dpts:4*dpts,:] = astarboardside
1083    boat[4*dpts:5*dpts,:] = stern
1084
1085    fname = 'boat_L' + str(int(length*100.)) + '_B' + str(int(beam*100.)) + '_lb' +  \
1086      str(int(lbeam*100.)) + '_sb' + str(int(sternbp*100.)) + '.dat'
1087    if not os.path.isfile(fname):
1088        print infmsg
1089        print '  ' + fname + ": writting boat coordinates file '" + fname + "' !!"
1090        of = open(fname, 'w')
1091        of.write('# boat file with Length: ' + str(length) +' max_beam: '+str(beam)+ \
1092          'length_at_max_beam:' + str(lbeam) + '% beam at stern: ' + str(sternbp)+   \
1093          ' %\n')
1094        for ip in range(dpts*5):
1095            of.write(str(boat[ip,0]) + ' ' + str(boat[ip,1]) + '\n')
1096       
1097        of.close()
1098        print fname + ": Successfull written '" + fname + "' !!"
1099
1100
1101    # Center line extending [fcl] percentage from length on aft and stern
1102    fcl = 0.15
1103    centerline = np.zeros((dpts,2), dtype=np.float)
1104    dl = length*(1.+fcl*2.)/(dpts-1)
1105    centerline[:,0] = np.arange(-length*fcl, length*(1. + fcl)+dl, dl)
1106
1107    # correct order of sections
1108    boatsecs = ['aportside', 'fportside', 'fstarboardside', 'astarboardside',        \
1109      'stern', 'centerline']
1110
1111    # dictionary with sections [polygon_vertices, line_type, line_color, line_width]
1112    dicboat = {'fportside': [fportside, '-', '#8A5900', 2.],                         \
1113      'aportside': [aportside, '-', '#8A5900', 2.],                                  \
1114      'stern': [stern, '-', '#8A5900', 2.],                                          \
1115      'astarboardside': [astarboardside, '-', '#8A5900', 2.],                        \
1116      'fstarboardside': [fstarboardside, '-', '#8A5900', 2.],                        \
1117      'centerline': [centerline, '-.', '#AA6464', 1.5]}
1118   
1119    fname = 'sailboat_L' + str(int(length*100.)) + '_B' + str(int(beam*100.)) +      \
1120      '_lb' + str(int(lbeam*100.)) + '_sb' + str(int(sternbp*100.)) +'.dat'
1121    if not os.path.isfile(fname):
1122        print infmsg
1123        print '  ' + fname + ": writting boat coordinates file '" + fname + "' !!"
1124        of = open(fname, 'w')
1125        of.write('# boat file with Length: ' + str(length) +' max_beam: '+str(beam)+ \
1126          'length_at_max_beam:' + str(lbeam) + '% beam at stern: ' +str(sternbp)+'\n')
1127        for ip in range(dpts*5):
1128            of.write(str(boat[ip,0]) + ' ' + str(boat[ip,1]) + '\n')
1129       
1130        of.close()
1131        print fname + ": Successfull written '" + fname + "' !!"
1132 
1133    return boat, boatsecs, dicboat
1134
1135def zsailing_boat(length=10., beam=1., lbeam=0.4, sternbp=0.5, lmast=0.6, wmast=0.1, \
1136  hsd=5., msd=5., lheads=0.38, lmains=0.55):
1137    """ Function to define an schematic sailing boat from the z-plane with sails
1138      length: length of the boat (without stern, default 10)
1139      beam: beam of the boat (default 1)
1140      lbeam: length at beam (as percentage of length, default 0.4)
1141      sternbp: beam at stern (as percentage of beam, default 0.5)
1142      lmast: position of the mast (as percentage of length, default 0.6)
1143      wmast: width of the mast (default 0.1)
1144      hsd: head sail direction respect to center line (default 5., -999.99 for upwind)
1145      msd: main sail direction respect to center line (default 5., -999.99 for upwind)
1146      lheads: length of head sail (as percentage of legnth, defaul 0.38)
1147      lmains: length of main sail (as percentage of legnth, defaul 0.55)
1148    """
1149    fname = 'zsailing_boat'
1150
1151    bow = np.array([length, 0.])
1152    maxportside = np.array([length*lbeam, -beam])
1153    maxstarboardside = np.array([length*lbeam, beam])
1154    portside = np.array([0., -beam*sternbp])
1155    starboardside = np.array([0., beam*sternbp])
1156
1157    aportside = circ_sec(portside, maxportside, length*2)
1158    fportside = circ_sec(maxportside, bow, length*2)
1159    fstarboardside = circ_sec(bow, maxstarboardside, length*2)
1160    astarboardside = circ_sec(maxstarboardside, starboardside, length*2)
1161    stern = circ_sec(starboardside, portside, length*2)
1162    dpts = fportside.shape[0]
1163
1164    # correct order of sections
1165    sailingboatsecs = ['aportside', 'fportside', 'fstarboardside', 'astarboardside', \
1166      'stern', 'mast', 'hsail', 'msail', 'centerline']
1167
1168    # forward section
1169
1170    # aft section
1171    # stern
1172    # mast
1173    mast = p_circle(wmast,N=dpts)
1174    mast = mast + [length*lmast, 0.]
1175    # head sails
1176    lsail = lheads*length
1177    if hsd != -999.99:
1178        sailsa = np.pi/2. - np.pi*hsd/180.
1179        endsail = np.array([lsail*np.sin(sailsa), lsail*np.cos(sailsa)])
1180        endsail[0] = length - endsail[0]
1181        if bow[1] > endsail[1]:
1182            hsail = circ_sec(endsail, bow, lsail*2.15)
1183        else:
1184            hsail = circ_sec(bow, endsail, lsail*2.15)
1185    else:
1186        hsail0 = p_sinusiode(length=lsail, amp=0.2, lamb=0.75, N=dpts)
1187        hsail = np.zeros((dpts,2), dtype=np.float)
1188        hsail[:,0] = hsail0[:,1]
1189        hsail[:,1] = hsail0[:,0]
1190        hsail = bow - hsail
1191
1192    # main sails
1193    lsail = lmains*length
1194    if msd != -999.99:
1195        sailsa = np.pi/2. - np.pi*msd/180.
1196        begsail = np.array([length*lmast, 0.])
1197        endsail = np.array([lsail*np.sin(sailsa), lsail*np.cos(sailsa)])
1198        endsail[0] = length*lmast - endsail[0]
1199        if endsail[1] > begsail[1]:
1200            msail = circ_sec(begsail, endsail, lsail*2.15)
1201        else:
1202            msail = circ_sec(endsail, begsail, lsail*2.15)
1203    else:
1204        msail0 = p_sinusiode(length=lsail, amp=0.25, lamb=1., N=dpts)
1205        msail = np.zeros((dpts,2), dtype=np.float)
1206        msail[:,0] = msail0[:,1]
1207        msail[:,1] = msail0[:,0]
1208        msail = [length*lmast,0] - msail
1209
1210    sailingboat = np.zeros((dpts*8+4,2), dtype=np.float)
1211
1212    sailingboat[0:dpts,:] = aportside
1213    sailingboat[dpts:2*dpts,:] = fportside
1214    sailingboat[2*dpts:3*dpts,:] = fstarboardside
1215    sailingboat[3*dpts:4*dpts,:] = astarboardside
1216    sailingboat[4*dpts:5*dpts,:] = stern
1217    sailingboat[5*dpts,:] = [gen.fillValueF, gen.fillValueF]
1218    sailingboat[5*dpts+1:6*dpts+1,:] = mast
1219    sailingboat[6*dpts+1,:] = [gen.fillValueF, gen.fillValueF]
1220    sailingboat[6*dpts+2:7*dpts+2,:] = hsail
1221    sailingboat[7*dpts+2,:] = [gen.fillValueF, gen.fillValueF]
1222    sailingboat[7*dpts+3:8*dpts+3,:] = msail
1223    sailingboat[8*dpts+3,:] = [gen.fillValueF, gen.fillValueF]
1224
1225    sailingboat = ma.masked_equal(sailingboat, gen.fillValueF)
1226
1227    # Center line extending [fcl] percentage from length on aft and stern
1228    fcl = 0.15
1229    centerline = np.zeros((dpts,2), dtype=np.float)
1230    dl = length*(1.+fcl*2.)/(dpts-1)
1231    centerline[:,0] = np.arange(-length*fcl, length*(1. + fcl)+dl, dl)
1232
1233    # dictionary with sections [polygon_vertices, line_type, line_color, line_width]
1234    dicsailingboat = {'fportside': [fportside, '-', '#8A5900', 2.],                  \
1235      'aportside': [aportside, '-', '#8A5900', 2.],                                  \
1236      'stern': [stern, '-', '#8A5900', 2.],                                          \
1237      'astarboardside': [astarboardside, '-', '#8A5900', 2.],                        \
1238      'fstarboardside': [fstarboardside, '-', '#8A5900', 2.],                        \
1239      'mast': [mast, '-', '#8A5900', 2.], 'hsail': [hsail, '-', '#AAAAAA', 1.],      \
1240      'msail': [msail, '-', '#AAAAAA', 1.],                                          \
1241      'centerline': [centerline, '-.', '#AA6464', 1.5]}
1242   
1243    fname = 'sailboat_L' + str(int(length*100.)) + '_B' + str(int(beam*100.)) +      \
1244      '_lb' + str(int(lbeam*100.)) + '_sb' + str(int(sternbp*100.)) +                \
1245      '_lm' + str(int(lmast*100.)) + '_wm' + str(int(wmast)) +                       \
1246      '_hsd' + str(int(hsd)) + '_hs' + str(int(lheads*100.)) +                       \
1247      '_ms' + str(int(lheads*100.)) + '_msd' + str(int(msd)) +'.dat'
1248    if not os.path.isfile(fname):
1249        print infmsg
1250        print '  ' + fname + ": writting boat coordinates file '" + fname + "' !!"
1251        of = open(fname, 'w')
1252        of.write('# boat file with Length: ' + str(length) +' max_beam: '+str(beam)+ \
1253          'length_at_max_beam:' + str(lbeam) + '% beam at stern: ' + str(sternbp)+   \
1254          ' % mast position: '+ str(lmast) + ' % mast width: ' + str(wmast) + ' ' +  \
1255          ' head sail direction:' + str(hsd) + ' head sail length: ' + str(lheads) + \
1256          ' %' + ' main sail length' + str(lmains) + ' main sail direction:' +       \
1257          str(msd) +'\n')
1258        for ip in range(dpts*5):
1259            of.write(str(sailingboat[ip,0]) + ' ' + str(sailingboat[ip,1]) + '\n')
1260       
1261        of.close()
1262        print fname + ": Successfull written '" + fname + "' !!"
1263 
1264    return sailingboat, sailingboatsecs, dicsailingboat
1265
1266def zisland1(mainpts= np.array([[-0.1,0.], [-1.,1.], [-0.8,1.2], [0.1,0.6], [1., 0.9],\
1267  [2.8, -0.1], [0.1,-0.6]], dtype=np.float), radfrac=3., N=200):
1268    """ Function to draw an island from z-axis as the union of a series of points by
1269        circular segments
1270      mainpts: main points of the island (clockwise ordered, to be joined by
1271        circular segments of radii as the radfrac factor of the distance between
1272        consecutive points)
1273          * default= np.array([[-0.1,0.], [-1.,1.], [-0.8,1.2], [0.1,0.6], [1., 0.9],
1274            [2.8, -0.1], [0.1,-0.6]], dtype=np.float)
1275      radfrac: multiplicative factor of the distance between consecutive points to
1276        draw the circular segment (3., default)
1277      N: number of points (200, default)
1278    """
1279    fname = 'zisland1'
1280
1281    island1 = np.ones((N,2), dtype=np.float)*gen.fillValueF
1282
1283    # Coastline
1284    island1 = join_circ_sec_rand(mainpts, arc='short', pos='left')
1285
1286    islandsecs = ['coastline']
1287    islanddic = {'coastline': [island1, '-', '#161616', 2.]}
1288
1289    island1 = ma.masked_equal(island1, gen.fillValueF)
1290
1291    return island1, islandsecs, islanddic
1292
1293def buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, N=200):
1294    """ Function to draw a buoy as superposition of prism and section of ball
1295      height: height of the prism (5., default)
1296      width: width of the prism (10., default)
1297      bradii: radii of the ball (1.75, default)
1298      bfrac: fraction of the ball above the prism (0.8, default)
1299      N: total number of points of the buoy (200, default)
1300    """
1301    fname = 'buoy1'
1302
1303    buoy = np.zeros((N,2), dtype=np.float)
1304
1305    NNp = 0
1306    iip = 0
1307    # Base
1308    ix = width/2.
1309    iy = 0.
1310    Np = 4
1311    dx = -width/(Np-1)
1312    dy = 0.
1313    for ip in range(Np):
1314        buoy[iip+ip,:] = [iy+dy*ip,ix+dx*ip]
1315    NNp = NNp + Np
1316    iip = NNp
1317
1318    # left lateral
1319    ix = -width/2.
1320    iy = 0.
1321    Np = 2
1322    dx = 0.
1323    dy = height/(Np-1)
1324    for ip in range(Np):
1325        buoy[iip+ip,:] = [iy+dy*ip,ix+dx*ip]
1326    NNp = NNp + Np
1327    iip = NNp
1328
1329    # left upper
1330    ix = -width/2.
1331    iy = height
1332    Np = 4
1333    dx = (width/2.-bradii*bfrac)/(Np-1)
1334    dy = 0.
1335    for ip in range(Np):
1336        buoy[iip+ip,:] = [iy+dy*ip,ix+dx*ip]
1337    NNp = NNp + Np
1338    iip = NNp
1339
1340    # ball
1341    p1 = np.array([height, -bradii*bfrac])
1342    p2 = np.array([height, bradii*bfrac])
1343    Np = N - 2*(NNp)
1344    buoy[iip:iip+Np,:] = circ_sec(p1, p2, 2.*bradii, 'long', 'left', Np)
1345    NNp = NNp + Np
1346    iip = NNp
1347
1348    # right upper
1349    ix = bradii*bfrac
1350    iy = height
1351    Np = 4
1352    dx = (width/2.-bradii*bfrac)/(Np-1)
1353    dy = 0.
1354    for ip in range(Np):
1355        buoy[iip+ip,:] = [iy+dy*ip,ix+dx*ip]
1356    NNp = NNp + Np
1357    iip = NNp
1358
1359    # right lateral
1360    ix = width/2.
1361    iy = height
1362    Np = 2
1363    dx = 0.
1364    dy = -height/(Np-1)
1365    for ip in range(Np):
1366        buoy[iip+ip,:] = [iy+dy*ip,ix+dx*ip]
1367    NNp = NNp + Np
1368    iip = NNp
1369
1370    buoysecs = ['base']
1371    buoydic = {'base': [buoy, '-', 'k', 1.5]}
1372
1373    return buoy, buoysecs, buoydic
1374
1375def band_lighthouse(height=10., width=2., hlight=3., bands=3, N=300):
1376    """ Function to plot a lighthouse with spiral bands
1377      height: height of the tower (10., default)
1378      width: width of the tower (2., default)
1379      hlight: height of the light (3., default)
1380      bands: number of spiral bands (3, default)
1381      N: number of points (300, default)
1382    """
1383    fname = 'band_lighthouse'
1384
1385    lighthouse = np.ones((N,2), dtype=np.float)*gen.fillValueF
1386    lighthousesecs = []
1387    lighthousedic = {}
1388
1389    # base Tower
1390    Nsec = int(0.30*N/7)
1391    p1=np.array([0., width/2.])
1392    p2=np.array([0., -width/2.])
1393    iip = 0
1394    lighthouse[0:Nsec,:] = circ_sec(p1, p2, 3*width, pos='left', Nang=Nsec)
1395    iip = iip + Nsec
1396
1397    # left side
1398    ix=-width/2.
1399    iy=0.
1400    dx = 0.
1401    dy = height/(Nsec-1)
1402    for ip in range(Nsec):
1403        lighthouse[iip+ip,:] = [iy+dy*ip, ix+dx*ip]
1404    iip = iip + Nsec
1405
1406    # Top Tower
1407    p1=np.array([height, width/2.])
1408    p2=np.array([height, -width/2.])
1409    lighthouse[iip:iip+Nsec,:] = circ_sec(p1, p2, 3*width, pos='left', Nang=Nsec)
1410    iip = iip + Nsec
1411
1412    # right side
1413    ix=width/2.
1414    iy=height
1415    dx = 0.
1416    dy = -height/(Nsec-1)
1417    for ip in range(Nsec):
1418        lighthouse[iip+ip,:] = [iy+dy*ip, ix+dx*ip]
1419    iip = iip + Nsec + 1
1420
1421    Ntower = iip-1
1422    lighthousesecs.append('tower')
1423    lighthousedic['tower'] = [lighthouse[0:iip-1], '-', 'k', 1.5]
1424
1425    # Left light
1426    p1 = np.array([height, -width*0.8/2.])
1427    p2 = np.array([height+hlight, -width*0.8/2.])
1428    lighthouse[iip:iip+Nsec,:] = circ_sec(p1, p2, 3*hlight, Nang=Nsec)
1429    iip = iip + Nsec
1430   
1431    # Top Light
1432    p1=np.array([height+hlight, width*0.8/2.])
1433    p2=np.array([height+hlight, -width*0.8/2.])
1434    lighthouse[iip:iip+Nsec,:] = circ_sec(p1, p2, 3*width, pos='left', Nang=Nsec)
1435    iip = iip + Nsec + 1
1436
1437    # Right light
1438    p1 = np.array([height+hlight, width*0.8/2.])
1439    p2 = np.array([height, width*0.8/2.])
1440    lighthouse[iip:iip+Nsec,:] = circ_sec(p1, p2, 3*hlight, Nang=Nsec)
1441    iip = iip + Nsec
1442
1443    # Base Light
1444    p1=np.array([height, width*0.8/2.])
1445    p2=np.array([height, -width*0.8/2.])
1446    lighthouse[iip:iip+Nsec,:] = circ_sec(p1, p2, 3*width, pos='left', Nang=Nsec)
1447    iip = iip + Nsec + 1
1448    lighthousesecs.append('light')
1449    lighthousedic['light'] = [lighthouse[Ntower+1:iip-1], '-', '#EEEE00', 1.5]
1450
1451    # Spiral bands
1452    hb = height/(2.*bands)
1453    Nsec2 = (N - Nsec*8 - 3)/bands
1454    for ib in range(bands-1):
1455        iband = iip
1456        Nsec = Nsec2/4
1457        bandS = 'band' + str(ib).zfill(2)
1458        # hband
1459        ix = -width/2.
1460        iy = hb*ib*2
1461        dx = 0.
1462        dy = hb/(Nsec-1)
1463        for ip in range(Nsec):
1464            lighthouse[iip+ip,:] = [iy+dy*ip, ix+dx*ip]
1465        iip = iip + Nsec
1466        # uband
1467        p1 = np.array([hb*(ib*2+1), -width/2.])
1468        p2 = np.array([hb*(ib*2+2), width/2.])
1469        lighthouse[iip:iip+Nsec,:] = circ_sec(p1, p2, 3*width, pos='right', Nang=Nsec)
1470        iip = iip + Nsec
1471        # dband
1472        ix = width/2.
1473        iy = hb*(ib*2+2)
1474        dx = 0.
1475        dy = -hb/(Nsec-1)
1476        for ip in range(Nsec):
1477            lighthouse[iip+ip,:] = [iy+dy*ip, ix+dx*ip]
1478        iip = iip + Nsec
1479        # dband
1480        p1 = np.array([hb*(ib*2+1), width/2.])
1481        p2 = np.array([hb*ib*2, -width/2.])
1482        lighthouse[iip:iip+Nsec,:] = circ_sec(p1, p2, 3*width, pos='left', Nang=Nsec)
1483        iip = iip + Nsec + 1
1484        lighthousesecs.append(bandS)
1485        lighthousedic[bandS] = [lighthouse[iband:iip-1], '-', '#6408AA', 2.]
1486
1487    ib = bands-1
1488    Nsec3 = (N - iip - 1)
1489    Nsec = int(Nsec3/4)
1490    bandS = 'band' + str(ib).zfill(2)
1491    # hband
1492    iband = iip
1493    ix = -width/2.
1494    iy = hb*ib*2
1495    dx = 0.
1496    dy = hb/(Nsec-1)
1497    for ip in range(Nsec):
1498        lighthouse[iip+ip,:] = [iy+dy*ip, ix+dx*ip]
1499    iip = iip + Nsec
1500    # uband
1501    p1 = np.array([hb*(ib*2+1), -width/2.])
1502    p2 = np.array([hb*(ib*2+2), width/2.])
1503    lighthouse[iip:iip+Nsec,:] = circ_sec(p1, p2, 3*width, pos='right', Nang=Nsec)
1504    iip = iip + Nsec
1505    # dband
1506    ix = width/2.
1507    iy = hb*(2+ib*2)
1508    dx = 0.
1509    dy = -hb/(Nsec-1)
1510    for ip in range(Nsec):
1511        lighthouse[iip+ip,:] = [iy+dy*ip, ix+dx*ip]
1512    iip = iip + Nsec
1513    # dband
1514    Nsec = N - iip
1515    p1 = np.array([hb*(1+ib*2), width/2.])
1516    p2 = np.array([hb*ib*2, -width/2.])
1517    lighthouse[iip:iip+Nsec,:] = circ_sec(p1, p2, 3*width, pos='left', Nang=Nsec)       
1518    lighthousesecs.append(bandS)
1519    lighthousedic[bandS] = [lighthouse[iband:iip-1], '-', '#6408AA', 2.]
1520
1521    lighthouse = ma.masked_equal(lighthouse, gen.fillValueF)
1522
1523    return lighthouse, lighthousesecs, lighthousedic
1524
1525def north_buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, hsigns=0.7, N=300):
1526    """ Function to draw a North danger buoy using buoy1
1527      height: height of the prism (5., default)
1528      width: width of the prism (10., default)
1529      bradii: radii of the ball (1.75, default)
1530      bfrac: fraction of the ball above the prism (0.8, default)
1531      hisgns: height of the signs [as reg. triangle] as percentage of the height
1532        (0.7, default)
1533      N: total number of points of the buoy (300, default)
1534    """
1535    fname = 'north_buoy1'
1536
1537    buoy = np.ones((N,2), dtype=np.float)*gen.fillValueF
1538
1539    # buoy
1540    N2 = int(N/2)
1541    buoy1v, buoy1vsecs, buoy1vdic = buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, N=N2)
1542    buoy[0:N2,:] = buoy1v
1543
1544    # signs
1545    N3 = N - N2 - 2
1546   
1547    bottsigns = 2.*bradii+height
1548    lsign = height*hsigns
1549    # up
1550    N32 = int(N3/2) 
1551    triu = p_angle_triangle(N=N32)
1552    trib = triu*lsign + [0.,-lsign/2.] 
1553
1554    buoy[N2+1:N2+1+N32,:] = trib + [bottsigns+2.1*lsign,0.]
1555
1556    # up
1557    N323 = N - N32 - N2 - 2
1558    trid = p_angle_triangle(N=N323)
1559    trib = trid*lsign + [0.,-lsign/2.] 
1560    buoy[N2+N32+2:N,:] = trib + [bottsigns+1.1*lsign,0.]
1561
1562    buoy = ma.masked_equal(buoy, gen.fillValueF)
1563
1564    buoysecs = ['buoy', 'sign1', 'sign2']
1565    buoydic = {'buoy': [buoy[0:N2,:],'-','k',1.5],                                   \
1566      'sign1': [buoy[N2+1:N2+N32+1,:],'-','k',1.5],                                  \
1567      'sign2': [buoy[N2+N32+2:N,:],'-','k',1.5]}
1568
1569    return buoy, buoysecs, buoydic
1570
1571def east_buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, hsigns=0.7, N=300):
1572    """ Function to draw a East danger buoy using buoy1
1573      height: height of the prism (5., default)
1574      width: width of the prism (10., default)
1575      bradii: radii of the ball (1.75, default)
1576      bfrac: fraction of the ball above the prism (0.8, default)
1577      hisgns: height of the signs [as reg. triangle] as percentage of the height
1578        (0.7, default)
1579      N: total number of points of the buoy (300, default)
1580    """
1581    fname = 'east_buoy1'
1582
1583    buoy = np.ones((N,2), dtype=np.float)*gen.fillValueF
1584
1585    # buoy
1586    N2 = int(N/2)
1587    buoy1v, buoy1vsecs, buoy1vdic = buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, N=N2)
1588    buoy[0:N2,:] = buoy1v
1589
1590    # signs
1591    N3 = N - N2 - 2
1592   
1593    bottsigns = 2.*bradii+height
1594    lsign = height*hsigns
1595    # up
1596    N32 = int(N3/2) 
1597    triu = p_angle_triangle(N=N32)
1598    trib = triu*lsign + [0.,-lsign/2.] 
1599
1600    buoy[N2+1:N2+1+N32,:] = trib + [bottsigns+2.1*lsign,0.]
1601
1602    # down
1603    N323 = N - N32 - N2 - 2
1604
1605    trid = p_angle_triangle(N=N323)
1606    trid = mirror_polygon(trid, 'x')
1607    trib = trid*lsign + [lsign,-lsign/2.] 
1608    buoy[N2+N32+2:N,:] = trib + [bottsigns+0.9*lsign,0.]
1609
1610    buoy = ma.masked_equal(buoy, gen.fillValueF)
1611
1612    buoysecs = ['buoy', 'sign1', 'sign2']
1613    buoydic = {'buoy': [buoy[0:N2,:],'-','k',1.5],                                   \
1614      'sign1': [buoy[N2+1:N2+N32+1,:],'-','k',1.5],                                  \
1615      'sign2': [buoy[N2+N32+2:N,:],'-','k',1.5]}
1616
1617    return buoy, buoysecs, buoydic
1618
1619def south_buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, hsigns=0.7, N=300):
1620    """ Function to draw a South danger buoy using buoy1
1621      height: height of the prism (5., default)
1622      width: width of the prism (10., default)
1623      bradii: radii of the ball (1.75, default)
1624      bfrac: fraction of the ball above the prism (0.8, default)
1625      hisgns: height of the signs [as reg. triangle] as percentage of the height
1626        (0.7, default)
1627      N: total number of points of the buoy (300, default)
1628    """
1629    fname = 'east_buoy1'
1630
1631    buoy = np.ones((N,2), dtype=np.float)*gen.fillValueF
1632
1633    # buoy
1634    N2 = int(N/2)
1635    buoy1v, buoy1vsecs, buoy1vdic = buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, N=N2)
1636    buoy[0:N2,:] = buoy1v
1637
1638    # signs
1639    N3 = N - N2 - 2
1640   
1641    bottsigns = 2.*bradii+height
1642    lsign = height*hsigns
1643    # up
1644    N32 = int(N3/2) 
1645    trid = p_angle_triangle(N=N32)
1646    trid = mirror_polygon(trid, 'x')
1647    trib = trid*lsign + [0.,-lsign/2.] 
1648
1649    buoy[N2+1:N2+1+N32,:] = trib + [bottsigns+2.9*lsign,0.]
1650
1651    # down
1652    N323 = N - N32 - N2 - 2
1653    trid = p_angle_triangle(N=N323)
1654    trid = mirror_polygon(trid, 'x')
1655    trib = trid*lsign + [lsign,-lsign/2.] 
1656    buoy[N2+N32+2:N,:] = trib + [bottsigns+0.9*lsign,0.]
1657
1658    buoy = ma.masked_equal(buoy, gen.fillValueF)
1659
1660    buoysecs = ['buoy', 'sign1', 'sign2']
1661    buoydic = {'buoy': [buoy[0:N2,:],'-','k',1.5],                                   \
1662      'sign1': [buoy[N2+1:N2+N32+1,:],'-','k',1.5],                                  \
1663      'sign2': [buoy[N2+N32+2:N,:],'-','k',1.5]}
1664
1665    return buoy, buoysecs, buoydic
1666
1667def west_buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, hsigns=0.7, N=300):
1668    """ Function to draw a West danger buoy using buoy1
1669      height: height of the prism (5., default)
1670      width: width of the prism (10., default)
1671      bradii: radii of the ball (1.75, default)
1672      bfrac: fraction of the ball above the prism (0.8, default)
1673      hisgns: height of the signs [as reg. triangle] as percentage of the height
1674        (0.7, default)
1675      N: total number of points of the buoy (300, default)
1676    """
1677    fname = 'east_buoy1'
1678
1679    buoy = np.ones((N,2), dtype=np.float)*gen.fillValueF
1680
1681    # buoy
1682    N2 = int(N/2)
1683    buoy1v, buoy1vsecs, buoy1vdic = buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, N=N2)
1684    buoy[0:N2,:] = buoy1v
1685
1686    # signs
1687    N3 = N - N2 - 2
1688   
1689    bottsigns = 2.*bradii+height
1690    lsign = height*hsigns
1691
1692    # down
1693    N32 = int(N3/2) 
1694    trid = p_angle_triangle(N=N32)
1695    trid = mirror_polygon(trid, 'x')
1696    trib = trid*lsign + [lsign,-lsign/2.] 
1697    buoy[N2+1:N2+1+N32,:] = trib + [bottsigns+1.9*lsign,0.]
1698
1699    # up
1700    N323 = N - N32 - N2 - 2
1701    triu = p_angle_triangle(N=N323)
1702    trib = triu*lsign + [0.,-lsign/2.] 
1703
1704    buoy[N2+N323+2:N,:] = trib + [bottsigns+1.*lsign,0.]
1705
1706    buoy = ma.masked_equal(buoy, gen.fillValueF)
1707
1708    buoysecs = ['buoy', 'sign1', 'sign2']
1709    buoydic = {'buoy': [buoy[0:N2,:],'-','k',1.5],                                   \
1710      'sign1': [buoy[N2+1:N2+N32+1,:],'-','k',1.5],                                  \
1711      'sign2': [buoy[N2+N32+2:N,:],'-','k',1.5]}
1712
1713    return buoy, buoysecs, buoydic
1714
1715####### ####### ##### #### ### ## #
1716# Plotting
1717
1718def plot_sphere(iazm=-60., iele=30., dist=10., Npts=100, radii=10,                   \
1719  drwsfc=[True,True], colsfc=['#AAAAAA','#646464'],                                  \
1720  drwxline = True, linex=[':','b',2.], drwyline = True, liney=[':','r',2.],          \
1721  drwzline = True, linez=['-.','g',2.], drwxcline=[True,True],                       \
1722  linexc=[['-','#646400',1.],['--','#646400',1.]],                                   \
1723  drwequator=[True,True], lineeq=[['-','#AA00AA',1.],['--','#AA00AA',1.]],           \
1724  drwgreeenwhich=[True,True], linegw=[['-','k',1.],['--','k',1.]]):
1725    """ Function to plot an sphere and determine which standard lines will be also
1726        drawn
1727      iazm: azimut of the camera form the sphere
1728      iele: elevation of the camera form the sphere
1729      dist: distance of the camera form the sphere
1730      Npts: Resolution for the sphere
1731      radii: radius of the sphere
1732      drwsfc: whether 'up' and 'down' portions of the sphere should be drawn
1733      colsfc: colors of the surface of the sphere portions ['up', 'down']
1734      drwxline: whether x-axis line should be drawn
1735      linex: properties of the x-axis line ['type', 'color', 'wdith']
1736      drwyline: whether y-axis line should be drawn
1737      liney: properties of the y-axis line ['type', 'color', 'wdith']
1738      drwzline: whether z-axis line should be drawn
1739      linez: properties of the z-axis line ['type', 'color', 'wdith']
1740      drwequator: whether 'front' and 'back' portions of the Equator should be drawn
1741      lineeq: properties of the lines 'front' and 'back' of the Equator
1742      drwgreeenwhich: whether 'front', 'back' portions of Greenqhich should be drawn
1743      linegw: properties of the lines 'front' and 'back' Greenwhich
1744      drwxcline: whether 'front', 'back' 90 line (lon=90., lon=270.) should be drawn
1745      linexc: properties of the lines 'front' and 'back' for the 90 line
1746    """
1747    fname = 'plot_sphere'
1748
1749    iazmrad = iazm*np.pi/180.
1750    ielerad = iele*np.pi/180.
1751
1752    # 3D surface Sphere
1753    sfcsphereu, sfcsphered = surface_sphere(radii,Npts)
1754   
1755    # greenwhich
1756    if iazmrad > np.pi/2. and iazmrad < 3.*np.pi/2.:
1757        ia=np.pi-ielerad
1758    else:
1759        ia=0.-ielerad
1760    ea=ia+np.pi
1761    da = (ea-ia)/(Npts-1)
1762    beta = np.arange(ia,ea+da,da)[0:Npts]
1763    alpha = np.zeros((Npts), dtype=np.float)
1764    greenwhichc = spheric_line(radii,alpha,beta)
1765    ia=ea+0.
1766    ea=ia+np.pi
1767    da = (ea-ia)/(Npts-1)
1768    beta = np.arange(ia,ea+da,da)[0:Npts]
1769    greenwhichd = spheric_line(radii,alpha,beta)
1770
1771    # Equator
1772    ia=np.pi-iazmrad/2.
1773    ea=ia+np.pi
1774    da = (ea-ia)/(Npts-1)
1775    alpha = np.arange(ia,ea+da,da)[0:Npts]
1776    beta = np.zeros((Npts), dtype=np.float)
1777    equatorc = spheric_line(radii,alpha,beta)
1778    ia=ea+0.
1779    ea=ia+np.pi
1780    da = (ea-ia)/(Npts-1)
1781    alpha = np.arange(ia,ea+da,da)[0:Npts]
1782    equatord = spheric_line(radii,alpha,beta)
1783
1784    # 90 line
1785    if iazmrad > np.pi and iazmrad < 2.*np.pi:
1786        ia=3.*np.pi/2. + ielerad
1787    else:
1788        ia=np.pi/2. - ielerad
1789    if ielerad < 0.:
1790        ia = ia + np.pi
1791    ea=ia+np.pi
1792    da = (ea-ia)/(Npts-1)
1793    beta = np.arange(ia,ea+da,da)[0:Npts]
1794    alpha = np.ones((Npts), dtype=np.float)*np.pi/2.
1795    xclinec = spheric_line(radii,alpha,beta)
1796    ia=ea+0.
1797    ea=ia+np.pi
1798    da = (ea-ia)/(Npts-1)
1799    beta = np.arange(ia,ea+da,da)[0:Npts]
1800    xclined = spheric_line(radii,alpha,beta)
1801
1802    # x line
1803    xline = np.zeros((2,3), dtype=np.float)
1804    xline[0,:] = position_sphere(radii, 0., 0.)
1805    xline[1,:] = position_sphere(radii, np.pi, 0.)
1806
1807    # y line
1808    yline = np.zeros((2,3), dtype=np.float)
1809    yline[0,:] = position_sphere(radii, np.pi/2., 0.)
1810    yline[1,:] = position_sphere(radii, 3*np.pi/2., 0.)
1811
1812    # z line
1813    zline = np.zeros((2,3), dtype=np.float)
1814    zline[0,:] = position_sphere(radii, 0., np.pi/2.)
1815    zline[1,:] = position_sphere(radii, 0., -np.pi/2.)
1816
1817    fig = plt.figure()
1818    ax = fig.gca(projection='3d')
1819
1820    # Sphere surface
1821    if drwsfc[0]:
1822        ax.plot_surface(sfcsphereu[0,:,:], sfcsphereu[1,:,:], sfcsphereu[2,:,:],     \
1823          color=colsfc[0])
1824    if drwsfc[1]:
1825        ax.plot_surface(sfcsphered[0,:,:], sfcsphered[1,:,:], sfcsphered[2,:,:],     \
1826          color=colsfc[1])
1827
1828    # greenwhich
1829    linev = linegw[0]
1830    if drwgreeenwhich[0]:
1831        ax.plot(greenwhichc[:,0], greenwhichc[:,1], greenwhichc[:,2], linev[0],      \
1832          color=linev[1], linewidth=linev[2],  label='Greenwich')
1833    linev = linegw[1]
1834    if drwgreeenwhich[1]:
1835        ax.plot(greenwhichd[:,0], greenwhichd[:,1], greenwhichd[:,2], linev[0],      \
1836          color=linev[1], linewidth=linev[2])
1837
1838    # Equator
1839    linev = lineeq[0]
1840    if drwequator[0]:
1841        ax.plot(equatorc[:,0], equatorc[:,1], equatorc[:,2], linev[0],               \
1842          color=linev[1], linewidth=linev[2], label='Equator')
1843    linev = lineeq[1]
1844    if drwequator[1]:
1845        ax.plot(equatord[:,0], equatord[:,1], equatord[:,2], linev[0],               \
1846          color=linev[1], linewidth=linev[2])
1847
1848    # 90line
1849    linev = linexc[0]
1850    if drwxcline[0]:
1851        ax.plot(xclinec[:,0], xclinec[:,1], xclinec[:,2], linev[0], color=linev[1],  \
1852          linewidth=linev[2], label='90-line')
1853    linev = linexc[1]
1854    if drwxcline[1]:
1855        ax.plot(xclined[:,0], xclined[:,1], xclined[:,2], linev[0], color=linev[1],  \
1856          linewidth=linev[2])
1857
1858    # x line
1859    linev = linex
1860    if drwxline:
1861        ax.plot([xline[0,0],xline[1,0]], [xline[0,1],xline[1,1]],                    \
1862          [xline[0,2],xline[1,2]], linev[0], color=linev[1], linewidth=linev[2],  label='xline')
1863
1864    # y line
1865    linev = liney
1866    if drwyline:
1867        ax.plot([yline[0,0],yline[1,0]], [yline[0,1],yline[1,1]],                    \
1868          [yline[0,2],yline[1,2]], linev[0], color=linev[1], linewidth=linev[2],  label='yline')
1869
1870    # z line
1871    linev = linez
1872    if drwzline:
1873        ax.plot([zline[0,0],zline[1,0]], [zline[0,1],zline[1,1]],                    \
1874          [zline[0,2],zline[1,2]], linev[0], color=linev[1], linewidth=linev[2],  label='zline')
1875
1876    plt.legend()
1877
1878    return fig, ax
1879
1880def paint_filled(objdic, fillsecs):
1881    """ Function to draw an object filling given sections
1882      objdic: dictionary of the object
1883      filesecs: list of sections to be filled
1884    """
1885    fname = 'paint_filled'
1886
1887    Nsecs = len(fillsecs)
1888
1889    for secn in fillsecs:
1890        secvals=objdic[secn]
1891        pvals = secvals[0]
1892        plt.fill(pvals[:,1], pvals[:,0], color=secvals[2])
1893
1894    return
1895
Note: See TracBrowser for help on using the repository browser.