Example #1
0
def buildHan(uchHan):
    Common.say('Creating Han Definition file for ' + uchHan)

    hcf = Genome.HCF(Common.pathToURL(Common.makeHanPath(uchHan + Common.Constants.extHCF), Globals.urlHan))
    
    aryGroups = [ _HAN_GROUP % (str(hcfG.bounds), hcfG.length, hcfG.ptCenter.x, hcfG.ptCenter.y,
                            ' '.join([ str(i+1) for i in hcfG.containedStrokes])) for hcfG in hcf.aryGroups ]
    aryStrokes = [ _HAN_STROKE % (str(hcfS.bounds),
                                hcfS.length,
                                '\n'.join([ _HAN_POINT % (ptd.x, ptd.y, ptd.distance) for ptd in hcfS.aryPointsForward]),
                                '\n'.join([ _HAN_POINT % (ptd.x, ptd.y, ptd.distance) for ptd in hcfS.aryPointsReverse]) ) for hcfS in hcf.aryStrokes ]
    aryOverlaps = [ _HAN_OVERLAP % (hcfO.firstStroke, hcfO.secondStroke, hcfO.fRequired and 'true' or 'false') for hcfO in hcf.aryOverlaps ]
    strHan = _HAN_DEFINITION % (str(uuid.uuid4()).upper(), hcf.unicode, datetime.datetime.utcnow().isoformat(), _NAME,
                                str(hcf.bounds), hcf.length, hcf.minimumStrokeLength,
                                '\n'.join(aryGroups),
                                '\n'.join(aryStrokes),
                                aryOverlaps and ('<overlaps>%s</overlaps>' % '\n'.join(aryOverlaps)) or '')
                                
    strPath = Common.resolvePath(os.path.join(Globals.strArchetypePath, Common.makeHanPath(hcf.unicode + Common.Constants.extHan)))
    strDir = os.path.dirname(strPath)
    if not os.path.exists(strDir):
        try: os.makedirs(os.path.dirname(strPath))
        except OSError, err: raise Common.BiologicError('Unable to create %s - %s' % (strDir, str(err)))

    try:
        fileHan = os.open(strPath, os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0664)
        os.write(fileHan, strHan)
    except IOError, err: raise Common.BiologicError('Unable to create %s - %s' % (strPath, str(err)))
    os.close(fileHan)
    
    Common.say('Han definition written to ' + strPath)
    return
Example #2
0
def getArguments():
    # Start with command-line arguments and append those passed via the environment
    # (The command-line overrides the environment)
    args = Common.readEnvironment('$STYLUS_GRIDARGS')
    argv = args and args.split() or []
    argv += sys.argv[1:]
    
    Globals.strLocalPath = Common.resolvePath(os.path.dirname(sys.argv[0]))
    
    Globals.strXgridVolume = Common.readEnvironment('$STYLUS_XGRID_VOLUME')
    Globals.strXgridNotify = Common.readEnvironment('$STYLUS_XGRID_EMAIL')
    Globals.strXgridShell = Common.readEnvironment('$STYLUS_XGRID_SHELL')
    Globals.strXgridController = Common.readEnvironment('$XGRID_CONTROLLER_HOSTNAME')
    Globals.strXgridPassword = Common.readEnvironment('$XGRID_CONTROLLER_PASSWORD')

    try:
        opts, Globals.aryArgs = getopt.getopt(argv,
                    'erj:lg:p:xv:n:s:c:h',
                    [ 'exec', 'report', 'job=', 'launch', 'genomes=', 'plans=', 'xgrid', 'volume=', 'notify=', 'shell=', 'controller=', 'help' ])
    except getopt.error, err:
        raise Usage(' '.join(argv[1:]) + ' contains unknown arguments')
Example #3
0
def main():
    form = cgi.FieldStorage()
    
    if not 'code' in form or not form['code']:
        raise Common.BiologicError('Han unicode value is missing')
    uchHan = form.getfirst('code').upper()

    if 'hcf' in form:
        pathHCF = Common.resolvePath('./../../Archetypes/' + Common.makeHanPath(uchHan + Common.Constants.extHCF))
        try:
            fileHCF = os.open(pathHCF, os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0664)
            os.write(fileHCF, form['hcf'].value)
            os.close(fileHCF)
        except IOError, err:
            raise Common.BiologicError('Unable to write %s - %s' % (pathHCF, str(err)))
            
        inscribe.setGlobals([ '-d', './../../Archetypes/', '-u', './../../Archetypes/' ])
        inscribe.buildHan(uchHan)

        inscribe.setGlobals([ '-o', './../../Genes/', '-u', './../../Archetypes/' ])
        aryGeneNames = inscribe.buildGenes(uchHan, [ 'default' ])
        returnMsg('Successfully created Han definition and default gene (%s) for %s' % (aryGeneNames[0], uchHan))
