Beispiel #1
0
    def _readOMETiffHeader(self, omeformat=True):
        """
        get the right ImageReader directry from Java Class Wrapper
        return ImageReader object just in case to do more work
        """
        # https://github.com/CellProfiler/python-bioformats/issues/23
        # also refer to bioformats.formatreader.py and metadatatools.py

        clsOMEXMLService = javabridge.JClassWrapper(
            'loci.formats.services.OMEXMLService')
        serviceFactory = javabridge.JClassWrapper(
            'loci.common.services.ServiceFactory')()
        service = serviceFactory.getInstance(clsOMEXMLService.klass)
        metadata = service.createOMEXMLMetadata()
        level = bioformats.metadatatools.get_metadata_options(
            bioformats.metadatatools.ALL)

        if omeformat:
            # for OME-Tiff only
            self.is_ometiff = True
            rdr = javabridge.JClassWrapper('loci.formats.in.OMETiffReader')()
            rdr.setOriginalMetadataPopulated(True)
        else:
            # rather in general
            rdr = bioformats.formatreader.make_image_reader_class()()
            rdr.allowOpenToCheckType(True)

        rdr.setMetadataStore(metadata)
        rdr.setMetadataOptions(level)
        rdr.setId(self.fn)
        self.xml = service.getOMEXML(metadata)

        return rdr
    def save_figure(self, *args):
        """Save the current figure"""
        default_filetype = self.canvas.get_default_filetype()
        filetypes = self.canvas.get_supported_filetypes_grouped()

        def compare(a, b):
            aname, aextensions = a
            bname, bextensions = b
            if default_filetype in aextensions:
                return 0 if default_filetype in bextensions else -1
            elif default_filetype in bextensions:
                return 1
            else:
                return cmp(aname, bname)

        filetypes = list(filetypes.items())
        filetypes.sort(cmp=compare)
        chooser_cls = javabridge.JClassWrapper('javax.swing.JFileChooser')
        chooser = chooser_cls()
        chooser.setDialogTitle("Save figure")
        filter_cls = javabridge.JClassWrapper(
            'javax.swing.filechooser.FileNameExtensionFilter')
        default_filter = None
        for name, extensions in filetypes:
            file_filter = filter_cls(name, *extensions)
            chooser.addChoosableFileFilter(file_filter)
            if default_filter is None:
                default_filter = file_filter
        chooser.setFileFilter(default_filter)
        result = chooser.showSaveDialog(self.canvas.component)
        if result == chooser_cls.APPROVE_OPTION:
            path = chooser.getSelectedFile().getAbsolutePath()
            exts = chooser.getFileFilter().getExtensions()
            ext = javabridge.get_env().get_object_array_elements(exts.o)[0]
            self.canvas.print_figure(path, format=javabridge.to_string(ext))
Beispiel #3
0
    def __init__(self,
                 df,
                 penaltydiscount=4,
                 maxDegree=3,
                 faithfulnessAssumed=True,
                 numofthreads=2,
                 verbose=False,
                 priorKnowledge=None):

        tetradData = pycausal.loadContinuousData(df)

        score = javabridge.JClassWrapper('edu.cmu.tetrad.search.SemBicScore')(
            tetradData)
        score.setPenaltyDiscount(
            penaltydiscount
        )  # set to 2 if variable# <= 50 otherwise set it to 4

        fgs = javabridge.JClassWrapper('edu.cmu.tetrad.search.Fgs')(score)
        fgs.setMaxDegree(maxDegree)
        fgs.setNumPatternsToStore(0)
        fgs.setFaithfulnessAssumed(faithfulnessAssumed)
        fgs.setParallelism(numofthreads)
        fgs.setVerbose(verbose)

        if priorKnowledge is not None:
            fgs.setKnowledge(priorKnowledge)

        tetradGraph = fgs.search()

        self.nodes = pycausal.extractTetradGraphNodes(tetradGraph)
        self.edges = pycausal.extractTetradGraphEdges(tetradGraph)
        self.graph = pycausal.generatePyDotGraph(self.nodes, self.edges)
