def getOptionsBoxPackageNameInfo(cls, prevChoices):
     core = HtmlCore()
     core.divBegin(divClass='infomessagesmall')
     core.append('Package name selected: ')
     core.emphasize(cls._getProtoToolPackageName(prevChoices))
     core.divEnd()
     return '__rawstr__', str(core)
 def getOptionsBoxError(cls, prevChoices):
     if prevChoices.tool != cls.SELECT_TEXT:
         try:
             import_module(prevChoices.tool)
         except Exception:
             core = HtmlCore()
             core.divBegin(divClass='infomessagesmall')
             core.smallHeader('Exception traceback:')
             core.preformatted(traceback.format_exc())
             core.divEnd()
             return '__rawstr__', str(core)
示例#3
0
 def getToolDescription():
     from proto.HtmlCore import HtmlCore
     core = HtmlCore()
     core.smallHeader("General description")
     core.paragraph("This tool is used to try out ProTo tools that have "
                    "not been installed as separate tools in the tool "
                    "menu. This is typically used for development "
                    "purposes, so that one can polish the tool until it "
                    "is finished for deployment in the tool menu. "
                    "When a tool is installed into the menu, the tool "
                    "disappears from the tool list in this tool."
                    "The logic for inclusion in the list is that there "
                    "exists a Python module with a class that inherits "
                    "from GeneralGuiTool, without there existing "
                    "a Galaxy xml file for the tool.")
     core.paragraph(
         "Note: when the list of tools is generated, modules "
         "under the tool directory that does not contain "
         "ProTo tool classes are stored and excluded from "
         "subsequent runs. This is done to improve loading "
         "times. The hidden tool modules are stored in the "
         '"%s" ' % os.path.basename(HIDDEN_NONTOOL_MODULES_CONFIG_FN) +
         'file in the "config" folder. This file can be manually edited if needed.'
     )
     return str(core)
 def _exampleText(text):
     from proto.HtmlCore import HtmlCore
     core = HtmlCore()
     core.styleInfoBegin(styleClass='debug', linesep=False)
     core.append(text.replace('\t', '\\t'))
     core.styleInfoEnd()
     return str(core)
示例#5
0
 def getToolDescription(cls):
     from proto.HtmlCore import HtmlCore
     core = HtmlCore()
     core.smallHeader("General description")
     core.paragraph(
         "This tool is used to hide modules containing ProTo tools from "
         'the "Explore ProTo tools" tool. This is both useful in order to '
         "to reduce the list, and also to reduce the loading times of the "
         "explore tool.")
     core.paragraph(
         "Hidden tool modules are stored in the "
         '"%s" ' % os.path.basename(HIDDEN_MODULES_CONFIG_FN) +
         'file in the "config" folder. This file can be manually edited if needed.'
     )
     return str(core)
 def getToolDescription(cls):
     from proto.HtmlCore import HtmlCore
     core = HtmlCore()
     core.smallHeader("General description")
     core.paragraph(
         "This tool is used for debugging when an uninstalled tool does not appear "
         'in the "Explore ProTo tools" tool. This is typically due to an Python '
         "exception being raised at the import the tool module. This tool "
         "lists all modules under the tool directory that cannot be imported "
         "due to an exception. When selecting the tool, a traceback of the "
         'exception is shown. One can also click "Execute" to store the exception '
         "within a history element (which will then become red). This is "
         "useful if one wants to send a bug report for the exception, or if one "
         "wants to keep a backlog of the error messages.")
     return str(core)