Example #4
0
def getArguments():
    # Start with command-line arguments and append those passed via the environment
    # (The command-line overrides the environment)
    args = Common.readEnvironment('$STYLUS_GRIDARGS')
    argv = args and args.split() or []
    argv += sys.argv[1:]

    Globals.strLocalPath = Common.resolvePath(os.path.dirname(sys.argv[0]))

    Globals.strXgridVolume = Common.readEnvironment('$STYLUS_XGRID_VOLUME')
    Globals.strXgridNotify = Common.readEnvironment('$STYLUS_XGRID_EMAIL')
    Globals.strXgridShell = Common.readEnvironment('$STYLUS_XGRID_SHELL')
    Globals.strXgridController = Common.readEnvironment(
        '$XGRID_CONTROLLER_HOSTNAME')
    Globals.strXgridPassword = Common.readEnvironment(
        '$XGRID_CONTROLLER_PASSWORD')

    try:
        opts, Globals.aryArgs = getopt.getopt(argv, 'erj:lg:p:xv:n:s:c:h', [
            'exec', 'report', 'job=', 'launch', 'genomes=', 'plans=', 'xgrid',
            'volume=', 'notify=', 'shell=', 'controller=', 'help'
        ])
    except getopt.error, err:
        raise Usage(' '.join(argv[1:]) + ' contains unknown arguments')
Example #5
0
            raise Usage('Xgrid does not support both exec and report -- run with exec first followed by report once completed')
        if not Globals.strXgridVolume:
            raise Usage('Xgrid requires the full path to the Stylus working directoryon an Xgrid client (e.g., /Stylus)')
        if not Globals.strXgridShell:
            raise Usage('Xgrid requires the full path to the shell within which to spawn Stylus on an Xgrid client')
        if not Globals.strXgridController:
            raise Usage('Xgrid requires the controller hostname')

        if not Globals.fLaunchJobs:
            Globals.fLaunchJobs = not Globals.strGenomes and not Globals.strPlans
            
    else:
        Globals.fLaunchJobs = True
            
    if Globals.strGenomes and Globals.fLaunchJobs:
        Globals.strGenomes = Common.resolvePath(Globals.strGenomes)
        if Globals.fUseXgrid and not os.path.isabs(Globals.strGenomes):
            Globals.strGenomes = os.path.join(Globals.strXgridVolume, Globals.strGenomes)
            
    if Globals.strPlans and Globals.fLaunchJobs:
        Globals.strPath = Common.resolvePath(Globals.strPlans)
        if Globals.fUseXgrid and not os.path.isabs(Globals.strPlans):
            Globals.strPlans = os.path.join(Globals.strXgridVolume, Globals.strPlans)
            
#------------------------------------------------------------------------------
# Function: spawnStylus
#
# Spawn one or more instances of a Stylus script
#------------------------------------------------------------------------------
def spawnStylus(fScript, dictEnv):
    if (Globals.strGenomes or Globals.strPlans) and Globals.fLaunchJobs:
Example #6
0
            
        if option in ('-f', '--folders'):
            Globals.aryFolders = value
            
        if option in ('-r', '--removeage'):
            nDays = int(value)
            if nDays <= 0:
                raise Usage('%s is an illegal value for removeage')
            Globals.nRemoveAge = nDays

        if option in ('-h', '--help'):
            raise Usage('')

    if not Globals.pathSrc:
        raise Usage('Required source path was not specified')
    Globals.pathSrc = os.path.abspath(Common.resolvePath(Globals.pathSrc))
    if not os.path.exists(Globals.pathSrc) or not os.path.isdir(Globals.pathSrc):
        raise Usage('Source path - %s - does not exist or is not a directory' % Globals.pathSrc)

    if not Globals.pathDst:
        raise Usage('Required destination path was not specified')
    Globals.pathDst = os.path.abspath(Common.resolvePath(Globals.pathDst))
    if not os.path.exists(Globals.pathDst) or not os.path.isdir(Globals.pathSrc):
        raise Usage('Destination path - %s - does not exist or is not a directory' % Globals.pathDst)
        
    if not Globals.aryFolders:
        raise Usage('Required folders were not supplied')
    Globals.aryFolders = Globals.aryFolders.split(':')
    for folder in Globals.aryFolders:
        pathFolder = os.path.abspath(os.path.join(Globals.pathSrc, folder))
        if not os.path.exists(pathFolder) or not os.path.isdir(pathFolder):
