Sunday, August 22, 2010

Drawing equations with Curveplot using R

You can generate plots for up to 6 equations using our http://extreme.adorio-research.org/solvers/rplotpage/curve/
The graphs can be generated separately or together in a composite graph.
Here is an example of the basic hyperbolic functions plotted together.


This is the solver page with the settings for the composite graph above.



Doubtless this solver needs much improvement. For example, the lines are too thin! and the grid (there is ?!) is drawn also thinly. To remind the solver page writer, we include the source code
so that other people using QP/QPY may make constructive comments.

# file      curve.qpy
# 2006.09.02   0.0.1  first version
# 2006.09.20   0.0.2  split from pie, dot page.
# 2010.08.22   0.0.3  added checkboxes.

__file__    = curve.qpy
__version__ = "0.0.2"
__date__    = "2006.09.20"
__author__  = "ernesto.adorio@gmail.com
__title__   = "XY Equation Curve plots using R"
__catalog__ = "CURVE-RPLOT-0125"
__url__     = "/solvers/rplotpage/curve"

import time
import tempfile
import commands
import os

from   qp.fill.directory  import Directory
from   qp.fill.form       import Form, StringWidget, TextWidget,CheckboxWidget,SingleSelectWidget
from   qp.fill.css   import BASIC_FORM_CSS

from   qp.sites.extreme.lib.tmpfilesmanager import TmpFilesManager
from   qp.sites.extreme.lib.uicommon        import renderheader, renderfooter, processheader, processfooter
from   qp.pub.common                        import page
from   qp.sites.extreme.lib.checkinput      import checkInputs, getFormStrings
from   qp.sites.extreme.lib.qpyutils        import printRlines, showLogo
from   qp.sites.extreme.lib.webutils        import vecRead, GraphicsFile, as_R_cvector, as_R_vector, as_R_matrix
from   qp.sites.extreme.lib import config
import qp.sites.extreme.lib.checkinput as check

_MAXEQN  = 6

def Solve(fields):
    
    # Buildup the R code.
    Rcode = 'source("%s")\n'  % (config.lib_dir + "/mylib.R",)
    (gX, gY, splitq, legendQ, bty, ptype, draweqnQ, eqn, xlo,  xhi, ylo, yhi,  n, col, main, xlab, ylab) = fields

    if splitq == "True":
        splitq = True
    else:
        splitq   = False

    legend = ""
    fname  = ""
    for i in range(_MAXEQN):
        if draweqnQ[i] is True:
           eqni = str(eqn[i]).strip(str(" "))
           if len(eqni) > 0:
              xlow  = float(xlo[i])
              xhigh = float(xhi[i])
    
       ylim  = ",ylim=%s" % as_R_vector([ylo[i], yhi[i]])

              nx    = int(n[i])
              if xhigh <= xlow:
                  return "ERROR: (xhi[%s] = %s) < (xlow[%s] = %s)" % (i, xhigh, i, xlow)
       plottype = ptype[i]

              if splitq:
                 
                 fname    = GraphicsFile("png")
                 barefile = fname.split(str("/")) [-1]
                 Rcode += """png('%s',width=%s*72,height=%s*72)\n""" % (fname, gX, gY)

                 if main[i] != "":
                   mainlabel = ',main="%s"' % main[i]
                 else:
                   mainlabel = ''

                 if xlab[i] != "":
                    xlabel = ',xlab="%s"' % xlab[i]
                 else:
                   xlabel = ''

                 if ylab[i] != "":
                   ylabel = ',ylab="%s"' % ylab[i]
                 else:
                   ylabel = ''

                 Rcode += """
curve(%s,from=%s,to=%s,n=%s, col="%s", type="%s" %s %s %s %s)
grid(col="darkgray")
dev.off()
#img %s
"""            % (eqni, xlo[i], xhi[i], nx, col[i], plottype, ylim, mainlabel, xlabel, ylabel, barefile)
                 TmpFilesManager().add(fname)

                 fname    = GraphicsFile("png")
                 barefile = fname.split(str("/")) [-1]
       # Single plot.     
              else:
                  if i > 0:
                     add = ",add=TRUE"
                  else:
                     add = ""
                  if fname == "":
                    fname    = GraphicsFile("png")
                    barefile = fname.split(str("/")) [-1]
                    Rcode += """png('%s',width=%s*72,height=%s*72)\n""" % (fname, gX, gY)
                    title = ',main="%s"' % main[i]
                    Rcode += """
curve(%s,from=%s,to=%s,n=%s, ylim=c(%s, %s), col="%s", type="%s", xlab="%s", ylab="%s", main="%s")
"""               % (eqni, xlo[i], xhi[i], n[i], ylo[i], yhi[i], col[i], plottype, xlab[i], ylab[i], main[i])
                  else:
                    Rcode += """
curve(%s,from=%s,to=%s,n=%s, ylim=c(%s, %s), col="%s", type="%s" %s)
"""               % (eqni, xlo[i], xhi[i], n[i], ylo[i], yhi[i], col[i], plottype,  add)
 
                  if legend == "":
                     legend="c(\"%s\"" % ylab[i]
                     legendcol= "c(\"%s\"" % col[i]
                  else:
                     legend    += ",\"%s\"" % ylab[i]
                     legendcol += ",\"%s\"" % col[i]
    if not splitq:
        if legendQ :
           Rcode += 'legend("%s", legend=%s), col=%s), lty=1,bty="%s")' % \
                         (legendQ, legend, legendcol,  bty)

    if not splitq:
        Rcode += """
grid()
#img %s""" % barefile
        TmpFilesManager().add(fname)
            
    # Write to temporary file.
    try:
       (f, name) = tempfile.mkstemp(suffix=str(".r"), prefix=str("tmp"), dir= config.tmp_dir)
       os.write(f, str(Rcode))
       (status, output) = commands.getstatusoutput(str("R -q --no-save < %s")  % name)
       os.close(f)   # auto delete.
    except:
        output = str(Rcode) + "\nError: evaluation error in R" 
    return output