示例#7
0
    def action(self):
        self.options = []
        reset = self.resetAll

        for i in range(len(self.inputNames)):
            name = self.inputNames[i]
            id = self.inputIds[i]
            if self.initChoicesDict:
                val = self.initChoicesDict[id]
            else:
                val = self.params.get(id)

            display_only = False
            opts = self.getOptionsBox(id, i, val)

            if reset and not self.initChoicesDict:
                val = None

            if opts == None:
                self.inputTypes += [None]
                val = None

            elif isinstance(opts, dict) or opts == '__genomes__':
                self.inputTypes += ['multi']
                if opts == '__genomes__':
                    try:
                        opts = self.cachedExtra[id]
                    except:
                        opts = self.getDictOfAllGenomes()
                        self.cachedExtra[id] = opts
                if not self.initChoicesDict:
                    values = type(opts)()
                    for k, v in opts.items():
                        #values[k] = bool(self.params.get(id + '|' + k, False if val else v))
                        values[k] = bool(
                            self.params.get(id + '|' + k, False) if val else v)
                    val = values

            elif isinstance(opts, basestring):
                if opts == '__genome__':
                    self.inputTypes += ['__genome__']
                    try:
                        genomeCache = self.getCacheData(id)
                    except Exception as e:
                        #raise e
                        print 'genome cache empty', e
                        genomeCache = self._getAllGenomes()
                        #print genomeCache
                        self.putCacheData(id, genomeCache)

                    opts = self.getGenomeElement(id, genomeCache)
                    val = self.getGenome(id)

                elif opts == '__track__':
                    self.inputTypes += ['__track__']
                    val = self.getInputValueForTrack(id, name)

                elif opts == '__password__':
                    self.inputTypes += ['__password__']
                    if val == None:
                        val = ''

                else:
                    self.inputTypes += ['text']
                    if val == None:
                        val = opts
                    opts = (val, 1, False)

            elif isinstance(opts, tuple):
                if opts[0] == '__history__':
                    self.inputTypes += opts[:1]
                    opts = self.galaxy.optionsFromHistoryFn(
                        exts=opts[1:] if len(opts) > 1 else None, select=val)
                    if val == None and opts and len(opts[1]) > 0:
                        val = opts[1][0]
                    #opts = self.galaxy.getHistory(GalaxyInterface.getSupportedGalaxyFileFormats())
                elif opts[0] == '__toolhistory__':
                    self.inputTypes += opts[:1]
                    opts = self.galaxy.optionsFromHistoryFn(
                        tools=opts[1:] if len(opts) > 1 else None, select=val)
                    if val == None and opts and len(opts[1]) > 0:
                        val = opts[1][0]
                elif opts[0] == '__multihistory__':
                    self.inputTypes += opts[:1]
                    opts = self.galaxy.itemsFromHistoryFn(
                        opts[1:] if len(opts) > 1 else None)
                    if not self.initChoicesDict:
                        values = OrderedDict()
                        for k, v in opts.items():
                            itemval = self.params.get(id + '|' + k, None)
                            #if itemval:
                            values[unicode(k)] = itemval

                        val = values

                elif opts[0] == '__track__':
                    self.inputTypes += ['__track__']
                    fileTree = opts[1] if len(opts) > 1 else 'preprocessed'
                    val = self.getInputValueForTrack(id, name, fileTree)

                elif opts[0] == '__hidden__':
                    self.inputTypes += opts[:1]
                    if opts[1] != None:
                        val = opts[1]
                    #elif val:
                    #    val = unquote(val)
                elif len(opts) in [2, 3] and (isinstance(opts[0], basestring)):
                    if len(opts) == 2:
                        opts = opts + (False, )
                    if isinstance(opts[1], int):
                        if isinstance(opts[2], bool):
                            if opts[2]:
                                self.inputTypes += ['text_readonly']
                                val = opts[0]
                                #display_only = True
                            else:
                                self.inputTypes += ['text']
                                if val == None:
                                    val = opts[0]
                    else:
                        self.inputTypes += ['rawStr']
                        val = opts[1]
                        display_only = True
                else:
                    self.inputTypes += [None]
                    val = None

            elif isinstance(opts, list):
                if len(opts) > 0 and isinstance(opts[0], list):
                    self.inputTypes += ['table']
                    core = HtmlCore()
                    core.tableHeader(opts[0], sortable=True)
                    if len(opts) > 1:
                        for r in range(1, len(opts)):
                            core.tableLine(opts[r])
                    core.tableFooter()
                    val = unicode(core)
                    display_only = True

                else:
                    self.inputTypes += ['select']
                    if len(opts) > 0 and (val == None or val not in opts):
                        val = opts[0]

            elif isinstance(opts, bool):
                self.inputTypes += ['checkbox']
                val = True if val == "True" else opts if self.use_default else False

            #elif isinstance(opts, list) and len(opts) == 0:
            #    self.inputTypes += ['text']
            #    if val == None:
            #        val = ''

            self.displayValues.append(
                val if isinstance(val, basestring) else repr(val))
            self.inputValues.append(None if display_only else val)
            self.options.append(opts)

            oldval = self.oldValues[id] if id in self.oldValues else None
            if i in self.resetBoxes:
                self.oldValues[id] = val
                if oldval == None or val != oldval:
                    reset = True

        ChoiceTuple = namedtuple('ChoiceTuple', self.inputIds)
        self.choices = ChoiceTuple._make(self.inputValues)
        self.validate()
 def getOptionsBoxPackageNameInfo(cls, prevChoices):
     core = HtmlCore()
     core.divBegin(divClass='infomessagesmall')
     core.append('Package name selected: ')
     core.emphasize(cls._getProtoToolPackageName(prevChoices))
     core.line('')
     core.line('')
     core.append('To import tool, use equivalent package name: ')
     core.emphasize(cls._getProtoToolSymlinkedPackageName(prevChoices))
     core.divEnd()
     return '__rawstr__', str(core)