Beispiel #4
0
    def setup(self, arr):
        # ome = bioformats.omexml
        # bioformats/formatwriter.py

        if arr.ndim == 3:
            p = self.omexml.image(0).Pixels
            p.SizeC = arr.shape[2]
            p.Channel(0).SamplesPerPixel = pixels.shape[2]
            self.omexml.structured_annotations.add_original_metadata(
                ome.OM_SAMPLES_PER_PIXEL, str(pixels.shape[2]))

        self.xml = self.omexml.to_xml()
        self.xml = self.xml.replace('&#181;', '\xb5')

        clsOMEXMLService = javabridge.JClassWrapper(
            'loci.formats.services.OMEXMLService')
        serviceFactory = javabridge.JClassWrapper(
            'loci.common.services.ServiceFactory')()
        service = serviceFactory.getInstance(clsOMEXMLService.klass)
        metadata = service.createOMEXMLMetadata(self.xml)

        if self.file.endswith(OMETIFF):
            self.fp = javabridge.JClassWrapper(
                'loci.formats.out.OMETiffWriter')()
        else:
            self.fp = javabridge.JClassWrapper('loci.formats.ImageWriter')()

        self.fp.setMetadataRetrieve(metadata)

        self.fp.setId(self.fn)
        #if self.imgSequence in (0, 2, 3, 5):
        #    self.fp.setInterleaved(True)
        #else:
        self.fp.setInterleaved(False)
Beispiel #5
0
    def __init__(self,
                 df,
                 continuous=True,
                 depth=3,
                 aggressivelyPreventCycles=False,
                 significance=0.05,
                 verbose=False,
                 priorKnowledge=None):
        indTest = None

        if (continuous):
            tetradData = pycausal.loadContinuousData(df)
            indTest = javabridge.JClassWrapper(
                'edu.cmu.tetrad.search.IndTestFisherZ')(tetradData,
                                                        significance)
        else:
            tetradData = pycausal.loadDiscreteData(df)
            indTest = javabridge.JClassWrapper(
                'edu.cmu.tetrad.search.IndTestChiSquare')(tetradData,
                                                          significance)

        cpcstable = javabridge.JClassWrapper(
            'edu.cmu.tetrad.search.CpcStable')(indTest)
        cpcstable.setDepth(depth)
        cpcstable.setAggressivelyPreventCycles(aggressivelyPreventCycles)
        cpcstable.setVerbose(verbose)

        if priorKnowledge is not None:
            cpcstable.setKnowledge(priorKnowledge)

        tetradGraph = cpcstable.search()

        self.nodes = pycausal.extractTetradGraphNodes(tetradGraph)
        self.edges = pycausal.extractTetradGraphEdges(tetradGraph)
        self.graph = pycausal.generatePyDotGraph(self.nodes, self.edges)
Beispiel #6
0
    def __init__(self,
                 df,
                 continuous=True,
                 depth=3,
                 significance=0.05,
                 verbose=False,
                 priorKnowledge=None):
        indTest = None

        if (continuous):
            tetradData = pycausal.loadContinuousData(df)
            indTest = javabridge.JClassWrapper(
                'edu.cmu.tetrad.search.IndTestFisherZ')(tetradData,
                                                        significance)
        else:
            tetradData = pycausal.loadDiscreteData(df)
            indTest = javabridge.JClassWrapper(
                'edu.cmu.tetrad.search.IndTestChiSquare')(tetradData,
                                                          significance)

        ccd = javabridge.JClassWrapper('edu.cmu.tetrad.search.Ccd')(indTest)
        ccd.setDepth(depth)
        ccd.setVerbose(verbose)

        if priorKnowledge is not None:
            ccd.setKnowledge(priorKnowledge)

        tetradGraph = ccd.search()

        self.nodes = pycausal.extractTetradGraphNodes(tetradGraph)
        self.edges = pycausal.extractTetradGraphEdges(tetradGraph)
Beispiel #7
0
    def __init__(self,
                 df,
                 structurePrior=1.0,
                 samplePrior=1.0,
                 maxDegree=3,
                 faithfulnessAssumed=True,
                 numofthreads=2,
                 verbose=False,
                 priorKnowledge=None):

        tetradData = pycausal.loadDiscreteData(df)

        score = javabridge.JClassWrapper('edu.cmu.tetrad.search.BDeuScore')(
            tetradData)
        score.setStructurePrior(structurePrior)
        score.setSamplePrior(samplePrior)

        fgs = javabridge.JClassWrapper('edu.cmu.tetrad.search.Fgs')(score)
        fgs.setMaxDegree(maxDegree)
        fgs.setNumPatternsToStore(0)
        fgs.setFaithfulnessAssumed(faithfulnessAssumed)
        fgs.setParallelism(numofthreads)
        fgs.setVerbose(verbose)

        if priorKnowledge is not None:
            fgs.setKnowledge(priorKnowledge)

        tetradGraph = fgs.search()

        self.nodes = pycausal.extractTetradGraphNodes(tetradGraph)
        self.edges = pycausal.extractTetradGraphEdges(tetradGraph)
        self.graph = pycausal.generatePyDotGraph(self.nodes, self.edges)
