Example #1
0
class Tl(object):
    """The Line object allows the manipulation of line type, width, color index,
    view port, world coordinates, and (x,y) points.

    This class is used to define an line table entry used in VCS, or it
    can be used to change some or all of the line attributes in an
    existing line table entry.

    .. describe:: Useful Functions:

        .. code-block:: python

            >>> a=vcs.init() # VCS Canvas Constructor
            >>> a.show('line') # Show predefined line objects
            *******************Line Names List**********************
            ...
            *******************End Line Names List**********************
            >>> a.getline('red').list() # show properties of 'red' line
             ---------- ... ----------
            ...
            >>> a.update() # manually update canvas

    .. describe:: Create a new instance of line:

        .. code-block:: python

            >>> ln=a.createline('new','red') # Copies 'red' to 'new'
            >>> ln=a.createline('new2') # Copies 'default' to 'new2'

    .. describe:: Modify an existing line:

        * Get a line object 'ln' to manipulate:

            .. code-block:: python

                >>> ln=a.getline('red')

        * Set line color:

            .. code-block:: python

                >>> ln.color=100 # Range from 1 to 256

        * Set line width:

            .. code-block:: python

                >>> ln.width=100 # Range from 1 to 300

        * Specify the line type:

            .. code-block:: python

                >>> ln.type='solid' # Same as ln.type=0
                >>> ln.type='dash' # Same as ln.type=1
                >>> ln.type='dot' # Same as ln.type=2
                >>> ln.type='dash-dot' # Same as ln.type=3
                >>> ln.type='long-dash' # Same as ln.type=4

        * Set the graphics priority on the canvas:

            .. code-block:: python

                >>> ln.priority=1
                >>> ln.viewport=[0, 1.0, 0,1.0] # float [0,1]x[0,1]
                >>> ln.worldcoordinate=[0,1.0,0,1.0] # float [#,#]x[#,#]

        * Set line x and y values:

            .. code-block:: python

                >>> ln.x=[[0,.1,.2], [.3,.4,.5]] # List of floats
                >>> ln.y=[[.5,.4,.3], [.2,.1,0]] # List of floats

    .. ln.x and ln.y above cause ln to be unplottable. Need a better example.
    .. Use doctests in this class as a model for converting other class docstrings to use doctests.
    """
    __slots__ = [
        's_name',
        'name',
        'color',
        'priority',
        'type',
        'width',
        'viewport',
        'worldcoordinate',
        'x',
        'y',
        'projection',
        'colormap',
        '_color',
        '_priority',
        '_type',
        '_width',
        '_viewport',
        '_worldcoordinate',
        '_x',
        '_y',
        '_projection',
        '_name',
        '_colormap',
    ]
    colormap = VCS_validation_functions.colormap

    def _getname(self):
        return self._name

    def _setname(self, value):
        value = VCS_validation_functions.checkname(self, 'name', value)
        self._name = value

    name = property(_getname, _setname)

    def _getfillareacolors(self):
        return self._color

    def _setfillareacolors(self, value):
        if isinstance(value, int):
            value = [
                value,
            ]
        self._color = VCS_validation_functions.checkColorList(
            self, 'color', value)

    color = property(_getfillareacolors, _setfillareacolors)

    def _gettype(self):
        return self._type

    def _settype(self, value):
        if isinstance(value, (str, int)):
            value = [
                value,
            ]
        self._type = VCS_validation_functions.checkLineTypeList(
            self, 'type', value)

    type = property(_gettype, _settype)

    def _getwidth(self):
        return self._width

    def _setwidth(self, value):
        if isinstance(value, (int, float)):
            value = [
                value,
            ]
        self._width = VCS_validation_functions.checkListOfNumbers(self,
                                                                  'width',
                                                                  value,
                                                                  minvalue=1,
                                                                  maxvalue=300)

    width = property(_getwidth, _setwidth)

    def _getpriority(self):
        return self._priority

    def _setpriority(self, value):
        self._priority = VCS_validation_functions.checkInt(self,
                                                           'priority',
                                                           value,
                                                           minvalue=0)

    priority = property(_getpriority, _setpriority)

    def _getprojection(self):
        return self._projection

    def _setprojection(self, value):
        self._projection = VCS_validation_functions.checkProjection(
            self, 'projection', value)

    projection = property(_getprojection, _setprojection)

    def _getwc(self):
        return self._worldcoordinate

    def _setwc(self, value):
        self._worldcoordinate = VCS_validation_functions.checkListOfNumbers(
            self, 'worldcoordinate', value, maxelements=4)

    worldcoordinate = property(_getwc, _setwc)

    def _getvp(self):
        return self._viewport

    def _setvp(self, value):
        self._viewport = VCS_validation_functions.checkListOfNumbers(
            self, 'viewport', value, maxelements=4, minvalue=0., maxvalue=1.)

    viewport = property(_getvp, _setvp)

    def _getx(self):
        return self._x

    def _setx(self, value):
        if value is None:
            self._x = None
            return
        if not isinstance(value, (list, tuple)):
            raise ValueError('%s must be a tuple or list of values.')
        try:
            # first we'll see if it is simply a list of values
            value = VCS_validation_functions.checkListOfNumbers(
                self, 'x', value)
        except:
            # ok it was not, so it maybe a list of list of numbers ?
            val = []
            for v in value:
                tmp = VCS_validation_functions.checkListOfNumbers(self, 'x', v)
                val.append(tmp)
            value = val
        # ok it worked
        self._x = value

    x = property(_getx, _setx)

    def _gety(self):
        return self._y

    def _sety(self, value):
        if value is None:
            self._y = None
            return
        if not isinstance(value, (list, tuple)):
            raise ValueError('%s must be a tuple or list of values.')
        try:
            # first we'll see if it is simply a list of values
            value = VCS_validation_functions.checkListOfNumbers(
                self, 'y', value)
        except:
            # ok it was not, so it maybe a list of list of numbers ?
            val = []
            for v in value:
                tmp = VCS_validation_functions.checkListOfNumbers(self, 'y', v)
                val.append(tmp)
            value = val
        # ok it worked
        self._y = value

    y = property(_gety, _sety)

    ##########################################################################
    #                                                                           #
    # Initialize the line attributes.                                           #
    #                                                                           #
    ##########################################################################
    def __init__(self, Tl_name, Tl_name_src='default'):
        #                                                         #
        ###########################################################
        # Initialize the line class and its members               #
        # The getTlmember function retrieves the values of the    #
        # line members in the C structure and passes back the     #
        # appropriate Python Object.                              #
        ###########################################################
        #                                                         #
        if Tl_name in vcs.elements["line"].keys():
            raise ValueError("lineobject '%' already exists" % Tl_name)
        self._name = Tl_name
        if isinstance(Tl_name_src, Tl):
            Tl_name_src = Tl_name_src.name
        self.s_name = 'Tl'
        if Tl_name == "default":
            self._type = [
                'solid',
            ]
            self._projection = "default"
            self._width = [
                1.0,
            ]
            self._color = [
                [0., 0., 0., 100.],
            ]
            self._priority = 1
            self._viewport = [0., 1., 0., 1.]
            self._worldcoordinate = [0., 1., 0., 1.]
            self._x = None
            self._y = None
            self._colormap = None
        else:
            if Tl_name_src not in vcs.elements["line"].keys():
                raise ValueError("The line source '%s' does not exists" %
                                 Tl_name_src)
            src = vcs.elements["line"][Tl_name_src]
            self.type = src.type
            self.projection = src.projection
            self.width = src.width
            self.color = src.color
            self.priority = src.priority
            self.viewport = src.viewport
            self.worldcoordinate = src.worldcoordinate
            self.x = src.x
            self.y = src.y
            self.colormap = src.colormap
        vcs.elements["line"][Tl_name] = self

    ##########################################################################
    #                                                                           #
    # List out line members (attributes).                                       #
    #                                                                           #
    ##########################################################################
    def list(self):
        if (self.name == '__removed_from_VCS__'):
            raise ValueError('This instance has been removed from VCS.')
        print "---------- Line (Tl) member (attribute) listings ----------"
        print "secondary method =", self.s_name
        print "name =", self.name
        print "type =", self.type
        print "width =", self.width
        print "color =", self.color
        print "priority =", self.priority
        print "viewport =", self.viewport
        print "worldcoordinate =", self.worldcoordinate
        print "x =", self.x
        print "y =", self.y
        print "projection =", self.projection
        print "colormap =", self.colormap

    list.__doc__ = listdoc.format(name="line", parent="")

    ##########################################################################
    #                                                                           #
    # Script out secondary line method in VCS to a file.                        #
    #                                                                           #
    ##########################################################################
    def script(self, script_filename=None, mode=None):
        if (script_filename is None):
            raise ValueError(
                'Error - Must provide an output script file name.')

        if (mode is None):
            mode = 'a'
        elif (mode not in ('w', 'a')):
            raise ValueError(
                'Error - Mode can only be "w" for replace or "a" for append.')

        # By default, save file in json
        scr_type = script_filename.split(".")
        if len(scr_type) == 1 or len(scr_type[-1]) > 5:
            scr_type = "json"
            if script_filename != "initial.attributes":
                script_filename += ".json"
        else:
            scr_type = scr_type[-1]
        if scr_type == '.scr':
            raise DeprecationWarning("scr script are no longer generated")
        elif scr_type == "py":
            mode = mode + '+'
            py_type = script_filename[len(script_filename) -
                                      3:len(script_filename)]
            if (py_type != '.py'):
                script_filename = script_filename + '.py'

            # Write to file
            fp = open(script_filename, mode)
            if (fp.tell() == 0):  # Must be a new file, so include below
                fp.write("#####################################\n")
                fp.write("#                                 #\n")
                fp.write("# Import and Initialize VCS     #\n")
                fp.write("#                             #\n")
                fp.write("#############################\n")
                fp.write("import vcs\n")
                fp.write("v=vcs.init()\n\n")

            unique_name = '__Tl__' + self.name
            fp.write(
                "#----------Line (Tl) member (attribute) listings ----------\n"
            )
            fp.write("tl_list=v.listelements('line')\n")
            fp.write("if ('%s' in tl_list):\n" % self.name)
            fp.write("   %s = v.getline('%s')\n" % (unique_name, self.name))
            fp.write("else:\n")
            fp.write("   %s = v.createline('%s')\n" % (unique_name, self.name))
            fp.write("%s.type = %s\n" % (unique_name, self.type))
            fp.write("%s.width = %s\n" % (unique_name, self.width))
            fp.write("%s.color = %s\n" % (unique_name, self.color))
            fp.write("%s.priority = %d\n" % (unique_name, self.priority))
            fp.write("%s.viewport = %s\n" % (unique_name, self.viewport))
            fp.write("%s.worldcoordinate = %s\n" %
                     (unique_name, self.worldcoordinate))
            fp.write("%s.x = %s\n" % (unique_name, self.x))
            fp.write("%s.y = %s\n\n" % (unique_name, self.y))
            fp.write("%s.projection = %s\n\n" % (unique_name, self.projection))
            fp.write("%s.colormap = '%s'\n\n" %
                     (unique_name, repr(self.colormap)))
        else:
            # Json type
            mode += "+"
            f = open(script_filename, mode)
            vcs.utils.dumpToJson(self, f)
            f.close()

    script.__doc__ = scriptdocs['line']