示例#9
0
 def getLoadToHistoryLink(self, linkText, galaxyDataType='bed'):
     return str(HtmlCore().link(
         linkText,
         getLoadToGalaxyHistoryURL(self.getDiskPath(relativeToBase=True),
                                   galaxyDataType=galaxyDataType)))
示例#10
0
 def getEmbeddedImage(self):
     return str(HtmlCore().image(self.getURL()))
示例#11
0
 def getLink(self, linkText):
     return str(HtmlCore().link(linkText, self.getURL()))
 def getToolDescription():
     core = HtmlCore()
     core.smallHeader("General description")
     core.paragraph("This tool is used to dynamically generate a Python "
                    "module defining a new ProTo tool. After tool "
                    "execution, The tool will be available from the "
                    "'ProTo tool explorer' tool for development purposes.")
     core.divider()
     core.smallHeader("Parameters")
     core.descriptionLine(
         "Choose directory for new tool",
         "Hierarchical selection of directory in which to "
         "place the new tool. The directory structure defines "
         "the Python package which is used if one needs to import "
         "the tool. The package name is automatically shown in an info "
         "box according to the selections. It is also possible "
         "to create new directories. Note that the creation of "
         "new directories happens at execution of this tool. ",
         emphasize=True)
     core.descriptionLine("Module/class name",
                          "The name of the Python module (filename) and "
                          "class for the new tool. For historical reasons, "
                          "ProTo uses 'MixedCase' naming for both the "
                          "module and the class. By convention, it is "
                          "advised (but not required) to end the name "
                          "with 'Tool', e.g. 'MyNewTool'. This will create "
                          "a Python module 'MyNewTool.py' with the class "
                          "'MyNewTool', inheriting from "
                          "'proto.GeneralGuiTool'.",
                          emphasize=True)
     core.descriptionLine("Tool name",
                          "A string with the name or title of the tool. "
                          "This will appear on the top of the tool GUI "
                          "as well as being the default value for the "
                          "tool name in the menu (which can be changed "
                          "when installing).",
                          emphasize=True)
     core.descriptionLine("Use template with inline documentation",
                          "The new Python module is based upon a template"
                          "file containing a simple example tool with "
                          "two option boxes (one selection box and one "
                          "text box). There are two such template files, "
                          "one that contains inline documentation of the "
                          "methods and possible choices, and one without "
                          "the documentation. Advanced users could select "
                          "the latter to make the tool code itself shorter "
                          "and more readable.",
                          emphasize=True)
     return str(core)
