def _generateJSON(self, seriesUIDs):
        data = self._getGeneralMetaInformation()
        data['imageLibrary'] = []

        params = {"metaDataFileName": os.path.join(self.tempDir, "meta.json")}
        acqTypes = self._getAcquisitionTypes()
        data["compositeContext"], params[
            "compositeContextDataDir"] = self._populateCompositeContext(
                seriesUIDs)

        seriesDirs = set(
            os.path.dirname(os.path.abspath(self.db.filesForSeries(series)[0]))
            for series in seriesUIDs)
        params["imageLibraryDataDir"] = os.path.commonprefix(list(seriesDirs))

        for series in seriesUIDs:
            try:
                data['imageLibrary'].append(
                    self._createImageLibraryEntry(series, acqTypes, params,
                                                  len(seriesDirs) > 1))
            except ValueError as exc:
                print(exc)

        if not data['imageLibrary']:
            raise ValueError(
                "No eligible series has been found for PIRADS reading!")

        if not os.path.exists(self.tempDir):
            ModuleLogicMixin.createDirectory(self.tempDir)
        with open(params['metaDataFileName'], 'w') as outfile:
            json.dump(data, outfile, indent=2)

        return params
Beispiel #2
0
  def generateReport(self):

    def currentDateTime():
      from datetime import datetime
      return  datetime.now().strftime('%Y-%m-%d_%H%M%S')

    html = self.template.format(self.style, self.getData())

    outputPath = os.path.join(slicer.app.temporaryPath, "QIICR", "QR")
    if not os.path.exists(outputPath):
      ModuleLogicMixin.createDirectory(outputPath)
    outputHTML = os.path.join(outputPath, currentDateTime()+"_testReport.html")
    print outputHTML
    f = open(outputHTML, 'w')
    f.write(html)
    f.close()
    webbrowser.open("file:///private"+outputHTML)
Beispiel #3
0
    def generateReport(self):
        def currentDateTime():
            from datetime import datetime
            return datetime.now().strftime('%Y-%m-%d_%H%M%S')

        html = self.template.format(self.style, self.getData())

        outputPath = os.path.join(slicer.app.temporaryPath, "QIICR", "QR")
        if not os.path.exists(outputPath):
            ModuleLogicMixin.createDirectory(outputPath)
        outputHTML = os.path.join(outputPath,
                                  currentDateTime() + "_testReport.html")
        print(outputHTML)
        f = open(outputHTML, 'w')
        f.write(html)
        f.close()
        webbrowser.open("file:///private" + outputHTML)
    def load(self, loadable):

        uid = loadable.uids[0]
        self.tempDir = os.path.join(slicer.app.temporaryPath, self.TEMPLATE_ID,
                                    self.currentDateTime)
        if not os.path.exists(self.tempDir):
            ModuleLogicMixin.createDirectory(self.tempDir)

        outputFile = os.path.join(self.tempDir, "{}.json".format(uid))

        srFileName = self.db.fileForInstance(uid)
        if srFileName is None:
            logging.debug(
                'Failed to get the filename from the DICOM database for ', uid)
            return False

        param = {
            "inputDICOM": srFileName,
            "metaDataFileName": outputFile,
        }

        cliNode = slicer.cli.run(slicer.modules.qiicrxsr,
                                 None,
                                 param,
                                 wait_for_completion=True)
        if cliNode.GetStatusString() != 'Completed':
            logging.debug(
                'qiicrxsr did not complete successfully, unable to load DICOM {}'
                .format(self.TEMPLATE_ID))
            # self.cleanup()
            return False

        with open(outputFile) as metaFile:
            data = json.load(metaFile)
            for imageLibraryEntry in data['imageLibrary']:
                files = [
                    self.db.fileForInstance(e)
                    for e in imageLibraryEntry['instanceUIDs']
                ]
                self.loadSeries(files)

        return True
  def generateReport(self):

    def currentDateTime():
      from datetime import datetime
      return  datetime.now().strftime('%Y-%m-%d_%H%M%S')

    html = self.template.format(self.style, self.getData())

    outputPath = os.path.join(slicer.app.temporaryPath, "QIICR", "QR")
    if not os.path.exists(outputPath):
      ModuleLogicMixin.createDirectory(outputPath)
    outputHTML = os.path.join(outputPath, currentDateTime()+"_testReport.html")
    print(outputHTML)
    f = open(outputHTML, 'w')
    f.write(html)
    f.close()

    # Open the html report in the default web browser
    import qt
    qt.QDesktopServices.openUrl(qt.QUrl.fromLocalFile(outputHTML));
