示例#1
0
 def _enableUpgradeFlag(self):
     """Setup upgrade flag to application config
     """
     AppConfigurationService().add("Temp")
     AppConfigurationService().set("Temp", "isUpgrading", str(True))
     AppConfigurationService().set("Temp", "upgradeFinished", str(False))
     AppConfigurationService().saveConfiguration()
示例#2
0
    def __init__(self, parent=None):
        """Constructor of ExportModule View
        """
        QWidget.__init__(self, parent)
        self.parent = parent

        #-----------------------------------------------------------------------
        #----------------------- Logger ----------------------------------------
        self.logger = logging.getLogger(__name__)
        logging.config.fileConfig('logging.ini',
                                  disable_existing_loggers=False)
        #-----------------------------------------------------------------------
        #---------------------- App config --------------------------------------
        self.appConfig = AppConfigurationService()
        #-----------------------------------------------------------------------
        #--------------------- Create Module UI --------------------------------
        self.setupUi(self)
        #-----------------------------------------------------------------------
        #----------------------- Services --------------------------------------
        # There are two http services, one for communicating with my own
        # site server/database
        section = "RadPlanBioServer"
        hostname = self.appConfig.get(section)["host"]
        port = self.appConfig.get(section)["port"]
        self.svcHttp = HttpConnectionService(hostname, port, UserDetails())

        #TODO: SiteName according to user account
        self.mySite = self.svcHttp.getPartnerSiteByName("DKTK-DRESDEN")
        baseUrl = self.mySite.edc.soapbaseurl

        # Create connection artefact to OC
        self.ocConnectInfo = OCConnectInfo(baseUrl, OCUserDetails().username)
        self.ocConnectInfo.setPassword(OCUserDetails().password)
        self.ocWebServices = OCWebServices(self.ocConnectInfo)

        # Create REST mainzellieste
        userName = self.mySite.pidg.adminusername
        password = self.mySite.pidg.adminpassword
        baseUrl = self.mySite.pidg.generatorbaseurl
        apiKey = self.mySite.pidg.apikey

        connectInfo = MainzellisteConnectInfo(baseUrl, userName, password,
                                              apiKey)
        self.svcPseudonymisation = PseudonymisationService(connectInfo)
        #-----------------------------------------------------------------------
        #----------------------- On Create -------------------------------------
        self.reloadSites()
        #-----------------------------------------------------------------------
        #---------- Load modules buttons - events definitions ------------------
        self.btnNew.clicked.connect(self.btnNewClicked)
        self.btnReload.clicked.connect(self.btnReloadClicked)
        self.tvStudies.selectionModel().currentChanged.connect(
            self.tvStudyChanged)
示例#3
0
def startup():
    """Start the updater
    """
    logger = logging.getLogger(__name__)
    logging.config.fileConfig("logging.ini", disable_existing_loggers=False)

    logger.info("Updater folder contains: ")
    logger.info(os.listdir("./"))

    appConfig = None
    # Running from source or packed executable
    if (os.path.isfile("mainClient.py")
            or os.path.isfile("RadPlanBio-client.exe")):
        appConfig = AppConfigurationService("radplanbio-client.cfg")
    else:
        appConfig = AppConfigurationService("../radplanbio-client.cfg")

    section = "Temp"
    if appConfig.hasSection(section):
        isUpgrading = appConfig.get(section)["isupgrading"]
        upgradeFinished = appConfig.get(section)["upgradefinished"]

        app = QtGui.QApplication(sys.argv)

        # Startup
        if isUpgrading == "False":
            # Exit updater
            app.quit()
        else:
            # Start upgrade procedure
            svcUpgrade = UpgradeService()
            svcUpgrade.upgrade()

            # Start client (RadPlanBio-client.exe)
            if platform.system() == "Windows":
                if os.path.isfile("../RadPlanBio-client.exe"):
                    QtCore.QProcess.startDetached("../RadPlanBio-client.exe")
                elif os.path.isfile("RadPlanBio-client.exe"):
                    QtCore.QProcess.startDetached("RadPlanBio-client.exe")
                else:
                    QtCore.QProcess.startDetached("python mainClient.py")
            elif platform.system() == "Linux":
                if os.path.isfile("../RadPlanBio-client"):
                    QtCore.QProcess.startDetached("../RadPlanBio-client")
                else:
                    QtCore.QProcess.startDetached("python mainClient.py")
            else:
                QtCore.QProcess.startDetached("python mainClient.py")

            # Exit updater
            app.quit()