Beispiel #8
0
    def __init__(self):
        algorithmAnnotations = javabridge.JClassWrapper("edu.cmu.tetrad.annotation.AlgorithmAnnotations")
        algoClasses = algorithmAnnotations.getInstance().getAnnotatedClasses()

        for i in range(0,algoClasses.size()):
            algo = algoClasses.get(i)
            algoType = str(algo.getAnnotation().algoType())
            if algoType != 'orient_pairwise':
                self.algos[str(algo.getAnnotation().command())] = algo
            
        testAnnotations = javabridge.JClassWrapper("edu.cmu.tetrad.annotation.TestOfIndependenceAnnotations")
        testClasses = testAnnotations.getInstance().getAnnotatedClasses()

        for i in range(0,testClasses.size()):
            test = testClasses.get(i)
            self.tests[str(test.getAnnotation().command())] = test

        scoreAnnotations = javabridge.JClassWrapper("edu.cmu.tetrad.annotation.ScoreAnnotations")
        scoreClasses = scoreAnnotations.getInstance().getAnnotatedClasses()

        for i in range(0,scoreClasses.size()):
            score = scoreClasses.get(i)
            self.scores[str(score.getAnnotation().command())] = score
            
        paramDescs = javabridge.JClassWrapper("edu.cmu.tetrad.util.ParamDescriptions")
        self.paramDescs = paramDescs.getInstance()

        self.algoFactory = javabridge.JClassWrapper("edu.cmu.tetrad.algcomparison.algorithm.AlgorithmFactory")
Beispiel #9
0
 def setUp(self):
     self.no_seq = J.JClassWrapper('java.lang.Integer')(3)
     self.a = J.JClassWrapper('java.util.ArrayList')()
     self.assertEquals(len(self.a), 0)
     self.ints = [0, 1, 2, 4, 8, 16]
     self.assertEquals(len(self.ints), 6)
     for i in self.ints:
         self.a.add(i)
Beispiel #10
0
 def __init__(self, df, dataType = 'continuous', numCategoriesToDiscretize = 4, depth = 3, alpha = 0.05, priorKnowledge = None, numBootstrap = -1, ensembleMethod = 'Highest'):
     tetradData = None
     indTest = None
     
     pc = self.pc
     
     # Continuous
     if dataType == 'continuous':
         if numBootstrap < 1:                
             tetradData = pc.loadContinuousData(df)
             indTest = javabridge.JClassWrapper('edu.cmu.tetrad.search.IndTestFisherZ')(tetradData, alpha)
         else:
             tetradData = pc.loadContinuousData(df, outputDataset = True)
             indTest = javabridge.JClassWrapper('edu.cmu.tetrad.algcomparison.independence.FisherZ')()
     # Discrete
     elif dataType == 'discrete':
         tetradData = pc.loadDiscreteData(df)
         if numBootstrap < 1:
             indTest = javabridge.JClassWrapper('edu.cmu.tetrad.search.IndTestChiSquare')(tetradData, alpha)
         else:
             indTest = javabridge.JClassWrapper('edu.cmu.tetrad.algcomparison.independence.ChiSquare')()
     # Mixed
     else:
         tetradData = pc.loadMixedData(df, numCategoriesToDiscretize)
         if numBootstrap < 1:
             indTest = javabridge.JClassWrapper('edu.cmu.tetrad.search.IndTestConditionalGaussianLRT')(tetradData, alpha, False)
         else:
             indTest = javabridge.JClassWrapper('edu.cmu.tetrad.algcomparison.independence.ConditionalGaussianLRT')()
     
     ccd = None
     
     if numBootstrap < 1:
         ccd = javabridge.JClassWrapper('edu.cmu.tetrad.search.Ccd')(indTest)
         ccd.setDepth(depth)
     else:
         algorithm = javabridge.JClassWrapper('edu.cmu.tetrad.algcomparison.algorithm.oracle.pag.Ccd')(indTest)
         
         parameters = javabridge.JClassWrapper('edu.cmu.tetrad.util.Parameters')()
         parameters.set('depth', depth)
         parameters.set('alpha', alpha)
         
         ccd = javabridge.JClassWrapper('edu.pitt.dbmi.algo.bootstrap.GeneralBootstrapTest')(tetradData, algorithm, numBootstrap)
         edgeEnsemble = javabridge.get_static_field('edu/pitt/dbmi/algo/bootstrap/BootstrapEdgeEnsemble',
                                            ensembleMethod,
                                            'Ledu/pitt/dbmi/algo/bootstrap/BootstrapEdgeEnsemble;')
         ccd.setEdgeEnsemble(edgeEnsemble)
         ccd.setParameters(parameters)
     
     if priorKnowledge is not None:    
         ccd.setKnowledge(priorKnowledge)
         
     self.tetradGraph = ccd.search()
     
     self.nodes = pc.extractTetradGraphNodes(self.tetradGraph)
     self.edges = pc.extractTetradGraphEdges(self.tetradGraph)
     self.graph = pc.generatePyDotGraph(self.nodes,self.edges,self.tetradGraph)