Example #2
0
class To(object):
    """
    The (To) Text Orientation lists text attribute set names that define the font, spacing,
    expansion, and color index.

    This class is used to define an text orientation table entry used in VCS, or it
    can be used to change some or all of the text orientation attributes in an
    existing text orientation table entry.

    .. describe:: Useful Functions:

        .. code-block:: python

            # VCS Canvas Constructor
            a=vcs.init()
            # Show predefined text orientation objects
            a.show('textorientation')
            # Updates the VCS Canvas at user's request
            a.update()

    .. describe:: Make a canvas object to work with:

        .. code-block:: python

            a=vcs.init()

    .. describe:: Create a new instance of text orientation:

        .. code-block:: python

            # Copies content of '7left' to 'new'
            to=a.createtextorientation('new','7left')
            # Copies content of 'default' to 'new'
            to=a.createtextorientation('new')

    .. describe:: Modify an existing textorientation:

        .. code-block:: python

            to=a.gettextorientation('7left')

    .. describe:: Overview of textorientation attributes:

        * Listing the attributes:

            .. code-block:: python

                # Will list all the textorientation attribute values
                to.list()

        * Specify the text height:

            .. code-block:: python

                # The height value must be an integer
                to.height=20

        * Specify the text angle:

            .. code-block:: python

                # The angle value must be in the range 0 to 360
                to.angle=0

        * Specify the text path:

            .. code-block:: python

                # Same as to.path=0
                to.path='right'
                # Same as to.path=1
                to.path='left'
                # Same as to.path=2
                to.path='up'
                # Same as to.path=3
                to.path='down'

        * Specify the text horizontal alignment:

            .. code-block:: python

                # Same as to.halign=0
                to.halign='right'
                # Same as to.halign=1
                to.halign='center'
                # Same as to.halign=2
                to.halign='right'

        * Specify the text vertical alignment:

            .. code-block:: python

                # Same as tovalign=0
                to.valign='top'
                # Same as tovalign=1
                to.valign='cap'
                # Same as tovalign=2
                to.valign='half'
                # Same as tovalign=3
                to.valign='base'
                # Same as tovalign=4
                to.valign='bottom'

    .. pragma: skip-doctest TODO: convert examples to doctests
    """
    __slots__ = [
        's_name',
        'name',
        'height',
        'angle',
        'path',
        'halign',
        'valign',
        '_name',
        '_height',
        '_angle',
        '_path',
        '_halign',
        '_valign',
    ]

    def _getname(self):
        return self._name

    def _setname(self, value):
        value = VCS_validation_functions.checkname(self, 'name', value)
        self._name = value

    name = property(_getname, _setname)

    def _getheight(self):
        return self._height

    def _setheight(self, value):
        self._height = VCS_validation_functions.checkNumber(
            self, 'height', value)

    height = property(_getheight, _setheight)

    def _getangle(self):
        return self._angle

    def _setangle(self, value):
        self._angle = VCS_validation_functions.checkInt(self,
                                                        'angle',
                                                        value,
                                                        minvalue=-360,
                                                        maxvalue=360)

    angle = property(_getangle, _setangle)

    def _getpath(self):
        return self._path

    def _setpath(self, value):
        vals = ["right", "left", "up", "down"]
        self._path = VCS_validation_functions.checkInStringsListInt(
            self, 'path', value, vals)

    path = property(_getpath, _setpath)

    def _gethalign(self):
        return self._halign

    def _sethalign(self, value):
        vals = ["left", "center", "right"]
        self._halign = VCS_validation_functions.checkInStringsListInt(
            self, 'halign', value, vals)

    halign = property(_gethalign, _sethalign)

    def _getvalign(self):
        return self._valign

    def _setvalign(self, value):
        vals = ["top", "cap", "half", "base", "bottom"]
        self._valign = VCS_validation_functions.checkInStringsListInt(
            self, 'valign', value, vals)

    valign = property(_getvalign, _setvalign)

    ##########################################################################
    #                                                                           #
    # Initialize the text orientation attributes.                               #
    #                                                                           #
    ##########################################################################
    def __init__(self, To_name, To_name_src='default'):
        #                                                           #
        #############################################################
        # Initialize the text orientation class and its members     #
        #                                                           #
        # The getTomember function retrieves the values of the      #
        # text orientation members in the C structure and passes    #
        # back the appropriate Python Object.                       #
        #############################################################
        #                                                           #
        if To_name in vcs.elements["textorientation"].keys():
            raise ValueError("textorientation object '%' already exists" %
                             To_name)
        self._name = To_name
        if isinstance(To_name_src, To):
            To_name_src = To_name_src.name
        self.s_name = 'To'
        if To_name == "default":
            self._height = 14
            self._angle = 0
            self._path = "right"
            self._halign = "left"
            self._valign = "half"
        else:
            if To_name_src not in vcs.elements["textorientation"].keys():
                raise ValueError(
                    "source textorientation '%s' does not exists" %
                    To_name_src)
            src = vcs.elements["textorientation"][To_name_src]
            self.height = src.height
            self.angle = src.angle
            self.path = src.path
            self.halign = src.halign
            self.valign = src.valign
        vcs.elements["textorientation"][To_name] = self

    ##########################################################################
    #                                                                           #
    # List out text orientation members (attributes).                           #
    #                                                                           #
    ##########################################################################
    def list(self):
        if (self.name == '__removed_from_VCS__'):
            raise ValueError('This instance has been removed from VCS.')
        print "---------- Text Orientation (To) member (attribute) listings ----------"
        print "secondary method =", self.s_name
        print "name =", self.name
        print "height =", self.height
        print "angle =", self.angle
        print "path =", self.path
        print "halign =", self.halign
        print "valign =", self.valign

    list.__doc__ = listdoc.format(name="textorientation", parent="")

    ##########################################################################
    #                                                                           #
    # Script out secondary text orientation method in VCS to a file.            #
    #                                                                           #
    ##########################################################################
    def script(self, script_filename=None, mode=None):
        if (script_filename is None):
            raise ValueError(
                'Error - Must provide an output script file name.')

        if (mode is None):
            mode = 'a'
        elif (mode not in ('w', 'a')):
            raise ValueError(
                'Error - Mode can only be "w" for replace or "a" for append.')

        # By default, save file in json
        scr_type = script_filename.split(".")
        if len(scr_type) == 1 or len(scr_type[-1]) > 5:
            scr_type = "json"
            if script_filename != "initial.attributes":
                script_filename += ".json"
        else:
            scr_type = scr_type[-1]
        if scr_type == '.scr':
            raise DeprecationWarning("scr script are no longer generated")
        elif scr_type == "py":
            mode = mode + '+'
            py_type = script_filename[len(script_filename) -
                                      3:len(script_filename)]
            if (py_type != '.py'):
                script_filename = script_filename + '.py'

            # Write to file
            fp = open(script_filename, mode)
            if (fp.tell() == 0):  # Must be a new file, so include below
                fp.write("#####################################\n")
                fp.write("#                                 #\n")
                fp.write("# Import and Initialize VCS     #\n")
                fp.write("#                             #\n")
                fp.write("#############################\n")
                fp.write("import vcs\n")
                fp.write("v=vcs.init()\n\n")

            unique_name = '__To__' + self.name
            fp.write(
                "#----------Text Orientation (To) member (attribute) listings ----------\n"
            )
            fp.write("to_list=v.listelements('textorientation')\n")
            fp.write("if ('%s' in to_list):\n" % self.name)
            fp.write("   %s = v.gettextorientation('%s')\n" %
                     (unique_name, self.name))
            fp.write("else:\n")
            fp.write("   %s = v.createtextorientation('%s')\n" %
                     (unique_name, self.name))
            fp.write("%s.height = %g\n" % (unique_name, self.height))
            fp.write("%s.angle = %g\n" % (unique_name, self.angle))
            fp.write("%s.path = '%s'\n" % (unique_name, self.path))
            fp.write("%s.halign = '%s'\n" % (unique_name, self.halign))
            fp.write("%s.valign = '%s'\n\n" % (unique_name, self.valign))
            fp.close()
        else:
            # Json type
            mode += "+"
            f = open(script_filename, mode)
            vcs.utils.dumpToJson(self, f)
            f.close()

    script.__doc__ = scriptdocs['textorientation']