def configure():
    """Read configuration settings from config file
    """
    appConfig = AppConfigurationService(ConfigDetails().configFileName)
    
    section = "OpenClinica"
    if appConfig.hasSection(section):
        option = "host"
        if appConfig.hasOption(section, option):
            ConfigDetails().ocHost = appConfig.get(section)[option]
        option = "port"
        if appConfig.hasOption(section, option):
            ConfigDetails().ocPort = appConfig.get(section)[option]

    section = "OpenClinica-ws"
    if appConfig.hasSection(section):
        option = "host"
        if appConfig.hasOption(section, option):
            ConfigDetails().ocWsHost = appConfig.get(section)[option]
        option = "port"
        if appConfig.hasOption(section, option):
            ConfigDetails().ocWsPort = appConfig.get(section)[option]

    section = "Proxy"
    if appConfig.hasSection(section):
        option = "enabled"
        if appConfig.hasOption(section, option):
            ConfigDetails().proxyEnabled = appConfig.getboolean(section, option)
        option = "host"
        if appConfig.hasOption(section, option):
            ConfigDetails().proxyHost = appConfig.get(section)[option]
        option = "port"
        if appConfig.hasOption(section, option):
            ConfigDetails().proxyPort = appConfig.get(section)[option]
        option = "noproxy"
        if appConfig.hasOption(section, option):
            ConfigDetails().noProxy = appConfig.get(section)[option]

    section = "Proxy-auth"
    if appConfig.hasSection(section):
        option = "enabled"
        if appConfig.hasOption(section, option):
            ConfigDetails().proxyAuthEnabled = appConfig.getboolean(section, option)
        option = "login"
        if appConfig.hasOption(section, option):
            ConfigDetails().proxyAuthLogin = appConfig.get(section)[option]
        option = "password"
        if appConfig.hasOption(section, option):
            ConfigDetails().proxyAuthPassword = appConfig.get(section)[option]

    section = "GUI"
    if appConfig.hasSection(section):
        option = "main.width"
        if appConfig.hasOption(section, option):
            ConfigDetails().width = int(appConfig.get(section)[option])
        option = "main.height"
        if appConfig.hasOption(section, option):
            ConfigDetails().height = int(appConfig.get(section)[option])