Beispiel #11
0
    def loadDiscreteData(self, df):
        tetradData = None

        if (len(df.index) * df.columns.size <= 1500):

            dataBox = javabridge.JClassWrapper(
                'edu.cmu.tetrad.data.VerticalIntDataBox')(len(df.index),
                                                          df.columns.size)

            node_list = javabridge.JClassWrapper('java.util.ArrayList')()
            col_no = 0
            for col in df.columns:

                cat_array = sorted(set(df[col]))
                cat_list = javabridge.JClassWrapper('java.util.ArrayList')()
                for cat in cat_array:
                    cat = str(cat)
                    cat_list.add(cat)

                nodname = javabridge.JClassWrapper('java.lang.String')(col)
                nodi = javabridge.JClassWrapper(
                    'edu.cmu.tetrad.data.DiscreteVariable')(nodname, cat_list)
                node_list.add(nodi)

                for row in df.index:
                    value = javabridge.JClassWrapper('java.lang.Integer')(
                        cat_array.index(df.iloc[row, col_no]))
                    dataBox.set(row, col_no, value)

                col_no = col_no + 1

            tetradData = javabridge.JClassWrapper(
                'edu.cmu.tetrad.data.BoxDataSet')(dataBox, node_list)

        else:
            # Generate random name
            temp_data_file = ''.join(
                random.choice(string.ascii_lowercase + string.digits)
                for _ in range(10)) + '.csv'
            temp_data_path = os.path.join(tempfile.gettempdir(),
                                          temp_data_file)
            df.to_csv(temp_data_path, sep="\t", index=False)

            # Read Data from File
            f = javabridge.JClassWrapper('java.io.File')(temp_data_path)
            delimiter = javabridge.get_static_field(
                'edu/pitt/dbmi/data/Delimiter', 'TAB',
                'Ledu/pitt/dbmi/data/Delimiter;')
            dataReader = javabridge.JClassWrapper(
                'edu.pitt.dbmi.data.reader.tabular.VerticalDiscreteTabularDataReader'
            )(f, delimiter)
            tetradData = dataReader.readInData()
            tetradData = javabridge.static_call(
                'edu/cmu/tetrad/util/DataConvertUtils', 'toDataModel',
                '(Ledu/pitt/dbmi/data/Dataset;)Ledu/cmu/tetrad/data/DataModel;',
                tetradData)

            os.remove(temp_data_path)

        return tetradData