Example #3
0
class Proj(object):

    """
    The projection secondary method (Proj) is used when plotting 2D data, and define
    how to project from lon/lat coord to another mapping system (lambert, mercator, mollweide, etc...)

    This class is used to define a projection table entry used in VCS, or it
    can be used to change some or all of the attributes in an existing
    projection table entry.

    .. describe:: Projection Transformation Package Projection Parameters

        +-----------------------+---------------------------------------------------------+
        |                       |                  Array Element                          |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |*Code & Projection Id* |   1  |   2  |  3   |  4   |   5   |    6    |7 | 8|  9  |
        +=======================+======+======+======+======+=======+=========+==+==+=====+
        |0 Geographic           |      |      |      |      |       |         |  |  |     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |1 U T M                |Lon/Z |Lat/Z |      |      |       |         |  |  |     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |2 State Plane          |      |      |      |      |       |         |  |  |     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |3 Albers Equal Area    |SMajor|SMinor|STDPR1|STDPR2|CentMer|OriginLat|FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |4 Lambert Conformal C  |SMajor|SMinor|STDPR1|STDPR2|CentMer|OriginLat|FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |5 Mercator             |SMajor|SMinor|      |      |CentMer|TrueScale|FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |6 Polar Stereographic  |SMajor|SMinor|      |      |LongPol|TrueScale|FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |7 Polyconic            |SMajor|SMinor|      |      |CentMer|OriginLat|FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |8 Equid. Conic A       |SMajor|SMinor|STDPAR|      |CentMer|OriginLat|FE|FN| zero|
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |  Equid. Conic B       |SMajor|SMinor|STDPR1|STDPR2|CentMer|OriginLat|FE|FN| one |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |9 Transverse Mercator  |SMajor|SMinor|Factor|      |CentMer|OriginLat|FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |10 Stereographic       |Sphere|      |      |      |CentLon|CenterLat|FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |11 Lambert Azimuthal   |Sphere|      |      |      |CentLon|CenterLat|FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |12 Azimuthal           |Sphere|      |      |      |CentLon|CenterLat|FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |13 Gnomonic            |Sphere|      |      |      |CentLon|CenterLat|FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |14 Orthographic        |Sphere|      |      |      |CentLon|CenterLat|FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |15 Gen. Vert. Near Per |Sphere|      |Height|      |CentLon|CenterLat|FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |16 Sinusoidal          |Sphere|      |      |      |CentMer|         |FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |17 Equirectangular     |Sphere|      |      |      |CentMer|TrueScale|FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |18 Miller Cylindrical  |Sphere|      |      |      |CentMer|         |FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |19 Van der Grinten     |Sphere|      |      |      |CentMer|OriginLat|FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |20 Hotin Oblique Merc A|SMajor|SMinor|Factor|      |       |OriginLat|FE|FN|Long1|
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |   Hotin Oblique Merc B|SMajor|SMinor|Factor|AziAng|AzmthPt|OriginLat|FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |21 Robinson            |Sphere|      |      |      |CentMer|         |FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |22 Space Oblique Merc A|SMajor|SMinor|      |IncAng|AscLong|         |FE|FN|PSRev|
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |   Space Oblique Merc B|SMajor|SMinor|Satnum|Path  |       |         |FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |23 Alaska Conformal    |SMajor|SMinor|      |      |       |         |FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |24 Interrupted Goode   |Sphere|      |      |      |       |         |  |  |     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |25 Mollweide           |Sphere|      |      |      |CentMer|         |FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |26 Interrupt Mollweide |Sphere|      |      |      |       |         |  |  |     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |27 Hammer              |Sphere|      |      |      |CentMer|         |FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |28 Wagner IV           |Sphere|      |      |      |CentMer|         |FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |29 Wagner VII          |Sphere|      |      |      |CentMer|         |FE|FN|     |
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+
        |30 Oblated Equal Area  |Sphere|      |Shapem|Shapen|CentLon|CenterLat|FE|FN|Angle|
        +-----------------------+------+------+------+------+-------+---------+--+--+-----+

        +-----------------------+-----------------------+
        |                       |       Array Element   |
        +-----------------------+-----+-----+-----+-----+
        |  Code & Projection Id |  10 |  11 |  12 |  13 |
        +=======================+=====+=====+=====+=====+
        |20 Hotin Oblique Merc A|Lat1 |Long2|Lat2 |zero |
        +-----------------------+-----+-----+-----+-----+
        |   Hotin Oblique Merc B|     |     |     | one |
        +-----------------------+-----+-----+-----+-----+
        |22 Space Oblique Merc A|LRat |PFlag|     |zero |
        +-----------------------+-----+-----+-----+-----+
        |   Space Oblique Merc B|     |     |     | one |
        +-----------------------+-----+-----+-----+-----+

            .. note::

                All other projections are blank (containing 0) for elements 10-13



        .. glossary::

            Lon/Z

                Longitude of any point in the UTM zone or zero.  If zero,
                a zone code must be specified.

            Lat/Z

                Latitude of any point in the UTM zone or zero.  If zero, a
                zone code must be specified.

            SMajor

                Semi-major axis of ellipsoid.  If zero, Clarke 1866 in meters
                is assumed.

            SMinor

                Eccentricity squared of the ellipsoid if less than zero,
                if zero, a spherical form is assumed, or if greater than
                zero, the semi-minor axis of ellipsoid.

            Sphere

                Radius of reference sphere.  If zero, 6370997 meters is used.

            STDPAR

                Latitude of the standard parallel

            STDPR1

                Latitude of the first standard parallel

            STDPR2

                Latitude of the second standard parallel

            CentMer

                Longitude of the central meridian

            OriginLat

                Latitude of the projection origin

            FE

                False easting in the same units as the semi-major axis

            FN

                False northing in the same units as the semi-major axis

            TrueScale

                Latitude of true scale

            LongPol

                Longitude down below pole of map

            Factor

                Scale factor at central meridian (Transverse Mercator) or
                center of projection (Hotine Oblique Mercator)

            CentLon

                Longitude of center of projection

            CenterLat

                Latitude of center of projection

            Height

                Height of perspective point

            Long1

                Longitude of first point on center line (Hotine Oblique
                Mercator, format A)

            Long2

                Longitude of second point on center line (Hotine Oblique
                Mercator, format A)

            Lat1

                Latitude of first point on center line (Hotine Oblique
                Mercator, format A)

            Lat2

                Latitude of second point on center line (Hotine Oblique
                Mercator, format A)

            AziAng

                Azimuth angle east of north of center line (Hotine Oblique
                Mercator, format B)

            AzmthPt

                Longitude of point on central meridian where azimuth occurs
                (Hotine Oblique Mercator, format B)

            IncAng

                Inclination of orbit at ascending node, counter-clockwise
                from equator (SOM, format A)

            AscLong

                Longitude of ascending orbit at equator (SOM, format A)

            PSRev

                Period of satellite revolution in minutes (SOM, format A)

            LRat

                Landsat ratio to compensate for confusion at northern end
                of orbit (SOM, format A -- use 0.5201613)

            PFlag

                End of path flag for Landsat:  0 = start of path,
                1 = end of path (SOM, format A)

            Satnum

                Landsat Satellite Number (SOM, format B)

            Path

                Landsat Path Number (Use WRS-1 for Landsat 1, 2 and 3 and
                WRS-2 for Landsat 4, 5 and 6.)  (SOM, format B)

            Shapem

                Oblated Equal Area oval shape parameter m

            Shapen

                Oblated Equal Area oval shape parameter n

            Angle

                Oblated Equal Area oval rotation angle


        .. describe:: Array Elements:

            * Array elements 14 and 15 are set to zero

            * All array elements with blank fields are set to zero

            * All angles (latitudes, longitudes, azimuths, etc.) are entered in packed
                degrees/ minutes/ seconds (DDDMMMSSS.SS) format

        .. describe:: Space Oblique Mercator A projection:

            * A portion of Landsat rows 1 and 2 may also be seen as parts of rows
                246 or 247.  To place these locations at rows 246 or 247, set the end of
                path flag (parameter 11) to 1--end of path.  This flag defaults to zero.

            * When Landsat-1,2,3 orbits are being used, use the following values
                for the specified parameters:

                * Parameter 4   099005031.2
                * Parameter 5   128.87 degrees - (360/251 * path number) in packed DMS format

                * Parameter 9   103.2669323
                * Parameter 10  0.5201613

            * When Landsat-4,5 orbits are being used, use the following values
                for the specified parameters:

                * Parameter 4   098012000.0
                * Parameter 5   129.30 degrees - (360/233 * path number) in packed DMS format
                * Parameter 9   98.884119
                * Parameter 10  0.5201613

        .. note::
            In vcs angles can be entered either in DDDMMMSSS or regular angle format.

    .. describe:: Useful Functions:

        .. code-block:: python

            # VCS Canvas Constructor
            a=vcs.init()
            # Show predefined projection secondary methods
            a.show('projection')

    .. describe:: Create a Canvas object to work with:

        .. code-block:: python

            a=vcs.init()

    .. describe:: Create a new instance of projection:

        .. code-block:: python

            # Copies content of 'quick' to 'new'
            p=a.createprojection('new','quick')
            # Copies content of 'default' to 'new'
            p=a.createprojection('new')

    .. describe:: Modify an existing projection:

        .. code-block:: python

            p=a.getprojection('lambert')
            # List all the projection attribute values
            p.list()
            p.type='lambert'
            # Fill a list with projection parameter values
            params= []
            for _ in range(0,14):
               params.append(1.e20)
            # params now a list with 1.e20, 15 times
            p.parameters= params
            iso=x.createisoline('new')
            iso.projection=p
            # or
            iso.projection='lambert'

    .. pragma: skip-doctest
    """

    def __init__(self, Proj_name=None, Proj_name_src='default'):

        # Initialize the projection class and its members
        # The getProjmember function retrieves the values of the
        # projection members in the C structure and passes back the
        # appropriate Python Object.

        if isinstance(Proj_name_src, Proj):
            Proj_name_src = Proj_name_src.name
        if Proj_name_src != "default" and Proj_name_src not in vcs.elements[
                "projection"].keys():
            raise ValueError("Projection '%s' does not exists" % Proj_name_src)
        if (Proj_name is None):
            raise ValueError('Must provide a projection name.')
        else:
            if Proj_name in vcs.elements["projection"].keys():
                raise ValueError(
                    "The projection '%s' already exists, use getprojection instead" %
                    Proj_name)
        self._name = Proj_name
        self.s_name = 'Proj'
        #                                                         #
        ###########################################################
        # Inherits core secondary method attributes.		  #
        ###########################################################
        #                                                         #
        # graphics_secondary method_core.__init__(self, parent)
        # Doesn't make sense to inherit. This would mean writing more code
        self._type = 0
        self._parameters = [
            1e+20,
            1e+20,
            1e+20,
            1e+20,
            1e+20,
            1e+20,
            1e+20,
            1e+20,
            1e+20,
            1e+20,
            1e+20,
            1e+20,
            1e+20,
            1e+20,
            1e+20]
        if Proj_name != "default":
            src = vcs.elements["projection"][Proj_name_src]
            self.type = src.type
            self.parameters = copy.copy(src.parameters)
        vcs.elements["projection"][Proj_name] = self

    ##########################################################################
    #                                                                           #
    # List out projection secondary method members (attributes).                    #
    #                                                                           #
    ##########################################################################
    def list(self):
        if (self.name == '__removed_from_VCS__'):
            raise ValueError('This instance has been removed from VCS.')
        print '---------- Projection (Proj) member (attribute) listings ----------'
        print 'secondary method =', self.s_name
        print 'name =', self.name
        print 'type =', self.type
        # print 'parameters =',self.parameters

        for att in self.attributes:
            print att, '=', getattr(self, att)
    list.__doc__ = listdoc.format(name="projection", parent="")

    @property
    def attributes(self):
        p = []
        if self._type in [3, 4]:
            p.append('smajor')
            p.append('sminor')
            p.append('standardparallel1')
            p.append('standardparallel2')
            p.append('centralmeridian')
            p.append('originlatitude')
            p.append('falseeasting')
            p.append('falsenorthing')
        elif self._type == 5:
            p.append('smajor')
            p.append('sminor')
            p.append('centralmeridian')
            p.append('truescale')
            p.append('falseeasting')
            p.append('falsenorthing')
        elif self._type == 6:
            p.append('smajor')
            p.append('sminor')
            p.append('centerlongitude')
            p.append('truescale')
            p.append('falseeasting')
            p.append('falsenorthing')
        elif self._type == 7:
            p.append('smajor')
            p.append('sminor')
            p.append('centralmeridian')
            p.append('originlatitude')
            p.append('falseeasting')
            p.append('falsenorthing')
        elif self._type == 8:
            p.append('subtype')
            p.append('smajor')
            p.append('sminor')
            p.append('centralmeridian')
            p.append('originlatitude')
            p.append('falseeasting')
            p.append('falsenorthing')
            if self.subtype == 0:
                p.append('standardparallel')
            else:
                p.append('standardparallel1')
                p.append('standardparallel2')
        elif self._type == 9:
            p.append('smajor')
            p.append('sminor')
            p.append('factor')
            p.append('centralmeridian')
            p.append('originlatitude')
            p.append('falseeasting')
            p.append('falsenorthing')
        elif self._type in [10, 11, 12, 13, 14]:
            p.append('sphere')
            p.append('centerlongitude')
            p.append('centerlatitude')
            p.append('falseeasting')
            p.append('falsenorthing')
        elif self._type == 15:
            p.append('sphere')
            p.append('height')
            p.append('centerlongitude')
            p.append('centerlatitude')
            p.append('falseeasting')
            p.append('falsenorthing')
        elif self._type in [16, 18, 21, 25, 27, 28, 29]:
            p.append('sphere')
            p.append('centralmeridian')
            p.append('falseeasting')
            p.append('falsenorthing')
        elif self._type == 17:
            p.append('sphere')
            p.append('centralmeridian')
            p.append('truescale')
            p.append('falseeasting')
            p.append('falsenorthing')
        elif self._type == 19:
            p.append('sphere')
            p.append('centralmeridian')
            p.append('originlatitude')
            p.append('falseeasting')
            p.append('falsenorthing')
        elif self._type == 20:
            p.append('subtype')
            p.append('smajor')
            p.append('sminor')
            p.append('factor')
            p.append('originlatitude')
            p.append('falseeasting')
            p.append('falsenorthing')
            if self.subtype == 0:
                p.append('longitude1')
                p.append('latitude1')
                p.append('longitude2')
                p.append('latitude2')
            else:
                p.append('azimuthalangle')
                p.append('azimuthallongitude')
        elif self._type == 22:
            p.append('subtype')
            p.append('smajor')
            p.append('sminor')
            p.append('falseeasting')
            p.append('falsenorthing')
            if self.subtype == 0:
                p.append('orbitinclination')
                p.append('orbitlongitude')
                p.append('satelliterevolutionperiod')
                p.append('landsatcompensationratio')
                p.append('pathflag')
            else:
                p.append('satellite')
                p.append('path')
        elif self._type == 23:
            p.append('smajor')
            p.append('sminor')
            p.append('falseeasting')
            p.append('falsenorthing')
        elif self._type in [24, 26]:
            p.append('sphere')
        elif self._type == 30:
            p.append('sphere')
            p.append('shapem')
            p.append('shapen')
            p.append('centerlongitude')
            p.append('centerlatitude')
            p.append('falseeasting')
            p.append('falsenorthing')
        return p

    ##########################################################################
    #                                                                           #
    # Script out primary projection secondary method in VCS to a file.              #
    #                                                                           #
    ##########################################################################
    def script(self, script_filename=None, mode=None):
        if (script_filename is None):
            raise ValueError(
                'Error - Must provide an output script file name.')

        if (mode is None):
            mode = 'a'
        elif (mode not in ('w', 'a')):
            raise ValueError(
                'Error - Mode can only be "w" for replace or "a" for append.')

        # By default, save file in python script mode
        scr_type = script_filename[
            len(script_filename) -
            4:len(script_filename)]
        if (script_filename is None):
            raise ValueError(
                'Error - Must provide an output script file name.')

        if (mode is None):
            mode = 'a'
        elif (mode not in ('w', 'a')):
            raise ValueError(
                'Error - Mode can only be "w" for replace or "a" for append.')

        # By default, save file in json
        scr_type = script_filename.split(".")
        if len(scr_type) == 1 or len(scr_type[-1]) > 5:
            scr_type = "json"
            if script_filename != "initial.attributes":
                script_filename += ".json"
        else:
            scr_type = scr_type[-1]
        if scr_type == '.scr':
            raise DeprecationWarning("scr script are no longer generated")
        elif scr_type == "py":
            mode = mode + '+'
            py_type = script_filename[
                len(script_filename) -
                3:len(script_filename)]
            if (py_type != '.py'):
                script_filename = script_filename + '.py'

            # Write to file
            fp = open(script_filename, mode)
            if (fp.tell() == 0):  # Must be a new file, so include below
                fp.write("#####################################\n")
                fp.write("#                                 #\n")
                fp.write("# Import and Initialize VCS     #\n")
                fp.write("#                             #\n")
                fp.write("#############################\n")
                fp.write("import vcs\n")
                fp.write("v=vcs.init()\n\n")

            unique_name = '__Proj__' + self.name
            fp.write(
                "#----------Projection (Proj) member (attribute) listings ----------\n")
            fp.write("proj_list=v.listelements('projection')\n")
            fp.write("if ('%s' in proj_list):\n" % self.name)
            fp.write(
                "   %s = v.getprojection('%s')\n" %
                (unique_name, self.name))
            fp.write("else:\n")
            fp.write(
                "   %s = v.createprojection('%s')\n" %
                (unique_name, self.name))
            # Common core secondary method attributes
            fp.write("%s.type = '%s'\n" % (unique_name, self.type))
            fp.write("%s.parameters = '%s'\n" % (unique_name, self.parameters))
        else:
            # Json type
            mode += "+"
            f = open(script_filename, mode)
            vcs.utils.dumpToJson(self, f)
            f.close()
    script.__doc__ = scriptdocs['projection']

    __slots__ = [
        's_name',
        'smajor',
        'sminor',
        'centralmeridian',
        'truescale',
        'falseeasting',
        'falsenorthing',
        'factor',
        'originlatitude',
        'azimuthalangle',
        'azimuthlongitude',
        'longitude1',
        'longitude2',
        'latitude1',
        'latitude2',
        'subtype',
        'orbitinclination',
        'orbitlongitude',
        'satelliterevolutionperiod',
        'landsatcompensationratio',
        'pathflag',
        'path',
        'satellite',
        'sphere',
        'centerlongitude',
        'centerlatitude',
        'standardparallel1',
        'standardparallel2',
        'standardparallel',
        'height',
        'angle',
        'shapem',
        'shapen',
        'parent',
        'name',
        'type',
        'parameters',
        '_smajor',
        '_sminor',
        '_centralmeridian',
        '_truescale',
        '_falseeasting',
        '_falsenorthing',
        '_factor',
        '_originlatitude',
        '_azimuthalangle',
        '_azimuthlongitude',
        '_longitude1',
        '_longitude2',
        '_latitude1',
        '_latitude2',
        '_subtype',
        '_orbitinclination',
        '_orbitlongitude',
        '_satelliterevolutionperiod',
        '_landsatcompensationratio',
        '_pathflag',
        '_path',
        '_satellite',
        '_sphere',
        '_centerlongitude',
        '_centerlatitude',
        '_standardparallel1',
        '_standardparallel2',
        '_standardparallel',
        '_height',
        '_angle',
        '_shapem',
        '_shapen',
        '_name',
        '_type',
        '_parameters',
    ]

    def checkPP(self, name, value):
        value = VCS_validation_functions.setProjParameter(self, name, value)
        setattr(self, '_' + name, value)

    def _getsmajor(self):
        return self._smajor

    def _setsmajor(self, value):
        self.checkPP('smajor', value)
    smajor = property(_getsmajor, _setsmajor)

    def _getsminor(self):
        return self._sminor

    def _setsminor(self, value):
        self.checkPP('sminor', value)
    sminor = property(_getsminor, _setsminor)

    def _getcentralmeridian(self):
        return self._centralmeridian

    def _setcentralmeridian(self, value):
        self.checkPP('centralmeridian', value)
    centralmeridian = property(_getcentralmeridian, _setcentralmeridian)

    def _gettruescale(self):
        return self._truescale

    def _settruescale(self, value):
        self.checkPP('truescale', value)
    truescale = property(_gettruescale, _settruescale)

    def _getfalseeasting(self):
        return self._falseeasting

    def _setfalseeasting(self, value):
        self.checkPP('falseeasting', value)
    falseeasting = property(_getfalseeasting, _setfalseeasting)

    def _getfalsenorthing(self):
        return self._falsenorthing

    def _setfalsenorthing(self, value):
        self.checkPP('falsenorthing', value)
    falsenorthing = property(_getfalsenorthing, _setfalsenorthing)

    def _getfactor(self):
        return self._factor

    def _setfactor(self, value):
        self.checkPP('factor', value)
    factor = property(_getfactor, _setfactor)

    def _getoriginlatitude(self):
        return self._originlatitude

    def _setoriginlatitude(self, value):
        self.checkPP('originlatitude', value)
    originlatitude = property(_getoriginlatitude, _setoriginlatitude)

    def _getazimuthalangle(self):
        return self._azimuthalangle

    def _setazimuthalangle(self, value):
        self.checkPP('azimuthalangle', value)
    azimuthalangle = property(_getazimuthalangle, _setazimuthalangle)

    def _getazimuthallongitude(self):
        return self._azimuthallongitude

    def _setazimuthallongitude(self, value):
        self.checkPP('azimuthallongitude', value)
    azimuthallongitude = property(
        _getazimuthallongitude,
        _setazimuthallongitude)

    def _getlongitude1(self):
        return self._longitude1

    def _setlongitude1(self, value):
        self.checkPP('longitude1', value)
    longitude1 = property(_getlongitude1, _setlongitude1)

    def _getlongitude2(self):
        return self._longitude2

    def _setlongitude2(self, value):
        self.checkPP('longitude2', value)
    longitude2 = property(_getlongitude2, _setlongitude2)

    def _getlatitude1(self):
        return self._latitude1

    def _setlatitude1(self, value):
        self.checkPP('latitude1', value)
    latitude1 = property(_getlatitude1, _setlatitude1)

    def _getlatitude2(self):
        return self._latitude2

    def _setlatitude2(self, value):
        self.checkPP('latitude2', value)
    latitude2 = property(_getlatitude2, _setlatitude2)

    def _getsubtype(self):
        return self._subtype

    def _setsubtype(self, value):
        self.checkPP('subtype', value)
    subtype = property(_getsubtype, _setsubtype)

    def _getorbitinclination(self):
        return self._orbitinclination

    def _setorbitinclination(self, value):
        self.checkPP('orbitinclination', value)
    orbitinclination = property(_getorbitinclination, _setorbitinclination)

    def _getorbitlongitude(self):
        return self._orbitlongitude

    def _setorbitlongitude(self, value):
        self.checkPP('orbitlongitude', value)
    orbitlongitude = property(_getorbitlongitude, _setorbitlongitude)

    def _getsatelliterevolutionperiod(self):
        return self._satelliterevolutionperiod

    def _setsatelliterevolutionperiod(self, value):
        self.checkPP('satelliterevolutionperiod', value)
    satelliterevolutionperiod = property(
        _getsatelliterevolutionperiod,
        _setsatelliterevolutionperiod)

    def _getlandsatcompensationratio(self):
        return self._landsatcompensationratio

    def _setlandsatcompensationratio(self, value):
        self.checkPP('landsatcompensationratio', value)
    landsatcompensationratio = property(
        _getlandsatcompensationratio,
        _setlandsatcompensationratio)

    def _getpathflag(self):
        return self._pathflag

    def _setpathflag(self, value):
        self.checkPP('pathflag', value)
    pathflag = property(_getpathflag, _setpathflag)

    def _getpath(self):
        return self._path

    def _setpath(self, value):
        self.checkPP('path', value)
    path = property(_getpath, _setpath)

    def _getsatellite(self):
        return self._satellite

    def _setsatellite(self, value):
        self.checkPP('satellite', value)
    satellite = property(_getsatellite, _setsatellite)

    def _getsphere(self):
        return self._sphere

    def _setsphere(self, value):
        self.checkPP('sphere', value)
    sphere = property(_getsphere, _setsphere)

    def _getcenterlongitude(self):
        return self._centerlongitude

    def _setcenterlongitude(self, value):
        self.checkPP('centerlongitude', value)
    centerlongitude = property(_getcenterlongitude, _setcenterlongitude)

    def _getcenterlatitude(self):
        return self._centerlatitude

    def _setcenterlatitude(self, value):
        self.checkPP('centerlatitude', value)
    centerlatitude = property(_getcenterlatitude, _setcenterlatitude)

    def _getstandardparallel1(self):
        return self._standardparallel1

    def _setstandardparallel1(self, value):
        self.checkPP('standardparallel1', value)
    standardparallel1 = property(_getstandardparallel1, _setstandardparallel1)

    def _getstandardparallel2(self):
        return self._standardparallel2

    def _setstandardparallel2(self, value):
        self.checkPP('standardparallel2', value)
    standardparallel2 = property(_getstandardparallel2, _setstandardparallel2)

    def _getstandardparallel(self):
        return self._standardparallel

    def _setstandardparallel(self, value):
        self.checkPP('standardparallel', value)
    standardparallel = property(_getstandardparallel, _setstandardparallel)

    def _getheight(self):
        return self._height

    def _setheight(self, value):
        self.checkPP('height', value)
    height = property(_getheight, _setheight)

    def _getangle(self):
        return self._angle

    def _setangle(self, value):
        self.checkPP('angle', value)
    angle = property(_getangle, _setangle)

    def _getshapem(self):
        return self._shapem

    def _setshapem(self, value):
        self.checkPP('shapem', value)
    shapem = property(_getshapem, _setshapem)

    def _getshapen(self):
        return self._shapen

    def _setshapen(self, value):
        self.checkPP('shapen', value)
    shapen = property(_getshapen, _setshapen)

    def _getname(self):
        return self._name

    def _setname(self, value):
        value = VCS_validation_functions.checkname(self, 'name', value)
        self._name = value
    name = property(_getname, _setname)

    def _settype(self, value):
        value = VCS_validation_functions.checkProjType(self, 'type', value)
        self._type = value

    def _gettype(self):
        return VCS_validation_functions.getProjType(self)
    type = property(_gettype, _settype)

    def _getparameters(self):
        return self._parameters

    def _setparameters(self, value):
        value = VCS_validation_functions.checkProjParameters(
            self,
            'parameters',
            value)
        self._parameters = value
    parameters = property(_getparameters, _setparameters)
