Ejemplo n.º 1
0
def load_mech_design(equation, dbSession=None, unit=None):
    sys.path.append(os.path.abspath('../../../'))  #server root
    sys.path.append(os.path.abspath('../../'))  #apps path
    from ServerSettings import get_server_setting
    from ServerSettings import db, Session
    from re import findall, compile
    if not dbSession:
        from sqlalchemy.orm import sessionmaker
        DbSession = sessionmaker(db)
        dbSession = DbSession()
    mechDrawings = list()
    if isinstance(equation, (int, str)):
        equationId = int(equation)
        equation = dbSession.query(ModelCloudMath.EquationStorage).filter(
            ModelCloudMath.EquationStorage.number == equationId).first()
    elif isinstance(equation, ModelCloudMath.EquationStorage):
        equationId = int(equation.number)
    searchStr = '%d_*.mech' % equationId
    files = glob.glob(
        os.path.join(get_server_setting('mechdrawdir'), searchStr))
    if not files:
        raise Exception('Unable to locate files using search string "%s"' %
                        searchStr)
    for file in files:
        mechVariables = list()
        fileBase = os.path.basename(file)
        filename, ext = fileBase.split('.')
        _, perspective = filename.split('_')
        fId = open(file, 'r')
        drawing = fId.read()
        fId.close()
        #location variables in drawings
        for variable in equation.variables:
            desigStr = variable.desig.longhand + str(variable.number)
            patternStr = r'(\(| |,|\+|\-|\*)(%s)' % desigStr
            pattern = compile(patternStr)
            if len(findall(pattern, drawing)) > 0:
                mechVariables.append(variable)
        mechDrawing = MechanicalDrawing(perspective, mechVariables, drawing,
                                        unit)
        dbSession.add(mechDrawing)
        mechDrawings.append(mechDrawing)
    return MechanicalDesign(equation, mechDrawings)
Ejemplo n.º 2
0
def load_mech_design(equation, dbSession = None, unit = None):
    sys.path.append(os.path.abspath('../../../')) #server root
    sys.path.append(os.path.abspath('../../')) #apps path
    from ServerSettings import get_server_setting
    from ServerSettings import db, Session
    from re import findall, compile
    if not dbSession:
        from sqlalchemy.orm import sessionmaker
        DbSession = sessionmaker(db)
        dbSession=DbSession()
    mechDrawings = list()
    if isinstance(equation, (int, str) ):
        equationId = int(equation)
        equation = dbSession.query(ModelCloudMath.EquationStorage).filter(ModelCloudMath.EquationStorage.number == equationId).first()
    elif isinstance(equation,ModelCloudMath.EquationStorage):
        equationId = int(equation.number)
    searchStr = '%d_*.mech'%equationId
    files =  glob.glob(os.path.join(get_server_setting('mechdrawdir'), searchStr))
    if not files:
        raise Exception('Unable to locate files using search string "%s"'%searchStr)
    for file in files:
        mechVariables = list()
        fileBase  = os.path.basename(file)
        filename, ext = fileBase.split('.')
        _, perspective = filename.split('_')
        fId = open(file, 'r')
        drawing = fId.read()
        fId.close()
        #location variables in drawings
        for variable in equation.variables:
            desigStr = variable.desig.longhand + str(variable.number)
            patternStr = r'(\(| |,|\+|\-|\*)(%s)'%desigStr
            pattern = compile(patternStr)
            if len(findall(pattern, drawing)) > 0:
                mechVariables.append(variable)
        mechDrawing = MechanicalDrawing(perspective, mechVariables, drawing, unit)
        dbSession.add(mechDrawing)  
        mechDrawings.append(mechDrawing)
    return MechanicalDesign(equation, mechDrawings)