Beispiel #12
0
    def __init__(self,
                 tetradGraph,
                 dfs,
                 dataType='continuous',
                 numCategoriesToDiscretize=4,
                 rule='R1',
                 score='andersonDarling',
                 alpha=0.01,
                 epsilon=1.0,
                 zeta=0.0,
                 orientStrongerDirection=False,
                 r2Orient2Cycles=True,
                 edgeCorrected=False,
                 selfLoopStrength=1.0):
        datasets = javabridge.JClassWrapper('java.util.ArrayList')()

        pc = self.pc

        for idx in range(len(dfs)):
            df = dfs[idx]
            tetradData = None
            # Continuous
            if dataType == 'continuous':
                tetradData = pc.loadContinuousData(df, outputDataset=True)
            # Discrete
            elif dataType == 'discrete':
                tetradData = pc.loadDiscreteData(df)
            # Mixed
            else:
                tetradData = pc.loadMixedData(df, numCategoriesToDiscretize)
            datasets.add(tetradData)

        lofs2 = javabridge.JClassWrapper('edu.cmu.tetrad.search.Lofs2')(
            tetradGraph, datasets)
        rule = javabridge.get_static_field(
            'edu/cmu/tetrad/search/Lofs2$Rule', rule,
            'Ledu/cmu/tetrad/search/Lofs2$Rule;')
        score = javabridge.get_static_field(
            'edu/cmu/tetrad/search/Lofs$Score', score,
            'Ledu/cmu/tetrad/search/Lofs$Score;')
        lofs2.setRule(rule)
        lofs2.setScore(score)
        lofs2.setAlpha(alpha)
        lofs2.setEpsilon(epsilon)
        lofs2.setZeta(zeta)
        lofs2.setOrientStrongerDirection(orientStrongerDirection)
        lofs2.setR2Orient2Cycles(r2Orient2Cycles)
        lofs2.setEdgeCorrected(edgeCorrected)
        lofs2.setSelfLoopStrength(selfLoopStrength)

        self.tetradGraph = lofs2.orient()

        self.nodes = pc.extractTetradGraphNodes(self.tetradGraph)
        self.edges = pc.extractTetradGraphEdges(self.tetradGraph)
 def __init__(self, num, figure):
     self.frame = javabridge.JClassWrapper('javax.swing.JFrame')()
     self.canvas = FigureCanvasSwing(figure)
     dimension = javabridge.JClassWrapper('java.awt.Dimension')(
         figure.bbox.width, figure.bbox.height)
     border_layout_cls = javabridge.JClassWrapper('java.awt.BorderLayout')
     self.canvas.component.setPreferredSize(dimension)
     self.frame.add(self.canvas.component, border_layout_cls.CENTER)
     self.toolbar = NavigationToolbar2Swing(self.canvas, self.frame)
     self.frame.pack()
     self.figmgr = FigureManagerSwing(self.canvas, num, self)
 def read_metadata_with_bioformats(self):
     # Using javabridge to parse and store all required metadata
     # -------------------------------------------------
     javabridge.start_vm(class_path=bioformats.JARS,
                         run_headless=True,
                         max_heap_size='2G')
     bioformats_log4j.basic_config()  # Configure logging for "WARN" level
     rdr = javabridge.JClassWrapper('loci.formats.in.ZeissCZIReader')()
     # ZeissCZIReader is the file format reader for Zeiss .czi files.
     # rdr = javabridge.JClassWrapper('loci.formats.in.OMETiffReader')()
     # OMETiffReader is the file format reader for OME-TIFF files
     rdr.setOriginalMetadataPopulated(True)
     # Specifies whether to save proprietary metadata in the MetadataStore.
     clsOMEXMLService = javabridge.JClassWrapper(
         'loci.formats.services.OMEXMLService')
     # Classes in loci.formats.services that implement OMEXMLService
     serviceFactory = javabridge.JClassWrapper(
         'loci.common.services.ServiceFactory')()
     # Constructor loading runtime initiation of services from the defult location
     service = serviceFactory.getInstance(
         clsOMEXMLService.klass
     )  # Retrieves an instance of a given service.
     omemetadata = service.createOMEXMLMetadata()
     # Creates OME-XML metadata object using reflection - avoids direct dependencies on loci.formats.ome package.
     rdr.setMetadataStore(
         omemetadata)  # Sets the default metadata store for this reader.
     rdr.setId(self.fname)
     # Initializes a reader from the input file name.
     # Calls initFile(String id) to initializes the input file
     # Reads all of the metadata and sets the reader up for reading planes. This can take time here...
     # rdr.saveOriginalMetadata = True
     orgmetadata = service.getOriginalMetadata(omemetadata)
     globalmetadata = rdr.getGlobalMetadata()
     # Obtains the hashtable containing the metadata field/value pairs from the current file.
     keys = globalmetadata.keySet().toString().split(',')
     nkeys = globalmetadata.size()
     metadatavalues = globalmetadata.values().toString().split(',')
     metadatakeys = globalmetadata.keys()
     # Get additional atrributes
     self.dimOrder = copy.deepcopy(rdr.getDimensionOrder())
     self.isChannelInterleaved = copy.deepcopy(rdr.isInterleaved())
     self.isDimOrderCertain = copy.deepcopy(rdr.isOrderCertain())
     for i in np.arange(0, nkeys):
         key = metadatakeys.nextElement()
         value = globalmetadata.get(key)
         # print(key,value)
         if key in zeiss_keymaps.linescan:
             self.metadata[
                 zeiss_keymaps.linescan[key]] = comfun.string_convert(value)
     # -----------------------------------
     javabridge.kill_vm()  # kill javabridge
     print(self.metadata)
     print('Metadata reading successful')