def copyData(data, outputDir):

    logic = DeepInfer.DeepInferLogic()
    parameters = DeepInfer.ModelParameters()
    segmenter_json_file = os.path.join(DeepInfer.JSON_LOCAL_DIR,
                                       "ProstateNeedleFinder.json")
    with open(segmenter_json_file, "r") as fp:
        j = json.load(fp, object_pairs_hook=OrderedDict)

    iodict = parameters.create_iodict(j)
    dockerName, modelName, dataPath = parameters.create_model_info(j)

    csvData = [[
        'Case', 'SeriesNumber', 'TargetName', 'Pos', 'NeedleDistance',
        'ErrorVector', 'Comment'
    ]]

    for case, caseData in data.iteritems():
        if not caseData:
            continue
        outputCaseDir = os.path.join(outputDir, case)
        if not os.path.exists(outputCaseDir):
            ModuleLogicMixin.createDirectory(outputCaseDir)

        print "processing data of case %s" % case

        for data in caseData:
            seriesNumber = data["seriesNumber"]

            inputs = dict()

            temp = os.path.join(outputCaseDir,
                                "{}-label.nrrd".format(seriesNumber))
            if not os.path.exists(temp):
                copy(os.path.join(data["path"], data["label"]), temp)
            # success, inputs['InputProstateMask'] = slicer.util.loadLabelVolume(temp, returnNode=True)

            temp = os.path.join(outputCaseDir,
                                "{}-volume.nrrd".format(seriesNumber))
            if not os.path.exists(temp):
                copy(os.path.join(data["path"], data["volume"]), temp)
            # success, inputs['InputVolume'] = slicer.util.loadVolume(temp, returnNode=True)

            temp = os.path.join(outputCaseDir,
                                "{}-targets.fcsv".format(seriesNumber))
            if not os.path.exists(temp):
                copy(os.path.join(data["path"], data["targets"]), temp)
            success, targetNode = slicer.util.loadMarkupsFiducialList(
                temp, returnNode=True)

            temp = os.path.join(outputCaseDir,
                                "{}-needle-label.nrrd".format(seriesNumber))
            if not os.path.exists(temp):
                outputs = dict()
                outputs['OutputLabel'] = slicer.mrmlScene.AddNewNodeByClass(
                    "vtkMRMLLabelMapVolumeNode")
                outputs[
                    'OutputFiducialList'] = slicer.mrmlScene.AddNewNodeByClass(
                        "vtkMRMLMarkupsFiducialNode")

                params = dict()
                params['InferenceType'] = 'Ensemble'

                logic.executeDocker(dockerName, modelName, dataPath, iodict,
                                    inputs, params)
                logic.updateOutput(iodict, outputs)

                ModuleLogicMixin.saveNodeData(
                    outputs['OutputLabel'],
                    outputCaseDir,
                    FileExtension.NRRD,
                    name="{}-needle-label".format(seriesNumber))
                ModuleLogicMixin.saveNodeData(
                    outputs['OutputFiducialList'],
                    outputCaseDir,
                    FileExtension.FCSV,
                    name="{}-needle-tip".format(seriesNumber))

            temp = os.path.join(
                outputCaseDir,
                "{}-needle-centerline.fcsv".format(seriesNumber))
            if not os.path.exists(temp):
                centerLine = CenterLinePoints(
                    os.path.join(outputCaseDir,
                                 "{}-needle-label.nrrd".format(seriesNumber)))
                points_ijk = centerLine.get_needle_points_ijk()
                points_ras = centerLine.convert_points_ijk_to_ras(points_ijk)
                centerLineNode = slicer.mrmlScene.AddNewNodeByClass(
                    "vtkMRMLMarkupsFiducialNode")
                for point in points_ras:
                    centerLineNode.AddFiducialFromArray(point)
                centerLineNode.SetLocked(True)
                ModuleLogicMixin.saveNodeData(
                    centerLineNode,
                    outputCaseDir,
                    FileExtension.FCSV,
                    name="{}-needle-centerline".format(seriesNumber))

            success, centerLineNode = slicer.util.loadMarkupsFiducialList(
                temp, returnNode=True)
            if not centerLineNode.GetNumberOfFiducials():
                csvData.append([
                    case, seriesNumber, "", "", "", "",
                    "No centerline was found"
                ])
            else:
                cmLogic = CurveMaker.CurveMakerLogic()
                cmLogic.DestinationNode = slicer.mrmlScene.CreateNodeByClass(
                    "vtkMRMLModelNode")
                cmLogic.SourceNode = centerLineNode
                cmLogic.updateCurve()

                cmLogic.CurvePoly = vtk.vtkPolyData()
                cmLogic.enableAutomaticUpdate(1)

                for idx in range(targetNode.GetNumberOfFiducials()):
                    targetName = targetNode.GetNthFiducialLabel(idx)
                    if targetName.lower() in ["right", "left"]:
                        continue
                    pos = ModuleLogicMixin.getTargetPosition(targetNode, idx)
                    (distance,
                     minErrorVec) = cmLogic.distanceToPoint(pos, True)
                    # print "{}: {} ({})".format(targetName, distance, minErrorVec)

                    csvData.append([
                        case, seriesNumber, targetName, pos, distance,
                        minErrorVec, ""
                    ])

                def cleanup():
                    slicer.mrmlScene.RemoveNode(cmLogic.DestinationNode)

                cleanup()

    return csvData