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

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

First working version of `cut_xpolygon' for multiple cuts

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