Beispiel #15
0
def loadDiscreteData(df):
    tetradData = None

    if (len(df.index) * df.columns.size <= 1500):

        dataBox = javabridge.JClassWrapper(
            'edu.cmu.tetrad.data.VerticalIntDataBox')(len(df.index),
                                                      df.columns.size)

        node_list = javabridge.JClassWrapper('java.util.ArrayList')()
        col_no = 0
        for col in df.columns:

            cat_array = sorted(set(df[col]))
            cat_list = javabridge.JClassWrapper('java.util.ArrayList')()
            for cat in cat_array:
                cat = str(cat)
                cat_list.add(cat)

            nodname = javabridge.JClassWrapper('java.lang.String')(col)
            nodi = javabridge.JClassWrapper(
                'edu.cmu.tetrad.data.DiscreteVariable')(nodname, cat_list)
            node_list.add(nodi)

            for row in df.index:
                value = javabridge.JClassWrapper('java.lang.Integer')(
                    cat_array.index(df.ix[row][col_no]))
                dataBox.set(row, col_no, value)

            col_no = col_no + 1

        tetradData = javabridge.JClassWrapper(
            'edu.cmu.tetrad.data.BoxDataSet')(dataBox, node_list)

    else:
        # Generate random name
        temp_data_file = ''.join(
            random.choice(string.lowercase) for i in range(10)) + '.csv'
        temp_data_path = os.path.join(tempfile.gettempdir(), temp_data_file)
        df.to_csv(temp_data_path, sep="\t", index=False)

        excludeVar = javabridge.JClassWrapper('java.util.HashSet')()
        excludeVar.add("MULT")

        # Read Data from File
        f = javabridge.JClassWrapper('java.nio.file.Paths').get(temp_data_path)
        dataReader = javabridge.JClassWrapper(
            'edu.cmu.tetrad.io.VerticalTabularDiscreteDataReader')(f, '\t')
        tetradData = dataReader.readInData(excludeVar)

        os.remove(temp_data_path)

    return tetradData
Beispiel #16
0
 def test_02_05_constructor_varargs(self):
     # Regression test of issue #41
     #
     args = ("foo", "bar")
     f = J.JClassWrapper("javax.swing.filechooser.FileNameExtensionFilter")(
         "baz", *args)
     exts = J.get_env().get_object_array_elements(f.getExtensions().o)
     self.assertEqual(args[0], J.to_string(exts[0]))
     self.assertEqual(args[1], J.to_string(exts[1]))
     # <AK> added
     with self.assertRaisesRegex(TypeError,
                                 "No matching constructor found"):
         f = J.JClassWrapper(
             "javax.swing.filechooser.FileNameExtensionFilter")()
 def __init__(self, canvas, frame):
     self._frame = frame
     self._tools = {}
     self._lastrect = None
     NavigationToolbar2.__init__(self, canvas)
     self._idle = True
     clsCursor = javabridge.JClassWrapper('java.awt.Cursor')
     self.cursor_map = {
         cursors.MOVE: clsCursor(clsCursor.MOVE_CURSOR),
         cursors.HAND: clsCursor(clsCursor.HAND_CURSOR),
         cursors.POINTER: clsCursor(clsCursor.DEFAULT_CURSOR),
         cursors.SELECT_REGION: clsCursor(clsCursor.CROSSHAIR_CURSOR)
     }
     self.white = javabridge.JClassWrapper('java.awt.Color').WHITE
Beispiel #18
0
    def getAlgorithmDescription(self, algoId):
        algo = self.algos.get(algoId)
        algoClass = algo.getClazz()
        
        algorithmDescriptions = javabridge.JClassWrapper("edu.cmu.tetrad.util.AlgorithmDescriptions")
        algoDescs = algorithmDescriptions.getInstance()

        print(algoDescs.get(algoId))
        algorithmAnnotations = javabridge.JClassWrapper("edu.cmu.tetrad.annotation.AlgorithmAnnotations")
        if algorithmAnnotations.getInstance().requireIndependenceTest(algoClass):
            print("\nIt requires the independence test.")
        if algorithmAnnotations.getInstance().requireScore(algoClass):
            print("\nIt requires the score.")
        if algorithmAnnotations.getInstance().acceptKnowledge(algoClass):
            print("\nIt accepts the prior knowledge.")
Beispiel #19
0
def cp_stop_vm(kill=True):
    '''Shut down the Java VM

    Check for headlessness and the state of ImageJ and take
    whatever action is needed to stop AWT and the JVM.
    '''
    from imagej.imagej2 import allow_quit, the_imagej_context

    try:
        ij1 = javabridge.JClassWrapper("ij.IJ").getInstance()
    except javabridge.JavaException as e:
        logger.debug("No available instance: %s" % str(e))
        ij1 = None

    if the_imagej_context is not None:
        #
        # Tell the app service that it's OK to quit without prompt
        #
        allow_quit()
        javabridge.call(the_imagej_context.getContext(), "dispose", "()V")
    if ij1 is not None:
        #
        # Yes, the proper way to get ImageJ to quit is
        # to start it.
        #
        ij1.run()
    if kill:
        javabridge.kill_vm()