Example #4
0
class Tm(object):

    """
    The Marker object allows the manipulation of marker type, size, and color index.

    This class is used to define an marker table entry used in VCS, or it
    can be used to change some or all of the marker attributes in an
    existing marker table entry.


    .. describe:: Useful Functions:

        .. code-block:: python

            # VCS Canvas Constructor
            a=vcs.init()
            # Show predefined marker objects
            a.show('marker')
            # Updates the VCS Canvas at user's request
            a.update()
            a=vcs.init()

    .. describe:: Create a new instance of marker:

        .. code-block:: python

            # Copies content of 'red' to 'new'
            mk=a.createmarker('new','red')
            # Copies content of 'default' to 'new'
            mk=a.createmarker('new')

    .. describe:: Modify an existing marker:

        .. code-block:: python

            mk=a.getmarker('red')

    .. describe:: Overview of marker attributes:

        * List all the marker attribute values:

            .. code-block:: python

                mk.list()
                # Range from 1 to 256
                mk.color=100
                # Range from 1 to 300
                mk.size=100

        * Specify the marker type:

            .. code-block:: python

                # Same as mk.type=1
                mk.type='dot'
                # Same as mk.type=2
                mk.type='plus'
                # Same as mk.type=3
                mk.type='star'
                # Same as mk.type=4
                mk.type='circle'
                # Same as mk.type=5
                mk.type='cross'
                # Same as mk.type=6
                mk.type='diamond'
                # Same as mk.type=7
                mk.type='triangle_up'
                # Same as mk.type=8
                mk.type='triangle_down'
                # Same as mk.type=9
                mk.type='triangle_left'
                # Same as mk.type=10
                mk.type='triangle_right'
                # Same as mk.type=11
                mk.type='square'
                # Same as mk.type=12
                mk.type='diamond_fill'
                # Same as mk.type=13
                mk.type='triangle_up_fill'
                # Same as mk.type=14
                mk.type='triangle_down_fill'
                # Same as mk.type=15
                mk.type='triangle_left_fill'
                # Same as mk.type=16
                mk.type='triangle_right_fill'
                # Same as mk.type=17
                mk.type='square_fill'

        * Set the graphics priority on the canvas

            .. code-block:: python

                mk.priority=1
                # FloatType [0,1]x[0,1]
                mk.viewport=[0, 1.0, 0,1.0]
                # FloatType [#,#]x[#,#]
                mk.worldcoordinate=[0,1.0,0,1.0]

        * Example x and y coordinates:

            .. code-block:: python

                # List of FloatTypes
                mk.x=[[0,.1,.2], [.3,.4,.5]]
                # List of FloatTypes
                mk.y=[[.5,.4,.3], [.2,.1,0]]

        .. pragma: skip-doctest
        """
    __slots__ = [
        's_name',
        'name',
        'color',
        'priority',
        'type',
        'size',
        'viewport',
        'worldcoordinate',
        'x',
        'y',
        'colormap',
        '_name',
        '_color',
        '_priority',
        '_type',
        '_size',
        '_viewport',
        '_worldcoordinate',
        '_x',
        '_y',
        '_projection',
        '_colormap',
    ]
    colormap = VCS_validation_functions.colormap

    def _getname(self):
        return self._name

    def _setname(self, value):
        value = VCS_validation_functions.checkname(self, 'name', value)
        if value is not None:
            self._name = value
    name = property(_getname, _setname)

    def _getfillareacolors(self):
        return self._color

    def _setfillareacolors(self, value):
        if isinstance(value, int):
            value = [value, ]
        if value is not None:
            value = VCS_validation_functions.checkColorList(
                self,
                'color',
                value)
        self._color = value
    color = property(_getfillareacolors, _setfillareacolors)

    def _gettype(self):
        return self._type

    def _settype(self, value):
        if not isinstance(value, (list, tuple)) and value is not None:
            value = [value, ]
        if value is not None:
            value = VCS_validation_functions.checkMarkersList(
                self,
                'type',
                value)
        self._type = value
    type = property(_gettype, _settype)

    def _getsize(self):
        return self._size

    def _setsize(self, value):
        if VCS_validation_functions.isNumber(value):
            value = [value, ]
        if value is not None:
            value = VCS_validation_functions.checkListOfNumbers(
                self,
                'size',
                value,
                minvalue=0,
                maxvalue=300)
        self._size = value
    size = property(_getsize, _setsize)

    def _getpriority(self):
        return self._priority

    def _setpriority(self, value):
        value = VCS_validation_functions.checkInt(
            self,
            'priority',
            value,
            minvalue=0)
        self._priority = value
    priority = property(_getpriority, _setpriority)

    def _getprojection(self):
        return self._projection

    def _setprojection(self, value):
        value = VCS_validation_functions.checkProjection(
            self,
            'projection',
            value)
        self._projection = value
    projection = property(_getprojection, _setprojection)

    def _getwc(self):
        return self._worldcoordinate

    def _setwc(self, value):
        value = VCS_validation_functions.checkListOfNumbers(
            self,
            'worldcoordinate',
            value,
            maxelements=4)
        self._worldcoordinate = value
    worldcoordinate = property(_getwc, _setwc)

    def _getvp(self):
        return self._viewport

    def _setvp(self, value):
        value = VCS_validation_functions.checkListOfNumbers(
            self,
            'viewport',
            value,
            maxelements=4,
            minvalue=0.,
            maxvalue=1.)
        self._viewport = value
    viewport = property(_getvp, _setvp)

    def _getx(self):
        return self._x

    def _setx(self, value):
        if value is None:
            self._x = None
            return
        if not isinstance(value, (list, tuple)):
            raise ValueError(
                'x must be a tuple or list of values. You sent: %s' %
                value)
        try:
            # first we'll see if it is simply a list of values
            value = VCS_validation_functions.checkListOfNumbers(
                self,
                'x',
                value)
        except:
            # ok it was not, so it maybe a list of list of numbers ?
            val = []
            for v in value:
                tmp = VCS_validation_functions.checkListOfNumbers(self, 'x', v)
                val.append(tmp)
            value = val
        # ok it worked
        self._x = value
    x = property(_getx, _setx)

    def _gety(self):
        return self._y

    def _sety(self, value):
        if value is None:
            self._y = None
            return
        if not isinstance(value, (list, tuple)):
            raise ValueError(
                'y must be a tuple or list of values. You sent: %s' %
                value)
        try:
            # first we'll see if it is simply a list of values
            value = VCS_validation_functions.checkListOfNumbers(
                self,
                'y',
                value)
        except:
            # ok it was not, so it maybe a list of list of numbers ?
            val = []
            for v in value:
                tmp = VCS_validation_functions.checkListOfNumbers(self, 'y', v)
                val.append(tmp)
            value = val
        # ok it worked
        self._y = value
    y = property(_gety, _sety)

    def __init__(self, Tm_name, Tm_name_src='default'):
        if (Tm_name is None):
            raise ValueError('Must provide a marker name.')
        self._name = Tm_name
        self.s_name = 'Tm'
        if Tm_name == "default":
            self._type = ["dot", ]
            self._size = [1.0, ]
            self._color = [1, ]
            self._priority = 1
            self._viewport = [0., 1., 0., 1.]
            self._worldcoordinate = [0., 1., 0., 1.]
            self._x = None
            self._y = None
            self._projection = "default"
            self._colormap = None
        else:
            if isinstance(Tm_name_src, Tm):
                Tm_name_src = Tm_name_src.name
            if Tm_name_src not in vcs.elements['marker']:
                raise ValueError(
                    "The marker object '%s' does not exists" %
                    Tm_name_src)
            src = vcs.elements["marker"][Tm_name_src]
            for att in ['colormap', 'projection', 'color', 'size',
                        'type', 'viewport', 'worldcoordinate', 'priority', 'x', 'y']:
                setattr(self, att, getattr(src, att))
        # Ok now we need to stick in the elements
        vcs.elements["marker"][Tm_name] = self

    def list(self):
        if (self.name == '__removed_from_VCS__'):
            raise ValueError('This instance has been removed from VCS.')
        print "---------- Marker (Tm) member (attribute) listings ----------"
        print "secondary method =", self.s_name
        print "name =", self.name
        print "type =", self.type
        print "size =", self.size
        print "color =", self.color
        print "priority =", self.priority
        print "viewport =", self.viewport
        print "worldcoordinate =", self.worldcoordinate
        print "x =", self.x
        print "y =", self.y
        print "projection =", self.projection
        print "colormap =", self.colormap
    list.__doc__ = listdoc.format(name="marker", parent="")

    def script(self, script_filename=None, mode=None):
        if (script_filename is None):
            raise ValueError(
                'Error - Must provide an output script file name.')

        if (mode is None):
            mode = 'a'
        elif (mode not in ('w', 'a')):
            raise ValueError(
                'Error - Mode can only be "w" for replace or "a" for append.')

        # By default, save file in json
        scr_type = script_filename.split(".")
        if len(scr_type) == 1 or len(scr_type[-1]) > 5:
            scr_type = "json"
            if script_filename != "initial.attributes":
                script_filename += ".json"
        else:
            scr_type = scr_type[-1]
        if scr_type == '.scr':
            raise DeprecationWarning("scr script are no longer generated")
        elif scr_type == "py":
            mode = mode + '+'
            py_type = script_filename[
                len(script_filename) -
                3:len(script_filename)]
            if (py_type != '.py'):
                script_filename = script_filename + '.py'

            # Write to file
            fp = open(script_filename, mode)
            if (fp.tell() == 0):  # Must be a new file, so include below
                fp.write("#####################################\n")
                fp.write("#                                 #\n")
                fp.write("# Import and Initialize VCS     #\n")
                fp.write("#                             #\n")
                fp.write("#############################\n")
                fp.write("import vcs\n")
                fp.write("v=vcs.init()\n\n")

            unique_name = '__Tm__' + self.name
            fp.write(
                "#----------Marker (Tm) member (attribute) listings ----------\n")
            fp.write("tm_list=v.listelements('marker')\n")
            fp.write("if ('%s' in tm_list):\n" % self.name)
            fp.write("   %s = v.getmarker('%s')\n" % (unique_name, self.name))
            fp.write("else:\n")
            fp.write(
                "   %s = v.createmarker('%s')\n" %
                (unique_name, self.name))
            fp.write("%s.type = %s\n" % (unique_name, self.type))
            fp.write("%s.size = %s\n" % (unique_name, self.size))
            fp.write("%s.color = %s\n\n" % (unique_name, self.color))
            fp.write("%s.priority = %d\n" % (unique_name, self.priority))
            fp.write("%s.viewport = %s\n" % (unique_name, self.viewport))
            fp.write(
                "%s.worldcoordinate = %s\n" %
                (unique_name, self.worldcoordinate))
            fp.write("%s.x = %s\n" % (unique_name, self.x))
            fp.write("%s.y = %s\n" % (unique_name, self.y))
            fp.write("%s.projection = %s\n" % (unique_name, self.projection))
            fp.write(
                "%s.colormap = '%s'\n\n" %
                (unique_name, repr(
                    self.colormap)))
        else:
            # Json type
            mode += "+"
            f = open(script_filename, mode)
            vcs.utils.dumpToJson(self, f)
            f.close()
    script.__doc__ = scriptdocs['marker']