示例#5
0
class CreateSubjectModule(QWidget, CreateSubjectModuleUI):
    """PullDataRequest Module view class
    """

    #----------------------------------------------------------------------
    #--------------------------- Constructors -----------------------------

    def __init__(self, parent=None):
        """Constructor of ExportModule View
        """
        QWidget.__init__(self, parent)
        self.parent = parent

        #-----------------------------------------------------------------------
        #----------------------- Logger ----------------------------------------
        self.logger = logging.getLogger(__name__)
        logging.config.fileConfig('logging.ini',
                                  disable_existing_loggers=False)
        #-----------------------------------------------------------------------
        #---------------------- App config --------------------------------------
        self.appConfig = AppConfigurationService()
        #-----------------------------------------------------------------------
        #--------------------- Create Module UI --------------------------------
        self.setupUi(self)
        #-----------------------------------------------------------------------
        #----------------------- Services --------------------------------------
        # There are two http services, one for communicating with my own
        # site server/database
        section = "RadPlanBioServer"
        hostname = self.appConfig.get(section)["host"]
        port = self.appConfig.get(section)["port"]
        self.svcHttp = HttpConnectionService(hostname, port, UserDetails())

        #TODO: SiteName according to user account
        self.mySite = self.svcHttp.getPartnerSiteByName("DKTK-DRESDEN")
        baseUrl = self.mySite.edc.soapbaseurl

        # Create connection artefact to OC
        self.ocConnectInfo = OCConnectInfo(baseUrl, OCUserDetails().username)
        self.ocConnectInfo.setPassword(OCUserDetails().password)
        self.ocWebServices = OCWebServices(self.ocConnectInfo)

        # Create REST mainzellieste
        userName = self.mySite.pidg.adminusername
        password = self.mySite.pidg.adminpassword
        baseUrl = self.mySite.pidg.generatorbaseurl
        apiKey = self.mySite.pidg.apikey

        connectInfo = MainzellisteConnectInfo(baseUrl, userName, password,
                                              apiKey)
        self.svcPseudonymisation = PseudonymisationService(connectInfo)
        #-----------------------------------------------------------------------
        #----------------------- On Create -------------------------------------
        self.reloadSites()
        #-----------------------------------------------------------------------
        #---------- Load modules buttons - events definitions ------------------
        self.btnNew.clicked.connect(self.btnNewClicked)
        self.btnReload.clicked.connect(self.btnReloadClicked)
        self.tvStudies.selectionModel().currentChanged.connect(
            self.tvStudyChanged)

    #----------------------------------------------------------------------
    #------------------- Module buttons Handlers --------------------------

    def btnNewClicked(self):
        """
        """
        index = self.tabCreateSubjectModule.currentIndex()

        if index == 1:
            # Initialize dialog and bind data to UI
            dialog = NewSubjectDialog(self)
            dialog.svcPseudonymisation = self.svcPseudonymisation
            dialog.setData(self.selectedStudy, self.selectedStudySite)

            # Show dialog
            dialogResult = dialog.exec_()

            # When ok commit session transaction
            if dialogResult == QtGui.QDialog.Accepted:
                try:
                    newStudySubject = dialog.newStudySubject
                    self.ocWebServices.createStudySubject(
                        newStudySubject, self.selectedStudy,
                        self.selectedStudySite)
                except:
                    QtGui.QMessageBox.warning(self, 'Error',
                                              'OC study subject not created.')

            # Reload
            index = self.tabCreateSubjectModule.currentIndex()
            self.loadModuleData(index)
        elif index == 2:
            studyEvents = self.ocWebServices.listAllStydyEventDefinitionsByStudy(
                self.selectedStudy)

            dialog = NewEventDialog(self)
            dialog.setData(self.selectedStudy, self.selectedStudySite,
                           self.selectedSubject, studyEvents)

            # Show dialog
            dialogResult = dialog.exec_()

            # When ok commit session transaction
            if dialogResult == QtGui.QDialog.Accepted:
                #try:
                unsheduledEvent = dialog.selectedEvent
                self.ocWebServices.scheduleStudyEvent(self.selectedStudy,
                                                      self.selectedStudySite,
                                                      self.selectedSubject,
                                                      unsheduledEvent)
                #except:
                #    QtGui.QMessageBox.warning(self, 'Error', 'OC study event was not sheduled.')

            # Reload
            index = self.tabCreateSubjectModule.currentIndex()
            self.loadModuleData(index)

    def btnReloadClicked(self):
        """
        """
        index = self.tabCreateSubjectModule.currentIndex()
        self.loadModuleData(index)

    #----------------------------------------------------------------------
    #------------------- TableView Handlers -------------------------------

    def tvStudyChanged(self, current, previous):
        self.tvSubjects.setModel(None)

        index = current.row()

        self.selectedStudy = None
        self.selectedStudySite = None

        counter = 0
        found = False
        for study in self.studies:
            for site in study.sites:
                if counter == index:
                    self.selectedStudy = study
                    self.selectedStudySite = site
                    found = True
                    break
                else:
                    counter = counter + 1

            if found:
                break

        if found:
            self.reloadSubjects()

    def tvSubjectChanged(self, current, previous):
        index = current.row()

        self.selectedSubject = self.subjects[index]

        self.reloadEvents()

    def tvEventsChanged(self, current, previous):
        index = current.row()

        self.selectedEvent = self.events[index]

    #----------------------------------------------------------------------
    #------------------------ Module commands -----------------------------

    def loadModuleData(self, selectedIndex):
        if selectedIndex == 0:
            self.reloadSites()
            self.tvStudies.selectionModel().currentChanged.connect(
                self.tvStudyChanged)
        elif selectedIndex == 1:
            self.reloadSubjects()
            self.tvSubjects.selectionModel().currentChanged.connect(
                self.tvSubjectChanged)
        elif selectedIndex == 2:
            self.reloadSubjects()
            self.tvSubjects.selectionModel().currentChanged.connect(
                self.tvSubjectChanged)

            self.selectedSubject = first.first(
                subject for subject in self.subjects
                if subject.subject.uniqueIdentifier ==
                self.selectedSubject.subject.uniqueIdentifier)

            self.reloadEvents()
            self.tvEvents.selectionModel().currentChanged.connect(
                self.tvEventsChanged)

    def reloadSites(self):
        successfull, self.studies = self.ocWebServices.listAllStudies()

        # Quick way of crating simple viewModel
        self.studySitesModel = QtGui.QStandardItemModel()
        self.studySitesModel.setHorizontalHeaderLabels(
            ["OID", "Partner Site", "Study"])

        row = 0
        for study in self.studies:
            if len(study.sites) > 0:
                for site in study.sites:
                    siteOidValue = QtGui.QStandardItem(site.oid)
                    siteNameValue = QtGui.QStandardItem(site.name)
                    studyNameValue = QtGui.QStandardItem(study.name())

                    self.studySitesModel.setItem(row, 0, siteOidValue)
                    self.studySitesModel.setItem(row, 1, siteNameValue)
                    self.studySitesModel.setItem(row, 2, studyNameValue)

                    row = row + 1

        self.tvStudies.setModel(self.studySitesModel)
        self.tvStudies.resizeColumnsToContents()

    def reloadSubjects(self):
        self.subjects = self.ocWebServices.listAllStudySubjectsByStudySite(
            self.selectedStudy, self.selectedStudySite)

        # Quick way of crating simple viewModel
        self.subjectsModel = QtGui.QStandardItemModel()
        self.subjectsModel.setHorizontalHeaderLabels(
            ["PID", "Gender", "Enrollment date"])

        row = 0
        for studySubject in self.subjects:
            pidItem = QtGui.QStandardItem(
                studySubject.subject.uniqueIdentifier)
            genderItem = QtGui.QStandardItem(studySubject.subject.gender)
            enrollmentDateItem = QtGui.QStandardItem(
                studySubject.enrollmentDate)

            self.subjectsModel.setItem(row, 0, pidItem)
            self.subjectsModel.setItem(row, 1, genderItem)
            self.subjectsModel.setItem(row, 2, enrollmentDateItem)

            row = row + 1

        self.tvSubjects.setModel(self.subjectsModel)
        self.tvSubjects.resizeColumnsToContents()

    def reloadEvents(self):
        self.events = self.selectedSubject.events

        # Quick way of crating simple viewModel
        self.eventsModel = QtGui.QStandardItemModel()
        self.eventsModel.setHorizontalHeaderLabels(["Event OID", "Start date"])

        row = 0
        for event in self.events:
            oidItem = QtGui.QStandardItem(event.eventDefinitionOID)
            startDateItem = QtGui.QStandardItem(event.startDate.isoformat())

            self.eventsModel.setItem(row, 0, oidItem)
            self.eventsModel.setItem(row, 1, startDateItem)

            row = row + 1

        self.tvEvents.setModel(self.eventsModel)
        self.tvEvents.resizeColumnsToContents()