Beispiel #20
0
 def patch_start_vm(*args, **kwargs):
     jvm_args = list(args[0]) + [
         "-Dloci.bioformats.loaded=true",
         "-Djava.util.prefs.PreferencesFactory=" +
         "org.cellprofiler.headlesspreferences" +
         ".HeadlessPreferencesFactory"
     ]
     add_logback_xml_arg(jvm_args)
     #
     # Find the ij1patcher
     #
     if hasattr(sys, 'frozen') and sys.platform == 'win32':
         root = os.path.dirname(sys.argv[0])
     else:
         root = os.path.dirname(__file__)
     jardir = os.path.join(root, "imagej", "jars")
     patchers = sorted([
         x for x in os.listdir(jardir)
         if x.startswith("ij1-patcher") and x.endswith(".jar")
     ])
     if len(patchers) > 0:
         jvm_args.append("-javaagent:%s=init" %
                         os.path.join(jardir, patchers[-1]))
     result = start_vm(jvm_args, *args[1:], **kwargs)
     if javabridge.get_env() is not None:
         try:
             event_service_cls = javabridge.JClassWrapper(
                 "org.bushe.swing.event.ThreadSafeEventService")
             event_service_cls.CLEANUP_PERIOD_MS_DEFAULT = None
         except:
             pass
     return result
Beispiel #21
0
def knowledge(forbiddirect=None, requiredirect=None, addtemporal=None):
    prior = javabridge.JClassWrapper('edu.cmu.tetrad.data.Knowledge2')()

    # forbidden directed edges
    if forbiddirect is not None:
        for i in range(0, len(forbiddirect)):
            forbid = forbiddirect[i]
            _from = forbid[0]
            _to = forbid[1]
            prior.setForbidden(_from, _to)

    # required directed edges
    if requiredirect is not None:
        for i in range(0, len(requiredirect)):
            require = requiredirect[i]
            _from = require[0]
            _to = require[1]
            prior.setRequired(_from, _to)

    # add temporal nodes' tiers
    if addtemporal is not None:
        for i in range(0, len(addtemporal)):
            tier = i
            temporal = addtemporal[i]
            if isinstance(temporal, ForbiddenWithin):
                prior.setTierForbiddenWithin(tier, True)
                temporal = temporal.nodes
            for j in range(0, len(temporal)):
                node = temporal[j]
                node = node.replace(' ', '.')
                prior.addToTier(tier, node)

    return prior
Beispiel #22
0
 def test_02_02_set_field(self):
     obj = J.JClassWrapper("org.cellprofiler.javabridge.test.RealRect")(1.5,
                                                                        2.5,
                                                                        3.5,
                                                                        4.5)
     obj.x = 2.5
     self.assertEquals(obj.x, 2.5)
    def test_01_03_globals(self):
        jglobals = javabridge.JClassWrapper('java.util.HashMap')()
        jref = javabridge.JClassWrapper('java.util.ArrayList')()
        jglobals.put("numerator", "6")
        jglobals.put("denominator", "2")
        jglobals.put("answer", jref.o)
        self.cpython.execute(
            """
global javabridge
import javabridge
def fn():
    result = int(numerator) / int(denominator)
    javabridge.call(answer, "add", "(Ljava/lang/Object;)Z", str(result))
fn()
""", None, jglobals.o)
        self.assertEqual(javabridge.to_string(jref.get(0)), "3")