Example #5
0
class Tf(object):
    """The Fillarea class allows the user to edit fillarea attributes, including
    fillarea interior style, style index, and color index.

    This class is used to define an fillarea table entry used in VCS, or it
    can be used to change some or all of the fillarea attributes in an
    existing fillarea table entry.


    .. describe:: Useful Functions:

        .. code-block:: python

            # VCS Canvas Constructor
            a=vcs.init()
            # Show predefined fillarea objects
            a.show('fillarea')
            # Updates the VCS Canvas at user's request
            a.update()

    .. describe:: Create a fillarea object:

        .. code-block:: python

            #Create a VCS Canvas object
            a=vcs.init()

            # Two ways to create a fillarea:

            # Copies content of 'def37' to 'new'ea:
            fa=a.createfillarea('new','def37')
            # Copies content of 'default' to 'new'
            fa=a.createfillarea('new')

    .. describe::  Modify an existing fillarea:

        .. code-block:: python

            fa=a.getfillarea('red')

    * Overview of fillarea attributes:

        * List all the fillarea attribute values

            .. code-block:: python

                fa.list()

        * There are three possibilities for setting the isofill style:

            .. code-block:: python

                fa.style = 'solid'
                fa.style = 'hatch'
                fa.style = 'pattern'

        * Setting index, color, opacity:

            .. code-block:: python

                # Range from 1 to 20
                fa.index=1
                # Range from 1 to 256
                fa.color=100
                # Range from 0 to 100
                fa.opacity=100

        * Setting the graphics priority viewport, worldcoordinate:

            .. code-block:: python

                fa.priority=1
                # FloatType [0,1]x[0,1]
                fa.viewport=[0, 1.0, 0,1.0]
                # FloatType [#,#]x[#,#]
                fa.worldcoordinate=[0,1.0,0,1.0]

        * Setting x and y values:

            .. code-block:: python

                #List of FloatTypes
                fa.x=[[0,.1,.2], [.3,.4,.5]]
                # List of FloatTypes
                fa.y=[[.5,.4,.3], [.2,.1,0]]

        .. pragma: skip-doctest
        """
    __slots__ = [
        'name', 's_name', 'color', 'opacity', 'pixelspacing', 'pixelscale',
        'priority', 'style', 'index', 'viewport', 'worldcoordinate', 'x', 'y',
        'projection', 'colormap', '_name', '_color', '_priority', '_style',
        '_index', '_viewport', '_worldcoordinate', '_x', '_y', '_projection',
        '_colormap', '_opacity', '_pixelspacing', '_pixelscale'
    ]

    colormap = VCS_validation_functions.colormap

    def _getname(self):
        return self._name

    def _setname(self, value):
        value = VCS_validation_functions.checkname(self, 'name', value)
        if value is not None:
            self._name = value

    name = property(_getname, _setname)

    def _getfillareacolors(self):
        return getmember(self, 'color')

    def _setfillareacolors(self, value):
        if isinstance(value, Tf):
            value = value.color
        if isinstance(value, (str, int)):
            value = [
                value,
            ]
        if value is not None:
            value = VCS_validation_functions.checkColorList(
                self, 'color', value)
        else:
            value = [(0.0, 0.0, 0.0, 100.0)]
        self._color = value

    color = property(_getfillareacolors, _setfillareacolors)

    def _getfillareaopacity(self):
        return getmember(self, 'opacity')

    def _setfillareaopacity(self, value):
        if not isinstance(value, (list, tuple)) and value is not None:
            value = [
                value,
            ]
        if value is not None:
            value = VCS_validation_functions.checkOpacitiesList(
                self, 'opacity', value)
        self._opacity = value

    opacity = property(_getfillareaopacity, _setfillareaopacity)

    def _getfillareaindices(self):
        return getmember(self, 'index')

    def _setfillareaindices(self, value):
        if not isinstance(value, (list, tuple)) and value is not None:
            value = [
                value,
            ]
        if value is not None:
            value = VCS_validation_functions.checkIndicesList(
                self, 'index', value)
        if value in [(), []]:
            raise ValueError("You cannot set fillarea index to an empty list")
        self._index = value

    index = property(_getfillareaindices, _setfillareaindices)

    def _getfillareastyle(self):
        return getmember(self, 'style')

    def _setfillareastyle(self, value):
        if isinstance(value, (str, int, Tf)):
            value = [
                value,
            ]
        vals = []
        for v in value:
            v = VCS_validation_functions.checkFillAreaStyle(self, 'style', v)
            vals.append(v)
        if vals == []:
            raise ValueError("fillareastyle cannot be empty list")
        value = vals
        self._style = value

    style = property(_getfillareastyle, _setfillareastyle)

    def _getfillareapixelspacing(self):
        return getmember(self, 'pixelspacing')

    def _setfillareapixelspacing(self, value):
        if value is not None:
            value = VCS_validation_functions.checkListOfNumbers(self,
                                                                'pixelspacing',
                                                                value,
                                                                minelements=2,
                                                                maxelements=2,
                                                                ints=True)
        self._pixelspacing = value

    pixelspacing = property(_getfillareapixelspacing, _setfillareapixelspacing)

    def _getfillareapixelscale(self):
        return getmember(self, 'pixelscale')

    def _setfillareapixelscale(self, value):
        if value is not None:
            value = VCS_validation_functions.checkNumber(
                self, 'pixelscale', value)
        self._pixelscale = value

    pixelscale = property(_getfillareapixelscale, _setfillareapixelscale)

    def _getpriority(self):
        return getmember(self, 'priority')

    def _setpriority(self, value):
        value = VCS_validation_functions.checkInt(self,
                                                  'priority',
                                                  value,
                                                  minvalue=0)
        self._priority = value

    priority = property(_getpriority, _setpriority)

    projection = VCS_validation_functions.projection

    worldcoordinate = VCS_validation_functions.worldcoordinate

    viewport = VCS_validation_functions.viewport

    def _getx(self):
        return getmember(self, 'x')

    def _setx(self, value):
        if value is None:
            self._x = value
            return
        if not isinstance(value, (list, tuple)):
            raise ValueError('x must be a tuple or list of values.')
        try:
            # first we'll see if it is simply a list of values
            value = VCS_validation_functions.checkListOfNumbers(
                self, 'x', value)
        except:
            # ok it was not, so it maybe a list of list of numbers ?
            val = []
            for v in value:
                tmp = VCS_validation_functions.checkListOfNumbers(self, 'x', v)
                val.append(tmp)
            value = val
        self._x = value

    x = property(_getx, _setx)

    def _gety(self):
        return getmember(self, 'y')

    def _sety(self, value):
        if value is None:
            self._y = None
            return
        if not isinstance(value, (list, tuple)):
            raise ValueError('y must be a tuple or list of values.')
        try:
            # first we'll see if it is simply a list of values
            value = VCS_validation_functions.checkListOfNumbers(
                self, 'y', value)
        except:
            # ok it was not, so it maybe a list of list of numbers ?
            val = []
            for v in value:
                tmp = VCS_validation_functions.checkListOfNumbers(self, 'y', v)
                val.append(tmp)
            value = val
        self._y = value

    y = property(_gety, _sety)

    #
    #
    # Initialize the fillarea attributes.                                       #
    #
    #
    def __init__(self, Tf_name=None, Tf_name_src='default'):
        #
        #
        # Initialize the fillarea class and its members           #
        # The getTfmember function retrieves the values of the    #
        # fillarea members in the C structure and passes back the #
        # appropriate Python Object.                              #
        #
        #
        if isinstance(Tf_name_src, Tf):
            Tf_name_src = Tf_name_src.name
        if Tf_name_src != "default" and Tf_name_src not in vcs.elements[
                "fillarea"].keys():
            raise ValueError("Fillarea '%s' does not exists" % Tf_name_src)
        if (Tf_name is None):
            raise ValueError('Must provide a fillarea name.')
        else:
            if Tf_name in vcs.elements["fillarea"].keys():
                raise ValueError(
                    "The fillarea '%s' already exists, use getfillarea instead"
                    % Tf_name)
        self._name = Tf_name
        self.s_name = 'Tf'

        if Tf_name == "default":
            self._style = [
                'solid',
            ]
            self._index = [
                1,
            ]
            self._color = [
                1,
            ]
            self._opacity = []
            self._pixelspacing = None
            self._pixelscale = None
            self._priority = 1
            self._viewport = [0., 1., 0., 1.]
            self._worldcoordinate = [0., 1., 0., 1.]
            self._x = None
            self._y = None
            self._projection = "default"
            self._colormap = None
        else:
            src = vcs.elements["fillarea"][Tf_name_src]
            self.style = src.style
            self.index = src.index
            self.color = src.color
            self.opacity = src.opacity
            self.pixelspacing = src.pixelspacing
            self.pixelscale = src.pixelscale
            self.priority = src.priority
            self.viewport = src.viewport
            self.worldcoordinate = src.worldcoordinate
            self.x = src.x
            self.y = src.y
            self.projection = src.projection
            self.colormap = src.colormap

        vcs.elements["fillarea"][Tf_name] = self

    #
    #
    # Fillarea out line members (attributes).                                   #
    #
    #
    def list(self):
        if (self.name == '__removed_from_VCS__'):
            raise ValueError('This instance has been removed from VCS.')
        print "---------- Fillarea (Tf) member (attribute) listings ----------"
        print "secondary method =", self.s_name
        print "name =", self.name
        print "style =", self.style
        print "index =", self.index
        print "color =", self.color
        print "opacity =", self.opacity
        print "pixelspacing =", self.pixelspacing
        print "pixelscale =", self.pixelscale
        print "priority =", self.priority
        print "viewport =", self.viewport
        print "worldcoordinate =", self.worldcoordinate
        print "x =", self.x
        print "y =", self.y
        print "projection =", self.projection
        print "colormap =", self.colormap

    list.__doc__ = listdoc.format(name="fillarea", parent="")

    #
    #
    # Script out secondary fillarea method in VCS to a file.                    #
    #
    #
    def script(self, script_filename=None, mode=None):
        if (script_filename is None):
            raise ValueError(
                'Error - Must provide an output script file name.')

        if (mode is None):
            mode = 'a'
        elif (mode not in ('w', 'a')):
            raise ValueError(
                'Error - Mode can only be "w" for replace or "a" for append.')

        # By default, save file in json
        scr_type = script_filename.split(".")
        if len(scr_type) == 1 or len(scr_type[-1]) > 5:
            scr_type = "json"
            if script_filename != "initial.attributes":
                script_filename += ".json"
        else:
            scr_type = scr_type[-1]
        if scr_type == '.scr':
            raise DeprecationWarning("scr script are no longer generated")
        elif scr_type == "py":
            mode = mode + '+'
            py_type = script_filename[len(script_filename) -
                                      3:len(script_filename)]
            if (py_type != '.py'):
                script_filename = script_filename + '.py'

            # Write to file
            fp = open(script_filename, mode)
            if (fp.tell() == 0):  # Must be a new file, so include below
                fp.write("#####################################\n")
                fp.write("#                                 #\n")
                fp.write("# Import and Initialize VCS     #\n")
                fp.write("#                             #\n")
                fp.write("#############################\n")
                fp.write("import vcs\n")
                fp.write("v=vcs.init()\n\n")

            unique_name = '__Tf__' + self.name
            fp.write(
                "#----------Fillarea (Tf) member (attribute) listings ----------\n"
            )
            fp.write("tf_list=v.listelements('fillarea')\n")
            fp.write("if ('%s' in tf_list):\n" % self.name)
            fp.write("   %s = v.getfillarea('%s')\n" %
                     (unique_name, self.name))
            fp.write("else:\n")
            fp.write("   %s = v.createfillarea('%s')\n" %
                     (unique_name, self.name))
            fp.write("%s.style = %s\n" % (unique_name, self.style))
            fp.write("%s.index = %s\n" % (unique_name, self.index))
            fp.write("%s.color = %s\n\n" % (unique_name, self.color))
            fp.write("%s.opacity = %s\n\n" % (unique_name, self.opacity))
            fp.write("%s.pixelspacing = %s\n\n" %
                     (unique_name, self.pixelspacing))
            fp.write("%s.pixelscale = %s\n\n" % (unique_name, self.pixelscale))
            fp.write("%s.priority = %d\n" % (unique_name, self.priority))
            fp.write("%s.viewport = %s\n" % (unique_name, self.viewport))
            fp.write("%s.worldcoordinate = %s\n" %
                     (unique_name, self.worldcoordinate))
            fp.write("%s.x = %s\n" % (unique_name, self.x))
            fp.write("%s.y = %s\n\n" % (unique_name, self.y))
            fp.write("%s.projection = %s\n\n" % (unique_name, self.projection))
            fp.write("%s.colormap = %s\n\n" %
                     (unique_name, repr(self.colormap)))
        else:
            # Json type
            mode += "+"
            f = open(script_filename, mode)
            vcs.utils.dumpToJson(self, f)
            f.close()

    script.__doc__ = scriptdocs['fillarea']