示例#6
0
 def _disableUpgradeFlag(self):
     """Remove upgrade flag from application config
     """
     AppConfigurationService().remove("Temp")
     AppConfigurationService().saveConfiguration()
示例#7
0
 def _enableUpgradeFinishedFlag(self):
     """
     """
     AppConfigurationService().set("Temp", "isUpgrading", str(False))
     AppConfigurationService().set("Temp", "upgradeFinished", str(True))
     AppConfigurationService().saveConfiguration()
示例#8
0
    def __init__(self, parent=None):
        """Constructor of ExportModule View
        """
        QWidget.__init__(self, parent)
        self.parent = parent

        #-----------------------------------------------------------------------
        #----------------------- Logger ----------------------------------------
        self.logger = logging.getLogger(__name__)
        logging.config.fileConfig('logging.ini',
                                  disable_existing_loggers=False)
        #-----------------------------------------------------------------------
        #---------------------- App config --------------------------------------
        self.appConfig = AppConfigurationService()
        #-----------------------------------------------------------------------
        #--------------------- Create Module UI --------------------------------
        self.setupUi(self)
        #-----------------------------------------------------------------------
        #---------- Load modules buttons - events definitions ------------------
        self.btnReload.clicked.connect(self.btnReloadClicked)

        self.btnMapExportField.clicked.connect(self.btnMapExportFieldClicked)

        self.btnLocateDataFilename.clicked.connect(
            self.btnLocateDataFilenameClicked)
        self.btnLocateMetaDataFilename.clicked.connect(
            self.btnLocateMetaDataFilenameClicked)
        self.btnValidateMapping.clicked.connect(
            self.btnValidateDataTransformationClicked)
        self.btnLoadMapping.clicked.connect(self.btnLoadMappingClicked)

        self.cmbStudyEvent.currentIndexChanged['QString'].connect(
            self.cmbStudyEventChanged)
        self.cmbEventForm.currentIndexChanged['QString'].connect(
            self.cmbEventFormChanged)
        #-----------------------------------------------------------------------
        # Domain model
        self.__study = None
        self.__studyEvents = []
        self.__selectedStudyEvent = None
        self.__studyEventCrfs = []
        self.__selectedEventCrf = None

        #-----------------------------------------------------------------------
        #----------------------- Services --------------------------------------
        # There are two http services, one for communicating with my own
        # site server/database
        section = "MySiteServer"
        hostname = self.appConfig.get(section)["host"]
        port = self.appConfig.get(section)["port"]
        self.svcHttp = HttpConnectionService(hostname, port, UserDetails())

        self.reload()

        #-----------------------------------------------------------------------
        # TODO: make it a Stragety desing pattern later
        self.fileDataService = CsvFileDataService()
        self.fileMetaDataService = OdmFileDataService()
        self.exportMapping = []

        # Just for testing to have guick access to files
        self.dataFilename = "/mnt/edv/skripcakt/ulice/branches/radplanbio/data/radiochemotherapy.csv"
        self.metaDataFilename = "/mnt/edv/skripcakt/ulice/branches/radplanbio/data/HNSCCStudyMetadata.xml"

        #-----------------------------------------------------------------------
        # Create REST mainzellieste
        userName = "******"
        password = "******"
        baseUrl = "http://g89rtpsrv.med.tu-dresden.de:8080/mainzelliste-1.1-SNAPSHOT/"
        apiKey = "mdatdd"

        connectInfo = MainzellisteConnectInfo(baseUrl, userName, password,
                                              apiKey)
        self.svcPseudonymisation = PseudonymisationService(connectInfo)