Beispiel #24
0
    def loadContinuousData(self, df, outputDataset=False):
        tetradData = None

        if (len(df.index) * df.columns.size <= 1500):

            dataBox = javabridge.JClassWrapper(
                'edu.cmu.tetrad.data.DoubleDataBox')(len(df.index),
                                                     df.columns.size)

            node_list = javabridge.JClassWrapper('java.util.ArrayList')()
            col_no = 0
            for col in df.columns:
                nodi = javabridge.JClassWrapper(
                    'edu.cmu.tetrad.data.ContinuousVariable')(col)
                node_list.add(nodi)

                for row in df.index:
                    value = javabridge.JClassWrapper('java.lang.Double')(
                        df.iloc[row, col_no])
                    dataBox.set(row, col_no, value)

                col_no = col_no + 1

            tetradData = javabridge.JClassWrapper(
                'edu.cmu.tetrad.data.BoxDataSet')(dataBox, node_list)

        else:
            #Generate random name
            temp_data_file = ''.join(
                random.choice(string.ascii_lowercase + string.digits)
                for _ in range(10)) + '.csv'
            temp_data_path = os.path.join(tempfile.gettempdir(),
                                          temp_data_file)
            df.to_csv(temp_data_path, sep='\t', index=False)

            # Read Data from File
            f = javabridge.JClassWrapper('java.io.File')(temp_data_path)
            path = f.toPath()
            delimiter = javabridge.get_static_field(
                'edu/pitt/dbmi/data/reader/Delimiter', 'TAB',
                'Ledu/pitt/dbmi/data/reader/Delimiter;')
            dataReader = javabridge.JClassWrapper(
                'edu.pitt.dbmi.data.reader.tabular.ContinuousTabularDatasetFileReader'
            )(path, delimiter)
            tetradData = dataReader.readInData()
            tetradData = javabridge.static_call(
                'edu/cmu/tetrad/util/DataConvertUtils', 'toDataModel',
                '(Ledu/pitt/dbmi/data/reader/Data;)Ledu/cmu/tetrad/data/DataModel;',
                tetradData)

            os.remove(temp_data_path)

        if (not outputDataset):
            tetradData = javabridge.JClassWrapper(
                'edu.cmu.tetrad.data.CovarianceMatrixOnTheFly')(tetradData)

        return tetradData
Beispiel #25
0
def popup_script_dlg(canvas):
    joptionpane = javabridge.JClassWrapper("javax.swing.JOptionPane")
    jresult = joptionpane.showInputDialog("Enter a script command")
    if jresult is not None:
        result = javabridge.to_string(jresult)
        axes = canvas.figure.axes[0]
        eval(result, globals(), locals())
        canvas.draw()
    def test_01_02_locals(self):
        jlocals = javabridge.JClassWrapper('java.util.HashMap')()
        jref = javabridge.JClassWrapper('java.util.ArrayList')()
        jlocals.put("numerator", "6")
        jlocals.put("denominator", "2")
        code = """
global javabridge
import javabridge
def fn(numerator, denominator, answer):
    result = int(numerator) / int(denominator)
    javabridge.call(answer, "add", "(Ljava/lang/Object;)Z", str(result))
fn(numerator, denominator, answer)
"""
        jlocals.put("code", code)
        jlocals.put("answer", jref.o)
        self.cpython.execute(code, jlocals.o, None)
        self.assertEqual(float(javabridge.to_string(jref.get(0))), 3)
Beispiel #27
0
 def test_02_05_constructor_varargs(self):
     # Regression test of issue #41
     #
     args = ("foo", "bar")
     f = J.JClassWrapper("javax.swing.filechooser.FileNameExtensionFilter")(
         "baz", *args)
     exts = J.get_env().get_object_array_elements(f.getExtensions().o)
     self.assertEqual(args[0], J.to_string(exts[0]))
     self.assertEqual(args[1], J.to_string(exts[1]))
Beispiel #28
0
 def test_02_04_static_call_varargs(self):
     #
     # Test calling a static function with a variable number of
     # arguments.
     #
     c = J.JClassWrapper("java.lang.String")
     self.assertEquals(c.format("Hello, %s.", "world"), "Hello, world.")
     self.assertEquals(c.format("Goodbye %s %s.", "cruel", "world"),
                       "Goodbye cruel world.")
    def test_01_04_globals_equals_locals(self):
        jglobals = javabridge.JClassWrapper('java.util.HashMap')()
        jref = javabridge.JClassWrapper('java.util.ArrayList')()
        jglobals.put("numerator", "6")
        jglobals.put("denominator", "2")
        jglobals.put("answer", jref.o)
        #
        # The import will be added to "locals", but that will be the globals.
        #
        self.cpython.execute(
            """
import javabridge
def fn():
    result = int(numerator) / int(denominator)
    javabridge.call(answer, "add", "(Ljava/lang/Object;)Z", str(result))
fn()
""", jglobals.o, jglobals.o)
        self.assertEqual(float(javabridge.to_string(jref.get(0))), 3)
Beispiel #30
0
 def patch_start_vm(*args, **kwargs):
     result = start_vm(*args, **kwargs)
     if javabridge.get_env() is not None:
         try:
             event_service_cls = javabridge.JClassWrapper(
                 "org.bushe.swing.event.ThreadSafeEventService")
             event_service_cls.CLEANUP_PERIOD_MS_DEFAULT = None
         except:
             pass
     return result