Example #7
0
def buildGenes(uchHan, aryGenes):
    Common.say('Creating %d gene(s)' % len(aryGenes))
    
    han = loadHan(uchHan)
    
    strAuthor = Globals.strAuthor and (" author='%s'" % Globals.strAuthor) or ''

    aryGeneNames = []
    for specification in aryGenes:
        Common.say('Creating gene from specification ' + specification)

        gs = GeneSpecification(specification != Constants.strDefault and specification or '', han)
        gsName = gs.toName(han.unicode) + Common.Constants.extGene
        gsPoints = gs.getPoints()
        Common.say('Gene to be named ' + gsName)

        ptCurrent = Genome.Point(pt=gsPoints[0][1][0])
        arySegments = []

        # Convert each set of points into a list of vectors
        for iSegment in xrange(len(gsPoints)):
            fCoherent, aryPoints = gsPoints[iSegment]
            
            # Build the segment starting from the current location
            # - Ensure incoherent segments always begin at the current location
            #   (This causes moves to absorb the tracing error, effectively trading placement error for stroke fit error.)
            if not fCoherent:
                aryPoints[0].x = ptCurrent.x
                aryPoints[0].y = ptCurrent.y
            ptCurrent, aryVectors = buildSegment(ptCurrent, fCoherent, aryPoints)
            
            if not fCoherent:
                # If the segment contains too few vectors, pad it with an incoherent sequence
                # - If there are no vectors, use No/So/Ea/We - binding code will ensure proper coherence at the endpoints
                # - Otherwise, use the four points of the direction "compass" that are guaranteed incoherent with the last vector
                if len(aryVectors) < 3:
                    iDirection = len(aryVectors) and Codons.Directions.add(Codons.Vectors.toDirection(aryVectors[-1]), 3) or Codons.Directions.North
                    aryVectors.append(Codons.Vectors.create(iDirection))
                    aryVectors.append(Codons.Vectors.create(Codons.Directions.toOpposite(iDirection)))
                    
                    iDirection = Codons.Directions.add(iDirection, 2)
                    aryVectors.append(Codons.Vectors.create(iDirection))
                    aryVectors.append(Codons.Vectors.create(Codons.Directions.toOpposite(iDirection)))
                    
                # Inject vectors to force incoherency for incoherent segments
                # - Essentially, add a vector pair to every two that forces incoherency
                # - Walking the list must take into account injected vector pairs
                else:
                    iVector = 0
                    while iVector < len(aryVectors):
                        if Codons.isCoherent([aryVectors[iVector-2], aryVectors[iVector-1], aryVectors[iVector+0]]):
                            idVector = aryVectors[iVector]
                            aryVectors.insert(iVector+0, Codons.Vectors.toOpposite(idVector))
                            aryVectors.insert(iVector+1, idVector)
                        iVector += 1

            # Ensure the vectors "bind" without affecting the coherence of an adjoining segment
            if iSegment:
                fCoherencePrev, aryVectorsPrev = arySegments[-1]
                if Codons.isCoherent([ aryVectorsPrev[-2], aryVectorsPrev[-1], aryVectors[0] ]) or Codons.isCoherent([ aryVectorsPrev[-1], aryVectors[0], aryVectors[1] ]):
                    if not fCoherencePrev:
                        aryVectorsPrev += [ Codons.Vectors.toOpposite(aryVectorsPrev[-1]), aryVectorsPrev[-1], aryVectors[0], Codons.Vectors.toOpposite(aryVectors[0]) ]
                    else:
                        aryVectors[:0] = [ Codons.Vectors.toOpposite(aryVectorsPrev[-1]), aryVectorsPrev[-1], aryVectors[0], Codons.Vectors.toOpposite(aryVectors[0]) ]

            arySegments.append((fCoherent, aryVectors))

        validateCoherence(arySegments)

        aryCodons = [ Codons.Vectors.toVector(idVector).codon for fCoherent, aryVectors in arySegments for idVector in aryVectors ]
        aryCodons[:0] = [ 'ATG' ]
        aryCodons.append(Codons.Vectors.toVector(Codons.Vectors.create(Codons.Directions.Stop, Codons.Constants.iVectorShort)).codon)

        aryStrokes = []
        iStroke = 0
        iBase = 4
        for fCoherent, aryVectors in arySegments:
            if fCoherent:
                aryStrokes.append(_GENE_STROKE % (iBase, iBase+(len(aryVectors)*3-1), gs.mapStrokeToHan(iStroke)+1))
                iStroke += 1
            iBase += len(aryVectors) * 3

        strGene = _GENE_DEFINITION % (str(uuid.uuid4()).upper(), strAuthor, datetime.datetime.utcnow().isoformat(), _NAME, str(gs),
                                    ''.join(aryCodons), len(aryCodons)*3,
                                    gsPoints[0][1][0].x, gsPoints[0][1][0].y,
                                    han.unicode,
                                    '\n'.join(aryStrokes))

        strPath = Common.resolvePath(os.path.join(Globals.strGenePath, Common.makeHanPath(gsName)))
        strDir = os.path.dirname(strPath)
        if not os.path.exists(strDir):
            try: os.makedirs(os.path.dirname(strPath))
            except OSError, err: raise Common.BiologicError('Unable to create %s - %s' % (strDir, str(err)))
        
        try:
            fileGene = os.open(strPath, os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0664)
            os.write(fileGene, strGene)
        except IOError, err: raise Common.BiologicError('Unable to create %s - %s' % (strPath, str(err)))
        os.close(fileGene)
        
        Common.say('\tWrote %s - %d codons, %d bases' % (strPath, len(aryCodons), len(aryCodons)*3))
        aryGeneNames.append(gsName)

    return aryGeneNames