示例#9
0
class ExportModule(QWidget, ExportModuleUI):
    """Export Module view class

    Export Module is class inerited from ExportModuleUI. There the GUI layout
    and elements are defined. In this class the handlers aka View application
    logic is defined. Handler are invoking functionality which is provided in
    bussiness layer of the application (services, domain).
    """

    #----------------------------------------------------------------------
    #--------------------------- Constructors -----------------------------

    def __init__(self, parent=None):
        """Constructor of ExportModule View
        """
        QWidget.__init__(self, parent)
        self.parent = parent

        #-----------------------------------------------------------------------
        #----------------------- Logger ----------------------------------------
        self.logger = logging.getLogger(__name__)
        logging.config.fileConfig('logging.ini',
                                  disable_existing_loggers=False)
        #-----------------------------------------------------------------------
        #---------------------- App config --------------------------------------
        self.appConfig = AppConfigurationService()
        #-----------------------------------------------------------------------
        #--------------------- Create Module UI --------------------------------
        self.setupUi(self)
        #-----------------------------------------------------------------------
        #---------- Load modules buttons - events definitions ------------------
        self.btnReload.clicked.connect(self.btnReloadClicked)

        self.btnMapExportField.clicked.connect(self.btnMapExportFieldClicked)

        self.btnLocateDataFilename.clicked.connect(
            self.btnLocateDataFilenameClicked)
        self.btnLocateMetaDataFilename.clicked.connect(
            self.btnLocateMetaDataFilenameClicked)
        self.btnValidateMapping.clicked.connect(
            self.btnValidateDataTransformationClicked)
        self.btnLoadMapping.clicked.connect(self.btnLoadMappingClicked)

        self.cmbStudyEvent.currentIndexChanged['QString'].connect(
            self.cmbStudyEventChanged)
        self.cmbEventForm.currentIndexChanged['QString'].connect(
            self.cmbEventFormChanged)
        #-----------------------------------------------------------------------
        # Domain model
        self.__study = None
        self.__studyEvents = []
        self.__selectedStudyEvent = None
        self.__studyEventCrfs = []
        self.__selectedEventCrf = None

        #-----------------------------------------------------------------------
        #----------------------- Services --------------------------------------
        # There are two http services, one for communicating with my own
        # site server/database
        section = "MySiteServer"
        hostname = self.appConfig.get(section)["host"]
        port = self.appConfig.get(section)["port"]
        self.svcHttp = HttpConnectionService(hostname, port, UserDetails())

        self.reload()

        #-----------------------------------------------------------------------
        # TODO: make it a Stragety desing pattern later
        self.fileDataService = CsvFileDataService()
        self.fileMetaDataService = OdmFileDataService()
        self.exportMapping = []

        # Just for testing to have guick access to files
        self.dataFilename = "/mnt/edv/skripcakt/ulice/branches/radplanbio/data/radiochemotherapy.csv"
        self.metaDataFilename = "/mnt/edv/skripcakt/ulice/branches/radplanbio/data/HNSCCStudyMetadata.xml"

        #-----------------------------------------------------------------------
        # Create REST mainzellieste
        userName = "******"
        password = "******"
        baseUrl = "http://g89rtpsrv.med.tu-dresden.de:8080/mainzelliste-1.1-SNAPSHOT/"
        apiKey = "mdatdd"

        connectInfo = MainzellisteConnectInfo(baseUrl, userName, password,
                                              apiKey)
        self.svcPseudonymisation = PseudonymisationService(connectInfo)

        # # Retrive all pids
        # allPids = self.svcPseudonymisation.getAllPatients()

        # # Start reading session (I know the PID and I want to gat patient data)
        # sessionId, uri1 = self.svcPseudonymisation.newSession()
        # tokenId, url2 = self.svcPseudonymisation.readPatientToken(sessionId, allPids[0].idString)
        # self.svcPseudonymisation.getPatient(tokenId)

        #tokenId, uri2 = self.svcPseudonymisation.newPatientToken(sessionId)
        #self.svcPseudonymisation.createPatientJson(tokenId)
        #self.svcPseudonymisation.resolveTempIds(tokenId)

    def loadModuleData(self, selectedIndex):
        if selectedIndex == 0:
            pass

    def reload(self):
        requests = []

        # TODO: read from users data
        # It is not Heidelberg I have it here just for testing to simulate on one database
        mySite = "DKTK-HEIDELBERG"
        site = self.svcHttp.getPartnerSiteByName(mySite)
        if site is not None:
            requests = self.svcHttp.getAllPullDataRequestsToSite(site.sitename)

        pullDataRequestModel = QtGui.QStandardItemModel()
        pullDataRequestModel.setHorizontalHeaderLabels(
            ["Request sent from", "Subject", "Created"])

        row = 0
        for itm in requests:
            fromValue = QtGui.QStandardItem(itm.sentFromSite.sitename)
            subjectValue = QtGui.QStandardItem(itm.subject)
            createdValue = QtGui.QStandardItem(str(itm.created))

            pullDataRequestModel.setItem(row, 0, fromValue)
            pullDataRequestModel.setItem(row, 1, subjectValue)
            pullDataRequestModel.setItem(row, 2, createdValue)

            row = row + 1

        self.tvPullDataRequests.setModel(pullDataRequestModel)
        self.tvPullDataRequests.resizeColumnsToContents()

    #----------------------------------------------------------------------
    #------------------- Browse Buttons Handlers -------------------------

    def btnLocateDataFilenameClicked(self):
        """User selects a file to export
        """
        # Get a data file name
        fileName = QtGui.QFileDialog.getOpenFileName(self, "Locate data file",
                                                     QtCore.QDir.currentPath(),
                                                     "csv files(*.csv)")

        # Check read access to the file
        ok = os.access(fileName, os.R_OK)

        # If access is OK
        if ok:
            self.dataFilename = str(fileName)
            self.txtDataFilename.setText(self.dataFilename)

    def btnLocateMetaDataFilenameClicked(self):
        """Open a file open dialog where user selects a study metadata XML file

        """
        # Get a metadata file name
        fileName = QtGui.QFileDialog.getOpenFileName(self,
                                                     "Locate metadata file",
                                                     QtCore.QDir.currentPath(),
                                                     "xml files(*.xml)")

        # Check read access to the file
        ok = os.access(fileName, os.R_OK)

        # If access is OK
        if ok:
            # Get file path as string
            self.metaDataFilename = str(fileName)
            # Set the path to GUI
            self.txtMetaDataFilename.setText(self.metaDataFilename)
            # Prepare service for reading XML ODM files
            self.fileMetaDataService.setFilename(self.metaDataFilename)

            # Load the Study domain object
            self.__study = self.fileMetaDataService.loadStudy()
            # And inform the GUI
            self.lblStudy.setText(self.__study.name())

            # Load list of Study Event Definition domain objects
            self.__studyEvents = self.fileMetaDataService.loadStudyEvents()

            # And prepare ViewModel for the GUI
            seModel = QtGui.QStandardItemModel()

            for studyEventDef in self.__studyEvents:
                text = QtGui.QStandardItem(studyEventDef.name())
                seModel.appendRow([text])

            self.cmbStudyEvent.setModel(seModel)

    #----------------------------------------------------------------------
    #------------------- Command Buttons Handlers -------------------------

    def btnReloadClicked(self):
        self.reload()

    def btnLoadMappingClicked(self):
        """Load mapping into table view
        """
        if self.dataFilename == "":
            if self.txtDataFileName.text() == "":
                # error
                pass
            else:
                ok = os.access(self.txtDataFilename.text(), os.R_OK)
                if ok:
                    self.dataFilename = self.txtDataFilename.text()
                else:
                    #error
                    pass

        if self.metaDataFilename == "":
            if self.txtMetaDataFilename.text() == "":
                # error
                pass
            else:
                ok = os.access(self.txtMetaDataFilename.text(), os.R_OK)
                if ok:
                    self.metaDataFilename = self.txtMetaDataFilename.text()
                else:
                    #error
                    pass

        # Accumulate data headers
        self.fileDataService.setFilename(self.dataFilename)
        self.fileDataService.loadHeaders()

        # Accumulate metadata headers
        self.fileMetaDataService.setFilename(self.metaDataFilename)
        self.fileMetaDataService.loadHeaders()

        # Create a exportMaping list for table ViewModel
        self.exportMapping = self.fileMetaDataService.loadExportMapping(
            self.__selectedEventCrf)

        # Create a tableView model
        self.exportMappingModel = ExportMappingTableModel(self.exportMapping)
        self.tvExportDataMapping.setModel(self.exportMappingModel)

        # Make tableView editable
        self.tvExportDataMapping.setEditTriggers(
            QtGui.QAbstractItemView.CurrentChanged)

        # Create combo box delegate to display in teableView
        #dataComboBoxDelegate = ComboBoxDelegate(self, self.fileDataService.headers)
        #actionButtonDelegate = PushButtonDelegate(self)

        # Assign delegates to columns
        #self.tvExportDataMapping.setItemDelegateForColumn(2, dataComboBoxDelegate)
        #self.tvExportDataMapping.setItemDelegateForColumn(4, actionButtonDelegate)

        # Make cobobox always displayed
        #for i in range(0, len(self.fileMetaDataService.headers)):
        #self.tvExportDataMapping.openPersistentEditor(self.exportMappingModel.index(i, 2));
        #self.tvExportDataMapping.openPersistentEditor(self.exportMappingModel.index(i, 4));

        # Resize table columns to content
        self.tvExportDataMapping.resizeColumnsToContents()

        self.tvExportDataMapping.selectionModel().currentChanged.connect(
            self.tblExportDataMappingItemChanged)

    def btnMapExportFieldClicked(self):
        """Map metadata to datafiled from provided CSV data
        """
        # Initialize dialog
        dialog = ExportFieldMappingDialog(self)
        dialog.dataService = self.fileDataService
        dialog.setData(self.selectedDataMapping, self.fileDataService.headers)

        # Show dialog
        dialogResult = dialog.exec_()

        if dialogResult == QtGui.QDialog.Accepted:
            # Take data from dialog
            self.exportMappingModel.dataItems[
                self.selectedRow].data = dialog.dataMapping.data
            self.exportMappingModel.dataItems[
                self.selectedRow].setConverter = dialog.dataMapping.converter

            # Resize table columns to content
            self.tvExportDataMapping.resizeColumnsToContents()

    def btnMapExportFieldConstantClicked(self):
        pass

    def btnValidateMappingClicked(self):
        """
        """
        mappingErrors = []
        for i in range(0, len(self.fileMetaDataService.headers)):
            print self.exportMappingModel.dataItems[
                i].metadata + " -> " + self.exportMappingModel.dataItems[i].data

        # Error: All mandatory columns are mapped
        # Warning: one column is mapped to several metadata

    def btnValidateDataTransformationClicked(self):
        """
        """
        dataSize = self.fileDataService.size()

        validationErrors = []
        # Try to convert all data (from 1 ignore the header)
        for i in range(1, dataSize):
            # For every row of input data set
            dataRow = self.fileDataService.getRow(i)
            # Go through specified export mapping
            for j in range(0, len(self.fileMetaDataService.headers)):
                # And locate data in csv which corresponds to mapping
                metadataHeader = self.exportMappingModel.dataItems[j].metadata

                dataHeader = self.exportMappingModel.dataItems[j].data
                dataIndex = self.fileDataService.headers.index(dataHeader)
                dataValue = dataRow[dataIndex]

                print "metadata: " + metadataHeader + " -> " + dataHeader + " = " + dataValue

                # Check if the data conform
                #self.exportMappingModel.dataItems[j].checkDataType(dataValue)
                if (self.exportMappingModel.dataItems[j].validate(dataValue) ==
                        False):
                    errorMessage = "Input file row: " + i + ". " + dataHeader + " = " + dataValue + "does not conform metadata codelist for: " + metadataHeader
                    validationErrors.append(errorMessage)

        # Show errors if appiers

        # Show confirmation of valid in no errors

    #----------------------------------------------------------------------
    #------------------- ComboBox Handlers --------------------------------

    def cmbStudyEventChanged(self, text):
        """
        """
        # I need to find StudyEvent object according to name (text)
        self.__selectedStudyEvent = first.first(event
                                                for event in self.__studyEvents
                                                if event.name() == text)

        # When selected event found search CRFs for the event
        if self.__selectedStudyEvent is not None:
            # Load list of Study Event Form Definition domain objects
            self.__studyEventCrfs = self.fileMetaDataService.loadEventCrfs(
                self.__selectedStudyEvent)

            # And prepare ViewModel for the GUI
            sefModel = QtGui.QStandardItemModel()

            for studyEventCrf in self.__studyEventCrfs:
                text = QtGui.QStandardItem(studyEventCrf.name())
                sefModel.appendRow([text])

            self.cmbEventForm.setModel(sefModel)

    def cmbEventFormChanged(self, text):
        """
        """
        self.__selectedEventCrf = first.first(crf
                                              for crf in self.__studyEventCrfs
                                              if crf.name() == text)

    #----------------------------------------------------------------------
    #------------------- TableView Handlers -------------------------------

    def tblExportDataMappingItemChanged(self, current, previous):
        self.selectedDataMapping = self.exportMappingModel.dataItems[
            current.row()]
        self.selectedRow = current.row()