Ejemplo n.º 3
0
def mech_design_get(idxMech=None):
    actions = list()
    user = cherrypy.session['user']
    mechDesign = cherrypy.session['mechDesign']
    equation = cherrypy.session['equation']
    solution = equation.solution_get('S')
    ds = Geometric.DraftSpace(backend='Agg')
    ds.clear()
    ds.showGrid = False
    ds.showTick = False
    ds.showAnchor = False
    mechPath = os.path.join(get_server_setting('imagesdir'),
                            cherrypy.session.id)
    ds.path = mechPath
    ds.authorOrigin = equation.instance.owner.firstName + ' ' + equation.instance.owner.lastName
    ds.authorModify = user.firstName + ' ' + user.lastName
    ds.dateOrigin = equation.instance.timestamp.strftime("%m-%d-%Y")
    ds.title = equation.instance.title
    if not os.path.exists(mechPath):
        os.mkdir(mechPath)
    idxList = list()
    if idxMech != None:
        idxList.append(idxMech)
    else:
        for drawing in mechDesign.drawings:
            idxList.append(drawing.id)
    storage = FileStorage.FileStorage(
        os.path.join(get_server_setting('cachedir'), 'cache.fs'))
    db = DB(storage)
    connection = db.open()
    root = connection.root()
    for idxMech in idxList:
        for drawing in mechDesign.drawings:  #search for drawing
            if drawing.id == idxMech:
                break
        mechOptions = cherrypy.session['mechOptions'][idxMech]
        ds.ratio = mechOptions['ratio']
        ds.perspective = drawing.perspective.capitalize()
        ds.name = 'Mechanical-Drawing' + drawing.perspective.capitalize(
        ) + time.strftime('%y%m%d%H%M%S')
        imgUrl = 'api/image?app=Mechanical&tab=Drawing&id1=%d&id2=%d' % (
            mechDesign.id, drawing.id) + '&image=' + ds.name + '.' + DRAWMODE
        values = dict()
        symbols = dict()
        baseUnit = equation.unumDict[int(mechOptions['unit'])]
        for variableSol in solution.variables:
            for variableMech in drawing.variables:
                desig = variableMech.desig.longhand + str(variableMech.number)
                if variableMech.id == variableSol.variable.id:
                    symbols[desig] = variableMech.desig.latex.replace(
                        '#', str(variableMech.number))
                    if variableSol.variable.desig.name == 'Length':
                        unumSelected = equation.variable_get_unit(
                            variableSol, 'selected-unum')
                        unumValue = variableSol.value * unumSelected
                        unumValue = unumValue.asUnit(baseUnit)
                        value = unumValue._value
                    else:
                        value = variableSol.value

                    values[desig] = value

        key = '%s\n%s\n%s\n%s\n%s' % (
            mechOptions['size'], mechOptions['checkOptions'],
            mechOptions['ratio'], mechOptions['unit'],
            ds.get_cmd(drawing.drawing, values))
        cache = root.cache_image.get(key, None)
        imgFileLoc = os.path.join(ds.path, ds.name + '.' + DRAWMODE)
        if cache:
            fId = open(imgFileLoc, 'wb+')
            fId.write(cache.image)
            cache.update()  # update timestamp
            root.cache_image[key] = cache
            transaction.commit()
        else:
            cherrypy.log.error('Draw %s, %s' % (drawing, values), 'MECHANICAL',
                               logging.DEBUG)
            ds.load(drawing.drawing, values)
            cherrypy.log.error('Set background.', 'MECHANICAL', logging.DEBUG)
            ds.draw_background(mechOptions['size'])
            ds.save(fmt=DRAWMODE)
            root.cache_image[key] = ModelCore.CacheImage(imgFileLoc)
            transaction.commit()
        ds.clear()
        actions.append(
            new_action('actDrawingAdd',
                       'Drawing',
                       idx=idxMech,
                       image=imgUrl,
                       variables=None,
                       code=drawing.drawing,
                       perspective=drawing.perspective))
        actions.append(
            new_action('actRatioChange',
                       'Drawing',
                       idx=idxMech,
                       ratio=mechOptions['ratio']))
        actions.append(
            new_action('actSizeFill',
                       'Drawing',
                       idx=idxMech,
                       options=Geometric.options,
                       value=mechOptions['size']))
        actions.append(
            new_action('actUnitFill',
                       'Drawing',
                       idx=idxMech,
                       options={
                           100000: 'm',
                           302800: 'ft',
                           300103: 'cm',
                           302700: 'in',
                           300102: 'mm',
                           302900: 'mil'
                       },
                       value=int(mechOptions['unit'])))
    connection.close()  #close cache
    db.close()
    storage.close()
    return {'actions': actions}
Ejemplo n.º 4
0
def render_circuitikz(latex, dest = None, equation = None, display = None):
    actions = list()
    if dest:
        filePath, fileName = os.path.split(dest)
        imageSessPath = filePath
        imagePath = os.path.join(imageSessPath, fileName + '.png')
    else:
        equation = cherrypy.session['equation']
        display = cherrypy.session['display']
        fileName = 'Diagram-Circuit%s'%time.strftime('%y%m%d%H%M%S')
        imageSessPath = os.path.join(get_server_setting('imagesdir'), cherrypy.session.id)
        actions.append(new_action('actCircuitTikzSubmit', 'Circuit', id =cherrypy.session['circuit'].id))      
        actions.append(new_action('actCircuitTikzSubmit', 'Solver', id =cherrypy.session['circuit'].id))
    imagePath = os.path.join(imageSessPath, fileName + '.png')
    if not os.path.isdir(imageSessPath):
        os.mkdir(imageSessPath)
        cherrypy.log.error('Making directory %s'%imageSessPath, 'DIAGRAM', logging.DEBUG)
    if latex == '':
        return {'actions':actions}
    else:
        # look in cache for existing results
        storage = FileStorage.FileStorage(os.path.join(get_server_setting('cachedir'), 'cache.fs'))
        db = DB(storage)
        connection = db.open()
        root = connection.root()
        cache = root.cache_image.get(latex, None)
        if cache:
            imgFile = open(imagePath, 'wb+')
            imgFile.write(cache.image)
            cache.update() # update timestamp
            root.cache_image[latex] = cache
            transaction.commit()
        else:            
            head =  \