Example #8
0
            Globals.strAuthor = value

        if option in ('-q', '--quiet'):
            Common.Globals.fQuiet = True

        if option in ('-h', '--help'):
            raise Usage('')

    if Globals.fInteractive and not Globals.uchHan:
        raise Usage('Required code was not specified')

    if Globals.fBuildArchetype and not Globals.strArchetypePath:
        raise Usage('Required archetype path was not specified')

    if Globals.fBuildArchetype:
        Globals.strArchetypePath = Common.resolvePath(Globals.strArchetypePath)
        if not os.path.exists(Globals.strArchetypePath):
            try: os.makedirs(Globals.strArchetypePath)
            except OSError: raise Usage('Unable to create ' + Globals.strArchetypePath)
        
    if len(Globals.aryGenes) > 0 and not Globals.strGenePath:
        raise Usage('Required gene output path was not specified')

    if len(Globals.aryGenes) > 0:
        Globals.strGenePath = Common.resolvePath(Globals.strGenePath)
        if not os.path.exists(Globals.strGenePath):
            try: os.makedirs(Globals.strGenePath)
            except OSError: raise Usage('Unable to create ' + Globals.strGenePath)
        
    if not Globals.urlHan:
        raise Usage('Required Han URL was not specified')
Example #9
0
            )
        if not Globals.strXgridShell:
            raise Usage(
                'Xgrid requires the full path to the shell within which to spawn Stylus on an Xgrid client'
            )
        if not Globals.strXgridController:
            raise Usage('Xgrid requires the controller hostname')

        if not Globals.fLaunchJobs:
            Globals.fLaunchJobs = not Globals.strGenomes and not Globals.strPlans

    else:
        Globals.fLaunchJobs = True

    if Globals.strGenomes and Globals.fLaunchJobs:
        Globals.strGenomes = Common.resolvePath(Globals.strGenomes)
        if Globals.fUseXgrid and not os.path.isabs(Globals.strGenomes):
            Globals.strGenomes = os.path.join(Globals.strXgridVolume,
                                              Globals.strGenomes)

    if Globals.strPlans and Globals.fLaunchJobs:
        Globals.strPath = Common.resolvePath(Globals.strPlans)
        if Globals.fUseXgrid and not os.path.isabs(Globals.strPlans):
            Globals.strPlans = os.path.join(Globals.strXgridVolume,
                                            Globals.strPlans)


