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

Last change on this file since 2583 was 2583, checked in by lfita, 5 years ago

Adding multiple cuts in `cut_xpolygon'

File size: 102.0 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_between_[x/y]polygon: Function to cut a polygon between 2 given value of the [x/y]-axis
26# cut_[x/y]polygon: Function to cut a polygon from a given value of the [x/y]-axis
27# deg_deci: Function to pass from degrees [deg, minute, sec] to decimal angles [rad]
28# dist_points: Function to provide the distance between two points
29# join_circ_sec: Function to join aa series of points by circular segments
30# join_circ_sec_rand: Function to join aa series of points by circular segments with
31#   random perturbations
32# max_coords_poly: Function to provide the extremes of the coordinates of a polygon
33# mirror_polygon: Function to reflex a polygon for a given axis
34# position_sphere: Function to tranform fom a point in lon, lat deg coordinates to
35#   cartesian coordinates over an sphere
36# read_join_poly: Function to read an ASCII file with the combination of polygons
37# rotate_2D: Function to rotate a vector by a certain angle in the plain
38# rotate_polygon_2D: Function to rotate 2D plain the vertices of a polygon
39# rotate_line2D: Function to rotate a line given by 2 pairs of x,y coordinates by a
40#   certain angle in the plain
41# rotate_lines2D: Function to rotate multiple lines given by mulitple pars of x,y
42#   coordinates by a certain angle in the plain
43# spheric_line: Function to transform a series of locations in lon, lat coordinates
44#   to x,y,z over an 3D spaceFunction to provide coordinates of a line  on a 3D space
45# val_between: Function to provide if a given value is between two consecutive ones
46# write_join_poly: Function to write an ASCII file with the combination of polygons
47
48## Shapes/objects
49# buoy1: Function to draw a buoy as superposition of prism and section of ball
50# band_lighthouse: Function to plot a lighthouse with spiral bands
51# circ_sec: Function union of point A and B by a section of a circle
52# ellipse_polar: Function to determine an ellipse from its center and polar coordinates
53# green_buoy1: Function to draw a green mark buoy using buoy1
54# isolateddanger_buoy1: Function to draw an isolated danger buoy using buoy1
55# p_angle_triangle: Function to draw a triangle by an initial point and two
56#   consecutive angles and the first length of face. The third angle and 2 and 3rd
57#   face will be computed accordingly the provided values
58# p_doubleArrow: Function to provide an arrow with double lines
59# p_circle: Function to get a polygon of a circle
60# p_cross_width: Function to draw a cross with arms with a given width and an angle
61# p_prism: Function to get a polygon prism
62# p_reg_polygon: Function to provide a regular polygon of Nv vertices
63# p_reg_star: Function to provide a regular star of Nv vertices
64# p_sinusiode: Function to get coordinates of a sinusoidal curve
65# p_square: Function to get a polygon square
66# p_spiral: Function to provide a polygon of an Archimedean spiral
67# p_triangle: Function to provide the polygon of a triangle from its 3 vertices
68# prefchannelport[A/B]_buoy1: Function to draw a preferred channel port system
69#   [A/B] buoy using buoy1
70# prefchannelstarboard[A/B]_buoy1: Function to draw a preferred channel starboard
71#   system [A/B] buoy using buoy1
72# red_buoy1: Function to draw a red mark buoy using buoy1
73# safewater_buoy1: Function to draw a safe water mark buoy using buoy1
74# special_buoy1: Function to draw an special mark buoy using buoy1
75# surface_sphere: Function to provide an sphere as matrix of x,y,z coordinates
76# z_boat: Function to define an schematic boat from the z-plane
77# zsailing_boat: Function to define an schematic sailing boat from the z-plane with sails
78# zisland1: Function to draw an island from z-axis as the union of a series of points by
79#   circular segments
80
81## Plotting
82# paint_filled: Function to draw an object filling given sections
83# plot_sphere: Function to plot an sphere and determine which standard lines will be
84#   also drawn
85# [north/east/south/west_buoy1: Function to draw a [North/East/South/West] danger buoy using buoy1
86
87def deg_deci(angle):
88    """ Function to pass from degrees [deg, minute, sec] to decimal angles [rad]
89      angle: list of [deg, minute, sec] to pass
90    >>> deg_deci([41., 58., 34.])
91    0.732621346072
92    """
93    fname = 'deg_deci'
94
95    deg = np.abs(angle[0]) + np.abs(angle[1])/60. + np.abs(angle[2])/3600.
96
97    if angle[0] < 0.: deg = -deg*np.pi/180.
98    else: deg = deg*np.pi/180.
99
100    return deg
101
102def position_sphere(radii, alpha, beta):
103    """ Function to tranform fom a point in lon, lat deg coordinates to cartesian 
104          coordinates over an sphere
105      radii: radii of the sphere
106      alpha: longitude of the point
107      beta: latitude of the point
108    >>> position_sphere(10., 30., 45.)
109    (0.81031678432964027, -5.1903473778327376, 8.5090352453411846
110    """
111    fname = 'position_sphere'
112
113    xpt = radii*np.cos(beta)*np.cos(alpha)
114    ypt = radii*np.cos(beta)*np.sin(alpha)
115    zpt = radii*np.sin(beta)
116
117    return xpt, ypt, zpt
118
119def spheric_line(radii,lon,lat):
120    """ Function to transform a series of locations in lon, lat coordinates to x,y,z
121          over an 3D space
122      radii: radius of the sphere
123      lon: array of angles along longitudes
124      lat: array of angles along latitudes
125    """
126    fname = 'spheric_line'
127
128    Lint = lon.shape[0]
129    coords = np.zeros((Lint,3), dtype=np.float)
130
131    for iv in range(Lint):
132        coords[iv,:] = position_sphere(radii, lon[iv], lat[iv])
133
134    return coords
135
136def rotate_2D(vector, angle):
137    """ Function to rotate a vector by a certain angle in the plain
138      vector= vector to rotate [y, x]
139      angle= angle to rotate [rad]
140    >>> rotate_2D(np.array([1.,0.]), np.pi/4.)
141    [ 0.70710678 -0.70710678]
142    """
143    fname = 'rotate_2D'
144
145    rotmat = np.zeros((2,2), dtype=np.float)
146
147    rotmat[0,0] = np.cos(angle)
148    rotmat[0,1] = -np.sin(angle)
149    rotmat[1,0] = np.sin(angle)
150    rotmat[1,1] = np.cos(angle)
151
152    rotvector = np.zeros((2), dtype=np.float)
153
154    vecv = np.zeros((2), dtype=np.float)
155
156    # Unifying vector
157    modvec = vector[0]**2+vector[1]**2
158    if modvec != 0: 
159        vecv[0] = vector[1]/modvec
160        vecv[1] = vector[0]/modvec
161
162        rotvec = np.matmul(rotmat, vecv)
163        rotvec = np.where(np.abs(rotvec) < 1.e-7, 0., rotvec)
164
165        rotvector[0] = rotvec[1]*modvec
166        rotvector[1] = rotvec[0]*modvec
167
168    return rotvector
169
170def rotate_polygon_2D(vectors, angle):
171    """ Function to rotate 2D plain the vertices of a polygon
172      line= matrix of vectors to rotate
173      angle= angle to rotate [rad]
174    >>> square = np.zeros((4,2), dtype=np.float)
175    >>> square[0,:] = [-0.5,-0.5]
176    >>> square[1,:] = [0.5,-0.5]
177    >>> square[2,:] = [0.5,0.5]
178    >>> square[3,:] = [-0.5,0.5]
179    >>> rotate_polygon_2D(square, np.pi/4.)
180    [[-0.70710678  0.        ]
181     [ 0.         -0.70710678]
182     [ 0.70710678  0.        ]
183     [ 0.          0.70710678]]
184    """
185    fname = 'rotate_polygon_2D'
186
187    rotvecs = np.zeros(vectors.shape, dtype=np.float)
188
189    Nvecs = vectors.shape[0]
190    for iv in range(Nvecs):
191        rotvecs[iv,:] = rotate_2D(vectors[iv,:], angle)
192
193    return rotvecs
194
195def rotate_line2D(line, angle):
196    """ Function to rotate a line given by 2 pairs of x,y coordinates by a certain
197          angle in the plain
198      line= line to rotate as couple of points [[y0,x0], [y1,x1]]
199      angle= angle to rotate [rad]
200    >>> rotate_line2D(np.array([[0.,0.], [1.,0.]]), np.pi/4.)
201    [[ 0.          0.        ]
202     [0.70710678  -0.70710678]]
203    """
204    fname = 'rotate_2D'
205
206    rotline = np.zeros((2,2), dtype=np.float)
207    rotline[0,:] = rotate_2D(line[0,:], angle)
208    rotline[1,:] = rotate_2D(line[1,:], angle)
209
210    return rotline
211
212def rotate_lines2D(lines, angle):
213    """ Function to rotate multiple lines given by mulitple pars of x,y coordinates 
214          by a certain angle in the plain
215      line= matrix of N couples of points [N, [y0,x0], [y1,x1]]
216      angle= angle to rotate [rad]
217    >>> square = np.zeros((4,2,2), dtype=np.float)
218    >>> square[0,0,:] = [-0.5,-0.5]
219    >>> square[0,1,:] = [0.5,-0.5]
220    >>> square[1,0,:] = [0.5,-0.5]
221    >>> square[1,1,:] = [0.5,0.5]
222    >>> square[2,0,:] = [0.5,0.5]
223    >>> square[2,1,:] = [-0.5,0.5]
224    >>> square[3,0,:] = [-0.5,0.5]
225    >>> square[3,1,:] = [-0.5,-0.5]
226    >>> rotate_lines2D(square, np.pi/4.)
227    [[[-0.70710678  0.        ]
228      [ 0.         -0.70710678]]
229
230     [[ 0.         -0.70710678]
231      [ 0.70710678  0.        ]]
232
233     [[ 0.70710678  0.        ]
234      [ 0.          0.70710678]]
235
236     [[ 0.          0.70710678]
237      [-0.70710678  0.        ]]]
238    """
239    fname = 'rotate_lines2D'
240
241    rotlines = np.zeros(lines.shape, dtype=np.float)
242
243    Nlines = lines.shape[0]
244    for il in range(Nlines):
245        line = np.zeros((2,2), dtype=np.float)
246        line[0,:] = lines[il,0,:]
247        line[1,:] = lines[il,1,:]
248
249        rotlines[il,:,:] = rotate_line2D(line, angle)
250
251    return rotlines
252
253def dist_points(ptA, ptB):
254    """ Function to provide the distance between two points
255      ptA: coordinates of the point A [yA, xA]
256      ptB: coordinates of the point B [yB, xB]
257    >>> dist_points([1.,1.], [-1.,-1.])
258    2.82842712475
259    """
260    fname = 'dist_points'
261
262    dist = np.sqrt( (ptA[0]-ptB[0])**2 + (ptA[1]-ptB[1])**2)
263
264    return dist
265
266def max_coords_poly(polygon):
267    """ Function to provide the extremes of the coordinates of a polygon
268      polygon: coordinates [Nvertexs, 2] of a polygon
269    >>> square = np.zeros((4,2), dtype=np.float)
270    >>> square[0,:] = [-0.5,-0.5]
271    >>> square[1,:] = [0.5,-0.5]
272    >>> square[2,:] = [0.5,0.5]
273    >>> square[3,:] = [-0.5,0.5]
274    >>> max_coords_poly(square)
275    [-0.5, 0.5], [-0.5, 0.5], [0.5, 0.5], 0.5
276    """
277    fname = 'max_coords_poly'
278
279    # x-coordinate min/max
280    nx = np.min(polygon[:,1])
281    xx = np.max(polygon[:,1])
282
283    # y-coordinate min/max
284    ny = np.min(polygon[:,0])
285    xy = np.max(polygon[:,0])
286
287    # x/y-coordinate maximum of absolute values
288    axx = np.max(np.abs(polygon[:,1]))
289    ayx = np.max(np.abs(polygon[:,0]))
290
291    # absolute maximum
292    xyx = np.max([axx, ayx])
293
294    return [nx, xx], [ny, xy], [ayx, axx], xyx
295
296def mirror_polygon(polygon,axis):
297    """ Function to reflex a polygon for a given axis
298      polygon: polygon to mirror
299      axis: axis at which mirror is located ('x' or 'y')
300    """
301    fname = 'mirror_polygon'
302
303    reflex = np.zeros(polygon.shape, dtype=np.float)
304
305    N = polygon.shape[0]
306    if axis == 'x':
307        for iv in range(N):
308            reflex[iv,:] = [-polygon[iv,0], polygon[iv,1]]
309    elif axis == 'y':
310        for iv in range(N):
311            reflex[iv,:] = [polygon[iv,0], -polygon[iv,1]]
312
313    return reflex
314
315def join_circ_sec(points, radfrac=3., N=200):
316    """ Function to join aa series of points by circular segments
317      points: main points of the island (clockwise ordered, to be joined by circular
318        segments of radii as the radfrac factor of the distance between
319        consecutive points)
320      radfrac: multiplicative factor of the distance between consecutive points to
321        draw the circular segment (3., default)
322      N: number of points (200, default)
323    """
324    fname = 'join_circ_sec'
325
326    jcirc_sec = np.ones((N,2), dtype=np.float)
327
328    # main points
329    lpoints = list(points)
330    Npts = len(lpoints)
331    Np = int(N/(Npts+1))
332    for ip in range(Npts-1):
333        p1 = lpoints[ip]
334        p2 = lpoints[ip+1]
335        dps = dist_points(p1, p2)
336        jcirc_sec[Np*ip:Np*(ip+1),:] = circ_sec(p1, p2, dps*radfrac, 'short', Np)
337
338    Np2 = N - (Npts-1)*Np
339    p1 = lpoints[Npts-1]
340    p2 = lpoints[0]
341    dps = dist_points(p1, p2)
342    jcirc_sec[(Npts-1)*Np:N,:] = circ_sec(p1, p2, dps*3., 'short', Np2)
343
344    return jcirc_sec
345
346def join_circ_sec_rand(points, radfrac=3., Lrand=0.1, arc='short', pos='left', N=200):
347    """ Function to join aa series of points by circular segments with random
348        perturbations
349      points: main points of the island (clockwise ordered, to be joined by circular
350        segments of radii as the radfrac factor of the distance between
351        consecutive points)
352      radfrac: multiplicative factor of the distance between consecutive points to
353        draw the circular segment (3., default)
354      Lrand: maximum length of the random perturbation to be added perpendicularly to
355        the direction of the union line between points (0.1, default)
356      arc: type of arc ('short', default)
357      pos: position of arc ('left', default)
358      N: number of points (200, default)
359    """
360    import random
361    fname = 'join_circ_sec_rand'
362
363    jcirc_sec = np.ones((N,2), dtype=np.float)
364
365    # main points
366    lpoints = list(points)
367    Npts = len(lpoints)
368    Np = int(N/(Npts+1))
369    for ip in range(Npts-1):
370        p1 = lpoints[ip]
371        p2 = lpoints[ip+1]
372        dps = dist_points(p1, p2)
373        angle = np.arctan2(p2[0]-p1[0], p2[1]-p1[1]) + np.pi/2.
374        jcirc_sec[Np*ip:Np*(ip+1),:] = circ_sec(p1, p2, dps*radfrac, arc, pos, Np)
375        drand = Lrand*np.array([np.sin(angle), np.cos(angle)])
376        for iip in range(Np*ip,Np*(ip+1)):
377            jcirc_sec[iip,:] = jcirc_sec[iip,:] + drand*random.uniform(-1.,1.)
378
379    Np2 = N - (Npts-1)*Np
380    p1 = lpoints[Npts-1]
381    p2 = lpoints[0]
382    dps = dist_points(p1, p2)
383    angle = np.arctan2(p2[0]-p1[0], p2[1]-p1[1]) + np.pi/2.
384    jcirc_sec[(Npts-1)*Np:N,:] = circ_sec(p1, p2, dps*3., arc, pos, Np2)
385    drand = Lrand*np.array([np.sin(angle), np.cos(angle)])
386    for iip in range(Np*(Npts-1),N):
387        jcirc_sec[iip,:] = jcirc_sec[iip,:] + drand*random.uniform(-1.,1.)
388
389    return jcirc_sec
390
391def write_join_poly(polys, flname='join_polygons.dat'):
392    """ Function to write an ASCII file with the combination of polygons
393      polys: dictionary with the names of the different polygons
394      flname: name of the ASCII file
395    """
396    fname = 'write_join_poly'
397
398    of = open(flname, 'w')
399
400    for polyn in polys.keys():
401        vertices = polys[polyn]
402        Npts = vertices.shape[0]
403        for ip in range(Npts):
404            of.write(polyn+' '+str(vertices[ip,1]) + ' ' + str(vertices[ip,0]) + '\n')
405
406    of.close()
407
408    return
409
410def read_join_poly(flname='join_polygons.dat'):
411    """ Function to read an ASCII file with the combination of polygons
412      flname: name of the ASCII file
413    """
414    fname = 'read_join_poly'
415
416    of = open(flname, 'r')
417
418    polys = {}
419    polyn = ''
420    poly = []
421    for line in of:
422        if len(line) > 1: 
423            linevals = line.replace('\n','').split(' ')
424            if polyn != linevals[0]:
425                if len(poly) > 1:
426                    polys[polyn] = np.array(poly)
427                polyn = linevals[0]
428                poly = []
429                poly.append([np.float(linevals[2]), np.float(linevals[1])])
430            else:
431                poly.append([np.float(linevals[2]), np.float(linevals[1])])
432
433    of.close()
434    polys[polyn] = np.array(poly)
435
436    return polys
437
438def val_between(valA, valB, val):
439    """ Function to provide if a given value is between two consecutive ones
440      valA: first value
441      valB: second value
442      val: value to determine if it is between
443      >>> val_between(0.5,1.5,0.8)
444      True
445      >>> val_between(0.5,1.5.,-0.8)
446      False
447      >>> val_between(0.5,1.5,0.5)
448      True
449    """
450    fname = 'val_between'
451
452    btw = False
453    if (valA <= val and valB > val) or (valA < val and valB >= val): btw =True
454
455    return btw
456
457def cut_ypolygon(polygon, yval, keep='below', Nadd=20):
458    """ Function to cut a polygon from a given value of the y-axis
459      polygon: polygon to cut
460      yval: value to use to cut the polygon
461      keep: part to keep from the height ('below', default)
462         'below': below the height
463         'above': above the height
464      Nadd: additional points to add to draw the line (20, default)
465    """
466    fname = 'cut_ypolygon'
467
468    N = polygon.shape[0]
469    availkeeps = ['below', 'above']
470
471    if not gen.searchInlist(availkeeps, keep):
472        print errormsg
473        print '  ' + fname + ": wring keep '" + keep + "' value !!"
474        print '    available ones:', availkeeps
475        quit(-1)
476
477    ipt = None
478    ept = None
479
480    # There might be more than 1 cut...
481    Ncuts = 0
482    icut = []
483    ecut = []
484    ipt = []
485    ept = []
486
487    if type(polygon) == type(gen.mamat) and type(polygon.mask) !=                    \
488      type(gen.mamat.mask[1]):
489        # Assuming clockwise polygons
490        for ip in range(N-1):
491            if not polygon.mask[ip,0]:
492                eep = ip + 1
493                if eep == N: eep = 0
494     
495                if val_between(polygon[ip,0], polygon[eep,0], yval):
496                    icut.append(ip)
497                    dx = polygon[eep,1] - polygon[ip,1]
498                    dy = polygon[eep,0] - polygon[ip,0]
499                    dd = yval - polygon[ip,0]
500                    ipt.append([yval, polygon[ip,1]+dx*dd/dy])
501
502                if val_between(polygon[ip,0], polygon[eep,0], yval):
503                    ecut.append(ip)
504                    dx = polygon[eep,1] - polygon[ip,1]
505                    dy = polygon[eep,0] - polygon[ip,0]
506                    dd = yval - polygon[ip,0]
507                    ept.append([yval, polygon[ip,1]+dx*dd/dy])
508                    Ncuts = Ncuts + 1
509    else:
510        # Assuming clockwise polygons
511        for ip in range(N-1):
512            eep = ip + 1
513            if eep == N: eep = 0
514     
515            if val_between(polygon[ip,0], polygon[eep,0], yval):
516                icut.append(ip)
517                dx = polygon[eep,1] - polygon[ip,1]
518                dy = polygon[eep,0] - polygon[ip,0]
519                dd = yval - polygon[ip,0]
520                ipt.append([yval, polygon[ip,1]+dx*dd/dy])
521
522            if val_between(polygon[ip,0], polygon[eep,0], yval):
523                ecut.append(ip)
524                dx = polygon[eep,1] - polygon[ip,1]
525                dy = polygon[eep,0] - polygon[ip,0]
526                dd = yval - polygon[ip,0]
527                ept.append([yval, polygon[ip,1]+dx*dd/dy])
528                Ncuts = Ncuts + 1
529
530    if ipt is None or ept is None or Ncuts == 0:
531        print errormsg
532        print '  ' + fname + ': no cutting for polygon at y=', yval, '!!'
533    else:
534        print '  ' + fname + ': found ', Ncuts, ' Ncuts'
535        print '    yval=', yval, 'cut, ip; ipt ep; ept ________'
536        for ic in range(Ncuts):
537            print '      ', ic, icut[ic], ';', ipt[ic], ecut[ic], ';', ept[ic] 
538
539    Nadds = []
540    if Ncuts > 1:
541        Naddc = Nadd/(Ncuts-1)
542        for ic in range(Ncuts-1):
543            Nadds.append(Naddc)
544
545        Nadds.append(N-Naddc*(Ncuts-1))
546    else:
547        Nadds.append(Nadd)
548
549    iip = 0
550    iipc = 0
551    for ic in range(Ncuts):
552        if keep == 'below':
553            Npts = icut[ic] + (N-ecut[ic]) + Nadds[ic]
554            cutpolygon = np.zeros((Npts,2), dtype=np.float)
555            cutpolygon[iipc:iipc+icut[ic]+1,:] = polygon[iip:iip+icut[ic]+1,:]
556            iip = iip+icut[ic]+1
557            iipc = iipc+icut[ic]+1
558        else:
559            Npts = ecut[ec] - icut[ic] + Nadds[ic]-1
560            cutpolygon = np.zeros((Npts,2), dtype=np.float)
561            cutpolygon[iipc,:] = ipt[ic]
562            cutpolygon[iipc+1:ecut[ic]-icut[ic],:] = polygon[icut[ic]+1:ecut[ic],:]
563            iip = ecut[ic]-icut[ic]-1
564            iipc = iipc + ecut[ic]-icut[ic]-1
565
566        # cutting line
567        cutline = np.zeros((Nadds[ic],2), dtype=np.float)
568        dx = (ept[ic][1] - ipt[ic][1])/(Nadds[ic]-2)
569        dy = (ept[ic][0] - ipt[ic][0])/(Nadds[ic]-2)
570        cutline[0,:] = ipt[ic]
571        for ip in range(1,Nadds[ic]-1):
572            cutline[ip,:] = ipt[ic] + np.array([dy*ip,dx*ip])
573        cutline[Nadds[ic]-1,:] = ept[ic]
574        if keep == 'below':
575            cutpolygon[iip:iip+Nadds[ic],:] = cutline
576            cutpolygon[iip+Nadds[ic]:Npts,:] = polygon[ecut[ic]+1:N,:]
577        else:
578            cutpolygon[iip:iip+Nadds[ic],:] = cutline[::-1,:]
579
580    rmpolygon = []
581    Npts = cutpolygon.shape[0]
582    if keep == 'below':
583        for ip in range(Npts):
584            if cutpolygon[ip,0] > yval:
585                rmpolygon.append([gen.fillValueF, gen.fillValueF])
586            else:
587                rmpolygon.append(cutpolygon[ip,:])
588    else:
589        for ip in range(Npts):
590            if cutpolygon[ip,0] < yval:
591                rmpolygon.append([gen.fillValueF, gen.fillValueF])
592            else:
593                rmpolygon.append(cutpolygon[ip,:])
594    Npts = len(rmpolygon)
595    cutpolygon = np.array(rmpolygon)
596
597    cutpolygon = ma.masked_equal(cutpolygon, gen.fillValueF)
598
599    return Npts, cutpolygon
600
601def cut_xpolygon(polygon, xval, keep='left', Nadd=20):
602    """ Function to cut a polygon from a given value of the x-axis
603      polygon: polygon to cut
604      yval: value to use to cut the polygon
605      keep: part to keep from the value ('left', default)
606         'left': left of the value
607         'right': right of the value
608      Nadd: additional points to add to draw the line (20, default)
609    """
610    fname = 'cut_xpolygon'
611
612    N = polygon.shape[0]
613    availkeeps = ['left', 'right']
614
615    if not gen.searchInlist(availkeeps, keep):
616        print errormsg
617        print '  ' + fname + ": wring keep '" + keep + "' value !!"
618        print '    available ones:', availkeeps
619        quit(-1)
620
621    ipt = None
622    ept = None
623
624    icut = []
625    ecut = []
626    ipt = []
627    ept = []
628    Ncuts = 0
629    if type(polygon) == type(gen.mamat) and type(polygon.mask) !=                    \
630      type(gen.mamat.mask[1]):
631        # Assuming clockwise polygons
632        for ip in range(N-1):
633            if not polygon.mask[ip,1]:
634                eep = ip + 1
635                if eep == N: eep = 0
636     
637                if val_between(polygon[ip,1], polygon[eep,1], xval):
638                    icut.append(ip)
639                    dx = polygon[eep,1] - polygon[ip,1]
640                    dy = polygon[eep,0] - polygon[ip,0]
641                    dd = xval - polygon[ip,1]
642                    ipt.append([polygon[ip,0]+dy*dd/dx, xval])
643
644                if val_between(polygon[ip,1], polygon[eep,1], xval):
645                    ecut.append(ip)
646                    dx = polygon[eep,1] - polygon[ip,1]
647                    dy = polygon[eep,0] - polygon[ip,0]
648                    dd = xval - polygon[ip,1]
649                    ept.append([polygon[ip,0]+dy*dd/dx, xval])
650                    Npts = Npts + 1
651    else:
652        # Assuming clockwise polygons
653        for ip in range(N-1):
654            eep = ip + 1
655            if eep == N: eep = 0
656     
657            if val_between(polygon[ip,1], polygon[eep,1], xval):
658                icut.append(ip)
659                dx = polygon[eep,1] - polygon[ip,1]
660                dy = polygon[eep,0] - polygon[ip,0]
661                dd = xval - polygon[ip,1]
662                ipt.append([polygon[ip,0]+dy*dd/dx, xval])
663
664            if val_between(polygon[ip,1], polygon[eep,1], xval):
665                ecut.append(ip)
666                dx = polygon[eep,1] - polygon[ip,1]
667                dy = polygon[eep,0] - polygon[ip,0]
668                dd = xval - polygon[ip,1]
669                ept.append([polygon[ip,0]+dy*dd/dx, xval])
670
671    if ipt is None or ept is None or Ncuts == 0:
672        print errormsg
673        print '  ' + fname + ': no cutting for polygon at x=', xval, '!!'
674    else:
675        print '  ' + fname + ': found ', Ncuts, ' Ncuts'
676        print '    yval=', xval, 'cut, ip; ipt ep; ept ________'
677        for ic in range(Ncuts):
678            print '      ', ic, icut[ic], ';', ipt[ic], ecut[ic], ';', ept[ic] 
679
680    # Length of joining lines
681    Nadds = []   
682    if Ncuts > 1:
683        Naddc = (Nadd-Ncuts)/(Ncuts-1)
684        if Naddc < 3:
685            print errormsg
686            print '  ' + fname + ': too few points for jioning lines !!'
687            print '    increase Nadd at least to:', Ncuts*3+Ncuts
688            quit(-1)
689        for ic in range(Ncuts-1):
690            Nadds.append(Naddc)
691
692        Nadds.append(N-Naddc*(Ncuts-1))
693    else:
694        Nadds.append(Nadd)
695
696   # Total points cut polygon
697    Ntotpts = 0
698    Ncpts = []
699    for ic in range(Ncuts):
700        ip = ipt[ic]
701        if ic == 0: 
702            dpts = icut[ic] + ecut[ic] + Nadds[ic]
703        else:
704            dpts = ecut[ic] - icut[ic] + Nadds[ic] - 1
705
706        # Adding end of the polygon in 'left' keeps
707        if keep == 'left' and ic == Ncuts - 1: dpts = dpts + N-ecut[ic]
708        Ncpts.append(dpts)
709        Ntotpts = Ntotpts + dpts
710
711    cutpolygon = np.ones((Ntotpts,2), dtype=np.float)*gen.fillValue
712
713    iip = 0
714    iipc = 0
715    for ic in range(Ncuts):
716        Npts = Ncpts[ic]
717        if keep == 'left':
718            if ic == 0:
719                cutpolygon[0:icut[ic]] = polygon[0:icut[ic],:]
720                iip = icut[ic]
721                iipc = icut[ic]
722            dcpt = Ncpts[ic]-Nadds[ic]
723            cutpolygon[iipc+1:iipc+dcpt,:] = polygon[icut[ic]-1:ecut[ic]+1,:]
724            iipc = iipc + dcpt
725        else:
726            cutpolygon[iipc,:] = ipt[ic]
727            cutpolygon[iipc+1:iipc+ecut[ic]-icut[ic],:]=polygon[icut[ic]+1:ecut[ic],:]
728            iipc = iipc+ecut[ic]-icut[ic]-1
729
730        # cutting line
731        cutline = np.zeros((Nadds[ic],2), dtype=np.float)
732        dx = (ept[ic][1] - ipt[ic][1])/(Nadds[ic]-2)
733        dy = (ept[ic][0] - ipt[ic][0])/(Nadds[ic]-2)
734        cutline[0,:] = ipt[ic]
735        for ip in range(1,Nadds[ic]-1):
736            cutline[ip,:] = ipt[ic] + np.array([dy*ip,dx*ip])
737        cutline[Nadd-1,:] = ept[ic]
738        if keep == 'left':
739            cutpolygon[iipc:iipc+Nadds[ic],:] = cutline
740#            cutpolygon[iip+Nadd:Npts,:] = polygon[ecut+1:N,:]
741        else:
742            cutpolygon[iipc:iipc+Nadds[ic],:] = cutline[::-1,:]
743
744    rmpolygon = []
745    if keep == 'left':
746        for ip in range(Npts):
747            if cutpolygon[ip,1] > xval:
748                rmpolygon.append([gen.fillValueF, gen.fillValueF])
749            else:
750                rmpolygon.append(cutpolygon[ip,:])
751    else:
752        for ip in range(Npts):
753            if cutpolygon[ip,1] < xval:
754                rmpolygon.append([gen.fillValueF, gen.fillValueF])
755            else:
756                rmpolygon.append(cutpolygon[ip,:])
757    Npts = len(rmpolygon)
758    cutpolygon = np.array(rmpolygon)
759
760    cutpolygon = ma.masked_equal(cutpolygon, gen.fillValueF)
761
762    return Npts, cutpolygon
763
764def cut_between_ypolygon(polygon, yval1, yval2, Nadd=20):
765    """ Function to cut a polygon between 2 given value of the y-axis
766      polygon: polygon to cut
767      yval1: first value to use to cut the polygon
768      yval2: first value to use to cut the polygon
769      Nadd: additional points to add to draw the line (20, default)
770    """
771    fname = 'cut_betwen_ypolygon'
772
773    N = polygon.shape[0]
774
775    ipt = None
776    ept = None
777
778    dx = np.zeros((2), dtype=np.float)
779    dy = np.zeros((2), dtype=np.float)
780    icut = np.zeros((2), dtype=int)
781    ecut = np.zeros((2), dtype=int)
782    ipt = np.zeros((2,2), dtype=np.float)
783    ept = np.zeros((2,2), dtype=np.float)
784
785    if yval1 > yval2:
786        print errormsg
787        print '  ' + fname + ': wrong between cut values !!'
788        print '     it is expected yval1 < yval2'
789        print '     values provided yval1: (', yval1, ')> yval2 (', yval2, ')'
790        quit(-1)
791
792    yvals = [yval1, yval2]
793
794    for ic in range(2):
795        yval = yvals[ic]
796        if type(polygon) == type(gen.mamat):
797            # Assuming clockwise polygons
798            for ip in range(N-1):
799                if not polygon.mask[ip,0]:
800                    eep = ip + 1
801                    if eep == N: eep = 0
802     
803                    if polygon[ip,0] <= yval and polygon[eep,0] >= yval:
804                        icut[ic] = ip
805                        dx[ic] = polygon[eep,1] - polygon[ip,1]
806                        dy[ic] = polygon[eep,0] - polygon[ip,0]
807                        dd = yval - polygon[ip,0]
808                        ipt[ic,:] = [yval, polygon[ip,1]+dx[ic]*dd/dy[ic]]
809
810                    if polygon[ip,0] >= yval and polygon[eep,0] <= yval:
811                        ecut[ic] = ip
812                        dx[ic] = polygon[eep,1] - polygon[ip,1]
813                        dy[ic] = polygon[eep,0] - polygon[ip,0]
814                        dd = yval - polygon[ip,0]
815                        ept[ic,:] = [yval, polygon[ip,1]+dx[ic]*dd/dy[ic]]
816        else:
817            # Assuming clockwise polygons
818            for ip in range(N-1):
819                eep = ip + 1
820                if eep == N: eep = 0
821     
822                if polygon[ip,0] <= yval and polygon[eep,0] >= yval:
823                    icut[ic] = ip
824                    dx[ic] = polygon[eep,1] - polygon[ip,1]
825                    dy[ic] = polygon[eep,0] - polygon[ip,0]
826                    dd = yval - polygon[ip,0]
827                    ipt[ic,:] = [yval, polygon[ip,1]+dx[ic]*dd/dy[ic]]
828
829                if polygon[ip,0] >= yval and polygon[eep,0] <= yval:
830                    ecut[ic] = ip
831                    dx[ic] = polygon[eep,1] - polygon[ip,1]
832                    dy[ic] = polygon[eep,0] - polygon[ip,0]
833                    dd = yval - polygon[ip,0]
834                    ept[ic,:] = [yval, polygon[ip,1]+dx[ic]*dd/dy[ic]]
835
836        if ipt is None or ept is None:
837            print errormsg
838            print '  ' + fname + ': no cutting for polygon at y=', yval, '!!'
839
840    Npts = icut[1] - icut[0] + Nadd + ecut[0] - ecut[1]
841    cutpolygon = np.zeros((Npts,2), dtype=np.float)
842    cutpolygon[0,:] = ipt[0,:]
843    cutpolygon[1:icut[1]-icut[0]+1,:] = polygon[icut[0]+1:icut[1]+1,:]
844    iip = icut[1]-icut[0]
845
846    # cutting lines
847    Nadd2 = int(Nadd/2)
848    cutlines = np.zeros((2,Nadd2,2), dtype=np.float)
849
850    for ic in range(2):
851        dx = (ept[ic,1] - ipt[ic,1])/(Nadd2-2)
852        dy = (ept[ic,0] - ipt[ic,0])/(Nadd2-2)
853        cutlines[ic,0,:] = ipt[ic,:]
854        for ip in range(1,Nadd2-1):
855            cutlines[ic,ip,:] = ipt[ic,:] + np.array([dy*ip,dx*ip])
856        cutlines[ic,Nadd2-1,:] = ept[ic,:]
857
858    cutpolygon[iip:iip+Nadd2,:] = cutlines[1,:,:]
859    iip = iip + Nadd2
860    cutpolygon[iip:iip+(ecut[0]-ecut[1]),:] = polygon[ecut[1]+1:ecut[0]+1,:]
861    iip = iip + ecut[0]-ecut[1]
862    cutpolygon[iip:iip+Nadd2,:] = cutlines[0,::-1,:]
863
864    cutpolygon = ma.masked_equal(cutpolygon, gen.fillValueF)
865
866    return Npts, cutpolygon
867
868def cut_between_xpolygon(polygon, xval1, xval2, Nadd=20):
869    """ Function to cut a polygon between 2 given value of the x-axis
870      polygon: polygon to cut
871      xval1: first value to use to cut the polygon
872      xval2: first value to use to cut the polygon
873      Nadd: additional points to add to draw the line (20, default)
874    """
875    fname = 'cut_betwen_xpolygon'
876
877    N = polygon.shape[0]
878
879    ipt = None
880    ept = None
881
882    dx = np.zeros((2), dtype=np.float)
883    dy = np.zeros((2), dtype=np.float)
884    icut = np.zeros((2), dtype=int)
885    ecut = np.zeros((2), dtype=int)
886    ipt = np.zeros((2,2), dtype=np.float)
887    ept = np.zeros((2,2), dtype=np.float)
888
889    if xval1 > xval2:
890        print errormsg
891        print '  ' + fname + ': wrong between cut values !!'
892        print '     it is expected xval1 < xval2'
893        print '     values provided xval1: (', xval1, ')> xval2 (', xval2, ')'
894        quit(-1)
895
896    xvals = [xval1, xval2]
897
898    for ic in range(2):
899        xval = xvals[ic]
900        if type(polygon) == type(gen.mamat):
901            # Assuming clockwise polygons
902            for ip in range(N-1):
903                if not polygon.mask[ip,0]:
904                    eep = ip + 1
905                    if eep == N: eep = 0
906     
907                    if (polygon[ip,1] <= xval and polygon[eep,1] > xval) or          \
908                      (polygon[ip,1] < xval and polygon[eep,1] >= xval):
909                        icut[ic] = ip
910                        dx[ic] = polygon[eep,1] - polygon[ip,1]
911                        dy[ic] = polygon[eep,0] - polygon[ip,0]
912                        dd = xval - polygon[ip,1]
913                        ipt[ic,:] = [polygon[ip,0]+dy[ic]*dd/dx[ic], xval]
914
915                    if (polygon[ip,1] >= yval and polygon[eep,1] < xval) or          \
916                      (polygon[ip,1] > yval and polygon[eep,1] <= xval):
917                        ecut[ic] = ip
918                        dx[ic] = polygon[eep,1] - polygon[ip,1]
919                        dy[ic] = polygon[eep,0] - polygon[ip,0]
920                        dd = xval - polygon[ip,1]
921                        ept[ic,:] = [polygon[ip,0]+dy[ic]*dd/dx[ic], xval]
922        else:
923            # Assuming clockwise polygons
924            for ip in range(N-1):
925                eep = ip + 1
926                if eep == N: eep = 0
927     
928                if (polygon[ip,1] <= xval and polygon[eep,1] > xval) or              \
929                  (polygon[ip,1] < xval and polygon[eep,1] >= xval):
930                    icut[ic] = ip
931                    dx[ic] = polygon[eep,1] - polygon[ip,1]
932                    dy[ic] = polygon[eep,0] - polygon[ip,0]
933                    dd = xval - polygon[ip,1]
934                    print 'Lluis ip', ip, 'poly:', polygon[ip,:], 'xval:', xval, 'ip+1', polygon[eep,:]
935                    print '  dx:', dx, 'dy:', dy, 'dd', dd
936                    ipt[ic,:] = [polygon[ip,0]+dy[ic]*dd/dx[ic], xval]
937
938                if (polygon[ip,1] >= xval and polygon[eep,1] < xval) or              \
939                  (polygon[ip,1] > xval and polygon[eep,1] <= xval):
940                    ecut[ic] = ip
941                    dx[ic] = polygon[eep,1] - polygon[ip,1]
942                    dy[ic] = polygon[eep,0] - polygon[ip,0]
943                    dd = xval - polygon[ip,1]
944                    if dx[ic] == 0.:
945                        ept[ic,:] = [polygon[eep,0], xval]
946                    else:
947                        ept[ic,:] = [polygon[ip,0]+dy[ic]*dd/dx[ic], xval]
948
949        if ipt is None or ept is None:
950            print errormsg
951            print '  ' + fname + ': no cutting for polygon at x=', xval, '!!'
952
953    Npts = icut[1] - icut[0] + Nadd + ecut[0] - ecut[1]
954    cutpolygon = np.zeros((Npts,2), dtype=np.float)
955    cutpolygon[0,:] = ipt[0,:]
956    cutpolygon[1:icut[1]-icut[0]+1,:] = polygon[icut[0]+1:icut[1]+1,:]
957    iip = icut[1]-icut[0]
958
959    # cutting lines
960    Nadd2 = int(Nadd/2)
961    cutlines = np.zeros((2,Nadd2,2), dtype=np.float)
962
963    for ic in range(2):
964        print ic, 'Lluis ipt:', ipt[ic,:], 'ept:', ept[ic,:]
965        dx = (ept[ic,1] - ipt[ic,1])/(Nadd2-2)
966        dy = (ept[ic,0] - ipt[ic,0])/(Nadd2-2)
967        print '    dx:', dx, 'dy', dy
968        cutlines[ic,0,:] = ipt[ic,:]
969        for ip in range(1,Nadd2-1):
970            cutlines[ic,ip,:] = ipt[ic,:] + np.array([dy*ip,dx*ip])
971        cutlines[ic,Nadd2-1,:] = ept[ic,:]
972
973    cutpolygon[iip:iip+Nadd2,:] = cutlines[1,:,:]
974    iip = iip + Nadd2
975    cutpolygon[iip:iip+(ecut[0]-ecut[1]),:] = polygon[ecut[1]+1:ecut[0]+1,:]
976    iip = iip + ecut[0]-ecut[1]
977    cutpolygon[iip:iip+Nadd2,:] = cutlines[0,::-1,:]
978
979    cutpolygon = ma.masked_equal(cutpolygon, gen.fillValueF)
980
981    return Npts, cutpolygon
982
983####### ###### ##### #### ### ## #
984# Shapes/objects
985
986def surface_sphere(radii,Npts):
987    """ Function to provide an sphere as matrix of x,y,z coordinates
988      radii: radii of the sphere
989      Npts: number of points to discretisize longitues (half for latitudes)
990    """
991    fname = 'surface_sphere'
992
993    sphereup = np.zeros((3,Npts/2,Npts), dtype=np.float)
994    spheredown = np.zeros((3,Npts/2,Npts), dtype=np.float)
995    for ia in range(Npts):
996        alpha = ia*2*np.pi/(Npts-1)
997        for ib in range(Npts/2):
998            beta = ib*np.pi/(2.*(Npts/2-1))
999            sphereup[:,ib,ia] = position_sphere(radii, alpha, beta)
1000        for ib in range(Npts/2):
1001            beta = -ib*np.pi/(2.*(Npts/2-1))
1002            spheredown[:,ib,ia] = position_sphere(radii, alpha, beta)
1003
1004    return sphereup, spheredown
1005
1006def ellipse_polar(c, a, b, Nang=100):
1007    """ Function to determine an ellipse from its center and polar coordinates
1008        FROM: https://en.wikipedia.org/wiki/Ellipse
1009      c= coordinates of the center
1010      a= distance major axis
1011      b= distance minor axis
1012      Nang= number of angles to use
1013    """
1014    fname = 'ellipse_polar'
1015
1016    if np.mod(Nang,2) == 0: Nang=Nang+1
1017 
1018    dtheta = 2*np.pi/(Nang-1)
1019
1020    ellipse = np.zeros((Nang,2), dtype=np.float)
1021    for ia in range(Nang):
1022        theta = dtheta*ia
1023        rad = a*b/np.sqrt( (b*np.cos(theta))**2 + (a*np.sin(theta))**2 )
1024        x = rad*np.cos(theta)
1025        y = rad*np.sin(theta)
1026        ellipse[ia,:] = [y+c[0],x+c[1]]
1027
1028    return ellipse
1029
1030def hyperbola_polar(a, b, Nang=100):
1031    """ Fcuntion to determine an hyperbola in polar coordinates
1032        FROM: https://en.wikipedia.org/wiki/Hyperbola#Polar_coordinates
1033          x^2/a^2 - y^2/b^2 = 1
1034      a= x-parameter
1035      y= y-parameter
1036      Nang= number of angles to use
1037      DOES NOT WORK!!!!
1038    """
1039    fname = 'hyperbola_polar'
1040
1041    dtheta = 2.*np.pi/(Nang-1)
1042
1043    # Positive branch
1044    hyperbola_p = np.zeros((Nang,2), dtype=np.float)
1045    for ia in range(Nang):
1046        theta = dtheta*ia
1047        x = a*np.cosh(theta)
1048        y = b*np.sinh(theta)
1049        hyperbola_p[ia,:] = [y,x]
1050
1051    # Negative branch
1052    hyperbola_n = np.zeros((Nang,2), dtype=np.float)
1053    for ia in range(Nang):
1054        theta = dtheta*ia
1055        x = -a*np.cosh(theta)
1056        y = b*np.sinh(theta)
1057        hyperbola_n[ia,:] = [y,x]
1058
1059    return hyperbola_p, hyperbola_n
1060
1061def circ_sec(ptA, ptB, radii, arc='short', pos='left', Nang=100):
1062    """ Function union of point A and B by a section of a circle
1063      ptA= coordinates od the point A [yA, xA]
1064      ptB= coordinates od the point B [yB, xB]
1065      radii= radi of the circle to use to unite the points
1066      arc= which arc to be used ('short', default)
1067        'short': shortest angle between points
1068        'long': largest angle between points
1069      pos= orientation of the arc following clockwise union of points ('left', default)
1070        'left': to the left of union
1071        'right': to the right of union
1072      Nang= amount of angles to use
1073    """
1074    fname = 'circ_sec'
1075    availarc = ['short', 'long']
1076    availpos = ['left', 'right']
1077
1078    distAB = dist_points(ptA,ptB)
1079
1080    if distAB > radii:
1081        print errormsg
1082        print '  ' + fname + ': radii=', radii, " too small for the distance " +     \
1083          "between points !!"
1084        print '    distance between points:', distAB
1085        quit(-1)
1086
1087    # Coordinate increments
1088    dAB = np.abs(ptA-ptB)
1089
1090    # angle of the circular section joining points
1091    alpha = 2.*np.arcsin((distAB/2.)/radii)
1092
1093    # center along coincident bisection of the union
1094    xcc = -radii
1095    ycc = 0.
1096
1097    # Getting the arc of the circle at the x-axis
1098    if arc == 'short':
1099        dalpha = alpha/(Nang-1)
1100    elif arc == 'long':
1101        dalpha = (2.*np.pi - alpha)/(Nang-1)
1102    else:
1103        print errormsg
1104        print '  ' + fname + ": arc '" + arc + "' not ready !!" 
1105        print '    available ones:', availarc
1106        quit(-1)
1107    if pos == 'left': sign=-1.
1108    elif pos == 'right': sign=1.
1109    else:
1110        print errormsg
1111        print '  ' + fname + ": position '" + pos + "' not ready !!" 
1112        print '     available ones:', availpos
1113        quit(-1)
1114
1115    circ_sec = np.zeros((Nang,2), dtype=np.float)
1116    for ia in range(Nang):
1117        alpha = sign*dalpha*ia
1118        x = radii*np.cos(alpha)
1119        y = radii*np.sin(alpha)
1120
1121        circ_sec[ia,:] = [y+ycc,x+xcc]
1122
1123    # Angle of the points
1124    theta = np.arctan2(ptB[0]-ptA[0],ptB[1]-ptA[1])
1125
1126    # rotating angle of the circ
1127    if pos == 'left': 
1128        rotangle = theta + np.pi/2. - alpha/2.
1129    elif pos == 'right':
1130        rotangle = theta + 3.*np.pi/2. - alpha/2.
1131    else:
1132        print errormsg
1133        print '  ' + fname + ": position '" + pos + "' not ready !!" 
1134        print '     available ones:', availpos
1135        quit(-1)
1136
1137    #print 'alpha:', alpha*180./np.pi, 'theta:', theta*180./np.pi, 'rotangle:', rotangle*180./np.pi
1138 
1139    # rotating the arc along the x-axis
1140    rotcirc_sec = rotate_polygon_2D(circ_sec, rotangle)
1141
1142    # Moving arc to the ptA
1143    circ_sec = rotcirc_sec + ptA
1144
1145    return circ_sec
1146
1147def p_square(face, N=5):
1148    """ Function to get a polygon square
1149      face: length of the face of the square
1150      N: number of points of the polygon
1151    """
1152    fname = 'p_square'
1153
1154    square = np.zeros((N,2), dtype=np.float)
1155
1156    f2 = face/2.
1157    N4 = N/4
1158    df = face/(N4)
1159    # SW-NW
1160    for ip in range(N4):
1161        square[ip,:] = [-f2+ip*df,-f2]
1162    # NW-NE
1163    for ip in range(N4):
1164        square[ip+N4,:] = [f2,-f2+ip*df]
1165    # NE-SE
1166    for ip in range(N4):
1167        square[ip+2*N4,:] = [f2-ip*df,f2]
1168    N42 = N-3*N4-1
1169    df = face/(N42)
1170    # SE-SW
1171    for ip in range(N42):
1172        square[ip+3*N4,:] = [-f2,f2-ip*df]
1173    square[N-1,:] = [-f2,-f2]
1174
1175    return square
1176
1177
1178def p_prism(base, height, N=5):
1179    """ Function to get a polygon prism
1180      base: length of the base of the prism
1181      height: length of the height of the prism
1182      N: number of points of the polygon
1183    """
1184    fname = 'p_prism'
1185
1186    prism = np.zeros((N,2), dtype=np.float)
1187
1188    b2 = base/2.
1189    h2 = height/2.
1190    N4 = N/4
1191    dh = height/(N4)
1192    db = base/(N4)
1193
1194    # SW-NW
1195    for ip in range(N4):
1196        prism[ip,:] = [-h2+ip*dh,-b2]
1197    # NW-NE
1198    for ip in range(N4):
1199        prism[ip+N4,:] = [h2,-b2+ip*db]
1200    # NE-SE
1201    for ip in range(N4):
1202        prism[ip+2*N4,:] = [h2-ip*dh,b2]
1203    N42 = N-3*N4-1
1204    db = base/(N42)
1205    # SE-SW
1206    for ip in range(N42):
1207        prism[ip+3*N4,:] = [-h2,b2-ip*db]
1208    prism[N-1,:] = [-h2,-b2]
1209
1210    return prism
1211
1212def p_circle(radii, N=50):
1213    """ Function to get a polygon of a circle
1214      radii: length of the radii of the circle
1215      N: number of points of the polygon
1216    """
1217    fname = 'p_circle'
1218
1219    circle = np.zeros((N,2), dtype=np.float)
1220
1221    dangle = 2.*np.pi/(N-1)
1222
1223    for ia in range(N):
1224        circle[ia,:] = [radii*np.sin(ia*dangle), radii*np.cos(ia*dangle)]
1225
1226    circle[N-1,:] = [0., radii]
1227
1228    return circle
1229
1230def p_triangle(p1, p2, p3, N=4):
1231    """ Function to provide the polygon of a triangle from its 3 vertices
1232      p1: vertex 1 [y,x]
1233      p2: vertex 2 [y,x]
1234      p3: vertex 3 [y,x]
1235      N: number of vertices of the triangle
1236    """
1237    fname = 'p_triangle'
1238
1239    triangle = np.zeros((N,2), dtype=np.float)
1240
1241    N3 = N / 3
1242    # 1-2
1243    dx = (p2[1]-p1[1])/N3
1244    dy = (p2[0]-p1[0])/N3
1245    for ip in range(N3):
1246        triangle[ip,:] = [p1[0]+ip*dy,p1[1]+ip*dx]
1247    # 2-3
1248    dx = (p3[1]-p2[1])/N3
1249    dy = (p3[0]-p2[0])/N3
1250    for ip in range(N3):
1251        triangle[ip+N3,:] = [p2[0]+ip*dy,p2[1]+ip*dx]
1252    # 3-1
1253    N32 = N - 2*N/3
1254    dx = (p1[1]-p3[1])/N32
1255    dy = (p1[0]-p3[0])/N32
1256    for ip in range(N32):
1257        triangle[ip+2*N3,:] = [p3[0]+ip*dy,p3[1]+ip*dx]
1258
1259    triangle[N-1,:] = p1
1260
1261    return triangle
1262
1263def p_spiral(loops, eradii, N=1000):
1264    """ Function to provide a polygon of an Archimedean spiral
1265        FROM: https://en.wikipedia.org/wiki/Spiral
1266      loops: number of loops of the spiral
1267      eradii: length of the radii of the final spiral
1268      N: number of points of the polygon
1269    """
1270    fname = 'p_spiral'
1271
1272    spiral = np.zeros((N,2), dtype=np.float)
1273
1274    dangle = 2.*np.pi*loops/(N-1)
1275    dr = eradii*1./(N-1)
1276
1277    for ia in range(N):
1278        radii = dr*ia
1279        spiral[ia,:] = [radii*np.sin(ia*dangle), radii*np.cos(ia*dangle)]
1280
1281    return spiral
1282
1283def p_reg_polygon(Nv, lf, N=50):
1284    """ Function to provide a regular polygon of Nv vertices
1285      Nv: number of vertices
1286      lf: length of the face
1287      N: number of points
1288    """
1289    fname = 'p_reg_polygon'
1290
1291    reg_polygon = np.zeros((N,2), dtype=np.float)
1292
1293    # Number of points per vertex
1294    Np = N/Nv
1295    # Angle incremental between vertices
1296    da = 2.*np.pi/Nv
1297    # Radii of the circle according to lf
1298    radii = lf*Nv/(2*np.pi)
1299
1300    iip = 0
1301    for iv in range(Nv-1):
1302        # Characteristics between vertices iv and iv+1
1303        av1 = da*iv
1304        v1 = [radii*np.sin(av1), radii*np.cos(av1)]
1305        av2 = da*(iv+1)
1306        v2 = [radii*np.sin(av2), radii*np.cos(av2)]
1307        dx = (v2[1]-v1[1])/Np
1308        dy = (v2[0]-v1[0])/Np
1309        for ip in range(Np):
1310            reg_polygon[ip+iv*Np,:] = [v1[0]+dy*ip,v1[1]+dx*ip]
1311
1312    # Characteristics between vertices Nv and 1
1313
1314    # Number of points per vertex
1315    Np2 = N - Np*(Nv-1)
1316
1317    av1 = da*Nv
1318    v1 = [radii*np.sin(av1), radii*np.cos(av1)]
1319    av2 = 0.
1320    v2 = [radii*np.sin(av2), radii*np.cos(av2)]
1321    dx = (v2[1]-v1[1])/Np2
1322    dy = (v2[0]-v1[0])/Np2
1323    for ip in range(Np2):
1324        reg_polygon[ip+(Nv-1)*Np,:] = [v1[0]+dy*ip,v1[1]+dx*ip]
1325
1326    return reg_polygon
1327
1328def p_reg_star(Nv, lf, freq, vs=0, N=50):
1329    """ Function to provide a regular star of Nv vertices
1330      Nv: number of vertices
1331      lf: length of the face of the regular polygon
1332      freq: frequency of union of vertices ('0', for just centered to zero arms)
1333      vs: vertex from which start (0 being first [0,lf])
1334      N: number of points
1335    """
1336    fname = 'p_reg_star'
1337
1338    reg_star = np.zeros((N,2), dtype=np.float)
1339
1340    # Number of arms of the star
1341    if freq != 0 and np.mod(Nv,freq) == 0: 
1342        Na = Nv/freq + 1
1343    else:
1344        Na = Nv
1345
1346    # Number of points per arm
1347    Np = N/Na
1348    # Angle incremental between vertices
1349    da = 2.*np.pi/Nv
1350    # Radii of the circle according to lf
1351    radii = lf*Nv/(2*np.pi)
1352
1353    iip = 0
1354    av1 = vs*da
1355    for iv in range(Na-1):
1356        # Characteristics between vertices iv and iv+1
1357        v1 = [radii*np.sin(av1), radii*np.cos(av1)]
1358        if freq != 0:
1359            av2 = av1 + da*freq
1360            v2 = [radii*np.sin(av2), radii*np.cos(av2)]
1361        else:
1362            v2 = [0., 0.]
1363            av2 = av1 + da
1364        dx = (v2[1]-v1[1])/(Np-1)
1365        dy = (v2[0]-v1[0])/(Np-1)
1366        for ip in range(Np):
1367            reg_star[ip+iv*Np,:] = [v1[0]+dy*ip,v1[1]+dx*ip]
1368        if av2 > 2.*np.pi: av1 = av2 - 2.*np.pi
1369        else: av1 = av2 + 0.
1370
1371    iv = Na-1
1372    # Characteristics between vertices Na and 1
1373    Np2 = N-Np*iv
1374    v1 = [radii*np.sin(av1), radii*np.cos(av1)]
1375    if freq != 0:
1376        av2 = vs*da
1377        v2 = [radii*np.sin(av2), radii*np.cos(av2)]
1378    else:
1379        v2 = [0., 0.]
1380    dx = (v2[1]-v1[1])/(Np2-1)
1381    dy = (v2[0]-v1[0])/(Np2-1)
1382    for ip in range(Np2):
1383        reg_star[ip+iv*Np,:] = [v1[0]+dy*ip,v1[1]+dx*ip]
1384
1385    return reg_star
1386
1387def p_sinusiode(length=10., amp=5., lamb=3., ival=0., func='sin', N=100):
1388    """ Function to get coordinates of a sinusoidal curve
1389      length: length of the line (default 10.)
1390      amp: amplitude of the peaks (default 5.)
1391      lamb: wave longitude (defalult 3.)
1392      ival: initial angle (default 0. in degree)
1393      func: function to use: (default sinus)
1394        'sin': sinus
1395        'cos': cosinus
1396      N: number of points (default 100)
1397    """
1398    fname = 'p_sinusiode'
1399    availfunc = ['sin', 'cos']
1400
1401    dx = length/(N-1)
1402    ia = ival*np.pi/180.
1403    da = 2*np.pi*dx/lamb
1404
1405    sinusoide = np.zeros((N,2), dtype=np.float)
1406    if func == 'sin':
1407        for ix in range(N):
1408            sinusoide[ix,:] = [amp*np.sin(ia+da*ix),dx*ix]
1409    elif func == 'cos':
1410        for ix in range(N):
1411            sinusoide[ix,:] = [amp*np.cos(ia+da*ix),dx*ix]
1412    else:
1413        print errormsg
1414        print '  ' + fname + ": function '" + func + "' not ready !!"
1415        print '    available ones:', availfunc
1416        quit(-1)
1417
1418    sinusoidesecs = ['sinusoide']
1419    sinusoidedic = {'sinusoide': [sinusoide, '-', '#000000', 1.]}
1420
1421    return sinusoide, sinusoidesecs, sinusoidedic
1422
1423def p_doubleArrow(length=5., angle=45., width=1., alength=0.10, N=50):
1424    """ Function to provide an arrow with double lines
1425      length: length of the arrow (5. default)
1426      angle: angle of the head of the arrow (45., default)
1427      width: separation between the two lines (2., default)
1428      alength: length of the head (as percentage in excess of width, 0.1 default)
1429      N: number of points (50, default)
1430    """
1431    function = 'p_doubleArrow'
1432
1433    doubleArrow = np.zeros((50,2), dtype=np.float)
1434    N4 = int((N-3)/4)
1435
1436    doublearrowdic = {}
1437    ddy = width*np.tan(angle*np.pi/180.)/2.
1438    # Arms
1439    dx = (length-ddy)/(N4-1)
1440    for ix in range(N4):
1441        doubleArrow[ix,:] = [dx*ix,-width/2.]
1442    doublearrowdic['leftarm'] = [doubleArrow[0:N4,:], '-', '#000000', 2.]
1443    doubleArrow[N4,:] = [gen.fillValueF,gen.fillValueF]
1444    for ix in range(N4):
1445        doubleArrow[N4+1+ix,:] = [dx*ix,width/2.]
1446    doublearrowdic['rightarm'] = [doubleArrow[N4+1:2*N4+1,:], '-', '#000000', 2.]
1447    doubleArrow[2*N4+1,:] = [gen.fillValueF,gen.fillValueF]
1448
1449    # Head
1450    N42 = int((N-2 - 2*N4)/2)
1451    dx = width*(1.+alength)*np.cos(angle*np.pi/180.)/(N42-1)
1452    dy = width*(1.+alength)*np.sin(angle*np.pi/180.)/(N42-1)
1453    for ix in range(N42):
1454        doubleArrow[2*N4+2+ix,:] = [length-dy*ix,-dx*ix]
1455    doublearrowdic['lefthead'] = [doubleArrow[2*N4:2*N4+N42,:], '-', '#000000', 2.]
1456    doubleArrow[2*N4+2+N42,:] = [gen.fillValueF,gen.fillValueF]
1457
1458    N43 = N-3 - 2*N4 - N42 + 1
1459    dx = width*(1.+alength)*np.cos(angle*np.pi/180.)/(N43-1)
1460    dy = width*(1.+alength)*np.sin(angle*np.pi/180.)/(N43-1)
1461    for ix in range(N43):
1462        doubleArrow[2*N4+N42+2+ix,:] = [length-dy*ix,dx*ix]
1463    doublearrowdic['rightthead'] = [doubleArrow[2*N4+N42+2:51,:], '-', '#000000', 2.]
1464
1465    doubleArrow = ma.masked_equal(doubleArrow, gen.fillValueF)
1466    doublearrowsecs = ['leftarm', 'rightarm', 'lefthead', 'righthead']
1467
1468    return doubleArrow, doublearrowsecs, doublearrowdic
1469
1470def p_angle_triangle(pi=np.array([0.,0.]), angle1=60., length1=1., angle2=60., N=100):
1471    """ Function to draw a triangle by an initial point and two consecutive angles
1472        and the first length of face. The third angle and 2 and 3rd face will be
1473        computed accordingly the provided values:
1474           length1 / sin(angle1) = length2 / sin(angle2) = length3 / sin(angle3)
1475           angle1 + angle2 + angle3 = 180.
1476      pi: initial point ([0., 0.], default)
1477      angle1: first angle from pi clockwise (60., default)
1478      length1: length of face from pi by angle1 (1., default)
1479      angle2: second angle from second point (60., default)
1480      length2: length of face from p2 by angle2 (1., default)
1481      N: number of points (100, default)
1482    """
1483    fname = 'p_angle_triangle'
1484
1485    angle3 = 180. - angle1 - angle2
1486    length2 = np.sin(angle2*np.pi/180.)*length1/np.sin(angle1*np.pi/180.)
1487    length3 = np.sin(angle3*np.pi/180.)*length1/np.sin(angle1*np.pi/180.)
1488
1489    triangle = np.zeros((N,2), dtype=np.float)
1490
1491    N3 = int(N/3)
1492    # first face
1493    ix = pi[1]
1494    iy = pi[0]
1495    dx = length1*np.cos(angle1*np.pi/180.)/(N3-1)
1496    dy = length1*np.sin(angle1*np.pi/180.)/(N3-1)
1497    for ip in range(N3):
1498        triangle[ip,:] = [iy+dy*ip, ix+dx*ip]
1499
1500    # second face
1501    ia = -90. - (90.-angle1)
1502    ix = triangle[N3-1,1]
1503    iy = triangle[N3-1,0]
1504    dx = length2*np.cos((ia+angle2)*np.pi/180.)/(N3-1)
1505    dy = length2*np.sin((ia+angle2)*np.pi/180.)/(N3-1)
1506    for ip in range(N3):
1507        triangle[N3+ip,:] = [iy+dy*ip, ix+dx*ip]
1508
1509    # third face
1510    N32 = N - 2*N3
1511    ia = -180. - (90.-angle2)
1512    ix = triangle[2*N3-1,1]
1513    iy = triangle[2*N3-1,0]
1514    angle3 = np.arctan2(pi[0]-iy, pi[1]-ix)
1515    dx = (pi[1]-ix)/(N32-1)
1516    dy = (pi[0]-iy)/(N32-1)
1517    for ip in range(N32):
1518        triangle[2*N3+ip,:] = [iy+dy*ip, ix+dx*ip]
1519
1520    return triangle
1521
1522def p_cross_width(larm=5., width=1., Narms=4, N=200):
1523    """ Function to draw a cross with arms with a given width and an angle
1524      larm: legnth of the arms (5., default)
1525      width: width of the arms (1., default)
1526      Narms: Number of arms (4, default)
1527      N: number of points to us (200, default)
1528    """
1529    fname = 'p_cross_width'
1530
1531    Narm = int((N-Narms)/Narms)
1532
1533    larm2 = larm/2.
1534    width2 = width/2.
1535
1536    cross = np.ones((N,2), dtype=np.float)*gen.fillValueF
1537    da = np.pi/Narms
1538
1539    N1 = int(Narm*3./8.)
1540    N2 = int((Narm - 2*N1)/2.)
1541    N21 = Narm - 2*N1 - N2
1542
1543    if N2 < 3:
1544        print errormsg
1545        print '  ' + fname + ": too few points for ", Narms, " arms !!"
1546        print "    increase number 'N' at least up to '", 25*Narms
1547        quit(-1)
1548
1549    crosssecs = []
1550    crossdic = {}
1551    Npot = int(np.log10(Narms))+1
1552
1553    iip = 0
1554    for iarm in range(Narms-1):
1555
1556        a = da*iarm
1557        iip0 = iip
1558
1559        # bottom coordinate
1560        bx = larm*np.cos(a+np.pi)
1561        by = larm*np.sin(a+np.pi)
1562
1563        # upper coordinate
1564        ux = larm*np.cos(a)
1565        uy = larm*np.sin(a)
1566
1567        rela = a+np.pi*3./2.
1568        # SW-NW
1569        ix = bx + width2*np.cos(rela)
1570        iy = by + width2*np.sin(rela)
1571        ex = ux + width2*np.cos(rela)
1572        ey = uy + width2*np.sin(rela)
1573        dx = (ex-ix)/(N1-1)
1574        dy = (ey-iy)/(N1-1)
1575        for ip in range(N1):
1576            cross[iip+ip,:] = [iy+dy*ip,ix+dx*ip]
1577        iip = iip + N1
1578
1579        # NW-NE
1580        ix = ex + 0.
1581        iy = ey + 0.
1582        ex = ux - width2*np.cos(rela)
1583        ey = uy - width2*np.sin(rela)
1584        dx = (ex-ix)/(N2-1)
1585        dy = (ey-iy)/(N2-1)
1586        for ip in range(N2):
1587            cross[iip+ip,:] = [iy+dy*ip,ix+dx*ip]
1588        iip = iip + N2
1589
1590        # NW-SW
1591        ix = ex + 0.
1592        iy = ey + 0.
1593        ex = bx - width2*np.cos(rela)
1594        ey = by - width2*np.sin(rela)
1595        dx = (ex-ix)/(N1-1)
1596        dy = (ey-iy)/(N1-1)
1597        for ip in range(N1):
1598            cross[iip+ip,:] = [iy+dy*ip,ix+dx*ip]
1599        iip = iip + N1
1600
1601        # SW-SE
1602        ix = ex + 0.
1603        iy = ey + 0.
1604        ex = bx + width2*np.cos(rela)
1605        ey = by + width2*np.sin(rela)
1606        dx = (ex-ix)/(N21-1)
1607        dy = (ey-iy)/(N21-1)
1608        for ip in range(N21):
1609            cross[iip+ip,:] = [iy+dy*ip,ix+dx*ip]
1610        iip = iip + N21 + 1
1611
1612        iarmS = str(iarm).zfill(Npot)
1613        crosssecs.append(iarmS)
1614        crossdic[iarmS] = [cross[iip0:iip0+iip-1], '-', 'k', '1.']
1615
1616    iip0 = iip
1617
1618    Narm = N - Narm*(Narms-1) - Narms
1619
1620    N1 = int(Narm*3./8.)
1621    N2 = int((Narm - 2*N1)/2.)
1622    N21 = Narm - 2*N1 - N2
1623
1624    iarm = Narms-1
1625    a = da*iarm
1626
1627    # bottom coordinate
1628    bx = larm*np.cos(a+np.pi)
1629    by = larm*np.sin(a+np.pi)
1630
1631    # upper coordinate
1632    ux = larm*np.cos(a)
1633    uy = larm*np.sin(a)
1634
1635    rela = a+np.pi*3./2.
1636    # SW-NW
1637    ix = bx + width2*np.cos(rela)
1638    iy = by + width2*np.sin(rela)
1639    ex = ux + width2*np.cos(rela)
1640    ey = uy + width2*np.sin(rela)
1641    dx = (ex-ix)/(N1-1)
1642    dy = (ey-iy)/(N1-1)
1643    for ip in range(N1):
1644      cross[iip+ip,:] = [iy+dy*ip,ix+dx*ip]
1645    iip = iip + N1
1646
1647    # NW-NE
1648    ix = ex + 0.
1649    iy = ey + 0.
1650    ex = ux - width2*np.cos(rela)
1651    ey = uy - width2*np.sin(rela)
1652    dx = (ex-ix)/(N2-1)
1653    dy = (ey-iy)/(N2-1)
1654    for ip in range(N2):
1655      cross[iip+ip,:] = [iy+dy*ip,ix+dx*ip]
1656    iip = iip + N2
1657
1658    # NW-SW
1659    ix = ex + 0.
1660    iy = ey + 0.
1661    ex = bx - width2*np.cos(rela)
1662    ey = by - width2*np.sin(rela)
1663    dx = (ex-ix)/(N1-1)
1664    dy = (ey-iy)/(N1-1)
1665    for ip in range(N1):
1666      cross[iip+ip,:] = [iy+dy*ip,ix+dx*ip]
1667    iip = iip + N1
1668
1669    # SW-SE
1670    ix = ex + 0.
1671    iy = ey + 0.
1672    ex = bx + width2*np.cos(rela)
1673    ey = by + width2*np.sin(rela)
1674    dx = (ex-ix)/(N21-1)
1675    dy = (ey-iy)/(N21-1)
1676    for ip in range(N21):
1677      cross[iip+ip,:] = [iy+dy*ip,ix+dx*ip]
1678    iip = iip + N21
1679
1680    iarmS = str(iarm).zfill(Npot)
1681    crosssecs.append(iarmS)
1682    crossdic[iarmS] = [cross[iip0:iip0+iip-1], '-', 'k', '1.']
1683
1684    cross = ma.masked_equal(cross, gen.fillValueF)
1685
1686    return cross, crosssecs, crossdic
1687
1688# Combined objects
1689##
1690
1691# FROM: http://www.photographers1.com/Sailing/NauticalTerms&Nomenclature.html
1692def zboat(length=10., beam=1., lbeam=0.4, sternbp=0.5):
1693    """ Function to define an schematic boat from the z-plane
1694      length: length of the boat (without stern, default 10)
1695      beam: beam of the boat (default 1)
1696      lbeam: length at beam (as percentage of length, default 0.4)
1697      sternbp: beam at stern (as percentage of beam, default 0.5)
1698    """
1699    fname = 'zboat'
1700
1701    bow = np.array([length, 0.])
1702    maxportside = np.array([length*lbeam, -beam])
1703    maxstarboardside = np.array([length*lbeam, beam])
1704    portside = np.array([0., -beam*sternbp])
1705    starboardside = np.array([0., beam*sternbp])
1706
1707    # forward section
1708    fportside = circ_sec(maxportside, bow, length*2)
1709    fstarboardside = circ_sec(bow, maxstarboardside, length*2)
1710    # aft section
1711    aportside = circ_sec(portside, maxportside, length*2)
1712    astarboardside = circ_sec(maxstarboardside, starboardside, length*2)
1713    # stern
1714    stern = circ_sec(starboardside, portside, length*2)
1715
1716    dpts = stern.shape[0]
1717    boat = np.zeros((dpts*5,2), dtype=np.float)
1718
1719    boat[0:dpts,:] = aportside
1720    boat[dpts:2*dpts,:] = fportside
1721    boat[2*dpts:3*dpts,:] = fstarboardside
1722    boat[3*dpts:4*dpts,:] = astarboardside
1723    boat[4*dpts:5*dpts,:] = stern
1724
1725    fname = 'boat_L' + str(int(length*100.)) + '_B' + str(int(beam*100.)) + '_lb' +  \
1726      str(int(lbeam*100.)) + '_sb' + str(int(sternbp*100.)) + '.dat'
1727    if not os.path.isfile(fname):
1728        print infmsg
1729        print '  ' + fname + ": writting boat coordinates file '" + fname + "' !!"
1730        of = open(fname, 'w')
1731        of.write('# boat file with Length: ' + str(length) +' max_beam: '+str(beam)+ \
1732          'length_at_max_beam:' + str(lbeam) + '% beam at stern: ' + str(sternbp)+   \
1733          ' %\n')
1734        for ip in range(dpts*5):
1735            of.write(str(boat[ip,0]) + ' ' + str(boat[ip,1]) + '\n')
1736       
1737        of.close()
1738        print fname + ": Successfull written '" + fname + "' !!"
1739
1740
1741    # Center line extending [fcl] percentage from length on aft and stern
1742    fcl = 0.15
1743    centerline = np.zeros((dpts,2), dtype=np.float)
1744    dl = length*(1.+fcl*2.)/(dpts-1)
1745    centerline[:,0] = np.arange(-length*fcl, length*(1. + fcl)+dl, dl)
1746
1747    # correct order of sections
1748    boatsecs = ['aportside', 'fportside', 'fstarboardside', 'astarboardside',        \
1749      'stern', 'centerline']
1750
1751    # dictionary with sections [polygon_vertices, line_type, line_color, line_width]
1752    dicboat = {'fportside': [fportside, '-', '#8A5900', 2.],                         \
1753      'aportside': [aportside, '-', '#8A5900', 2.],                                  \
1754      'stern': [stern, '-', '#8A5900', 2.],                                          \
1755      'astarboardside': [astarboardside, '-', '#8A5900', 2.],                        \
1756      'fstarboardside': [fstarboardside, '-', '#8A5900', 2.],                        \
1757      'centerline': [centerline, '-.', '#AA6464', 1.5]}
1758   
1759    fname = 'sailboat_L' + str(int(length*100.)) + '_B' + str(int(beam*100.)) +      \
1760      '_lb' + str(int(lbeam*100.)) + '_sb' + str(int(sternbp*100.)) +'.dat'
1761    if not os.path.isfile(fname):
1762        print infmsg
1763        print '  ' + fname + ": writting boat coordinates file '" + fname + "' !!"
1764        of = open(fname, 'w')
1765        of.write('# boat file with Length: ' + str(length) +' max_beam: '+str(beam)+ \
1766          'length_at_max_beam:' + str(lbeam) + '% beam at stern: ' +str(sternbp)+'\n')
1767        for ip in range(dpts*5):
1768            of.write(str(boat[ip,0]) + ' ' + str(boat[ip,1]) + '\n')
1769       
1770        of.close()
1771        print fname + ": Successfull written '" + fname + "' !!"
1772 
1773    return boat, boatsecs, dicboat
1774
1775def zsailing_boat(length=10., beam=1., lbeam=0.4, sternbp=0.5, lmast=0.6, wmast=0.1, \
1776  hsd=5., msd=5., lheads=0.38, lmains=0.55):
1777    """ Function to define an schematic sailing boat from the z-plane with sails
1778      length: length of the boat (without stern, default 10)
1779      beam: beam of the boat (default 1)
1780      lbeam: length at beam (as percentage of length, default 0.4)
1781      sternbp: beam at stern (as percentage of beam, default 0.5)
1782      lmast: position of the mast (as percentage of length, default 0.6)
1783      wmast: width of the mast (default 0.1)
1784      hsd: head sail direction respect to center line (default 5., -999.99 for upwind)
1785      msd: main sail direction respect to center line (default 5., -999.99 for upwind)
1786      lheads: length of head sail (as percentage of legnth, defaul 0.38)
1787      lmains: length of main sail (as percentage of legnth, defaul 0.55)
1788    """
1789    fname = 'zsailing_boat'
1790
1791    bow = np.array([length, 0.])
1792    maxportside = np.array([length*lbeam, -beam])
1793    maxstarboardside = np.array([length*lbeam, beam])
1794    portside = np.array([0., -beam*sternbp])
1795    starboardside = np.array([0., beam*sternbp])
1796
1797    aportside = circ_sec(portside, maxportside, length*2)
1798    fportside = circ_sec(maxportside, bow, length*2)
1799    fstarboardside = circ_sec(bow, maxstarboardside, length*2)
1800    astarboardside = circ_sec(maxstarboardside, starboardside, length*2)
1801    stern = circ_sec(starboardside, portside, length*2)
1802    dpts = fportside.shape[0]
1803
1804    # correct order of sections
1805    sailingboatsecs = ['aportside', 'fportside', 'fstarboardside', 'astarboardside', \
1806      'stern', 'mast', 'hsail', 'msail', 'centerline']
1807
1808    # forward section
1809
1810    # aft section
1811    # stern
1812    # mast
1813    mast = p_circle(wmast,N=dpts)
1814    mast = mast + [length*lmast, 0.]
1815    # head sails
1816    lsail = lheads*length
1817    if hsd != -999.99:
1818        sailsa = np.pi/2. - np.pi*hsd/180.
1819        endsail = np.array([lsail*np.sin(sailsa), lsail*np.cos(sailsa)])
1820        endsail[0] = length - endsail[0]
1821        if bow[1] > endsail[1]:
1822            hsail = circ_sec(endsail, bow, lsail*2.15)
1823        else:
1824            hsail = circ_sec(bow, endsail, lsail*2.15)
1825    else:
1826        hsail0 = p_sinusiode(length=lsail, amp=0.2, lamb=0.75, N=dpts)
1827        hsail = np.zeros((dpts,2), dtype=np.float)
1828        hsail[:,0] = hsail0[:,1]
1829        hsail[:,1] = hsail0[:,0]
1830        hsail = bow - hsail
1831
1832    # main sails
1833    lsail = lmains*length
1834    if msd != -999.99:
1835        sailsa = np.pi/2. - np.pi*msd/180.
1836        begsail = np.array([length*lmast, 0.])
1837        endsail = np.array([lsail*np.sin(sailsa), lsail*np.cos(sailsa)])
1838        endsail[0] = length*lmast - endsail[0]
1839        if endsail[1] > begsail[1]:
1840            msail = circ_sec(begsail, endsail, lsail*2.15)
1841        else:
1842            msail = circ_sec(endsail, begsail, lsail*2.15)
1843    else:
1844        msail0 = p_sinusiode(length=lsail, amp=0.25, lamb=1., N=dpts)
1845        msail = np.zeros((dpts,2), dtype=np.float)
1846        msail[:,0] = msail0[:,1]
1847        msail[:,1] = msail0[:,0]
1848        msail = [length*lmast,0] - msail
1849
1850    sailingboat = np.zeros((dpts*8+4,2), dtype=np.float)
1851
1852    sailingboat[0:dpts,:] = aportside
1853    sailingboat[dpts:2*dpts,:] = fportside
1854    sailingboat[2*dpts:3*dpts,:] = fstarboardside
1855    sailingboat[3*dpts:4*dpts,:] = astarboardside
1856    sailingboat[4*dpts:5*dpts,:] = stern
1857    sailingboat[5*dpts,:] = [gen.fillValueF, gen.fillValueF]
1858    sailingboat[5*dpts+1:6*dpts+1,:] = mast
1859    sailingboat[6*dpts+1,:] = [gen.fillValueF, gen.fillValueF]
1860    sailingboat[6*dpts+2:7*dpts+2,:] = hsail
1861    sailingboat[7*dpts+2,:] = [gen.fillValueF, gen.fillValueF]
1862    sailingboat[7*dpts+3:8*dpts+3,:] = msail
1863    sailingboat[8*dpts+3,:] = [gen.fillValueF, gen.fillValueF]
1864
1865    sailingboat = ma.masked_equal(sailingboat, gen.fillValueF)
1866
1867    # Center line extending [fcl] percentage from length on aft and stern
1868    fcl = 0.15
1869    centerline = np.zeros((dpts,2), dtype=np.float)
1870    dl = length*(1.+fcl*2.)/(dpts-1)
1871    centerline[:,0] = np.arange(-length*fcl, length*(1. + fcl)+dl, dl)
1872
1873    # dictionary with sections [polygon_vertices, line_type, line_color, line_width]
1874    dicsailingboat = {'fportside': [fportside, '-', '#8A5900', 2.],                  \
1875      'aportside': [aportside, '-', '#8A5900', 2.],                                  \
1876      'stern': [stern, '-', '#8A5900', 2.],                                          \
1877      'astarboardside': [astarboardside, '-', '#8A5900', 2.],                        \
1878      'fstarboardside': [fstarboardside, '-', '#8A5900', 2.],                        \
1879      'mast': [mast, '-', '#8A5900', 2.], 'hsail': [hsail, '-', '#AAAAAA', 1.],      \
1880      'msail': [msail, '-', '#AAAAAA', 1.],                                          \
1881      'centerline': [centerline, '-.', '#AA6464', 1.5]}
1882   
1883    fname = 'sailboat_L' + str(int(length*100.)) + '_B' + str(int(beam*100.)) +      \
1884      '_lb' + str(int(lbeam*100.)) + '_sb' + str(int(sternbp*100.)) +                \
1885      '_lm' + str(int(lmast*100.)) + '_wm' + str(int(wmast)) +                       \
1886      '_hsd' + str(int(hsd)) + '_hs' + str(int(lheads*100.)) +                       \
1887      '_ms' + str(int(lheads*100.)) + '_msd' + str(int(msd)) +'.dat'
1888    if not os.path.isfile(fname):
1889        print infmsg
1890        print '  ' + fname + ": writting boat coordinates file '" + fname + "' !!"
1891        of = open(fname, 'w')
1892        of.write('# boat file with Length: ' + str(length) +' max_beam: '+str(beam)+ \
1893          'length_at_max_beam:' + str(lbeam) + '% beam at stern: ' + str(sternbp)+   \
1894          ' % mast position: '+ str(lmast) + ' % mast width: ' + str(wmast) + ' ' +  \
1895          ' head sail direction:' + str(hsd) + ' head sail length: ' + str(lheads) + \
1896          ' %' + ' main sail length' + str(lmains) + ' main sail direction:' +       \
1897          str(msd) +'\n')
1898        for ip in range(dpts*5):
1899            of.write(str(sailingboat[ip,0]) + ' ' + str(sailingboat[ip,1]) + '\n')
1900       
1901        of.close()
1902        print fname + ": Successfull written '" + fname + "' !!"
1903 
1904    return sailingboat, sailingboatsecs, dicsailingboat
1905
1906def zisland1(mainpts= np.array([[-0.1,0.], [-1.,1.], [-0.8,1.2], [0.1,0.6], [1., 0.9],\
1907  [2.8, -0.1], [0.1,-0.6]], dtype=np.float), radfrac=3., N=200):
1908    """ Function to draw an island from z-axis as the union of a series of points by
1909        circular segments
1910      mainpts: main points of the island (clockwise ordered, to be joined by
1911        circular segments of radii as the radfrac factor of the distance between
1912        consecutive points)
1913          * default= np.array([[-0.1,0.], [-1.,1.], [-0.8,1.2], [0.1,0.6], [1., 0.9],
1914            [2.8, -0.1], [0.1,-0.6]], dtype=np.float)
1915      radfrac: multiplicative factor of the distance between consecutive points to
1916        draw the circular segment (3., default)
1917      N: number of points (200, default)
1918    """
1919    fname = 'zisland1'
1920
1921    island1 = np.ones((N,2), dtype=np.float)*gen.fillValueF
1922
1923    # Coastline
1924    island1 = join_circ_sec_rand(mainpts, arc='short', pos='left')
1925
1926    islandsecs = ['coastline']
1927    islanddic = {'coastline': [island1, '-', '#161616', 2.]}
1928
1929    island1 = ma.masked_equal(island1, gen.fillValueF)
1930
1931    return island1, islandsecs, islanddic
1932
1933def buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, N=300):
1934    """ Function to draw a buoy as superposition of prism and section of ball
1935      height: height of the prism (5., default)
1936      width: width of the prism (10., default)
1937      bradii: radii of the ball (1.75, default)
1938      bfrac: fraction of the ball above the prism (0.8, default)
1939      N: total number of points of the buoy (300, default)
1940    """
1941    fname = 'buoy1'
1942
1943    buoy = np.zeros((N,2), dtype=np.float)
1944
1945    N3 = int(N/3/5)
1946    NNp = 0
1947    iip = 0
1948    # left lateral
1949    ix = -width/2.
1950    Np = N3
1951    iy = 0.
1952    dx = 0.
1953    dy = height/(Np)
1954    for ip in range(Np):
1955        buoy[iip+ip,:] = [iy+dy*ip,ix+dx*ip]
1956    NNp = NNp + Np
1957    iip = NNp
1958
1959    # left upper
1960    ix = -width/2.
1961    iy = height
1962    dx = (width/2.-bradii*bfrac)/(Np)
1963    dy = 0.
1964    for ip in range(Np):
1965        buoy[iip+ip,:] = [iy+dy*ip,ix+dx*ip]
1966    NNp = NNp + Np
1967    iip = NNp
1968
1969    # ball
1970    p1 = np.array([height, -bradii*bfrac])
1971    p2 = np.array([height, bradii*bfrac])
1972    Np = int(2*N/3)
1973    buoy[iip:iip+Np,:] = circ_sec(p1, p2, 2.*bradii, 'long', 'left', Np)
1974    NNp = NNp + Np
1975    iip = NNp
1976
1977    # right upper
1978    ix = bradii*bfrac
1979    iy = height
1980    Np = N3
1981    dx = (width/2.-bradii*bfrac)/(Np)
1982    dy = 0.
1983    for ip in range(Np):
1984        buoy[iip+ip,:] = [iy+dy*ip,ix+dx*ip]
1985    NNp = NNp + Np
1986    iip = NNp
1987
1988    # right lateral
1989    ix = width/2.
1990    iy = height
1991    dx = 0.
1992    dy = -height/(Np)
1993    for ip in range(Np):
1994        buoy[iip+ip,:] = [iy+dy*ip,ix+dx*ip]
1995    NNp = NNp + Np
1996    iip = NNp
1997
1998    # Base
1999    ix = width/2.
2000    iy = 0.
2001    Np = N - int(2*N/3) - 4*N3 - 1
2002    dx = -width/(Np)
2003    dy = 0.
2004    for ip in range(Np):
2005        buoy[iip+ip,:] = [iy+dy*ip,ix+dx*ip]
2006    NNp = NNp + Np
2007    iip = NNp
2008
2009    buoy[N-1,:] = buoy[0,:]
2010
2011    buoysecs = ['base']
2012    buoydic = {'base': [buoy, '-', 'k', 1.5]}
2013
2014    return buoy, buoysecs, buoydic
2015
2016def band_lighthouse(height=10., width=2., hlight=3., bands=3, N=300):
2017    """ Function to plot a lighthouse with spiral bands
2018      height: height of the tower (10., default)
2019      width: width of the tower (2., default)
2020      hlight: height of the light (3., default)
2021      bands: number of spiral bands (3, default)
2022      N: number of points (300, default)
2023    """
2024    fname = 'band_lighthouse'
2025
2026    lighthouse = np.ones((N,2), dtype=np.float)*gen.fillValueF
2027    lighthousesecs = []
2028    lighthousedic = {}
2029
2030    # base Tower
2031    Nsec = int(0.30*N/7)
2032    p1=np.array([0., width/2.])
2033    p2=np.array([0., -width/2.])
2034    iip = 0
2035    lighthouse[0:Nsec,:] = circ_sec(p1, p2, 3*width, pos='left', Nang=Nsec)
2036    iip = iip + Nsec
2037
2038    # left side
2039    ix=-width/2.
2040    iy=0.
2041    dx = 0.
2042    dy = height/(Nsec-1)
2043    for ip in range(Nsec):
2044        lighthouse[iip+ip,:] = [iy+dy*ip, ix+dx*ip]
2045    iip = iip + Nsec
2046
2047    # Top Tower
2048    p1=np.array([height, width/2.])
2049    p2=np.array([height, -width/2.])
2050    lighthouse[iip:iip+Nsec,:] = circ_sec(p1, p2, 3*width, pos='left', Nang=Nsec)
2051    iip = iip + Nsec
2052
2053    # right side
2054    ix=width/2.
2055    iy=height
2056    dx = 0.
2057    dy = -height/(Nsec-1)
2058    for ip in range(Nsec):
2059        lighthouse[iip+ip,:] = [iy+dy*ip, ix+dx*ip]
2060    iip = iip + Nsec + 1
2061
2062    Ntower = iip-1
2063    lighthousesecs.append('tower')
2064    lighthousedic['tower'] = [lighthouse[0:iip-1], '-', 'k', 1.5]
2065
2066    # Left light
2067    p1 = np.array([height, -width*0.8/2.])
2068    p2 = np.array([height+hlight, -width*0.8/2.])
2069    lighthouse[iip:iip+Nsec,:] = circ_sec(p1, p2, 3*hlight, Nang=Nsec)
2070    iip = iip + Nsec
2071   
2072    # Top Light
2073    p1=np.array([height+hlight, width*0.8/2.])
2074    p2=np.array([height+hlight, -width*0.8/2.])
2075    lighthouse[iip:iip+Nsec,:] = circ_sec(p1, p2, 3*width, pos='left', Nang=Nsec)
2076    iip = iip + Nsec + 1
2077
2078    # Right light
2079    p1 = np.array([height+hlight, width*0.8/2.])
2080    p2 = np.array([height, width*0.8/2.])
2081    lighthouse[iip:iip+Nsec,:] = circ_sec(p1, p2, 3*hlight, Nang=Nsec)
2082    iip = iip + Nsec
2083
2084    # Base Light
2085    p1=np.array([height, width*0.8/2.])
2086    p2=np.array([height, -width*0.8/2.])
2087    lighthouse[iip:iip+Nsec,:] = circ_sec(p1, p2, 3*width, pos='left', Nang=Nsec)
2088    iip = iip + Nsec + 1
2089    lighthousesecs.append('light')
2090    lighthousedic['light'] = [lighthouse[Ntower+1:iip-1], '-', '#EEEE00', 1.5]
2091
2092    # Spiral bands
2093    hb = height/(2.*bands)
2094    Nsec2 = (N - Nsec*8 - 3)/bands
2095    for ib in range(bands-1):
2096        iband = iip
2097        Nsec = Nsec2/4
2098        bandS = 'band' + str(ib).zfill(2)
2099        # hband
2100        ix = -width/2.
2101        iy = hb*ib*2
2102        dx = 0.
2103        dy = hb/(Nsec-1)
2104        for ip in range(Nsec):
2105            lighthouse[iip+ip,:] = [iy+dy*ip, ix+dx*ip]
2106        iip = iip + Nsec
2107        # uband
2108        p1 = np.array([hb*(ib*2+1), -width/2.])
2109        p2 = np.array([hb*(ib*2+2), width/2.])
2110        lighthouse[iip:iip+Nsec,:] = circ_sec(p1, p2, 3*width, pos='right', Nang=Nsec)
2111        iip = iip + Nsec
2112        # dband
2113        ix = width/2.
2114        iy = hb*(ib*2+2)
2115        dx = 0.
2116        dy = -hb/(Nsec-1)
2117        for ip in range(Nsec):
2118            lighthouse[iip+ip,:] = [iy+dy*ip, ix+dx*ip]
2119        iip = iip + Nsec
2120        # dband
2121        p1 = np.array([hb*(ib*2+1), width/2.])
2122        p2 = np.array([hb*ib*2, -width/2.])
2123        lighthouse[iip:iip+Nsec,:] = circ_sec(p1, p2, 3*width, pos='left', Nang=Nsec)
2124        iip = iip + Nsec + 1
2125        lighthousesecs.append(bandS)
2126        lighthousedic[bandS] = [lighthouse[iband:iip-1], '-', '#6408AA', 2.]
2127
2128    ib = bands-1
2129    Nsec3 = (N - iip - 1)
2130    Nsec = int(Nsec3/4)
2131    bandS = 'band' + str(ib).zfill(2)
2132    # hband
2133    iband = iip
2134    ix = -width/2.
2135    iy = hb*ib*2
2136    dx = 0.
2137    dy = hb/(Nsec-1)
2138    for ip in range(Nsec):
2139        lighthouse[iip+ip,:] = [iy+dy*ip, ix+dx*ip]
2140    iip = iip + Nsec
2141    # uband
2142    p1 = np.array([hb*(ib*2+1), -width/2.])
2143    p2 = np.array([hb*(ib*2+2), width/2.])
2144    lighthouse[iip:iip+Nsec,:] = circ_sec(p1, p2, 3*width, pos='right', Nang=Nsec)
2145    iip = iip + Nsec
2146    # dband
2147    ix = width/2.
2148    iy = hb*(2+ib*2)
2149    dx = 0.
2150    dy = -hb/(Nsec-1)
2151    for ip in range(Nsec):
2152        lighthouse[iip+ip,:] = [iy+dy*ip, ix+dx*ip]
2153    iip = iip + Nsec
2154    # dband
2155    Nsec = N - iip
2156    p1 = np.array([hb*(1+ib*2), width/2.])
2157    p2 = np.array([hb*ib*2, -width/2.])
2158    lighthouse[iip:iip+Nsec,:] = circ_sec(p1, p2, 3*width, pos='left', Nang=Nsec)       
2159    lighthousesecs.append(bandS)
2160    lighthousedic[bandS] = [lighthouse[iband:iip-1], '-', '#6408AA', 2.]
2161
2162    lighthouse = ma.masked_equal(lighthouse, gen.fillValueF)
2163
2164    return lighthouse, lighthousesecs, lighthousedic
2165
2166def north_buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, hsigns=0.7, N=300):
2167    """ Function to draw a North danger buoy using buoy1
2168      height: height of the prism (5., default)
2169      width: width of the prism (10., default)
2170      bradii: radii of the ball (1.75, default)
2171      bfrac: fraction of the ball above the prism (0.8, default)
2172      hisgns: height of the signs [as reg. triangle] as percentage of the height
2173        (0.7, default)
2174      N: total number of points of the buoy (300, default)
2175    """
2176    fname = 'north_buoy1'
2177
2178    buoy = np.ones((N,2), dtype=np.float)*gen.fillValueF
2179
2180    # buoy
2181    N2 = int(N/2)
2182    buoy1v, buoy1vsecs, buoy1vdic = buoy1(height=5., width=10., bradii=1.75,         \
2183      bfrac=0.8, N=N2)
2184    buoy[0:N2,:] = buoy1v
2185
2186    # signs
2187    N3 = N - N2 - 2
2188   
2189    bottsigns = 2.*bradii+height
2190    lsign = height*hsigns
2191    # up
2192    N32 = int(N3/2) 
2193    triu = p_angle_triangle(N=N32)
2194    trib = triu*lsign + [0.,-lsign/2.] 
2195
2196    buoy[N2+1:N2+1+N32,:] = trib + [bottsigns+2.1*lsign,0.]
2197
2198    # up
2199    N323 = N - N32 - N2 - 2
2200    trid = p_angle_triangle(N=N323)
2201    trib = trid*lsign + [0.,-lsign/2.] 
2202    buoy[N2+N32+2:N,:] = trib + [bottsigns+1.1*lsign,0.]
2203
2204    # painting it
2205    Height = np.max(buoy1v[:,0])
2206
2207    Ncut, halfdown = cut_ypolygon(buoy1v, yval=Height/2., keep='below')
2208    Ncut, halfup = cut_ypolygon(buoy1v, yval=Height/2., keep='above')
2209
2210    buoy = ma.masked_equal(buoy, gen.fillValueF)
2211
2212    buoysecs = ['buoy', 'sign1', 'sign2', 'halfk', 'halfy']
2213    buoydic = {'buoy': [buoy[0:N2,:],'-','k',1.5],                                   \
2214      'sign1': [buoy[N2+1:N2+N32+1,:],'-','k',1.5],                                  \
2215      'sign2': [buoy[N2+N32+2:N,:],'-','k',1.5], 'half1': [halfup, '-', 'k', 1.],    \
2216      'half2': [halfdown, '-', '#FFFF00', 1.]}
2217
2218    return buoy, buoysecs, buoydic
2219
2220def east_buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, hsigns=0.7, N=300):
2221    """ Function to draw a East danger buoy using buoy1
2222      height: height of the prism (5., default)
2223      width: width of the prism (10., default)
2224      bradii: radii of the ball (1.75, default)
2225      bfrac: fraction of the ball above the prism (0.8, default)
2226      hisgns: height of the signs [as reg. triangle] as percentage of the height
2227        (0.7, default)
2228      N: total number of points of the buoy (300, default)
2229    """
2230    fname = 'east_buoy1'
2231
2232    buoy = np.ones((N,2), dtype=np.float)*gen.fillValueF
2233
2234    # buoy
2235    N2 = int(N/2)
2236    buoy1v, buoy1vsecs, buoy1vdic = buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, N=N2)
2237    buoy[0:N2,:] = buoy1v
2238
2239    # signs
2240    N3 = N - N2 - 2
2241   
2242    bottsigns = 2.*bradii+height
2243    lsign = height*hsigns
2244    # up
2245    N32 = int(N3/2) 
2246    triu = p_angle_triangle(N=N32)
2247    trib = triu*lsign + [0.,-lsign/2.] 
2248
2249    buoy[N2+1:N2+1+N32,:] = trib + [bottsigns+2.1*lsign,0.]
2250
2251    # down
2252    N323 = N - N32 - N2 - 2
2253
2254    trid = p_angle_triangle(N=N323)
2255    trid = mirror_polygon(trid, 'x')
2256    trib = trid*lsign + [lsign,-lsign/2.] 
2257    buoy[N2+N32+2:N,:] = trib + [bottsigns+0.9*lsign,0.]
2258
2259    # painting it
2260    Height = np.max(buoy1v[:,0])
2261
2262    Ncut, halfdown = cut_ypolygon(buoy1v, yval=Height/3., keep='below')
2263    Ncut, halfbtw = cut_between_ypolygon(buoy1v, yval1=Height/3., yval2=Height*2./3.)
2264    Ncut, halfup = cut_ypolygon(buoy1v, yval=Height*2./3., keep='above')
2265
2266    buoy = ma.masked_equal(buoy, gen.fillValueF)
2267
2268    buoysecs = ['buoy', 'sign1', 'sign2', 'third1', 'third2', 'third3']
2269    buoydic = {'buoy': [buoy[0:N2,:],'-','k',1.5],                                   \
2270      'sign1': [buoy[N2+1:N2+N32+1,:],'-','k',1.5],                                  \
2271      'sign2': [buoy[N2+N32+2:N,:],'-','k',1.5],                                     \
2272      'third1': [halfup, '-', 'k', 1.], 'third2': [halfbtw, '-', '#FFFF00', 1.],     \
2273      'third3': [halfdown, '-', 'k', 1.]}
2274
2275    return buoy, buoysecs, buoydic
2276
2277def south_buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, hsigns=0.7, N=300):
2278    """ Function to draw a South danger buoy using buoy1
2279      height: height of the prism (5., default)
2280      width: width of the prism (10., default)
2281      bradii: radii of the ball (1.75, default)
2282      bfrac: fraction of the ball above the prism (0.8, default)
2283      hisgns: height of the signs [as reg. triangle] as percentage of the height
2284        (0.7, default)
2285      N: total number of points of the buoy (300, default)
2286    """
2287    fname = 'south_buoy1'
2288
2289    buoy = np.ones((N,2), dtype=np.float)*gen.fillValueF
2290
2291    # buoy
2292    N2 = int(N/2)
2293    buoy1v, buoy1vsecs, buoy1vdic = buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, N=N2)
2294    buoy[0:N2,:] = buoy1v
2295
2296    # signs
2297    N3 = N - N2 - 2
2298   
2299    bottsigns = 2.*bradii+height
2300    lsign = height*hsigns
2301    # up
2302    N32 = int(N3/2) 
2303    trid = p_angle_triangle(N=N32)
2304    trid = mirror_polygon(trid, 'x')
2305    trib = trid*lsign + [0.,-lsign/2.] 
2306
2307    buoy[N2+1:N2+1+N32,:] = trib + [bottsigns+2.9*lsign,0.]
2308
2309    # down
2310    N323 = N - N32 - N2 - 2
2311    trid = p_angle_triangle(N=N323)
2312    trid = mirror_polygon(trid, 'x')
2313    trib = trid*lsign + [lsign,-lsign/2.] 
2314    buoy[N2+N32+2:N,:] = trib + [bottsigns+0.9*lsign,0.]
2315
2316    # painting it
2317    Height = np.max(buoy1v[:,0])
2318
2319    Ncut, halfdown = cut_ypolygon(buoy1v, yval=Height/2., keep='below')
2320    Ncut, halfup = cut_ypolygon(buoy1v, yval=Height/2., keep='above')
2321
2322    buoy = ma.masked_equal(buoy, gen.fillValueF)
2323
2324    buoysecs = ['buoy', 'sign1', 'sign2', 'half1', 'half2']
2325    buoydic = {'buoy': [buoy[0:N2,:],'-','k',1.5],                                   \
2326      'sign1': [buoy[N2+1:N2+N32+1,:],'-','k',1.5],                                  \
2327      'sign2': [buoy[N2+N32+2:N,:],'-','k',1.5], 'half1': [halfup, '-', '#FFFF00', 1.], \
2328      'half2': [halfdown, '-', 'k', 1.]}
2329
2330    return buoy, buoysecs, buoydic
2331
2332def west_buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, hsigns=0.7, N=300):
2333    """ Function to draw a West danger buoy using buoy1
2334      height: height of the prism (5., default)
2335      width: width of the prism (10., default)
2336      bradii: radii of the ball (1.75, default)
2337      bfrac: fraction of the ball above the prism (0.8, default)
2338      hisgns: height of the signs [as reg. triangle] as percentage of the height
2339        (0.7, default)
2340      N: total number of points of the buoy (300, default)
2341    """
2342    fname = 'east_buoy1'
2343
2344    buoy = np.ones((N,2), dtype=np.float)*gen.fillValueF
2345
2346    # buoy
2347    N2 = int(N/2)
2348    buoy1v, buoy1vsecs, buoy1vdic = buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, N=N2)
2349    buoy[0:N2,:] = buoy1v
2350
2351    # signs
2352    N3 = N - N2 - 2
2353   
2354    bottsigns = 2.*bradii+height
2355    lsign = height*hsigns
2356
2357    # down
2358    N32 = int(N3/2) 
2359    trid = p_angle_triangle(N=N32)
2360    trid = mirror_polygon(trid, 'x')
2361    trib = trid*lsign + [lsign,-lsign/2.] 
2362    buoy[N2+1:N2+1+N32,:] = trib + [bottsigns+1.9*lsign,0.]
2363
2364    # up
2365    N323 = N - N32 - N2 - 2
2366    triu = p_angle_triangle(N=N323)
2367    trib = triu*lsign + [0.,-lsign/2.] 
2368
2369    buoy[N2+N323+2:N,:] = trib + [bottsigns+1.*lsign,0.]
2370
2371    # painting it
2372    Height = np.max(buoy1v[:,0])
2373
2374    Ncut, halfdown = cut_ypolygon(buoy1v, yval=Height/3., keep='below')
2375    Ncut, halfbtw1 = cut_between_ypolygon(buoy1v, yval1=Height/3., yval2=Height*2./3.)
2376    Ncut, halfup = cut_ypolygon(buoy1v, yval=Height*2./3., keep='above')
2377
2378    buoy = ma.masked_equal(buoy, gen.fillValueF)
2379
2380    buoysecs = ['buoy', 'sign1', 'sign2', 'third1', 'third2', 'third3']
2381    buoydic = {'buoy': [buoy[0:N2,:],'-','k',1.5],                                   \
2382      'third1': [halfdown, '-', '#FFFF00', 1.], 'third2': [halfbtw1, '-', 'k', 1.],  \
2383      'third3': [halfup, '-', '#FFFF00', 1.],                                        \
2384      'sign1': [buoy[N2+1:N2+N32+1,:],'-','k',1.5],                                  \
2385      'sign2': [buoy[N2+N32+2:N,:],'-','k',1.5]}
2386
2387    return buoy, buoysecs, buoydic
2388
2389def safewater_buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, hsigns=0.3, N=300):
2390    """ Function to draw a safe water mark buoy using buoy1
2391      height: height of the prism (5., default)
2392      width: width of the prism (10., default)
2393      bradii: radii of the ball (1.75, default)
2394      bfrac: fraction of the ball above the prism (0.8, default)
2395      hisgns: height of the signs [as reg. triangle] as percentage of the height
2396        (0.3, default)
2397      N: total number of points of the buoy (300, default)
2398    """
2399    fname = 'safewater_buoy1'
2400
2401    buoy = np.ones((N,2), dtype=np.float)*gen.fillValueF
2402
2403    # buoy
2404    N2 = int(N/2)
2405    buoy1v, buoy1vsecs, buoy1vdic = buoy1(height=5., width=10., bradii=1.75,         \
2406      bfrac=0.8, N=N2)
2407    buoy[0:N2,:] = buoy1v
2408
2409    # signs
2410    N3 = N - N2 - 1
2411    lsign = height*hsigns
2412   
2413    Height = np.max(buoy1v[:,0])
2414    sign = p_circle(lsign, N3)
2415    buoy[N2+1:N2+2+N3,:] = sign + [Height+1.2*lsign,0.]
2416
2417    # painting it
2418    ix = -width/2.
2419    Ncut, quarter1 = cut_xpolygon(buoy1v, xval=ix+width/4., keep='left')
2420    Ncut, quarter2 = cut_between_xpolygon(buoy1v, xval1=ix+width/4., xval2=ix+width/2.)
2421    Ncut, quarter3 = cut_between_xpolygon(buoy1v, xval1=ix+width/2., xval2=ix+3.*width/4.)
2422    Ncut, quarter4 = cut_xpolygon(buoy1v, xval=ix+3.*width/4., keep='right')
2423
2424    buoy = ma.masked_equal(buoy, gen.fillValueF)
2425
2426    buoysecs = ['buoy', 'sign', 'quarter1', 'quarter2', 'quarter3', 'quarter4']
2427    buoydic = {'buoy': [buoy[0:N2,:],'-','k',1.5],                                   \
2428      'sign': [buoy[N2+1:N2+N3+1,:],'-','r',1.5], 'quarter1': [quarter1,'-','r',1.], \
2429      'quarter2': [quarter2,'-','#FFFFFF',1.], 'quarter3': [quarter3,'-','r',1.],    \
2430      'quarter4': [quarter4,'-','#FFFFFF',1.]}
2431
2432    return buoy, buoysecs, buoydic
2433
2434def red_buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, hsigns=0.3, N=300):
2435    """ Function to draw a red mark buoy using buoy1
2436      height: height of the prism (5., default)
2437      width: width of the prism (10., default)
2438      bradii: radii of the ball (1.75, default)
2439      bfrac: fraction of the ball above the prism (0.8, default)
2440      hisgns: height of the signs [as reg. triangle] as percentage of the height
2441        (0.3, default)
2442      N: total number of points of the buoy (300, default)
2443    """
2444    fname = 'red_buoy1'
2445
2446    buoy = np.ones((N,2), dtype=np.float)*gen.fillValueF
2447
2448    # buoy
2449    N2 = int(N/2)
2450    buoy1v, buoy1vsecs, buoy1vdic = buoy1(height=5., width=10., bradii=1.75,         \
2451      bfrac=0.8, N=N2)
2452    buoy[0:N2,:] = buoy1v
2453
2454    # signs
2455    N3 = N - N2 - 1
2456    lsign = height*hsigns*2.
2457   
2458    Height = np.max(buoy1v[:,0])
2459    triu = p_angle_triangle(N=N3)
2460    sign = triu*lsign
2461    buoy[N2+1:N2+2+N3,:] = sign + [Height+0.2*lsign,-lsign/2.]
2462
2463    # painting it
2464    buoy = ma.masked_equal(buoy, gen.fillValueF)
2465
2466    buoysecs = ['buoy', 'sign']
2467    buoydic = {'buoy': [buoy[0:N2,:],'-','r',1.5],                                   \
2468      'sign': [buoy[N2+1:N2+N3+1,:],'-','r',1.5]}
2469
2470    return buoy, buoysecs, buoydic
2471
2472def green_buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, hsigns=0.3, N=300):
2473    """ Function to draw a green mark buoy using buoy1
2474      height: height of the prism (5., default)
2475      width: width of the prism (10., default)
2476      bradii: radii of the ball (1.75, default)
2477      bfrac: fraction of the ball above the prism (0.8, default)
2478      hisgns: height of the signs [as reg. triangle] as percentage of the height
2479        (0.3, default)
2480      N: total number of points of the buoy (300, default)
2481    """
2482    fname = 'green_buoy1'
2483
2484    buoy = np.ones((N,2), dtype=np.float)*gen.fillValueF
2485
2486    # buoy
2487    N2 = int(N/2)
2488    buoy1v, buoy1vsecs, buoy1vdic = buoy1(height=5., width=10., bradii=1.75,         \
2489      bfrac=0.8, N=N2)
2490    buoy[0:N2,:] = buoy1v
2491
2492    # signs
2493    N3 = N - N2 - 1
2494    lsign = height*hsigns*2.
2495   
2496    Height = np.max(buoy1v[:,0])
2497    sign = p_prism(lsign, lsign*2, N=N3)
2498    buoy[N2+1:N2+2+N3,:] = sign + [Height+1.2*lsign,0.]
2499
2500    # painting it
2501    buoy = ma.masked_equal(buoy, gen.fillValueF)
2502
2503    buoysecs = ['buoy', 'sign']
2504    buoydic = {'buoy': [buoy[0:N2,:],'-','g',1.5],                                   \
2505      'sign': [buoy[N2+1:N2+N3+1,:],'-','g',1.5]}
2506
2507    return buoy, buoysecs, buoydic
2508
2509def prefchannelportA_buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, hsigns=0.3, \
2510  N=300):
2511    """ Function to draw a preferred channel port system A buoy using buoy1
2512      height: height of the prism (5., default)
2513      width: width of the prism (10., default)
2514      bradii: radii of the ball (1.75, default)
2515      bfrac: fraction of the ball above the prism (0.8, default)
2516      hisgns: height of the signs [as reg. triangle] as percentage of the height
2517        (0.3, default)
2518      N: total number of points of the buoy (300, default)
2519    """
2520    fname = 'prefchannelportA_buoy1'
2521
2522    buoy = np.ones((N,2), dtype=np.float)*gen.fillValueF
2523
2524    # buoy
2525    N2 = int(N/2)
2526    buoy1v, buoy1vsecs, buoy1vdic = buoy1(height=5., width=10., bradii=1.75,         \
2527      bfrac=0.8, N=N2)
2528    buoy[0:N2,:] = buoy1v
2529
2530    # signs
2531    N3 = N - N2 - 1
2532    lsign = height*hsigns*2.
2533   
2534    Height = np.max(buoy1v[:,0])
2535    triu = p_angle_triangle(N=N3)
2536    sign = triu*lsign
2537    buoy[N2+1:N2+2+N3,:] = sign + [Height+0.2*lsign,-lsign/2.]
2538
2539    # painting it
2540    Ncut, third1 = cut_ypolygon(buoy1v, yval=Height/3., keep='below')
2541    Ncut, third2 = cut_between_ypolygon(buoy1v, yval1=Height/3., yval2=Height*2./3.)
2542    Ncut, third3 = cut_ypolygon(buoy1v, yval=Height*2./3., keep='above')
2543
2544    buoy = ma.masked_equal(buoy, gen.fillValueF)
2545
2546    buoysecs = ['buoy', 'sign', 'third1', 'third2', 'third3']
2547    buoydic = {'buoy': [buoy[0:N2,:],'-','r',1.5],                                   \
2548      'sign': [buoy[N2+1:N2+N3+1,:],'-','g',1.5], 'third1': [third1,'-','g',1.5],    \
2549      'third2': [third2,'-','r',1.5], 'third3': [third3,'-','g',1.5]}
2550
2551    return buoy, buoysecs, buoydic
2552
2553def prefchannelportB_buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, hsigns=0.3, \
2554  N=300):
2555    """ Function to draw a preferred channel port system B buoy using buoy1
2556      height: height of the prism (5., default)
2557      width: width of the prism (10., default)
2558      bradii: radii of the ball (1.75, default)
2559      bfrac: fraction of the ball above the prism (0.8, default)
2560      hisgns: height of the signs [as reg. triangle] as percentage of the height
2561        (0.3, default)
2562      N: total number of points of the buoy (300, default)
2563    """
2564    fname = 'prefchannelportB_buoy1'
2565
2566    buoy = np.ones((N,2), dtype=np.float)*gen.fillValueF
2567
2568    # buoy
2569    N2 = int(N/2)
2570    buoy1v, buoy1vsecs, buoy1vdic = buoy1(height=5., width=10., bradii=1.75,         \
2571      bfrac=0.8, N=N2)
2572    buoy[0:N2,:] = buoy1v
2573
2574    # signs
2575    N3 = N - N2 - 1
2576    lsign = height*hsigns*2.
2577   
2578    Height = np.max(buoy1v[:,0])
2579    triu = p_angle_triangle(N=N3)
2580    sign = triu*lsign
2581    buoy[N2+1:N2+2+N3,:] = sign + [Height+0.2*lsign,-lsign/2.]
2582
2583    # painting it
2584    Ncut, third1 = cut_ypolygon(buoy1v, yval=Height/3., keep='below')
2585    Ncut, third2 = cut_between_ypolygon(buoy1v, yval1=Height/3., yval2=Height*2./3.)
2586    Ncut, third3 = cut_ypolygon(buoy1v, yval=Height*2./3., keep='above')
2587
2588    buoy = ma.masked_equal(buoy, gen.fillValueF)
2589
2590    buoysecs = ['buoy', 'sign', 'third1', 'third2', 'third3']
2591    buoydic = {'buoy': [buoy[0:N2,:],'-','r',1.5],                                   \
2592      'sign': [buoy[N2+1:N2+N3+1,:],'-','r',1.5], 'third1': [third1,'-','r',1.5],    \
2593      'third2': [third2,'-','g',1.5], 'third3': [third3,'-','r',1.5]}
2594
2595    return buoy, buoysecs, buoydic
2596
2597def prefchannelstarboardA_buoy1(height=5., width=10., bradii=1.75, bfrac=0.8,        \
2598  hsigns=0.3, N=300):
2599    """ Function to draw a preferred channel starboard system A buoy using buoy1
2600      height: height of the prism (5., default)
2601      width: width of the prism (10., default)
2602      bradii: radii of the ball (1.75, default)
2603      bfrac: fraction of the ball above the prism (0.8, default)
2604      hisgns: height of the signs [as reg. triangle] as percentage of the height
2605        (0.3, default)
2606      N: total number of points of the buoy (300, default)
2607    """
2608    fname = 'prefchannelstarboardA_buoy1'
2609
2610    buoy = np.ones((N,2), dtype=np.float)*gen.fillValueF
2611
2612    # buoy
2613    N2 = int(N/2)
2614    buoy1v, buoy1vsecs, buoy1vdic = buoy1(height=5., width=10., bradii=1.75,         \
2615      bfrac=0.8, N=N2)
2616    buoy[0:N2,:] = buoy1v
2617
2618    # signs
2619    N3 = N - N2 - 1
2620    lsign = height*hsigns*2.
2621   
2622    Height = np.max(buoy1v[:,0])
2623    sign = p_prism(lsign, lsign*2, N=N3)
2624    buoy[N2+1:N2+2+N3,:] = sign + [Height+1.2*lsign,0.]
2625
2626    # painting it
2627    # painting it
2628    Ncut, third1 = cut_ypolygon(buoy1v, yval=Height/3., keep='below')
2629    Ncut, third2 = cut_between_ypolygon(buoy1v, yval1=Height/3., yval2=Height*2./3.)
2630    Ncut, third3 = cut_ypolygon(buoy1v, yval=Height*2./3., keep='above')
2631
2632    buoy = ma.masked_equal(buoy, gen.fillValueF)
2633
2634    buoysecs = ['buoy', 'sign']
2635    buoydic = {'buoy': [buoy[0:N2,:],'-','g',1.5],                                   \
2636      'sign': [buoy[N2+1:N2+N3+1,:],'-','r',1.5], 'third1': [third1,'-','r',1.5],    \
2637      'third2': [third2,'-','g',1.5], 'third3': [third3,'-','r',1.5]}
2638
2639    return buoy, buoysecs, buoydic
2640
2641def prefchannelstarboardB_buoy1(height=5., width=10., bradii=1.75, bfrac=0.8,        \
2642  hsigns=0.3, N=300):
2643    """ Function to draw a preferred channel starboard system B buoy using buoy1
2644      height: height of the prism (5., default)
2645      width: width of the prism (10., default)
2646      bradii: radii of the ball (1.75, default)
2647      bfrac: fraction of the ball above the prism (0.8, default)
2648      hisgns: height of the signs [as reg. triangle] as percentage of the height
2649        (0.3, default)
2650      N: total number of points of the buoy (300, default)
2651    """
2652    fname = 'prefchannelstarboardB_buoy1'
2653
2654    buoy = np.ones((N,2), dtype=np.float)*gen.fillValueF
2655
2656    # buoy
2657    N2 = int(N/2)
2658    buoy1v, buoy1vsecs, buoy1vdic = buoy1(height=5., width=10., bradii=1.75,         \
2659      bfrac=0.8, N=N2)
2660    buoy[0:N2,:] = buoy1v
2661
2662    # signs
2663    N3 = N - N2 - 1
2664    lsign = height*hsigns*2.
2665   
2666    Height = np.max(buoy1v[:,0])
2667    sign = p_prism(lsign, lsign*2, N=N3)
2668    buoy[N2+1:N2+2+N3,:] = sign + [Height+1.2*lsign,0.]
2669
2670    # painting it
2671    # painting it
2672    Ncut, third1 = cut_ypolygon(buoy1v, yval=Height/3., keep='below')
2673    Ncut, third2 = cut_between_ypolygon(buoy1v, yval1=Height/3., yval2=Height*2./3.)
2674    Ncut, third3 = cut_ypolygon(buoy1v, yval=Height*2./3., keep='above')
2675
2676    buoy = ma.masked_equal(buoy, gen.fillValueF)
2677
2678    buoysecs = ['buoy', 'sign']
2679    buoydic = {'buoy': [buoy[0:N2,:],'-','g',1.5],                                   \
2680      'sign': [buoy[N2+1:N2+N3+1,:],'-','g',1.5], 'third1': [third1,'-','g',1.5],    \
2681      'third2': [third2,'-','r',1.5], 'third3': [third3,'-','g',1.5]}
2682
2683    return buoy, buoysecs, buoydic
2684
2685def isolateddanger_buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, hsigns=0.5,   \
2686  N=300):
2687    """ Function to draw an isolated danger buoy using buoy1
2688      height: height of the prism (5., default)
2689      width: width of the prism (10., default)
2690      bradii: radii of the ball (1.75, default)
2691      bfrac: fraction of the ball above the prism (0.8, default)
2692      hisgns: height of the signs [as reg. triangle] as percentage of the height
2693        (0.5, default)
2694      N: total number of points of the buoy (300, default)
2695    """
2696    fname = 'isolateddanger_buoy1'
2697
2698    buoy = np.ones((N,2), dtype=np.float)*gen.fillValueF
2699
2700    # buoy
2701    N2 = int(N/2)
2702    buoy1v, buoy1vsecs, buoy1vdic = buoy1(height=5., width=10., bradii=1.75,         \
2703      bfrac=0.8, N=N2)
2704    buoy[0:N2,:] = buoy1v
2705
2706    # signs
2707    N3 = N - N2 - 2
2708   
2709    bottsigns = 2.*bradii+height
2710    lsign = height*hsigns
2711    # up
2712    N32 = int(N3/2) 
2713    circle = p_circle(lsign/2., N=N32)
2714    trib = circle + [0.,0.] 
2715
2716    buoy[N2+1:N2+1+N32,:] = trib + [bottsigns+3.2*lsign,0.]
2717
2718    # up
2719    N323 = N - N32 - N2 - 2
2720    trid = p_circle(lsign/2., N=N32)
2721    trib = circle + [0.,0.] 
2722    buoy[N2+N32+2:N,:] = trib + [bottsigns+2.*lsign,0.]
2723
2724    # painting it
2725    Height = np.max(buoy1v[:,0])
2726
2727    Ncut, third1 = cut_ypolygon(buoy1v, yval=Height/3., keep='below')
2728    Ncut, third2 = cut_between_ypolygon(buoy1v, yval1=Height/3., yval2=Height*2./3.)
2729    Ncut, third3 = cut_ypolygon(buoy1v, yval=Height*2./3., keep='above')
2730
2731    buoy = ma.masked_equal(buoy, gen.fillValueF)
2732
2733    buoysecs = ['buoy', 'sign1', 'sign2', 'halfk', 'halfy']
2734    buoydic = {'buoy': [buoy[0:N2,:],'-','k',1.5],                                   \
2735      'sign1': [buoy[N2+1:N2+N32+1,:],'-','k',1.5],                                  \
2736      'sign2': [buoy[N2+N32+2:N,:],'-','k',1.5], 'third1': [third1, '-', 'k', 1.],   \
2737      'third2': [third2, '-', 'r', 1.], 'third3': [third3, '-', 'k', 1.]}
2738
2739    return buoy, buoysecs, buoydic
2740
2741def special_buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, hsigns=0.5, N=300):
2742    """ Function to draw an special mark buoy using buoy1
2743      height: height of the prism (5., default)
2744      width: width of the prism (10., default)
2745      bradii: radii of the ball (1.75, default)
2746      bfrac: fraction of the ball above the prism (0.8, default)
2747      hisgns: height of the signs [as reg. triangle] as percentage of the height
2748        (0.5, default)
2749      N: total number of points of the buoy (300, default)
2750    """
2751    fname = 'special_buoy1'
2752
2753    buoy = np.ones((N,2), dtype=np.float)*gen.fillValueF
2754
2755    # buoy
2756    N2 = int(N/2)
2757    buoy1v, buoy1vsecs, buoy1vdic = buoy1(height=5., width=10., bradii=1.75,         \
2758      bfrac=0.8, N=N2)
2759    buoy[0:N2,:] = buoy1v
2760
2761    Height = np.max(buoy1v[:,0])
2762
2763    # sign
2764    N3 = N - N2 - 1
2765   
2766    bottsigns = 2.*bradii+height
2767    lsign = height*hsigns
2768    # up
2769    cross, crosssecs, crossdic = p_cross_width(lsign, width=0.3*lsign, Narms=2, N=N3)
2770    cross = rotate_polygon_2D(cross, 40.05)
2771    buoy[N2+1:N,:] = cross + [Height+1.1*lsign,0.]
2772
2773    # painting it
2774    buoy = ma.masked_equal(buoy, gen.fillValueF)
2775
2776    buoysecs = ['buoy', 'sign']
2777    buoydic = {'buoy': [buoy[0:N2,:],'-','#FFFF00',1.5],                             \
2778      'sign': [buoy[N2+1:N,:],'-','#FFFF00',1.5]}
2779
2780    return buoy, buoysecs, buoydic
2781
2782def emergency_buoy1(height=5., width=10., bradii=1.75, bfrac=0.8, hsigns=0.5, N=300):
2783    """ Function to draw an eergency mark buoy using buoy1
2784      height: height of the prism (5., default)
2785      width: width of the prism (10., default)
2786      bradii: radii of the ball (1.75, default)
2787      bfrac: fraction of the ball above the prism (0.8, default)
2788      hisgns: height of the signs [as reg. triangle] as percentage of the height
2789        (0.5, default)
2790      N: total number of points of the buoy (300, default)
2791    """
2792    fname = 'emergency_buoy1'
2793
2794    buoy = np.ones((N,2), dtype=np.float)*gen.fillValueF
2795
2796    # buoy
2797    N2 = int(N/2)
2798    buoy1v, buoy1vsecs, buoy1vdic = buoy1(height=5., width=10., bradii=1.75,         \
2799      bfrac=0.8, N=N2)
2800    buoy[0:N2,:] = buoy1v
2801
2802    Height = np.max(buoy1v[:,0])
2803
2804    # sign
2805    N3 = N - N2 - 1
2806   
2807    bottsigns = 2.*bradii+height
2808    lsign = height*hsigns
2809    # up
2810    cross, crosssecs, crossdic = p_cross_width(lsign, width=0.3*lsign, Narms=2, N=N3)
2811    buoy[N2+1:N,:] = cross + [Height+1.1*lsign,0.]
2812
2813    # painting it
2814    ix = -width/2.
2815    Ncut, fifth1 = cut_xpolygon(buoy1v, xval=ix+width/5., keep='left')
2816    Ncut, fifth2 = cut_between_xpolygon(buoy1v,xval1=ix+width/5.,xval2=ix+width*2./5.)
2817    Ncut, fifth3 = cut_between_xpolygon(buoy1v,xval1=ix+width*2./5.,xval2=ix+width*3./5.)
2818    Ncut, fifth4 = cut_between_xpolygon(buoy1v,xval1=ix+width*3./5.,xval2=ix+width*4./5.)
2819    Ncut, fifth5 = cut_xpolygon(buoy1v, xval=ix+width*4./5., keep='right')
2820
2821    buoy = ma.masked_equal(buoy, gen.fillValueF)
2822
2823    buoysecs = ['buoy', 'sign', 'fifth1', 'fifth2', 'fifth3', 'fifth4', 'fifth5']
2824    buoydic = {'buoy': [buoy[0:N2,:],'-','#FFFF00',1.5],                             \
2825      'sign': [buoy[N2+1:N,:],'-','#FFFF00',1.5],'fifth1':[fifth1,'-','#FFFF00',1.5],\
2826      'fifth2': [fifth2,'-','#FFFF00',1.5],'fifth3': [fifth3,'-','#0000FF',1.5],     \
2827      'fifth4': [fifth4,'-','#FFFF00',1.5],'fifth5': [fifth5,'-','#0000FF',1.5]}
2828
2829    return buoy, buoysecs, buoydic
2830
2831####### ####### ##### #### ### ## #
2832# Plotting
2833
2834def plot_sphere(iazm=-60., iele=30., dist=10., Npts=100, radii=10,                   \
2835  drwsfc=[True,True], colsfc=['#AAAAAA','#646464'],                                  \
2836  drwxline = True, linex=[':','b',2.], drwyline = True, liney=[':','r',2.],          \
2837  drwzline = True, linez=['-.','g',2.], drwxcline=[True,True],                       \
2838  linexc=[['-','#646400',1.],['--','#646400',1.]],                                   \
2839  drwequator=[True,True], lineeq=[['-','#AA00AA',1.],['--','#AA00AA',1.]],           \
2840  drwgreeenwhich=[True,True], linegw=[['-','k',1.],['--','k',1.]]):
2841    """ Function to plot an sphere and determine which standard lines will be also
2842        drawn
2843      iazm: azimut of the camera form the sphere
2844      iele: elevation of the camera form the sphere
2845      dist: distance of the camera form the sphere
2846      Npts: Resolution for the sphere
2847      radii: radius of the sphere
2848      drwsfc: whether 'up' and 'down' portions of the sphere should be drawn
2849      colsfc: colors of the surface of the sphere portions ['up', 'down']
2850      drwxline: whether x-axis line should be drawn
2851      linex: properties of the x-axis line ['type', 'color', 'wdith']
2852      drwyline: whether y-axis line should be drawn
2853      liney: properties of the y-axis line ['type', 'color', 'wdith']
2854      drwzline: whether z-axis line should be drawn
2855      linez: properties of the z-axis line ['type', 'color', 'wdith']
2856      drwequator: whether 'front' and 'back' portions of the Equator should be drawn
2857      lineeq: properties of the lines 'front' and 'back' of the Equator
2858      drwgreeenwhich: whether 'front', 'back' portions of Greenqhich should be drawn
2859      linegw: properties of the lines 'front' and 'back' Greenwhich
2860      drwxcline: whether 'front', 'back' 90 line (lon=90., lon=270.) should be drawn
2861      linexc: properties of the lines 'front' and 'back' for the 90 line
2862    """
2863    fname = 'plot_sphere'
2864
2865    iazmrad = iazm*np.pi/180.
2866    ielerad = iele*np.pi/180.
2867
2868    # 3D surface Sphere
2869    sfcsphereu, sfcsphered = surface_sphere(radii,Npts)
2870   
2871    # greenwhich
2872    if iazmrad > np.pi/2. and iazmrad < 3.*np.pi/2.:
2873        ia=np.pi-ielerad
2874    else:
2875        ia=0.-ielerad
2876    ea=ia+np.pi
2877    da = (ea-ia)/(Npts-1)
2878    beta = np.arange(ia,ea+da,da)[0:Npts]
2879    alpha = np.zeros((Npts), dtype=np.float)
2880    greenwhichc = spheric_line(radii,alpha,beta)
2881    ia=ea+0.
2882    ea=ia+np.pi
2883    da = (ea-ia)/(Npts-1)
2884    beta = np.arange(ia,ea+da,da)[0:Npts]
2885    greenwhichd = spheric_line(radii,alpha,beta)
2886
2887    # Equator
2888    ia=np.pi-iazmrad/2.
2889    ea=ia+np.pi
2890    da = (ea-ia)/(Npts-1)
2891    alpha = np.arange(ia,ea+da,da)[0:Npts]
2892    beta = np.zeros((Npts), dtype=np.float)
2893    equatorc = spheric_line(radii,alpha,beta)
2894    ia=ea+0.
2895    ea=ia+np.pi
2896    da = (ea-ia)/(Npts-1)
2897    alpha = np.arange(ia,ea+da,da)[0:Npts]
2898    equatord = spheric_line(radii,alpha,beta)
2899
2900    # 90 line
2901    if iazmrad > np.pi and iazmrad < 2.*np.pi:
2902        ia=3.*np.pi/2. + ielerad
2903    else:
2904        ia=np.pi/2. - ielerad
2905    if ielerad < 0.:
2906        ia = ia + np.pi
2907    ea=ia+np.pi
2908    da = (ea-ia)/(Npts-1)
2909    beta = np.arange(ia,ea+da,da)[0:Npts]
2910    alpha = np.ones((Npts), dtype=np.float)*np.pi/2.
2911    xclinec = spheric_line(radii,alpha,beta)
2912    ia=ea+0.
2913    ea=ia+np.pi
2914    da = (ea-ia)/(Npts-1)
2915    beta = np.arange(ia,ea+da,da)[0:Npts]
2916    xclined = spheric_line(radii,alpha,beta)
2917
2918    # x line
2919    xline = np.zeros((2,3), dtype=np.float)
2920    xline[0,:] = position_sphere(radii, 0., 0.)
2921    xline[1,:] = position_sphere(radii, np.pi, 0.)
2922
2923    # y line
2924    yline = np.zeros((2,3), dtype=np.float)
2925    yline[0,:] = position_sphere(radii, np.pi/2., 0.)
2926    yline[1,:] = position_sphere(radii, 3*np.pi/2., 0.)
2927
2928    # z line
2929    zline = np.zeros((2,3), dtype=np.float)
2930    zline[0,:] = position_sphere(radii, 0., np.pi/2.)
2931    zline[1,:] = position_sphere(radii, 0., -np.pi/2.)
2932
2933    fig = plt.figure()
2934    ax = fig.gca(projection='3d')
2935
2936    # Sphere surface
2937    if drwsfc[0]:
2938        ax.plot_surface(sfcsphereu[0,:,:], sfcsphereu[1,:,:], sfcsphereu[2,:,:],     \
2939          color=colsfc[0])
2940    if drwsfc[1]:
2941        ax.plot_surface(sfcsphered[0,:,:], sfcsphered[1,:,:], sfcsphered[2,:,:],     \
2942          color=colsfc[1])
2943
2944    # greenwhich
2945    linev = linegw[0]
2946    if drwgreeenwhich[0]:
2947        ax.plot(greenwhichc[:,0], greenwhichc[:,1], greenwhichc[:,2], linev[0],      \
2948          color=linev[1], linewidth=linev[2],  label='Greenwich')
2949    linev = linegw[1]
2950    if drwgreeenwhich[1]:
2951        ax.plot(greenwhichd[:,0], greenwhichd[:,1], greenwhichd[:,2], linev[0],      \
2952          color=linev[1], linewidth=linev[2])
2953
2954    # Equator
2955    linev = lineeq[0]
2956    if drwequator[0]:
2957        ax.plot(equatorc[:,0], equatorc[:,1], equatorc[:,2], linev[0],               \
2958          color=linev[1], linewidth=linev[2], label='Equator')
2959    linev = lineeq[1]
2960    if drwequator[1]:
2961        ax.plot(equatord[:,0], equatord[:,1], equatord[:,2], linev[0],               \
2962          color=linev[1], linewidth=linev[2])
2963
2964    # 90line
2965    linev = linexc[0]
2966    if drwxcline[0]:
2967        ax.plot(xclinec[:,0], xclinec[:,1], xclinec[:,2], linev[0], color=linev[1],  \
2968          linewidth=linev[2], label='90-line')
2969    linev = linexc[1]
2970    if drwxcline[1]:
2971        ax.plot(xclined[:,0], xclined[:,1], xclined[:,2], linev[0], color=linev[1],  \
2972          linewidth=linev[2])
2973
2974    # x line
2975    linev = linex
2976    if drwxline:
2977        ax.plot([xline[0,0],xline[1,0]], [xline[0,1],xline[1,1]],                    \
2978          [xline[0,2],xline[1,2]], linev[0], color=linev[1], linewidth=linev[2],  label='xline')
2979
2980    # y line
2981    linev = liney
2982    if drwyline:
2983        ax.plot([yline[0,0],yline[1,0]], [yline[0,1],yline[1,1]],                    \
2984          [yline[0,2],yline[1,2]], linev[0], color=linev[1], linewidth=linev[2],  label='yline')
2985
2986    # z line
2987    linev = linez
2988    if drwzline:
2989        ax.plot([zline[0,0],zline[1,0]], [zline[0,1],zline[1,1]],                    \
2990          [zline[0,2],zline[1,2]], linev[0], color=linev[1], linewidth=linev[2],  label='zline')
2991
2992    plt.legend()
2993
2994    return fig, ax
2995
2996def paint_filled(objdic, fillsecs):
2997    """ Function to draw an object filling given sections
2998      objdic: dictionary of the object
2999      filesecs: list of sections to be filled
3000    """
3001    fname = 'paint_filled'
3002
3003    Nsecs = len(fillsecs)
3004
3005    for secn in fillsecs:
3006        secvals=objdic[secn]
3007        pvals = secvals[0]
3008        plt.fill(pvals[:,1], pvals[:,0], color=secvals[2])
3009
3010    return
3011
Note: See TracBrowser for help on using the repository browser.