示例#13
0
    def execute(cls, choices, galaxyFn=None, username=''):
        # from gold.application.LogSetup import setupDebugModeAndLogging
        # setupDebugModeAndLogging()
        cls._setDebugModeIfSelected(choices)

        print str(HtmlCore().styleInfoBegin(styleClass='debug'))

        shelveDict = {
            'track1':
            choices[3] if choices[3] != cls.NO_TRACK_SHORTNAME else None
        }
        shelveDict['track2'] = choices[
            5] if choices[5] != cls.NO_TRACK_SHORTNAME else None
        print len(choices)
        print cls._extraParams
        for i in range(len(cls._extraParams)):
            index = i * 2 + cls.FIRST_EXTRA_PARAM_BOX_NUMBER + 1
            shelveDict[index] = choices[index].strip()

        DebugInfoShelve = safeshelve.open(cls.SHELVE_FN)
        DebugInfoShelve[choices[0]] = shelveDict
        DebugInfoShelve.close()

        try:
            print 'Getting Unsplittable statClass'
            statClassName = choices[0]
            #statClass = STAT_CLASS_DICT[statClassName]
            #try:

            print 'Preparing arguments to init'
            unsplittableStatClass = MagicStatFactory._getClass(
                statClassName, 'Unsplittable')
            genome = choices[1]

            from gold.track.Track import PlainTrack
            prefixTN1 = cls.STD_PREFIX_TN if choices[2] == 'yes' else []
            tn1 = prefixTN1 + choices[3].split(':')
            track1 = PlainTrack(
                tn1) if choices[3] != cls.NO_TRACK_SHORTNAME else None
            prefixTN2 = cls.STD_PREFIX_TN if choices[4] == 'yes' else []
            tn2 = prefixTN2 + choices[5].split(':')
            track2 = PlainTrack(
                tn2) if choices[5] != cls.NO_TRACK_SHORTNAME else None
            from gold.track.GenomeRegion import GenomeRegion
            #region = GenomeRegion(genome, 'chr1',1000,2000)
            #region2 = GenomeRegion(genome, 'chr1',5000,6000)

            kwArgs = {}
            regVal = choices[cls.FIRST_EXTRA_PARAM_BOX_NUMBER + 1]
            binSpecVal = choices[cls.FIRST_EXTRA_PARAM_BOX_NUMBER + 3]
            ubSource = UserBinSource(regVal, binSpecVal, genome=genome)
            region = list(ubSource)[0]

            if len(cls._extraParams) > 3:
                for i in range(len(cls._extraParams)):
                    paramName = choices[i * 2 +
                                        cls.FIRST_EXTRA_PARAM_BOX_NUMBER]
                    param = paramName[:paramName.find('(')].strip()
                    val = choices[i * 2 + cls.FIRST_EXTRA_PARAM_BOX_NUMBER +
                                  1].strip()
                    if val != '':
                        kwArgs[param] = val
                        shelveDict[i * 2 + cls.FIRST_EXTRA_PARAM_BOX_NUMBER +
                                   1] = val

            print 'Calling __init__'
            #
            statObj = unsplittableStatClass(region, track1, track2, **kwArgs)

            print 'Calling createChildren'
            statObj.createChildren()

            print 'Calling getResult'
            statObj.getResult()

            #except:
            #    raise

            #print 'Preparing arguments to init'
            #genome = 'hg18'
            #prefixTN = ['DNA structure'] if choices[2] == 'yes' else []
            #from gold.track.Track import PlainTrack
            #tn1 = prefixTN + choices[3].split(':')
            #track1 = PlainTrack(tn1)
            #tn2 = prefixTN + choices[5].split(':')
            #track2 = PlainTrack(tn2)
            #from gold.track.GenomeRegion import GenomeRegion
            ##region = GenomeRegion(genome, 'chr1',1000,2000)
            ##region2 = GenomeRegion(genome, 'chr1',5000,6000)
            #
            #kwArgs = {}
            #regVal = choices[cls.FIRST_EXTRA_PARAM_BOX_NUMBER+1]
            #binSpecVal = choices[cls.FIRST_EXTRA_PARAM_BOX_NUMBER+3]
            #ubSource = UserBinSource(regVal, binSpecVal, genome=choices[1])
            #region = list(UserBinSource)[0]
            #
            #if len(cls._extraParams)>2:
            #    for i in range(2,len(cls._extraParams)):
            #        paramName = choices[i*2+cls.FIRST_EXTRA_PARAM_BOX_NUMBER]
            #        param = paramName[:paramName.find('(')].strip()
            #        val = choices[i*2+cls.FIRST_EXTRA_PARAM_BOX_NUMBER+1].strip()
            #        if val !='':
            #            kwArgs[param] = val
            #            shelveDict[i*2+cls.FIRST_EXTRA_PARAM_BOX_NUMBER+1] = val
            #
            #
            ##extraParams += [v.strip() for v in choices.kwArgs.split(',')] if choices.kwArgs.strip() != '' else []
            ##args = [region, track1, track2]
            #
            #print 'Calling __init__'
            ##
            #statObj = unsplittableStatClass(region, track1, track2, **kwArgs)
            #
            #print 'Calling createChildren'
            #statObj.createChildren()
            #
            #print 'Calling getResult'
            #statObj.getResult()

            print 'Running StatJob'
            magicStatClass = STAT_CLASS_DICT[statClassName]
            #res = StatJob([region,region2],track1,track2,magicStatClass,**kwArgs).run()
            res = StatJob(ubSource, track1, track2, magicStatClass,
                          **kwArgs).run()

            print str(HtmlCore().styleInfoEnd())

            from quick.application.GalaxyInterface import GalaxyInterface
            GalaxyInterface._viewResults([res], galaxyFn)

        except Exception, e:
            print 'Error: ', e
            raise
    def getToolDescription(cls):
        from proto.HtmlCore import HtmlCore
        core = HtmlCore()
        core.smallHeader("General description")
        core.paragraph(
            "This tool is used to install ProTo tools into the tool menu. "
            "The installation process creates a Galaxy tool XML file and "
            "adds the tool to the tool menu (in the 'tool_conf.xml' file). "
            "After execution, the XML file has been generated and added "
            "to the tool configuration file, but Galaxy needs to reload "
            "the tool menu for it to become visible. This is done by a "
            "Galaxy administrator, either from the Admin menu, or from a "
            "link in the output history element from this tool.")
        core.paragraph("Note that the after this tool has been executed "
                       "but before a Galaxy administrator has reloaded the "
                       "tool menu, the tool is not available from neither "
                       "of the 'ProTo tool explorer' tool or from the "
                       "Galaxy menu.")
        core.divider()
        core.smallHeader("Parameters")

        core.descriptionLine("Select tool", "The tool to install.",
                             emphasize=True)
        core.descriptionLine("Tool ID",
                             "The Galaxy tool id for the new tool to be "
                             "created. This is the 'id' argument to the "
                             "<tool> tag in the tool XML file.",
                             emphasize=True)
        core.descriptionLine("Tool name",
                             "The name of the tool as it will appear in the "
                             "tool menu. The tool name will appear as a HTML "
                             "link.", emphasize=True)
        core.descriptionLine("Tool description",
                             "The description of the tool as it will appear "
                             "in the tool menu. The tool description will "
                             "appear directly after the tool name as "
                             "normal text.", emphasize=True)
        core.descriptionLine("Tool XML file",
                             "The path (relative to '%s') and name " %
                             os.path.sep.join([''] + cls._getProtoRelToolDirs(fromBase=True)) +
                             "of the Galaxy tool XML file to be created. "
                             "The tool file can be named anything and be "
                             "placed anywhere (as the 'tool_conf.xml' file "
                             "contains the path to the tool XML file). "
                             "However, we encourage the practice of placing "
                             "the Galaxy tool XML file together with the "
                             "Python module, in the same directory and "
                             "with the same name as tool module (with e.g. "
                             "'ABCTool.xml' instead of 'AbcTool.py').",
                             emphasize=True)
        core.descriptionLine("Select section in tool_conf.xml file",
                             "The section in the tool_conf.xml file where"
                             "the tool should be placed in the menu. "
                             "This corresponds to the first level in the"
                             "tool hierarchy.", emphasize=True)
        return str(core)
    def execute(cls, choices, galaxyFn=None, username=''):
        # txt = ''
        # if choices.tool and choices.section:
        #     txt = 'Install %s into %s' % (choices.tool, choices.section)
        # tool_cls = choices.tool

        prototype = cls._getPrototype(choices.tool)
        tool_file = os.path.join(cls.XML_TOOL_DIR, choices.toolXMLPath)
        toolConf = GalaxyToolConfig()
        xml = toolConf.addTool(choices.section, tool_file)
        tool_xml = toolConf.createToolXml(choices.toolID,
                                          choices.name, cls.TOOL_ID_PREFIX,
                                          prototype.__module__,
                                          prototype.__class__.__name__,
                                          choices.description)

        abs_tool_xml_path = os.path.join(cls.TOOL_DIR, choices.toolXMLPath)

        try:
            os.makedirs(os.path.dirname(abs_tool_xml_path))
        except:
            pass

        with open(abs_tool_xml_path, 'w') as tf:
            tf.write(tool_xml)

        toolConf.write()

        from proto.HtmlCore import HtmlCore
        core = HtmlCore()

        extraJavaScriptCode = '''
<script type="text/javascript">
    $().ready(function() {
        $("#reload_toolbox").click(function(){
            $.ajax({
            url: "/api/configuration/toolbox",
            type: 'PUT'
            }).done(function() {
                    top.location.reload();
                }
            );
        });
    });
</script>
'''
        core.begin(extraJavaScriptCode=extraJavaScriptCode)
        core.link('Reload toolbox/menu', url='#', args='id="reload_toolbox"')
        core.preformatted(escape(xml))
        core.preformatted(escape(tool_xml))
        core.end()
        print>>open(galaxyFn, 'w'), core
示例#16
0
 def getOptionsBoxToolDescTop(cls, prevChoices):
     core = HtmlCore()
     core.bigHeader('genomic-permutation-tools')
     core.smallHeader('a collection of permutation approaches to shuffle genomic regions')
     core.divider()
     return '__rawStr__', str(core)