#------------------------------------------------------------------------------
# Function: spawnStylus
#
# Spawn one or more instances of a Stylus script
Example #10
0
            % (Globals.cmd == Constants.cmdCreate and 'create' or 'validate'))
    if Globals.cmd == Constants.cmdValidate and not Globals.strGenome and not Globals.strCodonTable:
        raise Usage(
            'validate takes either the genome or codon table as its source')
    if Globals.cmd == Constants.cmdTranslate and (not Globals.strGenome or
                                                  not Globals.strCodonTable):
        raise Usage(
            'translate requires both the genome to translate and the codon table to use'
        )

    if Globals.cmd <> Constants.cmdValidate:
        Globals.uuid = str(uuid.uuid4()).upper()

    if Globals.strGenome:
        Globals.urlGenome = Common.pathToURL(
            Common.makeHanPath(Common.resolvePath(Globals.strGenome)),
            Globals.urlGenomeBase)
    if Globals.strCodonTable:
        Globals.urlCodonTable = Common.pathToURL(Globals.strCodonTable,
                                                 Globals.urlCodonTableBase)

    if Globals.cmd <> Constants.cmdValidate and Globals.pathOutput:
        Globals.pathOutput = Common.resolvePath(Globals.pathOutput)
        Common.ensurePath(os.path.dirname(Globals.pathOutput))
        Globals.pathOutput = os.path.join(
            Globals.pathOutput,
            ('%s%s' %
             (Globals.uuid,
              (Globals.cmd == Constants.cmdTranslate and
               Common.Constants.extGene or Common.Constants.extCodonTable))))
    return
Example #11
0
        if option in ('-f', '--folders'):
            Globals.aryFolders = value

        if option in ('-r', '--removeage'):
            nDays = int(value)
            if nDays <= 0:
                raise Usage('%s is an illegal value for removeage')
            Globals.nRemoveAge = nDays

        if option in ('-h', '--help'):
            raise Usage('')

    if not Globals.pathSrc:
        raise Usage('Required source path was not specified')
    Globals.pathSrc = os.path.abspath(Common.resolvePath(Globals.pathSrc))
    if not os.path.exists(Globals.pathSrc) or not os.path.isdir(
            Globals.pathSrc):
        raise Usage('Source path - %s - does not exist or is not a directory' %
                    Globals.pathSrc)

    if not Globals.pathDst:
        raise Usage('Required destination path was not specified')
    Globals.pathDst = os.path.abspath(Common.resolvePath(Globals.pathDst))
    if not os.path.exists(Globals.pathDst) or not os.path.isdir(
            Globals.pathSrc):
        raise Usage(
            'Destination path - %s - does not exist or is not a directory' %
            Globals.pathDst)

    if not Globals.aryFolders:
Example #12
0
    Globals.urlCodonTableBase = Common.pathToURL(Globals.urlCodonTableBase, Common.Constants.schemeFile)
    if Globals.urlCodonTableBase[len(Globals.urlCodonTableBase)-1] <> Common.Constants.urlSeparator:
        Globals.urlCodonTableBase += Common.Constants.urlSeparator

    if Globals.cmd <> Constants.cmdTranslate and Globals.strGenome and Globals.strCodonTable:
        raise Usage('%s takes either the genome or codon table as its source - not both' % (Globals.cmd == Constants.cmdCreate and 'create' or 'validate'))
    if Globals.cmd == Constants.cmdValidate and not Globals.strGenome and not Globals.strCodonTable:
        raise Usage('validate takes either the genome or codon table as its source')
    if Globals.cmd == Constants.cmdTranslate and (not Globals.strGenome or not Globals.strCodonTable):
        raise Usage('translate requires both the genome to translate and the codon table to use')
        
    if Globals.cmd <> Constants.cmdValidate:
        Globals.uuid = str(uuid.uuid4()).upper()

    if Globals.strGenome:
        Globals.urlGenome = Common.pathToURL(Common.makeHanPath(Common.resolvePath(Globals.strGenome)), Globals.urlGenomeBase)
    if Globals.strCodonTable:
        Globals.urlCodonTable = Common.pathToURL(Globals.strCodonTable, Globals.urlCodonTableBase)
        
    if Globals.cmd <> Constants.cmdValidate and Globals.pathOutput:
        Globals.pathOutput = Common.resolvePath(Globals.pathOutput)
        Common.ensurePath(os.path.dirname(Globals.pathOutput))
        Globals.pathOutput = os.path.join(Globals.pathOutput, ('%s%s' % (Globals.uuid, (Globals.cmd == Constants.cmdTranslate and Common.Constants.extGene or Common.Constants.extCodonTable))))
    return

#------------------------------------------------------------------------------
# Function: createTable
# 
#------------------------------------------------------------------------------
def createTable():
    aryEntries = [ _CODONTABLE_ENTRY % (codon, vector, (_CODONTABLE_ISSTANDARD % (Globals.codonTable.hasStandardMapping(codon) and 'true' or 'false'))) for codon, vector in Globals.codonTable.entries() ]