class CurveplotPage(Directory):
    def get_exports(self):
        yield ('', 'index', 'xycurveplot', '')
           

    def index[html](self):
        form  = Form(enctype="multipart/form-data")  # enctype for file upload
        form.add(StringWidget, name = "gX",  title = "gX", value = "4", size =2)
        form.add(StringWidget, name = "gY",  title = "gY", value = "4", size =2)

        form.add(SingleSelectWidget, name = "splitq",
                 title = "graphs?",
                 value = "True",
                  options = [("True",  "Separate"),
                            ("False", "Single")
                           ]
                )

        form.add(SingleSelectWidget, name = "legendQ",
                 title = "Legend",
                 value = "",
                 options = [("",          "None"),
                            ("topright",  "topright"),
                            ("top",       "top"),
                            ("topleft",   "topleft"),
                            ("right",     "right"),
                            ("center",    "center"),
                            ("left",      "left"),
                            ("bottomright", "bottomright"),
                            ("bottom",    "bottom"),
                            ("bottomleft","bottomleft"),
                           ]
                )

        form.add(SingleSelectWidget, name = "bty",
                 title   = "Box",
                 value   = "o",
                 options = [("o", "o"),  ("n", "n")] 
                )

        form.add(StringWidget, name = "ptype", title="Plot Type", value="llllll", size = 4)
        for i in range(6):
            form.add(CheckboxWidget, name="eqn%sdrawQ" %i, value=False)        


        eqns = ["sin(x)", "cos(x)", "tan(x)", "sinh(x)", "cosh(x)", "tanh(x)"]
        cols = ["blue",   "red",    "black", "violet", "green", "violet"]
        for i in range(_MAXEQN):
            form.add(StringWidget,  name = "eqn%d" %i, title = "", value = "%s" % eqns[i], size = 32)
            form.add(StringWidget,  name = "xlo%d" %i, title = "", value = -10, size = 3)
            form.add(StringWidget,  name = "xhi%d" %i, title = "", value = 10,  size = 3)
            form.add(StringWidget,  name = "ylo%d" %i, title = "", value = -10, size = 3)
            form.add(StringWidget,  name = "yhi%d" %i, title = "", value = 10,  size = 3)
            form.add(StringWidget,  name = "main%d" %i, title = "", value = "Title%s" % (i+1), size = 5)
            form.add(StringWidget,  name = "xlab%d" %i, title = "", value = "X%s" % (i+1), size = 5)
            form.add(StringWidget,  name = "ylab%d" %i, title = "", value = "Y%s" % (i+1), size = 5)
            form.add(StringWidget,  name = "n%d"   %i, title = "", value = 100, size = 3)
            form.add(StringWidget,  name = "col%d" %i, title = "", value = "%s" % cols[i], size = 4)
        form.add_hidden("time",   value = time.time())
        form.add_submit("submit", "submit")

        def render [html] ():
            renderheader(__title__)

            """
            
%s%s%s%s%s%s
""" % (form.get_widget("gX").render(), form.get_widget("gY").render(), form.get_widget("splitq").render(), form.get_widget("legendQ").render(), form.get_widget("bty").render(), form.get_widget("ptype").render(), ) "" " " for i in range(_MAXEQN): """ \n""" % \ (form.get_widget("eqn%sdrawQ" %i).render(), form.get_widget("eqn%d" % i).render(), form.get_widget("xlo%d" % i).render(), form.get_widget("xhi%d" % i).render(), form.get_widget("ylo%d" % i).render(), form.get_widget("yhi%d" % i).render(), form.get_widget("n%d" % i).render(), form.get_widget("col%d" % i).render(), form.get_widget("main%d" %i).render(), form.get_widget("xlab%d" %i).render(), form.get_widget("ylab%d" %i).render(), ) "
draw?Equationxloxhiyloyhincolormainxlabylab
%s %s %s %s %s %s %s %s %s %s %s
" """ This page enables you to plot up to 6 equations either in separate graphs or in a single composite graph. For the latter, the title is obtained from the main title of the first equation to be plotted. """ renderfooter(form, __version__, __catalog__, __author__) if not form.is_submitted(): return page('curveplotpage', render(), style= BASIC_FORM_CSS) def process [html] (): processheader(__title__) calctime_start = time.time() # Get form strings. (gX,gY,splitq,legendQ,bty,ptype)= check.getFormStrings(form,["gX","gY","splitq","legendQ","bty","ptype"]) gX = str(min(int(gX), 10)) gy = str(min(int(gY), 10)) # Get the equations and their parameters. draweqnQ = [True] * _MAXEQN eqn = ["" for i in range(_MAXEQN)] xlo = ["" for i in range(_MAXEQN)] xhi = ["" for i in range(_MAXEQN)] ylo = ["" for i in range(_MAXEQN)] yhi = ["" for i in range(_MAXEQN)] main =["" for i in range(_MAXEQN)] xlab =["" for i in range(_MAXEQN)] ylab =["" for i in range(_MAXEQN)] n = ["" for i in range(_MAXEQN)] col = ["" for i in range(_MAXEQN)] for i in range(_MAXEQN): draweqnQ[i] = drawQ = form.get("eqn%sdrawQ" % i) if drawQ: eqn[i] = str(form.get("eqn%d" % i)) xlo[i] = str(form.get("xlo%d" % i)) xhi[i] = str(form.get("xhi%d" % i)) ylo[i] = str(form.get("ylo%d" % i)) yhi[i] = str(form.get("yhi%d" % i)) n[i] = str(form.get("n%d" % i)) col[i] = str(form.get("col%d" % i)) if col[i] == "None": col[i] = "" main[i] = str(form.get("main%d" % i)) if main[i] == "None": main[i] = "" xlab[i] = str(form.get("xlab%d" % i)) if xlab[i] == "None": xlab[i] = "" ylab[i] = str(form.get("ylab%d" % i)) if ylab[i] == "None": ylab[i] = "" # Check ptype: ptype = str(ptype).replace(str(" "), str("")) if len(ptype) == 0: ptype="llllll" elif len(ptype) == 1: ptype = ptype * _MAXEQN output = Solve((gX,gY,splitq,legendQ,bty,ptype,draweqnQ, eqn,xlo,xhi,ylo,yhi,n,col,main,xlab,ylab)) "
"
          printRlines(output)
          "
" """
Powered by
""" showLogo("Rlogo.jpg") processfooter(form, calctime_start, "./", __url__) process()

Also, the server and the developer's own laptop has problems with locales. Seem Ubuntu is infected with this bug.


0001 During startup - Warning messages:
0002 1: Setting LC_CTYPE failed, using "C"
0003 2: Setting LC_COLLATE failed, using "C"
0004 3: Setting LC_TIME failed, using "C"
0005 4: Setting LC_MESSAGES failed, using "C"
0006 5: Setting LC_PAPER failed, using "C"
0007 6: Setting LC_MEASUREMENT failed, using "C"

No comments:

Post a Comment