Example #6
0
class Tt(object):
    """
    The (Tt) Text Table lists text attribute set names that define the font, spacing,
    expansion, and color index.

    This class is used to define an text table table entry used in VCS, or it
    can be used to change some or all of the text table attributes in an
    existing text table table entry.

    .. describe:: Useful Functions:

        .. code-block:: python

            # VCS Canvas Constructor
            a=vcs.init()
            # Show predefined text table objects
            a.show('texttable')
            # Updates the VCS Canvas at user's request
            a.update()

    .. describe:: Make a Canvas object to work with:

        .. code-block:: python

            a=vcs.init()

    .. describe:: Create a new instance of text table:

        .. code-block:: python

            # Copies content of 'std' to 'new'
            tt=a.createtexttable('new','std')
            # Copies content of 'default' to 'new'
            tt=a.createtexttable('new')

    .. describe:: Modify an existing texttable:

        .. code-block:: python

            tt=a.gettexttable('std')

    .. describe:: Overview of texttable attributes:

        * Listing attributes:

            .. code-block:: python

                # Will list all the texttable attribute values
                tt.list()

        * Specify the text font type:

            .. code-block:: python

                # The font value must be in the range 1 to 9
                tt.font=1

        * Specify the text spacing:

            .. code-block:: python

                # The spacing value must be in the range -50 to 50
                tt.spacing=2

        * Specify the text expansion:

            .. code-block:: python

                # The expansion value must be in the range 50 to 150
                tt.expansion=100

        * Specify the text color:

            .. code-block:: python

            # The text color attribute value must be in the range 1 to 257
            tt.color=241

        * Specify the text background color and opacity:

            .. code-block:: python

                # The text backgroundcolor attribute value must be in the range 1 to 257
                tt.backgroundcolor=241
                # The text backgroundopacity attribute value must be in the range 0 to 100
                tt.backgroundopacity=0
                # Set the graphics priority on the canvas
                tt.priority=1
                # FloatType [0,1]x[0,1]
                tt.viewport=[0, 1.0, 0,1.0]
                # FloatType [#,#]x[#,#]
                tt.worldcoordinate=[0,1.0,0,1.0]
                # List of FloatTypes
                tt.x=[[0,.1,.2], [.3,.4,.5]]
                # List of FloatTypes
                tt.y=[[.5,.4,.3], [.2,.1,0]]

    .. pragma: skip-doctest TODO: convert examples to doctests
    """
    __slots__ = [
        's_name',
        'name',
        'color',
        'backgroundcolor',
        'backgroundopacity',
        'fillincolor',
        'priority',
        'font',
        'string',
        'spacing',
        'expansion',
        'viewport',
        'worldcoordinate',
        'x',
        'y',
        'projection',
        'colormap',
        '_name',
        '_color',
        '_backgroundcolor',
        '_backgroundopacity',
        '_fillincolor',
        '_priority',
        '_font',
        '_string',
        '_spacing',
        '_expansion',
        '_viewport',
        '_worldcoordinate',
        '_x',
        '_y',
        '_projection',
        '_colormap',
    ]
    colormap = VCS_validation_functions.colormap

    def _getname(self):
        return self._name

    def _setname(self, value):
        value = VCS_validation_functions.checkname(self, 'name', value)
        if value is not None:
            self._name = value

    name = property(_getname, _setname)

    def _getcolor(self):
        return self._color

    def _setcolor(self, value):
        if value is not None:
            value = VCS_validation_functions.checkColor(self, 'color', value)
        self._color = value

    color = property(_getcolor, _setcolor)

    def _getbackgroundcolor(self):
        return self._backgroundcolor

    def _setbackgroundcolor(self, value):
        if value is not None:
            value = VCS_validation_functions.checkColor(
                self, 'backgroundcolor', value)
        self._backgroundcolor = value

    backgroundcolor = property(_getbackgroundcolor, _setbackgroundcolor)

    def _getbackgroundopacity(self):
        return self._backgroundopacity

    def _setbackgroundopacity(self, value):
        if value is not None:
            value = VCS_validation_functions.checkOpacity(
                self, 'backgroundopacity', value)
            self._backgroundopacity = value

    backgroundopacity = property(_getbackgroundopacity, _setbackgroundopacity)

    def _getfillincolor(self):
        return self._fillincolor

    def _setfillincolor(self, value):
        if value is not None:
            value = VCS_validation_functions.checkColor(
                self, 'fillincolor', value)
        self._fillincolor = value

    fillincolor = property(_getfillincolor, _setfillincolor)

    def _getspacing(self):
        return self._spacing

    def _setspacing(self, value):
        self._spacing = VCS_validation_functions.checkInt(self,
                                                          'spacing',
                                                          value,
                                                          minvalue=-50,
                                                          maxvalue=50)

    spacing = property(_getspacing, _setspacing)

    def _getexpansion(self):
        return self._expansion

    def _setexpansion(self, value):
        self._expansion = VCS_validation_functions.checkInt(self,
                                                            'expansion',
                                                            value,
                                                            minvalue=50,
                                                            maxvalue=150)

    expansion = property(_getexpansion, _setexpansion)

    def _getfont(self):
        return self._font

    def _setfont(self, value):
        self._font = VCS_validation_functions.checkFont(self, 'font', value)

    font = property(_getfont, _setfont)

    def _getstring(self):
        return self._string

    def _setstring(self, value):
        if isinstance(value, str):
            value = [
                value,
            ]
        elif isinstance(value, (list, tuple)):
            vals = []
            for v in value:
                vals.append(str(v))
            value = vals
        else:
            raise ValueError('Must be a string or a list of strings.')
        self._string = value

    string = property(_getstring, _setstring)

    def _getpriority(self):
        return self._priority

    def _setpriority(self, value):
        self._priority = VCS_validation_functions.checkInt(self,
                                                           'priority',
                                                           value,
                                                           minvalue=0)

    priority = property(_getpriority, _setpriority)

    def _getprojection(self):
        return self._projection

    def _setprojection(self, value):
        self._projection = VCS_validation_functions.checkProjection(
            self, 'projection', value)

    projection = property(_getprojection, _setprojection)

    def _getwc(self):
        return self._worldcoordinate

    def _setwc(self, value):
        self._worldcoordinate = VCS_validation_functions.checkListOfNumbers(
            self, 'worldcoordinate', value, maxelements=4)

    worldcoordinate = property(_getwc, _setwc)

    def _getvp(self):
        return self._viewport

    def _setvp(self, value):
        self._viewport = VCS_validation_functions.checkListOfNumbers(
            self, 'viewport', value, maxelements=4, minvalue=0., maxvalue=1.)

    viewport = property(_getvp, _setvp)

    def _getx(self):
        return self._x

    def _setx(self, value):
        if value is None:
            self._x = None
            return
        if isinstance(value, (int, float)):
            value = [
                value,
            ]
        if not isinstance(value, (list, tuple)):
            raise ValueError('%s must be a tuple or list of values.')
        try:
            # first we'll see if it is simply a list of values
            value = VCS_validation_functions.checkListOfNumbers(
                self, 'x', value)
        except:
            # ok it was not, so it maybe a list of list of numbers ?
            val = []
            for v in value:
                tmp = VCS_validation_functions.checkListOfNumbers(self, 'x', v)
                val.append(tmp)
            value = val
        self._x = value

    x = property(_getx, _setx)

    def _gety(self):
        return self._y

    def _sety(self, value):
        if value is None:
            self._y = None
            return
        if isinstance(value, (int, float)):
            value = [
                value,
            ]
        if not isinstance(value, (list, tuple)):
            raise ValueError('%s must be a tuple or list of values.')
        try:
            # first we'll see if it is simply a list of values
            value = VCS_validation_functions.checkListOfNumbers(
                self, 'x', value)
        except:
            # ok it was not, so it maybe a list of list of numbers ?
            val = []
            for v in value:
                tmp = VCS_validation_functions.checkListOfNumbers(self, 'x', v)
                val.append(tmp)
            value = val
        self._y = value

    y = property(_gety, _sety)

    ##########################################################################
    #                                                                           #
    # Initialize the text table attributes.                                     #
    #                                                                           #
    ##########################################################################
    def __init__(self, Tt_name=None, Tt_name_src='default'):
        #                                                           #
        #############################################################
        # Initialize the text table class and its members           #
        #                                                           #
        # The getTtmember function retrieves the values of the      #
        # text table members in the C structure and passes back the #
        # appropriate Python Object.                                #
        #############################################################
        #                                                           #
        if (Tt_name is None):
            raise ValueError('Must provide a text table name.')
        if Tt_name in vcs.elements["texttable"].keys():
            raise ValueError("texttable '%s' already exists" % Tt_name)
        self._name = Tt_name
        self.s_name = 'Tt'
        if Tt_name == "default":
            self._string = ""
            self._font = 1
            self._spacing = 2
            self._expansion = 100
            self._color = (0., 0., 0., 100.)
            self._backgroundcolor = (100., 100., 100., 0.)
            self._backgroundopacity = 0
            self._fillincolor = 0
            self._priority = 1
            self._viewport = [0.0, 1.0, 0.0, 1.0]
            self._worldcoordinate = [0.0, 1.0, 0.0, 1.0]
            self._x = None
            self._y = None
            self._projection = "default"
            self._colormap = None
        else:
            if isinstance(Tt_name_src, Tt):
                Tt_name_src = Tt_name_src.name
            if Tt_name_src not in vcs.elements["texttable"].keys():
                raise ValueError("Source texttable: '%s' does not exists" %
                                 Tt_name_src)
            src = vcs.elements["texttable"][Tt_name_src]
            self.string = src.string
            self.font = src.font
            self.spacing = src.spacing
            self.expansion = src.expansion
            self.color = src.color
            self.backgroundcolor = src.backgroundcolor
            self.backgroundopacity = src.backgroundopacity
            self.fillincolor = src.fillincolor
            self.priority = src.priority
            self.viewport = src.viewport
            self.worldcoordinate = src.worldcoordinate
            self.x = src.x
            self.y = src.y
            self.projection = src.projection
            self.colormap = src.colormap
        vcs.elements["texttable"][Tt_name] = self

    ##########################################################################
    #                                                                           #
    # List out text table members (attributes).                                 #
    #                                                                           #
    ##########################################################################
    def list(self):
        if (self.name == '__removed_from_VCS__'):
            raise ValueError('This instance has been removed from VCS.')
        print "---------- Text Table (Tt) member (attribute) listings ----------"
        print "secondary method =", self.s_name
        print "name =", self.name
        print "string =", self.string
        print "font =", self.font
        print "spacing =", self.spacing
        print "expansion =", self.expansion
        print "color =", self.color
        print "backgroundcolor =", self.backgroundcolor
        print "backgroundopacity =", self.backgroundopacity
        print "fillincolor =", self.fillincolor
        print "priority =", self.priority
        print "viewport =", self.viewport
        print "worldcoordinate =", self.worldcoordinate
        print "x =", self.x
        print "y =", self.y
        print 'colormap =', self.colormap

    list.__doc__ = listdoc.format(name="texttable", parent="")

    ##########################################################################
    #                                                                           #
    # Script out secondary text table method in VCS to a file.                  #
    #                                                                           #
    ##########################################################################
    def script(self, script_filename=None, mode=None):
        if (script_filename is None):
            raise ValueError(
                'Error - Must provide an output script file name.')

        if (mode is None):
            mode = 'a'
        elif (mode not in ('w', 'a')):
            raise ValueError(
                'Error - Mode can only be "w" for replace or "a" for append.')

        # By default, save file in json
        scr_type = script_filename.split(".")
        if len(scr_type) == 1 or len(scr_type[-1]) > 5:
            scr_type = "json"
            if script_filename != "initial.attributes":
                script_filename += ".json"
        else:
            scr_type = scr_type[-1]
        if scr_type == '.scr':
            raise DeprecationWarning("scr script are no longer generated")
        elif scr_type == "py":
            mode = mode + '+'
            py_type = script_filename[len(script_filename) -
                                      3:len(script_filename)]
            if (py_type != '.py'):
                script_filename = script_filename + '.py'

            # Write to file
            fp = open(script_filename, mode)
            if (fp.tell() == 0):  # Must be a new file, so include below
                fp.write("#####################################\n")
                fp.write("#                                 #\n")
                fp.write("# Import and Initialize VCS     #\n")
                fp.write("#                             #\n")
                fp.write("#############################\n")
                fp.write("import vcs\n")
                fp.write("v=vcs.init()\n\n")

            unique_name = '__Tt__' + self.name
            fp.write(
                "#----------Text Table (Tt) member (attribute) listings ----------\n"
            )
            fp.write("tt_list=v.listelements('texttable')\n")
            fp.write("if ('%s' in tt_list):\n" % self.name)
            fp.write("   %s = v.gettexttable('%s')\n" %
                     (unique_name, self.name))
            fp.write("else:\n")
            fp.write("   %s = v.createtexttable('%s')\n" %
                     (unique_name, self.name))
            fp.write("%s.font = %g\n" % (unique_name, self.font))
            fp.write("%s.spacing = %g\n" % (unique_name, self.spacing))
            fp.write("%s.expansion = %g\n" % (unique_name, self.expansion))
            fp.write("%s.color = %g\n\n" % (unique_name, self.color))
            fp.write("%s.backgroundcolor = %g\n\n" %
                     (unique_name, self.backgroundcolor))
            fp.write("%s.backgroundopacity = %g\n\n" %
                     (unique_name, self.backgroundopacity))
            fp.write("%s.fillincolor = %g\n\n" %
                     (unique_name, self.fillincolor))
            fp.write("%s.priority = %d\n" % (unique_name, self.priority))
            fp.write("%s.viewport = %s\n" % (unique_name, self.viewport))
            fp.write("%s.worldcoordinate = %s\n" %
                     (unique_name, self.worldcoordinate))
            fp.write("%s.x = %s\n" % (unique_name, self.x))
            fp.write("%s.y = %s\n\n" % (unique_name, self.y))
            fp.write("%s.projection = %s\n\n" % (unique_name, self.projection))
            fp.write("%s.colormap = '%s'\n\n" %
                     (unique_name, repr(self.colormap)))
        else:
            # Json type
            mode += "+"
            f = open(script_filename, mode)
            vcs.utils.dumpToJson(self, f)
            f.close()

    script.__doc__ = scriptdocs['texttable']