On 11/01/2012 10:26 AM, Jason Grout wrote:
> 
> Here's a conversation about this:
> 
> https://groups.google.com/forum/?fromgroups=#!searchin/sage-support/Is$20there$20an$20efficient$20method$20of$20producing$20indexed$20variables?/sage-support/qj8q21wr7-0/Qs-Qxr8A0dAJ
> 
> In particular, this is a nice solution:
> 
> class SymbolicVariables(SageObject):
>      def __init__(self, prefix='x'):
>          self._prefix = prefix
>      def __getitem__(self, i):
>          return var("%s%s"%(self._prefix, i))
> 
> 
> a = SymbolicVariables('a')
> sum(a[i]*x^i for i in range(3))
> 
> would give a2*x^2 + a1*x + a0
> 

I need to do this a lot. We already have SR.symbol(), does anyone think
it would make sense to have this available as SR.symbols()?

Here's my first shot at it. I could clean it up and add more examples.


class SymbolCollection:
    """
    An indexed collection of symbolic variables.

    INPUT:

      - ``prefix`` -- The string with which to prefix the symbol
        names.

      - ``latex_prefix`` -- An optional latex expression (string) to
        use instead of `prefix` when converting the symbols to latex.

      - ``domain`` -- A string representing the domain of the symbol,
        either 'real', 'complex', or 'positive'.

    OUTPUT:

    An object which supports indexing. Each index references a
    particular symbolic variable.

    EXAMPLES:

    Create coefficients for polynomials of arbitrary degree::

        sage: a = SymbolCollection('a')
        sage: p = sum([ a[i]*x^i for i in range(0,5)])
        sage: p
        a4*x^4 + a3*x^3 + a2*x^2 + a1*x + a0

    Using a different latex name since 'lambda' is reserved::

        sage: l = SymbolCollection('l', '\lambda')
        sage: l[0]
        l0
        sage: latex(l[0])
        $\lambda_{0}$

    TESTS:

    We shouldn't overwrite variables in the global namespace::

        sage: a = SymbolCollection('a')
        sage: a0 = 4
        sage: a[0]
        a0
        sage: a0
        4

    The symbol at a given index should always be the same, even when
    the symbols themselves are unnamed. We store the string
    representation and compare because the output is unpredictable::

        sage: a = SymbolCollection()
        sage: a0str = str(a[0])
        sage: str(a[0]) == a0str
        True

    """

    def __init__(self, prefix=None, latex_prefix=None, domain=None):
        # We store a dict of already-created symbols so that we don't
        # recreate a symbol which already exists. This is especially
        # helpful when using unnamed variables, if you want e.g. a[0]
        # to return the same variable each time.
        self._symbols = {}

        self._prefix = prefix

        if latex_prefix is None:
            # Note: this can set the latex_prefix to None, so we check
            # this condition later.
            self._latex_prefix = prefix
        else:
            # Strip latex math-mode delimiters, since we'll add them
            # ourselves later.
            self._latex_prefix = latex_prefix.strip('$')

        self._domain = domain


    def create_symbol(self, i):
        if self._prefix is None:
            # Allow creating unnamed symbols, for consistency with
            # SR.symbol().
            name = None
        else:
            name = '%s%d' % (self._prefix, i)

        if self._latex_prefix is None:
            latex_name = None
        else:
            latex_name = r'$%s_{%d}$' % (self._latex_prefix, i)

        return SR.symbol(name, latex_name, self._domain)


    def __getitem__(self, i):
        if i < 0:
            # Cowardly refuse to create a variable named "a-1".
            raise IndexError('Index must be nonnegative')

        try:
            return self._symbols[i]
        except KeyError:
            self._symbols[i] = self.create_symbol(i)
            return self._symbols[i]

-- 
You received this message because you are subscribed to the Google Groups 
"sage-support" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
Visit this group at http://groups.google.com/group/sage-support?hl=en.


Reply via email to