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

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

Adding:

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