"""\\documentclass[border=4pt]{standalone}
\\usepackage{tikz}
\\usepackage{circuitikz}
\\usepackage{siunitx}
\\pagestyle{empty}
\\begin{document}
\\begin{circuitikz}[%s]
\\newcommand*{\\doublelabel}[3][3em]{\\parbox{#1}{\\raggedleft #2 \\\\ #3}}
"""
            head = head%('american')
            tail = \
"""
\\end{circuitikz}
\\end{document}
"""
            latexDoc = head + latex + tail
            latexDoc = execute_latex_controls(latexDoc, equation, display)
            imagePath = os.path.join(imageSessPath, fileName + '.png')
            args = '-interaction=nonstopmode -halt-on-error -jobname %s -output-directory=%s '%(fileName, imageSessPath)
            # string -> txt (\todo: fix, should render as a string
            if texMode == 'file':
                texFileLoc = os.path.join(imageSessPath, fileName + '.tex')
                f = open(texFileLoc, 'w')
                f.write(latexDoc)
                f.close()
                # tex -> pdf processingsa
                cmd = '"%s" %s %s'%(os.path.join(latexPath, latexEngine), args, texFileLoc)
            elif texMode == 'string':
                # string -> pdf processing
                cmd = '"%s" %s "%s"'%(os.path.join(latexPath, latexEngine), args, latexDoc.replace('\n', ' '))
            cherrypy.log.error("Running %s"%cmd, 'DIAGRAM', logging.DEBUG)
            p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
            stdoutdata, stderrdata  = p.communicate()
            if stderrdata:
                cherrypy.log.error('Error: %s'%stderrdata, 'DIAGRAM', logging.ERROR)
            idx = stdoutdata.find('!')
            if idx >0 :
                cherrypy.log.error('Error: %s'%stdoutdata[idx:], 'DIAGRAM', logging.ERROR, True)
                raise Exception('Latex Error ' + stdoutdata[idx:])
            else:
                imgMagicCmd = 'convert -trim -density 128 "%s.pdf" -background none -undercolor none -pointsize 6 label:"               " -gravity SouthEast -append -pointsize 6 label:"(c) OneSolver.com" -gravity SouthEast -append "%s"'
                if not dest:
                    # latex did not have any errors, save to ram
                    if cherrypy.session.has_key('circuit'):
                        dbCircuit = cherrypy.session['circuit']
                    else:
                        session_new()
                    dbCircuit.latex = latex
                    dbCircuit.equation.instance = equation.instance
                    cherrypy.session['circuit'] = dbCircuit
                    # pdf -> png processing (imagemagick)   
                    cmd = imgMagicCmd%(os.path.join(imageSessPath, fileName), imagePath)
                    cherrypy.log.error('Running %s'%cmd, 'DIAGRAM', logging.DEBUG)
                    p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
                    stdoutdata, stderrdata  = p.communicate()
                    if stdoutdata:
                        cherrypy.log.error('Output: %s'%stdoutdata, 'DIAGRAM', logging.INFO)
                    if stderrdata:
                        cherrypy.log.error('Error: %s'%stderrdata, 'DIAGRAM', logging.ERROR)
                else:
                    cmd = imgMagicCmd%(os.path.join(imageSessPath, fileName), imagePath)
                    p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
                    stdoutdata, stderrdata  = p.communicate()
                    if stdoutdata:
                        cherrypy.log.error('Output: %s'%stdoutdata, 'DIAGRAM', logging.INFO)
                    if stderrdata:
                        cherrypy.log.error('Error: %s'%stderrdata, 'DIAGRAM', logging.ERROR)
                cache = ModelCore.CacheImage(imagePath)
                root.cache_diagram[latex] = cache
                transaction.commit()
        connection.close() #close cache
        db.close()
        storage.close()
        return {'actions':actions}
Ejemplo n.º 5
0
from CloudMath.model import Model as ModelCloudMath
from CloudMath.model import MathHertz
from Diagram.model import Model as ModelDiagram
from Core.controller.GuiResponse import new_action, new_dialog
from Core.controller.Control import app_check, tab_get as tab_get_core, user_check, tab_parse_args, tab_get_reg_id, tab_search

from subprocess import Popen, PIPE, STDOUT

from ZODB import FileStorage, DB
import transaction
from BTrees.OOBTree import OOBTree

texMode = 'file' #(file, string)# todo get string mode working in linux
fileName = 'circuit'
latexEngine = 'pdflatex' #(pdflatex, xelatex)
latexPath = get_server_setting('latexdir')
# cleanup
def clean_files():
    fileExts = ('dvi', 'ps', 'log', 'aux', 'svg', 'eps')
    for ext in fileExts:
        try:
            os.remove('%s.%s'%(fileName,ext))
            cherrypy.log.error("Remove %s.%s"%(fileName,ext), 'DIAGRAM', logging.DEBUG)
        except Exception as err:
            cherrypy.log.error("Skip %s.%s"%(fileName,ext), 'DIAGRAM', logging.DEBUG) 
"""PAGE CONTROLLER HOOKS===================================================="""
def tab_get(*args):
    """ Get tabs for applications
    List Arguments
    @param args[0]: calling tab (int, string, sqa object)
    @param args[1]: search mode (load, session)