示例#10
0
def configure():
    """Read configuration settings from config file
    """
    appConfig = AppConfigurationService(ConfigDetails().configFileName)

    section = "RadPlanBioServer"
    if appConfig.hasSection(section):
        if appConfig.hasOption(section, "host"):
            ConfigDetails().rpbHost = appConfig.get(section)["host"]
        if appConfig.hasOption(section, "port"):
            ConfigDetails().rpbHostPort = appConfig.get(section)["port"]
        if appConfig.hasOption(section, "application"):
            ConfigDetails().rpbApplication = appConfig.get(
                section)["application"]

    section = "Proxy"
    if appConfig.hasSection(section):
        if appConfig.hasOption(section, "enabled"):
            ConfigDetails().proxyEnabled = appConfig.getboolean(
                section, "enabled")
        if appConfig.hasOption(section, "host"):
            ConfigDetails().proxyHost = appConfig.get(section)["host"]
        if appConfig.hasOption(section, "port"):
            ConfigDetails().proxyPort = appConfig.get(section)["port"]
        if appConfig.hasOption(section, "noproxy"):
            ConfigDetails().noProxy = appConfig.get(section)["noproxy"]

    section = "Proxy-auth"
    if appConfig.hasSection(section):
        if appConfig.hasOption(section, "enabled"):
            ConfigDetails().proxyAuthEnabled = appConfig.getboolean(
                section, "enabled")
        if appConfig.hasOption(section, "login"):
            ConfigDetails().proxyAuthLogin = appConfig.get(section)["login"]
        if appConfig.hasOption(section, "password"):
            ConfigDetails().proxyAuthPassword = appConfig.get(
                section)["password"]

    section = "GUI"
    if appConfig.hasSection(section):
        if appConfig.hasOption(section, "main.width"):
            ConfigDetails().width = int(appConfig.get(section)["main.width"])
        if appConfig.hasOption(section, "main.height"):
            ConfigDetails().height = int(appConfig.get(section)["main.height"])

    section = "DICOM"
    if appConfig.hasSection(section):
        if appConfig.hasOption(section, "replacepatientnamewith"):
            ConfigDetails().replacePatientNameWith = appConfig.get(
                section)["replacepatientnamewith"]
        if appConfig.hasOption(section, "constpatientname"):
            ConfigDetails().constPatientName = appConfig.get(
                section)["constpatientname"]
        if appConfig.hasOption(section, "allowmultiplepatientids"):
            ConfigDetails().allowMultiplePatientIDs = appConfig.getboolean(
                section, "allowmultiplepatientids")
        if appConfig.hasOption(section, "retainpatientcharacteristicsoption"):
            ConfigDetails(
            ).retainPatientCharacteristicsOption = appConfig.getboolean(
                section, "retainpatientcharacteristicsoption")
        if appConfig.hasOption(section, "retainstudydate"):
            ConfigDetails().retainStudyDate = appConfig.getboolean(
                section, "retainstudydate")
        if appConfig.hasOption(section, "retainstudytime"):
            ConfigDetails().retainStudyTime = appConfig.getboolean(
                section, "retainstudytime")
        if appConfig.hasOption(section, "retainseriesdate"):
            ConfigDetails().retainSeriesDate = appConfig.getboolean(
                section, "retainseriesdate")
        if appConfig.hasOption(section, "retainseriestime"):
            ConfigDetails().retainSeriesTime = appConfig.getboolean(
                section, "retainseriestime")
        if appConfig.hasOption(section, "retainstudyseriesdescriptions"):
            ConfigDetails(
            ).retainStudySeriesDescriptions = appConfig.getboolean(
                section, "retainstudyseriesdescriptions")
        if appConfig.hasOption(section, "autortstructmatch"):
            ConfigDetails().autoRTStructMatch = appConfig.getboolean(
                section, "autortstructmatch")
        if appConfig.hasOption(section, "autortstructref"):
            ConfigDetails().autoRTStructRef = appConfig.getboolean(
                section, "autortstructref")
        if appConfig.hasOption(section, "downloaddicompatientfoldername"):
            ConfigDetails().downloadDicomPatientFolderName = appConfig.get(
                section)["downloaddicompatientfoldername"]
        if appConfig.hasOption(section, "downloaddicomstudyfoldername"):
            ConfigDetails().downloadDicomStudyFolderName = appConfig.get(
                section)["downloaddicomstudyfoldername"]

    section = "AE"
    if appConfig.hasSection(section):
        if appConfig.hasOption(section, "name"):
            ConfigDetails().rpbAE = appConfig.get(section)["name"]
        if appConfig.hasOption(section, "port"):
            ConfigDetails().rpbAEport = int(appConfig.get(section)["port"])
        if appConfig.hasOption(section, "aetsuffix"):
            ConfigDetails().rpbAETsuffix = appConfig.get(section)["aetsuffix"]

        if not ApplicationEntityService().isReady:
            if ConfigDetails(
            ).rpbAE is not None and ConfigDetails().rpbAE != "":

                # Consider AET suffix option when creating AE for client
                AET = ConfigDetails().rpbAE

                if ConfigDetails().rpbAETsuffix == "host":
                    AET += str(QtNetwork.QHostInfo.localHostName())
                elif ConfigDetails().rpbAETsuffix == "fqdn":
                    AET += str(
                        QtNetwork.QHostInfo.localHostName()) + "." + str(
                            QtNetwork.QHostInfo.localDomainName())

                ApplicationEntityService().init(AET, ConfigDetails().rpbAEport)

    aeCount = 0
    section = "RemoteAEs"
    if appConfig.hasSection(section):
        if appConfig.hasOption(section, "count"):
            aeCount = int(appConfig.get(section)["count"])

    for i in range(0, aeCount):
        section = "RemoteAE" + str(i)
        if appConfig.hasSection(section):
            address = ""
            if appConfig.hasOption(section, "address"):
                address = appConfig.get(section)["address"]
            port = -1
            if appConfig.hasOption(section, "port"):
                port = int(appConfig.get(section)["port"])
            aet = ""
            if appConfig.hasOption(section, "aet"):
                aet = appConfig.get(section)["aet"]

            ConfigDetails().remoteAEs.append(
                dict(Address=address, Port=port, AET=aet))

    section = "SanityTests"
    if appConfig.hasSection(section):
        if appConfig.hasOption(section, "patientgendermatch"):
            ConfigDetails().patientGenderMatch = appConfig.getboolean(
                section, "patientGenderMatch")
        if appConfig.hasOption(section, "patientdobmatch"):
            ConfigDetails().patientDobMatch = appConfig.getboolean(
                section, "patientDobMatch")

    section = "General"
    if appConfig.hasSection(section):
        if appConfig.hasOption(section, "startupupdatecheck"):
            ConfigDetails().startupUpdateCheck = appConfig.getboolean(
                section, "startupupdatecheck")

    section = "Temp"
    if appConfig.hasSection(section):
        if appConfig.hasOption(section, "isupgrading"):
            ConfigDetails().isUpgrading = appConfig.get(section)["isupgrading"]
        if appConfig.hasOption(section, "upgradefinished"):
            ConfigDetails().upgradeFinished = appConfig.get(
                section)["upgradefinished"]